$(function() {
	$('.shoppingCartAutocomplete').autocomplete({
		minLength: 3,
		delay: 150,
		source: function(request, response) {
			$.ajax({
				url: 'zoeken/suggest/' + request.term,
				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() {
			$('.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);
	};
	
	$('.addProductToShoppingCart').click(function() {
		var productId = $(this).attr('id').split('_')[1];
		addProduct('winkelwagen', productId, 1);
		
		return false;
	});
	
	$('.addProductToShoppingCartWithProperties').click(function() {
		var amount = $('#productProperty_amount').val();
		
		if(isInteger(amount) && amount > 0)
		{
			var postdata = $('#shoppingCartProductProperties').serialize();
			var productId = $('#productProperty_productId').val();
		
			addProduct('winkelwagen', productId, amount, postdata);	
			$(this).dialog('close');
		}
		else
		{
			var msgDialog = $('<div></div>')
			.html('Geen geldig aantal')
			.dialog({
				resizable: false,
				draggable: false,
				modal: true,
				title: 'Geen geldig aantal',
				buttons: {
					Opnieuw: function() {
						$(this).dialog('close');
						$('#productProperty_amount').focus();
					}
				}
			});
		}
		
		return false;
	});
	
	$('#shoppingCartProductProperties').find('select').change(function() {
		var productId = $('#productProperty_productId').val();
		var productPropertyId = $(this).attr('id').split('_')[1];
		var productPropertyOptionId = $(this).val();
		
		getNewPrice('winkelwagen', productId, $('#productProperty_amount').val(), $('#shoppingCartProductProperties').serialize());
	});
	
	$('.shoppingCartAdd input').keyup(function() {
		var productId = $(this).attr('id').split('_')[1];
	
		getNewPrice('winkelwagen', productId, $(this).val(), '');
	});

	$('#productProperty_amount').keyup(function() {
		var productId = $('#productProperty_productId').val();
	
		getNewPrice('winkelwagen', productId, $(this).val(), $('#shoppingCartProductProperties').serialize());
	});
	
	$('.addProductToShoppingCartDialog').click(function() {
		var productId = $(this).attr('id').split('_')[1];
		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 = '';
						} 
						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="1">'));
				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>');
				
				var img = $('<img src="'+data.productImage+'" width="'+data.productWidth+'" height="'+data.productHeight+'" />');
				
				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 msgDialog = $('<div></div>')
				.append(containerDiv)
				.dialog({
					resizable: false,
					draggable: false,
					width: '550px',
					height: 'auto',
					modal: true,
					title: data.title,
					close: function(){
						$('.addProductDialog-select').die('change');
						$('.addProductDialog-input').die('keyup');
						$('.ui-dialog').html('');
						$('.ui-dialog').remove();
					},
					buttons: {
						Annuleren: function() {
							$(this).dialog('close');
						},
						Toevoegen: function() {
							var amount = $('#addProductDialog-productPropertiesForm input[name=amount]').val();
							
							if(isInteger(amount) && amount > 0)
							{
								var postdata = $('#addProductDialog-productPropertiesForm').serialize();
								var productId = $('.addProductDialog-productId').val();
							
								addProduct('winkelwagen', productId, amount, postdata);	
								$(this).dialog('close');
							}
							else
							{
								showDialog('Geen geldig aantal', 'Geen geldig aantal', 'error');
							}
						}
					}
				});
			}
		});
	});
	
	$('#searchForm .startSearch').click(function() {
		$('#searchForm').submit();
	});
});

function getNewPrice(handlerUrl, productId, amount, data)
{
	if(timer != null)
	{
		clearTimeout(timer);
		timeout = 10000;
	}
	else
	{
		timeout = 0;
	}
	
	timer =	setTimeout(
				function()
				{
					var url = handlerUrl + '/getNewPrice/' + productId + '/';
					
					$.ajax({
						type: 'POST',
						url: url,
						dataType: 'json',
						data: data+'&amount='+amount,
						//async: false,
						success: function(data)
						{
							if(data.stock > 0)
							{
								if(data.showStock==1)
								{
									$('#inStockField').html(data.stock);
								}
								else
								{
									$('#inStockField').html('Ja');
								}
								
								$('#notInStockInfo').css('display', 'none');
								$('#isInStockInfo').css('display', '');
								
								$('.addProductToShoppingCartWithProperties').removeAttr('disabled');
								$('.addProductToShoppingCartWithProperties').removeClass('disabled');							
							}
							else
							{
								if(data.showStock=='1')
								{
									$('#inStockField').html(data.stock);
								}
								else
								{
									$('#inStockField').html('Nee');
								}
								
								$('#notInStockInfo').css('display', '');
								$('#isInStockInfo').css('display', 'none');
								
								$('.addProductToShoppingCartWithProperties').addClass('disabled');
								$('.addProductToShoppingCartWithProperties').attr('disabled', 'disabled');
							}
							
							if(data.isOnSale == '1')
							{
								$('#shoppingCartProductPropertiesPrice span').html(data.onSalePrice);
								$('.productPriceUpdateField').html(data.onSalePrice);
							}
							else
							{
								$('#shoppingCartProductPropertiesPrice span').html(data.price);
								$('.productPriceUpdateField').html(data.price);
							}
							
							$('.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 = '';
			$(fieldId).qtip("destroy");
		}
		
		$(fieldId).removeClass('error');
	}
}

function addProduct(handlerUrl, productId, amount, postData)
{
	var url = handlerUrl + '/addProduct/' + productId + '/' + amount;
	var data = postData;
	
	$.ajax({
		url: url,
		type: 'POST',
		dataType: 'json',
		data: data,
		success: function(data)
		{
			$('#numberOfProductsInShoppingCart').text(data.totalAmount);
			$('#totalPriceShoppingCart').text(data.subtotal);
			
			/*
			var msgDialog = $('<div></div>')
				.html(data.message)
				.dialog({
					resizable: false,
					draggable: false,
					height:140,
					modal: true,
					title: data.title,
					buttons: {
						Sluiten: function() {
							$(this).dialog('close');
						},
						Afrekenen: function() {
							window.location.href = 'winkelwagen';
						}
					}
				});
			*/
			
			//alert($('#productId_' + productId).attr('id'));
			
			var lnk = $('#productId_' + productId);
			
			lnk.qtip({
					content: {
						text: data.message + (data.code == 'success' ? ' <a href="winkelwagen">Bekijk hier uw winkelwagen</a>' : '')
					},
			        position: {
						corner: {
							tooltip: 'bottomMiddle',
							target: 'topMiddle'
						}
					},
					style: {
						border: {
							width: 2,
							radius: 4
						},
						padding: 5,
						tip: true,
						name: data.code == 'success' ? 'cream' : 'red'
					},
					show: {
						delay: 0,
						ready: true, 
			            solo: true
					},
					hide: {
						when: {
							event: false
						},
						delay: 0
					},
					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()
				{
					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() {
		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);
				$('#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);
						
						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)
{
	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);
			$('#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 + '% 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()
{
	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()
				{
					var url = handlerUrl + '/checkEmail/' + email;
					
					$.ajax({
						type: 'POST',
						url: url,
						dataType: 'json',
						success: function(data)
						{
							if(data.code == 'userExists')
							{
								$('#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
		);
}
