(function(){
	
	$.fn.infiniteCarousel = function(){
		function repeat(str, n){
			return new Array( n + 1 ).join(str);
		}
	
		return this.each(function(){
			// magic!
			var $wrapper = $('> .wrapper', this).css('overflow', 'hidden'),
			$slider = $wrapper.find('> div').width(9999),
			$items = $slider.find('> div'),
			$single = $items.filter(':first')	
			singleWidth = $single.outerWidth(),
			visible = Math.ceil($wrapper.innerWidth() / singleWidth),
			currentPage = 1,
			pages = Math.ceil($items.length / visible);

			/* TASKS */
			// 1. pad the pages with empty element if required
			if ($items.length % visible != 0) {
				// pad
				$slider.append(repeat('<div class="empty" />', visible - ($items.length % visible)));
				$items = $slider.find('> div');
			}

			// 2. create the carousel padding on left and right (cloned)
			$items.filter(':first').before($items.slice(-visible).clone().addClass('cloned'));
			$items.filter(':last').after($items.slice(0, visible).clone().addClass('cloned'));
			$items = $slider.find('> div');
	
			// 3. reset scroll
			$wrapper.scrollLeft(singleWidth * visible);

			// 4. paging function
			function gotoPage(page){
				var dir = page < currentPage ? -1 : 1,
				n = Math.abs(currentPage - page),
				left = singleWidth * dir * visible * n;

				$wrapper.filter(':not(:animated)').animate({
					scrollLeft : '+=' + left
				}, 750, function(){
					//if page == last page - then reset position
					if(page > pages){
						$wrapper.scrollLeft(singleWidth * visible);
						page = 1;
					}else if(page == 0){
						page = pages;
						$wrapper.scrollLeft(singleWidth * visible * pages);
					}

					$('#pk_'+currentPage).find('> img').attr("src", $('#pk_'+currentPage).find('> img').attr("src").replace('_hover.jpg', '.jpg'));
					$('#pk_'+page).find('> img').attr("src", $('#pk_'+page).find('> img').attr("src").replace('.jpg', '_hover.jpg'));

					currentPage = page;
				});
			}
	
			// 5. insert the back and forward link
			//$wrapper.after('<a href="#" class="arrow back">&lt;</a><a href="#" class="arrow forward">&gt;</a>');
	
			// 6. bind the back and forward links
			$('a.car_back').click(function () {
				gotoPage(currentPage - 1);
				clearTimeout(window.car_timer);
				window.car_timer = setInterval(function(){
					if (window.autoscrolling){
						$('.infiniteCarousel').trigger('next');
					}
				}, 5000);
				return false;
			});
	
			$('a.car_forward').click(function () {
				gotoPage(currentPage + 1);
				clearTimeout(window.car_timer);
				window.car_timer = setInterval(function(){
					if (window.autoscrolling){
						$('.infiniteCarousel').trigger('next');
					}
				}, 5000);
				return false;
			});
	
			$(this).bind('goto', function (event, page) {
				gotoPage(page);
			});
	
			// THIS IS NEW CODE FOR THE AUTOMATIC INFINITE CAROUSEL
			$(this).bind('next', function () {
				gotoPage(currentPage + 1);
			});
		});
	};
})(jQuery);

// http://engineeredweb.com/blog/09/12/preloading-images-jquery-and-javascript
(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery);

$(document).ready(function(){

	// Preload all the images:
	jQuery.preLoadImages( 
		"/images/img_arrow_blue.png",
		"/images/icon_loading.gif",
		"/images/icon_available.png",
		"/images/icon_error.png",
		"/images/icon_information.jpg",
		"/images/img_checker_suggest_top.jpg",
		"/images/img_checker_suggest_top_hover.jpg",
		"/images/img_checker_suggest_middle.jpg",
		"/images/img_checker_suggest_middle_hover.jpg",
		"/images/img_checker_suggest_bottom.jpg",
		"/images/img_checker_suggest_bottom_hover.jpg"
	);

	$('#mnu_langselector').mouseover(function(){
		$('#mnu_langselector>ul').css("display", "block");
		$(this).css("height", "69px");
		$(this).css('background-image', $(this).css('background-image').replace('.png', '_hover.png'));
	});

	$('#mnu_langselector').mouseout(function(){
		$('#mnu_langselector>ul').css("display", "none");
		$(this).css("height", "20px");
		$(this).css('background-image', $(this).css('background-image').replace('_hover.png', '.png'));
	});

	$('#mnu_login').mouseover(function(){
		$('#mnu_login>ul').css("display", "block");
		$(this).css("height", "97px");
		$(this).css('background-image', $(this).css('background-image').replace('.png', '_hover.png'));
	});

	$('#mnu_login').mouseout(function(){
		$('#mnu_login>ul').css("display", "none");
		$(this).css("height", "20px");
		$(this).css('background-image', $(this).css('background-image').replace('_hover.png', '.png'));
	});

	// THIS IS NEW CODE FOR THE AUTOMATIC INFINITE CAROUSEL
	window.autoscrolling = true;
	
	$('.infiniteCarousel').infiniteCarousel().mouseover(function (){
		window.autoscrolling = false;
	}).mouseout(function (){
		window.autoscrolling = true;
	});

	window.car_timer = setInterval(function(){
		if (window.autoscrolling){
			$('.infiniteCarousel').trigger('next');
		}
	}, 5000);

	$('#pk_1').click(function(){
		$('.infiniteCarousel').trigger('goto', 1);
	});

	$('#pk_2').click(function(){
		$('.infiniteCarousel').trigger('goto', 2);
	});

	$('#pk_3').click(function(){
		$('.infiniteCarousel').trigger('goto', 3);
	});

	$('#pk_4').click(function(){
		$('.infiniteCarousel').trigger('goto', 4);
	});

	$('#pk_5').click(function(){
		$('.infiniteCarousel').trigger('goto', 5);
	});

	//Domain checker
	$('#domain_checker').click(function(){
		$('#domainname').focus();
	});

	$('.tbl_overview .row .closed').click(function(){

		var shouldOpen = !$(this).hasClass( 'open' );

		// Close the previous opened descriptions:
		var $openElements = $('.tbl_overview .row .open');
		$openElements.next().slideUp( 'slow', function() {
			$openElements.addClass('closed').removeClass('open').parent().removeClass('open');
		});

		// Open the description of this row:
		if ( shouldOpen ) {
			$(this).parent().addClass( 'open' );
			$(this).next().slideDown( 'slow', function() {
				$(this).prev().addClass('open').removeClass('closed');
			});
		}
	}).mouseover(function(){

		$(this).find('img').each(function(){
            var src = $(this).attr("src").replace("_gray", "");
            $(this).attr("src", src);
		});
	}).mouseout(function(){

		$(this).find('img').each(function(){
            var src = $(this).attr("src").match(/[^\.]+/) + "_gray.png";
            $(this).attr("src", src);
		});
	});

	if ( jQuery.fancybox ) {
		$('.addPacketLink').each(function(){

			var $link = $(this);
			$(this).fancybox({
				showNavArrows: false,
				ajax:{
					type: 'POST',
					data: 'type=packetbox&packet=' + $link.attr('rel')
				},
				onStart: function() {

					var result = true;

					// Checking for three rows because there is also a header and a footer row.
					var $domainRows = $('.row', '#orderTable');
					if ( $domainRows.size() == 3 ) {

						$domainRow = $domainRows[ 1 ];
						$domain = $('.orderDomain', $domainRow).html().replace( '.', '_' );

						$.ajax({
							type: "POST",
							url: location.href,
							data: "packettodomainshoppingbasket=new&domainname=" + $domain + "&packet=" + $link.attr("rel"),
							success: function( output ){

								$('#shopping_basket').fadeOut('fast', function(){

									$('#shopping_basket').html( output ).fadeIn('fast');
								});
							}
						});

						result = false;
					}

					return result;
				}
			});
		});

		$('div#orderLightBox .cancel a').live( 'click', function(){
			$.fancybox.close();
			return false;
		});

		$('div#orderLightBox .domain a').live( 'click', function(){

			$link = $(this);

			$.ajax({
				type: "POST",
				url: location.href,
				data: "packettodomainshoppingbasket=new&domainname=" + $link.attr("rel") + "&packet=" + $link.attr("rev"),
				success: function( output ){

					$('#shopping_basket').html( output );
				}
			});
			
			$.fancybox.close();
			return false;
		});
	}

	function removePacket( $link, $type ) {

		$.ajax({
			type: "POST",
			url: location.href,
			data: "packettodomainshoppingbasket=remove&type=" + $type + "&domainname=" + $link.attr("rel") + "&tld=" + $link.attr('rev'),
			success:function(output){
				$('#shopping_basket').html(output);
			}
		});
	}

	//Remove from Shopping Basket
	$('a.removePacket').live('click', function(){
		removePacket( $(this), 'packet' );
		return false;
	});
	$('a.removePacketOrder').live('click', function(){
		removePacket( $(this), 'order' );
		return false;
	});

	function setApproved( el, val, depth ) {

		if ( !depth ) {
			depth = 1;
		}

		var $theEl = $(el);

		for ( var i = 0; i < depth; ++i ) {
			$theEl = $theEl.parent();
		}

		$theEl = $theEl.next().children(':first-child');

		if ( val ) {
			$theEl.removeClass('declined').addClass('approved');
		} else {
			$theEl.addClass('declined').removeClass('approved');
		}
	}

	if ( $('input#name2').val() != 'voornaam' ) {
		$('input#name2').css( 'color', '#000' );
	}

	if ( $('input#name3').val() != 'achternaam' ) {
		$('input#name3').css( 'color', '#000' );
	}

	var name2HadFocus = false;
	var name3HadFocus = false;

	$('input#name2').focus(function(){

		name2HadFocus = true;

		if ( $(this).val() == 'voornaam' ) {
			$(this).val('');
			$(this).css('color', '#000');
		}

	}).blur(function(){

		var firstNameValid = $('input#name2').val() != 'voornaam' && $('input#name2').val() != '';
		var surnameValid = $('input#name3').val() != 'achternaam' && $('input#name3').val() != '';

		if ( name2HadFocus && name3HadFocus ) {
			setApproved( $(this), firstNameValid && surnameValid );
		}

		if ( $(this).val() == '' || $(this).val() == 'voornaam' ) {
			$(this).css('color', '#DDD');
			$(this).val('voornaam');
		}
	});

	$('input#name3').focus(function(){

		name3HadFocus = true;
		
		if ( $(this).val() == 'achternaam' ) {
			$(this).val('');
			$(this).css('color', '#000');
		}

	}).blur(function(){

		var firstNameValid = $('input#name2').val() != 'voornaam' && $('input#name2').val() != '';
		var surnameValid = $('input#name3').val() != 'achternaam' && $('input#name3').val() != '';

		setApproved( $(this), firstNameValid && surnameValid );

		if ( $(this).val() == '' || $(this).val() == 'achternaam' ) {
			$(this).css('color', '#DDD');
			$(this).val('achternaam');
		}
	});

	if ( $('#dateOfBirth').size() > 0 ) {
		$('#dateOfBirth').mask("99-99-9999");
	}
	
	$('#city, #country, #street').blur(function(){

		setApproved( $(this), $(this).valid() );
	});
	$('#dateOfBirth').blur(function(){

		setApproved( $(this), $(this).valid() );

	});

	var latestCheckZipcode = '';
	var latestCheckStreetNo = '';

	function doAddressCheck() {
		var newCheckZipcode = $('#zipcode').val();
		var newCheckStreetNo = $('#streetNumber').val();

		if ( newCheckZipcode != latestCheckZipcode || newCheckStreetNo != latestCheckStreetNo ) {
			latestCheckZipcode = newCheckZipcode;
			latestCheckStreetNo = newCheckStreetNo;

			var beg = location.protocol.length + location.hostname.length + 2;
			var end = location.href.length - beg;
			var url = location.href.substr( beg, end );

			var streetBackup = $('#street').val();
			var cityBackup = $('#city').val();
			var countryBackup = $('#country').val();

			var loadingMessage = 'op aan het zoeken...';

			$('#street').val( loadingMessage );
			$('#city').val( loadingMessage );
			$('#country').val( loadingMessage );

			// Disable the fields:
			$('#street').attr( 'disabled', true );
			$('#city').attr( 'disabled', true );
			$('#country').attr( 'disabled', true );

			$.ajax({
				type: "POST",
				url: url,
				dataType: 'json',
				data: 'address=get&zipcode=' + $('#zipcode').val() + '&streetNumber=' + $('#streetNumber').val(),
				success:function(output){
					if ( output.enabled ) {
						if ( output.street != '' ) {
							var $el = $('#street');
							$el.val( output.street );
							setApproved( $el, $el.valid() );
						} else {
							$('#street').val( streetBackup );
						}

						if ( output.city != '' ) {
							var $el = $('#city');
							$el.val( output.city );
							setApproved( $el, $el.valid() );
						} else {
							$('#city').val( cityBackup );
						}

						if ( output.state != '' ) {
							$('#state').val( output.state );
						}

						if ( output.country != '' ) {
							var $el = $('#country');
							$el.val( output.country );
							setApproved( $el, $el.valid() );
						} else {
							$('#country').val( countryBackup );
						}
					} else {
						$('#street').val( streetBackup );
						$('#city').val( cityBackup );
						$('#country').val( countryBackup );
					}
				},
				complete: function() {
					// Enable the fields:
					$('#street').removeAttr( 'disabled' );
					$('#city').removeAttr( 'disabled' );
					$('#country').removeAttr( 'disabled' );
				}
			});
		}
	}

	var zipcodeHadFocus = false;
	var streetNumberHadFocus = false;

	$('#zipcode').focus(function(){
		zipcodeHadFocus = true;
	}).blur(function(){

		if ( zipcodeHadFocus && streetNumberHadFocus ) {
			if ( $('#zipcode').valid() && $('#streetNumber').valid() ) {
				setApproved( $(this), true, 2 );
				doAddressCheck();
			} else {
				setApproved( $(this), false, 2 );
			}
		}
	});
	$('#streetNumber').focus(function(){
		streetNumberHadFocus = true;
	}).blur(function(){

		if ( zipcodeHadFocus && streetNumberHadFocus ) {
			if ( $('#zipcode').valid() && $('#streetNumber').valid() ) {
				setApproved( $(this), true, 2 );
				doAddressCheck();
			} else {
				setApproved( $(this), false, 2 );
			}
		}
	});
	$('#phoneNumber').blur(function(){

		setApproved( $(this), $(this).valid() );
	});
	$('#emailAddress').blur(function(){
		
		setApproved( $(this), $(this).valid() );
	});

	if($('#orderPayNewUserForm').length > 0){

		// When the shopping basket is empty, we shouldn't be here!
		if ( $('#shopping_basket').children().size() == 0 ) {
			window.location.href = '/bestel';
		} else {
			$('#orderPayNewUserForm').validate({
				/*submitHandler: function() {
					$('#orderPayNewUserForm > input').each(function(){
						//alert( this.name );
						//$(this).validate();
					});
					//return false;
				},*/
				messages: {
					companyName: { required: '' },
					name2: { required: '' },
					name3: { required: '' },
					dateOfBirth: { required: '' },
					zipcode: { required: '' },
					street: { required: '' },
					streetNumber: { required: '' },
					city: { required: '' },
					country: { required: '' },
					phoneNumber: { required: '' },
					emailAddress: { required: '', email: '' },
					disclaimer: { required: 'U dient akkoord te gaan met de algemene voorwaarden.' }
				}
			});
		}
	}

	$('#content_master .scroll').click(function(){
		
		var elementID = $(this).attr('href');

		if ( elementID == '#' ) {

			$('html,body').animate({scrollTop: 0},'slow');

		} else {
			
			var element = $('a[name=' + elementID.substring( 1 ) + ']');
			$('html,body').animate({scrollTop: element.offset().top},'slow');
		}
		
		return false;
	});

	if ( jQuery.fancybox ) {
		$('a.manageDNS').fancybox({
			showNavArrows: false,
			ajax:{
				type: 'POST',
				data: 'type=managedns'
			}
		});

		$('a#terms').fancybox();

		$('a#helpOrderDomain').fancybox();
		$('a#helpOrderPacket').fancybox();

		$('a.dynHelpDomain').live('click', function(){
			$(this).fancybox();
			$(this).triggerHandler( 'click' );
			return false;
		});

		$('#emailVideo').fancybox({
			width: 695,
			height: 553
		});
	}

	$('#domain').live('blur', function(){
		if ( $(this).val() == '' || $(this).val() == 'domain.ext' ) {
			$(this).val('domain.ext').css( 'color', '#AAA' );
		}
	}).live('focus', function(){
		if ( $(this).val() == '' || $(this).val() == 'domain.ext' ) {
			$(this).val('').css( 'color', '#000' );
		}
	});

	$('#manageDNSForm').live( 'submit', function(){

		var inputDomain = $('#domain', this).val();
		
		//var regex = /((http|https):\/\/|)(\w+:{0,1}\w*@)?(\S+)(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
		var regex = /((http|https):\/\/|)(www\.)?(([a-z0-9-]*[a-z0-9]+))\.([a-z\.]{2,})/;

		var match = inputDomain.match( regex );
		if ( match !== null ) {

			var domain = match[ match.length - 2 ];
			var tld = match[ match.length - 1 ];

			if ( domain != '' && inputDomain != 'domain.ext' && tld != '' ) {

				$.ajax({
					type: "POST",
					url: location.href,
					data: "domaintoshoppingbasket=managedns&domainname=" + domain + "&tld=" + tld,
					success:function(output){
						$('#shopping_basket').html(output);
					}
				});

				$.fancybox.close();
			} else {
				alert( 'Ongeldige domeinnaam.' );
			}
		} else {
			alert( 'Ongeldige domeinnaam.' );
		}

		return false;
	});
	
	$('#checkAllCancel').change(function(){
		$('.subscriptionCancelCheckbox').attr( 'checked', $(this).attr( 'checked' ) );
	});
	
	$('#frmCancelSubscriptionLogin').submit(function(){
		$('#txtUsername').removeClass( 'error' );
		$('#txtPassword').removeClass( 'error' );
		
		$('#btnLogin').hide();
		var loader = $('<div class="loader"><img src="/images/ajax-loader.gif" alt="" /> Bezig met inloggen. Dit kan tot 30 seconden duren.</div>').appendTo( this );
		
		$.ajax({
			type: 'POST',
			data: {
				'method': 'cancel_subscription_login',
				'username': $('#txtUsername').val(),
				'password': $('#txtPassword').val()
			},
			success: function( data ) {
				loader.remove();
				if ( data.success ) {
					window.location.reload();
				} else {
					$('#btnLogin').show();
					$('#txtUsername').addClass( 'error' );
					$('#txtPassword').addClass( 'error' );
				}
			}
		});
		return false;
	});
});

/***********************************************
* Smooth Navigational Menu- (c) Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/
ddsmoothmenu.init({
	mainmenuid: "top_menu",
	orientation: "h",
	classname: "ddsmoothmenu",
	contentsource: "markup"
});
