jQuery.alnum = function(value, whiteSpace){
	return String(value).replace(whiteSpace ? /[^a-zA-Z0-9\-\s]/gi : /[^a-zA-Z0-9\-]/gi,'');
}

jQuery.fn.alnum = function() {
	
  	return this.each(function(whiteSpace){
  		var input = jQuery(this);
  		var filter = function(){
		  	input.val(jQuery.alnum(this.value, whiteSpace));
		}
  		input.change(filter)
		/*.keyup(filter)*/;
		  
  	});
};

var HistoryManager = {
	getHash: function() {
		var href = top.location.href;
		var pos = href.indexOf('#') + 1;
		return (pos) ? href.substr(pos) : '';
	}
}
	
	
	/**
 	*	NETVLIES.NL JAVASCRIPTS
 	*	Author:	Sebastiaan Smid, Netvlies
 	*	Author: Stephan van Opstal, Netvlies 	
 	*	Author: Paul Verbeek, Netvlies 	
 	*
 	*	Dependencies: 
 	*	- jQuery v 1.2.2
 	*	- jQuery.lightbox 0.4
 	*/
	$(document).ready(function()
	{
		/**
		 *
		 * Cufon
		 * 
		 */
		Cufon.replace('h1, h3, h4, #payoff');
		
		/*
		$('#action-winkelmand-wrapper').scrollFollow({
			container: 'content-box'
		});
		*/
	
        $('#prinsenkade_stream').nvsMediaPopup({});
			
		jQuery('#domain_domain').change(function(){
			$('#domain_domain').val(dc.format_domain($('#domain_domain').val())).val()
		}).alnum(false);
	
		// Recentwork on the homepage 
		$('.recentwork').css({ cursor: "pointer" });
	
		$('.recentwork').click(function()
		{
			var div_id = this.id;
			var a_id = div_id.replace ('div', 'a');
			document.location = $('#'+a_id).attr("href");
		});
	
		$('.recentwork').hover(
		function() {
			$(this).addClass("hover");
		},
		function() {
			$(this).removeClass("hover");
		});
		
		$('.case:not(.company)').hover(
		function() {
			$(this).addClass("hover");
			$('hr', $(this)).css({ width: $('.case-info h3 a', $(this)).width() + 'px' });
		},
		function() {
			$(this).removeClass("hover");
		});
		
		//Replace the name of the bijlage with a new input type="file"
		$('#bijlage_verwijderen').click(function(){
			$($(this).parent()).replaceWith('<div><input type="file" name="bijlage" /></div>');
		});
	
		//	Open a new window without using target="_blank" for XHTML 1.1
		//	Usage: <a href="http://www.netvlies.nl" rel="external">netvlies.nl</a>
		$('a[rel$=external]').click(function(){
			this.target = '_blank';
		});
		
		// Clears input onclick
		$("#frm-search input[value!=][type=text]").focus(function () { 
			if(!$(this).attr("startvalue")) {  
				$(this).attr("startvalue", $(this).val());
			} 
			if($(this).val() == $(this).attr("startvalue")) {
				$(this).val('');	
			}
		}).blur(function () { 
			if($(this).val() == '') {
				$(this).val($(this).attr("startvalue"));
			}
		});

		// Lightbox
		$('a[rel*=lightbox]').lightBox(); // Select all links that contains lightbox in the attribute rel
		$('.presentation').flashBox();
		
		$('a[rel*=nvsalbum]').nvsAlbum({overlayBackground: '#e7e5e4', overlayTransparancy: '0.8', popUpBackground: 'white'});
		$('a[rel*=diensten_landingspage]').nvsAlbum({overlayBackground: '#e7e5e4', popUpsize: 'full', overlayTransparancy: '0.8', popUpBackground: 'white'});

		// Print button
		if(window.print && document.getElementById("btn-print")) { 
			$('#btn_print').css({display: "inline"});
			$('#btn_print').click(
				function() { 
					window.print();
				}
			);
		}
		
		// Inline print function (routebeschrijving)
		if(window.print && ($('.inline_print').length > 0)) { 
			$('.inline_print').click(
				function() { 
					window.print();
				}
			);
		}
		
// 		//login script 
// 		$('#client-login').click(function() {
// 			setTimeout(_login_show, 0);
// 		});
// 		
// 		if(HistoryManager.getHash() == 'login'){
//  			$('#client-login').click();
// 		}
		
		// IE6 PNG fix
		if (window.DD_belatedPNG) {
			DD_belatedPNG.fix('#frm-contact div span.error');
		}
		
		var mand = $('#action-winkelmand');
		if(mand[0]){
			dc.cart.init();
		}
		// HOSTING SCRIPTS
		$('a.moreinfo').toggle(
			function () {
				$(this).siblings('.pakketinfo').css({"display":"block"});
				$(this).children('img').css({ "position" : "absolute", "top" : "-13px" })
			},
			function () {
				$(this).siblings('.pakketinfo').css({"display":"none"});
				$(this).children('img').css({ "position" : "relative", "top" : "0" })
			}					   
		)
		
		
		factuuradres = false;
		$("#factuuradresbtn").change( function() {
			if($(this).attr('checked')){
				$("#factuuradres").show();
				factuuradres = true;
			} else { 
				$("#factuuradres").hide();
				factuuradres = true;
			}
			return false;
		}).change();
	
		$("#betaling input[type='radio']").change( function() {
			$("#betaling .payment-part").hide()
			obj = "." + $(this).attr('id') + "-part";
			$(obj).show();
		});
		if($('#bedrijf')[0]){
			var show_bedrijfsgegevens = function() {
				if($('#bedrijf')[0].checked){
					$('#bedrijfgegevens').show();
				} else {
					$('#bedrijfgegevens').hide();
				} 
	// 			if($(this).attr('id') == 'bedrijf') {
	// 				$('#bedrijfgegevens').show();
	// 				$('tr.postbusfield').show();
	// 			} else {
	// 				$('#bedrijfgegevens').hide();
	// 				$('tr.postbusfield').hide();
	// 			}
			}
			show_bedrijfsgegevens();
			$("#naw input[type='radio']").change(show_bedrijfsgegevens);
		}
		if($('#hosting_step2')[0]){
			dc.pack.init();
		}
		
		
		if ($('#action-newsletter').length > 0) { 
			$('#action-newsletter .text').click(function() {
				if (this.value == 'Naam' || this.value == 'E-mailadres') {
					this.value = '';
				}
			});		
		}
		
		/**
		 *
		 * Home banner
		 * 
		 */
		carroussel();	 		 		 		
		
		
		/**
		 *
		 * Jaarverslag
		 *
		 */
		if($('.jaarverslag').length) {
			$('.jaarverslag .meer-info').click(function (e) {
				$('html, body').animate({
					 scrollTop: $("#meer-info").offset().top
			 }, 500);
				e.preventDefault;
			});

			var SmallCarousel = function (wrapper, bubbles) {
				this._wrapper = wrapper;
				this._list = this._wrapper.find('ul');
				this._bubbles = bubbles;
				this._current = 0;
				this._itemWidth = this._wrapper.find('li:first').outerWidth(true);

				this._wrapper.find('li').each(function (i) {
					$(this).attr('data-index', i);
				});
			};
			SmallCarousel.prototype = {
				go : function (gotoIndex) {
					var animateLength,
					    wrapper = this._wrapper,
					    bubbles = this._bubbles,
							cloneEq = 0;
					if (this._current < gotoIndex) {
						animateLength = gotoIndex - this._current;
						this._list.stop(true, true);
						while(this._current != gotoIndex) {
							this._current++;
							this._list.append(this._wrapper.find('li:eq('+cloneEq+')').clone());
							cloneEq++;
						}
						this._list.animate({'left': '-' + animateLength * this._itemWidth}, function () {
							while(animateLength) {
								$(wrapper.find('li:first')).remove();
								animateLength--;
							}
							$(this).css('left', 0);
							bubbles.removeClass('current');
							$(bubbles[$(wrapper.find('li:first')).attr('data-index')]).addClass('current');
						});
					} else if (this._current > gotoIndex) {
						cloneEq = this._wrapper.find('li').length - 1;
						animateLength = this._current - gotoIndex;
						this._list.stop(true, true).css('left', '-' + animateLength * this._itemWidth + 'px');
						while(this._current != gotoIndex) {
							this._current--;
							this._list.prepend(this._wrapper.find('li:eq('+cloneEq+')').clone());
						}
						this._list.animate({'left': 0}, function () {
							while(animateLength) {
								$(wrapper.find('li:last')).remove();
								animateLength--;
							}
							bubbles.removeClass('current');
							$(bubbles[$(wrapper.find('li:first')).attr('data-index')]).addClass('current');
						});
					}
				},
				next : function () {
					var wrapper = this._wrapper,
					    bubbles = this._bubbles;
					this._current++;
					if (this._current > this._wrapper.find('li').length - 1) {
						this._current = 0;
					}
					this._list.stop(true, true).append(this._wrapper.find('li:first').clone()).animate({'left': '-' + this._itemWidth}, function () {
						$(wrapper.find('li:first')).remove();
						$(this).css('left', 0);
						bubbles.removeClass('current');
						$(bubbles[$(wrapper.find('li:first')).attr('data-index')]).addClass('current');
					});
				},
				previous : function () {
					var wrapper = this._wrapper,
					    bubbles = this._bubbles;
					this._current--
					if (this._current < 0) {
						this._current = this._wrapper.find('li').length - 1;
					}
					this._list.stop(true, true).css('left', '-' + this._itemWidth + 'px').prepend(this._wrapper.find('li:last').clone()).animate({'left': 0}, function () {
						wrapper.find('li:last').remove();
						bubbles.removeClass('current');
						$(bubbles[$(wrapper.find('li:first')).attr('data-index')]).addClass('current');
					});
				}
			}
			var carousel = new SmallCarousel($('.jaarverslag .wrapper'), $('.jaarverslag .bubbles span'));
			$('.jaarverslag .next').click(function () {
				carousel.next();
			});
			$('.jaarverslag .back').click(function () {
				carousel.previous();
			});
			$('.jaarverslag .bubbles span').click(function () {
				carousel.go($('.jaarverslag .bubbles span').index(this));
			});

			$('.jaarverslag .slides .slide-1, .jaarverslag .slides .slide-2, .jaarverslag .slides .slide-3').hover(function() {
				$(this).siblings().stop().animate({ 'width' : '13px' });
				$(this).stop().animate({ 'width': '322px' });
				$(this).find('h5').stop().animate({ 'width': '227px' });
			}, function() {
				$(this).find('h5').stop().animate({ 'width': '87px' });
				$(this).siblings().andSelf().stop().animate({ 'width' : '116px' });
			}).click(function () {
				$('html, body').animate({
					scrollTop: $("#meer-info").offset().top
				}, 500);
			});

			$('#meer-info .mail-ons a').click(function (e) {
				if (!$(this).hasClass('disabled')) {
					$(this).addClass('disabled').parent().animate({'height' : '343px' });
				}
				e.preventDefault();
			});

			$('#meer-info .mail-ons.invalid a').addClass('disabled').parent().animate({'height' : '343px' });

			$('#meer-info .form .close').click(function () {
				$('#meer-info .mail-ons a').removeClass('disabled').parent().animate({'height' : '108px' });
			});

			if(!("placeholder" in document.createElement("input"))) {
				$('input[placeholder]').each(function () {
					var elem = $(this),
							val = elem.attr('placeholder');
					elem.val(val);
					elem.focus(function () {
						elem.val() == val && elem.val('')
					}).blur(function () {
						elem.val().length || elem.val(val)
					});
				});
			}
			$('#meer-info form').submit(function (e) {
				$(this).find('input, textarea').removeClass('invalid');
				$(this).find('input, textarea').filter(function () { console.log($(this).val(), $(this).attr('placeholder')); return (!($(this).val().length) || $(this).val() == $(this).attr('placeholder')) }).addClass('invalid');
				if ($(this).find('.invalid').length) {
					e.preventDefault();
				}
			});
		}
	});
// });
	
	/**
	 *
	 * Carroussel functions
	 *
	 */
	var carrouselLoaded = 0;
	var carrouselTotal = 0;
	var carrouselActive = false;
	var carrouselTimeout = null;
	var carrouselTime = 8000;
	var carrouselTimeImg = 1000;
	var carrouselTimeTxt = 600;
	
	function carroussel() { 	 	 	
		carrouselTotal = $('#home_banner img').length;
	
		$('#home_banner').append('<div class="text"></div>');
		
		$('#home_banner img').each(function() {
			$(this).load(function() {
				if ($(this).attr('title') == '') {
					window.setTimeout("carrouselRetry(" + $(this) + ");", 500);
				} else {
					$(this).attr('id', 'item_'+carrouselLoaded);
					$('#home_banner div.text').append('<div class="item_'+ carrouselLoaded +'">' + $(this).attr('title') + '</div>');
					$(this).removeAttr('title');
					
					carrouselLoaded++;
					if (carrouselLoaded == carrouselTotal) {
						$('#home_banner img:last').addClass('last');
						$('#home_banner div.text div').hover(
						function() {
							$(this).addClass("hover");
							window.clearTimeout(carrouselTimeout);
						},
						function() {
							$(this).removeClass("hover");
							carrouselTimeout = window.setTimeout(carrouselNext, carrouselTime);
						});
						$('#home_banner div.text div').click(function() {
							if ($(this).hasClass('active')) {
								window.location = $(this).find('a').attr('href');
							}
						});
						
						carrouselDescription();
						carrouselTimeout = window.setTimeout(carrouselNext, carrouselTime);
					}
				}
			});
					
			if (this.complete || jQuery.browser.msie) {
				$(this).trigger("load");
			}
		});
	}
	
	function carrouselRetry(obj) {
		obj.trigger("load");
	}
	
	function carrouselDescription(id) {
		if (id == undefined) {
			id = $('#home_banner img.active').attr('id');
		}
		$('#home_banner div.text div').removeClass('active');
		$('#home_banner div.text div.' + id).addClass('active');
		$('#home_banner div.text').css({ bottom: -($('#home_banner div.text').outerHeight())+'px' });
		b = ($('#home_banner').outerHeight() - $('#home_banner div.text').outerHeight()) / 2;
		$('#home_banner div.text').animate({ bottom: b+'px' }, carrouselTimeTxt);
	}
	
	function carrouselNext() {
		if(!carrouselActive) {
			carrouselActive = true;
			if (carrouselTimeout != null) {
				window.clearTimeout(carrouselTimeout);
			}
			var n;
			if ($('#home_banner img.active').hasClass('last')) {
				n = $('#home_banner img:first');
			} else {
				n = $('#home_banner img.active').next('img');
			}
					
			var b = $('#home_banner').outerHeight();
			$('#home_banner div.text').animate({ bottom: b+'px'}, { duration: carrouselTimeTxt, complete: function() {
				carrouselDescription(n.attr('id'));
			} });
			
			$('#home_banner img.active').fadeOut(carrouselTimeImg).removeClass('active');
			n.fadeIn(carrouselTimeImg, function() {
				carrouselActive = false;
				carrouselTimeout = window.setTimeout(carrouselNext, carrouselTime);
			}).addClass('active');			
		
		}
	}
	
	function _login_show() {
		$('#client-login').unbind();
		$.nvsOverlay.show({ 
				background: '#ffffff', 
				transparancy: 0.5, 
				speed: 500  
			});
		$('#login-box').animate({top: '-40px'},1250,"easeOutElastic", function() {
			$(document).bind('keydown', _login_keyboard_action);
			$('#client-login, #nvs_overlay').click(function() { 
				_login_hide();
			});
		});
	}
	
	function _login_hide() {
		$.nvsOverlay.hide();
		$('#client-login').unbind();
		$(document).unbind('keydown', _login_keyboard_action);
		$('#login-box').animate({top: '-150px'},1000,"easeOutBounce", function() {
			$('#client-login').click(function() {
				_login_show();
			});		
		});

	}
	
	function _login_keyboard_action(objEvent) {
		if(objEvent.keyCode == 27) {
			_login_hide();
			$(document).unbind('keydown', _login_keyboard_action);
			$('#login-box').animate({top: '-150px'},1000,"easeOutBounce");
			
		}
	}
	
var dc = {
	common_ext: {},
	all_ext: {},
	create_domainrow: function(options){
		var img = '';
		var link_class = '';
		if(options.status == 'Vrij'){
			img = '<img src="/img/domein_ico_registreren.gif" alt="Plaats het domein in de winkelwagen" /> ';
			img+= 'Plaats in winkelwagen';
			link_class = 'add_cart';
		} else if(options.status == 'Bezet') {
			img = '<img src="/img/domein_ico_verhuizen.gif" alt="Verhuis het domein naar Netvlies" /> ';
			img+= 'Verhuis naar Netvlies';
			link_class = 'domain_registered';
		} else {
			img = '';
		}
		var tr = jQuery(
			'<tr id="'+options.id+'">'+
				'<td class="first"><a class="'+link_class+'">'+img+'</a></td>'+
				'<td>'+options.domain+'</td>'+
				'<td>'+options.status+'</td>'+
				'<td>&euro; '+options.price+'</td>'+
			'</tr>'
		);
		tr.find('.add_cart, .domain_registered').click(function(){
			dc.cart.add_domain(options.domain);
		});
		return tr;
	},
	format_domain: function(domain){
		return domain.split('.')[0];
	},
	send_form: function(){
		$('#domain_list').empty();
		//Format the domain
		var domain = $('#domain_domain').val(dc.format_domain($('#domain_domain').val())).val();
		
		var exts = jQuery('#domain_extensions').val() === 'common' ? dc.common_ext : dc.all_ext ; 
		jQuery(exts).each(function(index, domainext){
			var data = 'ext='+domainext.extension+'&'+jQuery('#hosting_step1').serialize();
			$('#domain_list').prepend(dc.create_domainrow({
				id: 'domain_row_'+domainext.domain_extension_id,
				domain: domain+'.'+domainext.extension,
				status: 'Controleren',
				price: domainext.price
			}));

			$.ajax({
				url: "/ajax/domaincheck.ajax.php",
 				data: data, 
 				dataType: 'json',
				success: function(data){
					$('#results').show(200);
					$('#domain_row_'+domainext.domain_extension_id).replaceWith(dc.create_domainrow({
						id: 'domain_row_'+domainext.domain_extension_id,
						domain: domain+'.'+domainext.extension,
						status: data.status,
						price: domainext.price
					}));
				}
			});
		});
		
		return false;
	},
	cart: {},
	pack: {}
}

dc.cart = {
	add_domain: function(domain){
		var data = 'domain='+domain+'&action=add_domain';
		$.ajax({
			url: "/ajax/domaincart.ajax.php",
			data: data,
			beforeSend: function() { $('#action-winkelmand-wrapper').fadeOut(); },
			complete: dc.cart.refresh
// 			dataType: 'json',
// 			success: function(data){
// 				alert(data);
// 			}
		});
	},
	init: function(){
		$('#action-winkelmand .del').click(function(){
			dc.cart.remove(this.id.split('_')[2]);
		});
	},
	remove: function(id){
		$.ajax({
			url: "/ajax/domaincart.ajax.php",
			data: 'action=remove_domain&domain_cart_id='+id, 
			dataType: 'html',
			complete: dc.cart.refresh,
			success: function(){
				if($('#hosting_step2')[0]){
					window.location.href = String(window.location.href);
				} else {
					dc.cart.refresh();
				}
			}
		});
	},
	refresh: function(){
		$.ajax({
			url: "/ajax/domaincart.ajax.php",
			data: 'action=list'+($('#hosting_step1')[0] ? '&allow_delete_last=1' : ''), 
			dataType: 'html',
			success: function(data){
				$('#action-winkelmand').html(data);
				dc.cart.init();
			},
			complete: function() { $('#action-winkelmand-wrapper').fadeIn() }
		});
	}
};

dc.pack = {
	init: function(){
		var form = $('#hosting_step2');
		form.submit(dc.pack.send_form);
		form.find('input').change(function(){ 
			form.submit();
		});
	},
	send_form: function(){
		$.ajax({
			url: "/ajax/domaincart.ajax.php",
			data: 'action=set_package&'+$('#hosting_step2').serialize(),
			complete: function(){
				dc.cart.refresh();
			} 
// 			dataType: 'jsson',
// 			success: function(data){
// 				$('#results').show(200);
// 				$('#domain_row_'+domainext.domain_extension_id).replaceWith(dc.create_domainrow({
// 					id: 'domain_row_'+domainext.domain_extension_id,
// 					domain: domain+'.'+domainext.extension,
// 					status: data.status,
// 					price: domainext.price
// 				}));
// 			}
		});
		return false;
	}
}

