/* All Javascript Modules */
var visibleMenu = "";;
var inty;
var ii;



function cookieCheck()
{
	var cookieEnabled=(navigator.cookieEnabled)? true : false;
        if (typeof navigator.cookieEnabled=="undefined" && !cookieEnabled)
	{ 
		document.cookie="testcookie";
		cookieEnabled=(document.cookie.indexOf("testcookie")!=-1)? true : false;
	}

	if (cookieEnabled)
	{
		document.getElementById("usingcookies").value='1';
	}
	else
	{
		document.getElementById("usingcookies").value='0';
	}
}

function numberformat(num,dec)
{

	mul=Math.pow(10,dec);
	num=num*mul;
	num=Math.round(num);
	num = num/mul;
	var numstr=String(num);
	if(numstr.indexOf(".") == -1)
	{
		numstr = numstr + ".";
		for(nfi=0;nfi<dec;nfi++) numstr = numstr + "0";
	}
	decpl = numstr.length - numstr.indexOf(".");
	decpl = decpl - 1;
	if (decpl < dec)
	{
		for(nfi=decpl;nfi<dec;nfi++) numstr = numstr + "0";
	}
	return (numstr);

}

//shows/hides the object (pass in the id)
function toCurrency(val)
{
	return numberformat(val,2);
}

function showHide(divobj)
{
	if(document.getElementById(divobj).style.display=="")
	{
		document.getElementById(divobj).style.display="none";
	}
	else
	{
		document.getElementById(divobj).style.display="";
	}
}

function verifyNumeric(obj)
{
	var strValidChars = "0123456789";
	var strChar;
	var blnResult = true;

	val = obj;
	if (val.length == 0) return false;
	if((val.length==1)&&(val.charAt(0)=="0"))
	{
		return false;
	}

   //  test obj consists of valid characters listed above
	for (i = 0; i < val.length && blnResult == true; i++)
	{
		strChar = val.charAt(i);
		if (strValidChars.indexOf(strChar) == -1)
		{
			blnResult = false;
		}
	}
	return blnResult;	   
}


//updates the price of a product, given the options
function updatePrice()
{
	var x;

	var unitprice = document.getElementById("p_unitprice").value;
	var addvat = document.getElementById("p_addvat").value;
	var totalprice = 0;

	if(addvat>0)
	{
		totalprice = 1.175 * unitprice;
	}
	else
	{
		totalprice = unitprice;
	}
	

	
	for(x in arrP)
	{
		var y;
		var t = arrP[x];
		for(y in t)
		{
			if(document.getElementById("optionselection_"+x).value>"")
			{
				actualid=-1;
				actualidpos = document.getElementById("optionselection_"+x).value.lastIndexOf("_");
				if(actualidpos>-1)
				{
					actualid = document.getElementById("optionselection_"+x).value.substr(actualidpos+1);
				}
				
				if(y==actualid)
				{
					if(t[y][1]!=0)
					{
						if(t[y][0]!=0)
						{
							totalprice = 1.175*(parseFloat(t[y][1])+parseFloat(unitprice));
						}
						else
						{
							totalprice = parseFloat(totalprice) + parseFloat(t[y][1]);
						}
					}
					else
					{
						//some options don't
						//have a price
						//difference, AND they
						//don't add vat
						if(t[y][0]==0)
						{
							//this is the
							//case
							totalprice = parseFloat(unitprice);
						}
					}
				}
			}
		}
	}
	var head1 = document.getElementById("pprice");
//	head1.firstChild.nodeValue = "£" + toCurrency(totalprice) + " each";
	head1.firstChild.nodeValue = toCurrency(totalprice);
	
	
}


function IsNumeric(sText)
{
	var ValidChars = "0123456789.";
	var IsNumber=true;
	var Char;

	for (i = 0; i < sText.length && IsNumber == true; i++) 
	{ 
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1) 
		{
			IsNumber = false;
		}
	}
	return IsNumber;
}


function addToBasket(pid)
{
	err=0;

	//check that the quantity value submitted is numeric
	if(!IsNumeric(document.getElementById("pquantity").value))
	{
		err++;
	}
	
	if(document.getElementById("pquantity").value = "")
	{
		err++;
	}
	

	//check that all options available have been selected
	for(x in arrP)
	{
		
		var y;
		var t = arrP[x];
		for(y in t)
		{
			if(document.getElementById("optionselection_"+x).value>"")
			{
				actualid=-1;
				actualidpos = document.getElementById("optionselection_"+x).value.lastIndexOf("_");
				if(actualidpos>-1)
				{
					actualid = document.getElementById("optionselection_"+x).value.substr(actualidpos+1);
					op = x;
					document.getElementById("selectid").value = op;
					document.getElementById("itemid").value = document.getElementById("optionselection_"+x).value;
				}
				else
				{
					err++;
				}
			}
		}
	}

	if(err>0)
	{
		alert("There was an error creating your order.\nPlease ensure that you have entered a valid quantity for the product and have selected all options for this product.");
	}
	else
	{	quant = document.getElementById("quantity").value;
		document.getElementById("pquantity").value = quant;
		document.getElementById("pid").value = pid;
		document.getElementById("productform").action = "http://www.beckyunwin.com/addtobasket";
		document.getElementById("productform").submit();
	}
}

//removes an item from the user's basket, given the basket contents id
function removeBasketItem(bcid)
{
	if(confirm("Are you sure that you want to remove this item from your shopping basket?"))
	{
		document.getElementById("vvar").value=bcid;
		document.getElementById("task").value="deleteitem";
		document.getElementById("userbasket").submit();
	}
}

function updateBasketQuantity(bcid)
{
	p = document.getElementById("basketQuantity"+bcid).value;
	if(verifyNumeric(p))
	{
		document.getElementById("vvar").value="basketQuantity"+bcid;
		document.getElementById("task").value="updatequantity";
		document.getElementById("userbasket").submit();
	}
	else
	{
		alert("Please enter a positive integer for the quantity.");
	}
}


function getCurrentPageAddress()
{
	slashpos = document.location.href.lastIndexOf("/");
	phpos = document.location.href.indexOf("php",slashpos+1);
	pagestr = document.location.href.substr(slashpos+1, (phpos-slashpos)+2);
	return pagestr;
}

function viewBasket()
{
	//get current page address
	strCurrentPage = getCurrentPageAddress();
	document.getElementById("currPage").value = strCurrentPage;
	document.getElementById("productform").action = "http://www.beckyunwin.com/viewbasket";
	document.getElementById("productform").submit();
}


//initially this just pops up the menu, but eventually this will scale
//n shit
function HideMenu(divobj)
{
	document.getElementById("menu_"+divobj).style.display="none";
	restoreBG("menu_item"+divobj);
	clearInterval(inty);
	clearInterval(ii);
	if(visibleMenu	==divobj)
	{
		visibleMenu="";
	}
}

function hideImmediately(divobj)
{
	document.getElementById("menu_"+divobj).style.display="none";
	restoreBG("menu_item"+divobj);
	clearInterval(inty);
	clearInterval(ii);
}

function showHideMenu(divobj)
{
	//hide all open menus
	//show the selected menu
	if(visibleMenu!="")
	{
		hideImmediately(visibleMenu);
	}
	document.getElementById("menu_"+divobj).style.display="";
//	doWidthChangeMem(document.getElementById(divobj),0,480,15,15,10);
	setOpacity(document.getElementById("menu_"+divobj),0);
	fadeIn("menu_"+divobj,0);
	visibleMenu = divobj;
}

function startCloseTimer(obj)
{
	inty = setInterval('HideMenu("'+obj+'")',500);
	ii = setInterval('restoreBG("menu_item'+obj+'")',500);
}

function resetCloseTimer(obj)
{
	clearInterval(inty);
	clearInterval(ii);
}

function doWidthChangeMem(elem,startWidth,endWidth,steps,intervals,powr) { 
//Width changer with Memory by www.hesido.com
	if (elem.widthChangeMemInt)
		window.clearInterval(elem.widthChangeMemInt);
	var actStep = 0;
	elem.widthChangeMemInt = window.setInterval(
		function() { 
		elem.currentWidth = easeInOut(startWidth,endWidth,steps,actStep,powr);
		elem.style.width = elem.currentWidth + "px"; 
		actStep++;
		if (actStep > steps) window.clearInterval(elem.widthChangeMemInt);
	} 
	,intervals)
}

function easeInOut(minValue,maxValue,totalSteps,actualStep,powr) { 
//Generic Animation Step Value Generator By www.hesido.com 
	var delta = maxValue - minValue; 
	var stepp = minValue+(Math.pow(((1 / totalSteps) * actualStep), powr) * delta); 
	return Math.ceil(stepp) 
}

function setOpacity(obj, opacity) {
	opacity = (opacity == 100)?99.999:opacity;

  // IE/Win
	obj.style.filter = "alpha(opacity:"+opacity+")";

  // Safari<1.2, Konqueror
	obj.style.KHTMLOpacity = opacity/100;

  // Older Mozilla and Firefox
	obj.style.MozOpacity = opacity/100;

  // Safari 1.2, newer Firefox and Mozilla, CSS3
	obj.style.opacity = opacity/100;
}

function fadeIn(objId,opacity) {
	if (document.getElementById) {
		obj = document.getElementById(objId);
		if (opacity <= 100) {
			setOpacity(obj, opacity);
			opacity += 10;
			window.setTimeout("fadeIn('"+objId+"',"+opacity+")", 30);
		}
	}
}

function changeBG(obj)
{
	document.getElementById(obj).style.backgroundColor='#D1CDB7';

}

function restoreBG(obj)
{
	document.getElementById(obj).style.backgroundColor='';
	clearInterval(ii);

}

function resizeInfoDiv()
{
	h = document.getElementById("ing").height;
	document.getElementById("inf").style.height = h + 60;
}

function doCheckout()
{
	strCurrentPage = getCurrentPageAddress();
	document.getElementById("currPage").value = strCurrentPage;
	document.getElementById("productform").action = "http://www.beckyunwin.com/checkout";
	document.getElementById("productform").submit();
}

function pointerMouse()
{
	document.cursor = 'pointer';
}

function arrowMouse()
{
	document.body.style.cursor = 'default';
}

function shoplinkOver(obj)
{
	obj.style.cursor = "pointer";
	obj.style.background = "#dddddd";
	obj.style.border = "solid 1px #aaaaaa";	
}

function shoplinkOut(obj)
{
	obj.style.cursor = "default";
	obj.style.background = "#eeeeee";
	obj.style.border = "dashed 1px #cccccc";	
}

function getProduct(pstrurl)
{
	document.getElementById("productform").action = pstrurl;
	document.getElementById("productform").submit();
}

function resetPageHeight()
{
	
	
	//alert("TEST");
	//d = document.getElementById("page_content").offsetHeight;
	d = document.getElementById("page").offsetHeight;
	var viewportwidth;
	var viewportheight;

	// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
	if (typeof window.innerWidth != 'undefined')
	{
		viewportwidth = window.innerWidth;
		viewportheight = window.innerHeight;
	}

	// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
	else if (typeof document.documentElement != 'undefined'
		 && typeof document.documentElement.clientWidth !=
		 'undefined' && document.documentElement.clientWidth != 0)
	{
		viewportwidth = document.documentElement.clientWidth;
		viewportheight = document.documentElement.clientHeight;
	}

	// older versions of IE

	else
	{
		
		viewportwidth = document.getElementsByTagName('body')[0].clientWidth;
		viewportheight = document.getElementsByTagName('body')[0].clientHeight;
	}
	//alert(d);
	//alert(viewportheight);
	if(d<viewportheight)
	{
		document.getElementById("page_height").style.height = viewportheight- 250+ "px";				
	}
	else
	{
		document.getElementById("page_height").style.height = document.getElementById("page").offsetHeight-250 + "px";
	}
}

function getPageSize(){

	var xScroll, yScroll;

	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;

	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		//xScroll = document.body.scrollWidth;
		yScroll = document.body.offsetHeight;
	}

	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.scrollWidth;
		//windowHeight = document.body.offsetHeight;
		windowHeight = document.documentElement.scrollHeight;
		//windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	

	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	if (navigator.appName == "Microsoft Internet Explorer")
		{yposition = document.body.scrollTop;}
	else {yposition = window.pageYOffset;}

	if (navigator.appName == "Microsoft Internet Explorer")
		{xposition = document.body.scrollLeft;}
	else {xposition = window.pageXOffset;}	

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight, xposition, yposition);
	return arrayPageSize;
}


var out_fade =
{
fadeout : function (id,curropacity,opacityToFade,bHidden)
	  {
		  var opacity = curropacity;
		  if(bHidden)
		  {
			  document.getElementById(id).style.display='';
		  }
		  this.fadeLoop(id, opacity,opacityToFade); // remember its not  "->" function name.. its "."
	  },
fadeLoop : function (id, opacity,opacityToFade)
	  {
		  var object = document.getElementById(id);
		  if (opacity <= opacityToFade)
		  { // just encase i forget 99% due to a firefox bug..
			  out_fade.setOpacity(object, opacity);
			  opacity += 10;
			  window.setTimeout("out_fade.fadeLoop('" + id + "', " + opacity + "," + opacityToFade + ")", 30);
		  }
		  else
		  {
			  ajaxrunning=false;
		  }
	  },
setOpacity : function (object, opacity)
	  {
		  object.style.filter = "alpha(style=0,opacity:" + opacity + ")";	// IE
		  object.style.KHTMLOpacity = opacity / 100;				// Konqueror
		  object.style.MozOpacity = opacity / 100;					// Mozilla (old)
		  object.style.opacity = opacity / 100;					// Mozilla (new)
	  }
}


var in_fade =
{
fadeout : function (id,curropacity,opacityToFade,bHide)
	  {
		  var opacity = curropacity; 
		  this.fadeLoop(id, opacity,opacityToFade,bHide); // remember its not  "->" function name.. its "."
	  },

fadeLoop : function (id, opacity,opacityToFade,bHide)
	  {
		  var object = document.getElementById(id);
		  if (opacity >= opacityToFade)
		  {
			  in_fade.setOpacity(object, opacity);
			  opacity -= 10;
			  window.setTimeout("in_fade.fadeLoop('" + id + "', " + opacity + "," + opacityToFade + ","+ bHide +")", 30);
		  }
		  else
		  {
			  if(bHide)
			  {
				  object.style.display='none';
			  }
		  }
	  },
setOpacity : function (object, opacity)
	  {
		  object.style.filter = "alpha(style=0,opacity:" + opacity + ")";	// IE
		  object.style.KHTMLOpacity = opacity / 100;				// Konqueror
		  object.style.MozOpacity = opacity / 100;					// Mozilla (old)
		  object.style.opacity = opacity / 100;					// Mozilla (new)
	  }
}

function zoomImage(imgsrc,caption)
{

  //document.getElementById("page").style.display = 'none';
//  document.getElementById("msh-contentarea").style.width = '100%';

	document.getElementById("zoombox").style.left = 50 + "%";
	document.getElementById("zoombox").style.top = 50 + "%";
	document.getElementById("zoombox").style.display = "block";
	document.getElementById("zoomimg").src = imgsrc;
	document.getElementById("zoomcaption").innerHTML = caption;
	w = document.getElementById("zoomimg").width;
	document.getElementById("zoombox").style.width = w  + 10 + "px";

	h = document.getElementById("zoomimg").height;
	document.getElementById("zoombox").style.height = h + 50 + "px";
	document.getElementById("zoomimg").style.marginLeft = "5px";
	document.getElementById("zoomimg").style.marginTop = "5px";


		//setOpacity(document.getElementById("fadebox"),30);
	document.getElementById("fadebox").style.width = "100%";

	var arrPageData = getPageSize();
	h2 = arrPageData[1];
	w2 = arrPageData[0];
	xpos = arrPageData[4];
	ypos = arrPageData[5];


	document.getElementById("zoombox").style.marginTop = ypos + (-1 * (h/2)) + "px";
	document.getElementById("zoombox").style.marginLeft = xpos + (-1 * (w/2)) + "px";
	document.getElementById("fadebox").style.height = h2 + "px";
	document.getElementById("fadebox").width = w2 + "px";
	document.getElementById("fadebox").style.display = "";

		//document.getElementById("zoombox").style.marginLeft =  + "px"; <------ retard r' us :D
	document.getElementById("zoombox").style.marginTop = (-1 * (h/2)) + "px";		

	out_fade.fadeout("fadebox",0,20,true);
	out_fade.fadeout("zoombox",0,100,true);
}

function hideImage()
{
	in_fade.fadeout("fadebox",20,0,true);
	in_fade.fadeout("zoombox",100,0,true);
}

function checkvalidemailaddress(str)
{
	return true;
}

function setBillingAddress()
{
	badstring = document.getElementById("personname").value + "<br>" + document.getElementById("add1").value;
	if(document.getElementById("add2").value!="")
	{
		badstring += "<br>" + document.getElementById("add2").value;
	}
	badstring += "<br>" + document.getElementById("town").value + "<br>" + document.getElementById("county").value + "<br>" + document.getElementById("postcode").value;
	document.getElementById("baddress").innerHTML = badstring;
}

function setDeliveryAddress(bUseBillingAddress)
{
	if(bUseBillingAddress)
	{
		badstring = document.getElementById("personname").value + "<br>" + document.getElementById("add1").value;
		if(document.getElementById("add2").value!="")
		{
			badstring += "<br>" + document.getElementById("add2").value;
		}
		badstring += "<br>" + document.getElementById("town").value + "<br>" + document.getElementById("county").value + "<br>" + document.getElementById("postcode").value;
		document.getElementById("daddress").innerHTML = badstring;
	}
	else
	{
		badstring = document.getElementById("deliverypersonname").value + "<br>" + document.getElementById("deliveryadd1").value;
		if(document.getElementById("deliveryadd2").value!="")
		{
			badstring += "<br>" + document.getElementById("deliveryadd2").value;
		}
		badstring += "<br>" + document.getElementById("deliverytown").value + "<br>" + document.getElementById("deliverycounty").value + "<br>" + document.getElementById("deliverypostcode").value;
		document.getElementById("daddress").innerHTML = badstring;			
	}
}

function proceedToNextStage(currentStage)
{
	if(currentStage=="1")
	{
			//we're at the billing details screen
		err=0;
		errStr="";
		if(document.getElementById("personname").value=="")
		{
			err++;
			errStr += "Please enter the name of the person paying for this transaction.\n";
		}

		if(document.getElementById("add1").value=="")
		{
			err++;
			errStr += "Please enter the first line of the billing address.\n";
		}

		if(document.getElementById("town").value=="")
		{
			err++;
			errStr += "Please enter the town name of the billing address.\n";
		}

		if(document.getElementById("county").value=="")
		{
			err++;
			errStr += "Please enter the county name of the billing address.\n";
		}	

		if(document.getElementById("postcode").value=="")
		{
			err++;
			errStr += "Please enter the postcode for the billing address.\n";
		}

		if(document.getElementById("telephone").value=="")
		{
			err++;
			errStr += "Please enter a contact telephone number.\n";
		}

		if(!checkvalidemailaddress(document.getElementById("email").value))
		{
			err++;
			errStr += "Please enter a valid email address.\n";
		}

		if(err>0)
		{
			alert("The following error(s) occurred:\n" + errStr);
		}
		else
		{
			if(document.getElementById("ufd").checked)
			{
				document.getElementById("usebilling").value="1";
				document.getElementById("checkoutform").action ="http://www.beckyunwin.com/checkout2";
				document.getElementById("checkoutform").submit();
			}
			else
			{
				document.getElementById("checkout-step-1a").style.display='';
//					document.getElementById("checkout-sidebar-stage1a").style.display='';
			}

			document.getElementById("checkout-step-1").style.display='none';
	//			document.getElementById("checkout-sidebar-stage1").style.display='none';
		}
	}

	if(currentStage=="1a")
	{
			//we're at the billing details screen
		err=0;
		errStr="";
		if(document.getElementById("deliverypersonname").value=="")
		{
			err++;
			errStr += "Please enter the name of the person receiving the delivery.\n";
		}

		if(document.getElementById("deliveryadd1").value=="")
		{
			err++;
			errStr += "Please enter the first line of the delivery address.\n";
		}

		if(document.getElementById("deliverytown").value=="")
		{
			err++;
			errStr += "Please enter the town name of the delivery address.\n";
		}

		if(document.getElementById("deliverycounty").value=="")
		{
			err++;
			errStr += "Please enter the county name of the delivery address.\n";
		}	

		if(document.getElementById("deliverypostcode").value=="")
		{
			err++;
			errStr += "Please enter the postcode for the delivery address.\n";
		}


		if(err>0)
		{
			alert("The following error(s) occurred:\n" + errStr);
		}
		else
		{
			document.getElementById("usebilling").value="0";
			document.checkoutform.action ="http://www.beckyunwin.com/checkout2";
			document.getElementById("checkoutform").submit();					
		}
	}

}

function previousStage(currentStage)
{
		//at the moment there's only stages 1 & 1a, so we can only go back to 1
	document.getElementById("checkout-step-1a").style.display='none';
	document.getElementById("checkout-step-1").style.display='';
}

function previouseCheckoutPage()
{
	document.getElementById("checkoutform").action = '<? print $SITEURL;?>/checkout';
	document.getElementById("checkoutform").submit();
}

function goToBank()
{
	document.getElementById("checkoutform").action = '/paymentpage';
	document.getElementById("checkoutform").submit();
}

function checkMailingList()
{
        err = 0;
	message ="";
	if(document.getElementById("subscriptionname").value == "")
	{
		err++;
		message += "Name\n";
	}

	if(document.getElementById("subscriptionemail").value == "")
	{
		err++;
		message += "E-mail address\n";
	}

	if(err>0)
	{
		alert("Please enter the following information:\n" + message);
		return false;
	}
	else
	{
		return true;
	}     
}

function checkForm()
{
	
	err = 0;
	message ="";
	if(document.getElementById("name").value == "")
	{
		err++;
		message += "Name\n";
	}
	if(document.getElementById("number").value == "")
	{
		err++;
		message += "Telephone Number\n";
	}
	if(document.getElementById("email").value == "")
	{
		err++;
		message += "E-mail address\n";
	}
	if(document.getElementById("message").value == "")
	{
		err++;
		message += "Message\n";
	}

	if(err>0)
	{
		alert("Please enter the following information:\n" + message);
		return false;
	}
	else
	{
		return true;
	}
}

function doEmailPayment()
{
	document.getElementById("productform").action = "http://www.beckyunwin.com/paybycheque";
	document.getElementById("productform").submit();
}

function confirmDelData()
{
	document.getElementById("gotaddress").value = 1;
	document.getElementById("chequeorder").submit();
}