
function LoadWebshopWidget(szPage, szElementSelector, szParams) { var szUrl = szBaseUrl+'?tc=Webshop&page=' + szPage + '&type=widget&dt=' + new Date().getTime(); if (szParams != null) { jQuery.each(szParams, function(key, val) { szUrl += '&' + key + '=' + val; }); } jQuery.ajax({ async:true,  url:szUrl, success:function(data){ $(szElementSelector).html(data); } }); } 
function WebshopRedirect(szPage, szParams) { var szUrl = szBaseUrl + '?tc=Webshop&page=' + szPage; if (szParams != null) { jQuery.each(szParams, function(key, val) { szUrl += '&' + key + '=' + val; }); } document.location = szUrl; }
jQuery.fn.Loading = function() { if ($(this).length > 0) { $(this).find('input.button').attr('disabled', 'disabled'); $(this).append('<div class="loading_panel" style="width:' + $(this).outerWidth() + 'px;height:' + $(this).outerHeight() + 'px;top:' + $(this).position().top + 'px;left:' + $(this).position().left + 'px;"></div>'); } };
jQuery.fn.FinishedLoading = function() { if ($(this).find('.loading_panel').length > 0) { $(this).find('input.button').attr('disabled', ''); $(this).find('.loading_panel').hide(); } };

function CheckCustomerInfo() {
	var szMessages = '';
	$('.account_info label').css('color','');
	var bFieldsOK = true;
	for (var i = 0; i < $('.account_info').length; i++) {
		var oAccountInfo = $('.account_info').eq(i);
		for (var j = 0; j < oAccountInfo.find(':input:visible').length; j++) {
			var oInput = oAccountInfo.find(':input:visible').eq(j);
			if ((oInput.attr('name').indexOf('field_') == 0) && (oInput.attr('name').indexOf('housenumberaddition') < 0) && (oInput.val().length == 0)) {
				oInput.parent().find('label').css('color','red');
				bFieldsOK = false;
			}
		}
		if(oAccountInfo.find('.field_email input:visible').length > 0) {
			if(!IsValidEmail(oAccountInfo.find('.field_email input:visible').val()))
				szMessages += 'Je hebt geen geldig e-mail adres opgegeven.\n';
			else if(oAccountInfo.find('.field_email input:visible').val() != oAccountInfo.find('.field_email2 input:visible').val())
				szMessages += 'Je hebt je e-mail adres niet goed bevestigd.\n';
		}
		if((oAccountInfo.find('.field_postalcode input:visible').length > 0) && !IsValidPostalCode(oAccountInfo.find('.field_postalcode input:visible').val()))
			szMessages += 'Geef een geldige postcode op.\n';
	}
	if (!bFieldsOK)
		szMessages += 'Je hebt niet alle verplichte velden ingevoerd.\n';
	return szMessages;
}

function CheckOrder() {
	var szMessages = '';
	
	if ($('#field_customerid').length == 0)  // check customer account
		szMessages += 'Je moet inloggen met je account, of anders een nieuw account aanmaken.\n';
	
	// check customer data
	szMessages += CheckCustomerInfo();
	
	// check terms
	if ($('#field_terms:checked').length == 0)
		szMessages += 'Je moet akkoord gaan met onze voorwaarden.\n';
	
	var szUrl = szBaseUrl + '?tc=Webshop&page=CheckoutProcess&type=widget&action=process';
	for (var i = 0; i < $('.checkout_container .account_block input').length; i++) {
		var oInput = $('.checkout_container .account_block input').eq(i);
		szUrl += '&' + oInput.attr('name') + '=' + escape(oInput.val());
	}
	if($('#field_deliveryaddress:checked').length > 0)
		szUrl += '&deliveryaddress=yes';
	for (var i = 0; i < $('.checkout_container .delivery_block input').length; i++) {
		var oInput = $('.checkout_container .delivery_block input').eq(i);
		szUrl += '&' + oInput.attr('name') + '=' + escape(oInput.val());
	}
	szUrl += '&dt=' + new Date().getTime();
	
	if (szMessages.length > 0)
		alert(szMessages);
	else {
		$('#webshop_checkout_buttonbar').Loading();
		jQuery.ajax({
			async:true, 
			url:szUrl,
			success:function(data){
				$('#webshop_checkout_buttonbar').FinishedLoading();
				$('#webshop_checkout_results').html(data);
			} 
		});
	}
	return false;
}

function PayForOrder() {
	if (confirm('Weet u zeker dat u de bestelling wilt plaatsen, en wilt gaan betalen?')) {
		$('#webshop_confirmation_buttonbar').Loading();
		jQuery.ajax({
			async:true, 
			url:szBaseUrl + '?tc=Webshop&page=To_Payment&type=widget&action=process&dt=' + new Date().getTime(),
			success:function(data){
				//$('#webshop_confirmation_buttonbar').FinishedLoading();
				$('#webshop_confirmation_results').html(data);
			} 
		});
	}
}

function LoadDeliveryAddressWidget() {
	if ($('.webshop_action_usedeliveryaddress:checked').length > 0) {
		$('.delivery_block').show();
		if($('.delivery_block').children().length == 0) {
			$('.delivery_block').Loading();
			LoadWebshopWidget('Account', '.delivery_block', { values:'delivery', load_in_account_block:'no', set_customerid:'no', fieldprefix:'delivery_' });
		}
	}
	else
		$('.delivery_block').hide();
}

function CheckSaveAccount() {
	var szMessages = CheckCustomerInfo();
	if (szMessages.length > 0)
		alert(szMessages);
	else {
		var szUrl = szBaseUrl + '?tc=Webshop&page=AccountProcess&type=widget&action=process';
		for (var i = 0; i < $('.account_info input').length; i++) {
			var oInput = $('.account_info input').eq(i);
			szUrl += '&' + oInput.attr('name') + '=' + escape(oInput.val());
		}
		szUrl += '&dt=' + new Date().getTime();
		$('#webshop_account_buttonbar').Loading();
		jQuery.ajax({
			async:true, 
			url:szUrl,
			success:function(data){
				$('#webshop_account_buttonbar').FinishedLoading();
				$('#webshop_account_results').html(data);
			} 
		});
	}
}

/* INITIALIZATION */
$(document).ready(function() {
	if(window.location.href.indexOf('https://') < 0) {
		LoadWebshopWidget('Basket_Widget', '#shopping_cart_widget');
		LoadWebshopWidget('Account_Widget', '#signup');
	}
	InitializeDynamicBindings();
	
	// one-off bindings
	$('.loading').Loading();
	$('.webshop_basketlink').click(function(){ WebshopRedirect('Basket'); });
	$('.webshop_action_to_checkout').click(function(){ WebshopRedirect('Checkout'); });
	$('.webshop_action_orderstatus').click(function(){ WebshopRedirect('OrderStatus', { ordernumber:$(this).text() }); });
	$('.webshop_action_to_basket').click(function(){ WebshopRedirect('Basket'); });
	$('.webshop_action_saveaccount').click(function(){ CheckSaveAccount(); });
	$('.webshop_action_checkorder').click(function(){ CheckOrder(); });
	$('.webshop_action_to_confirmation').click(function(){ WebshopRedirect('Confirmation'); });
	$('.webshop_action_to_payment').click(function(){ PayForOrder(); });
	$('.webshop_action_basketupdate').change(function(){ WebshopRedirect('Basket', {action:'update', biid:$(this).val(), number:$('#' + $(this).attr('id') + ' option:selected').text()}) });
	$('.webshop_action_basketremove').click(function(){ WebshopRedirect('Basket', {action:'remove', biid:$(this).attr('href') }); return false; });
	$('.webshop_action_checkoutregister').click(function(){ $('.checkout_block').hide(); $('.account_block').show(); $('.account_block').Loading(); LoadWebshopWidget('Account', '.account_block'); });
	$('.webshop_action_usedeliveryaddress').click(function() { LoadDeliveryAddressWidget(); });
	$('.webshop_action_termslink').click(function(){
		var szUrl = $(this).attr('href') + '&view=ajax&dt=' + new Date().getTime();
		$('#terms_window').show();
		$('#terms_window').mouseleave(function(){ $('#terms_window').hide(); });
		$('#terms_container').Loading();
		jQuery.ajax({
			async:true, 
			url:szUrl,
			success:function(data){
				$('#terms_container').html(data);
			} 
		});
		return false;
	});
	
	$('#dialog').dialog({
		autoOpen: false,
		closeOnEscape: true,
		width: 700,
		minHeight: 500,
		modal: true,
		//hide: {effect: "fadeOut", duration: 5000},
		buttons: {
			"Toevoegen aan mandje": function(){ AddProductToCart(); }, 
			"Sluiten": function() { $(this).dialog("close"); } 
		}
	});
	
	// DIALOG LINK
	$('.dialog_link').click(function(event){
		event.preventDefault();	
		$("#dialog")
			.html("LOADING...")
			.load($(this).attr("href") + "&view=ajax&dt=" + new Date().getTime(), function(){ InitializeDynamicBindings(); })
			.dialog('open');	
	});
});


function BindAjaxForms() {
	$('form.ajaxform').submit(function() {
		var oForm = $(this);
		oForm.Loading();
		$.post($(this).attr('action'), $(this).serialize(), function(data) {
			oForm.html(data);
		});
		return false;
	});
}




function InitializeDynamicBindings() {
	$(".product_detail select.reload").bind('change',function(){
		var url = szBaseUrl + '?tc=productdetail&pid=' + $(this).attr('title') + '&aid=' + $(this).val() + '&dt=' + new Date().getTime();
		if ($('#dialog:visible').length > 0)
			$("#dialog").load(url + '&view=ajax', function(){ InitializeDynamicBindings(); })
		else
			document.location = url;
	});
	
	// SELECT PRODUCT BY IMAGE
	$(".product_detail div.jquery_select_product_byimage").bind('click',function(event){
		AddProductToCart();
	});	
	
	// ADD THUMBNAILS OF PRODUCT IN PRODUCTDETAIL TO THE CLICK EVENT  
	$(".product_detail img.productdetailthumb").bind('click',function(){
		// Large productphoto
		$("img#" + $(this).attr("alt")).addClass("active");
		$("div.productdetail_image_container img.active").not("img#" + $(this).attr("alt")).removeClass("active");	
		
		// chnange thumb active state
		$("ul.productdetail_images li").removeClass("active");
		$(this).parent().addClass("active");
	});	
	
	// IMAGE HOVERS
	$('.product_detail img.image_thumbnail').hover(function() {
		var szImageTitle = $(this).attr('title');
		$('.product_detail .image .image_container').hide();
		jQuery.each($('.product_detail .image .image_container'), function(node) {
			if($('.product_detail .image .image_container').eq(node).children().eq(0).attr('title') == szImageTitle) {
				$('.product_detail .image .image_container').eq(node).show();
			}
		});
	});
	
	// WEBSHOP WIDGETS
	if($('.login_widget').length > 0) { LoadWebshopWidget('Login', '.login_widget'); }
	if($('.account_widget').length > 0) { LoadWebshopWidget('Account', '.account_widget'); }
	LoadDeliveryAddressWidget();
}












/********** SECONDARY FUNCTIONS ***********/


function AddProductToCart(){
	var szArticleID = $("#productdetail_select_size").val();
	jQuery.ajax({
		async:true, 
		url:szBaseUrl+'?tc=Webshop&page=Basket_Widget&action=add&type=widget&aid=' + szArticleID + '&dt=' + new Date().getTime(),
		success:function(data){
			$('#shopping_cart_widget').html(data);
		} 
	});
	AnimateProductToCartWidget();
}


function AnimateProductToCartWidget() {
	// GET ALL VALUES NEEDED TO DUPLICATE - MOVE - SCALE PRODUCTIMAGE
	var position_product = $(".product_detail div.image div.image_container:visible").offset();
	var position_cart = $("#shoppingcarticon").offset();
	
	var image = $(".product_detail div.image img:visible");
	
	if((position_product != null) && (image != null)) {
		var image_width = image.width();
		var image_height = image.height();	
		
		var image_top = position_product.top + 10; // -1 because of border around div.jquery_select_product_byimage
		var image_left = position_product.left + 10;
		
		var cart = $("#shoppingcarticon");
		var cart_top = position_cart.top;
		var cart_left = position_cart.left;
		var cart_width = cart.width();
		var cart_height = cart.height();	
		
		// CREATE DUPLICATE
		$("<div></div>")
			.attr("id", "productduplicate")
			.css({display: "block", position: "absolute", zIndex: 2000})
			.width(image_width)
			.height(image_height)
			.offset({ top: image_top, left: image_left })
			.appendTo("body")
			.html($(".product_detail div.image img:visible").clone());
	
		// CREATE ANIMATION AND DELETE DUPLICATE FROM DOM
		$("#productduplicate").animate({
			opacity: 0.6,
			left: cart_left,
			top: cart_top,
			height: cart_height,
			width: cart_width
			}, 800, function() {
				$(".shopping_cart").addClass("shopping_cart_selected"); // HIGLIGHT CARTCONTAINER
				$("#productduplicate").remove();
				$("#dialog").dialog("close");
				$(".shopping_cart").removeClass("shopping_cart_selected", 1400); // REMOVE HIGLIGHT CARTCONTAINER
		});
	}
	else {
		$(".shopping_cart").addClass("shopping_cart_selected"); // HIGLIGHT CARTCONTAINER
		$("#dialog").dialog("close");
		$(".shopping_cart").removeClass("shopping_cart_selected", 1400); // REMOVE HIGLIGHT CARTCONTAINER
	}
}

function IsValidEmail(szEmail)
{
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	return (filter.test(szEmail));
}
function IsValidPostalCode(szPostalcode)
{
	var filter = /^[1-9][0-9]{3}\s?[a-zA-Z]{2}$/;
	return (filter.test(szPostalcode));
}
