/**
 * COMMENTAAR TOEGEVOEGD WAT NIET GESCHIKT IS VOOR PRODUCTIE
 * 
 */
$(function() {
	if ($('.shoppingCartAutocomplete').length > 0) {
				
		$('.shoppingCartAutocomplete').autocomplete({
			minLength: 3,
			delay: 150,
			source: function(request, response) {
				
				if(multilanguage != '' && multilanguage)
				{
					var url = languageId+'/zoeken/suggest/' + request.term;
				}
				else
				{
					var url = 'zoeken/suggest/' + request.term;
				}
				
				$.ajax({
					url: url,
					type: 'POST',
					dataType: 'json',
					success: function(data) {
						response($.map(data.items, function(item) {
							return {
								label: item.name,
								value: item.name,
								data: item
							}
						}));
					}
				});
			},
			select: function(event, ui) {
				document.location = ui.item.data.url;
			},
			open: function() {
				$('.ui-autocomplete').prepend('<strong>'+language.getText('Zoeksuggesties voor')+' <em>' + $('.shoppingCartAutocomplete').val() + '</em></strong>');
				$('.ui-autocomplete').append('<a href="#" class="allResults">Alle zoekresultaten</a>');
				$('.ui-autocomplete .allResults').click(function() {
					$('.shoppingCartAutocomplete').parent().submit();
					
					return false;
				});
				
				$('.shoppingCartAutoSuggestItem:last').addClass('last');
			}
		}).data('autocomplete')._renderItem = function(ul, item) {
			var li = '<li class="shoppingCartAutoSuggestItem">';
			li += '<a>';
			li += '<span class="image">';
			
			if (item.data.image.length > 0) {
				li += '<img src="' + item.data.image + '" alt="" height="50" />';
			}
			
			li += '</span>';
			li += '<span class="meta">';
			li += '<span class="name">' + item.data.name + '</span>';
			
			if (item.data.shortDescription.length > 0) {
				li += '<span class="shortDescription">' + item.data.shortDescription + '</span>';
			}
			
			li += '</span>';
			li += '<span class="clear"></span>';
			li += '</a>';
			li += '</li>';
			
			return $(li).data('item.autocomplete', item).appendTo(ul);
		};
	}
	
	$('#stockInfo .moreInfo').live('click', function() {
		var text = $('em', this).text();
		
		showDialog(text, +language.getText('Meer informatie'));
		
		return false;
	});
	
	$('#productWrapper .addProductToShoppingCart').live('click', function() {
		var productId = $(this).attr('id').split('_')[1];
		var shoppingCartSessionProductId = $(this).attr('id').split('_')[2];
		
		var customData = '';
		addProduct('winkelwagen', productId, 1, customData, shoppingCartSessionProductId);
		
		return false;
	});
	
	$('.shoppingCartAdd .addProductToShoppingCart').live('click', function() {
		var productId = $(this).attr('id').split('_')[1];
		var shoppingCartSessionProductId = $(this).attr('id').split('_')[2];
		var amount = 1;
		
		// Gebruik in productdetails?
		var productIdChk = $('#productProperty_productId').val();
		var amountObj = $('#productProperty_amount');
		
		if($('#customData').length > 0)
		{
			var customData = $('#customData').serialize();
		}
		else
		{
			var customData = '';
		}
		
		if(amountObj.length)
		{
			amount = amountObj.val();
		}
		
		addProduct('winkelwagen', productId, amount, customData, shoppingCartSessionProductId);
		
		return false;
	});
	
	$('.addProductToShoppingCartWithProperties').live('click', function() {
		var productId = $(this).attr('id').split('_')[1];
		var shoppingCartSessionProductId = $(this).attr('id').split('_')[2];
		var amount = $('#productProperty_amount').val();

		if(isInteger(amount) && amount > 0)
		{
			var postdata = $('#shoppingCartProductProperties').serialize();
		
			addProduct('winkelwagen', productId, amount, postdata, shoppingCartSessionProductId);	
			$(this).dialog('close');
		}
		else
		{
			var buttons = {};
			buttons[language.getText('Opnieuw')] = function(){ 
				$(this).dialog('close');
				$('#productProperty_amount').focus();
			}
			
			var msgDialog = $('<div></div>')
			.html('Geen geldig aantal')
			.dialog({
				resizable: false,
				draggable: false,
				modal: true,
				title: language.getText('Geen geldig aantal'),
				buttons: buttons
			});
		}
		
		return false;
	});

	
	$('#shoppingCartProductProperties select').change(function() {
		var productId = $('#productProperty_productId').val();
		var productPropertyId = $(this).attr('id').split('_')[1];
		var productPropertyOptionId = $(this).val();
		var amount = $('#productProperty_amount').val();
		var postData = $('#shoppingCartProductProperties').serialize();
		
		getNewPrice('winkelwagen', productId, amount, postData);
	});
	
	/**
	 * Wat doet deze? Doet deze uberhaubt nog iets?
	 */
	$('.shoppingCartAdd input').keyup(function() {
		var productId = $(this).attr('id').split('_')[1];
		var productId = $('#productProperty_productId').val();

		getNewPrice('winkelwagen', productId, $(this).val(), '');
	});

	$('#productProperty_amount').keyup(function() {
		var productId = $('#productProperty_productId').val();
	
		getNewPrice('winkelwagen', productId, $(this).val(), $('#shoppingCartProductProperties').serialize());
	});
	
	$('.addProductToShoppingCartDialog').live('click', function() {
		var productId = $(this).attr('id').split('_')[1];
		
		if(multilanguage != '' && multilanguage)
		{
			var url = languageId+'/winkelwagen' + '/addProductDialog/' + productId + '';
		}
		else
		{
			var url = 'winkelwagen' + '/addProductDialog/' + productId + '';
		}
		
		$.ajax({
			url: url,
			type: 'POST',
			dataType: 'json',
			data: 'productId='+productId,
			success: function(data)
			{	
				var namespace = 'addProductDialog';
							
				var containerDiv = $('<div id="'+namespace+'-productProperties"></div>');
				
				var form = $('<form id="'+namespace+'-productPropertiesForm"></form>');
			
				var fieldset = $('<fieldset class="'+namespace+'-fieldset"></fieldset>');
				
				var legend = $('<legend>'+data.message+'</legend>)'); 
				fieldset.append(legend);
				
				$(data.productProperties).each(function(){
					var dt = $('<dt></dt>');
					var dd = $('<dd></dd>');
					
					var selectFieldLabel = $('<label class="'+namespace+'-label" for="'+namespace+'-productProperty_'+this.id+'">'+this.description+'</label>');
					dt.append(selectFieldLabel);
					
					var selectField = $('<select class="'+namespace+'-select" id="'+namespace+'-productProperty_'+data.productId+'_'+this.id+'" name="productProperty['+this.id+']">');
					$(this.options).each(function(){
						
						var selected = '';
						if(this.selected == this.id)
						{
							selected = 'selected="selected"';
						} 
						selectField.append('<option value="'+this.id+'" '+selected+' >'+this.value+'</option>');
					});
					
					dd.append(selectField);
					
					fieldset.append(dt);
					fieldset.append(dd);
				});
			
				var dt = $('<dt></dt>');
				var dd = $('<dd></dd>');
				dt.append($('<label class="'+namespace+'-label" for="'+namespace+'-amount">Aantal</label>'));
				dd.append($('<input type="text" class="text '+namespace+'-input" id="'+namespace+'_'+data.productId+'" name="amount" value="'+data.from+'">'));
				dd.append($('<input type="hidden" class="addProductDialog-productId" name="productId" value="'+data.productId+'">'));
				
				fieldset.append(dt);
				fieldset.append(dd);
				
				form.append(fieldset);
				
				containerDiv.append(form);
				
				var divProductPrice = $('<div class="productPrice"></div>');

				var divTitle = $('<div class="propertyTitle">&euro;</div>');

				if(data.isOnSale == '1')
				{
					var currentUnitPrice = data.onSalePrice;
				}
				else
				{
					var currentUnitPrice = data.price;
				}
				
				var divValue = $('<div class="productPriceUpdateField">'+currentUnitPrice+'</div>');
				
				if(data.productImage)
				{
					var src = data.productImage;
					var width = data.productWidth;
					var height = data.productHeigh;
				}
				else
				{
					var src = 'layout/frontend/images/noPicDialog.jpg';
					var width = 146;
					var height = 146;
				}
				
				var img = $('<img src="'+src+'" width="'+width+'" height="'+height+'" style="margin-top:10px;" />');
				
				divProductPrice.append(divTitle);
				divProductPrice.append(divValue);
				divProductPrice.append(img);
				
				containerDiv.append(divProductPrice);

				if(data.hasMatrix == '1')
				{
					$('.addProductDialog-select').live('change', function(){
						var productId = $(this).attr('id').split('_')[1];
						var productPropertyId = $(this).attr('id').split('_')[2];
						var productPropertyOptionId = $(this).val();
						
						getNewPrice('winkelwagen', productId, $('.addProductDialog-input').val(), $('#addProductDialog-productPropertiesForm').serialize());
					});
					
					$('.addProductDialog-input').live('keyup', function(){
						var productId = $(this).attr('id').split('_')[1];					
						getNewPrice('winkelwagen', productId, $(this).val(), $('#addProductDialog-productPropertiesForm').serialize());
					});
				}
				
				var annuleren = language.getText('Annuleren');
				var toevoegen = language.getText('Toevoegen');
				
				var buttons = {};
				buttons[language.getText('Annuleren')] = function(){ 
					$(this).dialog('close');
				};
				
				buttons[language.getText('Toevoegen')] = function(){ 
					if(multilanguage != '' && multilanguage)
					{
						var url = languageId+'/winkelwagen/getNewPrice/' + productId + '/';
					}
					else
					{
						var url = 'winkelwagen/getNewPrice/' + productId + '/';
					}
					
					var data = $('#addProductDialog-productPropertiesForm').serialize();
					$.ajax({
						type: 'POST',
						url: url,
						dataType: 'json',
						data: data,
						//async: false,
						success: function(data)
						{	
							if(data.code=='failed' && data.from > 0)
							{
								$('#addProductDialog-productPropertiesForm input[name="amount"]').val(data.from);
								showDialog(language.getText('Voor dit product geldt een minimale afname van')+' <strong>'+data.from+'</strong> ', language.getText('Ongeldig aantal'), 'error');
							}	
							else
							{
					
								var amount = $('#addProductDialog-productPropertiesForm input[name=amount]').val();
								
								if(data.stock > 0 || data.notInStockOrderable)
								{
							
									if(amount <= data.stock || data.notInStockOrderable)
									{
										if(isInteger(amount) && amount > 0)
										{
											var postdata = $('#addProductDialog-productPropertiesForm').serialize();
											var productId = $('.addProductDialog-productId').val();
										
											addProduct('winkelwagen', productId, amount, postdata, 0);	
											$(msgDialog).dialog('close').remove();
										}
										else
										{
											showDialog(language.getText('Geen geldig aantal'), language.getText('Geen geldig aantal'), 'error');
										}
									}
									else
									{
										var msg = '';
										if(data.stock==1)
										{
											msg = language.getText('Van dit product is er nog')+' '+data.stock+' '+language.getText('op voorraad. Verminder uw aantal of neem contact met ons op.');
										}
										else
										{
											msg = language.getText('Van dit product zijn er nog')+' '+data.stock+' '+language.getText('op voorraad. Verminder uw aantal of neem contact met ons op.');
										}
										
										showDialog(msg, language.getText('Geen geldig aantal'), 'error');
									}
								}
								else
								{
									showDialog(language.getText('Dit product is niet op voorraad'), language.getText('Dit product is niet op voorraad'), 'error');
								}
							}
						}
					});	
				};
				
				var msgDialog = $('<div id="ui-productProperties-dialog"></div>')
				
				.append(containerDiv)
				.dialog({
					resizable: false,
					draggable: false,
					width: '500px',
					height: 'auto',
					modal: true,
					title: data.title,
					buttons: buttons
				});
			}
		});
	});
	
	$('#searchForm .startSearch').click(function() {
		$('#searchForm').submit();
	});
});

function getNewPrice(handlerUrl, productId, amount, data)
{

	if(timer != null)
	{
		clearTimeout(timer);
		timeout = 500;
	}
	else
	{
		timeout = 0;
	}
	
	timer =	setTimeout(
				function()
				{
					if(multilanguage != '' && multilanguage)
					{
						var url = languageId+'/'+handlerUrl + '/getNewPrice/' + productId + '/';
					}
					else
					{
						var url = handlerUrl + '/getNewPrice/' + productId + '/';
					}
					
					$.ajax({
						type: 'POST',
						url: url,
						dataType: 'json',
						data: data+'&amount='+amount,
						//async: false,
						success: function(data)
						{	

							var buttons = $('.ui-dialog-buttonset').css('display', '');
					
							if(data.stock > 0)
							{
								if(data.showStock==1)
								{
									$('#inStockField').html(data.stock);
								}
								else
								{
									$('#inStockField').html('Ja');
								}
				
								$('#notInStockInfo').hide();
								$('#isInStockInfo').show();
								
								$('.amount').removeAttr('disabled');
								$('.amount').removeClass('disabled');
								
								$('.addProductToShoppingCartWithProperties').removeAttr('disabled');
								$('.addProductToShoppingCartWithProperties').removeClass('disabled');							
							}
							else
							{
								if(data.showStock=='1')
								{
									$('#inStockField').html(data.stock);
								}
								else
								{
									$('#inStockField').html('Nee');
								}
						
								if(!data.notInStockOrderable)
								{
									$('#notInStockInfo').show();
									$('#isInStockInfo').hide();
									
									$('.amount').addClass('disabled');
									$('.amount').attr('disabled', 'disabled');
									
									$('.addProductToShoppingCartWithProperties').addClass('disabled');
									$('.addProductToShoppingCartWithProperties').attr('disabled', 'disabled');
								}
							}
							
							
							if(data.isOnSale == '1')
							{
								if($('#addProductDialog-productProperties').length)
								{
									$('.productOnSalePriceUpdateField', $('#addProductDialog-productProperties')).html(data.price);
									$('.productPriceUpdateField', $('#addProductDialog-productProperties')).html(data.onSalePrice);
									
									if(data.pricePer || data.onSalePricePer)
									{
										$('.productPricePerUpdateField', $('#addProductDialog-productProperties')).html(data.pricePer);
										$('.productOnSalePricePerUpdateField', $('#addProductDialog-productProperties')).html(data.onSalePricePer);
									}
								}
								else
								{
									$('.productOnSalePriceUpdateField', $('.productView')).html(data.price);
									$('.productPriceUpdateField', $('.productView')).html(data.onSalePrice);
									
									if(data.pricePer || data.onSalePricePer)
									{
										$('.productPricePerUpdateField', $('.productView')).html(data.pricePer);
										$('.productOnSalePricePerUpdateField', $('.productView')).html(data.onSalePricePer);
									}
								}
							}
							else
							{
								if($('#addProductDialog-productProperties').length)
								{
									$('.productPriceUpdateField', $('#addProductDialog-productProperties')).html(data.price);
									
									if(data.pricePer || data.onSalePricePer)
									{
										$('.productPricePerUpdateField', $('#addProductDialog-productProperties')).html(data.pricePer);
										$('.productOnSalePricePerUpdateField', $('#addProductDialog-productProperties')).html(data.onSalePricePer);
									}
								}
								else
								{
									$('.productPriceUpdateField', $('.productView')).html(data.price);
									
									if(data.pricePer || data.onSalePricePer)
									{
										$('.productPricePerUpdateField', $('.productView')).html(data.pricePer);
										$('.productOnSalePricePerUpdateField', $('.productView')).html(data.onSalePricePer);
									}
								}
							}

							
							
							$('.productCodeUpdateField').html(data.productCode);
							
							timer = null;
						}
					});
				},
				timeout
		);
}

function setFieldError(fieldId, message)
{
	var text = '';
	
	try
	{
		text = $(fieldId).qtip('api').options.content.text;
	}
	catch(ex) {}
	
	if(message != '')
	{
		if($(fieldId).data("qtip") && text != message)
		{
			$(fieldId).qtip("destroy");
		}
		
		if(message != text || text == '')
		{
			$(fieldId).qtip({
					content: message,
					position: {
						corner: {
							tooltip: 'leftBottom',
							target: 'rightTop'
						}
					},
					style: {
						border: {
							width: 2,
							radius: 4
						},
						padding: 5,
						textAlign: 'center',
						tip: true,
						name: 'red'
					},
					show: {
						delay: 0,
						ready: true
					},
					hide: {
						when: {
							event: false
						},
						delay: 0
					}
			});
			
			$(fieldId).addClass('error');
		}
	}
	else
	{
		if($(fieldId).data("qtip"))
		{
			$(fieldId).qtip('api').options.content.text = '';
			alert
			$(fieldId).qtip("destroy");
		}
		
		$(fieldId).removeClass('error');
	}
}

function addProduct(handlerUrl, productId, amount, postData, shoppingCartSessionProductId, qtipDisabled, rowKey)
{	
	if(multilanguage != '' && multilanguage)
	{
		var url = languageId+'/'+handlerUrl + '/addProduct/' + productId + '/' + amount;
		var cartUrl = languageId+'/winkelwagen';
	}
	else
	{
		var url = handlerUrl + '/addProduct/' + productId + '/' + amount;
		var cartUrl = 'winkelwagen';
	}
	
	var data = postData+'&shoppingCartSessionProductId='+shoppingCartSessionProductId;

	$.ajax({
		url: url,
		type: 'POST',
		dataType: 'json',
		data: data,
		success: function(data)
		{
			$('#numberOfProductsInShoppingCart').text(data.totalAmount);
			$('#totalPriceShoppingCart').text(data.subtotal);
			
			if(qtipDisabled)
			{
				if(data.code == 'failed')
				{	
					showDialog(data.message, data.title, 'error');
				}
				else
				{
					var div = $('<div class="succes-message" style="display:none; text-align:center; position:absolute; z-index:10; background:green; width:400px; margin-top:-4px; margin-left:-350px; color:#FFF; padding:5px;">'+language.getText('Dit product is succesvol toegevoegd aan')+' <a href="'+cartUrl+'" style="color:#FFF; text-decoration:underline;">'+language.getText('uw winkelwagen')+'</a></div>');
					
					$('#productId_'+productId+'_'+rowKey+'_'+shoppingCartSessionProductId).parent('td').append(div);
					
					div.fadeIn();
					setTimeout(function() { $(div).fadeOut(); }, 2000);
				}
			}
			else
			{
				var lnk = $('#productId_' + productId+'_'+shoppingCartSessionProductId);
				
				if(lnk.length < 1)
				{
					var lnk = $('#productId_' + productId);
				}
				
				lnk.qtip({
						content: {
							text: data.message + (data.code == 'success' ? ' <a href="'+cartUrl+'">'+language.getText('Bekijk hier uw winkelwagen')+'</a>' : '')
						},
						style: {
							classes: data.code == 'success' ? 'cream' : 'ui-tooltip-red'
						},
						position: {
							my: 'bottom center', 
							at: 'top center'
						},
						show: {
							delay: 0,
							ready: true, 
				            solo: true
						},
						hide: false,
						events: {
							hide: function() {
								lnk.qtip('destroy');
							},
							show: function() {
								setTimeout(function() { lnk.qtip('hide'); }, 2000);
							}
						},
						api: {
							onHide: function() {
								lnk.qtip('destroy');
							},
							onShow: function() {
								setTimeout(function() { lnk.qtip('hide'); }, 2000);
							}
						}
				});
			}
		}
	});
}

var timer = null;

function setAmount(handlerUrl, productId, amount)
{
	if(timer != null)
	{
		clearTimeout(timer);
		timeout = 200;
	}
	else
	{
		timeout = 0;
	}
	
	timer =	setTimeout(
				function()
				{
					if(multilanguage != '' && multilanguage)
					{
						var url = handlerUrl +'/'+languageId+'/setProducts/' + productId + '/' + amount;
					}
					else
					{
						var url = handlerUrl + '/setProducts/' + productId + '/' + amount;
					}

					var data = $('#winkelwagen').serialize();
					
					$.ajax({
						type: 'POST',
						url: url,
						dataType: 'json',
						data: data,
						success: function(data)
						{
							$('#numberOfProductsInShoppingCart').text(data.totalAmount);
							$('#totalPriceShoppingCart').text(data.subtotal);
							
							$('.amountField').each(function()
									{
										setFieldError('#amount_' + $(this).attr('id'), '');
									});
							
							$.each(data.products, function(index, value)
									{
										if(value.code == 'success')
										{
											$('#price_' + value.productId).text(value.subTotal);
											
											setFieldError('#amount_' + value.productId, '');
										}
										else
										{
											setFieldError('#amount_' + value.productId, value.message);
										}
										
									});
							
							timer = null;
						}
					});
				},
				timeout
		);
}

var updateShoppingCartTimer = null;

function updateShoppingCart(handlerUrl, productId, amount)
{
	if(updateShoppingCartTimer != null)
	{
		clearTimeout(updateShoppingCartTimer);
		timeout = 200;
	}
	else
	{
		timeout = 0;
	}
	
	updateShoppingCartTimer = setTimeout(function() {
		
		if(multilanguage != '' && multilanguage)
		{
			var url = handlerUrl + '/setProducts/' + productId + '/' + amount;
		}
		else
		{
			var url = handlerUrl + '/setProducts/' + productId + '/' + amount;
		}

		var data = $('#winkelwagen').serialize();
		
		$.ajax({
			type: 'POST',
			url: url,
			dataType: 'json',
			data: data,
			success: function(data) {
				$('#numberOfProductsInShoppingCart').text(data.totalAmount);
				$('#totalPriceShoppingCart').text(data.subtotal);
				$('#shoppingCartSubtotal').text(data.subtotal);
				$('#shoppingCartShippingCosts').text(data.shippingCosts);
				$('#shoppingCartPaymentCosts').text(data.paymentCosts);
				$('#shoppingCartTotal').text(data.total);
				$('#shoppingCartTotalWithTax').text(data.totalWithTax);
				$('#shoppingCartSubtotalWithTax').text(data.subtotalWithTax);
				$('#shoppingCartSubtotalWithoutTax').text(data.subtotalWithoutTax);
				
				$('.amountField').each(function() {
					setFieldError('#amount_' + $(this).attr('id'), '');
				});
				
				$.each(data.products, function(index, value) {
					if(value.code == 'success')
					{
						$('#price_' + value.productId).text(value.subtotal);
						$('#piecePrice_' + value.productId).text(value.price);
						$('#pricePerPiece_' + value.productId).text(value.pricePerPiece);
	
						setFieldError('#amount_' + value.productId, '');
					}
					else
					{
						setFieldError('#amount_' + value.productId, value.message);
					}
					
				});
				
				$('.tax').remove();
				
				var lastElement = $('.totalWithoutTax');

				$.each(data.taxes, function(index, value) {
					var tr = '';
					tr += '<tr class="total tax">';
					tr += '	<td>&nbsp;</td>';
					tr += '	<td class="artikelen">' + value.taxRate + '% B.T.W.</td>';
					tr += '	<td>&nbsp;</td>';
					tr += '	<td>&nbsp;</td>';
					tr += '	<td>&euro; <span id="shoppingCartTaxRate">' + value.tax + '</span></td>';
					tr += '	<td>&nbsp;</td>';
					tr += '</tr>';
					
					lastElement = lastElement.after(tr);
				});
				
				updateShoppingCartTimer = null;
			}
		});
	}, timeout);
}

function deleteProduct(handlerUrl, productId)
{
	if(multilanguage != '' && multilanguage)
	{
		var url = languageId+'/'+ handlerUrl + '/deleteProduct/' + productId;
	}
	else
	{
		var url = handlerUrl + '/deleteProduct/' + productId;
	}
	
	var url = handlerUrl + '/deleteProduct/' + productId;
	var data = {};
	
	$.ajax({
		url: url,
		dataType: 'json',
		data: data,
		success: function(data)
		{
			$('#numberOfProductsInShoppingCart').text(data.totalAmount);
			$('#totalPriceShoppingCart').text(data.subtotal);
			
			$('#shoppingCartSubtotal').text(data.subtotal);
			$('#shoppingCartShippingCosts').text(data.shippingCosts);
			$('#shoppingCartPaymentCosts').text(data.paymentCosts);
			$('#shoppingCartTotal').text(data.total);
			$('#shoppingCartTotalWithTax').text(data.totalWithTax);
			$('#shoppingCartSubtotalWithTax').text(data.subtotalWithTax);
			$('#shoppingCartSubtotalWithoutTax').text(data.subtotalWithoutTax);
			
			$('.tax').remove();
			
			var lastElement = $('.totalWithoutTax');

			$.each(data.taxes, function(index, value) {
				var tr = '';
				tr += '<tr class="total tax">';
				tr += '	<td>&nbsp;</td>';
				tr += '	<td class="artikelen">' + value.taxRate + '% '+language.getText('B.T.W.')+'</td>';
				tr += '	<td>&nbsp;</td>';
				tr += '	<td>&nbsp;</td>';
				tr += '	<td>&euro; <span id="shoppingCartTaxRate">' + value.tax + '</span></td>';
				tr += '	<td>&nbsp;</td>';
				tr += '</tr>';
				
				lastElement = lastElement.after(tr);
			});
			
			if($('.winkelwagen .row').length <= 0)
			{
				location.reload(true);
			}
		}
	});
}

function gotoStep(url)
{
	$('#winkelwagen').attr('action', url);
	$('#winkelwagen').submit();
}

function showLogin(copyEmail)
{
	if($('#customerEmail').data("qtip"))
	{
		$('#customerEmail').qtip('api').options.content.text = '';
		$('#customerEmail').qtip("destroy");
	}
	
	$('.loginShown').slideDown();
	$('.loginHidden').slideUp();
	$('.customerShown').slideUp();
	$('.customerHidden').slideDown();

	$('#newUser').val('');
}

function showCustomer()
{
	$('.loginShown').slideUp();
	$('.loginHidden').slideDown();
	$('.customerShown').slideDown();
	$('.customerHidden').slideUp();

	$('#newUser').val('true');
}

var checkEmailTimer = null;

function checkEmailExistence(handlerUrl, email)
{
	if(checkEmailTimer != null)
	{
		clearTimeout(checkEmailTimer);
		timeout = 200;
	}
	else
	{
		timeout = 0;
	}
	
	checkEmailTimer = setTimeout(
				function()
				{
					if(multilanguage != '' && multilanguage)
					{
						var url = handlerUrl +'/'+languageId+'/checkEmail/' + email;
						console.log(1);
					}
					else
					{
						var url = handlerUrl + '/checkEmail/' + email;
						console.log(2);
					}
					console.log(url);
					$.ajax({
						type: 'POST',
						url: url,
						dataType: 'json',
						success: function(data)
						{
							if(data.code == 'userExists')
							{
							
								$('#shoppingCartLoginForm #userEmail').val(email);
	
								$('.customerData input').attr('disabled', 'disabled');
								$('.customerData select').attr('disabled', 'disabled');
								$('.customerData textarea').attr('disabled', 'disabled');
								
								$('#customerEmail').removeAttr('disabled');
	
								$('#userExistsMessage input').removeAttr('disabled');
								$('#userExistsMessage').show();
							}
							else
							{
								$('#userExistsMessage').hide();
								
								$('.customerData input').removeAttr('disabled');
								$('.customerData select').removeAttr('disabled');
								$('.customerData textarea').removeAttr('disabled');
							}
							
							updateShoppingCartTimer = null;
						}
					});
				},
				timeout
		);
}


//with productMatrixView
function addMatrixProductToCart(row)
{
	var productId = $(row).attr('id').split('_')[1];
	var rowKey = $(row).attr('id').split('_')[2];
	var amount = $('#productProperty_amount_'+rowKey).val();
	
	if(isInteger(amount) && amount > 0)
	{	
		
		var len = $('#productRow-'+rowKey+' .ppid').length;
		var productProperties  = '';
		productProperties = '{ "productProperty" :  { ';
		
		$('#productRow-'+rowKey+' .ppid').each(function(index, element){
			var array = $(this).val().split(':');			
			productProperties += ' "'+array[0]+'" : "'+array[1]+'" ';    
	
			 if (index == len - 1) 
			 {
				 productProperties += '}';
	         }
			 else
			 {
				 productProperties += ',';
			 }
		});
		productProperties += ' } ';
	
		try 
		{
			queryString = decodeURIComponent($.param($.parseJSON(productProperties)));
		} 
		catch(e) 
		{
			queryString = '';
		}
		
		addProduct('winkelwagen', productId, amount, queryString, true, rowKey);	
	}
	else
	{
		var buttons = {};
		buttons[language.getText('Opnieuw')] = function(){ 
			$(this).dialog('close');
			$('#productProperty_amount').focus();
		}
		
		var msgDialog = $('<div></div>')
		.html(language.getText('Geen geldig aantal'))
		.dialog({
			resizable: false,
			draggable: false,
			modal: true,
			title: language.getText('Geen geldig aantal'),
			buttons: buttons
		});
	}
}
