$().ready(function() {
	$(".basket_qty").click(function() {
		$(this).parent().children('input[type=text]').val()
		var $button = $(this).children('img');
		var oldValue = $button.parent().parent().find("input[type=text]").val();
		if ($button.attr("alt") == "add") {
			var newVal = parseFloat(oldValue) + 1;
		} else {
			if (oldValue >= 1) {
				var newVal = parseFloat(oldValue) - 1;
			};
		};
		$button.parent().parent().find("input[type=text]").val(newVal);
	});
	$(".basket_update").click(function() {
		$(this).parent().parent().find('form').trigger("submit");
	});
	$("#coupon-input").click(function() {
		if ($("#coupon-input").val()=="ENTER CODE") {
			$("#coupon-input").val("");
		};
	});
	$("#voucher-input").click(function() {
		if ($("#voucher-input").val()=="ENTER REF.") {
			$("#voucher-input").val("");
		};
	});
	$('.lightboxphoto, .lightboxphoto2').lightBox({});
	$(".compgallery a").lightBox();
	// validate the comment/checkout forms when submitted, ensure includes both names for billing
	jQuery.validator.addMethod("hasspace", function(value, params,message) {
		return $(params).val().indexOf(" ") > 1 && $(params).val().indexOf(" ")<$(params).val().length-1;
	}, "You must enter both your firstname and surname (with a space between)");
	jQuery.validator.addMethod("ispostcode",
		function(value, element) {
			var rx = new RegExp("^([a-zA-Z]){1}([0-9][0-9]|[0-9]|[a-zA-Z][0-9][a-zA-Z]|[a-zA-Z][0-9][0-9]|[a-zA-Z][0-9]|[0-9][a-zA-Z]){1}([        ])([0-9][a-zA-z][a-zA-z]){1}$");
			return this.optional(element) || rx.test(value);
		},
        "Please enter a valid postcode e.g. CO5 8NA."
	); 
	$("#customerform").validate({
		rules:{
			CustomerName:{hasspace:"#CustomerName"},
			BillingPostCode:{ispostcode:"#BillingPostCode"},
			DeliveryPostCode:{ispostcode:"#DeliveryPostCode"}
		}
	});
	$("#form-right input#altdelivery").change(function() {
		if ($("#form-right input#altdelivery").prop("checked")==true) {
			$("#form-right div label, #form-right div dd, #form-right div.jqTransformSelectWrapper div").css("color","#000000");
			$("#form-right input[type=text], #form-right select").prop("disabled","");
		} else {
			$("#form-right div label, #form-right div dd, #form-right div.jqTransformSelectWrapper div").css("color","#aaaaaa");
			$("#form-right input[type=text], #form-right select").prop("disabled","disabled");
		};
	});

	// validate the feedback form when it is submitted
	$("#feedbackform form, #contactform, #whatpeoplesayform form, #contact_right form, #newsletterform").validate();

	$("#newsletter").click(function() {
		if ($("#newsletter").attr("checked")=="") {
			$("#newslettershare").attr("checked","");
		};
	});

	$("#competitionform").submit(function() {
		if ($("#competitionform form #name").val()=="" ||$("#competitionform form #email").val()=="") {
			alert("You have not completed your name or email address");
			return false;
		};
		if ($("#competitionform form #useie").length==0) {	//firefox etc
			if ($("#competitionform form #photo").val().substr($("#competitionform form #photo").val().length-3).toLowerCase()!=="jpg") {
				alert("You must select a valid JPG file");
				return false;
			};
		} else {	//IE
			if ($("#competitionform form #photo_ie").val().substr($("#competitionform form #photo_ie").val().length-3).toLowerCase()!=="jpg") {
				alert("You must select a valid JPG file");
				return false;
			};
		};
	});
	$("#competitionform #photo").change(function() {
		$("#fakefile").val($("#photo").val());
	});
	$("#product_delivery_popup_launch").click(function(){
		$("#product_delivery_popup").dialog('open');
		return false;
	});
	if ($('#product_delivery_popup').length > 0) {
		$('#product_delivery_popup').dialog({
			autoOpen: false,
			width: 450,
			height: 400,
			draggable: true,
			modal: true,
			close: function(event, ui) {
				$("#qtyselect").show()
			},
			open: function(event, ui) {
				$("#qtyselect").hide(); //for IE6 when delivery_popup is in use
			}
		});
	};
	var ua = $.browser;
	if ( !(ua.msie && ua.version.slice(0,1) == "6")) {
		//addthis facebook causes JS error on IE6
		$(".addthis_toolbox").prepend('<a class="addthis_button_facebook_like" fb:like:layout="button_count"></a>');
	};
	if ($('#giftwrap_popup').length > 0) {
		//basket gift wrap dialog
		$('#giftwrap_popup').dialog({
			autoOpen: false,
			width: 400,
			draggable: true,
			modal: true,
			buttons: {
				"Add Giftwrap": function() { 
					$("#giftwrap_form").submit();
					$(this).dialog("close"); 
				},
				"Cancel": function() { 
					$(this).dialog("close"); 
				}
			}
		});
		$('.giftwrap_launch').click(function(){
			$('#giftwrap_itemno').val($(this).parent().parent().find("input.itemno").val());
			$('#giftwrap_popup').dialog('open');
			return false;
		});
	};
	$(".giftwrap_message").keyup(function() {
		if ($(".giftwrap_message").val().length>250) {
			$(".giftwrap_message").val($(".giftwrap_message").val().substring(0,250));
			alert("Sorry, only 250 characters are permitted");
		};
	});
	$("#video-right a").click(function() {
		_gaq.push(['_trackEvent', 'Videos', 'Play', 'Play home video', 1]);
		embedhomevideo();
		return false;
	});
	$("#prod_video a").click(function() {
		_gaq.push(['_trackEvent', 'Videos', 'Play', 'Play product video', 1]);
		embedprodvideo();
		return false;
	});

	$("#newsletter-signup-email").focus(function() {
		if($(this).val()=='Enter your E-mail Address...') {
			$(this).val('');
		};
	});
	$("#newsletter-signup-email").blur(function() {
		if($(this).val()=='') {
			$(this).val('Enter your E-mail Address...');
		};
	});


	$(".toggle_container").hide();
	$("#cat_sortby select").change(function() {
		$("#cat_sortby").submit();
	});
 
	var config = {    
		 sensitivity: 1, // number = sensitivity threshold (must be 1 or higher)    
		 interval: 0, // number = milliseconds for onMouseOver polling interval    
		 over: megaHoverOver, // function = onMouseOver callback (REQUIRED)    
		 timeout: 0, // number = milliseconds delay before onMouseOut    
		 out: megaHoverOut // function = onMouseOut callback (REQUIRED)    
	};
 
	$("ul#topnav li .sub").css({'opacity':'0'});
	$("ul#topnav li").hoverIntent(config);
	$("ul#topnav li a").click(function() {
		$(this).parent().children("div.sub").hide();
	});
	if($('#banner').length>0) {
// Uncomment next line at end of 2012 Sale
		$('#banner').s3Slider({
			timeOut: 4000
		});
	};
    $("form.jqtransform, select.jqtransform").jqTransform();
	$("#associated_products div.jqTransformSelectWrapper ul li a").click(function(){   //associated products drop-down jqtransform handler	
		var value= $("#associated_products div.jqTransformSelectWrapper span").text()
		$.getJSON('../../json_handler.php?type=associatedproduct&value='+encodeURIComponent(value)+"&mainprod="+encodeURIComponent($("#prodid").val()), function(data) {
			if (data.length>0) {
				window.location.href=data;
			}
		});
		return false;
	});
	$(".prodthumbs").hover(function() {
		$("#main-product-image").attr("src",$(this).children("img").attr("src").replace("tiny","lge"));
		$("#main-product-image").parent("a").attr("href",$(this).children("img").attr("src").replace("tiny","lge"));
	});
	$("#prod-details-qty").hide();
	$('#form-basket').submit(function(){	//product pg. add to basket
		$("#minilink").animate({opacity: 0.25},10);//grey out to show we're updating and show spinner
		$("#basketspan").css("background-image",'url("../../images/ajax_spinner.gif")');
		if (typeof(disablehandler)=='undefined') {
			$.ajax({url:'../../json_handler.php?type=basket_add&prod='+$("#prodid").val()+"&option="+$("#option1").val()+"&qty="+$("#qtyselect").val()+"&rand="+Math.floor(Math.random()*10001), timeout: 5000, success: function(data) {
				if (data=='Error') {
					alert("We could not add the item to your basket, it may be out of stock, please call 0845 258 7532 for information");
					$("#basketspan").css("background-image",'none');
					$("#minilink").animate({opacity: 1},1000);//bring back into focus
				} else {
					$("#product-added-to-basket").css("display","block");
					$("#product-added-to-basket").effect("highlight",{color:"#009933"},1750);

					$("#minilink").html(data);
					$("#minilink").animate({opacity: 1},1000);//bring back into focus
				};
			},error: function(data) {
				disablehandler=true;
				$("#form-basket").submit();
			}});
		} else {
			return true;
		};
		//animate adding item to basket
		img = $("#main-product-image").clone();
		img_offset = $("#main-product-image").offset();
		bskt_offset = $("#minilink").offset();
		img.css("position", "absolute");
		img.css('left', img_offset.left + 'px');
		img.css('top', img_offset.top + 'px');
		img.css('width', (($("#main-product-image").attr("width")*1)/2)+ 'px');
		img.css('height', (($("#main-product-image").attr("height")*1)/2)+ 'px');
		$('body').append(img);
		img.animate({left: bskt_offset.left, top: bskt_offset.top, opacity: 1}, 'normal', 'swing', function(){ $(this).remove() });
		return false;
	});
	$("#product-secondary-sidebar2 .alsolike .prod_related_buy").click(function() {
		href=$(this).attr("href");
		prodid=href.substring(href.lastIndexOf("?id=")+4);
		$("#minilink").animate({opacity: 0.25},10);//grey out to show we're updating and show spinner
		$("#basketspan").css("background-image",'url("../../images/ajax_spinner.gif")');
		$.ajax({url:'../../json_handler.php?type=basket_add&prod='+prodid+"&option=0&qty=1&rand="+Math.floor(Math.random()*10001), timeout:5000, success: function(data) {
			$("#minilink").html(data);
			$("#minilink").animate({opacity: 1},1000);//bring back into focus
		},error: function(data) {
			//the ajax timed out for some reason so fall back to original link
			window.location.href=$("#product-secondary-sidebar2 .alsolike .prod_related_buy").attr("href");
		}});
		//animate adding item to basket
		img = $(this).parent().parent().parent().children("a").children("img").clone();
		img_offset = $(this).parent().parent().parent().children("a").children("img").offset();
		bskt_offset = $("#minilink").offset();
		img.css("position", "absolute");
		img.css('left', img_offset.left + 'px');
		img.css('top', img_offset.top + 'px');
		img.css('width', (($(this).parent().parent().parent().children("a").children("img").attr("width")*1)/2)+ 'px');
		img.css('height', (($(this).parent().parent().parent().children("a").children("img").attr("height")*1)/2)+ 'px');
		$('body').append(img);
		img.animate({left: bskt_offset.left, top: bskt_offset.top, opacity: 1}, 'normal', 'swing', function(){ $(this).remove() });
		window.location.href="#minibasket";
		return false;
	});
/*	$(".box-details2 form").submit(function() {
		alert($('input[type=radio]:checked',this).val());
		return false;
	});
*/
});

function megaHoverOver(){
	$(this).find(".sub").stop().fadeTo('fast', 1).show();
		
	//Calculate width of all ul's
	(function($) { 
		jQuery.fn.calcSubWidth = function() {
			rowWidth = 0;
			//Calculate row
			$(this).find("ul").each(function() {					
				rowWidth += $(this).width(); 
			});	
		};
		
	})(jQuery); 
	
	if ( $(this).find(".row").length > 0 ) { //If row exists...
		var biggestRow = 0;	
		//Calculate each row
		$(this).find(".row").each(function() {							   
			$(this).calcSubWidth();
			//Find biggest row
			if(rowWidth > biggestRow) {
				biggestRow = rowWidth;
			}
		});
		//Set width
		$(this).find(".sub").css({'width' :biggestRow});
		$(this).find(".row:last").css({'margin':'0'});
		
	} else { //If row does not exist...
		
		$(this).calcSubWidth();
		//Set Width
		$(this).find(".sub").css({'width' : rowWidth});
		
	}
}

function megaHoverOut(){ 
  $(this).find(".sub").stop().fadeTo('fast', 0, function() {
	  $(this).hide(); 
  });
}
