var isClickOnQty = false;
var count=0;
var haveToRefreshMiniCart=true;
var isReloadMiniCart=null;
var TimerIDArray = new Array();
var TimerIDCount = 0;
var AddToCartArray = new Array();
var AddToCartCount = 0;
var cartItem=0;
var goto_top_type = -1;
var goto_top_itv = 0;
var totTwdkEntries = 0;

document.onclick=checkPopup;
function checkPopup(e) {
	var target = (e && e.target) || (event && event.srcElement);
	var clickedOn = target.id;
	var isDisplaySearchtList = false;

	while(target.parentNode) {
		if(target==document.getElementById('searchResultContainer'))
			isDisplaySearchtList = true;
		target=target.parentNode;
	}
	if((isDisplaySearchtList)==false && document.getElementById('searchResultContainer') != null) {
		document.getElementById('searchResultContainer').style.display = "none";
		document.getElementById('scat').style.visibility = "visible";
		document.getElementById('Occasion').style.visibility = "visible";
		document.getElementById('Personality').style.visibility = "visible";
		document.getElementById('price').style.visibility = "visible";
	}
}

function borderOn(val,val2) {
	if(val2=='rel')
		var id= "product_rel"+val;
	else
		var id= "product"+val;
	document.getElementById(id).className='borderOn';
}
	
function borderOff(val,val2) {
	if(val2=='rel')
		var id= "product_rel"+val;
	else
		var id= "product"+val;
	document.getElementById(id).className='borderOff';
}

function buttonOn(val1,val2) {
	var id= val1;
	var image = val2;
	var parts = image.split(".");
	var imgName = parts[0];
	var imgExt = parts[1];
	document.getElementById(id).src = imgName+'On.'+imgExt;
}
	
function buttonOff(val1,val2) {
	var id= val1;
	var image = val2;
	document.getElementById(id).src = val2;
}

function proddetail(prod) {
	location.href = "/"+prod+".html";
}

function showAll() {
	document.getElementById("form2").submit();
}

function searchByPrice(min,max) {
	document.form3.sminprice.value = min;
	document.form3.sprice.value = max;
	document.getElementById("form3").submit();
}

function addtocart(form,page) {
	if(count>0)
		AddToCartArray[AddToCartCount++] = "add('"+form+"','"+page+"',"+AddToCartCount+");";
	else
		add(form,page,0);
}

function add(form,page,cartItemNo) {
	if(cartItemNo!=0)
		cartItem = cartItemNo;
		
	haveToRefreshMiniCart=true;
	var formName = form;
	if(page!="cart") {
		for (j = 0 ; j < TimerIDCount ; j++) {
		    window.clearTimeout(TimerIDArray[j]);
		}
		
		if(form=='mainform0') {
			var imagename = document.getElementById("hiddenSmallImage").value;
			document.getElementById("message").innerHTML = '<table border="0" cellspacing="0" cellpadding="0"><tr><td><img src="'+imagename+'" alt="" width="64" height="64"></td><td>Sorry, there is not sufficient stock in this product.</td></tr></table>';
			setOpacity("message",0);
			document.getElementById("message").style.zIndex = "1000";
				
			offArr = getScrollXY();
			winSizArr = getWinSize();
			document.getElementById("message").style.top = (offArr[1]+((winSizArr[1])/2))+"px";
			document.getElementById("message").style.left = (offArr[0]+((winSizArr[0]-document.getElementById("message").offsetWidth)/2))+"px";

			fadeIn('message',100,300);			
			TimerIDArray[TimerIDCount++] = window.setTimeout("fadeOut('message',100,1000,'fadoutstart');", 3000);
			TimerIDArray[TimerIDCount++] = window.setTimeout('document.getElementById("message").style.zIndex = "0";', 4000);
		}
		else {
			document.getElementById("message").innerHTML="";
			setOpacity("message",0);
			document.getElementById("message").style.display="none";		
			if(form!='mainform1')
				document.getElementById(formName).target = "hiddenFrame";
			else
				document.getElementById("mainform").target = "hiddenFrame";
		}	
	}
	
	if(form!='mainform0' && form!='mainform1')
			document.getElementById(formName).submit();
	else
		return false;
}

function getWinSize() 
{
	  var myWidth = 0, myHeight = 0;
	  if( typeof( window.innerWidth ) == 'number' ) 
	  {
	    //Non-IE
	    myWidth = window.innerWidth;
	    myHeight = window.innerHeight;
	  } 
	  else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) 
	  {
	    //IE 6+ in 'standards compliant mode'
	    myWidth = document.documentElement.clientWidth;
	    myHeight = document.documentElement.clientHeight;
	  } 
	  else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) 
	  {
	    //IE 4 compatible
	    myWidth = document.body.clientWidth;
	    myHeight = document.body.clientHeight;
	  }
	  return [ myWidth, myHeight ];
}

function getScrollXY() 
{
	  var scrOfX = 0, scrOfY = 0;
	  if( typeof( window.pageYOffset ) == 'number' ) 
	  {
	    //Netscape compliant
	    scrOfY = window.pageYOffset;
	    scrOfX = window.pageXOffset;
	  } 
	  else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) 
	  {
	    //DOM compliant
	    scrOfY = document.body.scrollTop;
	    scrOfX = document.body.scrollLeft;
	  } 
	  else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) 
	  {
	    //IE6 standards compliant mode
	    scrOfY = document.documentElement.scrollTop;
	    scrOfX = document.documentElement.scrollLeft;
	  }
	  return [ scrOfX, scrOfY ];
}

function reloadMiniCart(prodname,prodimage,isAdded) {
	isReloadMiniCart = true;	
	count +=1;
	if(count==1) {
		if(document.getElementById("hiddenIsntCart")!=null) {
			if(isAdded!="notadded")
				document.getElementById("message").innerHTML = '<table border="0" cellspacing="0" cellpadding="0"><tr><td><img src="'+prodimage+'" alt="" width="64" height="64"></td><td>'+prodname+' has been added to your order.</td></tr></table>';
			else {
				document.getElementById("message").innerHTML = '<table border="0" cellspacing="0" cellpadding="0"><tr><td><img src="'+prodimage+'" alt="" width="64" height="64"></td><td>Sorry, there is not sufficient stock in this product.</td></tr></table>';
				isReloadMiniCart = false;
				count=0;
			}			
			if(isAdded!='') {
				setOpacity("message",0);
				document.getElementById("message").style.zIndex = "1000";
				
				offArr = getScrollXY();
				winSizArr = getWinSize();
				document.getElementById("message").style.top = (offArr[1]+((winSizArr[1])/2))+"px";
				document.getElementById("message").style.left = (offArr[0]+((winSizArr[0]-document.getElementById("message").offsetWidth)/2))+"px";
				
				fadeIn('message',100,300);
				TimerIDArray[TimerIDCount++] = window.setTimeout("fadeOut('message',100,1000,'fadoutstart');", 3000);
				TimerIDArray[TimerIDCount++] = window.setTimeout('document.getElementById("message").style.zIndex = "0";', 4000);
			}
		}
	}
	else {
		count=0;		
		if(cartItem<AddToCartCount)
			window.setTimeout(""+AddToCartArray[(cartItem)]+"",1);
	}
	
	if(isReloadMiniCart && haveToRefreshMiniCart==true)	{
		ajx=new AJAXHandler();
		ajx.setTarget(document.location.protocol + '//'+window.location.hostname+'/minicartAjx.php');
		ajx.sendRequest("",'POST',2,"cart,cartprodlist","");
	}
}

function viewlargeimage(val1,val2,val3,val4) {
	if(document.getElementById("thumbForpLargeImage3")!==null)
		document.getElementById("thumbForpLargeImage3").className = '';
	if(document.getElementById("thumbForpLargeImage4")!==null)
		document.getElementById("thumbForpLargeImage4").className = '';
	if(document.getElementById("thumbForpLargeImage5")!==null)
		document.getElementById("thumbForpLargeImage5").className = '';
	document.getElementById(val3).className = 'on';
	
	var image = val1.replace(/&/ig,'xqzwozqx');
	var prodID = val2.replace(/&/ig,'xqzwozqx');
	var alt = val4.replace(/&/ig,'xqzwozqx');
	
	ajx=new AJAXHandler();
	ajx.setTarget('viewImageAjx.php');
	ajx.sendRequest("image="+image+"&prodId="+prodID+"&alt="+alt,'POST',1,"mainImage","");
}

function cartrowOn(val1,val2) {
	var prodid= "prod"+val1;
	var prodoptid= "prodopt"+val1;
	document.getElementById(prodid).className='on';
	if(document.getElementById(prodoptid)!=null)
		document.getElementById(prodoptid).className='on';
}

function cartrowOff(val1,val2) {
	var prodid= "prod"+val1;
	var prodoptid= "prodopt"+val1;
	var checkboxid= "delet"+val2;
	if(!(document.getElementById(checkboxid).checked)) {
		document.getElementById(prodid).className='';
		if(document.getElementById(prodoptid)!=null)
			document.getElementById(prodoptid).className='';
	}
}

function cartrowClick(val1,val2) {
	if(!isClickOnQty) {
		var checkboxid= "delet"+val2;
		if(document.getElementById(checkboxid).checked)	{
			document.getElementById(checkboxid).checked=false;
			cartrowOff(val1,val2);
		}
		else {
			document.getElementById(checkboxid).checked=true;
			cartrowOn(val1,val2);
		}
	}
	isClickOnQty = false;
}

function cartrowClick1() {
	isClickOnQty = true;
}

function submitfeedback() {
	var name = document.getElementById('name').value.replace(/^\s+|\s+$/g, '');
	var email = document.getElementById('email').value.replace(/^\s+|\s+$/g, '');
	var feedback = document.getElementById('feedback').value.replace(/^\s+|\s+$/g, '');
	
	if(name=="" || email=="" || feedback=="" || !isValidEmail(email)) {
		if(name=="") {
			alert("Please complete \"Name\".");
			document.getElementById('name').focus();
		}
		else if(email=="") {
			alert("Please complete \"Email Address\".");
			document.getElementById('email').focus();
		}
		else if(!isValidEmail(email)) {
			alert("Please enter a valid \"Email Address\".");
			document.getElementById('email').focus();
		}
		else if(feedback=="") {
			alert("Please complete \"Feedback\".");
			document.getElementById('feedback').focus();
		}
	}
	else
		document.mainform.submit();
}

function showSearchListAjx() {
	
	var keyword = document.findGift.stext.value.replace(/^\s+|\s+$/g, '');
	var occ = document.findGift.Occasion.options[document.findGift.Occasion.selectedIndex].value;
	var per = document.findGift.Personality.options[document.findGift.Personality.selectedIndex].value;
	var scat = document.findGift.scat.options[document.findGift.scat.selectedIndex].value;
	var price = document.findGift.price.options[document.findGift.price.selectedIndex].value;
		
	if(keyword!='') {
		ajx=new AJAXHandler();
		ajx.setTarget('showSearchListAjx.php');
		ajx.sendRequest("stext="+keyword+"&Occasion="+occ+"&Personality="+per+"&scat="+scat+"&price="+price,'POST',3,"searchResultContainer","");
	}
	else {
		document.getElementById("searchResultContainer").style.display = 'none';
	}
}

function changeWrappingMethod(val) {
	if(val=='noWrap') {
		document.getElementById("tblIndividualWrap").style.display = 'none';
//		document.getElementById("tblWrapAll").style.display = 'none';
	}
	else if(val=='individualWrap') {
		document.getElementById("tblIndividualWrap").style.display = 'block';
//		document.getElementById("tblWrapAll").style.display = 'none';
	}
/*	else if(val=='wrapAll') {
		document.getElementById("tblIndividualWrap").style.display = 'none';
		document.getElementById("tblWrapAll").style.display = 'block';
	}*/
}

function isValidEmail(val) {
	var emailVal = val;
	apos=emailVal.indexOf("@");
	dotpos=emailVal.lastIndexOf(".");
	
	if (apos<1||dotpos-apos<2 || !(emailVal.match(/^[\w\d!#$%&'*+-\/=?^`{|}~]+(\.[\w\d!#$%&'*+-\/=?^`{|}~]+)*@([a-z\d][-a-z\d]*[a-z\d]\.)*[a-z][-a-z\d]*[a-z]$/))) {
		return false;
	}
	else {
		return true;
	}
}

function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

Array.prototype.find = function(searchStr) {
	var returnArray = false;
	for (i=0; i<this.length; i++) {
	    if (typeof(searchStr) == 'function') {
	    	if (searchStr.test(this[i])) {
	    		if (!returnArray) { returnArray = []; }
	    		returnArray.push(i);
	    	}
	    } 
	    else {
	    	if (this[i]===searchStr) {
	    	 	if (!returnArray) { returnArray = []; }
	    	 	returnArray.push(i);
	    	}
	    }
	}
	return returnArray;
};

//source from : http://www.xfunda.com/index.php?option=com_content&view=article&id=55&catid=40:javascript&Itemid=75
function goto_top_timer() {
	var y = goto_top_type == 1 ? document.documentElement.scrollTop : document.body.scrollTop;
	var moveby = 15;
	
	y -= Math.ceil(y * moveby / 100);
	if (y < 0)
	y = 0;
	
	if (goto_top_type == 1)
		document.documentElement.scrollTop = y;
	else
		document.body.scrollTop = y;
	
	if (y == 0) {
		clearInterval(goto_top_itv);
		goto_top_itv = 0;
	}
}

//source from : http://www.xfunda.com/index.php?option=com_content&view=article&id=55&catid=40:javascript&Itemid=75
function goto_top() {
	if (goto_top_itv == 0) {
		if (document.documentElement && document.documentElement.scrollTop)
			goto_top_type = 1;
		else if (document.body && document.body.scrollTop)
			goto_top_type = 2;
		else
			goto_top_type = 0;
		
		if (goto_top_type > 0)
			goto_top_itv = setInterval('goto_top_timer()', 25);
	}
}

function initializeTwdk() {
	totTwdkEntries = document.getElementById('twdkContainer').getElementsByTagName('p').length;
	var height=0;
	var elem = null;
	var elemHeight = null;
	for(var i=0;i<totTwdkEntries;i++) {
		elem = document.getElementById('twdkContainer').getElementsByTagName('p')[i];
		elemHeight = elem.offsetHeight;
		if(elemHeight>height)
			height = elemHeight;
		if(i!=0)
			elem.style.display = 'none';
	}
	document.getElementById('twdkContainer').style.height = height+"px";
}

function slidingTwdk(elemNo) {
	hideElem = "twdk"+elemNo;
	showElem = (elemNo==totTwdkEntries)?'twdk1':'twdk'+(elemNo+1);
	fadeOut(hideElem,100,600);
	fadeIn(showElem,100,600);
	if(elemNo==totTwdkEntries)
		window.setTimeout('slidingTwdk(1)',5000);
	else
		window.setTimeout('slidingTwdk('+(elemNo+1)+')',5000);
}

//http://www.codeproject.com/KB/ajax/Flash_user_confirmation.aspx?display=Print
function setOpacity(id, level) {
    var element = document.getElementById(id); 
    element.style.display = 'block';
    element.style.zoom = 1;
    element.style.opacity = level;
    element.style.MozOpacity = level;
    element.style.KhtmlOpacity = level;
    element.style.filter = "alpha(opacity=" + (level * 100) + ");";
}

//http://www.codeproject.com/KB/ajax/Flash_user_confirmation.aspx?display=Print
function fadeOut(id, steps, duration,val) {
    var fadeOutComplete;       
    for (i = 0; i <= 1; i += (1 / steps)) {
    	TimerIDArray[TimerIDCount++] = setTimeout("setOpacity('" + id + "', "  + 
                (1 - i) + ")", i * duration);
      fadeOutComplete = i * duration;
    }
    TimerIDArray[TimerIDCount++] = setTimeout("hide('" + id + "')", fadeOutComplete);
}

//http://www.codeproject.com/KB/ajax/Flash_user_confirmation.aspx?display=Print
function fadeIn(id, steps, duration, interval, fadeOutSteps, fadeOutDuration) {  
   
	var fadeInComplete;
    for (i = 0; i <= 1; i += (1 / steps)) {
      var istr = i+"";
      istr = istr.substring(0, 4);
      if(istr=="0.99")
    	  i=1;
      TimerIDArray[TimerIDCount++] = setTimeout("setOpacity('" + id + "', " + i + ")", i * duration); 
      fadeInComplete = i * duration;             
    }
    //set the timeout to start after the fade in time and the interval to display the 
    //message on the screen have both completed

    TimerIDArray[TimerIDCount++] = setTimeout("fadeOut('" + id + "', " + fadeOutSteps + 
               ", " + fadeOutDuration + ")", fadeInComplete + interval);
}

//http://www.codeproject.com/KB/ajax/Flash_user_confirmation.aspx?display=Print
function hide(id) {
    document.getElementById(id).style.display = 'none';
}

function AJAXHandler()
{
	var target=null;
	var respVal=null;
	        	
	this.setTarget=function(target)
	{
		this.target=target;
	}
	 	
	this.createRequestObject=function(){
	 		
		var httpRequest=false;
		if(window.XMLHttpRequest){
			httpRequest=new XMLHttpRequest();
		}
		else if(window.ActiveXObject){
			httpRequest=new ActiveXObject("Microsoft.XMLHTTP");
		}
		else{
			alert("This page will not work as desired, lack of support from browser");
		}
			
		return httpRequest;
	}

	var xmlhttp=this.createRequestObject();
	var flag=null;
	var div=null;
	var divsOfPage=null;
	var divs=null;

	this.sendRequest=function(paramslist,method,flagPrm,divId,divSet)
	{
		params=paramslist; 		
		flag=flagPrm; 		
		div = divId;
		divsOfPage = divSet;
		
		if(method=='POST')
		{
			xmlhttp.open("POST",this.target,true);
			xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			xmlhttp.setRequestHeader("Content-length", params.length);
			xmlhttp.setRequestHeader("Connection", "close");
			xmlhttp.onreadystatechange=this.handleResponce;
			xmlhttp.send(params);
		}
		else if(method=='GET')
		{
			xmlhttp.open("GET",this.target+params,true);
			xmlhttp.onreadystatechange=this.handleResponce;
			xmlhttp.send(null);
		}
			 		    
	}

	this.handleResponce=function()
	{
		if(xmlhttp.readyState==4)
		{
			responce=xmlhttp.responseText;
		
			if(flag==1)
			{
				document.getElementById(div).innerHTML = responce;
			}
			
			else if(flag==2)
			{
				var divArr =  div.split(",");
				var responceArr = responce.split("{cartitems}");
				if(document.getElementById(divArr[0])!= null)
					if(document.getElementById(divArr[0]).type != 'hidden')	// there is a conflict in IE with a hidden text field with name "cart".
						document.getElementById(divArr[0]).innerHTML = responceArr[0];
				if(document.getElementById(divArr[1])!= null)
					document.getElementById(divArr[1]).innerHTML = responceArr[1];
				haveToRefreshMiniCart = false;
			}
			else if(flag==3)
			{
				document.getElementById(div).style.display='inline';
				document.getElementById(div).innerHTML = responce;
				document.getElementById("stext").focus();
			}
	   }
	   else
	   {
		   if(flag == 1)
		   {
			   document.getElementById(div).innerHTML = '<table border="0" cellspacing="0" cellpadding="0"><tr><td style="vertical-align:middle;width: 270px;height:275px;" align="center">Loading...</td></tr></table>';
		   }
		   
		   else if(flag==2)
		   {
			   var divArr =  div.split(",");
			   if(document.getElementById(divArr[0])!= null)
				   if(document.getElementById(divArr[0]).type != 'hidden')	// there is a conflict in IE with a hidden text field with name "cart".
					   document.getElementById(divArr[0]).innerHTML = '<div class="docHeadTitle">My Shopping Basket</div><div class="docHeadBox"><table border="0" cellspacing="0" cellpadding="0"><tr><td width="170" valign="top"><strong>Items</strong></td><td valign="top"></td></tr><tr><td width="170" valign="top"><strong>Total</strong></td><td valign="top" class="goToCheckout" style="font-size:11px;">Updating...</td></tr></table><div class="viewBasket"><a rel="nofollow" href="https://www.pangadgets.com/cart.php">View Basket </a></div></div>';
		   }
		   else if(flag==3)
		   {
			   document.getElementById(div).style.display='inline';
			   document.getElementById(div).innerHTML = '<div id="searchResults"><p>Loading...</p></div>';
			   document.getElementById("stext").focus();
		   }
	   }
 	}
}

function shippingAddressChange()
{
	shipCheckBox = document.getElementById('sameBilling');
	shippingAddress = document.getElementById('shipAddress');
	if(shipCheckBox.checked)
	{
		resetShipAddress()
		shippingAddress.style.display = "none";
	}
	else
	{
		shippingAddress.style.display = "";
	}
	
}
function resetShipAddress()
{
	document.forms.mainform.sname.value = ''
	document.forms.mainform.saddress.value = ''
	document.forms.mainform.scity.value = ''
	document.forms.mainform.sstate.value = ''
	document.forms.mainform.sstate2.value = ''
	document.forms.mainform.scountry.value = 'United Kingdom'
	document.forms.mainform.szip.value = ''
	document.forms.mainform.sphone.value = ''
}
