﻿// javascript file
function ManageTabPanelDisplay () {
var idlist = new Array ('tab1focus','tab2focus','tab3focus','tab1ready','tab2ready','tab3ready','content1','content2','content3');

if(arguments.length < 1) {
    return;
    }
for(var i = 0; i < idlist.length; i++) {
    var block = false;
    for(var ii = 0; ii < arguments.length; ii++) {
        if(idlist[i] == arguments[ii]) {
            block = true;
            break;
            }
        }
    if(block) { 
//        document.write('Block is True');
        document.getElementById(idlist[i]).style.display = "block"; 
        } else {
        //document.write('Block is False');
        document.getElementById(idlist[i]).style.display = "none"; 
        }
    }
}

function CheckEnter(e) {
    var characterCode
    if(e && e.which) { //if which property of event object is supported (NN4)
        e = e;
        characterCode = e.which; //character code is contained in NN4's which property
    }
    else {
        e = window.event;
        characterCode = e.keyCode;
    }
    if(characterCode == 13) { // enter key
        document.forms[0].submit;
    }    
}
function CalculateQtyTotal() {
    
    // This fires when any quantity for any size gets modified by customer.
    // Loop through all input boxes for quantities (SM, Med, etc.) and gather
    // how many items were entered, then sum them up to get total order qty
    // This total quantity is then used to calculate price for the entire
    // order for S-XL. Than as these prices are populated into price boxes
    // for each quantity, size surchages are being added to XXL, XXXL, etc.
    // In this case all input text form elements that contain size quantities
    // have the same id of SizeQty, while each has a name of the actual size
    // for example SM, MED, etc.
    
    var total = 0, totalCost = 0;
    var arrayQty = getElementsById("SizeQty");
    var objQty, intQty, totalPrice;
    var arrayCost, objCost, intCost; 
    //variables for updating additional costs
    var targetControl, objSenderCheckBox, objSenderInputText, UnitAdditionalCost, SetupAdditionalCost;

    for (var i = 0; i < arrayQty.length; i++) {
        objQty = arrayQty[i];
        if (objQty.value.length > 0)
            intQty = parseFloat(objQty.value);
        else
            intQty = 0;
        total += intQty;
    }
    document.forms[0].elements["TotalQty"].value = total;
    totalPrice = getPrice(total); //this is price for S-XL based on total order qty
    populateSizePrices(totalPrice);
    totalCost = CalculateTotalCost();
    document.forms[0].elements["TotalCost"].value = formatCurrency(totalCost);
    // update additional cost for 1 line underneath Tackle Twill or additional line of large text
    var array0 = getGroupElementNames("CostLine");
    for (var ii = 0; ii < array0.length; ii++) {
        targetControl = document.forms[0].elements[array0[ii]];
        objSenderCheckBox = document.forms[0].elements["AddLineCheck"+array0[ii].substring(array0[ii].indexOf('$'),array0[ii].length)];
        objSenderInputText = document.forms[0].elements["AddLineText"+array0[ii].substring(array0[ii].indexOf('$'),array0[ii].length)];
        UnitAdditionalCost = 2; 
        targetControl.value=calculateAdditionalCost(objSenderCheckBox, objSenderInputText, UnitAdditionalCost);
    }
    // end Tackle Twill and Large Text
    // update additional cost for 3-rd line of personalization
    var array0 = getGroupElementNames("CostLinePers");
    for (var ii = 0; ii < array0.length; ii++) {
        targetControl = document.forms[0].elements[array0[ii]];
        objSenderCheckBox = document.forms[0].elements["AddLinePersCheck"+array0[ii].substring(array0[ii].indexOf('$'),array0[ii].length)];
        objSenderInputText = document.forms[0].elements["AddLinePersText"+array0[ii].substring(array0[ii].indexOf('$'),array0[ii].length)];
        UnitAdditionalCost = 1; 
        targetControl.value=calculateAdditionalCost(objSenderCheckBox, objSenderInputText, UnitAdditionalCost);
    }
    // end Tackle Twill and Large Text
    // update additional cost for 2-color or 3-color screen print
    checkMultiColor ();
    // sum up everything and divide by total quantity
    calcAvgPrice();
}
    function calcAvgPrice() {
    // after all elements of the price have been calculated, add them all and divide
    // by total qty to get all inclusive (average) price
    var total = 0;
    var arrayCost = getElementsById("Cost");
    var intQty = parseFloat(document.forms[0].elements["TotalQty"].value);
    var intAvgCost = 0;
    for (var i = 0; i < arrayCost.length; i++) {
        objCost = arrayCost[i];
        if (objCost.value.length > 0)
        {
            intCost = parseFloat(objCost.value.replace(",","").substr(1));
        }
        else
            intCost = 0;
        total += intCost;
    }
    if (intQty == 0)
        intAvgCost = 0;
    else
        intAvgCost = total/intQty;
    //update average (all-inclusive) cost 
    document.forms[0].elements["AvgPrice"].value = formatCurrency(intAvgCost);
    //also update the total cost form field after all fixed and setup charges have been calculated
    document.forms[0].elements["TotalCostWithSetup"].value = formatCurrency(intAvgCost*intQty);        
}
function getPrice(totalQty) {

    // QtyRangePrice is a hidden object on the form that has already been calculated
    // in the Instant Quote section. We now need to pair it with the actual quantities
    // that customer enters in the order boxes. As they enter quantity, find the 
    // price that would apply based on entered quantity and price qty range.
    
    // the sale price is always populated; if item not on sale it is same as QtyRangePrice
    var arrayQtyRangePrice = getElementsById("QtyRangeSalePrice");
    var objQtyRangePrice;
    var strQtyRange;
    var totalPrice; 
    var index, index2;
    var intQty = parseFloat(totalQty);
    for (var i = 0; i < arrayQtyRangePrice.length; i++) {
        objQtyRangePrice = arrayQtyRangePrice[i];
        strQtyRange = objQtyRangePrice.name;
        index = strQtyRange.indexOf(" - ");
        index2 = strQtyRange.indexOf("+"); 
        // Quantity falls in the range, for example 12-24
        if (intQty >= parseFloat(strQtyRange.substring(0,index))&&
            intQty <= parseFloat(strQtyRange.substr(index + 3))) 
        {
            totalPrice = objQtyRangePrice.value;
            break;
        }
        // quantity is 144+
        else if (intQty >= parseFloat(strQtyRange.substring(0,index2)))
        {
            totalPrice = objQtyRangePrice.value;
            break;
        }
        // quantity is less than minimum    
        else if (intQty < parseFloat(strQtyRange.substring(0,index)))
        {
            totalPrice = objQtyRangePrice.value;
            break;
        }
        else
        {
                totalPrice = "n/a";
        }
    }
    return totalPrice;
}
    
function populateSizePrices(totalPrice) {

    // Size surcharge is stored in the title of SizePrice input field
    // Add surcharge to the calculated price
    
    var total = 0;
    var intSizeSurcharge = 0;
    var arraySizePrice = getElementsById("SizePrice");
    var objSizePrice; 
    for (var i = 0; i < arraySizePrice.length; i++) {
        objSizePrice = arraySizePrice[i];
        intSizeSurcharge = parseFloat(objSizePrice.title);
        objSizePrice.value = formatCurrency(parseFloat(totalPrice.replace(",","").substr(1)) + intSizeSurcharge);
    }
}

function CalculateTotalCost() {
    
    // multiply each size quantity by the corresponding price, that was
    // calculated in the previous step. Qty and Price input fields have
    // same names, their ID's are different

    var total = 0, totalCost = 0;
    var arrayQty = getElementsById("SizeQty");
    var arrayPrice = getElementsById("SizePrice");    
    var objQty, objPrice, intQty = 0;
    for (var i = 0; i < arrayQty.length; i++) {
        objQty = arrayQty[i];
        if (objQty.value.length > 0)
            intQty = parseFloat(objQty.value);
        else
            intQty = 0;
        for (var j = 0; j < arrayPrice.length; j++) {
            objPrice = arrayPrice[j]; 
            if (objQty.name == objPrice.name) 
            {
                total = intQty * parseFloat(objPrice.value.substr(1));
                totalCost += total;
                total = 0;
                break;
            }
        }
    }
    return totalCost;
}
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 calculateAdditionalCost(objSenderCheckBox, objSenderInputText, UnitAdditionalCost) {

    // Multiply Total Qty by the unit Additional Cost, for example when adding one line underneath tackle twill
    // Additional cost is always associated with a check box and an input text
    // If checkbox is checked calculate total price, otherwise clear the input text and set cost to zero
    // This function is called from each check box for additional cost and also must be called for
    // each check box from CalculateQtyTotal for the case when additional cost is checked first and then some 
    // quantities added or removed, to pick up latest quantities

    var intQty = parseFloat(document.forms[0].elements["TotalQty"].value);
    var intCost = parseFloat(UnitAdditionalCost);
    
    if (objSenderCheckBox.checked == true) 
        return formatCurrency(intCost*intQty);
    else 
    {
        objSenderInputText.value = "";
        return formatCurrency(0);
    }
}

function calculateAdditionalCost2(objSenderCheckBox, SetupAdditionalCost, UnitAdditionalCost) {

    // Multiply Total Qty by the unit Additional Cost and add fixed setup cost
    // SetupAdditionalCost is a multiplier for originally chosen setup ($25) or reorder ($8) cost

    var intQty = parseFloat(document.forms[0].elements["TotalQty"].value);
    //there is only one element with this name, using array for convenience of using existing function
    var array1 = getGroupElementNames("ScreenCost");
    for (var ii = 0; ii < array1.length; ii++) {
        var targetControl = document.forms[0].elements[array1[ii]];
        var intSetupCost = parseFloat(SetupAdditionalCost) * parseFloat(targetControl.value.replace(",","").substr(1));
    }
    var intUnitCost = parseFloat(UnitAdditionalCost);
    if (objSenderCheckBox.checked == true) 
        return formatCurrency(intUnitCost*intQty + intSetupCost);
    else
        return formatCurrency(0);
}

function getElementsById(strId) {

    var arrayAllFormElements = document.forms[0].elements;
    var arrayMatchingElements = new Array();
    var j = 0;
    for (var i = 0; i < arrayAllFormElements.length; i++) {
        if (arrayAllFormElements[i].id == strId) 
        {
            arrayMatchingElements[j] = arrayAllFormElements[i];
            j++;
        }
    }
    return arrayMatchingElements;
}
function getGroupElementNames(strGrp) {
    //find all elements that start with same name
    //convention is that group name is followed by a $ sign and imprint option code
    var arrayAllFormElements = document.forms[0].elements;
    var arrayMatchingElements = new Array();
    var j = 0;
    for (var i = 0; i < arrayAllFormElements.length; i++) {
        if (arrayAllFormElements[i].id.substring(0,arrayAllFormElements[i].id.indexOf("$")) == strGrp)
        {
            arrayMatchingElements[j] = arrayAllFormElements[i].id;
            j++;
        }
        else 
        {
            if (arrayAllFormElements[i].name.substring(0,arrayAllFormElements[i].name.indexOf("$")) == strGrp) 
            {
                arrayMatchingElements[j] = arrayAllFormElements[i].name;
                j++;
            }
        }
    }
    return arrayMatchingElements;
}

function checkMultiColor () {

    var targetControl, objSenderCheckBox, objSenderInputText, UnitAdditionalCost, SetupAdditionalCost;
    // update additional cost for 2-color screen print
    var array1 = getGroupElementNames("ScreenCost2Colors");
    for (var ii = 0; ii < array1.length; ii++) {
        targetControl = document.forms[0].elements[array1[ii]];
        objSenderCheckBox = document.forms[0].elements["ScreenAdd1ColorCheck"+array1[ii].substring(array1[ii].indexOf('$'),array1[ii].length)];
        SetupAdditionalCost = 1;
        UnitAdditionalCost = 1; 
        targetControl.value=calculateAdditionalCost2(objSenderCheckBox, SetupAdditionalCost, UnitAdditionalCost);
    }
    // end Screen Print 2 Colors
    // update additional cost for 3-color screen print
    var array2 = getGroupElementNames("ScreenCost3Colors");
    for (var iii = 0; iii < array1.length; iii++) {
        targetControl = document.forms[0].elements[array2[iii]];
        objSenderCheckBox = document.forms[0].elements["ScreenAdd2ColorsCheck"+array2[iii].substring(array2[iii].indexOf('$'),array2[iii].length)];
        SetupAdditionalCost = 2;
        UnitAdditionalCost = 1.75; 
        targetControl.value=calculateAdditionalCost2(objSenderCheckBox, SetupAdditionalCost, UnitAdditionalCost);
    }
    // end Screen Print 3 Colors
}


function transferview(image,width,height) {

var cond1,cond2

if (width==0) 
    cond1=" ";
else 
    cond1="width="+(width+20)+"";
if (height==0) 
    cond2=" ";
else 
    cond2="height="+(height+70)+"";

var s1 ="<TITLE>Image</TITLE>";
var s15="";
var s2 ="<CENTER><IMG SRC='"+image+"' BORDER=0>";
var s3 ="<FORM id='imageform'><INPUT TYPE='BUTTON' VALUE='Close Window'"+ " onClick='self.close()'>";
var s4 ="</FORM></CENTER>";
ImageWindow=window.open("","newwin"+width,"toolbar=no,scrollbars="+scroll+",menubar=no,"+cond1+","+cond2);
ImageWindow.document.write(s1+s15+s2+s3+s4);
ImageWindow.document.close();
ImageWindow.focus();
}

function calculateTax(strAmt, strShippingAmt, strTaxPercentage) {
    //tax must be calculated on subtotal plus shipping
   var strTaxAmt;
   var numShippingAmt = parseFloat(strShippingAmt.substring(1,strShippingAmt.length));
   strTaxAmt = formatCurrency((parseFloat(strAmt)+numShippingAmt)*parseFloat(strTaxPercentage)/100);
   return strTaxAmt;
}

function calculateShipping(strAmt, strMinCharge, strProvince) {

// apply amounts set for each province on every $400.
// If amount is less than MinCharge apply full MinCharge
// For Ontario, no shipping charge for bills over $200
 
    var strShippingAmt, numMinCharge, numShippingAmt, numAmt;
    numAmt = parseFloat(strAmt);
    numMinCharge = parseFloat(strMinCharge);
  
    if (strProvince == "Ontario")
    {
        if (numAmt > 200)
            strShippingAmt = formatCurrency(0);
        else
            strShippingAmt = formatCurrency(numMinCharge);
    }
    else
    {
        numShippingAmt = parseFloat(strAmt)/400*numMinCharge;
        if (numShippingAmt < numMinCharge)
            strShippingAmt = formatCurrency(numMinCharge);
        else 
            strShippingAmt = formatCurrency(numShippingAmt);
    }
    return strShippingAmt;
}

