﻿$(document).ready(function(){
	$(document).ajaxStart(function(){
		$('img.img-loading').show();
	}).ajaxStop(function(){
		$('img.img-loading').hide();
	});

	jQuery.fn.dataTableExt.aTypes.push(  
		function ( sData )  
		{  
			var sValidChars = "0123456789.-,";  
			var Char;  
			  
			/* Check the numeric part */  
			for ( i=1 ; i<sData.length ; i++ )   
			{   
				Char = sData.charAt(i);   
				if (sValidChars.indexOf(Char) == -1)   
				{  
					return null;  
				}  
			}  
			  
			/* Check prefixed by currency */  
			if ( sData.charAt(0) == '€')  
			{  
				return 'currency';  
			}  
			return null;  
		}  
	);
	
	jQuery.fn.dataTableExt.oSort['currency-asc'] = function(a,b) {
		/* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */
		var x = a == "-" ? 0 : a.replace( /,/g, "" );
		var y = b == "-" ? 0 : b.replace( /,/g, "" );
		
		/* Remove the currency sign */
		x = x.substring( 1 );
		y = y.substring( 1 );
		
		/* Parse and return */
		x = parseFloat( x );
		y = parseFloat( y );
		return x - y;
	};

	jQuery.fn.dataTableExt.oSort['currency-desc'] = function(a,b) {
		/* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */
		var x = a == "-" ? 0 : a.replace( /,/g, "" );
		var y = b == "-" ? 0 : b.replace( /,/g, "" );
		
		/* Remove the currency sign */
		x = x.substring( 1 );
		y = y.substring( 1 );
		
		/* Parse and return */
		x = parseFloat( x );
		y = parseFloat( y );
		return y - x;
	};
	
	jQuery.fn.maxlength = function(){
		$("textarea[@maxlength]").keypress(function(event){ 
			var key = event.which;
			
			//all keys including return.
			if(key >= 33 || key == 13) {
				var maxLength = $(this).attr("maxlength");
				var length = this.value.length;
				if(length >= maxLength) {
					
					event.preventDefault();
				}
			}
		});

	}
	
	/* Wordt o.a. gebruikt om ProductID uit ID van een rij te halen. prod[x] */
	$.fn.extractNumber = function(e){
		return e.match(/\d+/)[0]; 
	};
	
	/* Fix for IE versions to make the css menu work */
	$("#navmenu-h li,#navmenu-v li").hover(
		function() { $(this).addClass("iehover"); },
		function() { $(this).removeClass("iehover"); }
	);

	$('a[rel=lightbox]').lightBox({
		txtImage: 'Afbeelding',
		containerResizeSpeed: 150,
	});
	
	$('div#notification').live("click", function(){
		window.location.href = '/winkelwagen/';
	}).live("mouseenter", function(){
		$(this).clearQueue().stop().show();
	}).live("mouseleave", function(){
		$(this).slideUp();
	});
	
	
	//Klikken op productrij -> doorlinken
	$('table.products-table tr.product-row').click(function(e){
		var productID = $().extractNumber($(this).attr('id'));
		window.location.href = '/webshop/prod/'+productID+'/';
	});
	
	//Plaats een product in de winkelwagen
	$('#BtnBuyProduct').click(function(){
		$.__storage = {};
		$.__storage['tmp'] = {};
		
		//Bekijk of er productopties zijn
		$('.product_option').each(function(index, elem){
			if($(elem).is('select') || $(elem).is('input') || $(elem).is('textarea')){
				var option_id = $().extractNumber($(elem).attr('name'));
				$.__storage['tmp'][option_id] = $(elem).val();
			}
		});
		
		
		$.ajax({
			url: '/index.php?ajax=1&ac=cart&cart=add_product_to_cart&id='+$('input#prod_id').val()+'&quantity='+$('input#txt_amount').val(),
			data: { 'options': $.__storage['tmp'] },
			success: function(r){
				updateSmallCart();
				$('#small-cart-container').fadeIn(1000);
				$('div#box-quantity').hide();
				$('#BtnBuyProduct').html('<span class="icon check"></span>Het product is toegevoegd').attr('href', '/winkelwagen/').unbind('click');
			}
		});
	});
	
	//Bewerk een productbestelling
	$('#BtnEditProduct').click(function(){
		$.__storage = {};
		$.__storage['tmp'] = {};
		
		//Bekijk of er productopties zijn
		$('.product_option').each(function(index, elem){
			if($(elem).is('select') || $(elem).is('input') || $(elem).is('textarea')){
				var option_id = $().extractNumber($(elem).attr('name'));
				$.__storage['tmp'][option_id] = $(elem).val();
			}
		});
		
		
		$.ajax({
			url: '/index.php?ajax=1&ac=cart&cart=edit_product_in_cart&id='+$('input#index').val()+'&quantity='+$('input#txt_amount').val(),
			data: { 'options': $.__storage['tmp'] },
			success: function(r){
				updateSmallCart();
				$('#small-cart-container').fadeIn(1000);
				$('div#box-quantity').hide();
				$('#BtnEditProduct').html('<span class="icon check"></span>Het product is bewerkt').attr('href', '/winkelwagen/').unbind('click');
			}
		});
	});
	
	//Verwijder een product uit de winkelwagen (mini-cart)
	$('img.remove-product-cart').live("click", function(){
		var iIndex = $(this).attr("rel");
		$.get('/index.php?ajax=1&ac=cart&cart=remove_product_from_cart&id='+iIndex,
			function(r){
				updateSmallCart();
			}		
		);
	});
	

	
	//http://docs.jquery.com/Plugins/Autocomplete/autocomplete#url_or_dataoptions
	$('input#search-input-fld').autocomplete('/index.php?ajax=1&ac=search&search=search-autocomplete',
		{
			dataType: "json",
			parse: function(data){
				return $.map(data, function(row) {
					return {
						data: row,
						value: row.name,
						result: row.name
					}
				});
			},
			formatItem: function(item) {
				return item.name;
			}

		}
	).result(function(event, data, formatted){
		if(data){
			window.location.href = '/webshop/prod/'+data.id+'/'+data.name_frmt+'/';
		}
	});
	
	
	$('select#option_lettertype').selectmenu({
		icons: [
			{find: '.image'}
		],
		bgImage: function() {
			return $(this).css("background-image");
		}
	});
	
	
	//Vernieuw de winkelwagen (mini-cart)
	function updateSmallCart(){
		$.get('/index.php?ajax=1&ac=cart&cart=get_cart_small',
			function(data){
				if(data.indexOf('empty-cart') != -1){
					$('#small-cart-container').fadeTo(300,0.5).html(data).fadeTo(300,1);
				} else {
					$('#small-cart-container').html(data);
				}
			}
		);
	}
	
	// Vernieuw de winkelwagen (groot)
	function updateLargeCart(){
		$.get('/index.php?ajax=1&ac=cart&cart=get_cart_large',
			function(data){
				$('#large-cart-container').html(data);
			}
		);
	}
	
	//Inlogformulier / registratieformulier
	$('input[name=action_type]').change(function(){
		if($(this).val() == "login"){
			$("#type_register").css({"display":"none"});
			$("#type_login").slideDown();
		} else if($(this).val() == "register"){
			$("#type_login").css({"display":"none"});
			$("#type_company").slideUp();
			$("#type_register").slideDown();	
		} else if($(this).val() == "register_company"){
			$("#type_login").css({"display":"none"});
			$("#type_company").slideDown();
			$("#type_register").slideDown();
		}
	});

	
	
	
	//Verzendadres en factuuradres zijn gelijk = 0
	$('input[name=i_d_copy]').change(function(){
		if($('input[name=i_d_copy]:checked').val() == 0){
			//Kopieer wijzigingen naar delivery adres
			$('fieldset#type_invoice input,select').trigger('change');
			$("#type_delivery").slideUp();
		} else if($('input[name=i_d_copy]:checked').val() == 1){
			$("#type_delivery").slideDown();
		}
	});
	
	//Formulier voor nieuwe gebruikers
	$('#frm_register_address').ready(function(){
		//Bij page refresh moet uitschuiven goed gaan
		$('input[name=i_d_copy]').trigger('change');
		
		$('input[name=i_gender]').change(function(){
			if($('input[name=i_d_copy]:checked').val() == 0){
				var index = $('input[name=i_gender]:checked').index('input[name=i_gender]');
				if(index > -1){
					$('input[name=d_gender]')[index].checked=true;
				}
			}
		});
		
		var arr = ['first_name','middle_name','last_name','company_name','address','postcode','city','country'];
		$.each(arr, function(key,value){
			$('#i_'+value).change(function(){
				if($('input[name=i_d_copy]:checked').val() == 0){
					$('#d_'+value).val($(this).val());//.trigger("blur");
				}
			});
		});
	});
	
	//Login formulier wat als optie wordt getoond bij registratie gebruikers
	$('a#login_from_cart').live("click", function(){
		$(this).data('value', $(this).find('span').html());
		$('#login_from_cart_error').html("Even geduld...").show();
		
		$.post('/index.php?ajax=1&ac=feuser&feuser=login_cart', 
			{ 
				email: $('#login_cart_email').val(),
				password: $('#login_cart_password').val()
			},
			function(data){
				//Niet ingelogd
				if(data.length > 1){
					$('#login_from_cart_error').html(data);
				} else {
					$('#login_from_cart_error').html('');
					$('#login_table').html("U bent nu ingelogd en wordt doorgestuurd...");
					window.location.href = '/winkelwagen/adres/';
				}
				
				$('a#login_from_cart').find('span').html($('a#login_from_cart').data('value'));
			}
		);	
	});
	
	
	
	
	$('a.submit-form').click(function(){
		var $frm = $('form#'+$(this).attr("rel"));
		$frm.trigger('submit');	
	});
	
	//Als op enter wordt gedrukt bij invoervelden, kijk of het formulier gesubmit kan worden
	$('form input').keypress(function(event){
		//Enter char
		if (event.which == '13') {
			var form_id = $(this).parents('form').attr('id');
			if(form_id){
				$('a[rel='+form_id+']').trigger('click');
			}
		}
	});
	
	
	//Controleer of e-mailadres niet al in gebruik is.
	$('#frm_register_customer #email').live("blur", function(){
		$fld_email = $(this);
		$.get('/index.php?ajax=1&ac=feuser&feuser=check_unique_pass&email='+$fld_email.val(),
			function(data){ //0=uniek //1=ongeldig //2=in gebruik
				if(data == 1){
					$fld_email.addClass('fld_error').after('<span class="error">E-mailadres is ongeldig!</span>');
				} else if(data == 2){
					$fld_email.addClass('fld_error').after('<span class="error">E-mailadres is al in gebruik!</span>');
					return false;
				} else {
					$fld_email.removeClass('fld_error');
					$fld_email.parent().find('span.error').remove();
				}
			}
		);
	});
	
	//Formulier nieuwe gebruikers -> validatie
	$('#frm_register_customer').live("submit", function(e){
		/* Alleen de velden die nog niet rood zijn gemarkeerd opnieuw valideren */
		$.ajaxSetup({ async: false });
		$(":input:not(.fld_error)").trigger('blur');
		$.ajaxSetup({ async: true });
		
		if($(".fld_error").length >0){
			alert('Enkele velden zijn nog niet juist ingevuld!');
			return false;
		}
		
		return true;
	});
	
	$('div#dialog-invoice-copy p#copy_invoice').click(function(){
		$('input[name=i_gender][value='+$(this).children('input[name=copy_i_gender]').val()+']').attr('checked', true);
		$('#i_first_name').val($(this).children('input[name=copy_i_first_name]').val());
		$('#i_middle_name').val($(this).children('input[name=copy_i_middle_name]').val());
		$('#i_last_name').val($(this).children('input[name=copy_i_last_name]').val());
		$('#i_company_name').val($(this).children('input[name=copy_i_company_name]').val());
		$('#i_address').val($(this).children('input[name=copy_i_address]').val());
		$('#i_postcode').val($(this).children('input[name=copy_i_postcode]').val());
		$('#i_city').val($(this).children('input[name=copy_i_city]').val());
		$('#i_country').val($(this).children('input[name=copy_i_country]').val());

		//Kopieer wijzigingen ook naar delivery adres
		if($('input[name=i_d_copy]:checked').val() == 0){
			$('fieldset#type_invoice input,select').trigger('change');
		}
		$('div#dialog-invoice-copy').dialog('close');
	});
	
	$('div#dialog-delivery-copy p#copy_delivery').click(function(){
		$('input[name=d_gender][value='+$(this).children('input[name=copy_d_gender]').val()+']').attr('checked', true);
		$('#d_first_name').val($(this).children('input[name=copy_d_first_name]').val());
		$('#d_middle_name').val($(this).children('input[name=copy_d_middle_name]').val());
		$('#d_last_name').val($(this).children('input[name=copy_d_last_name]').val());
		$('#d_company_name').val($(this).children('input[name=copy_d_company_name]').val());
		$('#d_address').val($(this).children('input[name=copy_d_address]').val());
		$('#d_postcode').val($(this).children('input[name=copy_d_postcode]').val());
		$('#d_city').val($(this).children('input[name=copy_d_city]').val());
		$('#d_country').val($(this).children('input[name=copy_d_country]').val());
		$('div#dialog-delivery-copy').dialog('close');
	});
	
	$('img#copy_invoice_address').click(function(){
		$('div#dialog-invoice-copy').dialog({
			position: ['center', 'center'],
			modal: true,
			draggable: false,
			width: 450,
			height: 200,
			title: 'Kopieer adresgegevens van vorige bestelling(en):'
		});
	});	
	
	$('img#copy_delivery_address').click(function(){
		$('div#dialog-delivery-copy').dialog({
			position: ['center', 'center'],
			modal: true,
			draggable: false,
			width: 450,
			title: 'Kopieer adresgegevens van vorige bestelling(en):'
		});
	});	
	
	
	
	
	$('tr.cart-product-row').live("mouseenter", function(){
		//$(this).find('img#cart-product-show-more').css("visibility","");
	}).live("mouseleave", function(){
		//$(this).find('img#cart-product-show-more').css("visibility","");
	}).live("click", function(eventOb){
		eventOb = $(eventOb.target);
		if(eventOb.is('div') && eventOb.parent().hasClass('cartAantal_plusmin')){
			var iIndex 	 	 = $(this).closest('tr').attr("id");
			var oQuantityFld = $(this).closest('tr').find(".cart_quantity");
			var current      = parseInt($(oQuantityFld).val());
			
			if(eventOb.hasClass('cartAantal_plus')){
				$.get('/index.php?ajax=1&ac=cart&cart=change_quantity&id='+iIndex+'&quantity='+(current+1),
					function(r){
						updateSmallCart();
						updateLargeCart();
					}	
				);
			} else {
				/* Verlaag productaantal - icoon */
				$.get('/index.php?ajax=1&ac=cart&cart=change_quantity&id='+iIndex+'&quantity='+(current-1),
					function(r){
						updateLargeCart();
						updateSmallCart();
					}	
				);
			}
		} else if(eventOb.is('a')){
			//			
		} else if(eventOb.is('input')){
			//Doe ff niets...		
		} else {
			//Slide them all up! ;)
			$('table#tbl_shoppingcart_large div.cart-product-more-info').slideUp(300);
			
			var $elem = $(this).find("div.cart-product-more-info");
			if($elem.css("display") == "none"){
				$elem.slideDown(500);
			} else {
				$elem.slideUp(300);
			}
		}
	}); 
	
	//Als een productbestelling wordt gewijzgd, moeten de opties worden ingevuld met waarden uit de sessie
	$('.product-option-value').each(function(){
		if($(this).html().length >0){
			var option_id = $().extractNumber($(this).attr('id'));
			
			//Lettertype gebruikt 'selectmenu', en dat werkt niet met .val()...
			if(option_id == 8){
				$('.product_option[name="option[8]"]').selectmenu('value', $(this).html());
			} else {
				$('.product_option[name="option['+option_id+']"]').val($(this).html());
			}
		}
	});
	
	
	//Wijzig waarde bij quantity text field
	$('input.cart_quantity').live("change", function(){
		var iProdId = $(this).closest('tr').attr("id");
		var current = $(this).val();
		
		$.get('/index.php?ajax=1&ac=cart&cart=remove_product_from_cart&id='+iProdId+'&quantity='+current,
			function(r){
				updateLargeCart();
				updateSmallCart();
			}	
		);
	});	
	
	
	$('a.button').click(function(e){
		if($(this).attr('href') == '#'){
			e.preventDefault();
		}
	});
	
	
	$('#caddyTabList ul li.inactive a').click(function(e){
		e.preventDefault();
		return false;
	});
	
	
	
	$('input#chk-general-conditions').click(function(){
		if($(this).attr("checked") == true){
			$('#fieldset-send-method').fadeIn();
		} else {
			$('#fieldset-send-method').fadeOut();
			$('#fieldset-payment-method').fadeOut();
		}
	});
	
	$('input.send-options-radio').click(function(){
		if($(this).attr("checked") == true){
			$('#fieldset-payment-method').fadeIn();
		} else {
			$('#fieldset-payment-method').fadeOut();
		}
	});
	
	$('div.send-method').click(function(){
		//Eerst alles 'resetten'
		$('div.send-method').removeClass('send-method-active');
		
		var rad = $(this).find('.send-options-radio');
		rad.attr("checked", "checked");
		
		$('#fieldset-payment-method').fadeIn();
		$(this).addClass('send-method-active');
	});
	
	
	$('div.payment-method').click(function(){
		//Eerst alles 'resetten'
		$('div.payment-method').removeClass('payment-method-active');
		
		var rad = $(this).find('.payment-options-radio');
		rad.attr("checked", "checked");
		
		
		if(rad.val() == "ideal"){
			if($('select#bank_id').val() != ''){
				$('#btn-payment-ideal').css("display", "block");
			} else {
				$('#btn-payment-ideal').css("display", "none");
			}
			$('#btn-payment-transfer').css("display", "none");
		} else {
			$('#btn-payment-ideal').css("display", "none");
			$('#btn-payment-transfer').css("display", "block");
		}
		
		$(this).addClass('payment-method-active');
	});
	
	$('select#bank_id').change(function(){
		if($(this).val() != ''){
			$('#btn-payment-ideal').css("display", "block");
		} else {
			$('#btn-payment-ideal').css("display", "none");
		}
	});
	
	
	//Tabs, o.a. bij account overzicht
	$('.tab_container > div').addClass('tab_content');
	if(location.hash != "") {
		var target = location.hash.split("#")[1]
		$(location.hash).show(); //Show first tab content
		$("ul.tabs li:has(a[rel=#"+target+"])").addClass("active").show();
	} else {
		$("ul.tabs li:first").addClass("active").show(); //Activate first tab
		$(".tab_content:first").show(); //Show first tab content
	}

	//On Click Event
	$("ul.tabs li").click(function() {
		$("ul.tabs li").removeClass("active"); //Remove any "active" class
		$(this).addClass("active"); //Add "active" class to selected tab
		$(".tab_content").hide(); //Hide all tab content
		var activeTab = $(this).find("a").attr("rel"); //Find the rel attribute value to identify the active tab + content
		$(activeTab).fadeIn(); //Fade in the active content
	});
	
	$('.products-table').dataTable( {
		"bPaginate": true,
		"bLengthChange": false, //products per page
		"bFilter": true, //zoeken
		"bSort": true,
		"bInfo": true,
		"bJQueryUI": true,
		"bStateSave": true, //cookie opslaan
		"aLengthMenu": [[20, 30, 60], [20, 30, 60]],
		"sPaginationType": "full_numbers",
		"bAutoWidth": true,
		"oLanguage": {
			"sSearch": "Zoeken in tabel",
			"sProcessing": "Verwerken...",
			"sLengthMenu": "_MENU_ per pagina",
			"sZeroRecords": "Geen producten gevonden...",
			"sEmptyTable": "Geen producten gevonden...",
			"sInfo": "Weergave _START_ tot _END_ van _TOTAL_ producten",
			"sInfoEmpty": "",
			"sInfoFiltered": "(na zoekopdracht uit _MAX_ producten)",
			"oPaginate": {
				"sFirst":    "Eerste",
				"sPrevious": "Vorige",
				"sNext":     "Volgende",
				"sLast":     "Laatste"
			}
		},
		"aoColumns": [
			{ "asSorting": [ "asc", "desc" ] },
			{ "asSorting": [ "asc", "desc" ] },
			{ "asSorting": [ "asc" ] },
			{ "asSorting": [ "asc", "desc" ], "sType": "currency" }
		]		
	} );
	
	
	/*Rating gebeuren*/
	$('div.rating').raty();
	
	$('div.rating-fixed').raty({
		readOnly:  true
	});
	
	$('div.rating-fixed').each(function(){
		var rate = $().extractNumber($(this).attr('class'));
		var boxid = '#'+$(this).attr('id');
		$.fn.raty.start(rate, boxid);
	});
	
	$('#open-review-frm').click(function(e){
		$('#box-frm-add-review').toggle();
		e.preventDefault();
		$(this).parent('div').hide();
	});
	
	
	if($('#box-frm-add-review').size() >0){
		//Er zijn errors na het versturen, klap dus form uit!
		if($('input.error, select.error, textarea.error').size() >0){
			$('#open-review-frm').trigger('click');
		}		
	}
	
	
	// We only want these styles applied when javascript is enabled
	$('div.navigation').css({'width' : '300px', 'float' : 'left'});
	$('div.content').css('display', 'block');

	if($('#thumbs').size() >0){
		$('#thumbs').galleriffic({
			delay:                     3000, // in milliseconds
			numThumbs:                 5, // The number of thumbnails to show page
			preloadAhead:              40, // Set to -1 to preload all images
			enableTopPager:            true,
			enableBottomPager:         false,
			maxPagesToShow:            7,  // The maximum number of pages to display in either the top or bottom pager
			imageContainerSel:         '#slideshow', // The CSS selector for the element within which the main slideshow image should be rendered
			controlsContainerSel:      '#controls', // The CSS selector for the element within which the slideshow controls should be rendered
			captionContainerSel:       '#caption', // The CSS selector for the element within which the captions should be rendered
			loadingContainerSel:       '#loading', // The CSS selector for the element within which should be shown when an image is loading
			renderSSControls:          false, // Specifies whether the slideshow's Play and Pause links should be rendered
			renderNavControls:         false, // Specifies whether the slideshow's Next and Previous links should be rendered
			playLinkText:              '',
			pauseLinkText:             'Pause',
			prevLinkText:              'Vorige',
			nextLinkText:              'Volgende',
			nextPageLinkText:          'Volgende &rsaquo;',
			prevPageLinkText:          '&lsaquo; Vorige',
			enableHistory:             false, // Specifies whether the url's hash and the browser's history cache should update when the current slideshow image changes
			enableKeyboardNavigation:  true, // Specifies whether keyboard navigation is enabled
			autoStart:                 false, // Specifies whether the slideshow should be playing or paused when the page first loads
			syncTransitions:           false, // Specifies whether the out and in transitions occur simultaneously or distinctly
			defaultTransitionDuration: 1000, // If using the default transitions, specifies the duration of the transitions
			onSlideChange:             undefined, // accepts a delegate like such: function(prevIndex, nextIndex) { ... }
			onTransitionOut:           undefined, // accepts a delegate like such: function(slide, caption, isSync, callback) { ... }
			onTransitionIn:            undefined, // accepts a delegate like such: function(slide, caption, isSync) { ... }
			onPageTransitionOut:       undefined, // accepts a delegate like such: function(callback) { ... }
			onPageTransitionIn:        undefined, // accepts a delegate like such: function() { ... }
			onImageAdded:              undefined, // accepts a delegate like such: function(imageData, $li) { ... }
			onImageRemoved:            undefined  // accepts a delegate like such: function(imageData, $li) { ... }
		});
	}
});

/* Wordt aangeroepen door FH gegenereerde code */
function FH_VALIDATE( validator, field, error, path, includedir, msg ){
	var url = path + 'ajax/validate.php';
	var pars = 'value=' + $('#'+field).val();
	pars += '&field=' + field;
	pars += '&validator=' + validator;
	pars += '&includedir=' + includedir;
	pars += '&msg=' + escape( msg );	
	pars += '&msgbox=error_' + error;
	var target = '#error_'+ error;
	
	$.get(url, pars, function(data){
		if(data.length < 1){
			$('#'+field).removeClass( 'fld_error' );
		} else {
			$('#'+field).addClass( 'fld_error' );
		}
	});
}
