﻿var RATES_ERROR_MESSAGE = "Discount Rates for This Lane Are Available Off-line. Call 800-878-1980 x1";
var ShipmentID = 0; // this is used for both shipping.aspx and admin.aspx
var ShipmentExsv = false;
var TotalPrice = 0;
var LTL=1;
var Truckload=2;
var Flatbed=3;
var ShipType=1;
var errosMsgs={
"incorrect":{
"Qty":"Please enter correct value for Qty field,it must be number of more than 0.",
"Packaging":"Please select Packaging type.",
"Weight (lbs)":"Please enter correct Weight of item,it must be number of more than 0.",
"Weight":"Please enter correct Weight of item,it must be number of more than 0.",
"L(in)":"Please enter correct length of item,it must be number of more than 0.",
"W(in)":"Please enter correct width of item,it must be number of more than 0.",
"H(in)":"Please enter correct height of item,it must be number of more than 0."
},
"requery":{"Weight (lbs)":"Please enter Weight of item,it must be number of more than 0."}
};

OnErrorCustom = OnPATError;
function showError(errorText) {
    var errTxt = $get("ErrorText");
    var errWnd = typeof(placeHolderID) != "undefined" && placeHolderID != null ? $find(placeHolderID) : null;
    if (errWnd && errTxt) {errTxt.innerHTML = errorText; errWnd.show();} else alert(errorText);
}
function gotServiceError(data)
{
    if(data._message=="Object reference not set to an instance of an object.")
    {
        window.location = window.location.href.split("#")[0];
        return;
    }   
    else
    {
        OnServiceError(data);
    }
}
function OnPATError(val)
{
    if (val == "NullUser")
        document.location("SignIn.aspx");
    var patt1 = /(\w+):\s(\w+)\s(.+):\s(.*)/;
    error=patt1.exec(val);
    if(error!=null&&error[2]=="Incorrect")
    {
        if(error[4]=="empty field")
        {
             if(errosMsgs["requery"][error[3]]!=undefined)
            {
                showError(errosMsgs["requery"][error[3]]);
            }
            else
            {
                showError("Please enter value for "+error[3]+" field");
            }
        }
        else 
        {
            if(errosMsgs["incorrect"][error[3]]!=undefined)
            {
                showError(errosMsgs["incorrect"][error[3]]);
            }
            else
            {
                showError("Please enter correct value for "+error[3]+" field");
            }
        }
        
    }
    else
    {
        var patt2=/(Required or invalid value for field|Selection required for field) (.*):(.*)/;
        error=patt2.exec(val);
        if(error[4]=="")
        {
            if(errosMsgs["requery"][error[2]]!=undefined)
            {
                showError(errosMsgs["requery"][error[2]]);
            }
            else
            {
                showError("Please enter value for "+error[2]+" field");
            }
        }
        else 
        {
            if(errosMsgs["incorrect"][error[2]]!=undefined)
            {
                showError(errosMsgs["incorrect"][error[2]]);
            }
            else
            {
                showError("Please enter correct value for "+error[2]+" field");
            }
        }
    }
    return false;
}

function InitShipment(id) {
    ShipmentID = id;
    REInit("ShipmentSRE", null, id, null, true, "ShipmentLoaded", ShipmentArrived, null, null, ShipmentUpdated);
    TableInit("ShipmentPackages", Hash("ShipmentID", ShipmentID));
    TableInit("CreateBOLShipmentPackages", Hash("ShipmentID", ShipmentID));
    TableInit("BOLViewShipmentPackages", Hash("ShipmentID", ShipmentID));
    TableInit("AddressBook", Hash("accID", accID));
    TableInit("PackageBook", Hash("accID", accID));
    Tables.GetSavedCards(accID,null, gotSavedCards,gotServiceError);
    Tables.GetStates(gotStates,gotServiceError);
    Tables.GetSavedCards(accID,-1,gotOneSavedCard,gotServiceError);
    $("#ShipSelect a").hover(
    function() {
        var hint = "#" + this.id.replace("label", "hint");
        $(hint).show();
    },
    function() {
        var hint = "#"+this.id.replace("label", "hint");
        $(hint).hide();
    }
    );

    switch (shipType) {
        case 2: $("#radioTruckload").attr("checked", true); break;
        case 3: $("#radioFlatbed").attr("checked", true); break;
        default: $("#radioLTL").attr("checked", true);
    }

    ShowHideByShipType(shipType);
   }

function CaptureTabKey()
{
    // Capture "tab" key and route focus into PAT table.    
    
    var tab = document.getElementById("ShipmentPackages");
    var Mcell = objList["ShipmentPackages"];
    
    var evt = new Object();
    evt.keyCode = 9;
    
    eval(Mcell.SelectCurRow(Mcell.TableRows[0]));
    eval(Mcell.DoEdit(Mcell.TableRows[0].cells[1],evt));
    
}

function paymentTypeSelector_Click(control) {
	var selected = $get("paymentType" + parseInt(control.value));
	selected.className = "";
	
	var unselected = $get("paymentType" + (3 - parseInt(control.value)));
	unselected.className = "hidden";
}

function ShipmentLoaded(sender, rowid) {
    document.getElementById("FromLimitedAccess").checked = fromLimAccChecked;
    document.getElementById("ToLimitedAccess").checked = toLimAccChecked;    

    disableCtrlByName("FromLimitedAccess_ShipmentSRE", !fromLimAccChecked);
    disableCtrlByName("ToLimitedAccess_ShipmentSRE", !toLimAccChecked);               
}

function fillAccessorials(data,accl) {
accl.html("");
    var accs = ["FromResidential", "ToResidential", "IsHazmat", "ToInside", "Appointment",
        "FromLiftgate", "ToLiftgate", "TradeShowDelivery", "TradeShowPickup"];
    $.each(accs, function(index, value) {
        if (data[value] == null || !data[value])
            return;
        var l = $("label[for=" + value + "_ShipmentSRE]").text();
        if (l != "")
            accl.append("<li>" + l + "</li>");
    });
    accs = ["FromLimitedAccess", "ToLimitedAccess"];
    $.each(accs, function(index, value) {
        if (data[value] == null)
            return;
        var l = $("label[for=" + value + "]").text();
        if (l != "") l += ": ";
        l += data[value + "Desc"];
        accl.append("<li>" + l + "</li>")
    });
}

function ShipmentArrived(table) {
    var data = table.rows[0];
    var status = data["status"];
    if (status == null || status < 1)
        status = 1;
    else if (status > 6)
        status = 6;
    switch (status) {
        case 2:
            UpdateCarrierHeader();
            break;
    }
    var shipDateDay = data["Date"].getDay();
    ShipmentExsv = data["ShipType"] != 1 || shipDateDay == 6 || shipDateDay == 0;        
    $("#ExcessiveShipmentBOL").text(data["No"]);
     $("#MaskExcessiveShipmentBOL").text(data["No"]);
    $("#CarrierQuoteNo").text(data["No"]);
    $("#QuoteIDS3").text(data["No"]);
    $("#QuoteIDS4").text(data["No"]);
    $("#QuoteIDS5").text(data["No"]);
    
    $("#CarrierDate").text(formatDate(data["Date"]));
    $("#CarrierZipFrom").text(data["FromZip"]);
    $("#CarrierZipTo").text(data["ToZip"]);
    $("#CreateBOLCarrier").text(data["CarrierName"]);
    $("#CreateBOLDate").text(formatDate(data["Date"]));
    $("#CreateBOLFromZip").text(data["FromZip"]);
    $("#CreateBOLToZip").text(data["ToZip"]);
    var accl = $("#CreateBOLAccessorials");
    fillAccessorials(data,accl);
    fillAccessorials(data,$("#AccessorialsStep2"));
    TotalPrice=data["Price"];
    $("#ChargeAmountS3").text(formatMoney(TotalPrice));
    $("#ChargeAmountS4").text(formatMoney(TotalPrice));
    $("#ChargeAmountS5").text(formatMoney(TotalPrice));
    $("#BOLViewCarrier").text($("#CreateBOLCarrier").text());
    $("#BOLViewDate").text($("#CreateBOLDate").text());
    var fields = ["FromCompanyName", "FromContactName", "FromAddress1", "FromAddress2",
        "FromCity", "FromZip", "FromState", "FromPhone",
        "ToCompanyName", "ToContactName", "ToAddress1", "ToAddress2",
        "ToCity", "ToZip", "ToState", "ToPhone",
        "SpecialInstructions"];
    $.each(fields, function(index, field) {
        var id = "#BOLView" + field;
        if (field.indexOf("State") > 0)
            field += "Name";
        var value = stringify(data[field]);
        if (value == "")
            $(id).html("&nbsp;");
        else
            $(id).text(value);
    });
    $("#BOLViewAccessorials").html(accl.html());
    // ----
    var oldStep = curStep;
    step(status, true);
    if (oldStep != curStep)
        switch (curStep) {
        case 2:
            GetCarriers();
            break;
    }
}

function OnChangeShipType(type) {
    ShipType=type;
    Tables.SetShipType(ShipmentID, type, OnSetShipType, gotServiceError);
    ShowHideByShipType(type);
    showStepErrors(curStep, false);
}

function ShowHideByShipType(type) {
    if (type == 1) {
        $("#PackagePane").show();
        $("#NonLTL").hide();
        RefreshPackages();
    }
    else {
        $("#PackagePane").hide();
        $("#NonLTL").show();
        Tables.DeleteShipProducts(ShipmentID, OnDeleteShipProd, gotServiceError);
        if (type == 2) {
            $("[class~='flatbed']").hide();
            $("[class~='truckspace']").show();
        }
        else {
            $("[class~='truckspace']").hide();
            $("[class~='flatbed']").show();
        }
    };   
}

function OnDeleteShipProd() { 
}

function OnSetShipType() {
}

function ShipmentUpdated(sre, res) {
}

function RefreshShipment() {
    RERefresh("ShipmentSRE", null, ShipmentID);
}

var curStep = null;
function step(st, force) {
    if (curStep != null && !force && st > curStep) {
        return;
    }
    if (curStep != null && curStep == 6&&st!=0) {
        return;
    }
    if(st==0) {
         Shipping.NextStep(0, OnNewShip,gotServiceError);
         return;
    }
    if(st==2&&curStep>st) {
        return;
    }
    
    if(st == 5) {
    
        if(TotalPrice>CreditLimit) {
            disableCtrlByName("viaTerms","disable");  
        }
    }
    if (curStep != null && curStep > st) {
        Shipping.UpdateStatus(ShipmentID, st,null,gotServiceError);
    }   
    curStep = st;
    showStep(st);
}

function OnNewShip(result) {
    window.location = "./Shipping.aspx";
}

function showStep(st) {
    for (var s = 1; s <= 6; s++) {
        var div = $("#Steps #Step" + s);
        var a = $(div).find("a");
        var img = $(div).find("img");
        var src = img.attr("src");
        if (s == st) {
            if (src.indexOf("-active") < 0)
                img.attr("src", src.replace(".gif", "-active.gif"));
        } else {
            if (src.indexOf("-active") > 0)
                img.attr("src", src.replace("-active", ""));
        }
        
        if (s==2||s>st||st==6&&s!=1) {
            a.removeAttr("href");
            a.attr("disabled", "disabled");
        } else {
            a.attr("href", "#");
            a.removeAttr("disabled");
        }
        var panel = $("#Step" + s + "Panel");
        if (panel != null) {
            if (st == s)
                panel.show();
            else
                panel.hide();
        }
    }
}

function validateReqSelect(val) {
    if(val=="-1") {
        return false;
    } else {
        return true;
    }
}
function validateStepInputs(step) {
    var errors=new Array();
    inputs=$("#Step"+step+"Panel input"); 
    var pattern=/validate.+/;
    inputs.each(
        function(index,item)
        {
            if($(item).attr("required") != null) 
            {
                if(item.value=="") 
                {
                    errors.push($(item).attr("required"));
                }
            }
            
            var isValid=false;
            attributes=item.attributes;
            for(var i=0;i<attributes.length;i++) 
            {
                if(attributes[i].nodeName.match(pattern)) 
                {
                    try 
                    {
                        toEval="isValid="+attributes[i].nodeName+"("+item.value+");";
                        if(!isValid) 
                        {
                            errors.push($(item).attr(attributes[i].nodeName));
                        }
                    } 
                    catch(e) {}
                }
            }
        });
    
    return errors.length > 0 ? errors : false;
}

function validateStep(step) {
    var stepErrors=false;
    switch (step)
    {
        case 1:
            stepErrors = validateStep1();
            break;
        case 3:
            stepErrors=validateStepInputs(step);
            break;
        case 5:
            stepErrors = validateStep5();
            break; 
        default:
            stepErrors=false;
    }
    
    return stepErrors;
}

function validateStep1() {
    var stepErrors = new Array();

    if (ShipType == LTL) {
        stepErrors = new Array();
        if ($("#ToLimitedAccess").attr("checked") && document.getElementById("ToLimitedAccess_ShipmentSRE").value == '-1') {
            stepErrors.push("Select Limited Access Delivery");
        }
        if ($("#FromLimitedAccess").attr("checked") && document.getElementById("FromLimitedAccess_ShipmentSRE").value == '-1') {
            stepErrors.push("Select Limited Access Pickup");
        }
    }

    if ($("#DeclaredValue_ShipmentSRE").val() <= 0) {
        stepErrors.push("'Declared Shipment Value' should be more than zero");
    }

    if (!Validation.Required($("#DeclaredValue_ShipmentSRE").val())) {
        stepErrors.push("'Declared Shipment Value' is required field");
    }

    if (!Validation.PositiveMoney($("#DeclaredValue_ShipmentSRE").val())) {
        stepErrors.push("'Declared Shipment Value' has invalid format (valid format is XXXX.XX)");
    }
    

//    var button = $get("radioButton1");
//    if (button == null || button.checked) {
//        if (!Validation.Required($("#CCName").val())) {
//            stepErrors.push("Card 'Nickname' is required field");
//        }

//        if (!Validation.Required($("#CCHolder").val())) {
//            stepErrors.push("'Name on Card' is required field");
//        }

//        if (!Validation.Required($("#CCNumber").val())) {
//            stepErrors.push("'Card Number' is required field");
//        }

//        if (!Validation.ExpDate($("#CCExpDate").val())) {
//            stepErrors.push("'Expiration Date' has incorrect format");
//        }

//        if (!Validation.Required($("#CCCVN").val())) {
//            stepErrors.push("'CSVII Code' is required field");
//        }

//        if (!Validation.Required($("#CCStreet").val())) {
//            stepErrors.push("'Billing Address' is required field");
//        }

//        if (!Validation.Required($("#CCCity").val())) {
//            stepErrors.push("'Billing City' is required field");
//        }

//        if (!Validation.Required($("#CCState").val())) {
//            stepErrors.push("'Billing State' is required field");
//        }

//        if (!Validation.Zip($("#CCZip").val())) {
//            stepErrors.push("'Billing Zip' is required field");
//        }
//    }

    return stepErrors;
}

function validateStep5() 
{
    var stepErrors = new Array();
    
    var button = $get("radioButton1");
    if (button == null || button.checked) 
    {
        if (!Validation.Required($("#CCName").val()))
        {
            stepErrors.push("Card 'Nickname' is required field");
        }
        
        if (!Validation.Required($("#CCHolder").val()))
        {
            stepErrors.push("'Name on Card' is required field");
        }
        
        if (!Validation.Required($("#CCNumber").val()))
        {
            stepErrors.push("'Card Number' is required field");
        }
        
        if (!Validation.ExpDate($("#CCExpDate").val()))
        {
            stepErrors.push("'Expiration Date' has incorrect format");
        }       
        
        if (!Validation.Required($("#CCCVN").val()))
        {
            stepErrors.push("'CSVII Code' is required field");
        }
        
        if (!Validation.Required($("#CCStreet").val()))
        {
            stepErrors.push("'Billing Address' is required field");
        }
        
        if (!Validation.Required($("#CCCity").val()))
        {
            stepErrors.push("'Billing City' is required field");
        }
        
        if (!Validation.Required($("#CCState").val()))
        {
            stepErrors.push("'Billing State' is required field");
        }
        
        if (!Validation.Zip($("#CCZip").val()))
        {
            stepErrors.push("'Billing Zip' is required field");
        }
    }
    
    return stepErrors;
}

function nextStep() 
{
    var stepErrors = validateStep(curStep);
    showStepErrors(curStep,stepErrors);
    if(stepErrors!=false) {
        return;
    }
	//TODO Refactor it
    disableStepButton(curStep);

    if (curStep == 3) {
        SaveToAB('To');
        SaveToAB('From');
    } else if (curStep == 5) {
        var button = $get("radioButton1");
        var isTerms = !(button == null || button.checked)
        $("#CarrierProgress").show();
        Shipping.ProcessShipment(ShipmentID, isTerms, ProcessShipment_OnSuccess, gotServiceError);
        return;
    }
    
    $("#CarrierProgress").show();
    Shipping.NextStep(ShipmentID, onNewStep, gotServiceError);
 }

function ProcessShipment_OnSuccess(result) 
{
     $("#CarrierProgress").hide();

     if (result.error) 
     {
         showStepErrors(curStep, result.message);
         return;
     } 
     
     var button = $get("radioButton1");
     if (button == null || button.checked) 
     {
         Pay();
     }
     else 
     {
         $("#CarrierProgress").show();
         cardID = $("#SavedCard").selectedValues()[0];
         Shipping.sendPayEmail(ShipmentID, onEmailSended, gotServiceError);
         Shipping.NextStep(ShipmentID, onNewStep, gotServiceError);
     }  

    //$("#CarrierProgress").show();
    //Shipping.NextStep(ShipmentID, onNewStep, gotServiceError);
}

   function onEmailSended()
   {
       $("#CarrierProgress").hide();
   	   //Shipping.NextStep(ShipmentID, onNewStep, gotServiceError);
   }

function OnGetInstruction(res) {
    $("#BOLinstruction").html(res);
}

function onNewStep(result) {
    $("#CarrierProgress").hide();
    
    disableStepButton(curStep, result.NextButtonDisabled);
    
    if (result.IsExceptionLoad && result.NextButtonDisabled)
    {
        showStepErrors(curStep, result.message);
        return;
    }
    
    if (result.error)
        showStepErrors(curStep, result.message);
    else 
    {
        showStepErrors(curStep, false);
        showStepErrors(result.status, false);
        if (result.status == 6 && pageTracker != null)
            pageTracker._trackPageview("/Shipping.aspx");
        RefreshShipment();
    }
}

function disableStepButton(step, disable) {
    disableCtrlByName("Step" + step + "Next", disable);
}

function disableCtrlByName(ctrlName, disable) {
    var ctrl = $("#" + ctrlName);
    if (disable == null)
        disable = true;
    if (disable)
        ctrl.attr("disabled", true);
    else
        ctrl.removeAttr("disabled");
}

function showStepErrors(step, message) {
    var show = true;
    if (typeof(message) == "boolean") {
        show = message;
        message = "";
    }
    var div = $("#Step" + step + "Errors");
    var msg=message;
    if(message instanceof Array) {
        msg="<ul class='errorList'>";
        for(var i=0;i<message.length;i++) {
            msg+="<li>"+message[i]+"</li>";
        }
        msg+="</ul>";
    }
    div.html(msg);
    
    if (show)
        div.show();
    else
        div.hide();
}    



function SetUnknownLimitedType(checkBox, dropDownName)
{
    if (!checkBox.checked) {
        var field = dropDownName.toString().replace('_ShipmentSRE','');
        DDSetValue(dropDownName, '-1');
        ServerCall("SetData", "ShipmentSRE", Hash("rowid", ShipmentID, "field", field, "value", "-1", "args", Hash("rowid", ShipmentID), "inputid", dropDownName));        
     }
}   

/* ===== common code ================================================ */
function showExtPane(pane, show) {
    if (show == null)
        show = true;
    var p = $find(pane);
    if (p != null)
        show ? p.show() : p.hide();
}

function ValidateShZip(val, prefix) {
    if (prefix == null)
        prefix = "";
    if (val.length == 0)
        return prefix + "value required!";
    if (!val.match(/^\d{5}(-\d{4})?$/))
        return prefix + "incorrect value!";
    return null;
}

/* ===== step 1 ===================================================== */
function ValidateFromZip(val) {
    return ValidateShZip(val, "Shipping from: ");
}
function ValidateZipCode(obj,msg) {
    if(ValidateZip(obj.value)==true) {
        showStepErrors(curStep, false);
        disableStepButton(curStep, "");
    }
    else {
        showStepErrors(curStep, msg);
        disableStepButton(curStep, true);
    }
}
function NewFromAddress(res) {
    Shipping.UpdateAddress(ShipmentID, true, -1);
}

function ValidateToZip(val) {
    return ValidateShZip(val, "Shipping to: ");
}

function NewToAddress(res) {
    Shipping.UpdateAddress(ShipmentID, false, -1);
}

function AddNewPackage() {
    
    var cnt = TableGetRowsCnt("ShipmentPackages");
    if (cnt < 4) {
        Shipping.AddProduct(ShipmentID, null, RefreshPackages,gotServiceError);
    }
    else {
        ShowPackageOverflow();
    }
}

function RefreshPackages() {
    TableRefresh("ShipmentPackages", Hash("ShipmentID", ShipmentID));
    TableRefresh("CreateBOLShipmentPackages", Hash("ShipmentID", ShipmentID));
    TableRefresh("BOLViewShipmentPackages", Hash("ShipmentID", ShipmentID));
}

function CheckShipDate(val) {
    var shipdate = new Date(Date.parse(val));

    var now = new Date();
    var summand = (ShipType == LTL) ? 0 : 1;
    //For truckload or flatbed, Preferred Ship Date must be next day or greater
    var today = new Date(now.getFullYear(), now.getMonth(), now.getDate() + summand, 0, 0, 0);

    if (shipdate < today) {
        return false;
    }

    var day = shipdate.getDay();
    
    if (day == 6 || day == 0)
    {
        ExcessiveShipment();
    }
    
    return null;
}

var selpackageID = -1;
function OnPackageSelectRow(name, id) { selpackageID = id; }
function SaveToPB(packid)
{
    /*
    if (selpackageID == -1)
        alert("Please select the package above.");
    else
        Tables.SavePackageToPB(selpackageID, onPackageSaved, onPackageSavedError);
    */
    Tables.SavePackageToPB(packid, onPackageSaved, onPackageSavedError);
}
function onPackageSaved(result)
{
    if (!result)
        alert("The same package already exists in your Package Book.");
    else
    {
        TableRefresh("PackageBook", Hash("accID", accID));
        alert("The selected package was successfully saved to your Package Book.");
    }
}
function onPackageSavedError(result) { 
    if(result._message=="Object reference not set to an instance of an object.")
    {
        window.location = window.location.href.split("#")[0]; 
        return;
    }   
    alert("The selected package fields aren't completed."); 
}

function SaveToAB(addrType)
{
    switch (addrType)
    {
        case "From":
            Tables.SaveAddressToAB(accID,$get("FromCompanyName_ShipmentSRE").value, $get("FromContactName_ShipmentSRE").value,
                $get("FromAddress1_ShipmentSRE").value,$get("FromAddress2_ShipmentSRE").value,$get("FromCity_ShipmentSRE").value,
                $get("CreateBOLFromZip").innerHTML,$get("FromState_ShipmentSRE").value,$get("FromPhone_ShipmentSRE").value);
            break;
        case "To":
            Tables.SaveAddressToAB(accID,$get("ToCompanyName_ShipmentSRE").value, $get("ToContactName_ShipmentSRE").value,
                $get("ToAddress1_ShipmentSRE").value,$get("ToAddress2_ShipmentSRE").value,$get("ToCity_ShipmentSRE").value,
                $get("CreateBOLToZip").innerHTML,$get("ToState_ShipmentSRE").value,$get("ToPhone_ShipmentSRE").value);
            break;
    }    
}


function ShowFCCalcInfo() { showExtPane(CalcInfoExtID); }
function HideFCCalcInfo() { showExtPane(CalcInfoExtID, false); }
function ShowNMFCInfo() { showExtPane(NMFCInfoExtID); }
function HideNMFCInfo() { showExtPane(NMFCInfoExtID, false); }
function ShowDeclaredShipmentValueInfo() { showExtPane(DeclaredShipmentValueInfoExtID); }
function HideNDeclaredShipmentValueInfo() { showExtPane(DeclaredShipmentValueInfoExtID, false); }
function ShowPackageOverflow() { showExtPane(PackageOverflowPaneExtID); }
function HidePackageOverflow() { showExtPane(PackageOverflowPaneExtID, false); }

function ExcessiveShipment(show) {
    if (typeof (show) == "object" && $(show).attr("type") == "checkbox") {
        if (!(show = show.checked))
            return;
    }
    showExtPane(ExcessiveShipmentPaneExt, show);
}

//---------------- Lookup Address -------------------------
var addressID = -1;
var addressType = "";

function LookupAddress(type) { addressType = type; showExtPane(AddressLookupPaneExtID); }
function CancelAddressLookup() { showExtPane(AddressLookupPaneExtID, false); }
function RowSelectedAddress(name, id) {
    addressID = id;
    switch (addressType) {
        case "From":
            $("#FromZip_ShipmentSRE").val(stringify(TableGetDataValue("AddressBook", "Zip", addressID)));
            Shipping.UpdateAddress(ShipmentID, true, addressID);
            break;
        case "To":
            $("#ToZip_ShipmentSRE").val(stringify(TableGetDataValue("AddressBook", "Zip", addressID)));
            Shipping.UpdateAddress(ShipmentID, false, addressID);
            break;
    }
    CancelAddressLookup();
    TableSetCurRow("AddressBook", null);
}

//---------------- Lookup Package -------------------------
var packageID = -1;
function LookupPackage() { showExtPane(PackageLookupPaneExtID); }
function CancelPackageLookup() { showExtPane(PackageLookupPaneExtID, false); }
function RowSelectedPackage(name, id) {
    packageID = id;
    CancelPackageLookup();
    TableSetCurRow("PackageBook", null);
    var cnt = TableGetRowsCnt("ShipmentPackages");
    if (cnt < 4) {
         Shipping.AddProduct(ShipmentID, packageID, RefreshPackages,gotServiceError);
    }
    else {
        ShowPackageOverflow();
    }
}

//function onError(error)
//{
//    alert("error: " + error.responseText);
//}

function validate_Desc_ShipmentProductsOnLineSRE()
{
}

function validate_Qty_ShipmentProductsOnLineSRE()
{
}

function validate_Weight_ShipmentProductsOnLineSRE()
{
}

function validate_Length_ShipmentProductsOnLineSRE()
{
}

function validate_Width_ShipmentProductsOnLineSRE()
{
}

function validate_Height_ShipmentProductsOnLineSRE()
{
}

function validate_NMFC_ShipmentProductsOnLineSRE()
{
}

function validate_Phone_ShipmentProductsOnLineSRE()
{
}

/* ====================== Step 2 ========================= */
function UpdateCarrierHeader() {
    Shipping.GetProductsTotals(ShipmentID, onCarrierHeaderData);
}

function onCarrierHeaderData(result) {
    $("#CarrierNoPieces").text(result["NoPieces"]);
    $("#CarrierTotalWeight").text(formatWeight(result["TotalWeight"]));
    $("#CarrierClasses").text(result["Classes"]);
}
function onCarrierError(errors, userContext, methodName)  
{
    $("#CarrierProgress").hide();
    showStepErrors(curStep, RATES_ERROR_MESSAGE);
}

function GetCarriers(start) {
    if (start == null)
        start = true;
    var id = null;
    if (start) {
        // disable next button
        disableStepButton(curStep);
        $("#CarrierQuotesTable tbody").html("");
        // show progress
        $("#CarrierProgress").show();
        id = ShipmentID;
    }
    // call ws
    Shipping.GetCarriers(id, gotCarriers,onCarrierError);
}

function gotCarriers(result) {
    var t = $("#CarrierQuotesTable tbody");
    t.html(result.list);
    if (result.error) {
        showStepErrors(curStep, result.message);
    }  else
        showStepErrors(curStep, false);
    if (result.error || result.finished)
        $("#CarrierProgress").hide();

    if (result.finished) {
        if (t.html() == '') {
            showStepErrors(curStep, RATES_ERROR_MESSAGE);
        }
        
        t.find("input[type=radio]").each(function() {
            $(this).removeAttr("disabled");
        });
    } 
    else if (!result.error) 
    {
        var call = function() {
            Shipping.GetCarriers(null, gotCarriers,onCarrierError);
        };
        var timer = CarrierTimer;
        if (timer != null && timer != "")
            timer = parseInt(timer);
        if (timer != 0)
            setTimeout(call, timer);
        else
            call();        
    }
}

function ChooseCarrier(id) {
    Shipping.ChooseCarrier(ShipmentID, id, onCarrierChosen,gotServiceError);
}
function onCarrierChosen(result) { 
    disableStepButton(curStep, !result);
}

function CheckCarrierQuote(source, args) {
    var v = $get(CarrierQuote).value;
    args.isValid = v != null && v != "";
}

function gotSavedCards(result) { // result == datatable
    if (result.rows == null)
        return;
    var cc = $("#SavedCard");
    $.each(result.rows, function(index, card) {
        cc.addOption(card["ID"], card["Name"], false);
    });
}
function errorSavedCards(result)
{
    console.debug(result);
}

					
function gotOneSavedCard(result) { // result == datatable
    if (result.rows == null)
        return;
        res=result.rows[0];
    $("#CCName").val(res["Name"]==null?"":res["Name"]);
    $("#CCNumber").val(res["Number"]==null?"":res["Number"]);
    $("#CCExpDate").val(res["ExpDate"]==null?"":res["ExpDate"]);
    $("#CCCVN").val(res["CVN"]==null?"":res["CVN"]);
    $("#CCStreet").val(res["Street"]==null?"":res["Street"]);
    $("#CCCity").val(res["City"]==null?"":res["City"]);
    $("#CCZip").val(res["Zip"]==null?"":res["Zip"]);
    $("#CCState").selectOptions([res["State"]==null?"":res["State"].toUpperCase()]);
    $("#CCHolder").val(res["Holder"]==null?"":res["Holder"]);
    disableCardEntries(res["isNew"]==null);
    
}

function gotStates(result) { 
    if (result.rows == null)
        return;
    var cs = $("#CCState");
    cs.addOption("", "-- Select State --", true);
    $.each(result.rows, function(index, state) {
        cs.addOption(state["abbr"], state["name"], false);
    });
}

function SelectSavedCard() {
    var id = $("#SavedCard").selectedValues();
    id = id.length == 1? parseInt(id[0],10) :-1;
    Tables.GetSavedCards(accID,id,gotOneSavedCard,gotServiceError);
}

function disableCardEntries(disable) {
    if (disable == null)
        disable = true;
    $.each(["CCName", "CCNumber", "CCExpDate", "CCCVN","CCZip","CCStreet","CCState","CCCity","CCHolder"], function(index, id) {
        var c = $("#" + id);
        if (disable)
            c.attr("disabled", true);
        else
            c.removeAttr("disabled");
    });
}

function Pay(cardID) 
{
	showStepErrors(curStep, false);
    
    if (cardID == null)
    {
        cardID = $("#SavedCard").selectedValues()[0];
    }

    $("#CarrierProgress").show();
    
    if (cardID =='-1') 
    {
        Shipping.PayNew(ShipmentID, $("#CCName").val(),$("#CCNumber").val(),$("#CCExpDate").val(),
    	$("#CCCVN").val(),$("#CCStreet").val(),$("#CCState").val(),
    	$("#CCCity").val(),$("#CCZip").val(),$("#CCHolder").val(), onPaid, onPayErr);
    } 
    else 
    {
        Shipping.PayEx(ShipmentID, cardID, onPaid, onPayErr);
    }
}

function onPaid(result) {
    $("#CarrierProgress").hide();
    onNewStep(result);
}

function onPayErr(error) {
    $("#CarrierProgress").hide();
    alert("error: " + error._message);    
}

function ResetPasswordField() {
    $get('curPassword').value = "";
    $get('newPassword').value = "";
    $get('confirmPassword').value = "";
}
function ChangePassword() {
    var curPassword = $get('curPassword').value;
    var newPassword = $get('newPassword').value;
    var confirmPassword = $get('confirmPassword').value;
    if (curPassword.length == 0 || newPassword.length == 0 || confirmPassword.length == 0) {
        OnError("Please input current and new passwords.");
        return;
    }
    if (newPassword != confirmPassword) {
        OnError("You have not confirmed new password. Please try again.");
        return;
    }
    Tables.ChgPwd(curPassword, newPassword,null, OnPasswordChanged, gotServiceError);
}
function OnPasswordChanged(res) {
    ResetPasswordField();
    if (res == null)
        alert('Password has been changed successfully');
    else
        alert(res);
}

function ProfileTabs(tab) {
    for (var i = 0; ; i++) {
        var el = $get("ProfileTab" + i);
        if (el == null) break;
        el.style.display = "none";
        $get("li" + i).className = "";
    }
    var el = $get("ProfileTab" + tab);
    if (el == null) return;
    el.style.display = "";
    $get("li" + tab).className = "selected";
}

function ProfilePageInit() {
    TableInit("CreditCardHistory", Hash("accID", accID));
    TableInit("AddressBook", Hash("accID", accID));
    TableInit("PackageBook", Hash("accID", accID));
    TableInit("AcctUsers", Hash("accID", accID));
    REInit("UserInfoSRE", null, 1); // 1 is baloney, because tables.cs will use the right user id.
    REInit("AcctUsersSRE", Hash("accID", accID), -1, "AcctUsers", true);
    REInit("AccSRE", null, accID);
    REInit("address_SRE", null, -1, "AddressBook");
    REInit("package_SRE", null, -1, "PackageBook");
    ProfileTabs("0");
}

//------------------------------------------------------------------------------
function ValidateFloatVal(val) {
    res = new RegExp("[^0-9].{2,}");
    return (val != null) && (val != "") && !res.test(val);
}
function ValidatePositiveNumber(val) {
    res=new RegExp("^[0-9]+(\.[0-9]+)?$");
    return (val != null) && (val != "") && res.test(val);
}
function ValidatePositiveNumberOrNull(val) {
    return val==""?true:ValidatePositiveNumber(val);
}
function ValidateFloatVal2(val) {

    if (val == null || val == "")
        return true;
    else
        return ValidateFloatVal(val);
}
function ValidateStringVal(val, ctrl) {
    res = new RegExp("^[A-Za-z]");
    return (val != null) && (val != "") && res.test(val);
}
function ValidateIDVal(val) {
    return (val != null) && (val != "") && val > 0;
}
function ValidatePhone(val) {
    res = new RegExp("^(\+?\(?\d{1,3}\)?[\s\-]?)?\(?\d{3}\)?[\s\-]?\d{3}\-?\d{4}$");
    return (val != null) && (val != "") && res.test(val);
}

var Validation = {
    ExpDate : function (value) {
        res = new RegExp(/^[0-9]{4}$/);
        return (value != null) && (value != "") && res.test(value);
    },
    Zip : function (value) {
        res = new RegExp(/^\d{5}(-\d{4})?$/);
        return (value != null) && (value != "") && res.test(value);
    },
    Required : function (value) {
        return (value != null) && (value != "");
    },
    PositiveMoney : function (value) {
        res = new RegExp(/^\d+(\.\d{1,2})?$/);
        return (value != null) && (value != "") && res.test(value);
    }    
};

function ValidatePhone2(val) {
    if (val == null || val == "")
        return true;
    else
        return ValidatePhone(val);
}
function ValidateFax(val) {
    if (val == null || val == "")
        return true;
    else
        return ValidatePhone(val);
}
function ValidateEmail(val) {
    if (val == null || val == "")
        return true;
    else {
        res = new RegExp("^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)");
        return res.test(val);
    }
}
function ValidateZip(val) {
    res = new RegExp(/^\d{5}(-\d{4})?$/);
    return (val != null) && (val != "") && res.test(val);
}

//------------------------------------------------------------------------------
function stringify(val) {
    return (val == null ? "" : val);
}
function stringifyFloat(val) {
    return (val == null || val == "" ? 0 : val);
}
//-----------------------------------------------------------------------------
function formatDate(col, val) {
    if (typeof (val) == "undefined")
        val = col;
    if (!val.constructor || !val.constructor.prototype.toString().match(/function Date/))
        val = new Date(val);
    return val.format("MM/dd/yyyy");
}

function formatDateTime(col, val) {
    if (typeof (val) == "undefined")
        val = col;
    if (!val.constructor || !val.constructor.prototype.toString().match(/function Date/))
        val = new Date(val);
    return val.format("MM/dd/yyyy HH:mm");
}

function formatMoney(col, val) {
    if (typeof (val) == "undefined")
        val = col;
    if (typeof (val) == "string")
        val = val == "" ? 0 : parseFloat(val);
    return "$" + val.toFixed(2);
}

function formatWeight(col, value) {
    if (typeof (value) == "undefined")
        value = col;
    if (value == null || value == "")
        return "";
    var n = typeof (value) == "string" ? parseFloat(value) : new Number(value);
    return n.toFixed(2);
}

//-----------------------------------------------------------------------------
function PrintablePDF(type, id) {
    window.open("BOL.aspx?type=" + type + "&ID=" + id, "BOLView", "height=700px,width=900px,location=no,status=no,scrollbars=yes,menubar=yes");
}

function autoCompleteUserInfo_ItemSelected(source, eventArgs) {
	var val = eventArgs.get_value();
	
	TableRefresh("UserInfo", Hash("AccountID", -1, "UserID", val));
}

function accountSearchAutoComplete_ItemSelected(source, eventArgs) {
	var val = eventArgs.get_value();
	TableRefresh("AccountInfo", Hash("AccountID", val, "UserID", -1));
	TableRefresh("BOLInfo", Hash('AccountID', val, 'BolNumber', -1));
}

function couponsAutoComplete_ItemSelected(source, eventArgs) {
    var value = eventArgs.get_value();
    TableRefresh("Coupons", Hash("CouponID", value));
}

function inputControlPatHandler_OnChange(control, tableName, hash) {
   	if (control == null) {
   		alert("control == null");
   	}
   	
   	if (control.value != null && control.value == "") {
   		TableRefresh(tableName, hash);
   	}
   }

   function UserInfo_Load(res, tabData) {
   	if (res.TableRows.length == 1) {
   		TableSetCurRow("UserInfo", res.TableRows[0].dbid);
   	}
   }

   function AccountInfo_Load(res, tabData) {
   	if (res.TableRows.length == 1) {
   		TableSetCurRow("AccountInfo", res.TableRows[0].dbid);
   	}
   }

   function BOLInfo_Load(res, tabData) {
	if (res.TableRows.length == 1) {
   		TableSetCurRow("BOLInfo", res.TableRows[0].dbid);
   	}
   }

   function LoginAsButtonCode(self, row, coldef, cell, val) {
    if (row == null || row.dbid == null || row.dbid < 1) {
        cell.innerHTML = "";
    }
    else {
        cell.innerHTML = "<a class='login_as_css' href=\"Admin.aspx?act=loginas&UserID=" + row.dbid + "\">Login as</a>";
    }
   }
   
   function RenderDeleteButton(self, row, coldef, cell, val) {
   	cell.innerHTML = "<a class='login_as_css link' href=\"javascript:TableDelRow('" + self.name + "', " + row.dbid + ", '" + self.delConfirm + "');\" >Del</a>";
   }

   function CreateQuoteButtonCode(self, row, coldef, cell, val) {
   	if (row == null || row.dbid == null || row.dbid < 1) {
   		cell.innerHTML = "";
   	}
   	else {
   		accid = TableGetCurRowID("AccountInfo");
   		if (accid == null) accid = 0;
   		cell.innerHTML = "<a class='login_as_css'" + (accid < 1 ? " disabled=\"disabled\" onclick=\"return false;\"" : "") + " href=\"Admin.aspx?act=createquote&UserID=" + row.dbid + "&AccID=" + accid + "\">Create Quote</a>";
   	}
   }
   function RenderChangePasswdBtn(self, row, coldef, cell, val) {
    if (row == null || row.dbid == null || row.dbid < 1) {
        cell.innerHTML = "";
    }
    else {
        cell.innerHTML = "<a class='login_as_css' href=\"#\" onclick=\"changeUserPassword("+row.dbid+")\">Change passwod</a>";
    }
   }
   function changeUserPassword(id) {
        var newPassword=prompt("Enter new password");
        if(newPassword==null) {
            alert("Enter password");
        } else if(newPassword.length<8) {
            alert("Password length must be greater than 8");
        } else {
            Tables.ChgPwd("", newPassword,id, OnUserPasswordChanged, gotServiceError);
        }
   }
   function OnUserPasswordChanged(res) {
     if (res == null)
        alert('Password has been changed successfully');
    else
        alert(res);
   }
   function SaveToPBButtonCode(self, row, coldef, cell, val) {
   	if (row == null || row.dbid == null || row.dbid < 1) {
   		cell.innerHTML = "";
   	}
   	else {
   		cell.innerHTML = "<a class='login_as_css link' href=\"javascript:SaveToPB("+ row.dbid +");\" title=\"Save this item to my Product Book\">Save</a>";
   	}
   }

function sendToDoEmail() {
    Shipping.SendEmail(RERowID("ShipInfoRE"), 'FreightClick :: Admin Notification', $get("EmailBody").value, sendToDoEmail_Success,gotServiceError);
}

function sendToDoEmail_Success(result)
{
    alert(result.message);
}

function AdminTabs(tab) {
    var el;
    for (var i = 0; ; i++) {
        el = $get("AdminTab" + i);
        if (el == null) break;
        el.style.display = "none";
        $get("li" + i).className = "";
    }
    el = $get("AdminTab" + tab);
    if (el == null) return;
    el.style.display = "";
    $get("li" + tab).className = "selected";
}

function AdminInit() {
    TableInit("Coupons", Hash("CouponID", -1));
    TableInit("UserInfo", Hash("AccountID", -1, "UserID", -1));
	TableInit("BOLInfo", Hash('AccountID', -1, 'BolNumber', -1));
	TableInit("LTLQuotes", Hash('AccountID', -1, 'BolNumber', -1));
	TableInit("NonLTLQuotes", Hash('AccountID', -1, 'BolNumber', -1));
	TableInit("AccountInfo", Hash("AccountID", -1, "UserID", -1));
	TableInit("CreditCards", Hash("AccountID", -1));
	TableInit("PaymentHistory", Hash('AccountID', -1));
	TableInit("ShipmentPackages", Hash("ShipmentID", -1));
    TableInit("Carriers");
    REInit("carriers_SRE",null,-1);
    TableInit("TODO");
    TableInit("Online");
    TableInit("CompletedBOLs");
    TableInit("TermsInfo");
    TableInit("Globals");
    REInit("ShipInfoRE", null, "-1", "ShippingInfo,CompletedBOLs");
    REInit("AccountInfoRE", null, "-1", "AccountInfo");
    TableInit("ShipmentSummary", Hash('AccountID', -1));
    AdminTabs(0);
   }

   function shipmentRowSelected(tabname, rowid) {
       if (tabname != "TODO") { TableSelectAllRows("TODO", false); }
       if (tabname != "BOLInfo") { TableSelectAllRows("BOLInfo", false); }
       if (tabname != "LTLQuotes") { TableSelectAllRows("LTLQuotes", false); }
       if (tabname != "NonLTLQuotes") { TableSelectAllRows("NonLTLQuotes", false); }
       if (tabname != "CompletedBOLs") { TableSelectAllRows("CompletedBOLs", false); }
       if (tabname != "PaymentHistory") { TableSelectAllRows("PaymentHistory", false); }
   }

   function RefreshAdminTables() {
   	TableRefresh("AccountInfo", Hash("AccountID", -1, "UserID", -1));
   	TableRefresh("UserInfo", Hash("AccountID", -1, "UserID", -1));
   	TableRefresh("BOLInfo", Hash('AccountID', -1, 'BolNumber', -1));
   	TableRefresh("CreditCards", Hash("AccountID", -1));
   	TableRefresh("LTLQuotes", Hash('AccountID', -1));
   	TableRefresh("NonLTLQuotes", Hash('AccountID', -1));
   	TableRefresh("ShipmentSummary", Hash('AccountID', -1));
   	TableRefresh("PaymentHistory", Hash('AccountID', -1));
   }

   function ShipInfoRE_Loaded(sourceID, value) {
       if (value == 6) 
       {
           $(".secured").attr("disabled", true);
       }
       else 
       {
           $(".secured").removeAttr("disabled"); 
       }     
       return;
   }
   
   function ShipInfoRE_Changed(source) 
   {
       if (source.value == 6)
       {
            TableRefresh('CompletedBOLs');
            $(".secured").attr("disabled", true);
       }
       return;
   }

function QuoteHistoryPageInit() {
    TableInit("QuoteHistory");
}

function GlobalsOnTableSet(p) {
	TableRefresh("AccountInfo", Hash("AccountID", -1, "UserID", -1));
}

function ShippingHistoryPageInit() {
    TableInit("ShippingHistory");
}

function PrintBOLLink(self, row, coldef, cell, val) {
    $(cell).html("<a href=\"#\" onclick=\"PrintablePDF('bol', " + val + ");\">print</a>");
}

function EditBOLLink(self, row, coldef, cell, val) {
	//$(cell).html("<a href=\"Shipping.aspx?ID=" + row.getAttribute("dbid") + "\">" + val + "</a>");
	$(cell).html("<a href=\"Shipping.aspx?ID=" + row.dbid + "\">" + val + "</a>");
}

function bolIDButton_ClientClick(source, eventArgs) {
	var bolIDTextBox = document.getElementById('bolIDTextBox');

	if (bolIDTextBox == null) {
		return;
	}

	if (bolIDTextBox.value == null || bolIDTextBox.value == '') {
		TableRefresh("BOLInfo", Hash('AccountID', -1, 'BolNumber', -1));
		return;
	}

	/*try {
		var selectedShippingID = parseInt(bolIDTextBox.value, 10);
	}
	catch (error) { }*/

	TableRefresh("BOLInfo", Hash('AccountID', -1, 'BolNumber', bolIDTextBox.value));
	TableRefresh("LTLQuotes", Hash('AccountID', -1, 'BolNumber', bolIDTextBox.value));
	TableRefresh("NonLTLQuotes", Hash('AccountID', -1, 'BolNumber', bolIDTextBox.value));
}

var SchedulePickup = {
	Submit: function(pickupDateControl, pickupOpenControl, pickupCloseControl) {
		$('#SchedulePickupProgress').show();
		Shipping.SendScheduleEmail(ShipmentID, $get(pickupDateControl).value, $get(pickupOpenControl).value, $get(pickupCloseControl).value, SchedulePickup.OnSubmitSuccess, SchedulePickup.OnSubmitError);
	},
	OnSubmitSuccess: function(result) {
		alert(result.message);
		$('#SchedulePickupProgress').hide();
		if (!result.error) {
			SchedulePickup.Cancel();
		}
	},
	OnSubmitError: function(result) {
		alert(result.message);
		$('#SchedulePickupProgress').hide();
	},
	Cancel: function() {
		showExtPane(SchedulePickupPaneExtID, false);
	}
};