ostSHOPPING_CART = 1
ostSUBMITTED = 2
ostPENDING = 3
ostPART_FULFILLED = 4
ostFULFILLED = 5
ostCOMPLETED = 6
ostCANCELED = 8
ostONHOLD = 7
ostONHOLD_PENDING = 9
ostONHOLD_SUBMITTED = 10
ostONHOLD_PART_FUL = 11

//Steps
oactBill=-1
oactShip=-3
var Excl_Ctrl="";

var storeVals =false;
var storedVals ="";
var key ="";

function RetrieveValue(txt,frm,sPrfx,sExcl,store){
	var sInf="";
	if(typeof(txt)=="undefined") return;
	if(typeof(txt)=="string")sInf=txt;
	else sInf=txt.value;
	//alert(txt.name + '...' + sInf);
	if(typeof(sPrfx)=="undefined")sPrfx="";
	if(typeof(sExcl)=='undefined')sExcl="";	Excl_Ctrl=sExcl;
	if(typeof(store)!="undefined"){storeVals = store; 	storedVals="";}

	SetValue(sPrfx + 'Name',GetValueByKey(sInf,'###name='));
	SetValue(sPrfx + 'ContactName',GetValueByKey(sInf,'###contactname='))
	RetrieveName(frm,sPrfx);
	//alert(sInf);
	SetValue(sPrfx + 'Address1',GetValueByKey(sInf,'###addr1='));
	SetValue(sPrfx + 'Address2',GetValueByKey(sInf,'###addr2='))
	SetValue(sPrfx + 'City',GetValueByKey(sInf,'###city='))
	SetValue(sPrfx + 'Zip',GetValueByKey(sInf,'###zip='))
	SetValue(sPrfx + 'Phone',GetValueByKey(sInf,'###phone='))
	SetValue(sPrfx + 'PhoneExt',GetValueByKey(sInf,'###ext='))
	SetValue(sPrfx + 'Fax',GetValueByKey(sInf,'###fax='))
	SetValue(sPrfx + 'Email',GetValueByKey(sInf,'###email='))
	SetValue(sPrfx + 'WebURL',GetValueByKey(sInf,'###weburl='))

	key='###country='; storeVal(document.getElementById(sPrfx + "Country").value);// store state selection before refilling cbo!!!
	key='###state='; storeVal(document.getElementById(sPrfx + "State").value);
	key='###statename='; storeVal(document.getElementById(sPrfx + "StateName").value);

	if(frm.elements[sPrfx + 'Country']) SetItemInCbo(frm.elements[sPrfx + 'Country'],GetValueByKey(sInf,'###country='),0);
	else SetItemInCbo(document.getElementById(sPrfx + 'Country'),GetValueByKey(sInf,'###country='),0);

	//note: The function is in PopulateStates.js (needs a link to it in the same Form)
	if(frm.elements[sPrfx + 'Country']) fillStates(frm,sPrfx+'State',eval("frm." + sPrfx + "Country.value"));
	else fillStates(frm,sPrfx+'State',document.getElementById(sPrfx + 'Country').value);

	if(frm.elements[sPrfx + 'State']) SetItemInCbo(frm.elements[sPrfx + 'State'],GetValueByKey(sInf,'###state='),0);
	else SetItemInCbo(document.getElementById(sPrfx + 'State'),GetValueByKey(sInf,'###state='),0);

	if(frm.elements[sPrfx + 'Country']){
		if(frm.elements[sPrfx + 'Country'].value>3){SetValue(sPrfx + 'StateName',GetValueByKey(sInf,'###statename='));}
	}else{
		if(document.getElementById(sPrfx + 'Country').value>3){SetValue(sPrfx + 'StateName',GetValueByKey(sInf,'###statename='));}
	}

	if (sPrfx=='Shipping' && (frm.name=='frmCheckOut' || frm.name=='frmOrderManage')){
		ajx('fnProcess',OI + '&cntry=' + frm.ShippingCountry.value + '&state=' + frm.ShippingState.value);
	}

	if(store && typeof(frm.hdnRevert)!='undefined')frm.hdnRevert.value=storedVals;
}

function SetValue(sName,sValue,setBlank){
	if (typeof(setBlank)=='undefined') setBlank=true;
	if(Excl_Ctrl.indexOf(sName)>-1){ setBlank=false; sValue='';} //do not overwrite vals selected
	try	{
		oFld=eval("document.all." +sName);
		storeVal(oFld.value);
		if (setBlank || sValue!='')	oFld.value=sValue;
	}
	catch (e){}
}

function storeVal(val){
	if(storeVals)  storedVals = storedVals + key + val + ";";
}

//Check Order Prfx(Billing,Shipping) and Individual option. Set the needed names in Name,AttnName fields
function RetrieveName(frm,sPrfx,txt){
	var company=false;
	if (typeof(frm.Individual)=='object'){
		if (frm.Individual.length>0) company=frm.Individual[0].checked;
		else company=(frm.Individual.value==0); //Billing page Individual=radio btn, Shipping page - hidden ctrl
		if(company){// Company
			SetValue(sPrfx + 'Name',GetFrmValue('CompanyName'),false);
		}
		else{
			SetValue(sPrfx + 'Name',GetFrmValue('AttnContactName'),false); //Billing/ShippingName defaults to AttnName
		}
		SetValue(sPrfx + 'ContactName',GetFrmValue('AttnContactName'),false);//Attn Name ctrl is hidden when Individual
	}
}

function GetFrmValue(sFld){
	var sVal='';
	try	{
		sValue=eval("document.all." +sFld).value;
		return sValue;
	}
	catch (e){}
}

function GetValueByKey(sInf,sKey){
	var iPos=0;
	var iPosStop=0;
    var sVal=""; //Return value
	key=sKey;
    iPos=sInf.indexOf(sKey);
    if (iPos==-1){
        sVal="";
    }
    else{
        sVal=sInf.substr(iPos+sKey.length,sInf.length);
        iPosStop=sVal.indexOf(';');
            if (iPosStop==-1){
            //End of Info string
                sVal=sVal;
            }
            else{
                //Retrieve information
                sVal=sVal.substr(0,iPosStop);
            }
        }
   return sVal;
}

function SetItemInCbo(cbo,sID,iDefaultIndex){
	var i;
    if (cbo.length>0&&sID!=''){
       if (iDefaultIndex>=0) cbo.options[iDefaultIndex].selected=true;
       for (i=0;i<cbo.length;i++){
           if (cbo.options[i].value==sID){
				cbo.options[i].selected=true;
                return;
		  }
	   }
	}
}

function SetCboItems(frm, WithAll,bck){
	if(typeof(frm)=="undefined") frm=document.frmOrderManage;
	if (typeof(bck)=="undefined") bck="";

	var lShipMthd = (typeof(frm.hdnShipMethod)=="object" && frm.hdnShipMethod.value!='')?frm.hdnShipMethod.value:-1;

	if (typeof(frm.txtShipMethods)!="undefined" && (bck=='' || lShipMthd!=-1)){
		var sShipMethods=frm.txtShipMethods.value;
		var i=0;
		var sVal="";
		var ss="";
		var iPos=0;
		sVal = sShipMethods.split('##val=')

		if (frm.cboShipMethod.options.length>0){
			iPos=frm.cboShipMethod.length
			for(i=iPos;i>=0;i--){
				frm.cboShipMethod.options[i]=null;
			}
		}
		iPos=0;
		if (typeof(WithAll)!='undefined' && WithAll!='')
		{
			var optNew=new Option("All","");
			frm.cboShipMethod.options[iPos]=optNew;
			iPos++;
		}
		for(i=0;i<sVal.length;i++){
			ss=sVal[i].split('###');
			if ((typeof(WithAll)=="undefined")||(frm.cboShipCarrier.value!=0) ){
				if (frm.cboShipCarrier.value==ss[0]){
					var optNew=new Option(ss[2],ss[1]);
					frm.cboShipMethod.options[iPos]=optNew;
					iPos++;
					}
				frm.cboShipMethod.disabled =false;
				}
			else if ((typeof(WithAll)!="undefined")&&(frm.cboShipCarrier.value==0)){
				var optNew=new Option(ss[2],ss[1]);
				frm.cboShipMethod.options[iPos]=optNew;
				iPos++;
				frm.cboShipMethod.disabled =true;
			}
		}
		if (lShipMthd!=-1) SetItemInCbo(frm.cboShipMethod,lShipMthd);
	}
}

function calculateTax(frm, sZip){
	if(typeof(frm)=="undefined")frm=document.frmOrderManage;
	var lUSA=1;
	var lTaxState=frm.ShippingState.value;
	var sTaxZip=frm.ShippingZip.value;
	var lTaxCountry=frm.ShippingCountry.value;
	var ss="";
	var i=0;
	var sTaxableTotal=frm.taxabletotal.value;
	var dTax=0;
	var dTotal=0;
	var lCounty=frm.ShippingCounty.value;
	var sTaxes=frm.taxrates.value;
	var sVal=sTaxes.split("##");

	if (lTaxCountry!=lUSA) WriteTaxSums(frm,dTax);
	else{
		if(typeof(sZip)!="undefined" && sZip!=sTaxZip){
			frm.action = frm.action + "&rt=yes";
			frm.submit();
		}
		else{
			for(i=0;i<sVal.length;i++){
				ss=sVal[i].split(";");
				//ss 0-Rate,1-State,2-County
				if (ss[1]==lTaxState && ss[2]==lCounty && dTax==0){
					dTax=Math.round(ss[0]* parseFloat(sTaxableTotal))/100;
					break;
				}
				if (ss[1]==lTaxState && ss[2]==0 && dTax==0){
					dTax=Math.round(ss[0]* parseFloat(sTaxableTotal))/100;
					break;
				}
			} //taxes cycle
			WriteTaxSums(frm,dTax);
		} //zip check
	}//Country check
}

function WriteTaxSums(frm,dTax){
	var sSubTotal= frm.SbTotal.value; //for calculating the Total value
	var sCharge=frm.ShCharge.value; //for calculating the Total value
	if(isNaN(dTax)) dTax=0;

	sSubTotal=sSubTotal.substr(1,sSubTotal.length);
	sSubTotal=sSubTotal.replace(',','');
	sCharge=sCharge.substr(1,sCharge.length);
	sCharge=sCharge.replace(',',''); //remove $ and , symbols

	dTotal=dTax + parseFloat(sCharge) + parseFloat(sSubTotal);

	frm.ShipTax.value= "$" + formatSum(dTax);
	frm.ShTotal.value= "$" + formatSum(dTotal);
}

function calculateShipCharge(frm,iFrmCtr){
	var sShipMethods=frm.txtShipMethods.value;
   	var i=0;
   	var sVal="";
   	var ss="";
   	var iPos=0;
	var dCharge=0;
	var sSubTotal=frm.ShipSbTotal.value;
	var sTax="";
	if (typeof(frm.ShipTax)=="object")	sTax=frm.ShipTax.value;

	sTax=sTax.substr(1,sTax.length);
	sSubTotal=sSubTotal.replace('$','');//remove any $ symbols
	sTax=sTax.replace(',','');
	sSubTotal=sSubTotal.replace(',','');

   	sVal = sShipMethods.split('##val=')

	for(i=0;i<sVal.length;i++){
		ss=sVal[i].split('###');
		//ss -0-Carrier,1-MethodId,2-Method,3-RatePerPound,4-PercOfSales 5-FixedFee,6-MinFee
		if (frm.cboShipCarrier.value==ss[0] && frm.cboShipMethod.value==ss[1]){
			if(parseFloat(ss[4])>0){
				dCharge=parseFloat(sSubTotal)*parseFloat(ss[4])/100
			}
			else  dCharge=parseFloat(ss[3])* parseFloat(frm.weight.value);
			if(isNaN(dCharge)) dCharge=0;
			if (parseFloat(sSubTotal)>0) //If all the items are with free shipping do not apply Fixed,Min Fees
			{
				dCharge=dCharge+parseFloat(ss[5]); //Fixed fee calc
				if(dCharge<parseFloat(ss[6])) dCharge=parseFloat(ss[6]); //MinFee compare
			}
		}
	}

	dTotal=parseFloat(sTax) + dCharge + parseFloat(sSubTotal);
	if(isNaN(dTotal))  dTotal=0;

	frm.ShCharge.value= "$" + formatSum(dCharge);
	if (typeof(frm.ShTotal)=="object")	frm.ShTotal.value="$" + formatSum(dTotal);
}

function ValidateBillInfo(chkMail,frm){
	if (typeof(chkMail)=="undefined")chkMail=true;
	return ValInfo(chkMail,"Billing");
}

function ValidateShipInfo(chkMail,frm){
	if (typeof(chkMail)=="undefined")chkMail=true;
	return ValInfo(chkMail,"Shipping");
}

function ValInfo(chkMail,sPrfx){
	var sValidate='';
	sValidate=sValidate + checkValue(sPrfx + "Name", sPrfx + " Name",(sValidate==''));
	sValidate=sValidate + AddrCheck(sPrfx);
	sValidate=sValidate + checkValue(sPrfx +"Phone", sPrfx + " Phone",(sValidate==''));
	if (chkMail) sValidate=sValidate + checkValue(sPrfx + "Email", sPrfx + " Email",(sValidate==''));
	return sValidate;
}

function ValidateOrder(frm, lType, Admin){
	var sValidate="";
	var sCtr="";
	if(typeof(lType)=="undefined") lType=0;
	if(typeof(Admin)=="undefined") Admin=false;

	switch(lType){
		case oactBill:
			sValidate=ValidateBillInfo(!Admin,frm);
			break;
		case oactShip:
			sValidate=ValidateShipInfo(!Admin,frm);
			break;
		default:
			sValidate=ValidateBillInfo(!Admin,frm);
			sValidate=sValidate + ValidateShipInfo(!Admin,frm);
			break;
	}

	if (sValidate!='')
	{
		sValidate= "Please, Enter :" + sValidate
	}

	if(frm.name=="frmCheckOut" && typeof(frm.chkPay)=="object"){
		var lPayMthd=-1; //default online payment
		if (typeof(frm.PayMethod)=="object"){
			lPayMthd=frm.PayMethod.value;
			if (frm.PayMethod.length!=0){
				for (var i=0;i<frm.PayMethod.length ;i++ ){
					if (frm.PayMethod[i].checked)lPayMthd=frm.PayMethod[i].value;
				}
			}
		}
		if (lPayMthd==-1)  sValidate=sValidate + "\n You can't proceed with your order witout a Payment Method selected.";

		if(lPayMthd==1 && frm.PayOnline.value==0){
			if(sCtr=="") sCtr= "PayOnline";
			sValidate=sValidate + "\n Please, select a Payment type to complete your order";
		}
	}
	if(typeof(frm.SalesPersonID)=="object" && typeof(frm.SalesPersons)=="object"){
		var i, bOK=false;
		if(frm.SalesPersons.value==0 && frm.SalesPersonID.value!=''){
			if (isNaN(parseInt(frm.SalesPersonID.value))) {
				sValidate=sValidate + "\n" + "Please, enter valid SalesPerson ID";
				sCtr="SalesPersonID";
			}
			else{
				for(i=0;i<frm.SalesPersons.length;i++){
					if(frm.SalesPersons[i].value==parseInt(frm.SalesPersonID.value)){
						bOK=true;
						break;
					}
				}
				if (!bOK) {
					sValidate=sValidate + "\n" + "Please, enter an existing SalesPerson ID or select it from the List box";
					sCtr="SalesPersonID";
				}
				else	frm.SalesPersons.value=frm.SalesPersonID.value;
			}
		}
	}

	try {
		if(sValidate!="" && sCtr!="") frm.elements(sCtr).focus();
	}
	catch(e) {}
	return sValidate;
}

function onProceed1(frm,lType, Admin,forResale){
	var sValidate=ValidateOrder(frm,lType,Admin);
	if (typeof(forResale)=="undefined") forResale=false;

	if (sValidate!=""){
		alert (sValidate);
		return;
	}
	else{
		if (lType==oactShip && forResale)
		{
			if (mdOpen('<center><b>Is this Order for Resale?</b></center>','280','140','Yes','No','','','','For Resale','')) document.frmCheckOut.action = document.frmCheckOut.action + '&resale=yes';
			else document.frmCheckOut.action = document.frmCheckOut.action + '&resale=no';
		}

		//if (typeof(sAction)!="undefined" && sAction != "")	document.frmCheckOut.action=sAction;
			if(document.frmCheckOut && document.frmCheckOut.PayOnline){
				var w = document.frmCheckOut.PayOnline.selectedIndex;
				var selected_text = document.frmCheckOut.PayOnline.options[w].text;
				if(document.frmCheckOut.PayOnline.value==13 && selected_text=='PayPal Express')  document.frmCheckOut.action="main.asp?uri=1030&act=101&oi=" + orderID;
			}
			frm.submit();
		//document.frmCheckOut.submit();
		}
	}


function calcQties(txt,txtAvl,txtBO,lQtyOrdered, bLimit,bInventory){
	var lQtyAvl=typeof(txtAvl)!="undefined"? parseInt(txtAvl.value): 0;
	var lQtyBO=typeof(txtBO)!="undefined"? parseInt(txtBO.value): 0;
	varlQtyDiff=0;
	txt.value=isNaN(parseInt(txt.value))?0:txt.value;

	lQtyDiff=lQtyOrdered - parseInt(txt.value)
	if (bInventory!='False'){
		if (bLimit=='False') txtBO.value=(lQtyBO - lQtyDiff)<0? 0: lQtyBO - lQtyDiff
		else{
			if(parseInt(txt.value)>lQtyAvl){
			alert('Please, either select quantity not exceeding ' + lQtyAvl + ' or delete the item.');
			txt.focus();
			}
		}
	}
}

function checkQties(sAction){
	var frm =document.frmCheckOut;
	var val="";
	var sQtyCrt="txtQtyOrdered";
	for(i=0;i<frm.elements.length;i++) {
		s=frm.elements(i).name;
		if (s.search(sQtyCrt)==0) {
			sID=s.substr(sQtyCrt.length);
			QtyOrdered=eval('frm.txtQtyOrdered' + sID + '.value') //get OrderItem qty

			QtyAvl=parseInt(eval('frm.txtQtyAvl' + sID + '.value')) + parseInt(eval('frm.txtQtyBO' + sID + '.value'));

			if (QtyOrdered>QtyAvl){
				alert('Please, correct the ' + eval('frm.txtItem' + sID + '.value') + ' quantity. It should not exceed ' + QtyAvl + '.');
				frm.elements('txtQtyOrdered' + sID).focus();
				val='no';
				break;
			}
		}
	}
	if(val!='') return;
	else{
		frm.action=sAction;
		frm.submit();
	}
}

function formatSum(dSum){
	//dSum must be rounded

	var sSum=""
	var iPosDot=0;
	var sMantice="";

	sSum=dSum+"";

	iPosDot=sSum.indexOf(".");
	if (iPosDot==-1){
		sMantice=".00";
		sSum = sSum+sMantice;
	}
	else{
		sMantice=sSum.substr(iPosDot,3)
		if (sMantice.length==2){
			sMantice+="0";
		}
		sSum = sSum.substr(0,iPosDot)+sMantice;
	}

	if (sSum.length>3 + sMantice.length){
		sSum=sSum.substr(0,sSum.length-3- sMantice.length) + ',' + sSum.substr(sSum.length-3-sMantice.length);
	}
	return sSum;
}

function indOption(company,frm,prfx,retrVal){
	if (typeof(frm)=='undefined')frm=document.frmCheckOut;
	if (typeof(prfx)=='undefined')prfx="Billing"; //after Answering the Question
	if (typeof(retrVal)=='undefined')retrVal=true;
	if (company){
		frm.Individual[0].checked=true;

		if(typeof(frm.lblName)!=='undefined'){ //modified by Spas
			frm.lblName.value='Company Name:';
		}

//		frm.lblName.value='Company Name:';
//		RetrieveName(frm,prfx);

//		replaceTag("Retrieve1" + prfx,"Home","Mailing","Home","CompanyMail")
//		replaceTag("Retrieve2" + prfx,"Office","Billing","Company","CompanyBill")
		replaceTag("Retrieve3" + prfx,"Billing","Billing","BillingAddrID","BillAddrID")
		replaceTag("Retrieve4" + prfx,"Shipping","Shipping","ShippingAddrID","ShipAddrID")

	}
	else{
		frm.Individual[1].checked=true;

		if(typeof(frm.lblName)!=='undefined'){  //modified by Spas
			frm.lblName.value='Name:';
		}

//		frm.lblName.value='Name:';
//		RetrieveName(frm,prfx);

//		replaceTag("Retrieve1" + prfx,"Mailing","Home","CompanyMail","Home")
//		replaceTag("Retrieve2" + prfx,"Billing","Office","CompanyBill","Company")
		replaceTag("Retrieve3" + prfx,"Billing","Billing","BillAddrID","BillingAddrID")
		replaceTag("Retrieve4" + prfx,"Shipping","Shipping","ShipAddrID","ShippingAddrID")
		}

	if (prfx=='Billing') MM_showHideLayers('divAttnName','',(frm.Individual[0].checked)?'show':'hide');
}

function replaceTag(elID,val1,val1replace,val2,val2replace){
	try{
		if (document.all.CompanyID.value>0){
			var clk=document.getElementById(elID).outerHTML.toString();
			clk=clk.replace('.' + val2,'.' + val2replace);
			clk=clk.replace('>' + val1,'>' + val1replace);
			document.getElementById(elID).outerHTML=clk;
		}
	}
	catch (e){}
}

function fnProcess(txt){
	var ss	= txt.split('###');
	setHTML('cbShipCarrier',ss[0])
	setHTML('cbShipMethod',ss[1])
	if (ss[2]!='') document.getElementById('ShCharge').value = ss[2];
	if (ss.length>3 && ss[3]!=''){ //frmOrderManage cll!
		onChangeElement();
		document.forms[0].ShipTax.value = ss[3];
		document.forms[0].ShTotal.value = ss[4]; //total calculated in DLL
	}
}

function setHTML(tgID,val){
	if (val!=''){
		try{
			var prfx=document.getElementById(tgID).innerHTML;
			prfx= prfx.substring(0,prfx.indexOf('>')+1); //end of select
			document.getElementById(tgID).innerHTML = prfx + val + '</select>';
		}
		catch (e){}
	}
}

function ajx(div,add,mthd,idPOST){
	if (typeof(mthd)=='undefined')mthd='POST';

	var regex = new RegExp('&amp;', "g"); add = add.replace(regex,'&');

	divID=div;
	qs++; //make sure HTTP QS is unique
	postdata ="AJX_DLL=GWC_Products.OrderSubmit";
	reqc=getXMLHTTP();
	if (objOK)
	{
		var gotoURL="test.asp" + STS(add) + '&cl=' + qs;
//		alert(gotoURL);
		reqc.onreadystatechange = process_c;
		reqc.open(mthd, gotoURL, true);

	}
	reqc.setRequestHeader('Content-Type',contType);
	reqc.send(postdata);

	window.status = "retrieving information..";
}
