﻿// JScript File


//function to add up all items and then update the subtotal & total
function ReTotal(arrProducts, SubTotalID, ShippingID, TotalID)
{
    var total = parseFloat(document.getElementById(SubTotalID).value);

    var OrderTotal = parseFloat(document.getElementById(ShippingID).value) + total;
    
    document.getElementById(TotalID).value =  + OrderTotal.toFixed(2);
    document.getElementById(GetDisplayFieldID(TotalID)).innerHTML = "$" + FormatNumber(OrderTotal.toFixed(2));
}

//function to insert shipping amount into cart field
function InsertShipping(ShippingID, ShippingAmtID)
{
    var ShipField = document.getElementById(ShippingID);
    ShipField.parentNode.parentNode.style.display = ''
    var ShipAmount = parseFloat(ParseShipping(ShippingAmtID));
    document.getElementById(ShippingID).value = ShipAmount.toFixed(2);
    //check for the display element
    var lblAmt = FormatNumber(ShipAmount.toFixed(2));
    var dispLabel = document.getElementById(GetDisplayFieldID(ShippingID));
    if(dispLabel){
        dispLabel.innerHTML = lblAmt;}
}

function GetDisplayFieldID(fieldID){
    var LastUnderscore = fieldID.lastIndexOf("_");
    return fieldID.substring(0, LastUnderscore+1) + 'disp' + fieldID.substring(LastUnderscore+1)
}

//function to format numbers with commas
function FormatNumber(val){
    var strVal = val + ""; //convert to string
    var startPos = strVal.lastIndexOf(".");
    var strFormatted = strVal.substring(startPos);
    var strToFormat = strVal.substring(0, startPos)
    while(strToFormat.length > 0){
        if(strFormatted.charAt(0) != "."){
            strFormatted = "," + strFormatted;}
        var start = strToFormat.length > 3 ? strToFormat.length - 3 : 0;
        strFormatted = strToFormat.substring(start, strToFormat.length) + strFormatted;
        strToFormat = strToFormat.substring(0, strToFormat.length - 3);
    }
    return strFormatted;
}


//Returns the shipping amount parsed out of the text. (necessary!)
function ParseShipping(ShippingAmtID){
    var ShipAmtField = document.getElementById(ShippingAmtID);
    var selectedItemText = ShipAmtField.options[ShipAmtField.selectedIndex].innerHTML
    //substring out the dollar amount
    var amount = selectedItemText.match(/\;.([0-9,]+\.\d{2})$/)
    if(amount.length > 1)
        return amount[amount.length-1]
    else
        return amount
}

function GetRegions(RegionFieldID){
    try{
        if (http_request.readyState == 4){
            if (http_request.status == 200){
                var RegionField = document.getElementById(RegionFieldID);
                ClearRegions(RegionField);
                if (window.XMLHttpRequest){ // Mozilla, Safari,...
                    var xmldoc = http_request.responseXML;
                    var regions = xmldoc.getElementsByTagName('CountryRegion');
                    //parse XML list of regions
                    for(i=0;i<regions.length;i++){
                        if(regions[i].childNodes.length > 1){
                            //loop through regions
                            var RegionID = regions[i].getElementsByTagName('Abbreviation')[0].firstChild.nodeValue;
                            var RegionName = regions[i].getElementsByTagName('Name')[0].firstChild.nodeValue;
                            AddRegionToField(RegionField,RegionID,RegionName);}
                    }
                    //If the country doesn't have regions, set N/A.
                    if(RegionField.childNodes.length < 1){
                        AddRegionToField(RegionField, '', 'N/A');}
                }else if (window.ActiveXObject){ // IE
                    result = http_request.responseText;
                    var xmldoc=new ActiveXObject("Microsoft.XMLDOM");
                    xmldoc.async="false";
                    xmldoc.loadXML(result);
                    var regions = xmldoc.getElementsByTagName('CountryRegion');
                    //Parse list of regions
                    for(i=0;i<regions.length;i++){
                        if(regions[i].childNodes.length > 1){
                            //loop through regions
                            var RegionID = regions[i].getElementsByTagName('Abbreviation')[0].firstChild.nodeValue;
                            var RegionName = regions[i].getElementsByTagName('Name')[0].firstChild.nodeValue;
                            AddRegionToField(RegionField,RegionID,RegionName);}
                    }
                    //If the country doesn't have regions, set N/A.
                    if(RegionField.childNodes.length < 1){
                        AddRegionToField(RegionField, '', 'N/A');}
                }
            }else{/*alert("Problem: HTTP status is " + http_request.status);*/}
        }
    }catch(e){/*alert('GetRegions: ' + e.message);*/}
}


function ClearRegions(RegionField){
    while(RegionField.childNodes.length > 0){
        RegionField.removeChild(RegionField.firstChild);}
}

function AddRegionToField(RegionField, RegionID, RegionName){
    var newOption = document.createElement("option");
    var newText = document.createTextNode(RegionName);
    newOption.setAttribute("value",RegionID);
    newOption.appendChild(newText);
    RegionField.appendChild(newOption);
}

function AddEstimate(EstimateField, Estimate, ShipVia){
    var MaxRegionLen = 40;
    var RegionName = '';
    var TextLength = Estimate.length + ShipVia.length
    var SpaceLength = MaxRegionLen - TextLength;
    if(Estimate.length + ShipVia.length > MaxRegionLen)
        RegionName = ShipVia.substring(0,MaxRegionLen - Estimate.length) + " " + Estimate
    else
        RegionName = ShipVia +  Array(SpaceLength + 1).join('\u00a0') + Estimate;
    var newOption = document.createElement("option");
    var newText = document.createTextNode(RegionName);
    newOption.setAttribute("value",Estimate);
    newOption.setAttribute("style", "font-family:Courier, monospace;")
    newOption.style.fontFamily = "Courier, monospace";
    newOption.appendChild(newText);
    EstimateField.appendChild(newOption);
}


function TestMessage(msg, amt){
    if(msg == 'No Shipping Lookup URL' || msg == 'No response received' || msg == 'Shipping is not calculated on Quotes.') return true;
    if(amt <= 0 && msg != 'Free Shipping') return true;
    if(msg.match(/.*error*/) || msg.match(/.*fail.*/)) return true;
    if(msg.match(/.*Datatype\serror.*/) || msg.match(/.*FailureHard.*/)) return true;
    if(msg.match(/.*maximum\sper\spackage\sweight\sfor\sthe\selected\sservice.*/)) return true;
    if(msg.match(/.*Invalid Customer Account Number.*/)) return true;
    return false
}

function setEstimates(EstimateFieldID, AdditionalShippingID){
    try{
        if (http_request.readyState == 4){
            if (http_request.status == 200){
                var EstimateField = document.getElementById(EstimateFieldID)
                var AdditionalShipping = parseFloat(document.getElementById(AdditionalShippingID).value)
                ClearRegions(EstimateField);
                EstimateField.style.fontFamily = "Courier, monospace";
                EstimateField.setAttribute("style", "font-family: Courier, monospace;")
                if (window.XMLHttpRequest){
                    var xmldoc = http_request.responseXML;
                    var estimates = xmldoc.getElementsByTagName('ShippingEstimate');
                    //parse XML list of estimates
                    for(i=0;i<estimates.length;i=i+2){
                        var ShipViaName = estimates[i].getElementsByTagName("ShipVia")[0].firstChild.nodeValue;
                        var ShipEstimate = parseFloat(estimates[i].getElementsByTagName("ShippingCharge")[0].firstChild.nodeValue);
                        var QuoteShipEst = parseFloat(estimates[i].getElementsByTagName("QuoteShippingCharge")[0].firstChild.nodeValue);
                        var SampleShipEst = parseFloat(estimates[i].getElementsByTagName("SampleShippingCharge")[0].firstChild.nodeValue);
                        ShipEstimate = ShipEstimate + QuoteShipEst + SampleShipEst + AdditionalShipping;
                        var shipMsg = estimates[i].getElementsByTagName("ShippingResponse")[0].firstChild.nodeValue;
                        if (TestMessage(shipMsg, (ShipEstimate + QuoteShipEst + SampleShipEst))){ShipEstimate = 'TBD';}
                        else{ShipEstimate = "$" + ShipEstimate.toFixed(2);}
                        AddEstimate(EstimateField,ShipEstimate,ShipViaName);
                    }
                }else if (window.ActiveXObject){
                    result = http_request.responseText;
                    var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
                    xmlDoc.async="false";
                    xmlDoc.loadXML(result);
                    var estimates = xmldoc.getElementsByTagName('ShippingEstimate');
                    //parse XML list of estimates
                    for(i=0;i<estimates.length;i=i+2){
                        var ShipViaName = estimates[i].getElementsByTagName("ShipVia")[0].firstChild.nodeValue;
                        var ShipEstimate = parseFloat(estimates[i].getElementsByTagName("ShippingCharge")[0].firstChild.nodeValue);
                        var QuoteShipEst = parseFloat(estimates[i].getElementsByTagName("QuoteShippingCharge")[0].firstChild.nodeValue);
                        var SampleShipEst = parseFloat(estimates[i].getElementsByTagName("SampleShippingCharge")[0].firstChild.nodeValue);
                        ShipEstimate = ShipEstimate + QuoteShipEst + SampleShipEst + AdditionalShipping;
                        var shipMsg = estimates[i].getElementsByTagName("ShippingResponse")[0].firstChild.nodeValue;
                        if (TestMessage(shipMsg, (ShipEstimate + QuoteShipEst + SampleShipEst))){ShipEstimate = 'TBD';}
                        else{ShipEstimate = "$" + ShipEstimate.toFixed(2);}
                        AddEstimate(EstimateField,ShipEstimate,ShipViaName);
                    }
                }
            }else{/*alert("Problem: HTTP status is " + http_request.status);*/}
        }
    }catch(e){/*alert('GetEstimates: ' + e.message);*/}
}