﻿var ajax_load_icon = "<img src='/images/ajaxloader/ajax-loader_snake.gif' alt='loading...' />";

/*----Ready ---------*/
$(function(){
/*-------------------*/
	
	//http://www.vancelucas.com/blog/fixing-ie7-z-index-issues-with-jquery/
	var zIndexNumber = 1000;
	$('div').each(function() {
		$(this).css('zIndex', zIndexNumber);
		zIndexNumber -= 10;
	});
	/*
	$.ajaxSetup ({   
	        cache: false
			//success: function(msg){alert( "Data Saved: " + msg );}
	    }); */
		

	/*ajax basket
	-----------------*/
	//load basket
	$("#basketSummaryBox").html(ajax_load_icon).load("/store/ajax/basket_display.asp");
	$(".cmdAddToBasket").live("click",function(event){
		event.preventDefault();		
		var form = $(this).parents('form:first');
		var itemID = $("input[name='itemID']",form).val(); 
		var q = $("#quantity",form).val(); 
		//var varID = $("#frmVariationID",form).val();
		var varID = $("input[name='frmVariationID']:checked",form).val();
		var formName= form.attr("name");
		var parentDivID = $("#parentDivID",form).val();
		var targetDiv= $("#basketSummaryBox");
		var redirectTo = encodeURI("/store/ajax/basket_display.asp");
		var url = "/store/ajax/basket_addto.asp";
		var postData = "itemID="+itemID+"&varID="+varID+"&quantity="+q+"&redirectTo="+redirectTo;
		var loadUrl = url + "?" + postData;
		
		/*
		alert(postData);
		var loadUrl = "/store/ajax/test.asp";
		alert(postData);
		$.fly( parentDivID, 'basketSummaryBox', $.removeShadow  );
		targetDiv.html(ajax_load_icon).load(loadUrl);
		targetDiv.html(loadUrl);
		 */
		$.ajax({   
			url: url,    
			type: "POST",          
			data: postData,        
			cache: false,   
			success: function (response) {    
				targetDiv.html(response);             
				               
			},
			error: function(){
				targetDiv.html("error fetching data..");   
				}
		
		}); 
		
		//show confirm div
		var t = $(this).offset().top;
		var l = $(this).offset().left;
		var w = $(this).width();
		var h = $(this).height();
		strDiv = $('<div id="#confirmDiv" style="position: absolute; top: '+t+'px;left: '+l+'px; ' 
			+'width: '+w+'px;height: '+h+'px;'
			+'background:#6AD568 url(/store/images/buttons/btnAddedToBag.gif) 0px 0px no-repeat; ' 
			+'color:#fff; font-weight:bold;text-align:center;'
			+'z-index: 100000;"></div>');
		$('body').prepend(strDiv);
		strDiv.animate({
		    opacity: 100
		  }, 200, function() {
		    // Animation complete.
			  strDiv.animate({
			    opacity: 0
			  }, 2000, function() {
			    // Animation complete.
				strDiv.remove();
			  });			
		  });
		  
		 
	});
	/*ajax basket end
	-----------------*/
	
	
	/* show large image when thumb clicked (view orders/view favs)
	----------------------*/
	$(".thumb").click(function(event) {

		var img = $(this);
		var w = img.width();var h = img.height(); //grab w and h 
	    if (w == 50) { 
			//first remove set values
			img.removeAttr("width") 
	           .removeAttr("height") 
	           .css({ width: "", height: "" }); // Remove css dimensions as well 
			//now we can read the actual values
			var newW = img.width();
			var newH = img.height();
			//now set back to 50 so that animation has a starting point
			img.css({ width: "50", height: "50" });
			img.attr("width","50");
			img.attr("height","50");
			img.animate({
			    width: [newW, 'swing'],
			    height: [newH, 'swing']
			  }, 500, function() {
			    // Animation complete.
			  });		
	    } 
	    else{ 
			w = 50;
			h = 50;	
			img.animate({
			    width: [w, 'swing'],
			    height: [h, 'swing']
			  }, 500, function() {
			    // Animation complete.
			  });	
	    } 
				
	});	
	/* end 
	----------------------*/
	
	/*favourites
	---------------*/
	$(".action").click(function(event) {
		event.preventDefault();
		$(".favPopupDiv").hide();//close any other open divs
		var itemID= $(this).attr("itemID");
		var varID= $(this).attr("varID");
		var targetDiv= $(this).attr("targetDiv");
		var div = $(this).parent().find(".favPopupDiv");
		div.css("z-index","10000");
		div.show('slow');
		var favAjaxDiv = $("#"+targetDiv);
		var loadUrl = "/myaccount/loadFavourites.asp?itemID="+itemID+"&varID="+varID; 
		favAjaxDiv.html(ajax_load_icon).load(loadUrl);
		
		/*alert(loadUrl);
		div.hide('slow');
		load content
		var favAjaxDiv = $(this).parent().find("#favAjaxDiv");
		var favAjaxDiv = $(this).parent().find("#"+targetDiv);
		favAjaxDiv.append(loadUrl);
		alert(loadUrl);
		favAjaxDiv.css("border","3px solid red").append("<br>"+targetDiv);
		*/
	});	
	
	$(".favPopupClose").click(function(event) {
		event.preventDefault();
		var div = $(this).parent();
		div.hide('slow');
	});	
	
	
	function hidePopups(){
		setTimeout(function(){
			$(".favPopupDiv").fadeOut('slow');
			}, 1500);
		
		}


	
	/*These are generated by the ajax request itself and need to be hooked up using LIVE*/
	$(".ajax_action").live('click',function(event) {
		event.preventDefault();
		var task= $(this).attr("task");
		var itemID= $(this).attr("itemID");
		var varID= $(this).attr("varID");
		var targetDiv= $(this).attr("targetDiv");
		var thisTargetDiv = $("#"+targetDiv); /*$(this).parent().find("#favAjaxDiv");*/
		var loadUrl = "/myaccount/loadFavourites.asp?task="+task+"&itemID="+itemID+"&varID="+varID; 

		thisTargetDiv.html(ajax_load_icon).load(loadUrl,
			function (responseText, textStatus, XMLHttpRequest) { 
			    if (textStatus == "success") { 
					hidePopups();
			    } 
			    if (textStatus == "error") { 
					 thisTargetDiv.html("error!<br />"+responseText);
			    } 
			 } );
		

		
	});	
	
	/*favourites end
	---------------*/
	
	var defaultSearchText = "By Keyword...";
	//set default text if empty
	var currentValue = $("input[name=frmKeyword]").val();
	if(currentValue==""){$("input[name=frmKeyword]").val(defaultSearchText);}
	
	$("input[name=frmKeyword]").click(function() {
		var v = $(this).val();
		if( v==defaultSearchText ){
			$(this).val("");
			}
	});	
	$("input[name=frmKeyword]").blur(function() {
		var v = $(this).val();
		if( v==""||v==" " ){
			$(this).val(defaultSearchText);
			}
	});
	
	$(".showDivInfo").click(function(event) {
		event.preventDefault();
		var targetDiv= $(this).attr("href");
		$(".divInfo:not("+targetDiv+")").hide();//close any other open divs (except target)
		$(targetDiv).toggle('slow');//show target div
	});	
	
	$(".closeParentDiv").click(function(event) {
		event.preventDefault();
		var div = $(this).parent();
		div.hide('slow');
	});	
	$(".closeParentWin").click(function(event) {
		event.preventDefault();
		//var window = $(this).window();
		//window.close();
		window.close();
	});
	
	

	$(".showDivInfoPopup").click(function(event) {
		event.preventDefault();
		var targetDiv= $(this).attr("href");
		$(targetDiv).css({'z-index':10000});
		$(targetDiv).toggle();//show target div
	});
	$(".showDivInfoPopup").mouseout(function(event) {
		event.preventDefault();
		var targetDiv= $(this).attr("href");
		$(targetDiv).hide();//show target div
	});
	
/*---- end Ready ----*/
});
/*-------------------*/




/* update these to use JQ*/

//-- Flash
var MM_contentVersion = 5;
var plugin = (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]) ? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin : 0;
if ( plugin ) {
		var words = navigator.plugins["Shockwave Flash"].description.split(" ");
	    for (var i = 0; i < words.length; ++i)
	    {
		if (isNaN(parseInt(words[i])))
		continue;
		var MM_PluginVersion = words[i]; 
	    }
	var MM_FlashCanPlay = MM_PluginVersion >= MM_contentVersion;
}
else if (navigator.userAgent && navigator.userAgent.indexOf("MSIE")>=0 
   && (navigator.appVersion.indexOf("Win") != -1)) {
	document.write('<SCR' + 'IPT LANGUAGE=VBScript\> \n'); //FS hide this from IE4.5 Mac by splitting the tag
	document.write('on error resume next \n');
	document.write('MM_FlashCanPlay = ( IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash." & MM_contentVersion)))\n');
	document.write('</SCR' + 'IPT\> \n');
}
//MM_FlashCanPlay = false;
//noFlashURL = "/home.asp";

function addToFavorite(favTitle){
  if ((navigator.appVersion.indexOf("MSIE") > 0) && (parseInt(navigator.appVersion) >= 4)) {
    window.external.AddFavorite(location.href, unescape(favTitle));
  }
}


var statusMsg = ""
function st_1(msg){window.status=msg;}function st_2(msg){window.status=statusMsg;return true;}

function showPopup( url, w, h, offsetX, offsetY, rsze, scr,st ){
	var winLeft = (screen.width / 2) - (w/2);
	var winTop = (screen.height / 2) - (h/2);
	winLeft += offsetX;winTop += offsetY;
	var newWin;newWin = "";
	if(!newWin  || newWin.closed){
		newWin = eval('window.open(url,"newWin","resizable='+rsze+',scrollbars='+scr+',status=yes,left='+winLeft+',top='+winTop+',Width='+w+'px,Height='+h+'px")');
		newWin.focus();
		newWin.resizeTo(w,h);
		newWin.moveTo(winLeft,winTop);
	}	
}

function closeMe(){top.close();}
//-- general
function cookieInfo(){showPopup( '/login/cookies.asp', 480, 470, 0, 0,1,1,1 );}
function secureInfo(){showPopup( '/secure/infoSecure.asp', 480, 400, 0, 0,0,1,1 );}
function requestDetails(){showPopup( '/login/request_my_details.asp', 500, 450, -20, -20,1,1,"yes" );}
function requestSecureDetails(){showPopup( '/secure/request_my_details.asp', 470, 350, -20, -20,1,0,"yes" );}
function whatsThisOrder(){showPopup( '/store/whatsThisOrder.asp', 480, 380, -20, -20,1,1,1 );}

function converter(){showPopup( '/store/howdoescurrencywork.asp', 480, 420, 200, -150,0,0 );}
function showPriceList(){showPopup( '/store/downloads/tradePriceList.asp', 680, 520,0,0,1,1 );}
function showMailingListWin(){showPopup( '/store/mailingList.asp',470,450, 0, 0,0,0);}


function showVenueWin( url, w, h, offsetX, offsetY, rsze, scr,st ){
	var winLeft = (screen.width / 2) - (w/2);
	var winTop = (screen.height / 2) - (h/2);
	winLeft += offsetX;winTop += offsetY;
	var priceBeaterWin;priceBeaterWin = "";
	if(!priceBeaterWin  || priceBeaterWin.closed){
		priceBeaterWin = eval('window.open(url,"venueWin","resizable='+rsze+',scrollbars='+scr+',status='+st+',left='+winLeft+',top='+winTop+',Width='+w+'px,Height='+h+'px")');
		priceBeaterWin.focus();
		
	}	
}
function showVenue(id){showVenueWin('/store/venue.asp?id='+id, 500, 450,40,50,1,1,1 );}






//------------------------------------------------------------------------
//----------------- STORE -------
//------------------------------------------------------------------------



function tradePriceList(){showPopup( '/store/tradePriceList.asp', 600, 480, 0, 0,0,1 );}


function checkForm(obj){
     //-- Check that they have entered  a quantity
     if (!obj.quantity.value){
          obj.quantity.value=prompt("You forgot to include a Quantity for this item. Please enter one below.","");
          if (obj.quantity.value=="null"){
               obj.quantity.value="";
          }
          return false;
        
     }
	 //-- check that the quantity is a number and convert to an integer
	 IntValue = obj.quantity.value;
		IntValue = parseInt(IntValue);
		if (isNaN(IntValue)) {   
			alert("Please enter a valid number value for the required quantity.\n\nThank you.");
			obj.quantity.value="";
			return false;
		}
	 //-- check the quantity is not zero
	 if(IntValue==0){
	 	alert("Please enter a valid number value for the required quantity.\n\nThank you.");
		return false;
	 }
	 
		//-- close the Cart Window
		theWin = window.cartWin;
        //if(!theWin || theWin.closed){ }else{theWin.close();}
		if(theWin){theWin.close();}
		return true;
		
}

function checkBasketForm(){
	theForm = document.forms["frmBasket"];
	for(i=0;i<theForm.length;i++){
		if(theForm.elements[i].type =="text"){
			//-- returns, "quanti", "priceE", "priceT", "allTot"
			if(theForm.elements[i].name.substring(0,6)=="quanti"){
				var quan = theForm.elements[i].value;
				if(isNaN(quan)){
					msg="Please enter a valid number value for the required quantity of all items."
					msg+="\n\nSetting an items quantity to '0' will remove that item."
					msg+="\n\nThank you."
					alert(msg);
					return false;
				}

			}
		}
	}
}


function DeleteMe(theElement){
	obj = document.forms["frmBasket"].elements[theElement];
	obj.value=0;
	checkBsktQuantity(obj);
}

function warnUpdate(obj){
	//alert("Please remember to use 'Update Order'.")
}

function promptUpdate(obj){
	//obj.elements['submit'].className="bskButtonPrompt";
	
	//btn_On = new Image(); btn_On.src = "/images/look/default/buttons/btnUpdateBskt.gif";
	//obj.elements['submit'].src = "/images/look/default/buttons/btnUpdateBskt.gif";
	//obj.elements['submit'].src = btn_On.src;
}

function checkBsktQuantity(obj){
		if(obj.value==0){
			
			//-- change style
			obj.className="bskEmptyTextBox";
			//reCalculate();
			//document.forms["frmBasket"].elements['submit'].className="bskButtonPrompt";
			obj.focus();
		}else{
			obj.className="textBox1";
			//reCalculate();
			//document.forms["frmBasket"].elements['submit'].className="bskButtonPrompt";
			obj.focus();
		}
}

function removeFocus(obj){
	//alert(toString(obj)+" hasfocus")
	obj.blur();
}

function reCalculate(){
	theForm = document.forms["frmBasket"];
	var allTot=0;
	for(i=0;i<theForm.length;i++){
		if(theForm.elements[i].type =="text"){
			//-- returns, "quanti", "priceE", "priceT", "allTot"
			if(theForm.elements[i].name.substring(0,6)=="quanti"){
				var quan = theForm.elements[i].value;if(isNaN(quan)){return false};quan = eval(quan*1);
				var priceEa = theForm.elements[i+1].value;priceEa = priceEa.substring(3);priceEa = parseFloat(priceEa);
				var priceTot = theForm.elements[i+2].value;priceTot = priceTot.substring(1);priceTot = parseFloat(priceTot);
				//-- adjust priceTot
				priceTot = (quan * priceEa);
				var allTot = allTot + priceTot;
				
				theForm.elements[i].value = quan;
				theForm.elements[i+1].value = "@ "+ GetCurrency(priceEa,"£") + " ea";
				theForm.elements[i+2].value = GetCurrency(priceTot,"£");
				theForm.elements['allTotal'].value = GetCurrency(allTot,"£");
				//alert(quan +" x "+ priceEa +" = "+ priceTot)
			}
		}
	}
}

function GetCurrency(amount,poundSign){
	tmpCurr = poundSign + amount  /**/
	hasPeriod = tmpCurr.indexOf(".")
	if(hasPeriod==-1){
		tmpCurr = tmpCurr +".00"
	}else{
		zerosAfterPeriod = tmpCurr.substring(hasPeriod)
		if(zerosAfterPeriod.length==3){
			tmpCurr = tmpCurr
		}else{
			tmpCurr = tmpCurr +"0"
		}
	}

	return tmpCurr;
}


function shutDown(){
	close('self');
}
