var req;
var addrReq;
var addrListReq;
var showReq;
var ns4 = (document.layers) ? true : false;
var ie4 = (document.all && !document.getElementById) ? true : false;
var ie5 = (document.all && document.getElementById) ? true : false;
var ns6 = (!document.all && document.getElementById) ? true : false;
var shipping=0
var subtotal=0
var tax=0

function keyinit()  {
    if (document.addEventListener)   {
       document.addEventListener("keydown",keydown,false);
    }else if (document.attachEvent){
       document.attachEvent("onkeydown", keydown);
    }else{
       document.onkeydown= keydown;
    }
}
function keydown(e)  {
   if (!e) {
       e = event
   }
   if (e.keyCode == 13) {
       searchItems()
      if (e.preventDefault){
         e.preventDefault();
      }
      if (e.stopPropagation){
         e.stopPropagation();
      }
      return false;
   }
}
function callPage(pageUrl, divElementId, loadinglMessage, pageErrorMessage) {
     document.getElementById(divElementId).innerHTML = loadinglMessage;
     req=GetXmlHttpObject();
 
     req.onreadystatechange = function() {responsefromServer(divElementId, pageErrorMessage);};
     req.open("GET",pageUrl,true);
     req.send(null);
  }
function responsefromServer(divElementId, pageErrorMessage) {
   var output = '';
   if(req.readyState == 4) {
      output = req.responseText;
      if(req.status == 200) {
         document.getElementById(divElementId).innerHTML = output;
         } else {
         document.getElementById(divElementId).innerHTML = pageErrorMessage+"\n"+output;
         }
      }
  }
function responsefromServerX(divElementId, pageErrorMessage) {
   var output = '';
   if(req.readyState == 4) {
      output = req.responseText;
        
      if(req.status == 200) {
     
         document.getElementById(divElementId).value = output;
         } else {
         document.getElementById(divElementId).value = pageErrorMessage+"\n"+output;
         }
      }
  }
function callPageWReq(pageURL, divElementID, loadingMessage, pageErrorMessage, theReq) {
    document.getElementById(divElementID).innerHTML=loadingMessage;
    theReq=GetXmlHttpObject();
    theReq.onreadystatechange=function() {responsefromServerWReq(divElementID,pageErrorMessage,theReq)}
    theReq.open("GET",pageURL,true)
    theReq.send(null);
}
function responsefromServerWReq(divElementId, pageErrorMessage, theReq) {
   var output = '';
   if(theReq.readyState == 4) {      
      if(theReq.status == 200) {
         output = theReq.responseText;      
         document.getElementById(divElementId).innerHTML = output;
       } else {
         document.getElementById(divElementId).innerHTML = pageErrorMessage+"\n"+output;
       }
   }
}

/* this function is for tab panels */
function activeTab(tab,destpage,destdiv)
{   	

	document.getElementById("tab"+tab).className = "active";
	if(destdiv=='content')
	{
		show(false,'tabdiv');
		show(true,'content');
	}else{
		show(true,'tabdiv');
		show(false,'content');
	}	
	callPage(destpage, destdiv, '<img src=\"imgs/loading.gif\" /> content is loading, please wait...', 'error in loading page <img src=\"imgs/error_caution.gif\" />');		
}

function aPostForm(formName,divElementId) {
    var pageErrorMessage='Error in Loading page';
    req=GetXmlHttpObject();
    pagename="login1.aspx";
    passData='&dowhat=Login';
    if (null == eval("document."+formName+".UserName.value")) {
        frmuser="";
    }else{
        frmuser=eval("document."+formName+".UserName.value");
    }    
    if (null == eval("document."+formName+".Password.value")) {
        frmpassword="";   
    }else{
        frmpassword=eval("document."+formName+".Password.value");
    }   
    
    passData='dowhat=Login';
    passData=passData+'&Password='+escape(frmpassword);
    passData=passData+'&UserName='+escape(frmuser);

    req.open("POST",pagename,true); 
    req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    req.onreadystatechange = function() {responsefromServer(divElementId, pageErrorMessage);}; 
    req.send(passData);
}

function aQuerystringForm(formName,divElementId){
    var pageErrorMessage='Error in Loading page';
    req=GetXmlHttpObject();
    pagename="survey.aspx";  
    frmmember=eval("document."+formName+".member.value");
    frmsurveyid=eval("document."+formName+".surveyid.value");
    for (var i=0; i < document.frmSurvey.answer.length; i++)
    {
    if (document.frmSurvey.answer[i].checked)
      {
      var rad_val = document.frmSurvey.answer[i].value;
      }
    }
    frmanswer = rad_val;
    passData='member='+escape(frmmember);
    passData=passData+'&answer='+escape(frmanswer);
    passData=passData+'&surveyid='+escape(frmsurveyid);
    passData=passData+'&dowhat=save';
    
    req.open("POST",pagename,true); 
    req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    req.onreadystatechange = function() {responsefromServer(divElementId, pageErrorMessage);}; 
    req.send(passData);
}
function singleCall(destpage,destdiv) {
    callPage(destpage,destdiv,'<img src=\"imgs/loading.gif\" /> content is loading, please wait...', 'error in loading page');
}

function nothingfunction(){
}

function GetXmlHttpObject() {
   var xmlHttp=null;
   try  { // Firefox, Opera 8.0+, Safari
     xmlHttp=new XMLHttpRequest();
   }
   catch (e) {  // Internet Explorer
      try {
        xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      }
      catch (e) {
        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
   }
   return xmlHttp;
}


function showme(divname){
	showdis=document.getElementById(divname).innerHTML
	document.getElementById('showmetext').value=showdis
}
function calPickDay(theday,themonth,theyear) {
    destpage="quickCalendar.aspx?monum=" + themonth + "&daynum=" + theday + "&yearnum=" + theyear
    callPage(destpage, 'calspan', '<img src=\"imgs/loading.gif\" /> content is loading, please wait...', 'error in loading page <img src=\"imgs/error_caution.gif\" />');		

}
function popupme() {
    alert("Got Here");
}
 function EditLine(formName,divElementId,pagename,editID) {
    var pageErrorMessage='Error in Loading page';
    req=GetXmlHttpObject();    
    passData='dowhat=Edit';
    passData=passData+'&editID='+editID;
    req.open("POST",pagename,true); 
    req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    req.onreadystatechange = function() {responsefromServer(divElementId, pageErrorMessage);}; 
    req.send(passData);
}

function gotoPage(pagename)  {
    parent.location = pagename
}

function show(sw,obj) {
	// show/hide the divisions
	if (sw && (ie4 || ie5) ) document.all[obj].style.visibility = 'visible';
	if (!sw && (ie4 || ie5) ) document.all[obj].style.visibility = 'hidden';
	if (sw && ns4) document.layers[obj].visibility = 'visible';
	if (!sw && ns4) document.layers[obj].visibility = 'hidden';
	if (sw && ns6) document.getElementById(obj).style.visibility = 'visible';
	if (!sw && ns6) document.getElementById(obj).style.visibility = 'hidden';
}
function openeditX(HT,WT,sbars) {
	var winX = (document.all)?window.screenLeft:window.screenX;
	var winY = (document.all)?window.screenTop:window.screenY;
	theX=parseFloat(winX)+parseFloat(100)
	theY=parseFloat(winY)+parseFloat(50)
	var W = "height="+HT+",width="+WT+",scrollbars="+sbars+",left="+theX+",top="+theY
	editwinX=open("blank.html","editwinX",W)
	return true
}
followme=""
function getSubCats(catID,level,text) {
    if (level>2) {
       parts=followme.split(">>")
       followme=""       
       for (x=1;x<=level-2;x++) {
           followme=followme + ">>" + parts[x]
       }
    } else {
       followme=""
    }
    //alert(catID + "-" + level + "-" + text)
    text=text.replace("~39","'")
    followme=followme + ">><a class=follow href=\"javascript:getSubCats(" + catID + "," + level +",'"+ escape(text) +"')\">" + text + "</a>&nbsp;&nbsp;"
    followDiv=document.getElementById("followme")
    followDiv.innerHTML=followme
    pageURL="bp_subcats.aspx?level=" + level + "&catID=" + catID    
    callPage(pageURL,"submaincontent","Loading","Unable to Locate SubCats")
}

function getitem(itemCode, itemDesc) {
    itemDesc=itemDesc.replace("~39","'")
    followme=followme +">>" + itemCode + "-" + itemDesc
    
    followDiv=document.getElementById("followme")
    followDiv.innerHTML=followme 
    
    pageURL="item.aspx?itemnum=" + itemCode    
    callPage(pageURL,"mainsec","Loading","Unable to Find Item")
}
function getaltitem(itemCode, itemDesc, oldItem) {
    itemDesc=itemDesc.replace("~39","'")
    // followme=followme +">><span class=title>" + itemCode + "-" + itemDesc + "</span>"
    followme=">><span class=title>" + itemCode + "-" + itemDesc + "</span>"
    
    followDiv=document.getElementById("followme")
    followDiv.innerHTML=followme 
    
    pageURL="bp_viewproduct.aspx?itemnum=" + itemCode + "&oldItem=" + oldItem    
    callPage(pageURL,"submaincontent","Loading","Unable to Find Item")
}

function getANitem() {    
    itemCode=document.getElementById("searchtext").value;
    pageURL="item.aspx?itemnum=" + itemCode    
    callPage(pageURL,"mainsec","Loading","Unable to Find Item")
}
function searchItem() {
    someString=document.getElementById("searchtext").value;
    pageURL="item.aspx?itemnum=" + someString;   
    if (document.getElementById("mainsec")==null) {
         document.location="catlist.aspx?someStr=" +someString
         return
    }     
    callPage(pageURL,"mainsec","Loading","Unable to Find Item");
}    
function searchItems() {
    someString=document.getElementById("searchfrm").value
    // alert(someString);
    pageURL="bp_productlist.aspx?someStr=" + someString    
    if (document.getElementById("maincontent")==null) {
         document.location="buyproducts_catalog.aspx?someStr=" +someString
         return
    }
    callPage(pageURL,"mainsec","Loading","Unable to Find Item")
}   
function getSelect(partNum,cnt,totcnt) {
    for (x=1;x<=totcnt;x++) {
       cleardiv="drop" + x
       document.getElementById(cleardiv).innerHTML=""
       
       show(false,cleardiv)
    }
    pageUrl = "prodselect.aspx?partnum=" + partNum
    thediv = "drop" + cnt
    show(true,thediv)
    callPage(pageUrl,thediv,"Loading","You may not really want this item")
}
function getSelect1(partNum,cnt,totcnt) {
    for (x=1;x<=totcnt;x++) {
       cleardiv="drop" + x
       document.getElementById(cleardiv).innerHTML=""
       
       show(false,cleardiv)
    }
    pageUrl = "prodselect.aspx?partnum=" + partNum
    thediv = "drop" + cnt
    show(true,thediv)
    callPage(pageUrl,thediv,"Loading","You may not really want this item")
}
function getSelect2(partNum,cnt,totcnt) {
    for (x=1;x<=totcnt;x++) {
       cleardiv="drop" + x
       document.getElementById(cleardiv).innerHTML=""
       
       show(false,cleardiv)
    }
    pageUrl = "prodselect.aspx?partnum=" + partNum
    thediv = "drop" + cnt
    show(true,thediv)
    callPage(pageUrl,thediv,"Loading","You may not really want this item")
}
function setNumGetPrice(part){
    Sz=document.getElementById("sz" + part).value  
    if (Sz == "") {
        Sz == "00"
    } 
    Frag=document.getElementById("frag" + part).value 
    if (Frag == "") {
        Frag == "00"
    }
    //alert(part + "-" + Frag + "-" + Sz)
    newnum=part + Frag + Sz + "11"    
    //alert(newnum)
    divElementId="price" + part
    document.getElementById("curnum").value = newnum
    
    if (newnum.length==13){
        var pageErrorMessage='Error in Loading page';
        req=GetXmlHttpObject();
        pagename="fetchPrice.aspx";  
        passData='dpnum='+escape(newnum);
        passData=passData+'&num='+escape(part);
        
        req.open("POST",pagename,true); 
        req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        req.onreadystatechange = function() {responsefromServerX(divElementId, pageErrorMessage);}; 
        req.send(passData);
    }

}
function putInCart(part) {
    Qty=document.getElementById("qty" + part).value
    Sz=document.getElementById("sz" + part).value   
    Frag=document.getElementById("frag" + part).value  
    url="cart.aspx?num=" + part + "&qty=" + Qty +"&sz=" + Sz + "&frag=" + Frag + "&dowhat=put";
    //alert(url)
    window.location=url
}  

function putinIFcart() {
    itemnum=document.getElementById("part").value
    qty=document.getElementById("qty").value
    um=document.getElementById("um").value       

    followme="<span class=title>Your Cart</span>"
    followDiv=document.getElementById("followme")
    followDiv.innerHTML=followme 

    pageURL="bp_putincart.aspx?itemnum=" + itemnum + "&qty=" + qty +"&um=" + um 
    callPage(pageURL,"submaincontent","Loading","Unable to Find Cart Items")
}    
function gototerms() {


}
function openCart() {
    followme="<span class=title>Your Cart</span>"
    followDiv=document.getElementById("followme")
    followDiv.innerHTML=followme 
    cartframe="<div><iframe id='IFbuyproducts' width='760px' height='1080px' frameborder='0' src='bp_cart.aspx' ></iframe></div>"
    cartDiv=document.getElementById("submaincontent")
    cartDiv.innerHTML=cartframe
}
function setFollowme(text) {
    followme="<span class=title>" + text + "</span>"
    followDiv=window.parent.document.getElementById("followme")
    followDiv.innerHTML=followme     
}
function change_parent_url(url) {
	    document.location=url;
}	
function altputincart(itemnum,qty,um) {
    window.location="bp_putincart.aspx?itemnum=" + itemnum + "&qty=" + qty +"&um=" + um
}    

function deleteline(index) {
    window.location="cart.aspx?dowhat=delete&index=" + index
}

function updatecart(linecnt) {
    qtystr = document.getElementById("qty" + linecnt).value
    cartdetid = document.getElementById("cartDetID" + linecnt).value
    window.location="cart.aspx?dowhat=update&partqty=" + qtystr + "&cartdetid=" + cartdetid
}
function dispTotals() {
   var total   
   total=subtotal+tax+parseFloat(shipping)
   document.getElementById("freight1").innerHTML=formatCurrency(shipping)
   document.getElementById("freight").value=shipping
   document.getElementById("total").innerHTML=formatCurrency(total)
   document.getElementById("ordertotal").value=total
}   
function calcTax(statetax,countytax) {
    ordAmt=document.getElementById("orderamt").innerHTML
    theTaxRate=document.getElementById("taxrate")
    theTaxAmt=document.getElementById("taxamt")
    ordAmt=ordAmt.replace("$","")
    ordAmt=ordAmt.replace(",","")
    shipst=document.getElementById("sstate").value
    shipst=shipst.toUpperCase()    
    if (shipst=="GA") {
        myTaxRate=statetax+countytax
    } else {
        myTaxRate=0
    }
    myTaxAmt=ordAmt*(myTaxRate/100)
    myTaxAmt=Math.round(myTaxAmt*100)
    myTaxAmt=myTaxAmt/100
    tax=myTaxAmt
    theTaxRate.innerHTML=myTaxRate
    theTaxAmt.innerHTML="$" + myTaxAmt
    
    totalinv=document.getElementById("total")
    theTotal=parseFloat(ordAmt)+parseFloat(myTaxAmt)
    totalinv.innerHTML="$" + theTotal
}        

// ------------ Old JJChem Javascript ---------------
//   function setprice(prefix,minqty) {
//		theNumber="<%= prefix %>"+document.putincart.frag.value+document.putincart.pack.value

//		x=find(theNumber,items)

//		if (x>=0) {
//           thePrice=prices[x]

//           if( document.putincart.partqty.value>=qtybrk[x] && qtybrk[x]!=0) {
//              thePrice=qtyprice[x]
//           }
//           document.putincart.price.value=formatCurrency(thePrice)
//           document.putincart.partNum.value=theNumber
//           document.putincart.partPrice.value=thePrice
//        } else {
//           alert("That combination is currently unavailable")
//        }
//        if (document.putincart.partqty.value<<%= minQty %>) {
//            alert("The minimum quantity you can order for this product is <%= minQty %>")
//            document.putincart.partqty.value=<%= minQty %>
//        }
//   }
function find(something,somearray) {
    y=-1
	for (x=0;x<somearray.length;x++) {
	    if (somearray[x]==something) {
			y=x
		}
	}
	return y
}
function round(number,X) {
 X = (!X ? 2 : X);
 answer=Math.round(number*Math.pow(10,X))/Math.pow(10,X);

 return formatCurrency(answer)
}


function formatCurrency(num) {
   num = num.toString().replace(/\$|\,/g,'');
   if(isNaN(num))
       num = "0";
   sign = (num == (num = Math.abs(num)));
   num = Math.floor(num*100+0.50000000001);
   cents = num%100;
   num = Math.floor(num/100).toString();
   if(cents<10)
     cents = "0" + cents;
   for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.substring(0,num.length-(4*i+3))+','+
   num.substring(num.length-(4*i+3));
return (((sign)?'':'-') + '$' + num + '.' + cents);
}

function getShipping() {
    theState=document.getElementById("sstate").value    
    pageUrl="calcShipping.aspx?state=" + theState
    req=GetXmlHttpObject()
    req.onreadystatechange = gotShipping    
    req.open("GET",pageUrl,true);
    req.send(null);    
}        
function gotShipping() {
   if(req.readyState == 4) {      
      if(req.status == 200) {
        shipping=req.responseText     
      } else {
         alert(req.responseText)
      }
      dispTotals()
    }
}    
