// JavaScript Document

function pausecomp(millis)
{
	var date = new Date();
	var curDate = null;
	do { curDate = new Date(); }
	while(curDate-date < millis);
} 

function Misc ()
{
	
	// Turn requested links in to target _blank's.
	$("a[rel='external']").attr("target", "_blank");
	
	// Basket alternative backgrounds
	$("#basket tbody tr").hover(
		function ()
		{
			$(this).addClass("alternative");
		},
		function ()
		{
			$(this).removeClass("alternative");
		});
	
	// Delivery/Billing address same checkbox.
	$("#del_same").click(
		function ()
		{
		
			var checkstatus = $(this).attr("checked");
			var billing_fields = $("#billingsection .textfield");
			
			$(billing_fields).each(
				function ()
				{
				
					var name = $(this).attr("name");
					var base_name = name.substr(4);
					var del_field = $("#deliverysection .textfield[name='del_"+base_name+"']");
					
					if(checkstatus) {
						
						$(del_field).val($(this).val())
						            .attr("disabled", true);
						$("#deliverysection").animate({"opacity": 0.4}, "fast");
					
					} else {
					
						$(del_field).val("")
						            .attr("disabled", false);
						$("#deliverysection").animate({"opacity": 1}, "fast");
					
					}
				
				});
			
		
		});
	
	// Form validation
	$("form").submit(function() 
		{
								  
			var fields = $(this).find(".mand");
			var invalid_count = 0;
			var formoutput = $(this).find(".formoutput");
			var invalid_email = false;
			var show_invalid_email_warning = true;
			var cmsg = "The highlighted email address you provided does not seem to be correct. Would you like to continue anyway?";
			if($(formoutput).css("display") !== "none") {
				if(formoutput.length > 0) $(formoutput).fadeOut(500);
			}
			for(i=0; i<fields.length; i++) {
				$(fields[i]).removeClass("invalid");
			}
			for(i=0; i<fields.length; i++) {
				switch(fields[i].type) {
					case "select-one":
					case "select-multiple":
						if(fields[i].selectedIndex == 0) {
							$(fields[i]).addClass("invalid");
							invalid_count++;
						}
						break;
					case "text":
					case "textarea":
					case "password":
						if(!fields[i].value) {
							$(fields[i]).addClass("invalid");
							invalid_count++;
						} else {
							var name = $(fields[i]).attr("name");
							if(name.indexOf("email") >= 0) {
								var emailRegxp = /^([\w]+)(.[\w]+)*@([\w]+)(.[\w]{2,4}){1,2}$/;
								if(emailRegxp.test(fields[i].value) == false) {
									invalid_email = true;
									if(show_invalid_email_warning) {
										$(fields[i]).addClass("invalid");
									}
								}
							}
						}
						break;
				}
			}
			if( !invalid_count ) {
				if(invalid_email && show_invalid_email_warning) {
					if(!confirm(cmsg)) { 
						return false;
					}
				}
				return true;
			} else {
				if(formoutput.length > 0) {
					$(formoutput).css("font-size", "0.9em");
					$(formoutput).css("color", "#ff0000");
					$(formoutput).css("font-weight", "bold");
					$(formoutput).text("Please ensure the highlighted fields are complete before proceeding.");
					$(formoutput).fadeIn(500);
				} else {
					alert("Please ensure the highlighted fields are complete before proceeding.");
				}
				return false;
			}
		}
	);
	
}

function Products ()
{
	
	$("#magnifyIntro").show();
	
	/* ~ Magnifier functionality ~ */
	$("#normalImage").mousemove(
		function (e)
		{
			
			$("#magnifyIntro").fadeOut();
			
			if( $("#magnifiedImage").length > 0 ) {
				
				// Drop the alt tag to avoid lag in IE
				$(this).attr("alt", "");
				
				$(this).css("cursor", "crosshair");
				var magnifiedImage = $("#magnifiedImage");
				var magnifiedImageContainer = $(magnifiedImage).parent();
				
				var normalWidth = $(this).width();
				var normalHeight = $(this).height();
				var largeWidth = $(magnifiedImage).width();
				var largeHeight = $(magnifiedImage).height();
				
				// Mouse position on the normal image.
				var mousePosX =  $(this).offset().left - e.pageX;
				var mousePosY =  $(this).offset().top - e.pageY;
				
				// Calculate where the focal point should be on the magnified image.
				var magnifiedPosX = ((mousePosX * (largeWidth / normalWidth)) + ($(magnifiedImageContainer).width()/2));
				var magnifiedPosY = ((mousePosY * (largeHeight / normalHeight)) + ($(magnifiedImageContainer).height()/2));
				
				// Alter the focal point of the magnified image
				$(magnifiedImage).css("left", magnifiedPosX + "px");
				$(magnifiedImage).css("top", magnifiedPosY + "px");
			
			}
			
		});
	
	$("#normalImage").mouseout(
		function ()
		{
		
			$("#magnifyIntro").fadeIn();
		
		});
	
	if($("#thumbsWrap .thumbItem").length == 0) $("#sort_style").attr("disabled", true);
	// Products filter form.
	$("form#filterProducts select").change(
		function ()
		{
			if( $(this).attr("id") == "sort_style" ) {
			
				// Disable the selects so they can't change it while the page is working.
				$(this).parent().children("select").attr("disabled", true);
				
				// Selected style id.
				var style_id = $(this).val();
				
				// Get all the products on the page.
				var products = Array();
				var counter = 0;
				$("#thumbsWrap .thumbItem").each(
					function ()
					{
						products[counter] = $(this).attr("id").substr(1);
						counter++;
					});
				
				if(counter > 0) {
					var products = products.join("|");
					var ajaxResult = $.ajax({
												type: "GET",
												url: "libs/includes/ajax.php",
												data: "action=reorderByStyle&style="+style_id+"&products="+products,
												async: false
											}).responseText;
					ajaxResult = eval("("+ajaxResult+")");
					$.each(ajaxResult, 
						function (i, id)
						{
							$("#p"+id).appendTo("#thumbsWrap");
						});
				}
				
				$(this).parent().children("select").attr("disabled", false);
			
			} else {
				
				// Submit form.
				$(this).parent().submit();
			
			}
			
		});
	
}

function headerRotate ()
{
	$("#headerimages .headerbox").css("display", "none");
	$("#headerimages .headerbox:first").css("display", "block");
	var wait_time = 3500; // miliseconds (1s = 1000ms)
	var currItem = 0;
	var numItems = $("#headerimages .headerbox").length;
	if(numItems > 1) {
		window.setInterval(doRotate, wait_time);
	}
	function doRotate()
	{
		$("#headerimages .headerbox:eq("+currItem+")").fadeOut(2000);
		if(currItem < (numItems-1)) {
			currItem++
		} else {
			currItem = 0;
		}
		$("#headerimages .headerbox:eq("+currItem+")").fadeIn(1000);
	}
}

function testimonialRotate ()
{
	$(".testimonials_img .imagebox").css("display", "none");
	$(".testimonials_img .imagebox:first").css("display", "block");
	var wait_time = 7500; // miliseconds (1s = 1000ms)
	var currItem = 0;
	var numItems = $(".testimonials_img .imagebox").length;
	if(numItems > 1) {
		window.setInterval(doRotate, wait_time);
	}
	function doRotate()
	{
		$(".testimonials_img .imagebox:eq("+currItem+")").fadeOut(2000);
		if(currItem < (numItems-1)) {
			currItem++
		} else {
			currItem = 0;
		}
		$(".testimonials_img .imagebox:eq("+currItem+")").fadeIn(1000);
	}
}

$(document).ready(function(){

	headerRotate();
	testimonialRotate();
	Misc();
	Products();
	
	$(".basket-added").each(
		function ()
		{
			function fadeBasket (el) { $(el).fadeOut("slow"); }
			window.setTimeout(fadeBasket, 3000, $(this));
		});
	
	$(".autoSubmit select").change(
		function ()
		{
			if( $(this).val() !== "" ) $(this).parent(".autoSubmit").submit();
		});

});
