var posleft = 0;
var posright = 0;

function getElemPosition(curelem)
{    
    for (posleft = 0, postop = 0; curelem.offsetParent; curelem = curelem.offsetParent) 
	{
		posleft += curelem.offsetLeft;
		postop += curelem.offsetTop;
	}
}

//function roundNumber(rnum) {
//    var rlength = 2; // The number of decimal places to round to
//    if (rnum > 8191 && rnum < 10485) {
//	    rnum = rnum-5000;
//	    var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
//	    newnumber = newnumber+5000;
//    } else {
//	    var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
//    }
//    return rnum;
//}

function roundNumber(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;
    return (num + '.' + cents);
}

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 showHover(srcelem)
{
	var cfore,cback;
	var src;	

	if (srcelem != null)	
		src = srcelem;
	
	if (src.style.backgroundColor == '#b06a24')		
		return;

	//for firefox
	if (src.style.backgroundColor == 'rgb(176, 106, 36)')
		return;
	
	if (src.style.backgroundColor == '#f0efef')	
		src.style.backgroundColor = "#C9C7C7";
	else
		src.style.backgroundColor = "#f0efef";
}

//used to show hover for side menu
var prevsidebackground = "";
var prevselecteddiv = null;
var selectedInnerdiv = null;

var prevselecteddiv2 = null;
var selectedInnerdiv2 = null;

function showHoverSide(src,action)
{
	//alert (document.getElementById("cidcategory").value);	
	if (src.className == 'selectedmenuinner' || src.id.substring(1) == document.getElementById("cidcategory").value)
		return;	

	if (action == 1){ //1 = over
		prevsidebackground = src.style.backgroundColor;	
		src.style.backgroundColor = "#C9C7C7";				
		if (src.childNodes[0].id == 'imgspan')
			src.childNodes[0].innerHTML = "<IMG SRC='../images/orangeselectarrow.gif' width='9' height='9' border='0' class='menuimg'  alt='left'>&nbsp;&nbsp;&nbsp;";
	}
	else{
		src.style.backgroundColor = prevsidebackground;
		prevsidebackground = "";
		if (src.childNodes[0].id == 'imgspan')
			src.childNodes[0].innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
	}
}

var prevcenterbackground = "";
function showHoverCenter(src,action)
{
	if (src.style.backgroundColor == '#b06a24')
		return;

	if (action == 'over'){
		prevcenterbackground = src.style.backgroundColor;	
		src.style.backgroundColor = "#C9C7C7";		
	}
	else{
		src.style.backgroundColor = prevcenterbackground;
		prevcenterbackground = "";
	}
}

function showMenu(curdiv,idcategory)
{
	var intxt = "";
	curdiv.className = "currentinnermenu";
	
	for (var x=0;x<menuArray.length;x++){
        if (menuArray[x][0] == idcategory){
			//alert(menuArray[x][5]);
			if (menuArray[x][5] == 'Always' || menuArray[x][5] == 'SubCat'){
				displaylevel = menuArray[x][5];
				intxt += "<div style='cursor:pointer;' class='leftmenuinner'"
				intxt += " onmouseover='showHoverSide(this,1)' onmouseout='showHoverSide(this,0)'"
				intxt += " onclick='menuClick(" + x + ")' title='" + menuArray[x][3] +"'><span id='imgspan'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>"
				intxt += menuArray[x][2] + "</div>";		
			}
			else{
				idcategory2 = menuArray[x][1];
				displaylevel = menuArray[x][5];
				intxt += "<div style='cursor:pointer;' class='currentinnermenu'"
				intxt += " onmouseover='showHoverSide(this,1)' onmouseout='showHoverSide(this,0)'"
				intxt += " onclick='showMenu2(this," + idcategory2 + ");'"
				intxt += " title='" + menuArray[x][3] +"'>"
				intxt += "<span id='imgspan'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>"
				intxt += menuArray[x][2] + "</div>";
				intxt += "<div id='divMenu2" + idcategory2 + "' style='position:relative;display:none;'></div>"
			}		
		}
	}

	//make prevselecteddiv white
	if (prevselecteddiv != null){
		if (displaylevel != 'SubCat')		
			prevselecteddiv.className = 'innermenu';
	}		
	
	prevselecteddiv = curdiv;	
	
	//make inner div not selected
	if (selectedInnerdiv != null)
		selectedInnerdiv.style.display='none';		
		
	selectedInnerdiv = document.getElementById('divMenu' + idcategory);
	
	selectedInnerdiv.innerHTML = intxt;				
	//setTimeout("selectedInnerdiv.style.display='block'",500);
	selectedInnerdiv.style.display='';			
}

//for second level (von duprin and monarch)
function showMenu2(curdiv,idcategory)
{
	var intxt = "";
	curdiv.className = "currentinnermenu";
	
	//make prevselecteddiv2 lowercase
	if (prevselecteddiv2 != null)
		prevselecteddiv2.className = 'currentinnermenu';			
	prevselecteddiv2 = curdiv;	
	
	//make inner div2 not selected
	if (selectedInnerdiv2 != null)
		selectedInnerdiv2.style.display='none';		
		
	selectedInnerdiv2 = document.getElementById('divMenu2' + idcategory);
	
	for (var x=0;x<menuArray.length;x++){
        if (menuArray[x][0] == idcategory){
			intxt += "<div style='cursor:pointer;' class='leftmenuinner2'"
			intxt += " onmouseover='showHoverSide(this,1)' onmouseout='showHoverSide(this,0)'"
			intxt += " onclick='menuClick(" + x + ")' title='" + menuArray[x][3] +"'><span id='imgspan'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>"
			intxt += menuArray[x][2] + "</div>";			
		}
	}
	
	selectedInnerdiv2.innerHTML = intxt;				
	//setTimeout("selectedInnerdiv.style.display='block'",500);
	selectedInnerdiv2.style.display='';			
}

function menuClick(arrnum)
{
	location = menuArray[arrnum][4];
}

function hideMenu(curdiv,action)
{
	if (action == 'show'){
		curdiv.style.display='';
	}
	else{
		curdiv.style.display='none';
		//selecteddiv.style.backgroundColor = prevsidebackground;
		//prevsidebackground = "";
	}
}

//validates checkout on cart.asp
function validateCheckout(minimum)
{	
	if (document.getElementById('savestate').value == 1){
		alert("Please update your cart.")
		return false;
	}
	
	var totalcart = document.getElementById('totalcart').value;
	
	if (minimum == 1000)
	{
	    if (document.getElementById('belowminimum').value == 0)
        {
	        if (totalcart < 1000 && totalcart >= 100)
	        {
		        document.getElementById('divBelowMin').style.display = "";
		        return false;
	        }
	        else if (totalcart < 100)
	        {
                alert("The minimum purchase amount is $100.00");
                return false;
            }
	    }	    
	}
	
	if (validateOpen() == false)
		return false;
		
	return true;
}

function showBelowMinMessage(curelem,display)
{
    if (display == 1)
    {
        curelem.className = "txtLinkOver";
        document.getElementById('divBelowMinMessage').style.display = "";
    }
    else
    {
        curelem.className = "txtLink";
        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()
{
	if (document.getElementById('isclosedwarning').value == 1){
	    if (!confirm("Our offices are closed " + document.getElementById("closeddates").value + ".\nYour order will be processed after we reopen.\nDo you want to proceed with the order?"))
	        return false;
	}
	return true;
}

function displayCartConfirm()
{
	document.getElementById('divcartmessage').style.display='';
	document.getElementById('tblrightcart').style.border= '5px solid #5E5D5D';
	//document.getElementById('divcartmessage').style.top = document.getElementById('tblrightcart').offsetTop + 20;
	setTimeout("document.getElementById('divcartmessage').style.display='none'",5000);
	setTimeout("document.getElementById('tblrightcart').style.border= '0px';",5000);
}

function highlightItem(idproduct)
{
    var curelem = document.getElementById('tditem' + idproduct);
    if (curelem)
    {
        curelem.style.backgroundColor= 'yellow'; //#5E5D5D';
        getElemPosition(curelem);
        window.scrollTo(posleft,(postop-300));
    }		
}

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;
}
	
function validateDelete()
{
	if (!confirm("Are you sure you want to delete this item?"))
		return false;
	return true;
}	



//used on CurrentDeals.asp to check if cust entered a number and the number > 0
//var globalvar;
function ckNumeric(curelem)
{
    if( (isNaN(curelem.value)) || (curelem.value < 0) )
    {
        alert("Please enter a correct quantity number.");
        curelem.value = "";
	    
        //globalvar = curelem; 
        //setTimeout("globalvar.focus();return false;",0);    
        
        curelem.focus();     
    }
}

function calculateCurrentDeals()
{
    var quantity = 0;
    var price;
    var curitemtotal = 0;
    var total = 0;
    var existingCart = false;
    
    var inelem = document.getElementsByTagName("INPUT");	
    var j=0;
    for (i=0;i<inelem.length;i++)
    {		
		if (inelem[i].id.indexOf("quantity") > -1)
		    {		        
		        price = 0;
		        curitemtotal = 0;
		        if (inelem[i].value != '')
		        {
		            quantity = inelem[i].value;		            
		            price = document.getElementById('dealprice' + j).value;
		            price = parseFloat(price);
		            curitemtotal = quantity * price;
		            if (document.getElementById('idcartrow' + j).value > 0)
		                existingCart = true;
		            document.getElementById('subtotal' + j).innerHTML = "&nbsp;" + formatCurrency(curitemtotal) + "&nbsp;";
		            document.getElementById('tdClear' + j).style.display = '';
		        }
		        else
		        {
		            document.getElementById('subtotal' + j).innerHTML = "&nbsp;";
		            document.getElementById('tdClear' + j).style.display = 'none';
		            document.getElementById('tdStar' + j).style.display = 'none';
		        }
		        total += parseFloat(curitemtotal);	       
		        j++; 
		    }		
	}			
	
	if (total > 0)
	    document.getElementById('dealtotal').innerHTML = formatCurrency(total);
	else
	    document.getElementById('dealtotal').innerHTML = "&nbsp;";
	
	document.getElementById('hidDealTotal').value = roundNumber(total);
	
	if (existingCart == true) //then allow to update current deals
	    document.getElementById('btnUpdateDeals').style.display = '';
    else
    {		
        if (total >= 1000 && document.getElementById('btnUpdateDeals').style.display == 'none')
            document.getElementById('btnAddDeals').style.display = '';
        else
            document.getElementById('btnAddDeals').style.display = 'none';       
    }
}


function clearQuantity(colnum)
{
    document.getElementById('quantity' + colnum).value = "";
    calculateCurrentDeals();
}

//Loop through items to calculate current-deal totals. If current-deal totals are less than 1000, alert customer.
function validateCurrentDeals()
{	
	//if (document.getElementById('savestate').value == 1){
	//	alert("Please update your cart.")
	//	return false;
	//}
	
	var quantity = 0;
    var price;
    var curitemtotal = 0;
    var total = 0;
    
    var inelem = document.getElementsByTagName("INPUT");	
    var j=0;
    for (i=0;i<inelem.length;i++)
    {		
		if (inelem[i].id.indexOf("quantity") > -1)
		    {		        
		        price = 0;
		        curitemtotal = 0;
		        if (inelem[i].value != '')
		        {
		            quantity = inelem[i].value;		            
		            price = document.getElementById('dealprice' + j).value;
		            price = parseFloat(price);
		            curitemtotal = quantity * price;
		        }
		        
		        total += parseFloat(curitemtotal);	       
		        j++; 
		    }		
    }	
    
    if (total < 1000)
    {
        if (!confirm("You did not reach $1000 of Current-Deals required to qualify for Current-Deal prices.\nDo you want to continue to cart without Current-Deal prices?"))
		    return false;
	}
	
	return true;

}

function validateDeleteDeal()
{
	if (!confirm("This item is already in your cart.\nDo you want to delete this item from your cart?"))
		return false;
	return true;
}	

//deletes product in cart on currentdeals.asp
function deleteDealInCart(colnum,curIDCartRow)
{
    if (document.getElementById('tdStar' + colnum).style.display == 'none')//then it was already deleted previously from database. So go straight to clearQuantity(colnum)
    {
        clearQuantity(colnum);
        return;
    }
    
    if (validateDeleteDeal())
    {
        var param = "&idCartRow=" + curIDCartRow;
	    //alert(param);
	    var xmlHttp = DoCallback('updateframe.asp?action=delItem',param);
        
        xmlHttp.onreadystatechange=function() 
	    {
		    if (xmlHttp.readyState==4) 
		    {
			    strResponse = xmlHttp.responseText;		    
			    if (strResponse.length >0){
			        document.getElementById('idcartrow' + colnum).value = 0; //since it's deleted from database, it's not a cartrow 
				    clearQuantity(colnum);
				    //alert(strResponse);
			    }
		    }
	    }	
        //document.frames("updateframe").location="updateframe.asp?action=delItem&idCartRow=" + curIDCartRow;
        //clearQuantity(colnum);
    }
}

//Popup of product details. Used on CurrentDeals.asp
function showProductDetails(curelem,idproduct)
{
    getElemPosition(curelem);
    
    var param = "&idproduct=" + idproduct;
    //alert(param);
    var xmlHttp = DoCallback('productdetailsframe.asp?action=displaydetails',param);
    
    
    setTimeout(xmlHttp.onreadystatechange=function() 
    {	    	
	    if (xmlHttp.readyState==4) 
	    {	        
	        strResponse = xmlHttp.responseText;	
	        
	        if (strResponse.length > 0){
	            document.getElementById("divproductdetails").innerHTML = strResponse;	            
	            
	            document.getElementById("divproductdetails").style.left = (posleft - 75) + "px";
	            document.getElementById("divproductdetails").style.top = (postop - 130) + "px";
	            document.getElementById("divproductdetails").style.display = "";
	        }
	    }
    },100);
}

//Close popup of product details. Used on CurrentDeals.asp
function closeProductDetails()
{
    document.getElementById("divproductdetails").innerHTML = "";
    document.getElementById('divproductdetails').style.display = 'none';
}


function DoCallback(url, params)
{
	var pageUrl = url + params;
	
	var xmlHttp = null;
	if (window.XMLHttpRequest) //IE7, Mozilla
	    xmlHttp = new XMLHttpRequest();
	else if (window.ActiveXObject)	//IE5, 6
	{
	    try
	    {
	        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
	    }
	    catch(e){}
	}
	xmlHttp.open("GET", pageUrl, true);
	xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xmlHttp.send(null);
	return xmlHttp;
}

function changePaymentMethod(paymenttype)
{
    if (paymenttype == 'CreditCard')
    {
        document.getElementById("tblwire").style.display = "none";
        document.getElementById("tblcc").style.display = "";
    }
    else
    {
        document.getElementById("tblwire").style.display = "";
        document.getElementById("tblcc").style.display = "none";
    }
}
   
