$(document).ready(function(){

	$('.itemcount').keyup(function() {
		var itemid = $(this).attr('id').replace('count','');
		updateItemCount(itemid, $(this).val());
	});
	var startDate = ''
	if (typeof(shopOverruleDate) != 'undefined') {
	
		var startDateSplit = shopOverruleDate.split(' ');

		if (startDateSplit.length == 3) {
			startDate = new Date(startDateSplit[2], startDateSplit[1], startDateSplit[0])
		}
	}

	var useDate = new Date().addDays(1);

	if (typeof(startDate) != 'undefined' && startDate != '') {
		useDate = startDate;
	}

	if($('.datePickerShop').length) {
		$('.datePickerShop').datePicker(
			{
				startDate: (useDate).asString(),
				endDate: (new Date().addMonths(5)).asString()
			}
		);
		$('.datePickerShop').change(function() {
			tempDate = $(this).val();
			$('.dateInputDay').val(tempDate.split('/')[0]);
			$('.dateInputMonth').val(tempDate.split('/')[1]);
			$('.dateInputYear').val(tempDate.split('/')[2]);
			var dateholderSelector = '#dateholder_' + $('.dateInputYear').attr('id').split('_')[1];
			$(dateholderSelector).val(tempDate.split('/')[0] + '/' + tempDate.split('/')[1] + '/' + tempDate.split('/')[2]); 
		});
		$('.datePickerShop').datePicker().val(useDate.asString()).trigger('change');
	} 	
});

function addToBasket(id) {
	// show the 'Please wait...' message
	scroll(0,0);
	$('#lockAll, #pleasewait').show();
	// Set the referer
	setCookie('shopreferer', '' + document.location.href, '');		
	
	var url = '/web/wcbservlet/nl.gx.product.wmpshopservlets.impl.Add?';
	var redirecturl = $('#jsonerrorsurl').attr('href');
	url = url + 'id=' + id + '&nrofitems=1&redirurl=' + redirecturl;
	$.ajax({
		url: "" + url + "",
		type: "GET",
		dataType: "json",
		success: function(data){
			// Hide the 'Please wait...' message
			$('#pleasewait').hide();		
			if (data.errors == 'false') {
				// Show the 'Product has been added' message
				$('#lockAll, #messagePopup').show();
				// Update the small shopping cart
				updateSmallShopCart();
			} else {
				$('#lockAll, #alreadyinbasket').show();
			}
		}
	});
}

function addLicenceToBasket(id) {
	// Set the referer
	setCookie('shopreferer', '' + document.location.href, '');		
	
	var url = '/web/wcbservlet/com.gxwebmanager.solutions.licenceservlet.servlet?';
	var redirecturl = $('#licencepageurl').attr('href');
	url = url + 'id=' + id + '&action=add&redirurl=' + redirecturl;
	document.location = url;

}

function updateItemCount(id, count) {
	$.ajax({
		type: "GET",
		url: "/web/wcbservlet/nl.gx.product.wmpshopservlets.impl.Update?nrofitems="+count+"&id="+id,
		success: function(msg) {
			// Update the shopcart
			updateShopCart();		
		}
  	});
}

function removeFromBasket(id) {
	// Remove the item from the basket
	var url = '/web/wcbservlet/nl.gx.product.wmpshopservlets.impl.Remove?';
	url = url + 'id=' + id;
	$.ajax({
		url: "" + url + "",
		type: "GET",
		success: function(html){
			// Remove the order line TR from the shopping cart TABLE
			$('#shopcartitem'+id).remove();
			// Update the shopcart
			updateShopCart();
		}
	});
}

function continueShopping() {
	var referer = getCookie('shopreferer');
	if (referer != '') {
		document.location = referer;	
	}
}

function doCheckout() {
	var redirecturl = $('#checkoutpageurl').attr('href');
	if ($('#licenceInShoppingCart').val() == 'true') {
		// validate the shopping cart
		var url = '/web/wcbservlet/com.gxwebmanager.solutions.licenceservlet.servlet?';
		var errorurl = $('#errorpageurl').attr('href');
		redirecturl = url + 'action=validate&redirurl=' + escape(redirecturl) + '&errorurl=' + errorurl;
	}
	document.location = redirecturl;
}

function updateShopCart() {
	// Get the updated shopcart
	var url = $('#jsonurl').attr('href');
	if (url != '') {
		$.getJSON("" + url + "", function(data, textStatus) {
			if (data.totalItemCount == 0) {
				// Remove shopping cart, show 'empty' message
				$('.block-tableWinkelwagen').remove();
				$('#checkoutbutton').remove();
				$('#emptyshoppingcart').show();
				return;
			} 
			// Update subtotal prices
			$.each(data.items, function(i, item) {
				$('#subtotal' + item.identifier).html(item.totalPrice);
			});			
			
			// Update total price
			$('#totalPriceTD').html(data.totalPrice);
		});
	}
}

function updateSmallShopCart() {
	// Get the updated shopcart
	var url = $('#jsonurl').attr('href');
	if (url != '') {
		$.getJSON("" + url + "", function(data, textStatus) {
			if (data.totalItemCount == 0) {
				$('#pleasewaitsc').hide();
				$('#emptysmallsc').show();
				$('#smallsc').hide();
			} else {
				$('#pleasewaitsc').hide();
				$('#emptysmallsc').hide();
				$('#smallsc').show();
				var html = '<b>' + data.totalItemCount + '</b>';
				if (data.totalItemCount == 1) {
					html = html+' product';
				} else {
					html = html+' producten';
				}
				html = html+' in uw winkelwagen';
				$('#smallSCText').html(html);
				$('#licenceInShoppingCart').val(data.licenceInShopCart);

				// Build the shop list of items.
				var $smallBasketItemsDiv = $('#smallBasketItems');

				if ($smallBasketItemsDiv.length > 0) {
					var shopList = new Array();

					var allItems = data.items;

					if (allItems.length > 0) {
						for (i = 0; i < allItems.length; i++) {
							shopList.push('<div class="item">');
							shopList.push('<a href="javascript:void(0)" class="delete-icon" onclick="removeFromBasket(\'');
							shopList.push(allItems[i].identifier);
							shopList.push('\');updateSmallShopCart();"></a>');
							shopList.push('<span>');
							shopList.push(allItems[i].name);
							shopList.push('</span>');
							shopList.push('</div>');
			}
					}
					$smallBasketItemsDiv.html(shopList.join(''));
				}
			}
		});
	}
}

function triggerBasket(link) {
	$('#smallBasketItems').slideToggle(300);
	$(link).toggleClass('opened');
}
