var	TimerId = "";
var TimerMenu = ""
var loadUrl = "/cgi-bin/generic.cgi";  
var Url = "/";  
var theid = "";
var thefullid = "";
var error = "";
var cartenter = "";
var responseText = "";
var now = Math.floor(Math.random()*9999999);
var buildit = "";
var continueit = "";
var cartenter = ""
var cartopen = "";
var allVals = [];
var thissiteID = "21";
var image = "";
var theprodids = "";
var thisid = "";
var cartloading = "";
var testresults = "";

$(document).ready(function() {

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

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

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

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

		$(".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();
			}
		});


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


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

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

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

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

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

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

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


		$("#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();
			}
		});


	   var mainheight = 250;
	   var height = $(".mainimage").height()
		if (height != "0") {
		var ratio = height / mainheight;
		height = mainheight + "px";
		var width = $(".mainimage").width() / ratio + "px";
	    $(".mainimage").css("width",width);
	    $(".mainimage").css("height",height);
	}

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


		// Check and sort options

			if ($(".product_sort_options").length > 0) {
				allVals = [];
			     $('.product_sort_options :checkbox:checked').each(function() {
		    	   allVals = allVals + "|" + $(this).val();
		     	});

			if (allVals) {
				$('#sort_response_loading').show();
				allVals = $('#catname').val() + "-" + allVals;
				sortit(allVals);
			}

			}

			$(".product_sort_options").click(function(){
				allVals = [];
			     $('.product_sort_options :checkbox:checked').each(function() {
		    	   allVals = allVals + "|" + $(this).val();
		     	});


				if (allVals) {
					$('#sort_response_loading').show();
					allVals = $('#catname').val() + "-" + allVals;
					sortit(allVals);
				}

			});

			var elem = $('#megadeal_anchor');
		    if(elem.length > 0) {
	        var target_offset = elem.offset();
	        var target_top = target_offset.top;
	 
	        $('html, body').animate({scrollTop:target_top}, 1000);
		    }


			if ($(".tab_content").length > 0) {
			
				$(".tab_content").hide(); //Hide all content
				$("ul.tabs li:first").addClass("active").show(); //Activate first tab
				$(".tab_content:first").show(); //Show first tab content

				$("ul.tabs li").click(function() {
				$("ul.tabs li").removeClass("active"); //Remove any "active" class
				$(this).addClass("active"); //Add "active" class to selected tab
				var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
				$(".tab_content").hide(); //Hide all tab content
				$(activeTab).fadeIn(); //Fade in the active content
	
				return false;
				});
			}


			$('#header_menu_wrapper').mouseleave(function() {
				TimerMenu = setTimeout("submenu($('#currentmenu').val())", 1000);
			});

			$('#header_menu_wrapper').mouseenter(function() {
					clearTimeout(TimerMenu);
			});

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

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

});



function viewcart() {
	cartenter = "";

	 $('#cart_contents').animate({
	  "height": "toggle", "opacity": "toggle"
	 }, 1000, 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) {
if (cartloading != "") {}
else {
cartloading = "true";
// 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, megaprod: $('#megaprod').val(), quickshop: quickshop, cartid: theid, nothing: now},  
             function(responseText){  
                 $("#cart_contents").html(responseText);
					cartloading = "";
					window.scrollTo(0,0)
					clearTimeout(TimerId);
					$('.cart_information_container').show();
					if (cartopen != "true") {viewcart();}
					TimerId = setTimeout("closecart()", 5000);
             },  
             "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; }
if (type == "remove") { qty = "0"; }

$('#' + prodid + '-price').html($('#loader').html());

       $.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){  
                 $("#Productinfo").html(responseText);
				 $('#Productinfo').modal();
             },  
             "html"  
         );       
}

function get_youtube(url) {
       $.get(  
             loadUrl,  
             {action: "ajax_youtube", url: url, nothing: now},  
             function(responseText){  
                 $("#Productinfo").html(responseText);
				 $('#Productinfo').modal();
             },  
             "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 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
    }
	}
}



function sortit(criteria) {

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

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

}

function checkout_check() {
error = "";
var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i

	$('.input_text :input').each(function(i){
		if ($(this).attr('id') == "b_cname") {}
		else if ($(this).attr('id') == "s_cname") {}
		else{
			if ($(this).attr('id') == "b_postcode") { 
				if ($('#b_country').val() == "Ireland") {$('#b_postcode').val('Nil')} 
				if ($('#s_country').val() == "Ireland") {$('#s_postcode').val('Nil')} 
			}

			if ($('#b_email').val() != $('#b_email_con').val()) { error = "true"; $('#b_email_con').addClass('input_error');}
			if ($(this).attr('id') == "b_email") {
				if (filter.test($('#b_email').val())) {}
				else{error = "true"; $('#b_email').addClass('input_error'); }
			}
			if ($(this).attr('id') == "s_email") {
				if (filter.test($('#s_email').val())) {}
				else{error = "true"; $('#s_email').addClass('input_error'); }
			}

			if (error != "true") {
	  			if ($(this).val() == "") {
					$(this).addClass('input_error');
					error = "true";
				}
				else {
				$(this).removeClass('input_error');
				}
			}
		}
});

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

}

function checkout_same() {
$('#s_title').val($('#b_title').val());
$('#s_firstname').val($('#b_firstname').val());
$('#s_lastname').val($('#b_lastname').val());
$('#s_address').val($('#b_address').val());
$('#s_town').val($('#b_town').val());
$('#s_county').val($('#b_county').val());
$('#s_country').val($('#b_country').val());
$('#s_postcode').val($('#b_postcode').val());
$('#s_telephone').val($('#b_telephone').val());
$('#s_email').val($('#b_email').val());
$('#s_cname').val($('#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()) {
	$('.validate_loader').show();

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

	if ($('#orderreference').length > 0) {
		if ($('#orderreference').val() != theid) {
			theid = $('#orderreference').val();
		}
	}

       $.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: "ajax_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();
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 {
					$('#prodIDs').val($('#prodIDs').val() + "|" + val);
					$('#response').html(holdresponse + responseText);
				}
             },  
             "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"  
         );       

}

// Put in to make the text black >

function megadeal_add(thisid) {

theprodids = $('#megaprod').val();

if (thisid == "start") {
	var idarray=theprodids.split("-");
		for (var i=1; i<idarray.length; i++) {
			// commented out to make the text black>
			if (idarray[i] == "start" || idarray[i] == "remove") {}
			else { $('#' + idarray[i]).hide(); $('#' + idarray[i] + "-1").hide();}
		}	

}
else {
	$('#' + thisid).hide();
	$('#' + thisid + "-1").hide();
}

 $.get(loadUrl, {action: "get_megadeal", prodids: theprodids, addedid: thisid, cartid: theid, nothing: now},  
            function(responseText){  
                $(".main-topimage").html(responseText);
				if (thisid == "start") {}
				else {$('#megaprod').val(theprodids + '-' + thisid);}
             },  
             "html"  
         );           
}

function megadeal_remove(thisid) {

theprodids = $('#megaprod').val();

var mySplitResult = theprodids.split("-");
theprodids = "";
for ( var i=0, len=mySplitResult.length; i<len; ++i ){
if (mySplitResult[i] == thisid) {}
else {theprodids = theprodids + "-" + mySplitResult[i]}
}
theprodids = theprodids.replace(/-/,'');

 $.get(loadUrl, {action: "get_megadeal", prodids: theprodids, cartid: theid, remove: "true", nothing: now},  
            function(responseText){  
                $(".main-topimage").html(responseText);
				$('#megaprod').val(theprodids);
				$('#' + thisid).show();
				$('#' + thisid + "-1").show();
             },  
             "html"  
         );           
}

//>
function submenu(showmenu) {
$('.submenu').hide();
$('.topmenu_selected').hide();
$('#' + showmenu).show();
$('#' + showmenu + '-menu').show();

}


function submitemail(ID,price,email) {
 $.get(loadUrl, {action: "get_pricedrop", id: ID, price: price, email: email, nothing: now},  
            function(responseText){  
                 $("#Productinfo").html(responseText);
				 $('#Productinfo').modal();
				 $('#email').val('');
             },  
             "html"  
         );    

}

