$(document).ready(function() {
	sessionID = 0;
	itemCount = 0;
	boolShowBasket = false;
	
	function updateBasket(responseText, statusText, xhr, $form) {
		
		var myJSONObject = 0;
		$('body').css('cursor','');
		
		try
		{
			var myJSONObject = JSON.parse(responseText);
		}
		catch(err)
		{
			var myJSONObject = eval('('+responseText+')');
		}
		var totalPrice = 0;
		
		// Empty
		$(".basket ul").empty();
		itemCount = 0;
		
		// Fill basket with JSON data
		$.each(myJSONObject.basket, function(i, obj)
		{
		  $(".basket ul").append('<li>' + 
			'<img src="'+obj.image+'" alt="" />' + 
			'<span class="name">'+obj.name+'</span>' + 
			'<span class="size">Options: '+obj.style+'</span>' + 
			'<span class="qty">Qty: <input type="text" value="'+obj.quantity+'" />' + 
			'<a href="#'+obj.cid+'">Update</a></span>' + 
			'<strong class="prise">&pound;'+Math.round(obj.price)+'</strong>' + 
			'<a class="remove" href="#'+obj.cid+'">Remove</a>' + 
			'</li>')
			
			itemCount++;
		});
		
		// set basket Totals
		sessionID = myJSONObject.sessionid;
		$(".checkoutBox .item span").html(myJSONObject.basket.length + ' Item' + (myJSONObject.basket.length != 1 ? 's' : '') + ' - &pound;'+myJSONObject.total);
		$(".checkoutBox .basket .total p").html(myJSONObject.basket.length+ ' Item' + (myJSONObject.basket.length != 1 ? 's' : '') + ' <span>&pound;'+myJSONObject.total+'</span>');
		
		if (boolShowBasket == true)
		{
			$('body').css('cursor','');
			$('.checkoutBox .item').addClass('open'); 
			$('.checkoutBox .basket').slideDown();
		}
		
		/* cart.php */
		if (typeof $(".otherBox") == "object")
		{
			$(".bottomPanel strong.total span").text($(".checkoutBox .item span").html());
		}
		
		boolShowBasket = false;
	}
	
	function loadBasket()
	{
		//$('body').css('cursor','wait');
		$.ajax({
			url: "http://" + location.host + "/shop/json.php",
			processData: false,
			cache: false,
			success: updateBasket
		})
	}
	
	function removeCartItem(cartID)
	{
		//$('body').css('cursor','wait');
		$.ajax({
			url: "http://" + location.host + "/shop/json.php",
			type: "POST",
			data: "delet"+cartID+"=on&quant"+cartID+"=1&mode=update&sessionid="+sessionID,
			processData: false,
			success: updateBasket
		})
	}
	
	function updateCartItem(cartID, quantTo)
	{
		$('body').css('cursor','wait');
		$.ajax({
			url: "http://" + location.host + "/shop/json.php",
			type: "POST",
			data: "quant"+cartID+"="+quantTo+"&mode=update&sessionid="+sessionID,
			processData: false,
			success: updateBasket
		})
	}
	
	// Close shopping basket on ESC keypress
	$(this).keyup(function(event){
		if(event.keyCode == 27)
		{
			$('.checkoutBox .item').removeClass('open'); 
			$('.checkoutBox .basket').slideUp();
		}
	});
	
	/* Update basket item */
	$(".checkoutBox .basket .qty a, .basketTable a.update").live("click", function() {
		$('body').css('cursor','wait');
		updateCartItem($(this).attr("href").substring($(this).attr("href").search('#') + 1, $(this).attr("href").length), $(this).prev().val());
		loadBasket();
		$('body').css('cursor','');
		return false;
	});
	
	/* Remove basket item */
	$(".checkoutBox .basket .remove, .basketTable a.remove").live("click", function() {
		$('body').css('cursor','wait');
		removeCartItem($(this).attr("href").substring($(this).attr("href").search('#') + 1, $(this).attr("href").length));
		loadBasket();
		
		/* cart.php */
		if (typeof $(".otherBox") == "object")
		{
			if ($(this).parent().parent().get(0).tagName.toLowerCase() == "tr")
			{
				$(this).parent().parent().fadeOut(500, function() { $(this).remove() } );
			}
			else {
				$(this).parent().fadeOut(500, function() { $(this).remove() } );
			}
		}
		
		$('body').css('cursor','');
		return false;
	});
	
	/* Use AJAX form post on Add to cart submit */
	$('#prodForm').bind('submit', function() {
		var isfunc = typeof window.formvalidator0;
		if(isfunc == 'function' && formvalidator0(this)) {
			$('body').css('cursor','wait');
			boolShowBasket = true;
			try
			{
				$(this).ajaxSubmit({success: updateBasket});
			}
			catch(err)
			{
				return true; // try to submit the old school way
			}
		}
		return false;
	});
	
	$("form[name=checkoutform]").submit(function(){
		// if (itemCount == 0)
		// {
			// alert("You have to add something to your basket before you can continue.");
			// return false;
		// }
	});
	
	$("form.addres").submit(function(){
	
	var frm = document.forms.mainform;
	var checkedfullname=false;
	var numhomecountries=0,nonhomecountries=0,checkaddress=true,scheckaddress=true;
	
	if(checkaddress){
	if(frm.name.value==""){
		alert("Please enter a value in the field \"Full Name\".");
		frm.name.focus();
		return (false);
	}
	gotspace=false;
	var checkStr = frm.name.value;
	for (i = 0; i < checkStr.length; i++){
		if(checkStr.charAt(i)==" ")
			gotspace=true;
	}
	if(!checkedfullname && !gotspace){
		alert("This message will not be shown again.\nPlease be sure to enter your first and last name in the field \"Full Name\".");
		frm.name.focus();
		checkedfullname=true;
		return (false);
	}
	if(frm.email.value==""){
		alert("Please enter a value in the field \"Email\".");
		frm.email.focus();
		return (false);
	}
	validemail=0;
	var checkStr = frm.email.value;
	for (i = 0; i < checkStr.length; i++){
		if(checkStr.charAt(i)=="@")
			validemail |= 1;
		if(checkStr.charAt(i)==".")
			validemail |= 2;
	}
	if(validemail != 3){
		alert("Please enter a valid email address.");
		frm.email.focus();
		return (false);
	}
	if(frm.address.value==""){
		alert("Please enter a value in the field \"Address\".");
		frm.address.focus();
		return (false);
	}
	if(frm.city.value==""){
		alert("Please enter a value in the field \"City\".");
		frm.city.focus();
		return (false);
	}
	if(frm.country.selectedIndex < numhomecountries){
		if(frm.state.selectedIndex==0){
			alert("Please select a State (US)");
			frm.state.focus();
			return (false);
		}
	}else{
		if(frm.state2.value==""){
			alert("Please enter a value in the field \"County / Province\".");
			frm.state2.focus();
			return (false);
		}
	}
	if(frm.zip.value==""){
		alert("Please enter a value in the field \"Postcode / Zip\".");
		frm.zip.focus();
		return (false);
	}
	if(frm.phone.value==""){
		alert("Please enter a value in the field \"Phone\".");
		frm.phone.focus();
		return (false);
	}
	}
	if(scheckaddress && frm.saddress.value!=""){
		if(frm.sname.value==""){
			alert("If you set the shipping address, please complete all shipping details.\n\nPlease enter a value in the field \"Full Name\".");
			frm.sname.focus();
			return (false);
		}
		if(frm.scity.value==""){
			alert("If you set the shipping address, please complete all shipping details.\n\nPlease enter a value in the field \"City\".");
			frm.scity.focus();
			return (false);
		}
		if(frm.scountry.selectedIndex < numhomecountries){
			if(frm.sstate.selectedIndex==0){
				alert("If you set the shipping address, please complete all shipping details.\n\nPlease select a State (US).");
				frm.sstate.focus();
				return (false);
			}
		}else{
			if(frm.sstate2.value==""){
				alert("If you set the shipping address, please complete all shipping details.\n\nPlease enter a value in the field \"County / Province\".");
				frm.sstate2.focus();
				return (false);
			}
		}
		if(frm.szip.value==""){
			alert("If you set the shipping address, please complete all shipping details.\n\nPlease enter a value in the field \"Postcode / Zip\".");
			frm.szip.focus();
			return (false);
		}
	}
	
	if(frm.terms.checked==false){
		alert("Please confirm that you have read our \"Terms & Conditions\".");
		return (false);
	}
	
	if(frm.remember.checked==false){
		if(confirm("Do you want us to remember your customer details for the next time you visit?\n\nOk=Yes, Cancel=No.")){
			frm.remember.checked=true
		}
	}
	return (true);
	});
	
	/* Checkout form overrule */
	$(".checkout2").click(
		function()
		{
			//$("#formGotoCheckout").submit();
		}
	);

	$('.checkoutBox .item a').click(
	   function()
		{
			$('.checkoutBox .item').toggleClass('open'); 
			$('.checkoutBox .basket').slideToggle();
			return false;
		} 
	  );
	$('.close a').click(
	   function() 
		{ 
			$('.checkoutBox .item').removeClass('open');  
			$('.checkoutBox .basket').slideToggle();
			return false;
		} 
	  );
	
		
		
		var config = {    
			 sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)    
			 interval: 200, // number = milliseconds for onMouseOver polling interval    
			 over: function(e) {
			$(this).children('ul').hoverFlow(e.type, 
			{
			  'width': 'show',
			  'height': 'show',
			  'opacity': 'show'
			})}, // function = onMouseOver callback (REQUIRED)    
			 timeout: 200, // number = milliseconds delay before onMouseOut    
			 out: function(e) {
			$(this).children('ul').hoverFlow(e.type, {
			  'width': 'hide',
			  'height': 'hide',
			  'opacity': 'hide'
			})} // function = onMouseOut callback (REQUIRED)    
		};
		
		$('#mainMenu > li').hoverIntent( config );
		
		$("#mainMenu ul a").mouseover(
		function () {
				$('span', this).stop().animate({opacity: 1}, {queue: false, duration: 500});
		}).mouseout(
		function () {
				$('span', this).stop().animate({opacity: 0}, {queue: false, duration: 500});
		});
		
		$('#mainMenu > li').hover(
		   function() 
			{ 
				$('> a', this).addClass('active_m'); 
				
			} 
		  ,
		  function() 
		
			{ 
		
				$('> a', this).removeClass('active_m'); 
		
			}
  );
  
  	// load basket on document ready
	loadBasket();
	
 });
