﻿/// <reference path="jquery-1.3.2.min-vsdoc.js" />

$(document).ready(function() {


    fixLookup();

    // png fix for ie6 an ie7
    $(document).pngFix();

    /*
        $("#aspnetForm").validate({
            onsubmit: false
        });
    */


    $("#PackageTbl tr:gt(1)").each(function(i, item) {
        //alert(i);
        var num = i;
        //if (num != 0 | num!=1)
        $(item).addClass("hiddentr");
        // alert('hello');
    });
    $(".articlesL1 tr:gt(1)").each(function(i, item) {

        if ($(item).attr('name') != "total") {
            $(item).addClass("hiddentr");
        }

    });
    $(".articlesL2 tr:gt(1)").each(function(i, item) {


        if ($(item).attr('name') != "total") {
            $(item).addClass("hiddentr");
        }

    });
    $(".articlesL3 tr:gt(1)").each(function(i, item) {

        if ($(item).attr('name') != "total") {
            $(item).addClass("hiddentr");
        }

    });
    $('.check').css('width', '20px');
    $('.articlesL1').show();
    $("input[name*='txtDateT']").datepicker({ showOn: 'button', buttonImage: 'Images/CalendarIcon.png', buttonImageOnly: true });
    $("input[name*='txtDateF']").datepicker({ showOn: 'button', buttonImage: 'Images/CalendarIcon.png', buttonImageOnly: true });

    $('.aBDP').each(function() {
        var wholePart, fractionPart;
        wholePart = Math.floor($(this).text() - 0);
        fractionPart = Math.floor(($(this).text() % 1) * 10000 + 0.5) / 10000 + "";
        html = '<span class="left">' + wholePart + '.' + '</span>';
        html += '<span class="right">' + fractionPart.substring(2) + '</span>';
        $(this).html(html);
    });

  //  alert($(".regPickup").val());
   if($(".regPickup").val()=="Y"){
    $(".pickup").removeClass("required");
   
   }

    $(".stypes").bind("change", function() {
        GetServices($(this).val());
    });


    //enable insurance 
    $(".chkInsurance").bind("blur", function() {

        if ($(this).attr('checked')) {
            $('.insurance').attr('disabled', '');
        }
        else {
            $('.insurance').attr('disabled', 'false');
        }
        return false;
    });
    hideRateDims();

    // $(".helpicon").tooltip({  position:['top', 'right'], offset: [10, -35] , tip: '.tooltip'});
    //$(".helpicon").betterTooltip({ speed: 250, delay: 200 });
    // $(".helpiconTariff").betterTooltip({ speed: 250, delay: 200 });

    DeliveryAddressCheck();
    AddressCheck();
    AddrressFileUpload();
    LoadPackageLine();
    LoadArticleLines(1);
    LoadArticleLines(2);
    LoadArticleLines(3);
    hideShippingDims();
    DeclarationCheck();
    checkInsurance();
    checkTotals();
    checkUnits();
    hideHistoryDocs();
    refreshTotals();
    commercialInvoiceOption();
    checkOwnInvoice();
    lmfCheckCity();
    htsCheck();

   // $('.txtAddress1').attr('disabled', 'false');
    //setPostMask();
  /*
    $.mask.masks.msk = { mask: '999' };

    //$('.txtAddrPost').setMask('msk');

    $.mask.masks = $.extend($.mask.masks, {
    mmk: { mask: '9999' },
    other_msk: { mask: '99999' }

    });
*/


    // 
    /*
  
    
    //  formatDecimals();

    /*----force only decimal amount characters-*/

    $(function() {
        $("input.numeric").bind('keyup blur', function() {

            if (this.value.match(/[^\d+(?:\.\d{0,2})?$]/g)) {
                this.value = this.value.replace(/[^\d+(?:\.\d{0,2})?$]/g, '');
            }

        });
    });

    //clear form function
    $.fn.clearForm = function() {
        return this.each(function() {
            var type = this.type, tag = this.tagName.toLowerCase();
            if (tag == 'form')
                return $(':input', this).clearForm();
            if (type == 'text' || type == 'password' || tag == 'textarea') {
                this.value = '';
                $("label,:input,textarea", this).removeClass("error");
            }
            else if (type == 'checkbox' || type == 'radio')
                this.checked = false;
            else if (tag == 'select')
                this.selectedIndex = -1;
        });
    };

});

/*------  Additional helper functions------------/
----------------------------------------------*/

function close() {
    //alert("hello");
    self.close(); ;
}

function checkservice() {

    $(".lblservice").attr("value", $(".dservice").val());
}
function checkOwnInvoice() {
    $('.chkOwnInvoice').bind("click", function() {
        if (this.checked) {
            $(".InvoiceDetails").hide();
            if ($('.chkCreateInvoice').attr('checked')) {
                $('.chkCreateInvoice').attr('checked', '');
            }

        }

    });
}
function commercialInvoiceOption() {
    $('.chkCreateInvoice').bind("click", function() {
        if (this.checked) {
            $(".InvoiceDetails").show();
            $("input[name*='totalWtPck']").attr('disabled', 'false');
            $("input[name*='TotalQtyPck']").attr('disabled', 'false');
            if ($('.chkOwnInvoice').attr('checked')) {
                $('.chkOwnInvoice').attr('checked', '');
            }
        }
        else
            $(".InvoiceDetails").hide();
    });
    checkInvoiceOpt();
}
function checkInvoiceOpt() {
    if ($('.chkCreateInvoice').attr('checked')) {
        $(".InvoiceDetails").show();
    }
    else {
        $(".InvoiceDetails").hide();
    }

}

//Alternate Delivery Check
function DeliveryAddressCheck() {
    $('.checkdel').bind("click", function() {
        if (this.checked) {
            $('.deladdr').css('display', 'block');
        }
        else
            $('.deladdr').css('display', 'none');
    });
    if ($('.checkdel').attr('checked')) {
        $('.deladdr').css('display', 'block');
    }
    else {
        $('.deladdr').css('display', 'none');
    }
}
function checkUnits() {


    $(".wtType").bind("change", function() {

        if ($(this).val() != "lbs") {
            $('.units').attr('text', '(cm)');
        }
        else {
            $('.units').attr('text', '(inches)');
        }
    });
    if ($(".wtType").val() != "lbs") {
        $('.units').attr('value', '(cm)');
    }
    else {
        $('.units').attr('value', '(inches)');
    }


}
//refreshes totals for invoice and articles automatically
function refreshTotals() {
    $(".valuea1").each(function(i, item) {
        $(item).bind("blur", function() {
            viewTotals();
        });
    });
    $(".wtval1").each(function(i, item) {
        $(item).bind("blur", function() {
            totalArticlesWT(1);
        });
    });
    $(".wtval2").each(function(i, item) {
        $(item).bind("blur", function() {
            totalArticlesWT(2);
        });
    });
    $(".wtval3").each(function(i, item) {
        $(item).bind("blur", function() {
            totalArticlesWT(3);
        });
    });
}
function hideRateDims() {
    var option = $(".rateShipmentType").val();
    if (option == "D") {
        $(".dimensions").hide();
        $(".dims").each(function(i, item) {
            $('.dims').attr('value', '1');

        });

    }
    else {
        $(".dims").each(function(i, item) {
            var dim = $('.dims').val();
            if (dim == 1) {
                $('.dims').attr('value', '');
            }
        });
        $(".dimensions").show();
    }
}

function hideShippingDims() {

    var option = $(".stypes").val();
    if (option == "D") {
        //$(".invoice").hide();
        $(".dimensions").hide();
        $(".dims").each(function(i, item) {
            $('.dims').attr('value', '1');

        });
        $('#Articles').hide();
    }
    else {
        //$('.dims').attr('disabled', '');
        $(".dimensions").show();
        $(".invoice").show();
        $(".dims").each(function(i, item) {
            var dim = $('.dims').val();
            if (dim == 1) {
                $('.dims').attr('value', '');
            }


        });
        $('#Articles').show();
    }
}
// gets service list for shipment type from webservice
function GetServices(option) {

    // $("#ddlName").get(0).options.length = 0;
    //$("#ddlName").get(0).options[0] = new Option("Loading Services", "-1");
    //alert(option);
    if ($(".goback").val() == "Y") {
        $(".stepCheck").attr('value', "0");
    }
    if (option == "D") {

        $(".dimensions").hide();
        $(".dims").each(function(i, item) {
            $('.dims').attr('value', '1');

        });
        $('.articlesL1').hide();
        $(".DangerousGood").hide();
        if ($(".goodsDesc").val() == "") {
            $(".goodsDesc").attr('value', 'Documents');
        }

    }
    else {
        //alert("non docs");
        //$('.dims').attr('disabled', '');
        $(".DangerousGood").show();
        $(".dimensions").show();
        $(".dims").each(function(i, item) {
            var dim = $('.dims').val();
            if (dim == 1) {
                $('.dims').attr('value', '');
            }

        });
        if ($(".goodsDesc").val() == "Documents") {
            $(".goodsDesc").attr('value', '');
        }
        $('.articlesL1').show();
    } 
    /*
    $.ajax({
        type: "POST",
        url: "ShipmentEntry.aspx/GetServices",
        data: "{option:'" + option + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            $(".dservice").get(0).options.length = 0;
            $(".dservice").get(0).options[0] = new Option("Select service", "-1");

            $.each(msg.d, function(index, item) {
                $(".dservice").get(0).options[$(".dservice").get(0).options.length] = new Option(item.Display, item.Value);
            });
        },
        error: function() {
            $(".dservice").get(0).options.length = 0;
            //alert("Failed to load names");
        }
    });*/
    


}
//Function that aligns numbers @ decimals
function formatDecimals() {
    var currency = $(".rateCurrency").val();
    $('.aBDP').each(function() {
        var wholePart, fractionPart;
        wholePart = Math.floor($(this).text() - 0);
        //var dec = $(this).text().s
        fractionPart = Math.floor(($(this).text() % 1) * 10000 + 0.5) / 10000 + "";

        var value = $(this).text();
        var dec = value.indexOf(".") + 1;
        var decval = value.substr(dec, value.length - dec);
        html = '<span class="left">' + wholePart + '.' + '</span>';

        html += '<span class="right">' + decval + '</span>';
        $(this).html(html);
    });
    //alert("format");
}
function AddressCheck() {
    $('.checkrpt :checkbox').bind("click", function() {

        if (!$(this).attr('checked')) {
            $('.checkrpt :checkbox').attr('disabled', '');
        }
        else {

            $('.checkrpt :checkbox').attr('disabled', 'false');
            $(this).attr('disabled', '');
        }
    });
}
function DeclarationCheck() {
    $('.chkDeclare').bind("click", function() {

        if ($(this).attr('checked')) {
            $('.declaration').show();
        }
        else {

            $('.declaration').hide();
        }
    });
}
function viewDeclaration(option) {
    if (option = "edit") {
        $('.declaration').show();
    }
    else {
        $('.declaration').show();
    }
}
function ViewArticles(article) {

    $(".ShipDetails").css('display', 'none');
    $(".articlesL" + article + "").css('display', 'block');

    //$("#Articles").dialog('open');
    // $(".articlesL" + article + "").modal();
}
function addArticleLine(article) {

    var line = $(".ArtPck" + article + "Lines").val();

    var line2 = parseInt(line) + 1;
    // alert(line2);
    var max = 10;
    if (line <= max) {
        $(".ArtPck" + article + "Lines").attr('value', line2);
        $(".articlesL" + article + " tr:eq(" + line2 + ")").show();
    }


}
function deleteArticleLine(article) {

    var line = $(".ArtPck" + article + "Lines").val();

    var line2 = parseInt(line) - 1;
    // alert(line2);
    var max = 10;
    if (line > 1) {
        $(".ArtPck" + article + "Lines").attr('value', line2);
        $(".articlesL" + article + " tr:eq(" + line + ")").hide();

        $("#articleTblPck" + article + " tr:eq(" + line + ")").find(':input').each(function(i, item) {

            $(item).attr('value', '');

        });
    }


}
function LoadArticleLines(article) {


    var line = $(".ArtPck" + article + "Lines").val();
    //alert(line);
    var line2 = parseInt(line);

    for (j = 2; j < line2 + 1; j++) {

        //   alert(j);
        $(".articlesL" + article + " tr:eq(" + j + ")").show();
    }


}
function validatePackages() 
{
    var line = $(".pcklLine").val();
    var shiptype = $(".stypes").val();
    var errors = 0;
    for (j = 1; j <= line ; j++) {
        $("#pckL" + j + " ").find(':input').each(function(i, item) {


            var name = $(item).attr("name");
            var cname = $(item).attr("class");
            if (shiptype != "D") {
                if (name.indexOf("chk") == -1 && name.indexOf("ImageButton") == -1) {

                   // alert(name + "vaL:" + $(item).val());
                    if ($(item).val() == "") {
                        $(item).addClass("input-validation-error2")
                        valid = false;
                        errors++;
                    }
                    else {
                       // $(item).removeClass("input-validation-error")


                    }
                    // alert(total);
                }
            }
            else {
                if (name.indexOf("Weight") != -1) {


                    if ($(item).val() == "") {
                        $(item).addClass("input-validation-error2")
                        valid = false;
                        errors++;
                    }
                    else {
                        $(item).removeClass("input-validation-error")


                    }
                }
            }
        });
    }

    return errors;
}
function AddPackageLine() {


    var line = $(".pcklLine").val();
    //alert(line);
    var line2 = parseInt(line) + 1;
    //alert(line2);
    var max = 3;
    if (line <= max) {
        $(".pcklLine").attr('value', line2);
        $("#pckL" + line2 + "").show();
        $(".articlesL" + line2 + "").show();
    }


    //$("#Articles").dialog('open');
    // $(".articlesL" + article + "").modal();
}
function deletePackageLine() {

    var line = $(".pcklLine").val();
    //alert(line);
    var line2 = parseInt(line) - 1;
    if (line > 1) {
        $(".pcklLine").attr('value', line2);
        $("#pckL" + line + "").hide();

        $("#pckL" + line + " :input").each(function(i, item) {

            $(item).attr('value', '');
            //
        });
        $(".articlesL" + line + "").hide();

    }
}


function LoadPackageLine() {


    var line = $(".pcklLine").val();
    //alert(line);
    var line2 = parseInt(line);

    for (j = 2; j <= line2; j++) {


        $("#pckL" + j + "").removeClass('hiddentr');
        $(".articlesL" + j + "").show();
    }


}

function UpdateArticleDesc() {

    var line = $(".pcklLine").val();
    //alert(line);
    var line2 = parseInt(line);

    for (j = 1; j <= line2; j++) {


        var field = $("#articleTblPck" + j + "").find(':input');
        field.eq(2).attr('value', $(".PackageType" + j + "").val());
        field.eq(5).attr('value', $(".PackageType" + j + "").val());

    }

}

//Validates articles and submits the form
function validateArticles() {
    CloseArticles("1");
    CloseArticles("2");
    CloseArticles("3");
    checkTotals();
    DoPost('btnProcessShipment');
}
function CloseArticles(article) {
    var count = 0;
    var valid = true;

    $(".articlesL" + article + "").find(':input').each(function(i, item) {
        //alert(i);

        var name = $(item).attr("name");
        if (name.indexOf("Items") != -1 && $(item).val() != "") {
            //$(item).addClass("input-validation-error")


            var field = $(".articlesL" + article + "").find(':input');
            field.eq(i - 1).attr('checked', 'true');
            for (j = 1; j < 5; j++) {

                // alert(name);
                var name2 = field.eq(i + j).attr("name");
                var wt = field.eq(i + j).val();
                if (field.eq(i + j).val() == "") {
                    field.eq(i + j).addClass("input-validation-error")
                    valid = false;
                }
                else {
                    field.eq(i + j).removeClass("input-validation-error")


                }
            }
            var tariff = field.eq(i + 5);
            if (tariff.val() == "") {
             // tariff.attr('value', '000000');
                tariff.addClass("input-validation-error")
                valid = false;
            }
            else{
             tariff.removeClass("input-validation-error")
            }


        }
        else if (name.indexOf("Items") != -1 && $(item).val() != "") {
            $(item).removeClass("input-validation-error")
        }


    });

    if (!valid) {
        $(".articlesL" + article + "Valid").attr("value", '0');



        //alert("Please complete the highlited fields to continue shipping");
    }
    else {

        $(".articlesL" + article + "Valid").attr("value", '1');
        // articlesL1Valid

        //
        //  $(".ShipDetails").css('display', 'block');

        //$(".articlesL" + article + "").css('display', 'none');
        // $(".articlesL" + article + "").jqmHide();
        //$.modal.close();
    }


    //$.modal.close();


}


// gets the total weight for package line
function totalPckLineWt(line) {

    var total = 0.0;
    var goodsValue = parseFloat($(".goodsValue").val());


    //  $("#pckL" + line2+ "")
    $("#pckL" + line + " ").find(':input').each(function(i, item) {
        //alert(i);

        var name = $(item).attr("name");
        if (name.indexOf("Pieces") != -1 && $(item).val() != "") {


            var field = $("#pckL" + line + " ").find(':input');
            var name2 = field.eq(i + 1).attr("name");
            var value = field.eq(i + 1).val();
            total += parseFloat(value) * parseFloat($(item).val());
            // alert(total);
        }

    });
    //alert(total);
    return total;
}
function totalPckLineItems(line) {

    var total = 0;


    //  $("#pckL" + line2+ "")
    $("#pckL" + line + " ").find(':input').each(function(i, item) {
        //alert(i);

        var name = $(item).attr("name");
        if (name.indexOf("Pieces") != -1 && $(item).val() != "") {


            total += parseInt($(item).val());
            // alert(total);
        }

    });
    //alert(total);
    return total;
}

// gets the total invoice value for article line
function totalArticles(article) {

    var total = 0.0;
    var goodsValue = parseFloat($(".goodsValue").val());

    $(".articlesL" + article + "").find(':input').each(function(i, item) {
        //alert(i);

        var name = $(item).attr("name");
        if (name.indexOf("Items") != -1 && $(item).val() != "") {


            var field = $(".articlesL" + article + "").find(':input');
            var name2 = field.eq(i + 3).attr("name");
            var value = field.eq(i + 3).val();
            if (value != "") {
                total += parseFloat(value) * parseFloat($(item).val());
            }
            // alert(total);
        }



    });
    // alert(total);

    $(".ArtPck" + article + "Val").attr('value', total);

    return total;
}

// gets the total weight value for article line
function totalArticlesWT(article) {

    var total = 0.0;
    var goodsValue = parseFloat($(".goodsValue").val());

    $(".articlesL" + article + "").find(':input').each(function(i, item) {
        //alert(i);

        var name = $(item).attr("name");
        if (name.indexOf("Items") != -1 && $(item).val() != "") {


            var field = $(".articlesL" + article + "").find(':input');
            var name2 = field.eq(i + 2).attr("name");
            var value = field.eq(i + 2).val();

            if (value != "") {
                // alert(value);
                // alert($(item).val());
                total += parseFloat(value) * parseFloat($(item).val());
            }
            // alert(total);
        }



    });
    // alert(total);
    $(".ArtPck" + article + "WT").attr('value', total);
    return total;
}


/*---Checks the articel total invoice value*/
function checkTotals() {
    var total = 0.0;
    var subtotal = 0.0;
    var insurance = 0.0;
    var goodsValue = 0.0
    var discount = 0.0;
    var freight = 0.0;
    var otherCharge = 0.0;
    if ($(".goodsValue").val() != "") {

        goodsValue = parseFloat($(".goodsValue").val());
    }
    subtotal = totalArticles(1) + totalArticles(2) + totalArticles(3);
    discount = parseFloat($(".discount").val());
    freight = parseFloat($(".freightCharge").val());
    otherCharge = parseFloat($(".otherCharges").val());
    if (subtotal > goodsValue) {

        $('.totalsValid').attr('value', 'N');
    }
    else {

        $('.totalsValid').attr('value', 'Y');
    }
    if ($(".insuranceTotals").val() != "") {
        insurance = parseFloat($(".insuranceTotals").val());
    }

    total = subtotal + insurance + freight + otherCharge - discount;
    // $(".insuranceTotals").attr('value', insurance);
    $(".subtotal").attr('value', subtotal);
    $(".totalDeclared").attr('value', total);
    //alert(total);
}
function checkInsurance() {

    if ($(".chkInsurance").attr('checked')) {
        $('.insurance').attr('disabled', '');
    }
}
//Max height hack for ie
function fixLookup() {
    /* --IE hack for max height*/
    if ($(".maxi").height() > 400) {
        $(".maxi").height('400px');
    }
}
function updateArticleTotalWt(line) {
    //ArtPck1WT
    var total = totalArticlesWT(line);

}
function lmfCheckCity() {

    $(".txtCity").bind("blur", function() {

        var country = $(".ddlAddressCountry").val();
        var zip = $(".txtZip").val();
        var city = $(".txtCity").val();
        

        $.ajax({
            type: "POST",
            url: "WS/RECIU.asmx/checkLMFCity",

            data: "town=" + city + "&country=" + country + "&zip=" + zip + "",

            success: function(msg) {
                if (msg.toString().length > 1) {


                    if (msg.toString().indexOf("Post code is required") == -1) {
                        alert(msg);
                        //$(".txtZip").attr('disabled', 'false');
                        // $(".txtZip").css('background', '#ccc');
                    }
                    else {
                        //$(".txtZip").attr('disabled', '');
                        //$(".txtZip").css('background', '');
                    }
                }
            }

        });


    });



 }
 function setPostMask() {
     $(".ddlAddressCountry").bind("change", function() {
         //  $('.txtzip').unsetMask();
         var country = $(".ddlAddressCountry").val();
         //var zip = $(".txtZip").val()
         
         
         $.ajax({
             type: "POST",
             url: "WS/RECIU.asmx/checkPostCode",
             data: "country=" + country + "",
             success: function(msg) {
                 if (msg.toString().length > 1) {
                   //  alert(msg);
                     $('.txtAddrPost').attr('disabled', '');
                     $('.txtAddrPost').css('background', '');
                 }
                 else {
                     //alert("disable zip ");
                     $('.txtAddrPost').attr('disabled', 'false')
                     $('.txtAddrPost').css('background', '#ccc');
                 }
             }
         });
       
         
         $.ajax({
             type: "POST",
             url: "WS/RECIU.asmx/getPostMask",
             data: "country=" + country + "",
             success: function(msg) {
                 if (msg.toString().length > 1)
                 // alert(msg);
                     $.mask.masks.ssk = { mask: msg };
                $('.txtAddrPost').setMask('ssk');
             }
         });
         
     });
 }
 // Hooks up hts event to textboxes
 function htsCheck() {

     //var city = $(".txtHts").val()
     $(".helpiconTariff").bind("mouseover", function() {
         $("#HTSLookup").modal({ persist: true,maxheight:500,autoResize:true, onClose: function(dialog) {
             dialog.data.fadeOut('slow', function() {
                 dialog.container.slideUp('slow', function() {
                     dialog.overlay.fadeOut('slow', function() {
                         $(".htsTable").html("");
                         $(".htssearch").attr('value', '');
                         $.modal.close(); // must call this!
                     });
                 });
             });
         }
         });
     });
 }
 //Function for HST look up
 function htslookup() {
     //alert("hts");
     var keyword = $(".HTSKeyword").val()
     var code = $(".HTSCode").val()
     
     $.ajax({
         type: "POST",
         url: "WS/RECIU.asmx/htsResults",
        // contentType: "text/html; charset=utf-8",
         data: "code=" + code + "&keyword=" + keyword + "",
         success: function(msg) {
            // alert(msg);
             if (msg.toString().length > 1)
                 $(".htsTable").html(msg);

         }

     }); 
   
 }



//Updates Invoice Totals
function viewTotals() {

    var total = 0.0;
    var subtotal = 0.0;
    var insurance = 0.0;
    var goodsValue = 0.0
    var discount = 0.0;
    var freight = 0.0;
    var otherCharge = 0.0;
    if ($(".goodsValue").val() != "") {
        goodsValue = parseFloat($(".goodsValue").val());
    }

    if ($(".insuranceTotals").val() != "")
        insurance = parseFloat($(".insuranceTotals").val());
    discount = parseFloat($(".discount").val());
    freight = parseFloat($(".freightCharge").val());
    otherCharge = parseFloat($(".otherCharges").val());
    subtotal = totalArticles(1) + totalArticles(2) + totalArticles(3);
    total = subtotal + insurance + freight + otherCharge - discount;
    //alert(total);
    //$(".insuranceTotals").attr('value', insurance);
    $(".subtotal").attr('value', subtotal);
    $(".totalDeclared").attr('value', total);

    $("#totals").show();
    if (subtotal > goodsValue) {
        // alert("The total articles values cannot be greater than the goods value");
    }
}
function disablePckTotals() { 

}

//get the package line# totals wt and qty
function packageLineTotals(line) {
    var totalWtPck = totalPckLineWt(line);
    var totalPck = totalPckLineItems(line);
    $(".totalWtPck" + line + "").attr('value', totalWtPck);
    $(".totalQtyPck" + line + "").attr('value', totalPck);
    // alert(totalWtPck);
    //$(".totalWtPck" + line + "").attr('disabled', 'false');
    //$(".totalQtyPck" + line + "").attr('disabled', 'false');
}
function goBack() {

    $(".step1").show();
    $(".step2").hide();
    $(".goback").attr('value', "Y");
    if ($(".hasErrors").val() == "Y") {
        $(".stepCheck").attr('value', "0");
    }
}
function hideHistoryDocs() {
    $(".hstCon").each(function(i, item) {
        if ($(item).attr('doctype') == "D")
            $(item).hide();

    });
    $(".hstInvoice").each(function(i, item) {
        if ($(item).attr('hasInvoice') == "Y")
            $(item).hide();

    });
    $(".voidbtn").each(function(i, item) {
        var d = (new Date($(item).attr('shipdate')));
        var today = new Date()
        var days = days_between(d, today)
        if ($(item).attr('void') == "Y")
            $(item).hide();

        if (days > 1) {
            $(item).hide();
        }

    });
}
function viewDocument(document, key, shipdate) {


    var d = (new Date(shipdate));
    var today = new Date()
    
    var days = days_between(d, today)
    if (days < 8) {

        if (document.indexOf("Note") != -1) {
            window.open("TestXml.aspx?Document=CONNOTE&Key=" + key + "");

        }
        else if (document.indexOf("Invoice") != -1) {
            window.open("TestXml.aspx?Document=INVOICE&Key=" + key + "");
        }
        else if (document.indexOf("Manifest") != -1) {
            window.open("TestXml.aspx?Document=MANIFEST&Key=" + key + "");
        }
        else if (document.indexOf("Labels") != -1) {
            window.open("TestXml.aspx?Document=LABEL&Key=" + key + "");
        }
    }
    else {
        alert("This document is no longer available");
    }
}
/* Gets days difference between dates*/
function days_between(date1, date2) {

    // The number of milliseconds in one day
    var ONE_DAY = 1000 * 60 * 60 * 24

    // Convert both dates to milliseconds
    var date1_ms = date1.getTime()
    var date2_ms = date2.getTime()
 

    // Calculate the difference in milliseconds
    var difference_ms = Math.abs(date1_ms - date2_ms)

    // Convert back to days and return
    return Math.round(difference_ms / ONE_DAY)

}
function checkClosedTime() {
    dtt = new Date();
    var valid = 1;
    var close = $(".closeTime").val();
    var pkup = $(".collTimeFrom").val();
    var dtstr = dtt.toLocaleDateString();
    var dtclose = new Date(dtstr +" "+ close);
    var dtPickup = new Date(dtstr+" "+pkup);
    var ONE_HOUR = 1000 * 60 * 60;

    // Calculate the difference in milliseconds
    var difference_ms =(dtclose - dtPickup)

    // Convert back to days and return
    var diff = Math.round(difference_ms / ONE_HOUR);

    if (diff < 0) {
        alert("the closed time has to be later than the pick up time, please select another closed time");
        valid = 0;
    }
    else if (diff == 0) {
      alert("the closed time has to be later than the pick up time, please select another closed time");
    
    valid = 0;
    }
    return valid;
}
function ClosedTime() {
    dtt = new Date();
    var valid = 1;
    var msg = "";
    var close = $(".closeTime").val();
    var pkup = $(".collTimeFrom").val();
    var dtstr = dtt.toLocaleDateString();
    var dtclose = new Date(dtstr + " " + close);
    var dtPickup = new Date(dtstr + " " + pkup);
    var ONE_HOUR = 1000 * 60 * 60;

    // Calculate the difference in milliseconds
    var difference_ms = (dtclose - dtPickup)

    // Convert back to days and return
    var diff = Math.round(difference_ms / ONE_HOUR);
    if (close != "") {
        if (diff < 0) {
            msg = "The Close time has to be later than the pick up time, please select another closed time";
            valid = 0;
        }
        else if (diff == 0) {
            msg = "The Close time has to be later than the pick up time, please select another closed time";

            valid = 0;
        }
    }
    return msg;
}
function roundUpCollectionTime(serviceCollectionCutOffTime) {

    var timeString = null;

    if (serviceCollectionCutOffTime != null) {
        var collectionCutOffTime = serviceCollectionCutOffTime;

        timeString = collectionCutOffTime.toString();
        var mins = (+timeString.substring(timeString.length - 2));
        var hours = (+timeString.substring(0, timeString.length - 2));

        if (mins > 0 && mins < 30) {
            mins = "00";
        } else if (mins > 30 && mins < 60) {
            mins = "30";
        } else {
            if (mins < 10) {
                mins = "0" + mins.toString();
            } else {
                mins = mins.toString();
            }
        }

        timeString = hours.toString() + mins;
    }

    return timeString;
}


/* Jquery function for address import in address book page
----------------------------------------------*/
function AddrressFileUpload() {

    new Ajax_upload('.A1', {
        action: 'FileHandler.ashx',
        onSubmit: function(file, ext) {
            if (!(ext && /^(csv)$/.test(ext))) {
                // extension is not allowed
                alert('Error: invalid file extension');
                // cancel upload
                return false;
            }

            this.disable();
            $('#loading').css('visibility', 'visible');
        },
        onComplete: function(file, response) {
            $('#loading').css('visibility', 'hidden');
            $('#result').append(response);

            this.enable();

        },
        data: {
            'customerID': $(".AddressBookCustomer").val()
        }
    });

}

function lmfValidation() {

    var country = $(".ddlAddressCountry").val();
    var zip = $(".txtZip").val()
    var city = $(".txtCity").val()
    var result = "AA";
    $.ajax({
        type: "POST",
        url: "WS/RECIU.asmx/checkLMFCity",
        async: false,
        data: "town=" + city + "&country=" + country + "&zip=" + zip + "",
        success: function(msg) {
           // alert(msg.toString().length);
            if (msg.toString().length > 0) {
                alert(msg);
                $(".lmfValidation").attr('value', "");
                //alert($(".lmfValidation").val())
                result = "NN";

            }
            else {
                //alert("Good");
                valid = "Y";
                $(".lmfValidation").attr('value', "Y");
                result = "YYY";
            }
        }

    });
    return result;
}

function Clear_Form() {
    $('#aspnetForm').clearForm();

}
/*  Does JS postback instead of page auto postback
------------------------------------------*/
function DoPost(control) {
    // alert(control);
    var conCount = $(".stepCheck").val();
    count = parseInt(conCount) + 1;
    var totalPck1 = 0;
    var totalWtPck1 = 0;
    var packcheck=0;
    $(".stepCheck").attr('value', count);

    $(".goback").attr('value', "N");


    var valid = "N";
    var isValid = $("#aspnetForm").valid();
    var close = "";
    var error = "Please correct to continue ";
    if (control == "btnContinue") {


        UpdateArticleDesc();
        packageLineTotals(1);
        packageLineTotals(2);
        packageLineTotals(3);
        packcheck = validatePackages();
        //alert(packcheck);
        valid = lmfValidation();
        close = ClosedTime();
        // $(".stepCheck").attr('value', '1');
        // alert($(".lmfValidation").val())

        if (isValid && $(".lmfValidation").val() == "Y" && packcheck==0 && close.length==0) {
            __doPostBack(control, '');
           // $(".step2").show();
            //$(".step1").hide();
        }
        else {
            if (!isValid || packcheck>0) {
                error = " \n Please fillout the highlited required fields ";
            }
            if (close.length > 0) {
                error += "\n " + close;
            }
            alert(error);
            $(".stepCheck").attr('value', '0');
        }
    }
    else {
        __doPostBack(control, '');
    }

    
 
    
    /*
    if ($(".lmfValidation").val() == "Y") {
        //alert("posting ");
        __doPostBack(control, '');
    }
    else {
        $(".stepCheck").attr('value', '0');
    }
   
    */
    
    
    
}
                
