/*--------------------------------------------------------------------

These functions are used on the /catalog/ shopping cart section.

--------------------------------------------------------------------*/



/* basic mouseover code */
function MM_swapImgRestore() { //v3.0
    var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
    var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
        var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
            if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
    var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
        d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
    if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
    for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
    if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
    var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
        if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}


function cantSaveCart()
{
    var msg = 'Your shopping cart is empty.';
    alert(msg);    
}

function cantCheckOut()
{
    var msg = 'Your shopping cart is empty.';
    alert(msg);
}

function confirmUserDelete()
{
    var msg = 'Are sure you want to delete this user?';
    return confirm(msg);    
}

function confirmSavedOrderDelete()
{
    var msg = 'Are sure you want to delete this saved order?';
    return confirm(msg);
}


function loadSubCategories(selectbox, id)
{
    if (selectbox.value == '')
        {        
        document.getElementById(id).innerHTML = '';
        obj = getTR(id);                    
        obj.className = 'hide';

        if (id == 'subcategorydiv')
            {
            id = 'subcategory2div';
            document.getElementById(id).innerHTML = '';
            obj = getTR(id);                    
            obj.className = 'hide';
        }

        return;
    }

    var obj = getTR(id);
    obj.className = '';
    document.getElementById(id).innerHTML = 'Loading...';

    try {
        var cat = document.getElementById('category').value;
    }
    catch (err) {var cat = 0;};

    try {
        var subcat = document.getElementById('subcategory').value;
    }
    catch (err) {var subcat = 0;};

    XMLRequest.GET('search.php?getSubcategories=' + cat + '&getSubcategories2='+ subcat, '', function (val) {

        var obj = document.getElementById(id);
        obj.innerHTML = val.responseText;

        if (val.responseText.length == 0)
            {
            var theTR = getTR(id);
            theTR.className = 'hide';

            if (id == 'subcategorydiv')
                {
                theTR = getTR('subcategory2div');
                theTR.className = 'hide';
                document.getElementById('subcategory2div').innerHTML = '';
            }
        }

    }, function (){ /*alert('error');*/ } );
}

function getTR(obj)
{
    if (String(typeof(obj)).toLowerCase() != 'object' )
        obj = document.getElementById(obj);

    while( String(obj.tagName).toLowerCase() != 'tr' )
    {
        obj = obj.parentNode;
    }

    return obj;
}

/*
function validateRegistrationPage()
{
var fields = ['UserName', 'FirstName', 'LastName', 'Company', 'Address', 'City', 'State', 'Zip', 'PhoneNo', 'FaxNo'];
var errorFound = false;
for (var x=0; x < fields.length; x++)
{
var field = document.getElementById(fields[x]);
field.className = field.className.replace(/[ ]?formError/g, '');
if (field.value.length == 0)
{
field.className += ' formError';
errorFound = true;
}
}

var pass = document.getElementById('Password');
pass.className = pass.className.replace(/[ ]?formError/g, '');

var repass = document.getElementById('RePassword');
repass.className = repass.className.replace(/[ ]?formError/g, '');

if (pass.value.length == 0)
{
pass.className += ' formError';
errorFound = true;
}

var err = document.getElementById('lblErr');
err.innerHTML = '';

if (pass.value != repass.value)
{
pass.className += ' formError';    
repass.className += ' formError';    
errorFound = true;
err.innerHTML = 'Passwords do not match';        
}

var email = document.getElementById('Email');
email.className = email.className.replace(/[ ]?formError/g, '');
if (email.value.match(/[^@]+[@][^.]+\.[^.]+/) == null)
{
email.className += ' formError';    
errorFound = true;
}

return !errorFound;
}

*/



/*----------------------------------------------------------------------------------
This function displays a preview image on the catalog browse page
----------------------------------------------------------------------------------*/
function showPreview(img, obj)
{
    hidePreview();

    if (img == '')
        return;

    document.getElementById('previewImg').src = '/catalog/products/' + img;

    if (obj != null)
        {
        var origObj = obj;

        var offsetX = 0;
        var offsetY = 0;
        do
        {
            offsetX += obj.offsetLeft;
            offsetY += obj.offsetTop;
        }
        while (obj = obj.offsetParent);

        // offsetY = the abs style['top'] location of the td, in px
        // image height = 200px + 1px border
        // origObj.parentNode.offsetHeight = height of the td
        document.getElementById('previewImg').style['top'] = (offsetY - 351 + origObj.parentNode.offsetHeight) + 'px';
        //document.getElementById('previewImg').style['left'] = (offsetX + 35) + 'px';
        document.getElementById('previewImg').style['left'] = 750 + 'px';
    }
}
function hidePreview()
{
    with (    document.getElementById('previewImg')    )
    {
        style['left'] = '-1000px';
        style['top'] = '0px';
        src = '/images/spacer.gif';
    }
}
function highlightRow(obj)
{
    unhighlightRow(obj);
    obj.className += ' highlight';
}
function unhighlightRow(obj)
{
    obj.className = obj.className.replace(/[ ]?highlight/, '');
}






//----------------------------------------------------------------------------------------------------------------
// This function automatically updates the total price when the user selcts a multipler or updates a quantity.
// sales_price = the intial price of this product (found by looking up the customer's contract code in the stock table)
// replacement_cost = the replacement cost (ie: listprice in the DB)
// tdnum is the number of the ROW, which is used to look up the quantity and multiplier amts by the ID
//----------------------------------------------------------------------------------------------------------------
function recalcPrice(sales_price, replacement_cost, tdnum, any_call_for_price_items)
{
    var amt = 0;
    var mult = document.getElementById('mult_' + tdnum);
    if (mult == null)
        mult=1;
    else
        {
        mult = Number(mult.value);

        var td = document.getElementById('priceTD_' + tdnum);
        //td.innerHTML = '$' + formatMoney(amt * mult);
    }

    //if multiplier is 1, use amt field for the price.  Otherwise, use the replacement cost.
    if (mult == 1){
        amt = sales_price;
    }else{
        amt = replacement_cost;
    }
    

    var totalTD = document.getElementById('totalTD_' + tdnum);
    var quant = cleanQty( document.getElementById('quant_' + tdnum) );

    var oldLineTotal = totalTD.innerHTML.replace(/[^0-9.]/g, '');
    var price_each = (Math.round(amt * mult * 100)/100);
    var newLineTotal = price_each * quant;

    if (newLineTotal == 0){
        totalTD.innerHTML = "**";
    }else{
        totalTD.innerHTML = '$' + formatMoney( newLineTotal );
    }

    // update price/ea field
    td.innerHTML = '$' + formatMoney( price_each );


    newLineTotal = String(newLineTotal).replace(/[^0-9.]/g, '');


    var diff = Number(newLineTotal) - Number(oldLineTotal);
    var preciseTotalTD = document.getElementById('preciseTotal');
    var preciseTotal = preciseTotalTD.innerHTML.replace(/[^0-9.]/g, '');
    var grandTotalTD = document.getElementById('grandTotal');
    var grandTotal = grandTotalTD.innerHTML.replace(/[^0-9.]/g, '');

    var adjGrandTotal = Number(preciseTotal) + Number(diff);
    var newMinFee = 0;
    preciseTotalTD.innerHTML = formatMoney( Number(adjGrandTotal) + Number(newMinFee) );
    if (any_call_for_price_items == false){

        var display_string;
        display_string = '<strong>Total:</strong> &nbsp;&nbsp;&nbsp;&nbsp;$';
        display_string = display_string + formatMoney( Math.round(Number(adjGrandTotal) + Number(newMinFee)) );
        if(adjGrandTotal < 500){
            display_string = display_string + ' (plus freight)';
        }
        grandTotalTD.innerHTML = display_string;
    }else{
        grandTotalTD.innerHTML = '<strong>Total:</strong> &nbsp;&nbsp;&nbsp;&nbsp;Call for total price';
    }

    startCartUpdateRequestTimer();


}






function cleanQty(inputObj)
{
    var quant = inputObj.value.replace(/[^0-9]/g, '').replace(/^([0-9]{1,5}).*$/g, '$1');
    if (quant != inputObj.value)
        inputObj.value = quant;

    return quant;
}

window.cartUpdateRequestTimer = 0;
function startCartUpdateRequestTimer()
{
    clearTimeout(window.cartUpdateRequestTimer);
    setTimeout('sendCartUpdateRequest()', 1000);
}

function sendCartUpdateRequest()
{
    clearTimeout(window.cartUpdateRequestTimer);

    var request = [];
    var theform = document.getElementById('cartform');

    for (var x=0; x < theform.elements.length; x++)
    {
        request[theform.elements[x].name] = theform.elements[x].value;
    }
    request['ajax'] = 'T';

    XMLRequest.POST( theform.action, '', request, function() {}, function() {} );
}

function formatMoney(price)
{
    price = Math.round(price * 100) / 100;
    // just in case there are any floating point issues...
    price = String(price).replace(/(\.[0-9]{2}).*/, '$1');
    price = price.replace(/(\.[0-9]{1})$/, '$1' + '0');
    if (price.indexOf('.') == -1)
        price += '.00';

    price = price.replace(/([0-9]{3}[.])+/, ',$1');
    price = price.replace(/([0-9]{3}[,])+/g, ',$1');
    price = price.replace(/^,/, '');
    return price;
}


function validateOptionForm(formObj)
{
    if (formObj.className.search(/tagcfmsp/i) == -1)
        return true;

    document.getElementById('tagcfmspError').className = 'hide';

    var fields = ['tag', 'cfm', 'staticpressure'];
    var isValid = true;
    for (var x=0; x < fields.length; x++)
    {
        var field = document.getElementById(fields[x]);
        field.className = field.className.replace(/formError/, '');
        field.value = field.value.replace(/^[ ]+/,'').replace(/[ ]+$/,'');    
        if (field.value.length == 0)
            {
            field.className += ' formError';
            isValid = false;
            document.getElementById('tagcfmspError').className = 'errorMsg';
        }
    }

    return isValid;
}



/* XMLRequest Object is C&P from http://www.bytemycode.com/snippets/snippet/526/ */
var XMLRequest=Object();
XMLRequest.buildQuery = function (query) {
    var data="";
    var first="?";
    for (i in query) {
        data+=first+escape(i)+"="+escape(query[i]);
        first="&";
    }
    return data;
}
XMLRequest.GET = function (url, query, callback, fallback) {
    var xmlhttp=null;
    if (window.XMLHttpRequest) {
        xmlhttp=new XMLHttpRequest()
    } else if (window.ActiveXObject) {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
    }
    if (xmlhttp!=null) {
        xmlhttp.onreadystatechange=function () {
            if (xmlhttp.readyState==4) {
                if (xmlhttp.status==200) callback(xmlhttp);
                else fallback(xmlhttp);
            }
        }
        var data = XMLRequest.buildQuery(query);
        xmlhttp.open("GET",url+data,true);
        xmlhttp.send("");
    }else{
        alert("Your browser does not support XMLHTTP.")
    }
}
XMLRequest.POST = function (url, query, form, callback, fallback) {
    var xmlhttp=null;
    if (window.XMLHttpRequest) {
        xmlhttp=new XMLHttpRequest()
    } else if (window.ActiveXObject) {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
    }
    if (xmlhttp!=null) {
        xmlhttp.onreadystatechange=function () {
            if (xmlhttp.readyState==4) {
                if (xmlhttp.status==200) {
                    callback(xmlhttp);
                } else {
                    fallback(xmlhttp);
                }

            }
        }
        var urldata = XMLRequest.buildQuery(query);
        var postdata = XMLRequest.buildQuery(form).substr(1);
        xmlhttp.open("POST",url+urldata,true);
        xmlhttp.setRequestHeader("Content-type" , "application/x-www-form-urlencoded");
        xmlhttp.setRequestHeader("Content-length", postdata.length);
        xmlhttp.setRequestHeader("Connection", "close");
        xmlhttp.send(postdata);
    }else{
        alert("Your browser does not support XMLHTTP.")
    }
}

