var	TimerId = "";
var loadUrl = "/cgi-bin/generic.cgi";  
var Url = "/";  
var theid = "";
var thefullid = "";
var error = "";
if (sessvars.username) { thefullid = sessvars.username; }
var cartenter = "";
var responseText = "";
var now = new Date();
var buildit = "";
var continueit = "";
var cartenter = ""
var cartopen = "";
var id = [];
var subid = [];
var thissiteID = "16";

$(document).ready(function() {
// Check to see if the session ID is blank, if so get a new one.

		theid = $('#cookie').val();

// If there are no cookies active use sessvars

		if (theid == "") {
			id = thefullid.split("|");
			for (i=0; i<id.length; i++) {
				subid = id[i].split("-");
					if (subid[0] == thissiteID) {
						theid = subid[1];		
				}	
			}
		}

// Put in to make the text black again!>
	if (theid == "") {
		  $.get(loadUrl, {action: "getcartID", nothing: now},  
             function(responseText){
				sessvars.username = thefullid + "|" + responseText;
				subid = responseText.split("-");
				theid = subid[1];
             },  
             "html"  
         );           
	}

	// Check to see if there is a orderreference for this order
		if ($('#orderreference').length > 0) {
			if ($('#orderreference').val() != theid) {
			theid = $('#orderreference').val();
			}
		}

		$('#cartID').val(theid);

		$(".individual_buy_container").click(function(){
			if ($('.individual_buy_options').html() != "options") {
				$('.individual_buy_options_text').hide();
				addtocart($(".individual_buy_ID").html());
			}
			else {
				$('.individual_buy_options_text').show();
			}
		});
	
		$(".individual_offer_container").click(function(){
				addtocart($(".individual_offer_ID").html());
		});


		$(".continueshopping_button").mousedown(function(){ $('.continueshopping_button').addClass('continueshopping_button_down'); });

		$(".continueshopping_button").mouseup(function(){ $('.continueshopping_button').removeClass('continueshopping_button_down'); });

		$(".checkout_button").mousedown(function(){ $('.checkout_button').addClass('checkout_button_down'); });

		$(".checkout_button").mouseup(function(){ $('.checkout_button').removeClass('checkout_button_down');});

		$(".login_button_container").click(function(){
			$('.login_form').submit();
			$("#login_form #cartID").val(theid);
		});

		$(".checkout_formbutton").click(function(){
			$('#' + $(this).children('div').attr('class')).submit();
		});

		$(".checkout_button_container").click(function(){
			$("#sub_action").val($(this).attr("id"));
				if ($(this).attr("id") == "checkout_delivery") {
					checkout_check(); 
				}
				else {
					continueit = "true";
				}
			if (continueit == "true") {
				$("#checkout_form #cartID").val(theid);
				$("#checkout_form").submit();
			}
		});

		var menu_selected = $('.menuitem_selected').html();
		$('#menu_navigation_list li a').each(function(){
			if($(this).html() == menu_selected) {
				$(this).parent().addClass('menu_selected');
			}
		});

		$(".update_button_container").click(function(){
			validate_update();
		});


		$(".payment_button_container").click(function(){
			$('#SecureTradingForm').submit();
		});

		$('.hide').hide();

			resize('mainimage', '500', '150');

		$('#showmenu').hide();

		$('#sort_response_loading').hide();

		$(".input_text :input").focus(function(){
				$(this).removeClass('input_error')
		});

		$("#checkout_same").click(function(){
			if ($("#checkout_same").is(':checked') == true) {
				checkout_same();
			}
		});

		$(".barlowtyrie_mainpage_chooser").click(function() {
			window.location = Url + "/" + $(this).attr('id')
		});

		$(".left_menu_list li").mouseover(function() {
			$(this).addClass('left_menu_list_hover');		
		});
		$(".left_menu_list li").mouseout(function() {
			$(this).removeClass('left_menu_list_hover');		
		});

		$(".barlowtyrie_mainpage_chooser_image").mouseover(function() {
			$(this).addClass('barlowtyrie_mainpage_chooser_image_hover');		
			$(this).children('div').show();
		});
		$(".barlowtyrie_mainpage_chooser_image").mouseout(function() {
			$(this).removeClass('barlowtyrie_mainpage_chooser_image_hover');		
			$(this).children('div').hide();
		});

		$('.spares_highlight tr td').click(function() {
			if ($('.sparerow-' + $(this).attr('id')).attr('checked') == true) {
				$('.sparerow-' + $(this).attr('id')).attr('checked',false);
			}
			else {
				$('.sparerow-' + $(this).attr('id')).attr('checked',true);
			}
		});

		$(".crumb li").hover(
		  function () {
		    $(this).addClass('crumb_hover');
		  }, 
		  function () {
		    $(this).removeClass('crumb_hover');
		  }
		);

		$(".home_chooser").click(function() {
			window.location = Url + $(this).attr('id');
		});

		$("#header_cart").click(function(){
			if (cartopen != "true") {
				viewcart();
			}	
			else if (cartopen == "true") {
				cartenter = "";
				closecart();
			}
		});


		$("#cart_contents").mouseenter(function() {
			if (cartenter != "closing" || cartopen != "false") {
				cartenter = "true";
			}
		});


		$("#cart_contents").mouseleave(function() {
			if (cartopen == "true") {
				cartenter = "";
				closecart();
			}
		});



		$('.checkoutit').attr('href',$('.checkoutit').attr('href') + theid); 

		// Fade in lifestyle image
			$('#lifestyle_main_image').fadeIn(2000);
			$('.lifestyle_smallimages').fadeIn(1000);


// Get what is in the cart, if anything.

  $.get(loadUrl, {action: "cart", cartid: theid, nothing: now},  
             function(responseText){  
                 $("#cart_contents").html(responseText);
             },  
             "html"  
         );           

});


function get_buildproducts(cat, type) {
  $.get(loadUrl, {action: "build", cat: cat, type: type, nothing: now},  
             function(responseText){  
                 $("#maincarousel").html(responseText);
             },  
             "html"  
         );           
}



function viewcart() {
	cartenter = "";

	 $('#cart_contents').animate({
	  "height": "toggle", "opacity": "toggle"
	 }, 2000, function() { cartopen = "true";});

}

function closecart() {

	if (cartenter != "true" && cartopen == "true") {

		cartenter = "closing";
		cartopen = "";

		 $('#cart_contents').animate({
			  "height": "toggle", "opacity": "toggle"
		 }, 1000, function() { $('.cart_information_container').hide(); cartopen = "false";});


	}
}

function changeimage(val) {
	$('#lifestyle_main_image').attr('src', val);
}


function addtocart(prodid) {
// See if there are any suggest items ticked
var suggest = "";
$('.suggest_wrapper input:checked').each(function() {
	suggest = suggest + "|" + $(this).attr('id');
});

// See if there are any quickshopids
var quickshop = "";
$('.quickshop_response_wrapper input').each(function() {
	quickshop = quickshop + "|" + $(this).val();
});


var qty = 1;
	qty = $(".quantity").val();
	if (qty) {} else {qty = 1; }

if($("#amount").val()) {
	qty = $("#amount").val();
}
       $.get(  
             loadUrl,  
             {action: "cart", prod: prodid, qty: qty, suggest: suggest, quickshop: quickshop, cartid: theid, nothing: now},  
             function(responseText){  
                 $("#cart_contents").html(responseText);
					window.scrollTo(0,0)
					clearTimeout(TimerId);
					TimerId = setTimeout("closecart()", 5000);
					$('.cart_information_container').show();
					if (cartopen != "true") {viewcart();}
             },  
             "html"  
         );       

}

function update_cart(prodid, type) {
var qty = $('#' + prodid + '_quantity').val();
qty = qty * 1;
if (type == "add") { qty = qty + 1; }
if (type == "minus") { qty = qty - 1; }
       $.get(  
             loadUrl,  
             {action: "ajax_view_cart", cartid: theid, product_ID: prodid, quantity: qty, nothing: now},  
             function(responseText){  
                 $("#view_cart_wrapper").html(responseText);

             },  
             "html"  
         );       

  	   $.get(
			loadUrl, {action: "cart", cartid: theid, qty:qty, nothing: now},  
		             function(response){  
		                 $("#cart_contents").html(response);
		             },  
		             "html"  
		     );           

}


function clearit() {
	clearTimeout(TimerId);
}

function get_product(prodid) {
       $.get(  
             loadUrl,  
             {action: "ajax_product", product_ID: prodid, nothing: now},  
             function(responseText){  
                 $("#product_content").html(responseText);
             },  
             "html"  
         );       
}

function remove(prodid) {
	prodid = "|" + prodid;
	buildit.replace(prodid,"");
	buildit="";
	build();
}

function build(prodid) {
if (prodid) {
buildit = buildit + "|" + prodid;
}
 $("#myset").show();
       $.get(  
             loadUrl,  
             {action: "add_build", product_ID: buildit, nothing: now},  
             function(responseText){  
                 $("#myset").html(responseText);
             },  
             "html"  
         );       
}

function show(div) {
  $('#' + div).toggle();
}

function showslow(div) {
  $('#' + div).animate({
		  "height": "toggle", "opacity": "toggle"
	 }, 500);
}

function selecttab(tab) {
  $('.product_information_tabs ul li').each(function(){
	$(this).removeClass("selected");
  });

	$('#' + tab).addClass("selected");
}


function hideit(theclass) {
  $('.' + theclass).hide();
}

function resize(name, mw, mh) {

    var maxWidth = mw; // Max width for the image
    var maxHeight = mh;    // Max height for the image
    var ratio = 0;  // Used for aspect ratio
    var width = $('.'+ name).width();    // Current image width
    var height = $('.'+ name).height();  // Current image height

	if (mw > 0) {
    // Check if the current width is larger than the max
    if(width > maxWidth){
        ratio = maxWidth / width;   // get ratio for scaling image
        $('.'+ name).css("width", maxWidth); // Set new width
        $('.'+ name).css("height", height * ratio);  // Scale height based on ratio
        height = height * ratio;    // Reset height to match scaled image
    }
	}
	if (mh > 0) {
    // Check if current height is larger than max
    if(height > maxHeight){
        ratio = maxHeight / height; // get ratio for scaling image
        $('.'+ name).css("height", maxHeight);   // Set new height
        $('.'+ name).css("width", width * ratio);    // Scale width based on ratio
        width = width * ratio;    // Reset width to match scaled image
    }
	}
}


/* MENU FUNCTIONS
=================== */

var	MenuTimerId = "";

function ShowMenu(val) {
$('div[id^=Menu]').hide();
val = "Menus_" + val;
$('#showmenu').show();

$('#' + val).animate({
		  "height": "toggle", "opacity": "toggle"
	 }, 500);

		clearTimeout(MenuTimerId);

	$('.' + val).mouseleave(function(){
		MenuTimerId = setTimeout("CloseMenu()", 2000);
	});

	$('#' + val).mouseenter(function(){
		clearTimeout(MenuTimerId);
		MenuTimerId = "";	
	});

	$('#' + val).mouseleave(function(){
		MenuTimerId = setTimeout("CloseMenu()", 100);

	});

}

function CloseMenu() {
$('div[id^=Menu]').animate({
		  "height": "hide", "opacity": "toggle"
	 }, 500);

		clearTimeout(MenuTimerId);
		MenuTimerId = "";	
$('#showmenu').hide();
}


function sortit(criteria) {

				$('#sort_response_loading').show();
				$('#sort_response').hide();

       $.get(  
             loadUrl,  
             {action: "sortit", criteria: criteria, catID: $('#catID').val(), nothing: now},  
             function(responseText){  
				$('#sort_response').html(responseText);
             },  
             "html"  
         );       
				$('#sort_response').show();
				$('#sort_response_loading').hide();

}

function checkout_check() {
error = "";
	$('.input_text :input').each(function(i){
		if ($(this).attr('id') == "b_cname") {}
		else if ($(this).attr('id') == "s_cname") {}
		else{
  		if ($(this).val() == "") {
			$(this).addClass('input_error');
			error = "true";
		}
		else {
			$(this).removeClass('input_error');
		}
		}
});

if (error != "true") { 
continueit = "true" 
}

}

function checkout_same() {
$('input[name=s_title]').val($('input[name=b_title]').val());
$('input[name=s_firstname]').val($('input[name=b_firstname]').val());
$('input[name=s_lastname]').val($('input[name=b_lastname]').val());
$('input[name=s_address]').val($('input[name=b_address]').val());
$('input[name=s_town]').val($('input[name=b_town]').val());
$('input[name=s_county]').val($('input[name=b_county]').val());
$('select[name=s_country]').val($('input[name=b_country]').val());
$('input[name=s_postcode]').val($('input[name=b_postcode]').val());
$('input[name=s_telephone]').val($('input[name=b_telephone]').val());
$('input[name=s_email]').val($('input[name=b_email]').val());
$('input[name=s_cname]').val($('input[name=b_cname]').val());
}


function address_find(type) {

if ($('#' + type).val()) {
	$('.' + type + '_loader').show();
	$('#' + type + '_checkout_find').hide();

       $.get(  
             loadUrl,  
             {action: "checkout", sub_action: "check_post", type: type, postcode: $('#' + type).val(), cartID: theid, nothing: now},  
             function(responseText){  
				if (type == "b_postcode") {
					$('#b_address_find').html(responseText);
				}
				if (type == "s_postcode") {
					$('#s_address_find').html(responseText);
				}

				$('.' + type + '_loader').hide();
	
             },  
             "html"  
         );       

}


}

function address_select(type, id) {
if ($('#' + type).val()) {
		if (type == "b_postcode") {
			$('#b_address_find').html('');
		}
		if (type == "s_postcode") {
			$('#s_address_find').html('');
		}

$('#s_address_find').html('');

$('.' + type + '_loader').show();

       $.get(  
             loadUrl,  
             {action: "checkout", sub_action: "get_address", id: id, cartID: theid, postcode: $('#' + type).val(), nothing: now},  
             function(responseText){
				var response = responseText.split('\|');
					if (type == "b_postcode") {
						$('#b_cname').val(response[0]);
						$('#b_address').val(response[1]);
						$('#b_town').val(response[2]);
						$('#b_county').val(response[3]);
						$('#b_address_find').html('');
					}
					if (type == "s_postcode") {
						$('#s_cname').val(response[0]);
						$('#s_address').val(response[1]);
						$('#s_town').val(response[2]);
						$('#s_county').val(response[3]);
						$('#s_address_find').html('');
					}
				$('.' + type + '_loader').hide();
				$('#' + type + '_checkout_find').show();

             },  
             "html"  
         );       

}


}

function validate() {
	if ($('#shoppercode').val()) {

if ($('#checkcart').val()) {
	if ($('#checkcart').val() != "") {
		theid = $('#checkcart').val();
	}
}

	$('.validate_loader').show();
       $.get(  
             loadUrl,  
             {action: "checkout", sub_action: "shoppercode", shoppercode: $('#shoppercode').val(), cartID: theid, nothing: now},  
             function(responseText){  
				$('#validate_response').html(responseText);
				$('.validate_loader').hide();
             },  
             "html"  
         );       

	}
}

function validate_update() {
       $.get(  
             loadUrl,  
             {action: "checkout", sub_action: "shoppercode", update: "true", delcharges: $('#delcharges').val(), amount: $('#amount').val(), cartID: theid, nothing: now},  
             function(responseText){ 
				$('#validate_response').html(responseText);
				$('.validate_loader').hide();
	
			  	   $.get(
						loadUrl, {action: "checkout_view_cart", cartID: theid, nothing: now},  
				             function(response){
				                 $("#cart").html(response);
				             },  
				             "html"  
				     );           

             },  
             "html"  
         );       



}

	var geocoder, location1, location2, gDir;

	function initialize() {
		geocoder = new GClientGeocoder();
		gDir = new GDirections();
		GEvent.addListener(gDir, "load", function() {
			var drivingDistanceMiles = gDir.getDistance().meters / 1609.344;
			var drivingDistanceKilometers = gDir.getDistance().meters / 1000;
			drivingDistanceMiles = drivingDistanceMiles * 1.75 * 1.175;
			var courier = drivingDistanceMiles.toFixed(2);
			document.getElementById('results').innerHTML = 'Same Day Cost: £' + courier;
		});
	}

	function showLocation(p1, p2) {
		geocoder.getLocations(p1, function (response) {
			if (!response || response.Status.code != 200)
			{
				alert("Sorry, we were unable to geocode the first address");
			}
			else
			{
				location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
				geocoder.getLocations(p2, function (response) {
					if (!response || response.Status.code != 200)
					{
						alert("Sorry, we were unable to geocode the second address");
					}
					else
					{
						location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
						gDir.load('from: ' + location1.address + ' to: ' + location2.address);
					}
				});
			}
		});
	}


function quickshop() {
var val = $('#quickshop_productID').val();
if (val == "") {
exit;
}
var holdresponse = $('#response').html();
$('#response_error').hide();
       $.get(  
             loadUrl,  
             {action: "quickshop", sub_action: "getproduct", productID: val, nothing: now},  
             function(responseText){  
				if (responseText == "") {
					$('#response_error').show();
					$('#response_error').html('No Product Code found');
				}
				else {
					$('#response').html(holdresponse + responseText);
					$('.individual_buy_container').show();
					$('#quickshop_productID').val('');
					$('#quickshop_productID').focus();
				}
             },  
             "html"  
         );       

}

function change_courier(id) {
var delval = $('#' + id + ' .option_delivery_price').html();
       $.get(  
             loadUrl,  
             {action: "checkout", sub_action: "changecourier", cartID: theid, name: id, delval: delval, nothing: now},  
             function(responseText){  
					$('.responsetext').html(responseText);

				$('.delivery_options_wrapper li').each(function() {
					$(this).removeClass('del_selected');
				});

				$('#' + id).addClass('del_selected');

             },  
             "html"  
         );       

}
