var refMoreCount = 0
var xmlhttp
var bolIsReady = false
var objSample
var arrSample = new Array()
var dvCartID = null

function ValidateReferee(){
	var term = document.getElementById("chkTerms")
	//alert('term checked: ' + term.checked)
	if(term.checked){
		document.getElementById("dvChkTerm").style.visibility = 'hidden'
		return true
	}
	else{
		document.getElementById("dvChkTerm").style.visibility = 'visible'
		return false
	}
	
}

function CheckReferTerm(id){
	var cid = id.substring(0,id.lastIndexOf("_")+1) + 'chkReferTerm'
	if(document.getElementById(cid).checked){
		document.getElementById('dvRefMsg').style.visibility = "hidden"
		document.getElementById(id).style.visibility = "hidden"
		return true
	}
	else{
		document.getElementById('dvRefMsg').style.visibility = "visible"
		return false
	}
		
}

function ShowMoreRefer(){
	if(document.getElementById('txtRefMore').value != '') refMoreCount = parseInt(document.getElementById('txtRefMore').value)
	if(refMoreCount < 9) refMoreCount = refMoreCount + 1
	var idx = 0
	var refID = ''
	var dv
	for(idx = 1; idx <= refMoreCount; idx ++){
		refID = 'dvRefMore' + idx;
		dv = document.getElementById(refID)
		if(dv != null) dv.style.display = 'inline'
	}
	//document.getElementById('dvRefMore1').style.display = 'inline'
	//document.getElementById('txtRefMore').value = 'true'
	document.getElementById('txtRefMore').value = refMoreCount
	//alert(document.getElementById('txtRefMore').value)
	
}

function OpenRefEmail(){
	var win = window.open("ReferralEmail.aspx", "viewRefEmail", 'width=560,height=550,menubar=no,toolbar=no,resizable=yes,scrollbars=no,status=no,directories=no,alwaysRaised=yes');
}

function ShowButton(id){
	var cid = id.substring(0,id.lastIndexOf("_")+1) + 'ibtnSubmitReferCode'
	var lid = id.substring(0,id.lastIndexOf("_")+1) + 'lblSubmit'
	document.getElementById(cid).style.visibility = "visible" 
	document.getElementById(cid).style.display = "inline" 

	if(document.getElementById(lid) != null)
		document.getElementById(lid).style.visibility = "hidden" 	
	//alert(document.getElementById(cid))
	
}

function ProcessRefCode(checked){

	if(checked){ 
		document.getElementById('dvRefCode').style.visibility = "visible"
		document.getElementById('Cart_ReferralCode1_ibtnSubmitReferCode').style.visibility = "visible"
		document.getElementById('dvRefCode').style.display = "block"
		document.getElementById('Cart_ReferralCode1_ibtnSubmitReferCode').style.display = "block"
	}
	else{
		document.getElementById('dvRefCode').style.visibility = "hidden"
		document.getElementById('Cart_ReferralCode1_ibtnSubmitReferCode').style.visibility = "hidden"
		document.getElementById('dvRefCode').style.display = "none"
		document.getElementById('Cart_ReferralCode1_ibtnSubmitReferCode').style.display = "none"

	}
	
}

function ReferCodeChange(e,id){
//debugger
	if(event.keyCode == "13"){
		ShowButton(id)
		return false
	}
	else if(e.which == "13"){
		ShowButton(id)
		return false
	}
	else
		return true
}

function TrickEnterKey(e){
    var kCode
    if (document.all)
        kCode = e.keyCode
    else
        kCode = e.which
    if ((kCode >= 48 && kCode <= 57) || kCode == 46)
		return true
    else if (kCode == 13) {
		/*var len = document.links.length
		var idx = 0
		for(idx = 0; idx < len; idx++){
			if(document.links[idx].href.indexOf("#update") > -1){
				document.links[idx].click()
				return false
			}
		}*/
		//document.forms[0].submit()
		return false
	}
//	else if(e.which == 13){
//		return false
//	}
	else
		return false
}
function CheckReferTermRer(){
	if(document.getElementById("chkTerms").checked){
		document.getElementById('dvChkTerm').style.visibility = "hidden"
		return true
	}
	else{
		document.getElementById('dvChkTerm').style.visibility = "visible"
		return false
	}
}
function SubmitForm(){
	if(document.getElementById("chkTerms").checked){
		document.getElementById('txtSubmit').value = 'true'
		document.forms[0].submit()
	}
	else
		document.getElementById('dvChkTerm').style.visibility = "visible"
}

function DisableEnterKey(e){
	if(event.keyCode == 13)
		return false
	else if(e.which == 13)
		return false
	else
		return true
}

/*********  for shopping cart qty and coverage change, calculate subtotal and product total ***************/
//document.addEventListener("keypress", KeyPressEvent, true);

function numbersonlyEnter(e, func, obj)
{
	var key;
	var keychar;
	if (window.event)
		key = window.event.keyCode;
	else if (e){
			key = e.which;
		}
		else
			return true;
	keychar = String.fromCharCode(key);
	keychar = keychar.toLowerCase();
	//alert('key: ' + key + ', keychar: ' + keychar)
	//Enter key
	if(key == 13){
		//alert(func)
		if (obj.value.length>0)
		    eval(func + "(" + obj.value + ",'" + obj.id + "')")
		
		return false
	}
	// control keys
	if ((key==null) || (key==0) || (key==8) || (key==9) || (key==27) )
		return true;
	// numbers
	else if ((("0123456789.").indexOf(keychar) > -1))
		return true;
	else
		return false;
}

//shopping cart 
function CalculateTotal(qty, id){

	var prefix = id.substring(0, id.lastIndexOf("_") + 1)
	var noShipping = (document.getElementById(prefix.substring(0,prefix.indexOf("ItemRptr")) + 'lblMShipping').innerHTML == '--')
	var minQty = parseInt(document.getElementById(prefix + 'MiniQuantity').innerHTML)
	var subtotal = document.getElementById(id.substring(0, id.lastIndexOf("_") + 1) + 'itemsubtotal')
	var unitPrice = formatCurrency(document.getElementById(prefix + 'lblprice').innerHTML)
	var pupsu = parseFloat(document.getElementById(prefix + 'PriceUnitPerSellUnit').innerHTML)
	var itemID = document.getElementById(prefix + 'ItemID').innerHTML
	var sMinQty = parseFloat(document.getElementById(prefix + 'lblSMinQty').innerHTML)
	var sMinDollar = parseFloat(document.getElementById(prefix + 'lblSMinDollar').innerHTML)
	var realQty = qty
	var cov = 0
	var stotal = 0
	
	//debugger
	if(noShipping){
		unitPrice = unitPrice.replace('$', '')
		unitPrice = unitPrice.replace(',', '')
		//if qty is less the minQty, use minQty instead
		if(qty < parseInt(minQty)){
			realQty = minQty
			document.getElementById(id).value = minQty
		}

		UpdateQty(itemID, realQty)
		//alert('finish update qty , ' + document.getElementById(prefix + 'SupplierMiniOrderRow'))
		if(document.getElementById(prefix + 'SupplierMiniOrderRow'))
			document.forms[0].submit();
		else{
			//alert('realQty:' + realQty + " unitPrice:" + parseFloat(unitPrice))
			//alert("unitprice: " + unitPrice + ", subtotal: " + subtotal.innerHTML)
			stotal = formatCurrency(parseFloat(unitPrice) * realQty * pupsu)
			subtotal.innerHTML = '$' + stotal
			if(document.getElementById(prefix + 'txtCoverage') != null){
				cov = formatCurrency(realQty * pupsu)
				document.getElementById(prefix + 'txtCoverage').value = cov
			}
			//check for manuf min qty and dollar
	//alert('sMinQty: ' + sMinQty + ', sMinDollar: ' + sMinDollar + ', stotal: ' + stotal)
			if(sMinQty > 0)
				if(cov > 0 && cov < sMinQty)
					document.forms[0].submit();
					
			if(sMinDollar > 0 && stotal < sMinDollar)
				document.forms[0].submit();
		}	
	}
	else{
		//shipping price exists, submit form to clear the shipping
		document.forms[0].submit();
	}
	
	CalculateShoppingCartTotal()
}

function CalculateTotal2(cov, id){
	//alert("cov: " + cov + ",id: " + document.getElementById(id).value)
	var prefix = id.substring(0, id.lastIndexOf("_") + 1)
	var noShipping = (document.getElementById(prefix.substring(0,prefix.indexOf("ItemRptr")) + 'lblMShipping').innerHTML == '--')
	var minQty = parseInt(document.getElementById(prefix + 'MiniQuantity').innerHTML)
	var subtotal = document.getElementById(id.substring(0, id.lastIndexOf("_") + 1) + 'itemsubtotal')
	var unitPrice = formatCurrency(document.getElementById(prefix + 'lblprice').innerHTML)
	var pupsu = parseFloat(document.getElementById(prefix + 'PriceUnitPerSellUnit').innerHTML)
	var itemID = document.getElementById(prefix + 'ItemID').innerHTML
	var sMinQty = parseFloat(document.getElementById(prefix + 'lblSMinQty').innerHTML)
	var sMinDollar = parseFloat(document.getElementById(prefix + 'lblSMinDollar').innerHTML)
	var qty = 0
	//var realQty = qty

	qty = Math.floor(cov/pupsu)
	if(qty < (cov/pupsu))
		qty = qty + 1
	
	if(qty < minQty)
		qty = minQty

	subtotal.innerHTML = '$' + formatCurrency(unitPrice * pupsu * qty)
	document.getElementById(id).value = formatCurrency(qty * pupsu)
	document.getElementById(prefix + 'txtQuantity').value = qty
	
	if(document.getElementById(prefix + 'SupplierMiniOrderRow'))
			document.forms[0].submit();
	else{
	//alert("sMinQty: " + sMinQty + ", sMinDollar: " + sMinDollar)
			if(sMinQty > 0)
				if(cov > 0 && cov < sMinQty)
					document.forms[0].submit();
					
			stotal = formatCurrency(parseFloat(unitPrice) * qty * pupsu)		
			if(sMinDollar > 0 && stotal < sMinDollar)
				document.forms[0].submit();
	}
	
	//update grand total
	CalculateShoppingCartTotal()

}

function CalculateShoppingCartTotal(){
	var mprefix, count, idx, id, msubtotal
	//debugger
	if(document.all){
		//IE
		mprefix = ''
		total = 0
		count = document.all.length
		for(idx = 0; idx < count; idx++){
			if(document.all[idx].tagName == 'SPAN'){
				id = document.all[idx].id
				//alert(id)
				if(id.indexOf('itemsubtotal') > -1){
					if(mprefix != id.substring(0, id.indexOf('ItemRptr'))) {
						if(mprefix != ''){
							//update lblMSubTotal
							document.getElementById(mprefix + 'lblMSubTotal').innerHTML = '$' + formatCurrency(total)
						}
												
						total = parseFloat(formatCurrency(document.all[idx].innerHTML))
						mprefix = id.substring(0, id.indexOf('ItemRptr'))
						
					}
					else
						total = total + parseFloat(formatCurrency(document.all[idx].innerHTML))
				}
			}
		}
		//udpate last lblMSubTotal
		document.getElementById(mprefix + 'lblMSubTotal').innerHTML = '$' + formatCurrency(total)		
	}
	else{
		//FireFox
		var iprefix
		count = document.forms[0].elements.length
		mprefix = ''
		total = 0
		iprefix = ''
		for(i = 0; i < count; i++){
			id = document.forms[0].elements[i].id
			if(id.indexOf('txtQuantity') > -1){
				//alert('mprefix: ' + mprefix + ', id:' + id)
				if(mprefix != id.substring(0, id.indexOf('ItemRptr'))){
				//alert('mprefix changed, mprefix: ' + mprefix + ', total: ' + total)
					
					if(mprefix != ''){
						
						//alert(document.getElementById(mprefix.substring(0,mprefix.indexOf('ItemRptr')) + 'lblMSubTotal'))
						document.getElementById(mprefix + 'lblMSubTotal').innerHTML = '$' + formatCurrency(total)
					}
					
					mprefix = id.substring(0, id.indexOf('ItemRptr'))
					iprefix = id.substring(0, id.indexOf('txtQuantity'))
					total = parseFloat(formatCurrency(document.getElementById(iprefix + 'itemsubtotal').innerHTML))
					//alert('total: ' + total + ', mprefix: ' + mprefix)
				}
				else{
					//alert('1 total: ' + total)
					iprefix = id.substring(0, id.indexOf('txtQuantity'))
					total = total + parseFloat(formatCurrency(document.getElementById(iprefix + 'itemsubtotal').innerHTML))
					//alert('2 total: ' + total)
				}
			}
		}
		//udpate last lblMSubTotal
		document.getElementById(mprefix.substring(0,mprefix.indexOf('ItemRptr')) + 'lblMSubTotal').innerHTML = '$' + formatCurrency(total)
		
	}
	
}


function CalculateTotalPDP(qty, id){
//debugger
    if (qty=="")
    {
        qty="0"
    }
    
	qty=parseInt(qty)
	var prefix = id.substring(0, id.lastIndexOf("_") + 1 )
	var itemtotal = document.getElementById(prefix + 'ItemSubtotal')

    //	var minOrder = parseFloat(document.getElementById(prefix + 'lblMiniOrder').innerHTML)
	var pupsu = 1
	//var pprice = document.getElementById(prefix + 'PPrice').innerHTML
	//var unitPrice = parseFloat(formatCurrency(pprice.substring(1, pprice.lastIndexOf("/"))))
    var priceList=GetMultiPriceAndMinOrder(qty)
    var cPrice =priceList[0].split(",")
    var unitPrice= cPrice[0]
    var minOrder =parseFloat(cPrice[1])

//	var pprice = document.getElementById(prefix + 'PPrice').innerHTML
//	var unitPrice = parseFloat(formatCurrency(pprice.substring(1, pprice.lastIndexOf("/"))))
	if(document.getElementById(prefix + 'lblPUPSU'))
		pupsu = parseFloat(document.getElementById(prefix + 'lblPUPSU').innerHTML)
	
	if(qty < minOrder)
		qty = minOrder
		
//	alert("prefix: " + prefix + ",unitPrice: " + unitPrice + ", pupsu : " + pupsu + ", qty: " + qty)
	itemtotal.innerHTML = '<b>$' + formatCurrency(unitPrice * pupsu * qty) + '</b>'
	document.getElementById(id).value = qty
	if(document.getElementById(prefix + 'ItemCoverage') != null)
		document.getElementById(prefix + 'ItemCoverage').value = formatCurrency(qty * pupsu)
	//update grand total
	CalculateProductTotal()
	//Call to webservice to set quontity in session 
	//used for optimost option A (pguo-stgol)
	SetItemQty(qty)
//	RewritePriceList(priceList,pupsu,id)
}




function CalculateTotalPDP2(cov, id){
//debugger 
	var prefix = id.substring(0, id.lastIndexOf("_") + 1 )
	var itemtotal = document.getElementById(prefix + 'ItemSubtotal')

//	var minOrder = parseFloat(document.getElementById(prefix + 'lblMiniOrder').innerHTML)
	var minOrder = parseFloat(document.getElementById(prefix + 'lblMiniOrder').innerHTML)
	var pupsu = parseFloat(document.getElementById(prefix + 'lblPUPSU').innerHTML)
//	var pprice = document.getElementById(prefix + 'PPrice').innerHTML
//	var unitPrice = parseFloat(formatCurrency(pprice.substring(1, pprice.lastIndexOf("/"))))
//	var pprice = document.getElementById(prefix + 'PPrice').innerHTML
//	var unitPrice = parseFloat(formatCurrency(pprice.substring(1, pprice.lastIndexOf("/"))))
	var qty = 0
	
	qty = Math.floor(cov/pupsu)
	if(qty < (cov/pupsu))
		qty = qty + 1
    var priceList=GetMultiPriceAndMinOrder(qty)
    var cPrice =priceList[0].split(",")
    var unitPrice= cPrice[0]
    var minOrder =cPrice[1]
    
	if(qty < minOrder)
		qty = minOrder

	itemtotal.innerHTML = '$' + formatCurrency(unitPrice * pupsu * qty)
	document.getElementById(id).value = formatCurrency(qty * pupsu)
	document.getElementById(prefix + 'ItemQuantity').value = qty
	
	//update grand total
	CalculateProductTotal()
    //Call to webservice to set coverage in session 
	//used for optimost option A (pguo-stgol)
	SetItemQty(qty)
		
	//RewritePriceList(priceList,pupsu, id)
}

function GetMultiPriceAndMinOrder(qty)
{
    var prices = multiPrices.split(",")
    var minQuantities = minQuantity.split(",")
    var maxQuantities = maxQuantity.split(",")
    var minCoverages=minCoverage.split(",")
    var lists = new Array(prices.length)
    var idx=0
    for (i=0;i<=prices.length -1; i++)
    {
          if (qty>=minQuantities[i])
            {
                lists[0]=prices[i]+","+minQuantities[i]+"," +maxQuantities[i]+"," +minCoverages[i]
                idx =i
                break
            }
            else if (qty<minQuantities[i] && i==prices.length-1) 
            {
               lists[0]=prices[i]+","+minQuantities[i]+"," +maxQuantities[i]+"," +minCoverages[i]
               idx =i
               break
            }
    }
    var j=1
    for (i=0;i<=prices.length-1;i++)
    {
        if (i != idx)
        {
            lists[j]=prices[i]+","+minQuantities[i]+"," +maxQuantities[i]+"," +minCoverages[i]
            j++
        }
    }
    
    return lists
    
}
function RewritePriceList(priceList,pupsu, id)
{
 // debugger 
    var selectedPrice =document.getElementById("selectedPriceDiv")
    var multiPriceList = document.getElementById("multiPriceDiv")
    var displayString=""
    var minOrder =0
    var minCoverage=0
    for (i=0; i<=priceList.length-1;i++)
    {
        var orderrange =""
        var item = priceList[i].split(",")
        var price = item[0]
        var minQty = item[3] //Math.floor(item[1]*pupsu)
        var maxQty =item[2]
        if (maxQty !="+")
        {
            maxQty = Math.floor(maxQty *pupsu)
            orderrange = minQty + " - " + maxQty 
        }
        else
        {
            orderrange =minQty + maxQty 
        }
        orderrange =orderrange + " " + priceunit
        if (i==0) //the price which match the quantity use enter
        {
           minOrder =item[1]
           minCoverage =minOrder  * pupsu    
           selectedPrice.innerHTML = "<b class='pdp_bluepriceb'>$" +formatCurrency(price) +" /" +priceunit +"</b> (" +orderrange+")"
        }
        else
        { 
            displayString = displayString + "<b class='pdp_greypriceb'>$"+formatCurrency(price)+" /"+priceunit+"</b> ("+orderrange+")"
            if (i!=priceList.length-1)
            {
                displayString =displayString +"<br>"
            }
           
        }
       
        
    }
    
    if (displayString.length >0)
    {
        multiPriceList.innerHTML=displayString 
    }
    
    var prefix = id.substring(0, id.lastIndexOf("_") + 1 )
   	var itemMinOrderQty=document.getElementById(prefix + "ItemMinOrderQty")
   	var itemMinCoverage =document.getElementById(prefix +"ItemMinOrderCoverage")
   	var pMinConverage = document.getElementById("PMinCoverage")
   	//debugger
	itemMinOrderQty.innerHTML="min. " + minOrder +" " + document.getElementById(prefix + 'QtyUnits').innerHTML
	itemMinCoverage.innerHTML ="min. " + minCoverage + " " +priceunit
	pMinConverage.innerHTML =minCoverage + " " + priceunit
	
	var errorMsg = document.getElementById(prefix +"ltError").innerHTML
	if (errorMsg.length>0)
	   document.getElementById(prefix +"ltError").innerHTML =""
}


function CalculateTotalPDPAcc(qty, id){
	//debugger
	var prefix = id.substring(0, id.lastIndexOf("_") + 1 )
	if(qty == "" || qty == "0"){
		//clear qty, subtotal
		if(document.getElementById(prefix + 'ItemCoverage') != null)
			document.getElementById(prefix + 'ItemCoverage').value = ''

		document.getElementById(prefix + 'ItemSubtotal').innerHTML = "$0.00"
		//CalculateProductTotal()		
	}
	else{
		var itemtotal = document.getElementById(prefix + 'ItemSubtotal')
		var minOrder = parseFloat(document.getElementById(prefix + 'ItemMinimum').innerHTML)
		var pupsu = parseFloat(document.getElementById(prefix + 'ItemPUPSU').innerHTML)
		var pprice = document.getElementById(prefix + 'ItemPrice').innerHTML
		var unitPrice = parseFloat(formatCurrency(pprice.substring(1)))
		
		if(qty < minOrder)
			qty = minOrder
			
	//	alert("prefix: " + prefix + ",unitPrice: " + unitPrice + ", pupsu : " + pupsu + ", qty: " + qty)
		itemtotal.innerHTML = '$' + formatCurrency(unitPrice * pupsu * qty)
		document.getElementById(id).value = qty
		if(document.getElementById(prefix + 'ItemCoverage') != null)
			document.getElementById(prefix + 'ItemCoverage').value = formatCurrency(qty * pupsu)
		
	}
	
	//update grand total
	CalculateProductTotal()
}

function CalculateTotalAcc2(cov, id){
	var prefix = id.substring(0, id.lastIndexOf("_") + 1 )
	if(cov == "" || cov == "0"){
	//alert(document.getElementById(prefix + 'ItemSubtotal'))
		document.getElementById(prefix + 'ItemSubtotal').innerHTML = "$0.00"
		document.getElementById(prefix + 'ItemQuantity').value = ''
	}
	else{
		var itemtotal = document.getElementById(prefix + 'ItemSubtotal')
		var minOrder = parseFloat(document.getElementById(prefix + 'ItemMinimum').innerHTML)
		var pupsu = parseFloat(document.getElementById(prefix + 'ItemPUPSU').innerHTML)
		var pprice = document.getElementById(prefix + 'ItemPrice').innerHTML
		var unitPrice = parseFloat(formatCurrency(pprice.substring(1)))
		var qty = 0
		
		qty = Math.floor(cov/pupsu)
		if(qty < (cov/pupsu))
			qty = qty + 1
		
		if(qty < minOrder)
			qty = minOrder

		itemtotal.innerHTML = '$' + formatCurrency(unitPrice * pupsu * qty)
		document.getElementById(id).value = formatCurrency(qty * pupsu)
		document.getElementById(prefix + 'ItemQuantity').value = qty
		
		//alert(cov + ',id: ' + id + ',minOrder: ' + minOrder)
	}
	
	//update grand total
	CalculateProductTotal()
}


function UpdateQty(itemID, qty){
//debugger
	var url = path + "/Services/WSShoppingCart.asmx/UpdateCartItemQty?itemID=" + itemID + "&qty=" + qty
	//alert(url)
	CreateXMLHTTP(url, UpdateQtyChanged)
	
}

function CreateXMLHTTP(url, changeEventHandler){
	var request = null;
	//Create XmlHttpxmlHttp object
    var ua = navigator.userAgent.toLowerCase();
    if (window.XMLHttpRequest) //IE7, Safari, Mozilla
    {
   // debugger
		if(xmlhttp == null || bolIsReady){
			//xmlhttp=new XMLHttpRequest();
			SendXMLHTTP(url, changeEventHandler);
		}
		else {
			//window.setTimeout('SendXMLHTTP("' + url + '", ' + changeEventHandler + ')', 2000)
			window.setTimeout('CreateXMLHTTP("' + url + '", ' + changeEventHandler + ')', 2000)
		}
				
      /* try{
			bolIsReady = false;
			xmlhttp.onreadystatechange=changeEventHandler;
			xmlhttp.open("GET",url,true);
			xmlhttp.setRequestHeader("myVal","BuildDirect");
			xmlhttp.send(null);
       }
       catch(ex){
			//alert(ex)
       }*/
    
    }
    else //IE5, IE6
    {
		if(xmlhttp == null || bolIsReady){
				
			SendXMLHttpIEOld(url, changeEventHandler);
		}
		else
			window.setTimeout('CreateXMLHTTP("' + url + '", ' + changeEventHandler + ')', 2000)
			
			/*if (ua.indexOf('msie 5') == -1)
				xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
			else
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    
		if(xmlhttp)
		{
			try
			{
				bolIsReady = false
				xmlhttp.onreadystatechange=changeEventHandler;
				xmlhttp.open("GET",url,false);
				xmlhttp.send();
			}
			catch(e){
				//alert(e)
			} 
		}*/
    }    
}

function SendXMLHTTP(url, changeEventHandler){
 try{
 //debugger
			xmlhttp=new XMLHttpRequest();
			bolIsReady = false;
			xmlhttp.onreadystatechange=changeEventHandler;
			xmlhttp.open("GET",url,true);
			xmlhttp.setRequestHeader("myVal","BuildDirect");
			xmlhttp.send(null);
       }
       catch(ex){
			//alert(ex)
       }
}

function SendXMLHttpIEOld(url, changeEventHandler){
	if (window.ActiveXObject){
		try{
			xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch(e){
			try{
				xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
				}
			catch(e){
				
			}
		}
	}

     
	if(xmlhttp)
	{
			try
			{
				//alert('SendXMLHttpIEOld url: ' + url)

				bolIsReady = false
				xmlhttp.onreadystatechange = changeEventHandler;
				xmlhttp.open("GET",url,true);
				xmlhttp.send();

			}
			catch(e){
				alert(e)
			} 
	}
}

function CreateXMLIEOld(){
	if (ua.indexOf('msie 5') == -1)
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	else
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

function UpdateQtyChanged(){
	if(xmlhttp.readyState==4)
    {
		bolIsReady = true
		if(xmlhttp.status==200){
           var myxml = xmlhttp.responseXML;
           var mytext = xmlhttp.responseText;
           
        }
    }
}

function CalculateProductTotal(){
	var i, count,pprice, qty
	var total = 0
	var pupsu
	var prefix, id
	
	//IE
	if(document.all){
		count = document.all.length
		for(i = 0; i < count; i++){
			if(document.all[i].tagName == 'SPAN')
				if(document.all[i].id.indexOf('ItemSubtotal') > -1){
					//alert(document.all[i].innerHTML)
					stotal = document.all[i].innerHTML.substring(document.all[i].innerHTML.indexOf("$"),document.all[i].innerHTML.indexOf("</")) 
					if(stotal == '') stotal = document.all[i].innerHTML.substring(1)
					//alert(stotal)
					total = total + parseFloat(formatCurrency(stotal))
					//alert(total)
				}
		}
	}
	else{
		var itemTotal = document.getElementById('SelectedProductItemDetail_ItemSubtotal').innerHTML
		total = parseFloat(formatCurrency(itemTotal.substring(itemTotal.indexOf("$") + 1, itemTotal.lastIndexOf("</"))))
		//alert('itemTotal: ' + itemTotal + ', total: ' + total)
		count = document.forms[0].elements.length
		for(i = 0; i < count; i++){
			id = document.forms[0].elements[i].id
			if(id.indexOf('ItemQuantity') > -1){
				prefix = id.substring(0, id.lastIndexOf("_") + 1 )
				if(document.getElementById(prefix + 'ItemPrice')){
					pprice = document.getElementById(prefix + 'ItemPrice').innerHTML
					pupsu = parseFloat(document.getElementById(prefix + 'ItemPUPSU').innerHTML)
					qty = parseFloat(formatCurrency(document.getElementById(id).value))
					//alert('subtotal: ' + qty * pupsu * parseFloat(pprice.substring(1)))
					total = total + qty * pupsu * parseFloat(pprice.substring(1))
				}
			}
		}
	}
	
	//alert('total: ' + total)
	if(total > 0)	
		if(document.getElementById('GrandTotal') != null)
			document.getElementById('GrandTotal').innerHTML = '$' + formatCurrency(total)
}

function formatCurrency(num) 
{
	var isNegative = false;
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num)) {num = new Number(0)} else { num = new Number(num); };
	if (num < 0) 
	{
		isNegative = true;
		num = num.toString().replace('-','');
	}
	cents = Math.floor((num*100+0.5)%100); 
	num = Math.floor(num).toString();
	if(cents < 10) cents = "0" + cents; 
	if (isNegative) 
		return ('-' + num + '.' + cents); 
	else
		return (num + '.' + cents);
}


/*********  end ****************/

//OPTIMOST 
function SetItemQty(qty){
 //Call to webservice to set quontity or coverage in session 
//optimost option A (pguo-stgol)
//debugger
	var url = path + "/Services/WSProduct.asmx/SetQty?qty=" + qty
	CreateXMLHTTP(url, SetQtyChanged)

}

function SetQtyChanged(){
if(xmlhttp.readyState==4)
    {
		bolIsReady = true
		if(xmlhttp.status==200){
           var myxml = xmlhttp.responseXML;
           var mytext = xmlhttp.responseText;
           
        }
    }
}

//End OPTIMOST 


//**************** one click sample functions ***************
function AddToCartClick(configID,supplierID,categoryID,orderTypeID,deliveryType, obj){
	//alert('add to sample clicked! configID:'+configID + ',supplierID:' + supplierID + ',categoryID: ' + categoryID + ',orderTypeID: ' + orderTypeID + ',DeliveryType: ' + deliveryType )
	//alert(obj + ',src: ' + obj.src)
	//debugger
	objSample = obj
	var src = obj.src
	var loadCart = false
	if(src.indexOf("add_sample.gif") > -1){
		//alert('path:' + path)
	    if (sampleCount < maxSampleCount) {
	        sampleCount = sampleCount + 1

	        arrSample.push(obj.id)
	        //alert('arrSample.push: ' + arrSample.length + ',ID: ' + obj.id)
	        obj.src = src.substring(0, src.lastIndexOf("/") + 1) + "ajax-loader2.gif"//"sample_added.gif"

	        /*if (screen.width >= 1200 &&
				(getCookieValueByName('SiteRefferUrl').toLowerCase().indexOf("result") > -1 ||
				 getCookieValueByName('SiteRefferUrl').toLowerCase().indexOf("ordersamples") > -1 ||
				 window.location.href.toLowerCase().indexOf("ordersamples") > -1) ||
				 location.pathname.toLowerCase().indexOf("mostpopular") > -1 ||
				 location.pathname.toLowerCase().indexOf("specials") > -1)
	            loadCart = true
	        else
	            loadCart = false*/
	        loadCart = true    
	        //debugger
	        CreateXMLHTTP(path + "/Services/OneClickSample.aspx?configId=" + configID + "&supplierID=" + supplierID +
				          "&deliveryType=" + deliveryType + "&orderTypeId=" + orderTypeID + "&categoryId=" +
				          categoryID + "&ran=" + Math.random() + "&loadCart=" + loadCart,
				           AddSampleChangeEvent)
	    }
	    else
	        alert("Sorry, you cannot order more than 40 samples at a time. If you require more samples, please contact a customer service representative")
	}
	else if(src.indexOf("sample_added.gif") > -1){
		//sample already add to cart, do redirect to cart page
		window.location.href = cartPath + '/Order/Cart.aspx'
	}
	else if(src.indexOf("please_call.gif") > -1){
		//please call displayed, redirect to contact us page
		window.location.href = cartPath + '/ContactUs.aspx'
	}

}


function AddSampleChangeEvent(){

	if(xmlhttp.readyState==4){
		bolIsReady = true
		if(xmlhttp.status==200){
			var myxml = xmlhttp.responseXML;
			var mytext = xmlhttp.responseText;
			//debugger
			//if( mytext == 'true' || mytext == 'True'){
			//alert('mytext: ' + mytext)
			if( mytext == "false"){
				//error when adding sample or binding mini shopping cart
				alert('Sorry, we had a problem adding this sample to your cart. Please click your browser refresh button and then try again')
				ClearSampleImage();
			}
			else {
				//successful add sample
				//alert(mytext)
				SwapSampleImage();
				if(mytext != "true")
				    LoadMiniCart(mytext);
			}
		}
		else{
			alert('Sorry, we had a problem adding this sample to your cart. Please click your browser refresh button and then try again')
			ClearSampleImage();
		}
		
		xmlhttp = null;
		
	}
}

function LoadMiniCart(text){
//debugger
	if(text != ""){
		if(dvCartID != null){
			var dvCart = document.getElementById(dvCartID)//flyoutright
			var currentUrl = window.location.href
//debugger
			if (currentUrl.toLowerCase().indexOf("ordersamples.aspx") >-1 )
			{
				if(dvCart)
				{
					dvCart.style.visibility = 'visible'
					dvCart.innerHTML = text
					document.getElementById("cart_container").className = 'sample_minicart'
					document.getElementById("flyout").className='sample_cart'
					document.getElementById("flyout_items").className='sample_cart_items'
				}
			}
			else if (currentUrl.toLowerCase().indexOf("mostpopular")>-1)
			{
				if (dvCart)
				{
					/*if (screen.width>=1200)
					{*/
						dvCart.style.visibility = 'visible'
						dvCart.innerHTML = text
						document.getElementById(dvCartID).style.visibility='visible'
						if (!document.all)
						{
//							document.getElementById("page_body").className = 'container_sc'
//							document.getElementById("page_left").className = 'container_blank'
//							document.getElementById("page_main").className = 'container_left'
							document.getElementById("cart_container").className = 'popular_minicart'
						}
			            else if (navigator.appVersion.indexOf('MSIE 8.0') > -1)
			                document.getElementById("cart_container").className = 'popular_minicart_ie8'
						else
							document.getElementById("cart_container").className = 'popular_minicart_ie'	
					
							document.getElementById("flyout").className ="popular_cart"
						    document.getElementById("flyout_items").className='popular_cart_items'	
	
						
					/*}
					else 
					{
						document.getElementById(dvCartID).style.visibility='hidden'
						document.getElementById("cart_container").className = 'minicart_hidden'
					}*/
				}
			}
            else if (currentUrl.toLowerCase().indexOf("article") > -1)
                document.getElementById("cart_container").className = 'minicart_articl'
            else if (currentUrl.toLowerCase().indexOf("photo") > -1)
                document.getElementById("cart_container").className = 'minicart_photo'
			else
			{
				//alert('dvCart:' + dvCart)
				if(dvCart){
				//debugger
					/*if (screen.width>=1200)
					{*/
						dvCart.style.visibility = 'visible'
						dvCart.innerHTML = text
				
						if (!document.all)
						{
							document.getElementById("cart_container").className = 'minicart'
//							document.getElementById("page_body").className = 'container_sc'
//							document.getElementById("page_left").className = 'container_blank'
//							document.getElementById("page_main").className = 'container_left'
						}
						else if (navigator.appVersion.indexOf('MSIE 8.0') > -1)
						    document.getElementById("cart_container").className = 'minicart_ie8'
						else
							document.getElementById("cart_container").className = 'minicart_ie'	
					/*}
					else
					{
						dvCart.style.visibility = 'hidden'
						document.getElementById("cart_container").className = 'minicart_hidden'
					}*/
				}
			}
		}
	}
	
}

function RefreshMiniCart(refreshUrl)
{
//debugger
    //if(screen.width>=1200 && refreshUrl.toLowerCase().indexOf("result")>-1)
	//alert('refreshUrl: ' + refreshUrl)
    if (refreshUrl.toLowerCase().indexOf("result") > -1 || refreshUrl.toLowerCase().indexOf("pdp.aspx") > -1)
		loadCart = true
	else
	    loadCart = false
		
	CreateXMLHTTP(path + "/Services/OneClickSample.aspx?loadCart=" + loadCart + "&refreshcart="+loadCart,
				        RefreshCart)
		 
}
function RefreshCart()
{
//debugger
	if(xmlhttp.readyState==4){
		bolIsReady = true
		if(xmlhttp.status==200){
			var myxml = xmlhttp.responseXML;
			var mytext = xmlhttp.responseText;
			//alert('mytext: ' + mytext)
			if( mytext != "false")
			{
				if(mytext != "true")
				{
					var dvCart = document.getElementById(dvCartID)
					//var dvFlyout=document.getElementById(dvFlyoutID)
					dvCart.style.visibility = 'visible'
					//dvFlyout.style.display='block'
					if (!document.all)
					{
//						document.getElementById("page_body").className = 'container_sc'
//						document.getElementById("page_left").className = 'container_blank'
//						document.getElementById("page_main").className = 'container_left'
						document.getElementById("cart_container").className = 'minicart'
		            }
					else if (navigator.appVersion.indexOf('MSIE 8.0') > -1)
					    document.getElementById("cart_container").className = 'minicart_ie8'
					else
					    document.getElementById("cart_container").className = 'minicart_ie'
					    
					dvCart.innerHTML=mytext;
				}
					
			}
		}
		else
		{
			alert('Sorry, we had a problem to refresh your cart. Please click your browser refresh button and then try again')

		}
	}
}
function SwapSampleImage(){
	var mySample = objSample
	var src = objSample.src
	if(arrSample.length > 0){
		mySample = document.getElementById(arrSample.shift())
		if(mySample)
			src = mySample.src
	}
	if (location.href.toLowerCase().indexOf("mostpopular")>-1)
	{
		mySample.src = src.substring(0, src.lastIndexOf("/")+1) + "top10_sample_added.gif"
	}
	else
	{
		mySample.src = src.substring(0, src.lastIndexOf("/")+1) + "sample_added.gif"
	}
	//alert('arrSample.length: ' + arrSample.length + ',mySample.src: ' + mySample.src + ',ID: ' + mySample.id)
}

function ClearSampleImage(){
	if(arrSample.length > 0){
		var len = arrSample.length 
		var idx
		for(idx = 0; idx < len; idx++){
			mySample = document.getElementById(arrSample.shift())
			if(mySample){
				src = mySample.src
				mySample.src = src.substring(0, src.lastIndexOf("/")+1) + "add_sample.gif"
			}
		}
	}
}

function displayEnlargeImage(enlargeDiv, e)
{
	var largeDv = document.getElementById(enlargeDiv)
	largeDv.style.display ="block"
}
function closeEnlargeImage(imageDiv)
{
	var enlargeDiv = document.getElementById(imageDiv)
	enlargeDiv.style.display="none"
}
function changeColor(elementId, colorCode)
{
	var elementDiv = document.getElementById(elementId)
	elementDiv.style.color = colorCode
}
function clickblePageUrl(pageUrl)
{
	location.href=pageUrl
}
function changeImage(elementId,imageName)
{
	var elementDiv = document.getElementById(elementId)
	elementDiv.src="snippet/Common_Images/"+ imageName
}

//****************** open catalog window **************
function OpenCatalogWindow(){
	var hasImg = 0
	var hasBrand = 0
	var hasMinOrder = 0
	var hasPrice = 0
	
//alert('OpenCatalogWindow ' + document.getElementById('chkBrandName').checked)
	if(document.getElementById('chkBrandName').checked) hasBrand = 1
	if(document.getElementById('chkProdImage').checked) hasImg = 1
	//if(document.getElementById('chkMinOrder').checked) hasMinOrder = 1
	if(document.getElementById('chkPrice').checked) hasPrice = 1

	openNewResizeBrowser('../catalog.aspx?img=' + hasImg + '&brand=' + hasBrand + '&price=' +  hasPrice , 835, 800)
}

//***********************************************************

//*********** CurMetric page Script *************************
function changeMetricTab(imgIndex, tabCount) {
	for (var i=0; i<tabCount; i++) {
		document.getElementById('div'+i).style.display = "none";
		document.getElementById('tab'+i).className = "tabOff"
	}

	document.getElementById('div'+imgIndex).style.display = "block";
	document.getElementById('tab'+imgIndex).className = "tabOn";
	tabFlag = imgIndex;
	
	SetDropDowns(imgIndex)
	ClearTxtUnit()
	
	ChangeMetric('txtUnit1')
}

function SetDropDowns(tabIdx){
	var ddl1 = document.getElementById('ddlUnit1')
	var ddl2 = document.getElementById('ddlUnit2')
	
	if(ddl1 != null && ddl2 != null){
		//clear dropdown list first
		RemoveOptions(ddl1)
		RemoveOptions(ddl2)
	}
	
	var arr1 = new Array();
	var arr2 = new Array();
	switch (tabIdx){
		case 0:
			arr1[0] = "Lineal Feet"
			arr1[1] = "Inches"
			arr2[0] = "Meters"
			break
		case 1: 
			arr1[0] = "Sq Ft"
			arr2[0] = "SqM"
			break
		case 2: 
			arr1[0] = "Pounds"
			arr2[0] = "Kilograms"
			break
		case 3:
			arr1[0] = "Quart"
			arr1[1] = "Gallon"
			arr2[0] = "Liter"
			break
	}
	
	AddDDLOptions(arr1, ddl1)
	AddDDLOptions(arr2, ddl2)
}


function GetConvertionRate(unitFrom, unitTo){
	/********* 1 Inch = 2.54 cm,1 Feet = 30.48 cm,1 Feet = 12 Inch *********/
	/********* 1 pound = 0.45 kg, 1000 sqft = 92.9 SqM			   *********/
	
	if(unitFrom == "LinealFeet" && unitTo == "Meters")
		return 0.3048
	else if(unitFrom == "Inches" && unitTo == "Meters")
		return 0.0254
	else if(unitFrom == "Inches" && unitTo == "Centimeters")
		return 2.54
	else if(unitFrom == "Inches" && unitTo == "Millimeters")
		return 25.4	
	else if(unitFrom == "SqFt" && unitTo == "SqM")
		return 0.09290304 
	else if(unitFrom == "Pounds" && unitTo == "Kilograms")
		return 0.45
	else if(unitFrom == "Quart" && unitTo == "Liter")
		return 0.946352946
	else if(unitFrom == "Gallon" && unitTo == "Liter")
		return 3.78541178 
	else
		return 1/GetConvertionRate(unitTo, unitFrom)		//if couldn't find the convert at first run, switch the unitTo and unitFrom, give another try
															//be aware infinit loop
}


function SetDDL2(){
	var ddl1 = document.getElementById('ddlUnit1')
	var ddl2 = document.getElementById('ddlUnit2')
	var arr2 = new Array();
	var val
	
	val = ddl1.options[ddl1.selectedIndex].value
	switch (val){
		case "Inches":
			arr2[0] = "Meters"
			arr2[1] = "Centimeters"
			arr2[2] = "Millimeters"	
			break
		case "LinealFeet":
			arr2[0] = "Meters"
			break
	}
	if(arr2.length > 0){
		RemoveOptions(ddl2)
		AddDDLOptions(arr2, ddl2)
	}
	
	ClearTxtUnit()
	
	ChangeMetric('txtUnit1')
}

function AddDDLOptions(arr, ddl){
	if(arr.length > 0 && ddl != null){
		var idx
		var op
		
		for (idx = 0; idx < arr.length; idx++){
			op = document.createElement('option')
			op.text = arr[idx]
			op.value = arr[idx].replace(' ', '')
			try{
				ddl.add(op, null)
			}
			catch(ex){
				ddl.add(op)
			}
		}
	}
	
}

function RemoveOptions(ddl){
	if(ddl != null){
		var len = ddl.length
		var idx
		
		for(idx = 0; idx < len; idx++){
			ddl.remove(0)
		}
		
	}
}

function ChangeCurrency(curFrom){
	var _curFrom, _curTo, _rate
	
	if(curFrom == 'USD'){
		_curFrom = 'USD'
		_curTo = document.getElementById('ddlCurrency').options[document.getElementById('ddlCurrency').selectedIndex].value
		_rate = FindExchangeRate(_curFrom, _curTo)
	//alert('_rate: ' + _rate)
		
		if(_rate == 0) 
			alert("Sorry, couldn't find exchange rate for converting currenct " + _curFrom + " to " + _curTo)
		else
			document.getElementById('txtCurrency').value = Round2TwoDigit(parseFloat(document.getElementById('txtUSD').value) * _rate)
	}
	else{
		_curFrom = document.getElementById('ddlCurrency').options[document.getElementById('ddlCurrency').selectedIndex].value
		_curTo = 'USD'
		_rate = FindExchangeRate(_curFrom, _curTo)
		if(_rate == 0) 
			alert("Sorry, couldn't find exchange rate for converting currenct " + _curFrom + " to " + _curTo)
		else
			document.getElementById('txtUSD').value = Round2TwoDigit(parseFloat(document.getElementById('txtCurrency').value) * _rate)
	}
	
	GetFinalResult()
}

function FindExchangeRate(curFrom, curTo){
	var xmldoc = zXmlDom.createDocument()
	var node
	var count,idx
	xmldoc.loadXML(xml)

	if(xmldoc != null){
		count = xmldoc.documentElement.childNodes.length
		
		var childNodes = xmldoc.documentElement.childNodes
		for(idx = 0; idx < count; idx++){
			node = childNodes[idx];
			//node:
			//<cur>
			//	<curFrom>AUD</curFrom> 
			//	<curTo>USD</curTo> 
			//	<rate>0.9319</rate> 
			//</cur>
			if(node.childNodes[0].text == curFrom && node.childNodes[1].text == curTo)
				return parseFloat(node.childNodes[2].text)
			else if(node.childNodes[0].text == curTo && node.childNodes[1].text == curFrom)
				return 1/parseFloat(node.childNodes[2].text)
		}
	}
	
	return 0
	
}

function NumbersEnterKeyOnly(e, ctlID){
//debugger
	var key
	var currency = ""
	if (window.event)
		key = window.event.keyCode;
	else if (e)
		key = e.which;
	
	if(ctlID == 'txtUSD')
		currency = 'USD'
	else
		currency = document.getElementById('ddlCurrency').options[document.getElementById('ddlCurrency').selectedIndex].value
	
	if(key == 13){
		ChangeCurrency(currency)
		return true
	}
	else
		return numbersonly(e)
	
}

function KeyUpEvent(e, ctlID){
	var txt
	var bolCurrency = true
	
	if(ctlID == 'txtUSD'){
		currency = 'USD'
		txt = document.getElementById('txtUSD').value
		bolCurrency = true
		
	}
	else if(ctlID == 'txtCurrency'){
		currency = document.getElementById('ddlCurrency').options[document.getElementById('ddlCurrency').selectedIndex].value
		txt = document.getElementById('txtCurrency').value
		bolCurrency = true
	}
	else if(ctlID == 'txtUnit1'){
		txt = document.getElementById('txtUnit1').value
		bolCurrency = false
	}
	else if(ctlID == 'txtUnit2'){
		txt = document.getElementById('txtUnit2').value
		bolCurrency = false
	}
	
	if(txt != "")
		if(bolCurrency)
			ChangeCurrency(currency)
		else
			ChangeMetric(ctlID)
	
}

function ChangeMetric(ctlID){
	var unitFrom, unitTo
	var ddl1 = document.getElementById('ddlUnit1')
	var ddl2 = document.getElementById('ddlUnit2')
	
	if(ctlID == 'txtUnit1'){
		unitFrom = ddl1.options[ddl1.selectedIndex].value
		unitTo = ddl2.options[ddl2.selectedIndex].value
		document.getElementById('txtUnit2').value = Round2Digit(parseFloat(document.getElementById('txtUnit1').value) * GetConvertionRate(unitFrom, unitTo), 4)
	}
	else{
		unitFrom = ddl2.options[ddl2.selectedIndex].value
		unitTo = ddl1.options[ddl1.selectedIndex].value
		document.getElementById('txtUnit1').value = Round2Digit(parseFloat(document.getElementById('txtUnit2').value) * GetConvertionRate(unitFrom, unitTo), 4)
	}
	
	GetFinalResult()
	
}

function GetFinalResult(){
	var txtUnit1 = document.getElementById('txtUnit1').value
	var txtUnit2 = document.getElementById('txtUnit2').value
	var txtUSD = document.getElementById('txtUSD').value
	var txtCurrency = document.getElementById('txtCurrency').value
	var ddl1 = document.getElementById('ddlUnit1')
	var ddl2 = document.getElementById('ddlUnit2')
	var ddl3 = document.getElementById('ddlCurrency')
	var lblUnit1 = document.getElementById('lblUnit1')
	var lblUnit2 = document.getElementById('lblUnit2')
	
	if(txtUnit1 == "" || txtUnit2 == "" || txtUSD == "" || txtCurrency == ""){
		lblUnit1.innerHTML = ""
		lblUnit2.innerHTML = ""
	}
	else{
		lblUnit1.innerHTML = "$" + Round2TwoDigit(parseFloat(txtUSD)/parseFloat(txtUnit1)) + " / " + FindSingular(ddl1.options[ddl1.selectedIndex].text)
		lblUnit2.innerHTML = "$" + Round2TwoDigit(parseFloat(txtCurrency)/parseFloat(txtUnit2)) + " " + ddl3.options[ddl3.selectedIndex].text + " / " + FindSingular(ddl2.options[ddl2.selectedIndex].text)
	}
}

function ClearTxtUnit(){
	ResetTxt('txtUnit1', '1')
	ResetTxt('txtUnit2', '')
}

function ClearTxtCurrency(){
	ResetTxt('txtUSD', '1')
	ResetTxt('txtCurrency', '')
}

function ResetTxt(txtID, value){
	document.getElementById(txtID).value = value
}

function Round2TwoDigit(num){
	return Round2Digit(num, 2)
}

function Round2Digit(num, digit) 
{
	var isNegative = false;
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num)) {num = new Number(0)} else { num = new Number(num); };
	if (num < 0) 
	{
		isNegative = true;
		num = num.toString().replace('-','');
	}
	
//alert('Round2Digit num: ' + num)
	if(digit == 2){
		cents = Math.floor((num*100+0.5)%100); 
		num = Math.floor(num+0.005).toString();
		if(cents < 10) cents = "0" + cents; 
	}
	else if(digit == 4){
		cents = Math.floor((num*10000+0.5)%10000); 
		num = Math.floor(num+0.00005).toString();
		if(cents < 10) 
			cents = "000" + cents; 
		else if(cents < 100)
			cents = "00" + cents;
		else if(cents < 1000)
			cents = "0" + cents;
	}
	
	if (isNegative) 
		return ('-' + num + '.' + cents); 
	else
		return (num + '.' + cents);
}

function FindSingular(str){
	switch(str){
		case "Lineal Feet":	return "Lineal Foot"
		case "Meters":		return "Meter"
		case "Inches":		return "Inch"
		case "Centimeters": return "Centimeter"
		case "Millimeters": return "Millimeter"
		case "Pounds":		return "Pound"
		case "Kilograms":	return "Kilogram"
	}
	
	return str
}

//***********************************************************
