// JavaScript Document
var FLORIDA_SALES_TAX = .07

// Called by computeIt() function - creates $xx.xx format.
function formatPrice(num)
{
        if(isNaN(num))
        {
                num = "0";
        }

        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 getElementsByClass(SEARCHCLASS,NODE,TAG) {
        var classElements = new Array();
        if ( NODE == null )
                NODE = document;
        if ( TAG == null )
                TAG = '*';
        var els = NODE.getElementsByTagName(TAG);
        var elsLen = els.length;
        var pattern = new RegExp("(^|\\s)"+SEARCHCLASS+"(\\s|$)");
        for (i = 0, j = 0; i < elsLen; i++) {
                if ( pattern.test(els[i].className) ) {
                        classElements[j] = els[i];
                        j++;
                }
        }
        return classElements;
}

function totalQuantity()
{

        var intUnit;
        var tempUnitName = "";
        var tempUnit;
        var intTotalQuantity = 0;
        var        intUnitCount = document.forms[0].rowsCount.value; //TODO: Replace this assignment with a runtime value set by ASP during writeProducts() routine.

        // Sum all quantity values.
        var asQuantityFields = getElementsByClass("txtQuantity");

        for (var i = 0; i < asQuantityFields.length; i++)
        {
                 tempUnit = asQuantityFields[i];
                 intTotalQuantity += parseInt(tempUnit.value);

        }

        /*for(intUnit=1;intUnit<=intUnitCount;intUnit++)
        {
                tempUnitName = "unit" + intUnit;
                alert(tempUnitName);
                tempUnit = document.getElementById(tempUnitName);
                alert(tempUnit);
                intTotalQuantity += parseInt(tempUnit.value);
        }        */
        // Return total quantity of items.

        return intTotalQuantity;
}



function maxOnlineOrderQuantity(rObjTextInput,vIntMaxOnlineOrderQuantity)
{
        // Compare current total quantity and maximum allowed quantity.
        if(totalQuantity() > vIntMaxOnlineOrderQuantity)
        {
                // Notify user of quantity restriction.
                alert("Sorry, the maximum number of items you may purchase at one time \n"
                        + "through the website is 8. Please call us at 727-834-8944 to place larger orders.")
                // Set TEXT INPUT value to zero.
                rObjTextInput.value = '0';
        }
}


function checkTotalQtyZero(rObjTextInput)
{
        if(totalQuantity()==0)
        {
                // Notify user that zero items have been selected.
                alert("You haven't specified any quantities of items.\n"
                        + "Please enter a quantity of at least 1 for one of the available products.")
                // Return focus to trigger control.
                rObjTextInput.focus()
                // Validation failed.
                return false;
        }
        // Validation succeeded.
        return true;
}

function subtotal()
{
        var intUnit = 0;
        var intSubtotal = 0;
        var        intUnitCount = 9; //TODO: Replace this assignment with a runtime value set by ASP during writeProducts() routine.
        var intUnitSubtotal = 0;

        // Sum all quantity values.
        var asFields = getElementsByClass("txtQuantity");
        var tempElement;
        for (var i = 0; i < asFields.length; i++)
        {
                  tempElement = asFields[i];
                  intUnitSubtotal = unitSubtotal(tempElement);

                        intSubtotal += intUnitSubtotal;
        }

        /*for(intUnit=1;intUnit<=intUnitCount;intUnit++)
        {
                intUnitSubtotal = unitSubtotal(intUnit);
                // Sum all item subtotals into order subtotal.
                intSubtotal += intUnitSubtotal;
        }        */
        return intSubtotal;
}

function unitSubtotal(tempElement)
{
        var intUnitCount = 0;
        var intUnitCost = 0;
        var intUnitSubtotal = 0;

  var strID = tempElement.id.substring(4);


        // Calculate item subtotal.
        intUnitCount = parseFloat(tempElement.value);
        intUnitCost = parseFloat(document.getElementById("cost" + strID).value);

  //alert(strID + "|" + intUnitCount + "|" + intUnitCost);


        intUnitSubtotal = (intUnitCount * intUnitCost);



        // HGH
//        alert('intUnitCount:' + intUnitCount);
//        alert('intUnitCost: ' + intUnitCost);
//        alert('intUnitSubtotal: ' + intUnitSubtotal);
        // HGH


        // Update item subtotal TEXT INPUT at end of each line.
        document.getElementById("display_cost" + strID).value = formatPrice(intUnitSubtotal);
        return intUnitSubtotal;
}

function orderTaxAmount(vStrBillingState,vStrTaxState,vIntTaxRate,vIntSubtotal)
{
        var intTaxAmount = 0;

        if(vStrBillingState==vStrTaxState)
        {
                intTaxAmount = vIntSubtotal * vIntTaxRate;
        }
        return intTaxAmount;
}

function computeIt()
{
        var intTotal = 0;
        var intShippingCost = "";
        var intSalesTax = 0
        var intSubtotal = 0;
        var intGrandTotal = 0;
        var objPackage = new thePackage();
        var form = document.forms[0];
        // Calculate subtotal.
//JA        intSubtotal += subtotal();
        intSubtotal = parseFloat(form.subtotal.value); //JA: quantities are now static on checkout
        // Calculate Sales Tax for Florida Residents.
        intSalesTax = orderTaxAmount(form.billTo_state[form.billTo_state.selectedIndex].value,'FL',FLORIDA_SALES_TAX,intSubtotal);
        // Add tax amount to grand total.
        intGrandTotal += intSubtotal + intSalesTax;
        // Calculate order shipping charges.
        /*
        objPackage.inventory()
        objPackage.pack();

        intShippingCost = objPackage.cost;
        */
        intShippingCost = orderShippingCost(intGrandTotal);
        // Add shipping cost to grand total.
        intGrandTotal += intShippingCost;

        // Present tax amount in form TEXT INPUT.
        document.forms[0].display_shipping.value = formatPrice(intShippingCost);
        document.forms[0].taxAmount.value = formatPrice(intSalesTax);
        document.forms[0].amount.value = formatPrice(intGrandTotal);

        var strDesc = "";
        // TODO: Concatenate all product descriptions to comments textbox value.
        form.comments.value = strDesc;
}

function orderShippingCost(intGrandTotal){
        if(document.forms[0].shipping.value=="USPM"){
                if(intGrandTotal<=59.96){
                        return 4.95
                } else if(intGrandTotal<=159.92){
                        return 8.95
                } else if(intGrandTotal<=239.88){
                        return 9.95
                }
        } else {
                if(intGrandTotal<=59.96){
                        return         9.50
                } else if(intGrandTotal<=159.92){
                        return 12.50
                } else if(intGrandTotal<=239.88){
                        return 15.50
                }
        }
}

function orderShippingCostOLD()
{
        var strShippingMethod;
        var intTotalQuantity;
        var intShippingCost;

        // Customer's selected shipping method. (USPM OR USGPM).
        strShippingMethod = document.forms[0].shipping[document.forms[0].shipping.selectedIndex].value;
        // Sum number of items ordered.
        intTotalQuantity = totalQuantity();
        // Calculate shipping cost based on selected shipping method and total quantity.
        if (strShippingMethod=="USPM")
        {
                if(intTotalQuantity>=1&&intTotalQuantity<=4){
                        intShippingCost = 4.95
                } else if(intTotalQuantity>=5&&intTotalQuantity<=8){
                        curShip = 6.95
                } else if(intTotalQuantity>=9&&intTotalQuantity<=10){
                        curShip = 9.95
                } else {
                        curShip = 0
                }
        } else if(strMethod=="USGPM") {
                if(intTotalQuantity>=1&&intTotalQuantity<=4){
                        intShippingCost = 8.95
                } else if(intTotalQuantity>=5&&intTotalQuantity<=6){
                        intShippingCost = 9.95
                } else if(intTotalQuantity>=7&&intTotalQuantity<=8){
                        intShippingCost = 11.95
                } else if(intTotalQuantity>=9&&intTotalQuantity<=10){
                        intShippingCost = 12.95
                } else {
                        intShippingCost = 0
                }
        }
}

function getItem(vIntCount,vStrColor,vStrProductCode)
{
        if(vIntCount>0)
        {
                return "[" + vIntCount + " : " + vStrColor + " " + vStrProductCode + "]"
        } else {
                return ""
        }
 }

function preserveZero(rObjTextInput)
{
        var CheckNum;

        CheckNum = parseFloat(rObjTextInput.value);

        if((rObjTextInput.value.length==0)||(isNaN(CheckNum)))
        {
                rObjTextInput.value = '0';
        }
}

function MM_openBrWindow(theURL,winName,features)
{ //v2.0
        window.open(theURL,winName,features);
}


function goodchars(e, goods)
{
        var key, keychar;

        key = getkey(e);

        if (key == null)
        {
                return true;
        }
        // get character
        keychar = String.fromCharCode(key);
        keychar = keychar.toLowerCase();
        goods = goods.toLowerCase();

        // check goodkeys
        if (goods.indexOf(keychar) != -1)
        {
                return true;
        }
        // control keys
        if ( key==null || key==0 || key==8 || key==9 || key==13 || key==27 )
        {
                return true;
        }
        // else return false
        return false;
}

function getkey(e)
{
        if (window.event){
           return window.event.keyCode;
        }else if(e){
           return e.which;
        }else{
           return null;
        }
}

function updateCountry(oSection)
{
        var oFrm = window.document.myform;
        var oState

        if(oSection=="bill")
        {
                oState = oFrm.billTo_state;
                oCountry = oFrm.billTo_country;
        }else if(oSection=="ship"){
                oState = oFrm.shipTo_state;
                oCountry = oFrm.shipTo_country;
        }

        var intState = oState.selectedIndex;

        if(intState>=61)
        {
                oCountry.selectedIndex=1;
                if(oSection=="ship")
                {
                        if(oFrm.shipping.selectedIndex!=1)
                        {
                                alert("You have modified the Shipping destination country.\n" +
                                        "This will automatically recalculate the shipping rate.\n" +
                                        "Please review your cart totals before submitting your order.")
                        }
                        oFrm.shipping.selectedIndex=1;
                }
        } else if(intState<=59) {
                oCountry.selectedIndex=0;
                if(oSection=="ship")
                {
                        if(oFrm.shipping.selectedIndex!=0)
                        {
                                alert("You have modified the Shipping destination country.\n" +
                                        "This will automatically recalculate the shipping rate.\n" +
                                        "Please review your cart totals before submitting your order.")
                        }
                        oFrm.shipping.selectedIndex=0;
                }
        } else {
                alert("This is not a valid selection for the " + oSection + " state.\nPlease select a valid state.");
        }
}

function updateShipData(){
        if(oChk.checked){
                //??????
        } else {
        //??????
        }
}

var shipTo_firstName = "";
var shipTo_lastName = "";
var shipTo_company = "";
var shipTo_street1 = "";
var shipTo_street2 = "";
var shipTo_city = "";
var shipTo_state = "";
var shipTo_stateIndex = 0;
var shipTo_postalCode = "";
var shipTo_country = "";
var shipTo_countryIndex = 0;
var shipTo_phoneNumber = "";

function InitSaveVariables(form)
{
        shipTo_firstName = form.shipTo_firstName.value;
        shipTo_lastName = form.shipTo_lastName.value;
        shipTo_company = form.shipTo_company.value;
        shipTo_street1 = form.shipTo_street1.value;
        shipTo_street2 = form.shipTo_street2.value;
        shipTo_city = form.shipTo_city.value;
        shipTo_stateIndex = form.shipTo_state.selectedIndex;
        shipTo_state = form.shipTo_state[shipTo_stateIndex].value;
        shipTo_postalCode = form.shipTo_postalCode.value;
        shipTo_countryIndex = form.shipTo_country.selectedIndex;
        shipTo_country = form.shipTo_country[shipTo_countryIndex].value;
        shipTo_phoneNumber = form.shipTo_phoneNumber.value;
}

function shipToBillPerson(form)
{
        if (form.shipTo_same_as_billTo.checked)
        {
                InitSaveVariables(form);
                form.shipTo_firstName.value = form.billTo_firstName.value;
                form.shipTo_lastName.value = form.billTo_lastName.value;
                form.shipTo_company.value = form.billTo_company.value;
                form.shipTo_street1.value = form.billTo_street1.value;
                form.shipTo_street2.value = form.billTo_street2.value;
                form.shipTo_city.value = form.billTo_city.value;
                form.shipTo_state.selectedIndex = form.billTo_state.selectedIndex;
                form.shipTo_postalCode.value = form.billTo_postalCode.value;
                form.shipTo_country.selectedIndex = form.billTo_country.selectedIndex;
                form.shipTo_phoneNumber.value = form.billTo_phoneNumber.value;
        } else {
                form.shipTo_firstName.value = shipTo_firstName;
                form.shipTo_lastName.value = shipTo_lastName;
                form.shipTo_company.value = shipTo_company;
                form.shipTo_street1.value = shipTo_street1;
                form.shipTo_street2.value = shipTo_street2;
                form.shipTo_city.value = shipTo_city;
                form.shipTo_state.selectedIndex = shipTo_stateIndex;
                form.shipTo_postalCode.value = shipTo_postalCode;
                form.shipTo_country.selectedIndex = shipTo_countryIndex;
                form.shipTo_phoneNumber.value = shipTo_phoneNumber;
   }
   updateCountry("ship");
   computeIt();
}