
var PFShowStockLevels=false;
var PFStockLevel=0;

function PFPriceCheck(field,unitprice,type,maxorder,minorder){
  if(type="int"){
    if ((checkInteger(field.value)) == false){ field.value = ""; }   
  }else{
    field.value = checkDecimal(field.value,4);
  }
  
  if (field.value!="" && parseFloat(field.value)>0){
     
     if(maxorder!=""){
     	if (parseInt(field.value)>parseInt(maxorder)){
	  field.value="1";
	  alert("Maximum Available for Order is : "+maxorder);           	
     	}
     }else{     
	if ((field.value*unitprice)>1000000){
	  field.value="1";
	  maxquantity=parseInt(1000000/unitprice);        
	  alert("Maximum Available for Order is : "+maxquantity);        
	}
     }     
     
  //}else if (parseFloat(field.value)=0){alert('t');
  
  }else if (field.value!="" && parseFloat(field.value)<=0){
    field.value="1";
  
  }
  
}


function PFpopulateComparsions(producttype) {
  var cookiecurrvalue=getCookie("PowerFrontProductComparisons");
     if(!cookiecurrvalue){  //nothing in cookie  
      
     }else{
	var cookiearray=cookiecurrvalue.split("::");
	var part_num=0;
	while (part_num < cookiearray.length)
	 {	  
	  highlightcheckbox=document.getElementById('comparisons'+cookiearray[part_num]);
	  if(highlightcheckbox){
	     highlightcheckbox.checked=true;
	  }
	  part_num+=1;
	}
     }
}

function PFAddCompare(checkbox,newvalue,maxcomp){
  
  var expiresdate=new Date(new Date().getTime()+86400000);  
  var cookiecurrvalue=getCookie("PowerFrontProductComparisons");
  
  if(checkbox.checked){

     if(!cookiecurrvalue){  //nothing in cookie  
      cookiecurrvalue=newvalue;   
     }else{
     
       var cookiearray=cookiecurrvalue.split("::");
	
       if(cookiearray.length>=maxcomp){
         alert("Maximum Allowed Comparisons is "+maxcomp);
       }else{
         if(cookiecurrvalue.indexOf(newvalue)>=0){ //check value does not already exist
         }else{
           cookiecurrvalue=cookiecurrvalue+"::"+newvalue; 
         } 
       }
     }
    
  }else{ //remove from cookie
    if(!cookiecurrvalue){ //nothing in cookie
    
    }else{
      if(cookiecurrvalue.indexOf(newvalue)>=0){  
        re = new RegExp("::"+newvalue,"gi")        
        cookiecurrvalue = cookiecurrvalue.replace(re,"");
        re = new RegExp("("+newvalue+"::)","gi")        
        cookiecurrvalue = cookiecurrvalue.replace(re,"");
        re = new RegExp("("+newvalue+")","gi")        
        cookiecurrvalue = cookiecurrvalue.replace(re,"");
      }
    
    }
    
  }
  
  if(!cookiecurrvalue){
    deleteCookie("PowerFrontProductComparisons","/");
    //alert("deletecookie");
  }else{
    setCookie("PowerFrontProductComparisons", cookiecurrvalue, expiresdate,"/");
    //alert("setcookie="+cookiecurrvalue);
  }  
}

function PFSwitchPrices(radio,currnum,formid,configtype){
    // get selected item
    pricedifference="";
    foundmatch=false;
    sumtodo="";
    selectedradio= document.getElementsByName(radio.name);
    
     if(configtype=="dropdown"){
        arraylength=selectedradio[0].length;
     }else{
        arraylength=selectedradio.length;     
     }

	for (i=0;i<arraylength;i++){
		if(configtype=="dropdown"){
		  if (selectedradio[0].options.selectedIndex==i){foundmatch=true;}else{foundmatch=false;}
		}else{
		  if (selectedradio[i].checked==true){foundmatch=true;}else{foundmatch=false;}
		}
		if(foundmatch){
			selecteditem=document.getElementById("ConfigOptPrice"+formid+"_"+currnum+"_"+i);
			if(selecteditem.innerHTML==""){
			  pricedifference="0";
			  sumtodo="+";
			}else{
			  pricedifference=selecteditem.innerHTML.replace(/<script(.*?)<\/script>/gi,"");
			  pricedifference=checkDecimal(pricedifference,2);
			  sumtodo=selecteditem.innerHTML.substring(1,2);
			}
		}
	}
	
	
	//loop and change current prices
	for (i=0;i<arraylength;i++){
	   selecteditem=document.getElementById("ConfigOptPrice"+formid+"_"+currnum+"_"+i);
	   if(configtype=="dropdown"){
	      if (selectedradio[0].options.selectedIndex==i){foundmatch=true}else{foundmatch=false}
	   }else{
	      if (selectedradio[i].checked==true){foundmatch=true}else{foundmatch=false}
	   }
	   if(foundmatch){
		  selecteditem.innerHTML="";
	   }else{
		  if(sumtodo=="+"){
			if(selecteditem.innerHTML==""){
			   if(parseFloat(pricedifference)==0){
				 selecteditem.innerHTML="";
			   }else{
			         selecteditem.innerHTML="(-"+PFFormatCurrency(pricedifference,"","","")+")";
			   }
			}else{
				itemprice=checkDecimal(selecteditem.innerHTML.replace(/<script(.*?)<\/script>/gi,""),2);						
				if(selecteditem.innerHTML.replace(/<script(.*?)<\/script>/gi,"").indexOf("-")>0){
				  itemprice=parseFloat(itemprice*-1)
				}
				newitemprice=parseFloat(itemprice)-parseFloat(pricedifference);
				
				if(newitemprice>0){
				  selecteditem.innerHTML="(+"+PFFormatCurrency(newitemprice,"","","")+")";
				}else if (newitemprice<0){
				  selecteditem.innerHTML="(-"+(PFFormatCurrency(newitemprice*-1,"","",""))+")";
				}else{
				  selecteditem.innerHTML="";
				}
			}
		  }else{
			if(selecteditem.innerHTML==""){
			   if(parseFloat(pricedifference)==0){
				 selecteditem.innerHTML="";
			   }else{
				 selecteditem.innerHTML="(+"+PFFormatCurrency(pricedifference,"","","")+")";
			   }
			}else{
				itemprice=checkDecimal(selecteditem.innerHTML.replace(/<script(.*?)<\/script>/gi,""),2);
				if(selecteditem.innerHTML.replace(/<script(.*?)<\/script>/gi,"").indexOf("-")>0){
				  itemprice=parseFloat(itemprice*-1)
				}
				newitemprice=parseFloat(itemprice)+parseFloat(pricedifference);
				if(newitemprice>0){
				  selecteditem.innerHTML="(+"+PFFormatCurrency(newitemprice,"","","")+")";
				}else if (newitemprice<0){
				  selecteditem.innerHTML="(-"+(PFFormatCurrency(newitemprice*-1,"","",""))+")";
				}else{
				  selecteditem.innerHTML="";
				}
			}
		  }
	  // }
	}
}

	if(pricedifference!=""){
	 currprice=checkDecimal(document.getElementById("Price"+formid).innerHTML.replace(/<script(.*?)<\/script>/gi,""),2);
         prevquantityvar=document.getElementById("prevquantity"+formid);
	 startquantityvar=document.getElementById("startquantity"+formid);	  
	 if(prevquantityvar.value!=""){
		currprice=parseFloat(currprice)/parseFloat(prevquantityvar.value);
	  }else{
         	currprice=parseFloat(currprice);
	  }
	  if(sumtodo=="-"){
		newprice=parseFloat(currprice)+parseFloat(pricedifference*-1);
	  }else{
		newprice=parseFloat(currprice)+parseFloat(pricedifference);
	  }
	  
	  if(startquantityvar.value!=""){
	  document.getElementById("Price"+formid).innerHTML=PFFormatCurrency(newprice*parseFloat(startquantityvar.value),"","","");
	  }else{
		document.getElementById("Price"+formid).innerHTML=PFFormatCurrency(newprice,"","","");
	  }
	}

	//loop through all selected items and add to basket
	//PFSubmitOrder(false,formid,configtype)

}

function PFChangeQuantities(formid){
	
	 currprice=checkDecimal(document.getElementById("Price"+formid).innerHTML.replace(/<script(.*?)<\/script>/gi,""),2);
	 prevquantityvar=document.getElementById("prevquantity"+formid);
	 startquantityvar=document.getElementById("startquantity"+formid);
	  if(prevquantityvar.value!=""){
	       currprice=parseFloat(currprice)/parseFloat(prevquantityvar.value);
	  }else{
	       currprice=parseFloat(currprice);
	  }
	  if(startquantityvar.value!=""){
	    document.getElementById("Price"+formid).innerHTML=PFFormatCurrency(currprice*parseFloat(startquantityvar.value),"","","");
	  }else{
	    document.getElementById("Price"+formid).innerHTML=PFFormatCurrency(currprice,"","","");
	  }
}

function PFCheckVariations(formid){
  //look for variations
  return true;
}

function PFSubmitOrder(submit,formid,target){

	var form = document.getElementById("fHtmlEditor"+formid);
	var quantity = document.getElementById("quantity"+formid);
	var startquantity = document.getElementById("startquantity"+formid);
	var mainproductid = document.getElementById("mainproductid"+formid);
	var productid = document.getElementById("productid"+formid);
	var formElements = form.elements;
	var allstock="";
	var allqty="";
	var curritem="";
	var newitem="";
	var variationcheck=false;
	if(submit){ //submit by image
	  variationcheck = PFCheckVariations()
	}else{ //submit via input submit button
	  variationcheck = true	
	}
	
	//loop through all form properties and find pfconfigoptid
	for (i=0; i<formElements.length; i++) {
		if(formElements[i].name.indexOf("pfconfigoptid")==0){
		  newitem=formElements[i].name.substring(13,formElements[i].name.indexOf("_"));
		  if(curritem!=newitem){
			curritem=newitem;
				selectedradio=formElements[i];	
				if(selectedradio){
				   if(selectedradio.type=="radio" || selectedradio.type==undefined){
				       selectedradiooption = document.getElementsByName(selectedradio.name);
					if(selectedradiooption.length){					   
					   for (j=0;j<selectedradiooption.length;j++){
					       if (selectedradiooption[j].checked==true){
						   allstock=allstock+selectedradiooption[j].value+", ";
						   if(startquantity.value!=""){
						     allqty=allqty+startquantity.value+", ";
						   }else{
						     allqty=allqty+"1, ";
						   }
						 }
					    }
					 }else{
					  singleradio=document.getElementById("singleoptionid"+newitem+"_"+formid);					  
					  if(singleradio){
						allstock=allstock+singleradio.value+", ";
						 if(startquantity.value!=""){
						   allqty=allqty+startquantity.value+", ";
						 }else{
						   allqty=allqty+"1, ";
						 }
				          }
					}
				   }else if(selectedradio.type=="select-one"){
				     allstock=allstock+selectedradio.options[selectedradio.selectedIndex].value+", ";
				     if(startquantity.value!=""){
				       allqty=allqty+startquantity.value+", ";
				     }else{
				       allqty=allqty+"1, ";
				     }
				   }
				}

		  }
		 }
	}
        if(mainproductid.value==""){ //no product found
           
           if(submit){
             alert("please select options!")
           }else{
             return false;
           }
        }else{	
		if(allstock!=""){
		    productid.value = mainproductid.value+", "+allstock.substring(0,allstock.length-2);
		}else{
		    productid.value = mainproductid.value;
		}
		
		//alert(form.productid.value);
		if((startquantity) && allqty!=""){
		  if(startquantity.value!=""){
			  quantity.value = startquantity.value+", "+allqty.substring(0,allqty.length-2);
			}else{
			  quantity.value = "1, "+allqty.substring(0,allqty.length-2);
			}
		}else if(allqty!=""){
			quantity.value="1, "+allqty.substring(0,allqty.length-2);
		}else{
			if(quantity.value!=""){
			}else{  
			  quantity.value=startquantity.value;
		        }
		}
		if(submit){
		  form.submit();
		}else{
		  return true;
		}
	}
	//return true;
}


function PFRemoveBlankOptions(fieldname){
   field=document.getElementById(fieldname);
   for (i=1; i<field.options.length; i++){
	 if(field.options[i].value=="" || field.options[i].value==null || field.options[i].value==undefined){
	   field.options[i]=null;
	   i=i-1;

	 }else{
	   //alert(field.options[i].value);
	 }
   }
}

function PFFindOptionCombo(totalvariations,formid,usestockonhand){

variationselectboxes = new Array(totalvariations);
//get selected options
   for (i=1;i<=totalvariations;i++){
     currvariation = document.getElementById("variationtype"+formid+"_"+i);
     if(currvariation){
       variationselectboxes[i-1]=currvariation.options[currvariation.selectedIndex].value;
     }else{
       variationselectboxes[i-1]="not found";
     }
   }
   //loop through all products and try to find a product match
   allvariationsarr = eval("allvariations"+formid);
   matchfound=-1;
   if(allvariationsarr){
	   for (i=0;i<allvariationsarr.length;i++){
		 c=15;
		 match=0;
		 for(j=1;j<=totalvariations;j++){
		   c=c+1;
		   if (allvariationsarr[i][c]==variationselectboxes[j-1]){
			 match=match+1;
		   }
		   c=c+1;
		 }
		 if (match==totalvariations){
		   matchfound=i;
		   break;
		 }
	   }
   }
   PFSetProduct(matchfound,formid,usestockonhand)
}

function PFSwapProduct(productid,formid,usestockonhand,totalvariations){
   allvariationsarr = eval("allvariations"+formid);
   matchfound=-1;
   if(allvariationsarr){
        
	for (i=0;i<allvariationsarr.length;i++){	
	   if (allvariationsarr[i][0]==productid){
	      matchfound=i;
	      break;
           }	
	}
   }  
   PFUpdateCombo(matchfound,formid,totalvariations);
   PFSetProduct(matchfound,formid,usestockonhand);
}

function PFUpdateCombo(matchfound,formid,totalvariations){   
   allvariationsarr = eval("allvariations"+formid);
   if(allvariationsarr){
     c=15;     
     for (i=1;i<=totalvariations;i++){
       c=c+1;
       currvariation = document.getElementById("variationtype"+formid+"_"+i);       
       if(currvariation){           
	   for (j=1;j<currvariation.length;j++){
	     if(currvariation.options[j].value==allvariationsarr[matchfound][c]){
	        currvariation.options[j].selected=true;	       
	     }
	   }
       }
       c=c+1;
     }
   }
}

function PFSetProduct(matchfound,formid,usestockonhand){
   
   form = document.getElementById("fHtmlEditor"+formid);
   if(matchfound>-1){
      pricedifference=0;
      currentprice = checkDecimal(document.getElementById("Price"+formid).innerHTML.replace(/<script(.*?)<\/script>/gi,""),2);
      currentprice = parseFloat(currentprice);
      
      myoriginalprice = document.getElementById("originalprice"+formid);
      startqty = document.getElementById("startquantity"+formid);
      if(myoriginalprice && startqty){
	pricedifference = parseFloat(currentprice) - (parseFloat(checkDecimal(myoriginalprice.value,2))*parseFloat(startqty.value));
	myoriginalprice.value = allvariationsarr[matchfound][5];
	newprice = (parseFloat(allvariationsarr[matchfound][5])*parseFloat(startqty.value)) + (parseFloat(pricedifference));
	
      }else{
        
        newprice=allvariationsarr[matchfound][5];
       
      }
      
      //update handling charge
     HandlingCharge = document.getElementById("HandlingCharge"+formid);
     HandlingChargeAmount = document.getElementById("HandlingChargeAmount"+formid);   
     if((HandlingCharge) && (HandlingChargeAmount)){
	     newhandling = parseFloat(allvariationsarr[matchfound][10]);
	     if(newhandling>0){
		HandlingChargeAmount.innerHTML=PFFormatCurrency(newhandling,"","","");
		HandlingCharge.style.display="";
	     }else{
		HandlingCharge.style.display="none";
		HandlingChargeAmount.innerHTML=PFFormatCurrency("0.00","","","");
	     }
     }      
     
     // hide Pre Sale Price - only show for items not on sale
     PreSalePrice = document.getElementById("PreSalePrice"+formid);
     WasAlias = document.getElementById("WasAlias"+formid);
     NowAlias = document.getElementById("NowAlias"+formid);
     PriceBreak = document.getElementById("PriceBreak"+formid);
     if(NowAlias){NowAlias.style.display="none";}
     if(WasAlias){
        WasAlias.style.display="none";
        if(PriceBreak){PriceBreak.style.display="none";}
     }
     if(PreSalePrice){
	   PreSalePrice.style.display="none";
	   PreSalePrice.innerHTML=PFFormatCurrency("0.00","","","");  
     }      

     // update price font color if sale price is true
     if (allvariationsarr[matchfound][4]=="true"){          
          //hide qty discount
          QuantityRange = document.getElementById("QuantityRange"+formid);
          if(QuantityRange){
            QuantityRange.style.display="none";
          }          
          PriceFontColor = document.getElementById("Price"+formid);
          SalePriceFontColor = document.getElementById("SalePriceFontColor"+formid);
          OnSale = document.getElementById("OnSale"+formid);
          if(OnSale){OnSale.style.display="";}
          if((SalePriceFontColor) && (PriceFontColor)){
             PriceFontColor.style.color=SalePriceFontColor.style.color;
          }     
     }else{
          OnSale = document.getElementById("OnSale"+formid);
          if(OnSale){OnSale.style.display="none";}          
          PriceFontColor = document.getElementById("Price"+formid);
          NormalPriceFontColor = document.getElementById("PriceFontColor"+formid);
          if((NormalPriceFontColor) && (PriceFontColor)){
            PriceFontColor.style.color=NormalPriceFontColor.style.color;
          }
     }
   
     //change presale price
     newpresaleprice = allvariationsarr[matchfound][9];
     if(newpresaleprice!=""){
       if(parseFloat(newpresaleprice)>0){
           if (allvariationsarr[matchfound][4]=="true"){ //if onsale do not show Now Alias
		  if(NowAlias){NowAlias.style.display="none";}
           }else{
           	  if(NowAlias){NowAlias.style.display="";}
           }
           if(WasAlias){
               WasAlias.style.display="";
               if(PriceBreak){PriceBreak.style.display="";}           
  	   }
  	   if(PreSalePrice){
	      PreSalePrice.innerHTML=PFFormatCurrency(newpresaleprice,"","","");
	      PreSalePrice.style.display="";
	   }	 
       }
     }   
   
     //update productid
     form.mainproductid.value = allvariationsarr[matchfound][0];

     //change price
     document.getElementById("Price"+formid).innerHTML = PFFormatCurrency(newprice,"","","");

     NotAvailable = document.getElementById("NotAvailable"+formid);
     if(NotAvailable){NotAvailable.style.display="none";}
     if(usestockonhand=="true" || usestockonhand=="True"){
       if(allvariationsarr[matchfound][6]>0){
	 //show stock
	 OutOfStock = document.getElementById("OutOfStock"+formid);
	 if(OutOfStock){OutOfStock.style.display="none";}
	 InStock = document.getElementById("InStock"+formid);
	 if(InStock){
	   StockLevel = document.getElementById("StockLevel"+formid);
	   StockLevel.innerHTML=allvariationsarr[matchfound][6];
	   InStock.style.display="";
	 }
	 AddToBasket = document.getElementById("AddToBasket"+formid);
	 if(AddToBasket){AddToBasket.style.display="";}
       }else{
	 OutOfStock = document.getElementById("OutOfStock"+formid);
	 if(OutOfStock){OutOfStock.style.display="";}
	 InStock = document.getElementById("InStock"+formid);
	 if(InStock){
	   InStock.style.display="none";
	   StockLevel = document.getElementById("StockLevel"+formid);
	   StockLevel.innerHTML="0";
	 }
	 AddToBasket = document.getElementById("AddToBasket"+formid);
	 if(AddToBasket){AddToBasket.style.display="none";}
       }
       mx = document.getElementById("maxcanorder"+formid);
       if(mx){         
         if(parseFloat(allvariationsarr[matchfound][6]) < parseFloat(allvariationsarr[matchfound][7])){ 
	   mx.value=allvariationsarr[matchfound][6];	   
	 }else{
	   mx.value=allvariationsarr[matchfound][7];
	 }
       }
     }else{ //not using stock on hand
       
       mx = document.getElementById("maxcanorder"+formid);
       if(mx){
      	   mx.value=allvariationsarr[matchfound][7];
       }
       AddToBasket = document.getElementById("AddToBasket"+formid);
       if(AddToBasket){AddToBasket.style.display="";}
       //stocklevel may still be shown
	 InStock = document.getElementById("InStock"+formid);
	 if(InStock){
		 if(InStock.style.display=="" || PFShowStockLevels){
		          InStock.style.display="";
			   StockLevel = document.getElementById("StockLevel"+formid);
			   if(allvariationsarr[matchfound][6]>0){
			     StockLevel.innerHTML=allvariationsarr[matchfound][6];	   
			   }else{
			     StockLevel.innerHTML="0";
			   }
		 }
	 }
     }
     
     //change displayimage1
     PFSwapLayers("Image1_"+formid+"_","Image1_"+formid+"_"+matchfound,300)     
     //change productcode
     ProductCode = document.getElementById("ProductCode"+formid);
     newproductcode = allvariationsarr[matchfound][2];
     if(ProductCode && newproductcode!=""){
       ProductCode.innerHTML=newproductcode;
     }
     return true;

   }else{ //no match found

     //display please select option
     form.mainproductid.value = "";     
     OutOfStock = document.getElementById("OutOfStock"+formid);
     if(OutOfStock){OutOfStock.style.display="none";}
     InStock = document.getElementById("InStock"+formid);
     if(InStock){
       if(InStock.style.display==""){PFShowStockLevels=true}       
       InStock.style.display="none";
     }
     AddToBasket = document.getElementById("AddToBasket"+formid);
     if(AddToBasket){AddToBasket.style.display="none";}   
     NotAvailable = document.getElementById("NotAvailable"+formid);
     if(NotAvailable){NotAvailable.style.display="";}
     return false;
   }
}

function PFCheckStock(productid){
	var PFxmlHttp;
	if(productid!=""){
		PFxmlHttp=PFGetXmlHttpObject();
		if (PFxmlHttp==null)
		  {
		    alert ("Sorry, this function is not possible because your browser does not support AJAX!");
		    return;
		  } 
		  var url = siteurl +"/scripts/getstocklevel.asp?productid="+productid;
		  PFxmlHttp.onreadystatechange=function(){
			  if(PFxmlHttp.readyState==4){ 
			      PFStockLevel=PFxmlHttp.responseText;    
			  }		  
		  }
		  PFxmlHttp.open("GET",url,true);
		  PFxmlHttp.send(null);
	}
}


function PFShowVariations(webpage,querystr,formid,styleclass,screenmaskopacity) {

        //set width of Product Container
         ProductContainer = document.getElementById("ProductContainer"+formid);
	if(ProductContainer.offsetHeight){
	   ProductContainer.style.height= ProductContainer.offsetHeight+"px";
	 }
	if(ProductContainer.offsetWidth){
	   ProductContainer.style.width= ProductContainer.offsetWidth+"px";
	 }
	 
	PFAddMask(screenmaskopacity);        
        coords = PFGetElementPosition("ProductContainer"+formid);
        var productlayer = document.createElement('div');
        productlayer.style.width = ProductContainer.offsetWidth+"px";
        productlayer.style.position = "absolute";
        productlayer.style.top = coords[1] + "px";
        productlayer.style.left = coords[0] + "px";
        productlayer.style.zIndex = 100000;
        productlayer.id = "ProductPopUp"+formid;
        document.body.appendChild(productlayer);
        FormContainer = document.getElementById("fHtmlEditor"+formid);
	productlayer.appendChild(FormContainer);
	 ProductTable = document.getElementById("ProductTable"+formid);
	 if(ProductTable){
           if(!ProductTable.style.border){
             ProductTable.style.border = "1px #000000 dashed";
           }
         }         
       //PFelementid="ProductVariations"+formid;
       ShowVariations = document.getElementById("ShowVariations"+formid);
       if(ShowVariations){ShowVariations.style.display="none";}
       PFdisplayid=formid;
       //PFtempURL=siteurl+'/scripts/getjavascript.asp';
       
       addjavascript=siteurl+'/scripts/getjavascript.asp?id='+formid;
       
       SlideLayerDiv = document.getElementById("SlideLayerDiv"+formid);     
       if(!SlideLayerDiv){     //AJAX Load
          PFInsertExternalHTML("ProductVariations"+formid,webpage,querystr+"&displayid="+formid+"&style="+styleclass,addjavascript);
       }else{
  	  layertomove=eval("slidelayer"+formid);
 	  layertomove._endfunction(null);
	  layertomove.slidedown();
       }
}

function PFHideVariations(formid){
     layertomove=eval('slidelayer'+formid);
     PFdisplayid=formid;
     layertomove._endfunction(PFShowVariationTrigger);
     layertomove.slideup();
}

PFShowVariationTrigger = function() {
     
      PFRemoveMask();
      ProductContainer = document.getElementById("ProductContainer"+PFdisplayid);
      ProductContainer.appendChild(document.getElementById("fHtmlEditor"+PFdisplayid));
      document.body.removeChild(document.getElementById("ProductPopUp"+PFdisplayid));
      // show add quick buy button
      ShowVariations = document.getElementById("ShowVariations"+PFdisplayid);
      if(ShowVariations){ShowVariations.style.display="block";}
      	
      ProductTable = document.getElementById("ProductTable"+PFdisplayid);
      if(ProductTable){
        if(ProductTable.style.borderStyle.indexOf("dashed")>=0){
            ProductTable.style.border = "";
         }
       }
}

function PFSwapLayers(id1,id2,millisec) {
    //speed for each frame
    var speed = Math.round(millisec / 100);
    var timer = 0;
    var img1 = document.getElementById(id1);
    var img2 = document.getElementById(id2);
    var newtimer;    
    if(img1 && img2){       
    
      //alert(img1.innerHTML)
      //alert(img2.innerHTML)    
    
       if((img1.innerHTML==img2.innerHTML) || (img2.innerHTML=="")){
          img1.style.display='block';
       }else{            
    	    for(i = 100; i >= 0; i--) {
	       newtimer = setTimeout("PFChangeOpac(" + i + ",'" + id1 + "')",(timer * speed));
	       timer++;
	       if (i==0){ //swap layers	         
		 newtimer = setTimeout("PFSwapHTML('"+id1+"','"+id2+"');"+id1+".style.display='block';",(timer * speed));
		 timer++;
		 for(j = 0; j <= 100; j++)
		 {
		    newtimer = setTimeout("PFChangeOpac(" + j + ",'" + id1 + "')",(timer * speed));
		    timer++;
		 }
	       }       
	    }
        }
     }
     clearTimeout(newtimer);   
}

function PFSwapHTML(myid1,myid2){
    var object1 = document.getElementById(myid1);
    var object2 = document.getElementById(myid2);
    if(object1 && object2){ object1.innerHTML = object2.innerHTML;}     
}

function PFanimateLayer(divId, animatetime, initstate){
	this.divId=divId
	this.endfuncname = null
	this.divObj=document.getElementById(divId)
	this.divObj.style.overflow="hidden"
	this.timelength=animatetime
	this.initstate=initstate
	if(initstate=="expanded"){
	  this.isExpanded="yes"
	  this.divObj.style.position="relative"
  	  this.divObj.style.display="block"
	  this.divObj.style.visibility="visible"
	}else{ //hide off screen
	  this.isExpanded="no"
	  this.divObj.style.position="absolute"	  
          this.divObj.style.left="-3000px";	  
	}
	this.contentheight=parseInt(this.divObj.style.height)
	var thisobj=this
	if (isNaN(this.contentheight)){
		thisobj._getheight();
	}else{ 

	}	
	if(this.initstate=="expand"){
	   thisobj.slidedown();
	}	
}

PFanimateLayer.prototype._getheight=function(){
	this.divObj.style.display="block"
	this.divObj.style.visibility="visible"
       	this.contentheight=this.divObj.offsetHeight
	if (this.isExpanded!="yes"){ 
	   this.divObj.style.height=1;
	}else{ 
	   this.divObj.style.height=this.contentheight+"px";
	}	
}

PFanimateLayer.prototype._endfunction=function(funcobject){
	this.endfuncname = funcobject;
}

PFanimateLayer.prototype._slideengine=function(direction){
	var elapsed=new Date().getTime()-this.startTime //get time animation has run
	var thisobj=this
	if (elapsed<this.timelength){ //if time run is less than specified length    
		var distancepercent=(direction=="down")? PFanimateLayer.curveincrement(elapsed/this.timelength) : 1-PFanimateLayer.curveincrement(elapsed/this.timelength)
		if(parseInt(distancepercent * this.contentheight) > 0){
	          this.divObj.style.height=parseInt(distancepercent * this.contentheight) +"px"
	        }
		this.runtimer=setTimeout(function(){thisobj._slideengine(direction)}, 10)
	}
	else{ //if animation finished
	        if(direction=="down"){
	          this.divObj.style.height=this.contentheight+"px";
	          this.divObj.style.overflow="";
	        }else{ //move layer off screen
		  this.divObj.style.height=1;
		  this.divObj.style.position="absolute";
		  this.divObj.style.left="-3000px";
		  
		}
		//this.isExpanded=(direction=="down")? "yes" : "no" //remember whether content is expanded or not
		if(this.endfuncname!=null){
		  this.endfuncname()
		}
		this.runtimer=null
	}
}

PFanimateLayer.prototype.slidedown=function(){
	if (typeof this.runtimer=="undefined" || this.runtimer==null){ //if animation isn't already running or has stopped running	    
		if (isNaN(this.contentheight)) //if content height not available yet (until window.onload)
			alert("Please wait until document has fully loaded then click again")
		else if (parseInt(this.divObj.style.height)==1){ //if content is collapsed
			this.startTime=new Date().getTime() //Set animation start time			
	                this.divObj.style.position="relative";
	                this.divObj.style.left="0px";
			this._slideengine("down");
		}
	}
}

PFanimateLayer.prototype.slideup=function(){
	if (typeof this.runtimer=="undefined" || this.runtimer==null){ //if animation isn't already running or has stopped running
		if (isNaN(this.contentheight)) //if content height not available yet (until window.onload)
			alert("Please wait until document has fully loaded then click again")
		else if (parseInt(this.divObj.style.height)==this.contentheight){ //if content is expanded
			this.startTime=new Date().getTime();
			this.divObj.style.overflow="hidden";
			this._slideengine("up");
		}
	}
}

PFanimateLayer.prototype.slideit=function(){
	if (isNaN(this.contentheight)) //if content height not available yet (until window.onload)
		alert("Please wait until document has fully loaded then click again")
	else if (parseInt(this.divObj.style.height)==1)
		this.slidedown()
	else if (parseInt(this.divObj.style.height)==this.contentheight)
		this.slideup()
}

PFanimateLayer.curveincrement=function(percent){
	return (1-Math.cos(percent*Math.PI)) / 2 //return cos curve based value from a percentage input
}

var PFUpdateProductRegistry = new Array();
var PFUpdateProductInterval = setInterval("PFUpdateProductData(PFUpdateProductRegistry);",50);

function PFUpdateProduct(counter, productid, immediate)
{
	var allvariations = "";
	try
	{
		if(eval("allvariations"+counter)) allvariations = "allvariations"+counter;
	}
	catch(e) {}

	if(immediate && PFSwapProduct)
	{
		PFUpdateProductData(new Array(new Array(counter,productid,allvariations)));
	}
	else
	{
		PFUpdateProductRegistry[PFUpdateProductRegistry.length] = new Array(counter,productid,allvariations);
		elem = document.getElementById("Price"+counter);		if(elem) elem.style.visibility = "hidden";
		elem = document.getElementById("PreSalePrice"+counter);	if(elem) elem.style.visibility = "hidden";
		elem = document.getElementById("NowAlias"+counter);		if(elem) elem.style.visibility = "hidden";
		elem = document.getElementById("WasAlias"+counter);		if(elem) elem.style.visibility = "hidden";
		elem = document.getElementById("PriceBreak"+counter);	if(elem) elem.style.visibility = "hidden";
		elem = document.getElementById("OnSale"+counter);		if(elem) elem.style.visibility = "hidden";
	}
}

function PFUpdateProductData(productlist)
{
	if(productlist.length == 0 || !PFSwapProduct) return;

	var p1 = "";
	var p2 = "";
	var p3 = "";
	
	for(var i = 0; i < productlist.length; i++) 
	{
		if(productlist[i].length >= 2)
		{
			p1 += ((p1=="")?(""):(",")) + productlist[i][0];
			p2 += ((p2=="")?(""):(",")) + productlist[i][1];
			if(i>0) p3+="|";
			allvariations = (productlist[i][2]!="")?eval(productlist[i][2]):null;
			if(allvariations)
			{
				for(var j=0; j<allvariations.length; j++)
				{
					if(j>0) p3+=",";
					p3+=allvariations[j][0];
				}
			}
		}
	}
	
	PFUpdateProductRegistry.length = 0;
	
	if(p1 != "" && p2 != "")
	{
		var xmlhttp = PFGetXmlHttpObject();
		if(xmlhttp)
		{
			xmlhttp.onreadystatechange = function()
			{
				try
				{
					if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
					{
						var xmldoc = xmlhttp.responseXML;
						if(xmldoc)
						{
							var productid, counter, price, wasprice, instore, onsale, onspecial, stock, maxorder;
							var elemPrice, elemNowAlias, elemPreSalePrice, elemWasAlias, elemPriceBreak, elemOnSale, elem, elemStockLevel;
							var showWasAlias, numPrice, numWasPrice;
							var timeoutScript, nodeText, nodelist;
							var useoutofstock, totalvariationtypes;
							var swapstr = "";
							
							nodelist = xmldoc.getElementsByTagName("useoutofstock");
							if(nodelist.length == 1)
							{
								if(nodelist[0].textContent) useoutofstock = nodelist[0].textContent
								else if(nodelist[0].text) useoutofstock = nodelist[0].text
								else useoutofstock = "False";
							}
							else
							{
								useoutofstock = "False";
							}

							var productnodelist = xmldoc.getElementsByTagName("product");
							for(var i=0; i<productnodelist.length; i++)
							{
								timeoutScript = "";
								productid = productnodelist[i].getAttribute("productid");
								counter = productnodelist[i].getAttribute("counter");
								index = productnodelist[i].getAttribute("index");
								elemPrice = document.getElementById("Price"+counter);
								elemOriginalPrice = document.getElementById("originalprice"+counter);
								if(!index)
								{
									elemNowAlias = document.getElementById("NowAlias"+counter);
									elemPreSalePrice = document.getElementById("PreSalePrice"+counter);
									elemWasAlias = document.getElementById("WasAlias"+counter);
									elemPriceBreak = document.getElementById("PriceBreak"+counter);
									elemOnSale = document.getElementById("OnSale"+counter);
									elemStockLevel = document.getElementById("StockLevel"+counter);
								}
								
								price = "";
								wasprice = "";
								instore = "";
								onsale = false;
								onspecial = false;
								stock = "";
								maxorder = "";
								handling = "";
								
								for(var j=0; j<productnodelist[i].childNodes.length; j++)
								{
									node = productnodelist[i].childNodes[j];
									if(node.textContent) nodeText = node.textContent
									else if(node.text) nodeText = node.text
									else nodeText = "";
									switch(node.nodeName)
									{
										case "price":		price = nodeText; break;
										case "wasprice":	wasprice = nodeText; break;
										case "instore":		instore = nodeText; break;
										case "onsale":		onsale = (nodeText=="True")?"true":"false"; break;
										case "onspecial":	onspecial = (nodeText=="True")?"true":"false"; break;
										case "stock":		stock = nodeText; break;
										case "maxorder":	maxorder = nodeText; break;
										case "handling":	handling = nodeText; break;
									}
								}
								if(index)
								{
									allvariations = eval("allvariations"+counter);
									if(allvariations)
									{
										allvariations[index][4] = onsale;
										allvariations[index][5] = price;
										allvariations[index][6] = stock;
										allvariations[index][7] = maxorder;
										allvariations[index][8] = instore;
										allvariations[index][9] = wasprice;
										allvariations[index][10] = handling;
									}
									if(swapstr.indexOf("|"+productid+"|"+counter) == -1)
									{
										totalvariationtypes = 0;
										while(document.getElementById("variationtype"+counter+"_"+(totalvariationtypes+1)))
										{
											totalvariationtypes++;
										}
										timeoutScript += "PFSwapProduct(\""+productid+"\",\""+counter+"\",\""+useoutofstock+"\",\""+totalvariationtypes+"\");";
										swapstr += "|"+productid+"|"+counter;
									}
								}
								else
								{
									numPrice = Math.round(parseFloat(price),2);
									if(wasprice != "") numWasPrice = Math.round(parseFloat(wasprice),2)
									else numWasPrice = numPrice;
									
									showWasAlias = (numPrice < numWasPrice);
									
									if(elemWasAlias) elemWasAlias.style.display = showWasAlias?"":"none";
									if(elemNowAlias) elemNowAlias.style.display = (showWasAlias && onsale!="true")?"":"none";
									if(elemOnSale) elemOnSale.style.display = (onsale=="true")?"":"none";
									
									if(elemPreSalePrice)
									{
										elemPreSalePrice.innerHTML = PFFormatCurrency(wasprice,"","","");
										elemPreSalePrice.style.display = showWasAlias?"":"none";
									}
									
									if(elemStockLevel) elemStockLevel.innerHTML = stock;
									
									if(elemPriceBreak) elemPriceBreak.style.display = showWasAlias?"":"none";
								}

								if(allvariations && index)
								{
									if(productid == allvariations[index][0])
									{
										if(elemPrice) elemPrice.innerHTML = PFFormatCurrency(price,"","","");
										if(elemOriginalPrice) elemOriginalPrice.value = price;
									}
								}
								else
								{
									if(elemPrice) elemPrice.innerHTML = PFFormatCurrency(price,"","","");
									if(elemOriginalPrice) elemOriginalPrice.value = price;
								}
								
								if(document.getElementById("Price"+counter)) 		timeoutScript += "document.getElementById(\"Price"+counter+"\").style.visibility = \"\";";
								if(document.getElementById("PreSalePrice"+counter))	timeoutScript += "document.getElementById(\"PreSalePrice"+counter+"\").style.visibility = \"\";";
								if(document.getElementById("NowAlias"+counter)) 	timeoutScript += "document.getElementById(\"NowAlias"+counter+"\").style.visibility = \"\";";
								if(document.getElementById("WasAlias"+counter)) 	timeoutScript += "document.getElementById(\"WasAlias"+counter+"\").style.visibility = \"\";";
								if(document.getElementById("PriceBreak"+counter)) 	timeoutScript += "document.getElementById(\"PriceBreak"+counter+"\").style.visibility = \"\";";
								if(document.getElementById("OnSale"+counter)) 		timeoutScript += "document.getElementById(\"OnSale"+counter+"\").style.visibility = \"\";";

								if(timeoutScript!="") setTimeout(timeoutScript,0);
							}

							nodelist = xmldoc.getElementsByTagName("script");
							timoutScript = "";
							if(nodelist.length>0)
							{
								for(var i=0; i<nodelist.length; i++)
								{
									if(nodelist[0].textContent)
									{
										if(nodelist[0].textContent!="") timeoutScript += nodelist[0].textContent;
									}
									else if(nodelist[0].text)
									{
										if(nodelist[0].text!="") timeoutScript += nodelist[0].text;
									}
								}
							}

							if(timeoutScript!="") setTimeout(timeoutScript,0);
						}
					}
				}
				catch(e){ }
			}
			xmlhttp.open("POST", siteurl+"/xml/xml-updateproductdata.asp?sid="+Math.random(), true);
			xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			xmlhttp.send("counters=" + p1 + "&products=" + p2 + "&allvariations=" + p3);
		}
	}
}

if(window.addEventListener)
{
	window.addEventListener("load", function() { clearInterval(PFUpdateProductInterval); if(PFUpdateProductRegistry.length > 0) { PFUpdateProductData(PFUpdateProductRegistry); } }, false);
}
else if(window.attachEvent)
{
	window.attachEvent("onload", function() { clearInterval(PFUpdateProductInterval); if(PFUpdateProductRegistry.length > 0) { PFUpdateProductData(PFUpdateProductRegistry); } });
}