var posleft = 0;
var postop = 0;

function getElemPosition(curelem)
{    
    for (posleft = 0, postop = 0; curelem.offsetParent; curelem = curelem.offsetParent) 
	{
		posleft += curelem.offsetLeft;
		postop += curelem.offsetTop;
	}
}

function hover(curelem)
{
    if (curelem.className == "boxouter")
        curelem.className = "boxouter2";
    else
        curelem.className = "boxouter";
}

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 disableEnterKey(e)
{
     var key;
     if(window.event)
          key = window.event.keyCode;     //IE
     else
          key = e.which;     //firefox

     if(key == 13)
          return false;
     else
          return true;
}


//used to show hover for top menu
/*Credits: Dynamic Drive CSS Library */
/*URL: http://www.dynamicdrive.com/style/ */
var menuids=["submenu"] //Enter id(s) of SuckerTree UL menus, separated by commas

function buildsubmenus_horizontal(){	
	for (var i=0; i<menuids.length; i++){
	  var ultags=document.getElementById(menuids[i]).getElementsByTagName("ul");
		for (var t=0; t<ultags.length; t++){
			if (ultags[t].parentNode.parentNode.id == menuids[i]){ //if this is a first level submenu
				ultags[t].style.top = ultags[t].parentNode.offsetHeight + "px" //dynamically position first level submenus to be height of main menu item
			    
			    var longest = 0;
			    var width;
			    
			    //find longest text in group
			    for (var v=0; v<ultags[t].getElementsByTagName("a").length; v++)
			    {
			        if (longest < ultags[t].getElementsByTagName("a")[v].innerHTML.length)			    
			            longest = ultags[t].getElementsByTagName("a")[v].innerHTML.length;
			    }			    
			    //set width of all <li> tags within this group based on longest line
			    width = 50 + (longest * 6);			    
			    for (var w=0; w<ultags[t].getElementsByTagName("li").length; w++)
			    {
			        ultags[t].getElementsByTagName("li")[w].style.width = width + "px";
			        ultags[t].getElementsByTagName("a")[w].style.width = (width-15) + "px";
			    }
			    
			    ultags[t].style.width = width + "px";
			    
			    //if (t != (ultags.length-1)) //add right border for all elements till last element 
			    //   ultags[t].parentNode.style.borderRight  = "solid #3EA131 1px";
			    
			    //determine direction where menu starts
			    //if there is less than width of <ul> on the right, then the menu starts at the right edge of the top
			    getElemPosition(ultags[t]);
		        if((posleft + width) > 950)			    
		            ultags[t].style.left = (ultags[t].parentNode.offsetWidth - width) + "px";
			}
			else{ //else if this is a sub level menu (ul)
			  ultags[t].style.left=ultags[t-1].getElementsByTagName("a")[0].offsetWidth+"px"; //position menu to the right of menu item that activated it
			}
			
			if( document.getElementById('selted1') != ultags[t].parentNode ){
				ultags[t].style.visibility = "hidden";
				ultags[t].parentNode.onmouseover=function(){
					this.getElementsByTagName("ul")[0].style.visibility = "visible";
					
					//nb keep parent ul the selected color
					this.getElementsByTagName("ul")[0].parentNode.className = "navtophover";
					
					if( document.getElementById('selted1') )
						document.getElementById('selted1').getElementsByTagName("ul")[0].style.visibility = "hidden";
					}
				ultags[t].parentNode.onmouseout=function(){
					this.getElementsByTagName("ul")[0].style.visibility = "hidden";
					
					//nb change parent ul to default color
					this.getElementsByTagName("ul")[0].parentNode.className = "navtop";
					
					if( document.getElementById('selted1') )
						document.getElementById('selted1').getElementsByTagName("ul")[0].style.visibility = "visible";
					}
			}
		}

	}
}
if (window.addEventListener)
window.addEventListener("load", buildsubmenus_horizontal, false)
else if (window.attachEvent)
window.attachEvent("onload", buildsubmenus_horizontal)
//end top menu


//Used in cart to confirm that customer will delete item
function validateDelete(obj)
{
	if (!confirm("Are you sure you want to delete this " + obj + "?"))
		return false;
	return true;
}

//function validateCheckout()
//{
//	if (document.getElementById('savestate').value == 1){
//		alert("Please update your cart.");
//		return false;
//	}
//	return true;
//}

//function validateCheckoutMinimum()
//{
//	if (document.getElementById('savestate').value == 1)
//		alert("Please update your cart.");
//	else
//	    alert('The minimum purchase amount is $375.00');
//	return false;
//}

//validates checkout on shoppingcart.aspx
function validateCheckout(curelem,minorder,minorderSurcharge,totalcart)
{	
	if (document.getElementById('savestate').value == 1){
		alert("Please update your cart.")
		return false;
	}

	if (minorder > 0) //then minimum required
	{
        if ((totalcart < parseInt(minorder)) && (totalcart >= parseInt(minorderSurcharge)))
        {
            getElemPosition(curelem);
            document.getElementById('divBelowMin').style.top = (postop - 50) + "px";
            
            document.getElementById('divBelowMin').style.display = "";
            return false;
        }
        else if (totalcart < parseInt(minorderSurcharge))
        {
            alert("The minimum purchase amount is $" + minorderSurcharge);
            return false;
        }	    
	}
	
	return true;
}

function showBelowMinMessage(curelem,display)
{
    if (display == 1)
    {
        curelem.className = "MinimumOrderLinkOver";
        document.getElementById('divBelowMinMessage').style.display = "";
    }
    else
    {
        curelem.className = "MinimumOrderLink";
        document.getElementById('divBelowMinMessage').style.display = "none";
    }
}

function validateCart()
{
	if (document.getElementById('totalcart').value < 1){
		alert("Your shopping cart is empty");
		return false
	}
	return true;
}

function validateOpen(closeddates)
{
	if (!confirm("Our offices are closed " + closeddates + ".\nYour order will be processed after we reopen.\nDo you want to proceed with the order?"))
	    return false;
	
	return true;
}

//used on shoppingcart.aspx to check if customer is getting multiples of boxquantity
function validateqtycart()	
{
	var inputelem = document.getElementsByTagName("input");
	var qty, qtyallowed, qtyextra, qtyelem, x;
	var qtyarray = new Array();
	//var qtyallowedarray = new Array();
	x = 0;
	for(i=0;i<inputelem.length;i++){			
		if(inputelem[i].id.indexOf('BoxQuantity') > -1){
			qtyarray[x] = new Array(3);
			qtyarray[x][0] = inputelem[i].value;								
		}
		
		//check if item is qty order
		if(inputelem[i].id.indexOf('qtyquoted') > -1){
			qtyarray[x][1] = inputelem[i].value;
		}
		
		if(inputelem[i].id.indexOf('uxQuantityText') > -1){
			qtyarray[x][2] = inputelem[i].value;	
			qtyarray[x][3] = inputelem[i].id;	
			inputelem[i].style.backgroundColor = "white";
			x++;				
		}			
	}
	
	for (i=0;i<x;i++){			
		qty = parseInt(qtyarray[i][2]);		
		qtyallowed = parseInt(qtyarray[i][0]);  
		qtyelem = qtyarray[i][3];
		qtyextra = qty%qtyallowed; 			
			
		if (qtyextra != 0 && qtyallowed != 0){  
			document.getElementById(qtyelem).style.backgroundColor = "red";      
			alert("Order must be in multiples of " + qtyallowed + ".\nPlease order " + (qty + (qtyallowed-qtyextra)) + ".");
			document.getElementById(qtyelem).focus();
			return false;
		}
		
		//check if item is qty order
		qtyquoted = parseInt(qtyarray[i][1]);
		if (qtyquoted > 0){
			if (qty < qtyquoted){
				document.getElementById(qtyelem).style.backgroundColor = "red";  
				alert("This item is a quoted quantity order and has a minimum of " + qtyquoted + ".");
				document.getElementById(qtyelem).focus();
				return false;
			}
		}
	}

	return true;
}

//used on shoppingcart.asp to show popup of orderitem
function displayOrderItemDetails(curelem, productid, optionsid, stockitem, idqty)
{   
    var intxt = "";    
    var producttxt = "";
    var optionstxt = "";    
    
    var arrSplit;
    var optionprice = "";   
    
    var productprefix;
    var productprice;
    
    //show options
    if (optionsid != "")
    {
        optionstxt = "<br /><div class='formareapopup'>";
        optionstxt += "<p><b>Selected Options:</b></p>";
        optionstxt += "<table cellpadding='0' cellspacing='5px'>";
                
        arrSplit = optionsid.split(",");
        for (i=0;i<arrSplit.length;i++)
        {
            curoptionid = arrSplit[i];
            for (j=0;j<cartOptionDetailsArray.length;j++)
            {
                if (curoptionid == cartOptionDetailsArray[j][0])
                {
                    if (cartOptionDetailsArray[j][3] != "")
                    {
                        optionprice = cartOptionDetailsArray[j][3];
                        
                        if (parseFloat(optionprice) > 0)
                            optionprice = " +" + formatCurrency(cartOptionDetailsArray[j][3]);
                        else
                            optionprice = "";
                    }
                    
                    optionstxt += "<tr>";
                    if (cartOptionDetailsArray[j][2] != "")
                        optionstxt += "<td><img src='" + cartOptionDetailsArray[j][2] + "'/></td>";
                    else
                        optionstxt += "<td>&nbsp;</td>";
                    optionstxt += "<td>" + cartOptionDetailsArray[j][1] + "</td>";                    
                                        
                    optionstxt += "<td>" + optionprice + "</td></tr>";
                    
                    productprefix = cartOptionDetailsArray[j][4];
                }
            }            
        }
        
        optionstxt += "</table></div>";
    }    
    
    
    //show product
    producttxt = "<div class='formareapopup'>";
    for (x=0;x<cartProductDetailsArray.length;x++)
    {
        if (productid == cartProductDetailsArray[x][0])
        {
            producttxt += "<p><img src='" + cartProductDetailsArray[x][2] + "'></p>";
            producttxt += "<p>" + cartProductDetailsArray[x][1] + "</p>";
            
            productprice = cartProductDetailsArray[x][3];
            if (productprefix == "PR")
                productprice = productprice * 2;
            producttxt += "<p>" + formatCurrency(productprice) + "</p>";
            break;
        }
    }    
    producttxt += "</div>";
    
    intxt = producttxt + optionstxt;
    
//    //lead time
//    if (idqty == "") //then show lead time
//        {
//        if (stockitem == "True")
//        {
//            intxt += "<table cellpadding='0' cellspacing='5px'>";
//            intxt += "<tr><td>Lead Time: Ships within 7-10 business days.</td></tr></table>";
//        }
//        else
//        {
//            intxt += "<table cellpadding='0' cellspacing='5px'>";
//            intxt += "<tr><td>Lead Time: Non-Stock item. Ships within 4-6 weeks.</td></tr></table>";
//        }      
//    }  
    
    document.getElementById("divorderitemdetailsintxt").innerHTML = intxt;
    
    getElemPosition(curelem);

    document.getElementById("divorderitemdetails").style.left = (posleft - 50) + "px";
    
    if (optionsid != "")
        document.getElementById("divorderitemdetails").style.top = (postop - 400) + "px";     
    else // no options. so shorter popup
        document.getElementById("divorderitemdetails").style.top = (postop - 250) + "px"; 
        
    document.getElementById("divorderitemdetails").style.display = "";  
}

function closeOrderItemDetails()
{
    document.getElementById("divorderitemdetails").style.display = "none";     
}
//end of popup of orderitem

//Used to confirm that customer accepts policy
function validateAccept()
{
    if (document.getElementById("ctl00_uxPlaceHolder_chkAccept").checked == false){
        alert("You must accept the terms and conditions before completing this order.\nPlease read the full terms and conditions and scroll down to accept.");        
        return false;
    }
    return true;
}

//Validate Credit Card
function validateCard()
{
	var idPrefix = "ctl00_uxPlaceHolder_";
	var varcardType = document.getElementById(idPrefix + "CreditCartTypeDropDownList").value;
	var varcardNum = document.getElementById(idPrefix + "CreditCardNumberTextBox").value;
	var varmt = document.getElementById(idPrefix + "ExpMonthDropDownList").value;
	var varyr = document.getElementById(idPrefix + "ExpYearDropDownList").value;
	var varcvv2 = document.getElementById(idPrefix + "CVV2TextBox").value;
	varcardNum = varcardNum.replace(/\s/g,"");
	
	//Card Type
	if (varcardType == ""){
		alert("Please select the Credit Card Type");
		document.getElementById(idPrefix + "CreditCartTypeDropDownList").focus();
		return false;
	}
			
	//Card #		
	if (varcardNum == ""){
		alert("Please enter the Card Number");
		document.getElementById(idPrefix + "CreditCardNumberTextBox").focus();
		return false;
	}
			
	//CVV2	
	if (varcvv2 == ""){
		alert("Please enter the Card Verification #");
		document.getElementById(idPrefix + "CVV2TextBox").focus();
		return false;
	}		
	
	//check if user entered 3#'s for MC/Visa or 4 #'s for American Exp
	if (varcardType=="American Express"){
		if (varcvv2.length != 4){
			alert("Please enter a 4 digit CVV for American Express");
			return false;
		}
	}
	else{
		if (varcvv2.length != 3){
			alert("Please enter a 3 digit CVV for Visa or Mastercard");
			return false;
		}
	}

	//Expiration Month
	if (varmt == ""){
		alert("Please select the Exp Month");
		document.getElementById(idPrefix + "ExpMonthDropDownList").focus();
		return false;
	}
	
	//Exp Year
	if (varyr == ""){
		alert("Please select the Exp Year");
		document.getElementById(idPrefix + "ExpYearDropDownList").focus();
		return false;
	}	
	
	//check if card expired
	var myDate=new Date();
	myDate.setDate(myDate.getDate());
	var curmt = myDate.getMonth()+1;
	var curyr = myDate.getFullYear();
	if (varyr == curyr){
		if (varmt < curmt){
			alert("Invalid date.");			
			return false;
		}
	}

	return true;
}

//begin functions for customer billing & shipping info
//if billing country is outside US, show NonUS popup msg
function toggleNonUSMsg(curelem)
{
    //get position
    var posleft = 0;
    var posright = 0;
    for (posleft = 0, postop = 0; curelem.offsetParent; curelem = curelem.offsetParent) 
	{
		posleft += curelem.offsetLeft;
		postop += curelem.offsetTop;
	}
    
    if (document.getElementById("divNonUS").style.display == "none")
    {
    	document.getElementById("divNonUS").style.left = (posleft) + "px";
	    document.getElementById("divNonUS").style.top = (postop - 220) + "px";
        document.getElementById("divNonUS").style.display = "";
    }
    else
        document.getElementById("divNonUS").style.display = "none";
}

//if billing country is outside US, show textbox by state
function displayNonUSMsg(curselect)
{
    var statedrop = document.getElementById("ctl00_uxPlaceHolder_uxCustomerRegister_uxStateList_uxStateDrop");
    var statetext = document.getElementById("ctl00_uxPlaceHolder_uxCustomerRegister_uxStateList_uxStateText");
    
    if (!statedrop)
    {
        statedrop = document.getElementById("ctl00_uxPlaceHolder_uxStateList_uxStateDrop");
        statetext = document.getElementById("ctl00_uxPlaceHolder_uxStateList_uxStateText"); 
    }
    
    if( curselect.value == 'US' )
    {        
        //statedrop.disabled = false;
        statedrop.value = '';
        statetext.style.visibility = 'hidden';
        document.getElementById( 'tdNonUS' ).style.display = 'none';
        
        if (statedrop.value == 'AK' || statedrop.value == 'HI')
            shippingAsBillingOption(0);
        else
            shippingAsBillingOption(1);
    }
    else 
    {
        statedrop.value = 'OT';
        //statedrop.disabled = true;
        statetext.style.visibility = 'visible';
        document.getElementById( 'tdNonUS' ).style.display = '';
        toggleNonUSMsg(curselect);   
        
        shippingAsBillingOption(0);
    }
}

//if billing country is outside US, disable shipping as billing 
function shippingAsBillingOption(display)
{    
    var elemprefix = "ctl00_uxPlaceHolder_uxCustomerRegister_";    
    tdUseBillingAsShippingElem = document.getElementById(elemprefix + "tdUseBillingAsShipping");
    tdDoNotUseBillingAsShippingElem = document.getElementById(elemprefix + "tdDoNotUseBillingAsShipping");
        
    if (!tdUseBillingAsShippingElem)
    {
        elemprefix = "ctl00_uxPlaceHolder_";
        tdUseBillingAsShippingElem = document.getElementById(elemprefix + "tdUseBillingAsShipping");
        tdDoNotUseBillingAsShippingElem = document.getElementById(elemprefix + "tdDoNotUseBillingAsShipping");
    }
    
    if (display == 1)
    {
        tdUseBillingAsShippingElem.style.display = '';
        tdDoNotUseBillingAsShippingElem.style.display = 'none';    
    }
    else
    {
        tdUseBillingAsShippingElem.style.display = 'none';
        tdDoNotUseBillingAsShippingElem.style.display = ''; 

        document.getElementById(elemprefix + "uxUseBillingAsShipping").checked = false; 
        document.getElementById(elemprefix + "uxShippingFirstName").disabled = false; 
        document.getElementById(elemprefix + "uxShippingLastName").disabled = false; 
        document.getElementById(elemprefix + "uxShippingCompany").disabled = false; 
        document.getElementById(elemprefix + "uxShippingAddress1").disabled = false; 
        document.getElementById(elemprefix + "uxShippingAddress2").disabled = false;
        document.getElementById(elemprefix + "uxShippingCity").disabled = false;
        document.getElementById(elemprefix + "uxShippingStateList_uxStateDrop").disabled = false; 
        document.getElementById(elemprefix + "uxShippingZip").disabled = false;
        document.getElementById(elemprefix + "uxShippingPhone").disabled = false; 
        document.getElementById(elemprefix + "uxShippingFax").disabled = false;         
    }
}
//end of functions for customer billing & shipping info

