var callbackTimeout = 0;
var callbackFunction = "";
document.onclick = function() {HandleCallbackEvent();}
document.onkeyup = function() {HandleCallbackEvent();}

function HandleCallbackEvent()
{
    if (callbackTimeout > 0)
    {
        setTimeout(callbackFunction, callbackTimeout);
        callbackTimeout = 0;
        callbackFunction = "";
    }
}

function Checkout()
{
    //this variable is set by the checkout control..if it exists, the checkout control is on this page.
    if (checkoutDivID)
    {
        //show checkout control.
        div = findElement(checkoutDivID);
        if (div)
        {
            if (div.style.display == "none")
                div.style.display = "block";
            else
                div.style.display = "none";
        }
    }
}

function findElement(id){
    if (document.getElementById)
    { 
	    return document.getElementById(id);
    }
    else if(document.all)
    {
	    return document.all[id];
    }
    else if(document.layers)
    {
	    return document.layers[id];
    }
    else
    {
	    return null;
    }
}

function SetLastPageCookie(lastpage)
{
    if (lastpage.indexOf('Cart.htm') < 0)
    {
        SetCookie("LastPage", lastpage, 3, '/');
    }
}

function GoToLastPage(pageprefix)
{
    window.location = pageprefix + GetCookie('LastPage');
}

function SetItemCount(item, newCount)
{
    //if newCount is -1, that means increment items by 1. 
    //otherwise, use the newCount that is specified.
    
    var itemAlreadyInCart = false;
    var itemInCustomCart = false;
    var customCartSplit;
    var cartSplit;
    var count;
    
    cartSplit = GetCartArray();
    customCartSplit = GetCustomCartArray();
    
    //search the cart array to see if this item's already in there.
    for (var index=0; index < cartSplit.length; index++)
    {
        if (cartSplit[index].substring(0,item.length + 1) == (item + ':'))
        {
            itemAlreadyInCart = true;
            var itemSplit = cartSplit[index].split(':');
            
            if (newCount < 0)
            {
                //just incrementing the old count...
                newCount = parseInt(itemSplit[1], 10) + 1;
            }
            itemSplit[1] = newCount;
            
            //rebuild string.
            cartSplit[index] = itemSplit.join(':');
        }
    }
    
    if (!itemAlreadyInCart)
    {
        //search custom the cart array to see if this item's already in there.
        for (var index=0; index < customCartSplit.length; index++)
        {
            if (customCartSplit[index].substring(0,item.length + 1) == (item + ':'))
            {
                itemInCustomCart = true;
                var itemSplit = customCartSplit[index].split(':');
                
                if (newCount < 0)
                {
                    //just incrementing the old count...
                    newCount = parseInt(itemSplit[2], 10) + 1;
                }
                itemSplit[2] = newCount;
                
                //rebuild string.
                customCartSplit[index] = itemSplit.join(':');
            }
        }
        
        if (newCount < 0 && itemInCustomCart == false)
        {
            newCount = 1;
        }
        
        //append new item to the array
        if (itemInCustomCart == false)
            cartSplit.push(item + ':' + newCount);
    }
    
    //reset cart cookie
    SetCookie('Cart', cartSplit.join('|'), 3, '/');
    SetCookie('CartCustom', customCartSplit.join('|'), 3, '/');
    
    //update numberitemsincart
    updateNumberItemsInCart();
}

function AddToCart(item)
{
    SetItemCount(item, -1);
}

function ClearCookie(name)
{
    SetCookie(name, null, -1, '/');
}

function SetCookie(name, value, expires, path, domain) 
{
    expDate=new Date();
    if (expires) 
    {
        // Exipration Date set in an increment of Days
        expDate.setDate(expDate.getDate()+expires);
    }
    var curCookie = name + '=' + escape(value) +
            ((expires) ? '; expires=' + expDate.toGMTString() : '') +
            ((path) ? '; path=' + path : '') +
            ((domain) ? '; domain=' + domain : '');
    document.cookie = curCookie;
}
function GetCookie(name) 
{
    var prefix = name + '=';
    var cookieStartIndex = document.cookie.indexOf(prefix);
    if (cookieStartIndex == -1)
    {
        return '';
    }
    
    var cookieEndIndex = document.cookie.indexOf(';', cookieStartIndex + prefix.length);
    if (cookieEndIndex == -1)
    {
        cookieEndIndex = document.cookie.length;
    }
    
    return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex));
}

function RemoveItem(item)
{  
    var foundInCart = false;
    var foundInCustomCart = false;
    var cartSplit = GetCartArray();
    var customCartSplit = GetCustomCartArray();
    
    // search the cart array to find this item.
    for (var index=0; index < cartSplit.length; index++)
    {
        if (cartSplit[index].substring(0,item.length + 1) == (item + ':'))
        {
            // remove the item.
            cartSplit.splice(index,1);
            foundInCart = true;
        }
    }
    
    if (foundInCart == true)
    {
        // reset cart cookie if the item was in the Cart cookie.
        SetCookie('Cart', cartSplit.join('|'), 3, '/');
    }
    else
    {
        for (var index=0; index < customCartSplit.length; index++)
        {
            if (customCartSplit[index].substring(0,item.length + 1) == (item + ':'))
            {
                // remove the item.
                customCartSplit.splice(index,1);
                foundInCustomCart = true;
            }
        }
    
        if (foundInCustomCart == true)
        {
            // reset custom cart cookie if the item was in the CustomCart cookie.
            ClearCookie('CartCustom');
        }
    }
    
    Postback();
}

function GetCustomCartArray()
{
    var customCartString = GetCookie('CartCustom');
    var customCartSplit = new Array();
    
    if (customCartString != '')
    {
        customCartSplit = customCartString.split('|');
    }
    
    return customCartSplit;
}

function GetCartArray()
{
    var cartString = GetCookie('Cart');
    var cartSplit = new Array();
    
    if (cartString != '')
    {
        cartSplit = cartString.split('|');
    }
    
    return cartSplit;
}

function RemoveAllItems()
{
    ClearCookie('Cart');
    ClearCookie('CartCustom');
    Postback();
}

function ResetCartStyle()
{
    var NumberItemsInCart = findElement('NumberItemsInCart');
    
    if (NumberItemsInCart)
    {
        var cartSplit = GetCartArray();
        var customCartSplit = GetCustomCartArray();
        var totalItems = 0;
        var itemTotal = 0;
        
        for (var index=0; index < cartSplit.length; index++)
        {
            var itemSplit = cartSplit[index].split(':');
            itemTotal = parseInt(itemSplit[1], 10);
            
            totalItems += itemTotal;
        }
        
        for (var index=0; index < customCartSplit.length; index++)
        {
            var itemSplit = customCartSplit[index].split(':');
            itemTotal = parseInt(itemSplit[2], 10);
            totalItems += itemTotal;
        }

        if (totalItems == 0)
            NumberItemsInCart.innerHTML = "";
        else
            NumberItemsInCart.innerHTML = "(" + totalItems + ")";
    }
}

function Postback()
{
    __doPostBack(null, null);
}

function updateNumberItemsInCart()
{
    var NumberItemsInCart = findElement('NumberItemsInCart');
    
    if (NumberItemsInCart)
    {
        callbackTimeout = 2000;
        callbackFunction = "ResetCartStyle()";
        
        var cartSplit = GetCartArray();
        var customCartSplit = GetCustomCartArray();
        var totalItems = 0;
        var itemTotal = 0;

        for (var index=0; index < cartSplit.length; index++)
        {
            var itemSplit = cartSplit[index].split(':');
            itemTotal = parseInt(itemSplit[1], 10);
            
            totalItems += itemTotal;
        }
        
        for (var index=0; index < customCartSplit.length; index++)
        {
            var itemSplit = customCartSplit[index].split(':');
            itemTotal = parseInt(itemSplit[2], 10);
            totalItems += itemTotal;
        }

        if (totalItems == 0)
            NumberItemsInCart.innerHTML = "";
        else
            NumberItemsInCart.innerHTML = "<font style='font-size:12px;font-weight:bold;color:#9c624b;'>(" + totalItems + ")</font>";
            
        window.scrollTo(0, 0);
    }
}

var printableCheckoutPath;
var checkoutClientControlHeader;
function PrintableForm()
{
    //i can't use a second form on the page, so i have to pass this all by querystring.
    var qs = 'language=' + escape(findElement(checkoutClientControlHeader + 'hidLanguage').value);
    qs += '&firstName=' + escape(findElement(checkoutClientControlHeader + 'txtFirstName').value);
    qs += '&lastName=' + escape(findElement(checkoutClientControlHeader + 'txtLastName').value);
    qs += '&emailAddress=' + escape(findElement(checkoutClientControlHeader + 'txtEmailAddress').value);
    qs += '&address1=' + escape(findElement(checkoutClientControlHeader + 'txtAddress1').value);
    qs += '&address2=' + escape(findElement(checkoutClientControlHeader + 'txtAddress2').value);
    qs += '&address3=' + escape(findElement(checkoutClientControlHeader + 'txtAddress3').value);
    qs += '&telephone=' + escape(findElement(checkoutClientControlHeader + 'txtTelephone').value);
    qs += '&city=' + escape(findElement(checkoutClientControlHeader + 'txtCity').value);
    qs += '&state=' + escape(findElement(checkoutClientControlHeader + 'txtState').value);
    qs += '&zip=' + escape(findElement(checkoutClientControlHeader + 'txtZip').value);
    qs += '&notes=' + escape(findElement(checkoutClientControlHeader + 'txtNotes').value);
    qs += '&dealer=';
    var dealerDropdown;
    var byStateRadio = findElement(checkoutClientControlHeader + 'radSelectEmailByState');
    var byNameRadio = findElement(checkoutClientControlHeader + 'radSelectEmailByName');
    var byCountryRadio = findElement(checkoutClientControlHeader + 'radSelectEmailByCountry');
    if ((byStateRadio) && (byStateRadio.checked))
    {
        dealerDropdown = findElement(checkoutClientControlHeader + 'drpSelectEmailByState');
    }
    else if ((byNameRadio) && (byNameRadio.checked))
    {
        dealerDropdown = findElement(checkoutClientControlHeader + 'drpSelectEmailByName');
    }
    else if ((byCountryRadio) && (byCountryRadio.checked))
    {
        dealerDropdown = findElement(checkoutClientControlHeader + 'drpSelectEmailByCountry');
    }
    
    if (dealerDropdown)
    {
        var dealerValue = dealerDropdown.options[dealerDropdown.selectedIndex].value;
        //looks like 123456|email@email.com, where 123456 is dealer number.
        var dealerSplit = dealerValue.split('|');
        qs += dealerSplit[0];
    }
    else
    {
        qs += escape(findElement(checkoutClientControlHeader + 'txtManualEmail').value);
    }
    
    window.open(printableCheckoutPath + '?' + qs, 'printableCheckout');
}

function EnableDisableFields(fields, enabled)
{
    var field;
    var arrFields = fields.split('|');
    for (var i=0; i<arrFields.length; i++)
    {
        field = findElement(checkoutClientControlHeader + arrFields[i]);
        if (field)
        {
            field.disabled = !enabled;
        }
    }
}

function ValidateNumeric(element)
{
    if (element.value=="" || isNaN(element.value))
    {
        element.value = '0';
        element.select();
        return false;
    }
    
    return true;
}
