﻿/*  FileName:CommonFunction.js
Description:File for all the common javascript function for the application.
*/


//This function calculates the dimensional weight of Each row
function CalculateDimweightForRateware(DimFactor, RowNo, IsClass) {

    var qtyId = "txtPkgNum" + RowNo;
    var lengthId = "txtLength" + RowNo;
    var widthId = "txtWidth" + RowNo;
    var heightId = "txtHeight" + RowNo;
    var weightId = "txtWeight" + RowNo;
    var dimWgtId = "txtDimWeight" + RowNo;
    var classId = "cmbClass" + RowNo;

    var density;
    density = CalculateDensity(weightId, lengthId, heightId, widthId, qtyId, DimFactor);

    //get the density value and set the class
    if (density != "" && IsClass == "True") {
        CalculateClass(density, classId);
    }

    //set the total weight value
    var totalWeight;
    totalWeight = CalculateTotalWeight(weightId, qtyId);

    if (totalWeight != "") {
        document.getElementById(dimWgtId).value = totalWeight;
    }
    return false;
}

//calculate the total weight
function CalculateTotalWeight(weightId, qtyId) {
    var totalWeight;
    var quantity = document.getElementById(qtyId).value.replace(/^\s*|\s*$/g, "");
    var weight = document.getElementById(weightId).value.replace(/^\s*|\s*$/g, "");

    if ((quantity != "") && (weight != "")) {
        totalWeight = quantity * weight;
    }
    return totalWeight;
}

//this function calculates the Cube for 1 quantity, using DimFactor. Scott 2011-04-25
function CalculateCube(LengthID, WidthID, HeightID, DimFactor) {

    var cube;
    var length = document.getElementById(LengthID).value.replace(/^\s*|\s*$/g, "");
    var width = document.getElementById(WidthID).value.replace(/^\s*|\s*$/g, "");
    var height = document.getElementById(HeightID).value.replace(/^\s*|\s*$/g, "");

    if (validateFloatForDetails(document.getElementById(LengthID), "Length", true) != "") {
        alert(validateFloatForDetails(document.getElementById(LengthID), "Length", true));
        document.getElementById(LengthID).focus();
        return false;
    }
    if (validateFloatForDetails(document.getElementById(WidthID), "Width", true) != "") {
        alert(validateFloatForDetails(document.getElementById(WidthID), "Width", true));
        document.getElementById(WidthID).focus();
        return false;
    }
    if (validateFloatForDetails(document.getElementById(HeightID), "Height", true) != "") {
        alert(validateFloatForDetails(document.getElementById(HeightID), "Height", true));
        document.getElementById(HeightID).focus();
        return false;
    }

    if ((length != "") && (width != "") && (height != "") && (DimFactor != "")) {
        cube = length * width * height / DimFactor;
        //Alert("Cube1: " + cube);
        cube = Math.ceil((cube * 10) / 10); //rounds up
        cube = parseInt(cube);
        //Alert("Cube2: " + cube);
        return cube;
    }
    return false;
}

//this function calculates the density
function CalculateDensity(WeightID, LengthID, WidthID, HeightID, QtyID, DimFactor) {

    var density;
    var weight = document.getElementById(WeightID).value.replace(/^\s*|\s*$/g, "");
    var length = document.getElementById(LengthID).value.replace(/^\s*|\s*$/g, "");
    var height = document.getElementById(HeightID).value.replace(/^\s*|\s*$/g, "");
    var quantity = document.getElementById(QtyID).value.replace(/^\s*|\s*$/g, "");
    var width = document.getElementById(WidthID).value.replace(/^\s*|\s*$/g, "");

    if (validateNumberForDetails(document.getElementById(QtyID), "Pieces", true) != "") {
        alert(validateNumberForDetails(document.getElementById(QtyID), "Pieces", true));
        document.getElementById(QtyID).focus();
        return false;
    }
    if (validateFloatForDetails(document.getElementById(LengthID), "Length", true) != "") {
        alert(validateFloatForDetails(document.getElementById(LengthID), "Length", true));
        document.getElementById(LengthID).focus();
        return false;
    }
    if (validateFloatForDetails(document.getElementById(WidthID), "Width", true) != "") {
        alert(validateFloatForDetails(document.getElementById(WidthID), "Width", true));
        document.getElementById(WidthID).focus();
        return false;
    }
    if (validateFloatForDetails(document.getElementById(HeightID), "Height", true) != "") {
        alert(validateFloatForDetails(document.getElementById(HeightID), "Height", true));
        document.getElementById(HeightID).focus();
        return false;
    }

    if (validateFloatForDetails(document.getElementById(WeightID), "Weight", true) != "") {
        alert(validateFloatForDetails(document.getElementById(WeightID), "Weight", true));
        document.getElementById(WeightID).focus();
        return false;
    }


    if ((quantity != "") && (length != "") && (width != "") && (height != "")) {
        var cube = length * width * height / DimFactor;
        density = weight / cube;
        return density;
    }
    return false;
}



function CalculateClass(density, idClass) {
    var ClassCombo = document.getElementById(idClass);
    var ClassTbl = { 50: 50, 35: 55, 30: 60, 22.5: 65, 15: 70, 13.5: 77.5, 12: 85, 10.5: 92.5, 9: 100, 8: 110, 7: 125, 6: 150, 5: 175, 4: 200, 3: 250, 2: 300, 1: 400, 0: 500 };
    var NMFCClass = "";

    var Sortedkeys = [50, 35, 30, 22.5, 15, 13.5, 12, 10.5, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0];

    for (var i = 0; i < Sortedkeys.length; i++) {
        if (density >= Sortedkeys[i]) {
            NMFCClass = ClassTbl[Sortedkeys[i]];
            break;
        }
    }

    for (var i = 1; i < ClassCombo.length; i++) {
        if (NMFCClass == ClassCombo.options[i].text) {
            ClassCombo.selectedIndex = i;
            break;
        }
    }
    return false;
}
//this function opens a pop up
function OpenPopUp(URL, name, settings) {
    if (settings == "") {
        settings = "width=800,height=600,status=no,scrollbars=yes,resizable=yes,location=no,menubar=no";
    }

    var myWin = window.open(URL, name, settings);
    myWin.focus();
    return false;
}
function FormatDateMMDDYYYY(objDate) {
    var day;
    var month;
    var year;
    var date = "";
    day = objDate.getDate();
    month = objDate.getMonth() + 1;
    year = objDate.getFullYear();

    if (month < 10) {
        month = "0" + month;
    }
    if (day < 10) {
        day = "0" + day;
    }

    date = month + "/" + day + "/" + year;
    return date;
}

//Formats the Date.
function FormatDateYYYYMMDD(objDate) {
    var Date = "";
    var day;
    var month;
    var year;
    var NewDate;

    NewDate = objDate.split("/");
    Date = NewDate[2] + NewDate[0] + NewDate[1];
    return Date;
}

function resetForm(formObj) {

    var FormName;
    if (document.title != "") {
        FormName = document.title;
    }
    else {
        FormName = "the";
    }
    var ConfirmMsg = "You are about to reset " + FormName + " form. Continue?";
    var ResetForm = confirm(ConfirmMsg);

    if (ResetForm == true) {
        var eleObj = formObj.elements;

        formObj.reset();

        for (i = 0; i < eleObj.length; i++) {

            var fieldType = eleObj[i].type.toLowerCase();

            switch (fieldType) {
                case "text":
                    eleObj[i].value = "";
                    break;
                case "radio":
                case "checkbox":
                    if (eleObj[i].parentElement.className == "checked") {
                        eleObj[i].parentElement.setAttribute("class", "");
                    }
                    break;
                case "select-one":
                case "select-multi":
                    eleObj[i].selectedIndex = 0;
                    break;
                default:
                    break;
            }
        }
        return false;
    }
    else {
        return false;
    }
}

//calculates the accessorial charges
function CalculateAccessorialCharge(ChargeType, DefaultRate, DimWeight) {
    var Charge;
    var Pieces;
    switch (ChargeType) {
        case "Per CWT":
            Charge = (parseFloat(DimWeight) / 100) * parseFloat(DefaultRate);
            break
        case "Per Unit":
            Charge = DefaultRate;
            break
        case "Per Cube":
            Charge = (parseFloat(DimWeight) / 100) * (parseFloat(DefaultRate));
            break
        case "Per Flat":
            Charge = parseFloat(DimWeight) * (parseFloat(DefaultRate));
            break
    }
    return Charge;
}

//replace the $ sign from the object
function removeDollar(Obj) {
    if (Obj.indexOf("$") > -1) {
        var ObjSpilt;
        ObjSpilt = Obj.split("$");
        Obj = ObjSpilt[1];
    }
    return Obj;
}

//trim the string
function trim(Obj) {
    return Obj.replace(/^\s*|\s*$/g, "");
}

//apend the dollar
function appendDollar(Obj) {
    return "$" + Obj;
}

// auto complete functionality for shipper and consignee

function AutoCompleteFields(Type, ID, Name, Address, City, State, Zip, Country, Contact, Phone, Fax, Email) {

    var CustNum = ID.val();

    autocomplete(Type, ID, Name, Address, City, State, Zip, Country, Contact, Phone, Fax, Email);

    ID.change(function() {
        CustNum = ID.val();
        autocomplete(Type, ID, Name, Address, City, State, Zip, Country, Contact, Phone, Fax, Email);
    });
}

//Autocomplete functionality for the description details grid   
function AutoCompleteDescription(id, RowCount) {

    var CustNum = $("#cmbInvoicee").val();
    var gridID;

    for (var cnt = 2; cnt <= RowCount; cnt++) {
        gridID = id + cnt + "_txtDescription";
        Autocompletedescriptionrows(gridID, CustNum);
    }

    $("#cmbInvoicee").change(function() {
        CustNum = $("#cmbInvoicee").val();
        for (var cnt = 2; cnt <= RowCount; cnt++) {
            gridID = id + cnt + "_txtDescription";
            Autocompletedescriptionrows(gridID, CustNum);
        }


    });
}

function Autocompletedescriptionrows(gridID, CustNum) {
    $("#" + gridID).unautocomplete();
    // Jquery autocomplete for Description  

    $("#" + gridID).autocomplete("GetAutoCompleteData.aspx?Type=Des&CusNum=" + CustNum, {
        delay: 10,
        matchSubset: 1,
        matchContains: 1,
        minChars: 0,
        parse: parseDesXML,
        formatItem: formatDesItem,
        formatResult: formatDesResult
    }).result(function(event, item) {
    });
}

function parseDesXML(xml) {

    var results = [];
    $.xmlDOM(xml).find('item').each(function() {
        var Description = $.trim($(this).find('Description').text());
        var ClassKey = $.trim($(this).find('ClassKey').text());

        results[results.length] = { 'data': { Description: Description, ClassKey: ClassKey },
            'result': Description, 'ClassKey': ClassKey
        };
    });
    return results;
};

function formatDesItem(data) {
    return data.Description;
};

function formatDesResult(data) {
    return data.Description;

};

// this function will parse xml and return as a array of string
function parseShipperXML(xml) {
    var results = [];
    $.xmlDOM(xml).find('item').each(function() {
        var ShipperName = $.trim($(this).find('ShipperName').text());
        var ShipperAddress = $.trim($(this).find('ShipperAddress').text());
        var ShipperCity = $.trim($(this).find('ShipperCity').text());
        var ShipperState = $.trim($(this).find('ShipperState').text());
        var ShipperZip = $.trim($(this).find('ShipperZip').text());
        var ShipperCountry = $.trim($(this).find('ShipperCountry').text());
        var ShipperContact = $.trim($(this).find('ShipperContact').text());
        var ShipperFax = $.trim($(this).find('ShipperFax').text());
        var ShipperPhone = $.trim($(this).find('ShipperPhone').text());
        var ShipperContactEMail = $.trim($(this).find('ShipperContactEMail').text());

        results[results.length] = { 'data': { ShipperName: ShipperName, ShipperAddress: ShipperAddress, ShipperCity: ShipperCity, ShipperState: ShipperState, ShipperZip: ShipperZip, ShipperCountry: ShipperCountry, ShipperContact: ShipperContact, ShipperFax: ShipperFax, ShipperPhone: ShipperPhone, ShipperContactEMail: ShipperContactEMail },
            'result': ShipperName, 'ShipperAddress': ShipperAddress, 'ShipperCity': ShipperCity, 'ShipperState': ShipperState, 'ShipperZip': ShipperZip, 'ShipperCountry': ShipperCountry, 'ShipperContact': ShipperContact, 'ShipperFax': ShipperFax, 'ShipperPhone': ShipperPhone, 'ShipperContactEMail': ShipperContactEMail

        };
    });
    return results;
};

function formatShipperItem(data) {
    return data.ShipperName + "," + data.ShipperAddress + "," + data.ShipperZip + "," + data.ShipperCity + "," + data.ShipperState + "," + data.ShipperCountry + "," + data.ShipperContact + "," + data.ShipperPhone + "," + data.ShipperContactEMail + "," + data.ShipperFax;
};

function formatShipperResult(data) {
    return data.ShipperName + "," + data.ShipperAddress + "," + data.ShipperZip + "," + data.ShipperCity + "," + data.ShipperState + "," + data.ShipperCountry + "," + data.ShipperContact + "," + data.ShipperPhone + "," + data.ShipperContactEMail + "," + data.ShipperFax;

};


// this function will parse xml and return as a array of string
function parseConsigneeXML(xml) {
    var results = [];
    $.xmlDOM(xml).find('item').each(function() {
        var ConsigneeName = $.trim($(this).find('ConsigneeName').text());
        var ConsigneeAddress = $.trim($(this).find('ConsigneeAddress').text());
        var ConsigneeCity = $.trim($(this).find('ConsigneeCity').text());
        var ConsigneeState = $.trim($(this).find('ConsigneeState').text());
        var ConsigneeZip = $.trim($(this).find('ConsigneeZip').text());
        var ConsigneeCountry = $.trim($(this).find('ConsigneeCountry').text());
        var ConsigneeContact = $.trim($(this).find('ConsigneeContact').text());
        var ConsigneeFax = $.trim($(this).find('ConsigneeFax').text());
        var ConsigneePhone = $.trim($(this).find('ConsigneePhone').text());
        var ConsigneeContactEmail = $.trim($(this).find('ConsigneeContactEmail').text());

        results[results.length] = { 'data': { ConsigneeName: ConsigneeName, ConsigneeAddress: ConsigneeAddress, ConsigneeCity: ConsigneeCity, ConsigneeState: ConsigneeState, ConsigneeZip: ConsigneeZip, ConsigneeCountry: ConsigneeCountry, ConsigneeContact: ConsigneeContact, ConsigneeFax: ConsigneeFax, ConsigneePhone: ConsigneePhone, ConsigneeContactEmail: ConsigneeContactEmail },
            'result': ConsigneeName, 'ConsigneeAddress': ConsigneeAddress, 'ConsigneeCity': ConsigneeCity, 'ConsigneeState': ConsigneeState, 'ConsigneeZip': ConsigneeZip, 'ConsigneeCountry': ConsigneeCountry, 'ConsigneeContact': ConsigneeContact, 'ConsigneeFax': ConsigneeFax, 'ConsigneePhone': ConsigneePhone, 'ConsigneeContactEmail': ConsigneeContactEmail

        };
    });
    return results;
};

function formatConsigneeItem(data) {
    return data.ConsigneeName + "," + data.ConsigneeAddress + "," + data.ConsigneeZip + "," + data.ConsigneeCity + "," + data.ConsigneeState + "," + data.ConsigneeCountry + "," + data.ConsigneeContact + "," + data.ConsigneePhone + "," + data.ConsigneeContactEmail + "," + data.ConsigneeFax;
};

function formatConsigneeResult(data) {
    return data.ConsigneeName + "," + data.ConsigneeAddress + "," + data.ConsigneeZip + "," + data.ConsigneeCity + "," + data.ConsigneeState + "," + data.ConsigneeCountry + "," + data.ConsigneeContact + "," + data.ConsigneePhone + "," + data.ConsigneeContactEmail + "," + data.ConsigneeFax;

};

function autocomplete(Type, ID, Name, Address, City, State, Zip, Country, Contact, Phone, Fax, Email) {
    Name.unautocomplete();

    if (Type == "Shipper") {

        // Jquery autocomplete for shipper
        Name.autocomplete("../GetAutoCompleteData.aspx?Type=Shipper&CusNum=" + ID.val(), {
            delay: 10,
            matchSubset: false,
            matchContains: true,
            minChars: 0,
            parse: parseShipperXML,
            formatItem: formatShipperItem,
            formatResult: formatShipperResult
        }).result(function(event, item) {
            Address.val(item.ShipperAddress);
            City.val(item.ShipperCity);
            State.val(item.ShipperState);
            Zip.val(item.ShipperZip);
            Country.val(item.ShipperCountry);
            Contact.val(item.ShipperContact);
            Fax.val(item.ShipperFax);
            Phone.val(item.ShipperPhone);
            Email.val(item.ShipperContactEMail);
        });
    }
    else {

        // Jquery autocomplete for Consignee

        Name.autocomplete("../GetAutoCompleteData.aspx?Type=Consignee&CusNum=" + ID.val(), {
            delay: 10,
            matchSubset: false,
            matchContains: true,
            minChars: 0,
            parse: parseConsigneeXML,
            formatItem: formatConsigneeItem,
            formatResult: formatConsigneeResult
        }).result(function(event, item) {
            Address.val(item.ConsigneeAddress);
            City.val(item.ConsigneeCity);
            State.val(item.ConsigneeState);
            Zip.val(item.ConsigneeZip);
            Country.val(item.ConsigneeCountry);
            Contact.val(item.ConsigneeContact);
            Fax.val(item.ConsigneeFax);
            Phone.val(item.ConsigneePhone);
            Email.val(item.ConsigneeContactEMail);
        });
    }
}

//Gets the Billing Information
function GetBillingInformation(ID, DataDisplayID, TogglerID, EffectID) {

    var CustNum = ID.val();
    if (CustNum != "0") {
        TogglerID.show();
    }
    GetBillingData(CustNum, DataDisplayID, TogglerID, EffectID);

    ID.change(function() {
        CustNum = ID.val();
        if (CustNum != "0") {
            TogglerID.show();
        }
        GetBillingData(CustNum, DataDisplayID, TogglerID, EffectID);

    });

}

function GetBillingData(CustNum, DataDisplayID, TogglerID, EffectID) {
    EffectID.effect('highlight', {}, 500, callback);
    function callback() {
        setTimeout(function() {
            EffectID.removeAttr("style").hide().fadeIn();
        }, 1000);
    };
    var BillingData;
    $.get("../GetAutoCompleteData.aspx?Type=BL&CusNum=" + CustNum,
        function(xml) {
            var Header = $.trim($.xmlDOM(xml).find('Header').text());
            var CompanyName = $.trim($.xmlDOM(xml).find('CompanyName').text());
            var Country = $.trim($.xmlDOM(xml).find('Country').text());
            var CityStateZip = $.trim($.xmlDOM(xml).find('CityStateZip').text());
            var Street1 = $.trim($.xmlDOM(xml).find('Street1').text());
            var Street2 = $.trim($.xmlDOM(xml).find('Street2').text());
            BillingData = "<Table class='bodytext' cellspacing='0' align='center' cellpadding='0' width='95%'>" + "<tr><td align='center'>" + CompanyName + "</td></tr>" + "<tr><td align='center'>" + Street1 + "</td></tr>" + "<tr><td align='center'>" + Street2 + "</td></tr>" + "<tr><td align='center'>" + CityStateZip + "</td></tr>" + "<tr><td align='center'>" + Country + "</td></tr></Table>";
            DataDisplayID.show();
            DataDisplayID.corner("round 15px top");
            DataDisplayID.html(BillingData);

        });

}

//This function returns the Date in the format
function GetLocalDate(Date) {

    var month = Date.getMonth() + 1
    var year = Date.getYear()
    var day = Date.getDate()

    if (day < 10) day = "0" + day
    if (month < 10) month = "0" + month
    if (year < 1000) year += 1900

    var localDate = month + "/" + day + "/" + year;

    return localDate;

}
//populates thedate in the field
function PopulateDate(id, DateType) {
    var localDate;
    if (DateType == "Today") {
        localDate = GetLocalDate(new Date());
    }
    else if (DateType == "YesterDay") {
        localDate = GetLocalDate(new Date(new Date().getTime() - 86400000));
    }

    else if (DateType == "LastWeek") {
        localDate = GetLocalDate(new Date(new Date().getTime() - (7 * 86400000)));
    }

    else if (DateType == "LastMonth") {
        var currentDate = new Date()
        var month = currentDate.getMonth() + 1
        var year = currentDate.getYear()
        var days = daysInMonth(month, year)
        localDate = GetLocalDate(new Date(currentDate.getTime() - (days * 86400000)));
    }
    id.val(localDate);
}

//Calculates the days in the current month
function daysInMonth(month, year) {
    var m = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    if (month != 2) return m[month - 1];
    if (year % 4 != 0) return m[1];
    if (year % 100 == 0 && year % 400 != 0) return m[1];
    return m[1] + 1;
}

//Added the input amounts in the grid
function CalculateAmount(GridID, TotalAmountID) {
    var TotalAmount = 0;

    GridID.each(function() {
        if ((this.id).search("AmountTxt") != "-1") {
            var NumMsg = validateCurrencyDetails(this, "Amount", false);
            if (NumMsg != "") {
                alert(NumMsg);
            }
            else {
                TotalAmount = parseFloat(TotalAmount) + parseFloat(this.value.replace("", 0));

            }
        }
    });

    TotalAmountID.val(TotalAmount);
    return false;
}

var DetailItem = 0;
var lineItemCnt = 0;
var ErrorMsg = "";

//validates the truckers details item
function ValidateDetailItem(Totalrow, errCount) {
    ErrorMsg = "";
    for (var i = 2; i <= Totalrow; i++) {
        lineItemCnt = 0;
        ValidateDetailsItem(i, errCount, i - 1);
    }

    if (DetailItem == 0) {
        errCount += 1;
        ErrorMsg += "\n" + errCount + ". A details Item is required.";
    }

    return ErrorMsg;
}

function ValidateDetailsItem(row, errCount, RowNumber) {

    var strPackageNum = document.getElementById('ctl00_MasterCph_InvoiceDetailsGv_ctl0' + row + '_QtyTxt')
    var strPackageType = document.getElementById('ctl00_MasterCph_InvoiceDetailsGv_ctl0' + row + '_PackageTypeCmb').value;
    var strDescription = document.getElementById('ctl00_MasterCph_InvoiceDetailsGv_ctl0' + row + '_DescriptionTxt').value.replace(/^\s*|\s*$/g, "");
    var strDimWeight = document.getElementById('ctl00_MasterCph_InvoiceDetailsGv_ctl0' + row + '_EstimatedWgtTxt')
    var strCubicfeet = document.getElementById('ctl00_MasterCph_InvoiceDetailsGv_ctl0' + row + '_CubicFeetTxt')
    var strCubicWeight = document.getElementById('ctl00_MasterCph_InvoiceDetailsGv_ctl0' + row + '_CubicWeightTxt')
    var strLength = document.getElementById('ctl00_MasterCph_InvoiceDetailsGv_ctl0' + row + '_LengthTxt')
    var strWidth = document.getElementById('ctl00_MasterCph_InvoiceDetailsGv_ctl0' + row + '_WidthTxt')
    var strHeight = document.getElementById('ctl00_MasterCph_InvoiceDetailsGv_ctl0' + row + '_HeightTxt')

    //check for a compulsory line item
    if ((strPackageNum.value.replace(/^\s*|\s*$/g, "") == "") && (strPackageType == "0") && (strDescription == "") && (strDimWeight.value.replace(/^\s*|\s*$/g, "") == "") && (strCubicfeet.value.replace(/^\s*|\s*$/g, "") == "") && (strCubicWeight.value.replace(/^\s*|\s*$/g, "") == "")) {

        lineItemCnt = 1;

    }
    if (lineItemCnt == 0) {

        DetailItem = 1;

        var NumMsg = validateNumberForDetails(strPackageNum, "Qty", true);
        if (NumMsg != "") {
            errCount += 1;
            ErrorMsg = ErrorMsg + "\n" + errCount + "." + NumMsg;
        }

        //validate pkg type
        if (strPackageType == "0") {
            errCount += 1;
            ErrorMsg += "\n" + errCount + ".Please select a Package type in the details row line " + RowNumber;
        }

        var ContainerSizeReq = document.getElementById("ctl00_MasterCph_ContainerSizeDD");
        var selectedText = ContainerSizeReq.options[ContainerSizeReq.selectedIndex].text;

        if ((selectedText == "Full Container: 20'") || (selectedText == "Full Container: 40'") || (selectedText == "Full Container: 40' high cube") || (selectedText == "Full Container: 45' high cube")) {
            var LenMsg = validateFloatForDetails(strLength, "Length", false);
            if (LenMsg != "") {
                errcnt += 1;
                MsgStr = MsgStr + "\n" + errcnt + "." + LenMsg;
            }

            var WidthMsg = validateFloatForDetails(strWidth, "Width", false);
            if (WidthMsg != "") {
                errcnt += 1;
                MsgStr = MsgStr + "\n" + errcnt + "." + WidthMsg;
            }

            var HeightMsg = validateFloatForDetails(strHeight, "Height", false);
            if (HeightMsg != "") {
                errcnt += 1;
                MsgStr = MsgStr + "\n" + errcnt + "." + HeightMsg;
            }
            var WtMsg = validateNumberForDetails(strDimWeight, "Weight", false);
            if (WtMsg != "") {
                errCount += 1;
                ErrorMsg = ErrorMsg + "\n" + errCount + "." + WtMsg;
            }

            var CubicFeetMsg = validateFloatForDetails(strCubicfeet, "Cubic Feet", false);
            if (CubicFeetMsg != "") {
                errCount += 1;
                ErrorMsg = ErrorMsg + "\n" + errCount + "." + CubicFeetMsg;
            }

            var CubicWtMsg = validateNumberForDetails(strCubicWeight, "Cubic Weight", false);
            if (CubicWtMsg != "") {
                errCount += 1;
                ErrorMsg = ErrorMsg + "\n" + errCount + "." + CubicWtMsg;
            }
        }
        else {
            var LenMsg = validateFloatForDetails(strLength, "Length", true);
            if (LenMsg != "") {
                errcnt += 1;
                MsgStr = MsgStr + "\n" + errcnt + "." + LenMsg;
            }

            var WidthMsg = validateFloatForDetails(strWidth, "Width", true);
            if (WidthMsg != "") {
                errcnt += 1;
                MsgStr = MsgStr + "\n" + errcnt + "." + WidthMsg;
            }

            var HeightMsg = validateFloatForDetails(strHeight, "Height", true);
            if (HeightMsg != "") {
                errcnt += 1;
                MsgStr = MsgStr + "\n" + errcnt + "." + HeightMsg;
            }
            var WtMsg = validateNumberForDetails(strDimWeight, "Weight", true);
            if (WtMsg != "") {
                errCount += 1;
                ErrorMsg = ErrorMsg + "\n" + errCount + "." + WtMsg;
            }

            var CubicFeetMsg = validateFloatForDetails(strCubicfeet, "Cubic Feet", true);
            if (CubicFeetMsg != "") {
                errCount += 1;
                ErrorMsg = ErrorMsg + "\n" + errCount + "." + CubicFeetMsg;
            }

            var CubicWtMsg = validateNumberForDetails(strCubicWeight, "Cubic Weight", true);
            if (CubicWtMsg != "") {
                errCount += 1;
                ErrorMsg = ErrorMsg + "\n" + errCount + "." + CubicWtMsg;
            }
        }

        //validate description
        if (strDescription == "") {
            errCount += 1;
            ErrorMsg += "\n" + errCount + ". Please enter Description in the details row line " + RowNumber;
        }

        return ErrorMsg;
    }
}

/*Enable the pallet count text box if the user wantts*/
function EnablePalletTextBox() {
    document.getElementById('txtPalletCount').disabled = false;
    return false;
}

/*Reset the values if other is present */
function ResetAmount(AmountTxt) {
    var AmountTxtValue = document.getElementById(AmountTxt.id).value.replace(/^\s*|\s*$/g, "");
    if (AmountTxtValue != "$00.00") {
        document.getElementById(AmountTxt.id).value = "$00.00";
    }
    return true;
}

/*Check if the pallet rate is enabled or not for this customer*/
function IsPalletRateEnabled() {
    var invoicee = document.getElementById("ctl00_TraceProMasterCph_InvoiceeDD");
    var Url = "";

    Url = "../GetJsonData.aspx?type=Pallet&InvoiceeKey=" + invoicee.value;
    $.ajax({
        type: 'POST',
        url: Url,
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function(Obj) {
            if ((Obj.length > 0) && (Obj[0].IsPallet == 'True')) {
                PromptPalletCheck();
                return true;
            }
            else {
                return false;
            }
        }
    });
}

var PalletText = 'Pallet Rate available';
var PalletCountText = 'Enter pallet count : <input type="text" id="txtPalletCount" name="txtPalletCount" value="">'

function PalletConfirm(YesNo, Obj1, Obj2) {
    if (YesNo != undefined) {
        if (YesNo) {
            $.prompt(PalletCountText, { submit: PalletCountcheck, buttons: [{ title: 'OK', value: true}] })
        }
    }
}

function PalletCountcheck(YesNo, Obj1, Obj2) {
    var txtPalletObj = Obj1.children('#txtPalletCount');

    if (Obj2.txtPalletCount == "") {
        txtPalletObj.css("border", "solid #ff0000 1px");
        alert("Please enter a valid pallet count.");
        return false;
    }
    else {
        PalletCount = Obj2.txtPalletCount;
        document.getElementById("hdnPalletCount").value = PalletCount;
        return true;
    }
}

function PromptPalletCheck() {
    $.prompt(PalletText, { submit: PalletConfirm, buttons: [{ title: 'YES', value: true }, { title: 'NO', value: false}] })
}

/*This function checks the ispallet bool value and opens up the message box*/
function CheckIsPalletAndOpenConfirmBox() {
    IsPalletRateEnabled();
}


/// For Dhx Pages Clocks
function _escape(str) {
    str = str.replace(/ /g, "+");
    str = str.replace(/%/g, '%25');
    str = str.replace(/\?/, '%3F');
    str = str.replace(/&amp;/, '%26');
    return str;
}

function showClock(obj) {
    var str = 'bed src="http://www.worldtimeserver.com/clocks/' + obj.wtsclock + "?";
    var prop;
    for (prop in obj) {
        if ('wtsclock' == prop || 'width' == prop || 'height' == prop || 'wmode' == prop || 'type' == prop) {
            continue;
        }
        str += (prop + "=" + _escape(obj[prop]) + "&");
    }
    str += '" ';
    str += ' width="' + obj.width + '"';
    str += ' height="' + obj.height + '"';
    var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
    if (isOpera != true) {
        str += ' wmode="' + obj.wmode + '"';
    }
    str += ' type="application/x-shockwave-flash" allowscriptaccess="always" />';
    document.write("<em" + str);
}
//set the nmfc class and weight values 
//Scott 2011-04-25function SetNmfcValues(nmfcClass, Weight, Pcs, TableRowNo) {
function SetNmfcValues(nmfcClass, Weight, Cube, Pcs, TableRowNo) {

    var classId = "ctl00_MasterCph_InvoiceDetailsGv_ctl0" + TableRowNo + "_ClassCmb";

    document.getElementById("ctl00_MasterCph_InvoiceDetailsGv_ctl0" + TableRowNo + "_QtyTxt").value = Pcs;
    document.getElementById("ctl00_MasterCph_InvoiceDetailsGv_ctl0" + TableRowNo + "_EstimatedWgtTxt").value = Weight;
    document.getElementById("ctl00_MasterCph_InvoiceDetailsGv_ctl0" + TableRowNo + "_CubicFeetTxt").value = Cube;

    //calculate the class
    CalculateClass(nmfcClass, classId);
    return false;
}    

var QuickQuoteDetailItem = 0;
var QuickQuotelineItemCnt = 0;
var ErrorMsg = "";

//validates the truckers details item
function ValidateQuickQuoteDetailItem(Totalrow, errCount) {
    ErrorMsg = "";
    for (var i = 2; i <= Totalrow; i++) {
        QuickQuotelineItemCnt = 0;
        ValidateQuickQuoteDetailsItem(i, errCount, i - 1);
    }

    if (QuickQuoteDetailItem == 0) {
        errCount += 1;
        ErrorMsg += "\n" + errCount + ". A details Item is required.";
    }

    return ErrorMsg;
}

function ValidateQuickQuoteDetailsItem(row, errCount, RowNumber) {

    var strPackageNum = document.getElementById('ctl00_MasterCph_InvoiceDetailsGv_ctl0' + row + '_QtyTxt');
    var strDescription = document.getElementById('ctl00_MasterCph_InvoiceDetailsGv_ctl0' + row + '_DescriptionTxt').value.replace(/^\s*|\s*$/g, "");
    var strDimWeight = document.getElementById('ctl00_MasterCph_InvoiceDetailsGv_ctl0' + row + '_EstimatedWgtTxt');
    var strPackageType = document.getElementById('ctl00_MasterCph_InvoiceDetailsGv_ctl0' + row + '_ClassCmb').value;

    //check for a compulsory line item
    if ((strPackageNum.value.replace(/^\s*|\s*$/g, "") == "") && (strDescription == "") && (strDimWeight.value.replace(/^\s*|\s*$/g, "") == "")) {

        QuickQuotelineItemCnt = 1;

    }
    if (QuickQuotelineItemCnt == 0) {

        QuickQuoteDetailItem = 1;

        var NumMsg = validateNumberForDetails(strPackageNum, "Qty", true);
        if (NumMsg != "") {
            errCount += 1;
            ErrorMsg = ErrorMsg + "\n" + errCount + "." + NumMsg;
        }

        var CubicWtMsg = validateNumberForDetails(strDimWeight, "Weight", true);
        if (CubicWtMsg != "") {
            errCount += 1;
            ErrorMsg = ErrorMsg + "\n" + errCount + "." + CubicWtMsg;
        }

        if (strDescription == "") {
            errCount += 1;
            ErrorMsg = ErrorMsg + "\n" + errCount + "." + " Description is required";
        }
        
        /*
        if (document.getElementById('ct100_MasterCph_InvoiceDetailsGv_ctl0' + row + '_ClassCmb').value == "Select One")) {
        errCount += 1;
        ErrorMsg += "\n" + errCount + ".Please select a Class in the details row line " + RowNumber;
        }
        */        

        return ErrorMsg;
    }
}
//Populate the Shipper and consignee data.
var DataDisplayID;
function GetData(Type, Name, Address, City, State, Zip, Country, Contact, Phone, Fax, Email) {
    if (Type == "Shipper") {

        DataDisplayID = "ctl00_MasterCph_";
        
        window.parent.document.getElementById(DataDisplayID + "PickupNameTxt").value = Name;
        window.parent.document.getElementById(DataDisplayID + "PickupAddressTxt").value = Address;
        window.parent.document.getElementById(DataDisplayID + "PickupZipTxt").value = Zip;
        window.parent.document.getElementById(DataDisplayID + "PickupCityTxt").value = City;
        window.parent.document.getElementById(DataDisplayID + "PickupStateTxt").value = State;
        window.parent.document.getElementById(DataDisplayID + "PickupCountryTxt").value = Country;
        window.parent.document.getElementById(DataDisplayID + "PickupFaxTxt").value = Fax;
        window.parent.document.getElementById(DataDisplayID + "PickupEmailTxt").value = Email;
        window.parent.document.getElementById(DataDisplayID + "PickupPhoneTxt").value = Phone;
        window.parent.document.getElementById(DataDisplayID + "PickupContactTxt").value = Contact;

    }
    else {
        if (Type == "DhxPickUpShipper") {
            DataDisplayID = "ctl00_MasterCph_";

            window.parent.document.getElementById(DataDisplayID + "CompanyTxt").value = Name;
            window.parent.document.getElementById(DataDisplayID + "AddressTxt").value = Address;
            window.parent.document.getElementById(DataDisplayID + "ZipCodeTxt").value = Zip;
            window.parent.document.getElementById(DataDisplayID + "CityTxt").value = City;
            window.parent.document.getElementById(DataDisplayID + "FaxTxt").value = Fax;
            window.parent.document.getElementById(DataDisplayID + "EmailTxt").value = Email;
            window.parent.document.getElementById(DataDisplayID + "PhoneTxt").value = Phone;
            window.parent.document.getElementById(DataDisplayID + "ContactNameTxt").value = Contact;
        }
        if (Type == "DhxPickUpConsignee") {
            DataDisplayID = "ctl00_MasterCph_";

            window.parent.document.getElementById(DataDisplayID + "DelCustomerNameTxt").value = Name;
            window.parent.document.getElementById(DataDisplayID + "DelAddressTxt").value = Address;
            window.parent.document.getElementById(DataDisplayID + "DesZipTxt").value = Zip;
            window.parent.document.getElementById(DataDisplayID + "DesCityTxt").value = City;    
            window.parent.document.getElementById(DataDisplayID + "DelPhoneTxt").value = Phone;
            window.parent.document.getElementById(DataDisplayID + "DelContactNameTxt").value = Contact;
        }
        if (Type == "DhxQuote") {

            DataDisplayID = "ctl00_MasterCph_";

            window.parent.document.getElementById(DataDisplayID + "ContactNameTxt").value = Contact;
            window.parent.document.getElementById(DataDisplayID + "PhoneTxt").value = Phone;
            window.parent.document.getElementById(DataDisplayID + "FaxTxt").value = Fax;
            window.parent.document.getElementById(DataDisplayID + "EmailTxt").value = Email;
            window.parent.document.getElementById(DataDisplayID + "AddressTxt").value = Address;
            window.parent.document.getElementById(DataDisplayID + "ZipCodeTxt").value = Zip;
            window.parent.document.getElementById(DataDisplayID + "CityTxt").value = City;
            window.parent.document.getElementById(DataDisplayID + "StateTxt").value = State;
           }
        else {
            DataDisplayID = "ctl00_MasterCph_";

            window.parent.document.getElementById(DataDisplayID + "DeliveryNameTxt").value = Name;
            window.parent.document.getElementById(DataDisplayID + "DeliveryAddressTxt").value = Address;
            window.parent.document.getElementById(DataDisplayID + "DeliveryZipTxt").value = Zip;
            window.parent.document.getElementById(DataDisplayID + "DeliveryCityTxt").value = City;
            window.parent.document.getElementById(DataDisplayID + "DeliveryStateTxt").value = State;
            window.parent.document.getElementById(DataDisplayID + "DeliveryCountryTxt").value = Country;
            window.parent.document.getElementById(DataDisplayID + "DeliveryFaxTxt").value = Fax;
            window.parent.document.getElementById(DataDisplayID + "DeliveryEMailTxt").value = Email;
            window.parent.document.getElementById(DataDisplayID + "DeliveryPhoneTxt").value = Phone;
            window.parent.document.getElementById(DataDisplayID + "DeliveryContactTxt").value = Contact;
        }
    }


    //CLOSE POP UP
    //window.parent.CloseAddressPopUp();
}

//Calculates the Dim weight
function DimWeightForAir(Length, Width, Height, Quantity, DimWeightId) {

    var DimFactor;
    var DimenWgt;
    var cmbServiceLevel = document.getElementById("ctl00_MasterCph_ServiceLevelCmb");
    var cmbServiceLevelVal = cmbServiceLevel.options[cmbServiceLevel.selectedIndex].value;

    var Url = "";

    Url = "../GetJSONData.aspx?type=Service&ServiceKey=" + cmbServiceLevelVal;

    $.ajax({
        type: 'POST',
        url: Url,
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function(Obj) {
            if ((Obj.length > 0)) {
                DimFactor = Obj[0].Service;
                DimenWgt = parseInt((Length * Width * Height * Quantity) / DimFactor);
                //If the dimensional weight is Less than 0
                if (DimenWgt <= 0) {
                   
                   $("#MessagePopUp").text("DimensionalWeight can not be 0. \n Please check length, width and height.");
                   $('#MessagePopUp').dialog('open');
                    document.getElementById(LengthId).focus();

                }
                if (DimenWgt > 999999) {                 
                    $("#MessagePopUp").text("DimensionalWeight not in range, must be less than 999,999. \n Please check and re-enter the dimensions.");
                    $('#MessagePopUp').dialog('open');
                    document.getElementById(LengthId).focus();
                }
             
                $("#" + DimWeightId).val(DimenWgt);

            }

        }
    });

}

//This function calculates the dimendetails and returns the result 
//message and the dimensionalweight in an array
function GetDimWeightOfLineItems(LengthId, WidthId, HeightId, QtyId, DimWeightId) {

    var ResultArr = new Array(2);
    var Quantity = 0;
    var Length = 0;
    var Width = 0;
    var Height = 0;
    var DimenWgt = 0;

    ResultArr[0] = "";
    ResultArr[1] = 0;
    
    Quantity = document.getElementById(QtyId);
    Length = document.getElementById(LengthId);
    Width = document.getElementById(WidthId);
    Height = document.getElementById(HeightId);

    if (validateNumberForDetails(Quantity, "Qty", true) != "") {
        ResultArr[0] = validateNumberForDetails(Quantity, "Qty", true);
        $("#MessagePopUp").text(ResultArr[0]);
        $('#MessagePopUp').dialog('open');
        document.getElementById(QtyId).focus();
       
    }

    if (validateNumberForDetails(Length, "Length", true) != "") {
        ResultArr[0] = validateNumberForDetails(Length, "Length", true);
       
    }

    if (validateNumberForDetails(Width, "Width", true) != "") {
        ResultArr[0] = validateNumberForDetails(Width, "Width", true);       
        
    }

    if (validateNumberForDetails(Height, "Height", true) != "") {
        ResultArr[0] = validateNumberForDetails(Height, "Height", true);       
        
    }

    if ((Quantity.value != "") && (Length.value != "") && (Width.value != "") && (Height.value != "")) {

        if ((ResultArr[0] != "") && (ResultArr[0] != undefined)) {
            $("#MessagePopUp").text(ResultArr[0]);
            $('#MessagePopUp').dialog('open');
            return false;
        }
        else {
            //get the dimensional weight
            DimWeightForAir(Length.value, Width.value, Height.value, Quantity.value, DimWeightId);
        }      
    }
}

//This function calls the dimensional calculation function and 
//returns the value along with error message if any
function GetDimensionalWeightByRowItem(obj) {

    $("#MessagePopUp").text("");
    
    var DimWeightArr = new Array();
    var BaseId = obj.id.split("GetDimWgtBtn")[0];
    var LengthId = BaseId + "LengthTxt";
    var WidthId = BaseId + "WidthTxt";
    var HeightId = BaseId + "HeightTxt";
    var QtyId = BaseId + "QtyTxt";
    var DimWeightId = BaseId + "DimWgtTxt";

    GetDimWeightOfLineItems(LengthId, WidthId, HeightId, QtyId,DimWeightId);

    return false;
}

//AutoFill Details Line Item
function AutoFillDetailsLineItemForDHX(PkgTypeObj) {

    var FC20Arr = ['19.5', '7.8', '7.9','1116'];
    var FC40Arr = ['39.6', '7.8', '7.9', '2377'];
    var FC40HArr = ['39.6', '7.8', '8.9', '2684'];
    var FC45Arr = ['44.6', '7.8', '8.10', '3013'];
    var FT20Arr = ['18.8', '8', '7.7', '0'];
    var FT40Arr = ['38.9', '7.6', '6.10', '0'];
    var FT40HArr = ['39.7', '6.11', '6.8', '0'];
    
    var PkgType = $(PkgTypeObj).val()
    var BaseId = PkgTypeObj.id.split("PackageTypeCmb")[0];
    var LengthId = BaseId + "LengthTxt";
    var WidthId = BaseId + "WidthTxt";
    var HeightId = BaseId + "HeightTxt";
    var TotalVolId = BaseId + "CubicFeetTxt";
    
    switch (PkgType) {
        case "FC20":
            SetDimension(LengthId, WidthId, HeightId,TotalVolId, FC20Arr);
            break;
        case "FC40":
            SetDimension(LengthId, WidthId, HeightId,TotalVolId, FC40Arr);
            break;
        case "FC40H":
            SetDimension(LengthId, WidthId, HeightId,TotalVolId, FC40HArr);
            break;
        case "FC45":
            SetDimension(LengthId, WidthId, HeightId,TotalVolId, FC45Arr);
            break;
        case "FT20":
            SetDimension(LengthId, WidthId, HeightId,TotalVolId, FT20Arr);
            break;
        case "FT40":
            SetDimension(LengthId, WidthId, HeightId,TotalVolId, FT40Arr);
            break;
        case "FT40H":
            SetDimension(LengthId, WidthId, HeightId,TotalVolId, FT40HArr);
            break;
        case "FC45":
            SetDimension(LengthId, WidthId, HeightId,TotalVolId, FC45Arr);
            break;
        default:
    }
}

//Set the dimensions
function SetDimension(LengthId, WidthId, HeightId,TotalVolId, DimenArr) {
    if (DimenArr[0] != '') {
        $("#" + LengthId).val(DimenArr[0]);
    }
    if (DimenArr[1] != '') {
        $("#" + WidthId).val(DimenArr[1]);
    }
    if (DimenArr[2] != '') {
        $("#" + HeightId).val(DimenArr[2]);
    }
    if (DimenArr[3] != '') {
        $("#" + TotalVolId).val(DimenArr[3]);
    }
}


