﻿
$(function(){

	
	//#region variation drop down
    var variations = [];
    var lastPrice = 0;
    var priceVaries = false;
    $('#tblPrices tr.Row, #tblPrices tr.AltRow').each(function(i,tableRow){
        variation  = {
            Id:parseInt(tableRow.cells[0].title),
            Description:$("h4",tableRow.cells[0]).text().replace(/^\s+|\s+$/g, ''),
            PriceText:$(tableRow.cells[1]).html().replace(/^\s+|\s+$/g, ''),
            Price:parseFloat(tableRow.cells[1].title),
            Quantity:1
        };
        variations.push(variation);
        if(variation.Price!=lastPrice && lastPrice!=0)
        {
            priceVaries = true;
        }
        lastPrice = variation.Price;
    });
    if(!priceVaries && variations.length > 1)
    {
        $('#tblPrices tr.Row, #tblPrices tr.AltRow').remove();
        $('#tblPrices tr:first').after('<tr class="Row"><td><select id="jsVariations"></select></td><td title="'+variations[0].Price+'" class="Cost">'+variations[0].PriceText+'</td><td><input class="QuantityField" type="text" id="jsQuantity" maxlength="10" value="1"/></td></tr>');
        select = $('#jsVariations')[0];
        
        for(var x=0;x<variations.length;x++)
        {
            option = document.createElement("option");
            option.value = variations[x].Id;
            option.text = variations[x].Description;
            select.appendChild(option);
        }
        /*
        VariationSelected(select);
        $('#jsVariations').bind('change',VariationSelected);
        $(row.cells[2],'input').bind('change',UpdateTotal);
        $(row.cells[2],'input').bind('keyup',UpdateTotal);
        */
    }
    
    if(variations.length==1)
    {
        $("#tblPrices .QuantityField").val(1);
    }
    
    /*
    function VariationSelected(event)
    {
        var select;
        if(typeof(event.currentTarget)!='undefined')
            select = event.currentTarget;
        else
            select = event;
        
        row = $('.ProductSelection table tr:eq(1)')[0];
        row.cells[1].innerHTML = variations[select.selectedIndex].PriceText;
        row.cells[2].firstChild.value = variations[select.selectedIndex].Quantity;
        total = variations[select.selectedIndex].Quantity * variations[select.selectedIndex].Price;
        UpdateTotal();
    }
	*/
	
    $("#tblPrices .QuantityField").bind('change',UpdateTotal).bind('keyup',UpdateTotal);
    function UpdateTotal()
    {
        var total=0;
        $("#tblPrices .QuantityField").each(function(i,ele){
            quant = $(ele);
            if(parseInt(quant.val()) == quant.val())
            {
                total += quant.val() * parseFloat($('.Cost',quant.parent().parent()).attr("title"));
            }
        });
        $('#itemsTotal').text("£"+total.toFixed(2));
    }
    UpdateTotal();
	//#endregion variations
	
	//#region mega hover
		//On Hover Over
		function megaHoverOver(){
			
			$(this).find(".sub").stop().fadeTo('fast', 1).show(); //Find sub and fade it in
			(function($) {
				//Function to calculate total width of all ul's
				jQuery.fn.calcSubWidth = function() {
					rowWidth = 0;
					//Calculate row
					$(this).find("ul").each(function() { //for each ul...
						rowWidth += $(this).width(); //Add each ul's width together
					});
				
				};
			})(jQuery); 

			if ( $(this).find(".row").length > 0 ) { //If row exists...

				var biggestRow = 0;	

				$(this).find(".row").each(function() {	//for each row...
					$(this).calcSubWidth(); //Call function to calculate width of all ul's
					//Find biggest row
					if(rowWidth > biggestRow) {
						biggestRow = rowWidth;
					}
				});

				$(this).find(".sub").css({'width' :biggestRow}); //Set width
				$(this).find(".row:last").css({'margin':'0'});  //Kill last row's margin

			} else { //If row does not exist...

				$(this).calcSubWidth();  //Call function to calculate width of all ul's
				$(this).find(".sub").css({'width' : rowWidth}); //Set Width

			}
		}
		//On Hover Out
		function megaHoverOut(){
		  $(this).find(".sub").stop().hide();
		  
		  /*.fadeTo('fast', 0, function() { //Fade to 0 opactiy
			  $(this).hide();  //after fading, hide it
		  });*/
		}
		
		//Set custom configurations
		var config = {
			 sensitivity: 10, // number = sensitivity threshold (must be 1 or higher)
			 interval: 10, // number = milliseconds for onMouseOver polling interval
			 over: megaHoverOver, // function = onMouseOver callback (REQUIRED)
			 timeout: 5, // number = milliseconds delay before onMouseOut
			 out: megaHoverOut // function = onMouseOut callback (REQUIRED)
		};

        //try{
		$(".moduleType_Ecommerce_Navigation ul li .sub").css({'opacity':'0'}); //Fade sub nav to 0 opacity on default
		$(".moduleType_Ecommerce_Navigation ul li").hoverIntent(config); //Trigger Hover intent with custom configurations
		//}catch(ex){}
		
	//#endregion mega hover
	
	//#region image gallery
	    
	    $('.MainPhotos ul li a').click(function(){
			aryImage = this.firstChild.data.split("|");
	        $('.MainPhotoImg')[0].src = aryImage[0];
			window.ImageZoomAddress = aryImage[1];
	        return false;
	    });
		
		if($('.MainPhotos')[0]!=undefined)
		{
			aryImage = $('.MainPhotos')[0].firstChild.data.split("|");
			window.ImageZoomAddress = aryImage[1];
			window.ImageHistoryAddress = aryImage[2];
		}
	    
	//#endregion image gallery
    
	//#region watermarks
		
		/*
		This does the watermarking for input boxes, use the watermark class on
		labels, watermarkJS is added so you can position the label over the input
	

		$('.moduleType_ContactForm label').addClass("watermarkJS");
		$('.moduleType_ContactForm label').each(function(index,label){
			//eleInput = $('#'+$(label).attr("for"))[0];
			eleInput = $('.dataField',$(label).parent())[0];
			
			if(eleInput.value != "")
			{
				$(label).hide();
			}
			
			$(eleInput).blur(function(){
				//eleInput = $('#'+$(label).attr("for"))[0];
				eleInput = $('.dataField',$(label).parent())[0];
				if(eleInput.value == "")
				{
					$(label).show();
				}
			});
			$(eleInput).focus(function(){
				//eleInput = $('#'+$(label).attr("for"))[0];
				eleInput = $('.dataField',$(label).parent())[0];
				$(label).hide();
			});
			
		});
			
	*/
	
	
	//#endregion watermarks
		
	//#region zoomy images
		ZoomDim = {
			Thumb : {Width:300,Height:250},
			Large : {Width:720,Height:600}
		}		
		$(".MainPhotoImg").after("<div style=\"display:none;\" class=\"ImageZoomer\"><img src=\"\" width=\""+ZoomDim.Large.Width+"\" height=\""+ZoomDim.Large.Height+"\" /></div>");
		$(".MainPhotoImg").mouseover(function(){
			$(".ImageZoomer img").attr("src","about:blank");
			$(this).hide();
			$(".ImageZoomer").show();
			
			// $(".ImageZoomer img").attr("src","/imgsizer.aspx?action=zoomed&img="+
			// /[\?|\&]img=([^&]*)/.exec($(".MainPhotoImg").attr("src"))[1]);
		
			$(".ImageZoomer img").attr("src",window.ImageZoomAddress);
		
			$(".ImageZoomer").bind("mousemove",ImageMoving);
		});
		$(".ImageZoomer").mouseout(function(){
			zoomr = this;
			//setTimeout(function(){
				$(zoomr).hide();
				$(".MainPhotoImg").show();
				$(".ImageZoomer").unbind("mousemove",ImageMoving);
			//},300);
		});
		function ImageMoving(e)
		{
			var x = e.pageX - this.offsetLeft;
			var y = e.pageY - this.offsetTop;
			console.log([x,y]);
			$(".ImageZoomer img")
			.css("top",-(
				(y/ZoomDim.Thumb.Height)
					*(ZoomDim.Large.Height-ZoomDim.Thumb.Height)
				))
			.css("left",-(
				(x/ZoomDim.Thumb.Width)
					*(ZoomDim.Large.Width-ZoomDim.Thumb.Width)
				));
		}
	//#endregion zoomy images
		
	//#region homepage features
		$("a.Tab").click(function(){
			$('li.Tab').removeClass("selected");
			$('.MainFeatureProductsInfo').hide();
			$(this).parent().addClass("selected")
			$(this).next().show();
			$('.MainFeatureImages .StyleImage').hide();
			$($('.MainFeatureImages .StyleImage')[$('a.Tab').index(this)]).show();
			return false;
		});
		$("li.Tab:first").addClass("selected");
		$(".MainFeatureProductsInfo:first").show();
		$('.MainFeatureImages .StyleImage').hide();
		$('.MainFeatureImages .StyleImage:first').show();
	//#endregion homepage features
	
	//#region product history
		
		aryHistory = $.cookie("productHistory")==null?new Array():$.cookie("productHistory").split("\r");

		strProdUrl = "/20/section.aspx";
		if(location.pathname.length > strProdUrl.length && location.pathname.substring(0,strProdUrl.length) == strProdUrl)
		{
			strRow = $(".ProductIntro h1").text()+
			"#cell#"+location.pathname+
			"#cell#"+window.ImageHistoryAddress+
			"#cell#"+$('.ProductHeader .Price span:first').text();
			for(x=0;x<aryHistory.length;x++)
			{
				if(aryHistory[x] == strRow)
				{
					aryHistory.splice(x,1);
				}
			}
			aryHistory.unshift(strRow);
			if(aryHistory.length > 7)
			{
				aryHistory.splice(7,aryHistory.length-7);
			}
			$.cookie("productHistory", aryHistory.join("\r"), { expires: 100, path:"/" });
		}
		
		if(aryHistory.length>0)
		{
			strInsertHTML = "<div class=\"BrowseHistory\"><h3>Recently Viewed</h3>"
			for(x=0;x<aryHistory.length;x++)
			{
				aryItems = aryHistory[x].split("#cell#");
				strInsertHTML +='<div class="Product"><a href="'+
				aryItems[1]+
				'"><img width="86" height="75" alt="'+
				aryItems[0]+
				'" src="/imgsizer.aspx?action=HomeThumb&amp;img='+
				aryItems[2]+
				'"/><span class="Price">'+
				aryItems[3]+
				'</span></a></div>';
			}
			strInsertHTML += '<div class="clear"></div></div>';
			$('.MainContent > .Container').append(strInsertHTML)
		}
	//#endregion product history
	
    
    //#region print this page
		$('.Print a').click(function(e){
			window.print();
			return false;
		});
	//#endregion print this page
	
	
	$('.HomeIntro ul').cycle({ 
    fx:     'fade', 
    speed:   1000, 
    pause:   3000 
});
	
});



$("a[rel]").overlay();




