
<style type="text/css">
    #InventoryInvoiceTable thead tr th {
/*        color:#FFF;*/
        border-bottom: 1px solid rgba(0,0,0,0.1);
    }
    #InventoryInvoiceTable tbody tr td input{
        width:100%;
        margin:0;
        border: 1px solid rgba(0,0,0,0.02);
        background-color:#e5e5e5;
    }
    #InventoryInvoiceTable tbody tr td {
        border:0;
        padding:3px 1px;
        position:relative;
    }
    #InventoryInvoiceTable tbody tr:first-child td{
        padding-top:10px;
    }
    #InvoiceDiscountInput{
        display: inline-block;
        width: 40px;
        padding: 3px;
        line-height: 20px;
        background: rgb(250, 250, 250);
        min-height: 12px;
        text-align: center;
        height: 25px;
        font-size: 12px;
        top: -2px;
        position: relative;
        margin: 0 3px;
    }
    #InventoryInvoiceTable .Hint{
        position: absolute;
        font-size: 10px;
        font-weight: bold;
        height: 20px;
        line-height: 20px;
        bottom: 2px;
        right: 4px;
        color: rgb(153, 153, 153);   
    }
    #InventoryInvoiceTable .TotalTD{
        width: auto;
        display: inline-block;
        text-align: center;
        font-size: 20px;
        font-weight: bold;
    }
    #InventoryInvoiceTable .NewDisc{
        width:70px;
    }
    #InventoryInvoiceTable input.wrong{
        border: 1px solid rgba(255, 0, 0, 0.2);
        background: rgba(255, 0, 0, 0.05);
        /*        width:100%;*/
    }
    .DropDownForForms > .dropdown-menu{
        width:100%;
        height:200px;
        max-height:200px;
        overflow-y:scroll;
    }
    .DropDownForForms > .dropdown-menu{
        height:auto;
        cursor: pointer;
        overflow-y:auto;
    }
    .DropDownForForms > button{
        position:relative;
        z-index:999;
    }
    .DropDownForForms > button > input{
        position: absolute;
        left:5;
        top: 0;
        width:90%;
        cursor: pointer;
        -webkit-user-select:none;
        -moz-user-select:none;
        user-select:none;
        padding: 0;
        border: 0;
        background: transparent;
    }
    .Disabled{
        cursor:default;
        opacity:0.5;
    }
    #AdvanceValue{
        width: 102px;
        display: inline-block;
    }
    .datepicker thead tr .dow {
        color:#4c0870!important;
    }
    .datepicker table tr td.day:hover {
        background: #4c0870!important;
        color:#fff;
    }
    .datepicker table tr td.active {
        background-color: #4c0870!important;
color:#ed9421 !important;    }
    .datepicker thead tr .datepicker-switch {
        color: #4c0870 !important;
        font-size: 13px;
    }
    .datepicker table tr td span.active {
        background-color: #4c0870!important;
color:#ed9421 !important;    }
    .datepicker table tr td span:hover {
        background-color: #4c0870!important;
color:#ed9421 !important;        color:#fff;
    }
    datepicker thead tr .next:before, .datepicker thead tr .prev:before {
        color: #4c0870!important;
        font-family: 'FontAwesome';
        font-size: 10px;
    }
    .datepicker thead tr .next:before, .datepicker thead tr .prev:before {
        color: #4c0870!important;
        font-family: 'FontAwesome';
        font-size: 10px;
    }
    .select2-container > .select2-choice{
        background-color: #e5e5e5;
        width: 150px;
    }
    #newInvoicePaymentSetup .nav.nav-tabs a {
        padding: 7px 14px;
        font-size: 11px;
    }
    .InputSpinner{
        width: 60px;
    }
    .InputSpinner > .form-control{
        border-color: rgb(221, 221, 221);
        height:36px;
        margin:0;
        padding:0;
        text-align: center;
        /*
        -webkit-border-radius: 3px 0px 0px 3px !important;
        -moz-border-radius: 3px 0px 0px 3px !important;
        border-radius: 3px 0px 0px 3px !important;
        */
    }
    .InputSpinner > .input-group-btn-vertical {
        position: relative;
        white-space: nowrap;
        width: 25px;
        vertical-align: middle;
        display: table-cell;
    }
    .InputSpinner > .input-group-btn-vertical > .btn {
        height:19px;
        display: block;
        float: none;
        width: 100%;
        max-width: 100%;
        padding: 8px;
        margin-left: -1px;
        position: relative;
        border-radius: 0;
    }
    .InputSpinner > .input-group-btn-vertical > .btn:first-child {
        border-top-right-radius: 4px;
    }
    .InputSpinner > .input-group-btn-vertical > .btn:last-child {
        margin-top: -2px;
        border-bottom-right-radius: 4px;
    }
    .InputSpinner > .input-group-btn-vertical i{
        position: absolute;
        top: 50%;
        left: 6px;
        margin-top:-9px;
        font-size: 18px;
    }
    .InputSpinner .input-group-btn-vertical .btn.btn-default{
        font-size: 10px;
        padding: 6px 10px;
    }
    #newInvoicePaymentSetup .table tbody > tr:last-child > td{
        border:0;
    }

    .select2-container > .select2-choice {

        width: 100%;

    }
          #InvoiceVAT{
        display: inline-block;
        width: 92px;
        padding: 3px;
        line-height: 20px;
        background: rgb(250, 250, 250);
        min-height: 12px;
        text-align: center;
        height: 25px;
        font-size: 12px;
        top: -2px;
        position: relative;
        margin: 0 3px;
         margin-left: 23px;

    }
    .Account_Code{
        margin-left:10px;
    }

</style>

<script src="<?php echo THEME_PATH; ?>plugins/jquery-validation/js/jquery.validate.min.js"></script>
<div class="modal fade stick-up" id="SalesInvoiceModal" tabindex="-1" role="dialog" aria-hidden="true" style="    margin-left: 55px;">
    <div id="InvoiceDisabler" style="position:absolute;left:0;right:0;top:0px;height:100%;background:rgba(255,255,255,0.9);z-index:2099;display:none"><img class="image-responsive-height demo-mw-50" src="img/demo/progress.svg" alt="Progress" style="position: absolute;left: 50%;top: 50%;margin: -25px 0 0 -25px;" /></div>
    <form method="POST" action="" onsubmit="return false" id="NewInvoiceForm">
        <div class="container-fluid container-fixed-lg">
            <div class="panel panel-default">
                <div class="modal-header clearfix text-left">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="pg-close fs-14"></i></button>

                </div>
                <div class="panel-body">
                    <div id="NewInvoiceSuccess" class="hidden"></div>
                    <div class="invoice padding-10 sm-padding-10">
                        <div class="container-sm-height">
                            <div class="row-sm-height">
                                <div class="col-md-9 col-sm-height sm-no-padding">
                                    <h2 class="font-montserrat all-caps hint-text"> <?php print CommonLanguage::getMessage('sales_invoice');?></h2>
                                    <div>
                                        <div class="input-group  col-md-4 center-margin" style="float: left;">
                                            <span class="input-group-addon  primary">
                                                <i class="fa fa-search"></i>
                                            </span>
                                            <input type="text" id="search_customer" class="form-control" placeholder="<?php print CommonLanguage::getMessage('customer_name');?>" >
                                        </div>
                                        <div class="clearfix"></div>
                                    </div>
                                    <br>
                                    <div id="CustomerInfo">
                                        <input type="hidden" name="Customer_ID"  id="Customer_ID" />
                                        <div id="CustomerInfoContent">
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-4 col-sm-height col-bottom sm-no-padding sm-p-b-20" style="vertical-align: top;">
                                    <div class="sm-m-t-20">
                                        <h4><?php print CommonLanguage::getMessage('invoice');?> # <?php if(empty($InvoiceNumber)){echo 1;}else{echo $InvoiceNumber+1;} ?></h4>
                                    </div>
                                    <div  class="form-group form-group-default input-group">
                                        <label><?php print CommonLanguage::getMessage('Date');?></label>
                                        <input type="hidden" id="Load_id" value="<?php echo $Load_ID?>">
                                        <input id="NewSalesInvoiceDate" name="NewSalesInvoiceDate" class="form-control" value="<?php echo ($today); ?>" />
                                        <span class="input-group-addon primary"><i class="fa fa-calendar"></i></span>
                                    </div>
                                    <div  class="form-group form-group-default input-group  ">
                                        <label><?php print CommonLanguage::getMessage('due_date');?></label>
                                        <input id="NewSalesInvoiceDueDate" name="NewSalesInvoiceDueDate" class="form-control">
                                        <span class="input-group-addon primary"><i class="fa fa-calendar-o"></i></span>
                                    </div>



                                    <div Default-Currency="<?php echo $DefaultCurrencyID; ?>" class="input-group-btn DropDownForForms Closable" id="NewCurrencyDropDown">
                                        <button type="button" class="btn btn-primary btn-block dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                                            <span><strong><?php print CommonLanguage::getMessage('Select_Currency');?></strong></span>
                                            <input type="hidden" value="<?php echo $DefaultCurrencyID; ?>" class="form-control ignore" onkeyup="return false" onkeydown="return false" required/>
                                        </button>
                                        <ul class="dropdown-menu">
                                            <?php echo($currencyList); ?>
                                            <li class="divider"></li>
                                            <li><a class="LoadMore"><?php print CommonLanguage::getMessage('More');?>..</a></li>
                                        </ul>
                                    </div>
                                    <br>
                                </div>
                            </div>
                        </div>
                        <div>
                            <div class="clearfix"></div>
                        </div>
                        <div class="table-responsive">
                            <table class="table m-t-50" id='InventoryInvoiceTable'>
                                <thead>
                                    <tr>

                                        <th class="text-center"><?php print CommonLanguage::getMessage('Code');?></th>
                                        <th class="text-center"><?php print CommonLanguage::getMessage('product_name');?></th>
                                        <th class="text-center"><?php print CommonLanguage::getMessage('Quantity');?></th>
                                        <th class="text-center"><?php print CommonLanguage::getMessage('unit_price');?></th>
                                        <th class="text-center" ><?php print CommonLanguage::getMessage('discount_percent');?></th>
                                        <th class="text-center"><?php print CommonLanguage::getMessage('total');?></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td><input type="text" class="form-control AutoComplete NewSalesInvoiceCODE"></td>
                                        <td><input type="text" class="form-control AutoComplete NewProductName"></td>
                                        <td><span class="Hint"></span><input type="text" class="form-control NewInvoiceQuantity isnumber"></td>
                                        <td><span class="Hint"></span><input type="text" class="form-control NewUnitPrice isnumber"  disabled style="color: #000;"></td>  
                                        <td><input type="text" class="form-control NewDisc" value=""></td>
                                        <td class="TotalTD"><span class="CurrencyIndicator"></span>&nbsp;<span class="Total">0</span></td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <br>
                        <div class="container-sm-height" >
                            <div class="row row-sm-height b-a b-grey">
                                <div class="col-sm-6 col-sm-height col-middle  clearfix" style="border-left: 1px solid #eee;padding-left: 6px;border-right: 1px solid #eee;padding-right:0">
                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold"><?php print CommonLanguage::getMessage('payment');?></h5>
                                    <div id="newInvoicePaymentSetup" class="no-print">
                                        <div class="Body">
                                            <div class="">
                                                <ul class="nav nav-tabs">
                                                    <li class="active"><a data-toggle="tab" href="#NewSetPaidFormTab_1"><i class="fa fa-money"></i>&nbsp;&nbsp;<?php print CommonLanguage::getMessage('cash');?></a></li>
                                                    <li><a data-toggle="tab" href="#NewSetPaidFormTab_2"><i class="fa fa-file-text-o"></i>&nbsp;&nbsp;<?php print CommonLanguage::getMessage('check');?></a></li>
                                                    <li><a data-toggle="tab" href="#NewSetPaidFormTab_3"><i class="fa fa-cc-visa"></i>&nbsp;&nbsp;<?php print CommonLanguage::getMessage('credit_card');?></a></li>
                                                </ul>
                                                <div class="tab-content" style="padding:0;overflow:visible">
                                                    <div id="NewSetPaidFormTab_1" class="tab-pane fade in active">
                                                        <table class="table" cellpadding="0" cellspacing="0">
                                                            <tbody>
                                                                <tr>
                                                                    <td style="width: 65%;"><span class="SpanInTableInPayment"><?php print CommonLanguage::getMessage('amount');?></span></td>
                                                                    <td>
                                                                        <div class="input-group InputSpinner" style="width:120px">
                                                                            <input type="text" id="newCashAmount" class="form-control" value="0" onblur="InputMustBeAtleastN(this,0);" />
                                                                            <div class="input-group-btn-vertical">
                                                                                <button class="btn btn-default more"><i class="fa fa-caret-up"></i></button>
                                                                                <button class="btn btn-default"><i class="fa fa-caret-down"></i></button>
                                                                            </div>
                                                                        </div>
                                                                    </td>
                                                                </tr>
                                                                <tr>
                                                                    <td><span class="SpanInTableInPayment"><?php print CommonLanguage::getMessage('Type');?></span></td>
                                                                    <td style="text-align:center">
                                                                        <div class="input-group-btn DropDownForForms Closable">
                                                                            <button type="button" class="btn btn-default btn-block dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                                                                                <span><?php print CommonLanguage::getMessage('select');?></span>
                                                                                <input type="hidden" value="" class="form-control" onkeyup="return false" onkeydown="return false"/>
                                                                            </button>
                                                                            <ul class="dropdown-menu">
                                                                                <?php for($x=0;$x<count($Cashes);$x++){ ?>
                                                                                <li value="<?php echo $Cashes[$x]["Payment_Type_ID"]; ?>"><a><?php echo $Cashes[$x]["Payment_Type_Name"]; ?></a></li>
                                                                                <?php } ?>
                                                                            </ul>
                                                                        </div>
                                                                    </td>
                                                                </tr>
                                                            </tbody>
                                                        </table>
                                                    </div>
                                                    <div id="NewSetPaidFormTab_2" class="tab-pane fade in">
                                                        <table class="table" cellpadding="0" cellspacing="0">
                                                            <tbody>
                                                                <tr>
                                                                    <td style="width: 65%;"><span class="SpanInTableInPayment"><?php print CommonLanguage::getMessage('amount');?></span></td>
                                                                    <td>
                                                                        <div class="input-group InputSpinner" style="width:120px">
                                                                            <input type="text" id="newCheckAmount" class="form-control" value="0" onblur="InputMustBeAtleastN(this,0);" />
                                                                            <div class="input-group-btn-vertical">
                                                                                <button class="btn btn-default more"><i class="fa fa-caret-up"></i></button>
                                                                                <button class="btn btn-default"><i class="fa fa-caret-down"></i></button>
                                                                            </div>
                                                                        </div>
                                                                    </td>
                                                                </tr>
                                                                <tr>
                                                                    <td><span class="SpanInTableInPayment"><?php print CommonLanguage::getMessage('Type');?></span></td>
                                                                    <td style="text-align:center">
                                                                        <div class="input-group-btn DropDownForForms Closable">
                                                                            <button type="button" class="btn btn-default btn-block dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                                                                                <span><?php print CommonLanguage::getMessage('select');?></span>
                                                                                <input type="hidden" value="" class="form-control" onkeyup="return false" onkeydown="return false"/>
                                                                            </button>
                                                                            <ul class="dropdown-menu">
                                                                                <?php for($x=0;$x<count($Checks);$x++){ ?>
                                                                                <li value="<?php echo $Checks[$x]["Payment_Type_ID"]; ?>"><a><?php echo $Checks[$x]["Payment_Type_Name"]; ?></a></li>
                                                                                <?php } ?>
                                                                            </ul>
                                                                        </div>
                                                                    </td>
                                                                </tr>
                                                                <tr>
                                                                    <td><span class="SpanInTableInPayment"><?php print CommonLanguage::getMessage('check');?> #</span></td>
                                                                    <td style="text-align:center"><input type="text" class="form-control CheckNumValue" /></td>
                                                                </tr>
                                                            </tbody>
                                                        </table>
                                                    </div>
                                                    <div id="NewSetPaidFormTab_3" class="tab-pane fade in">
                                                        <table class="table" cellpadding="0" cellspacing="0">
                                                            <tbody>
                                                                <tr>
                                                                    <td style="width: 65%;"><span class="SpanInTableInPayment"><?php print CommonLanguage::getMessage('amount');?></span></td>
                                                                    <td>
                                                                        <div class="input-group InputSpinner" style="width:120px">
                                                                            <input type="text" id="newCreditAmount" class="form-control" value="0" onblur="InputMustBeAtleastN(this,0);" />
                                                                            <div class="input-group-btn-vertical">
                                                                                <button class="btn btn-default more"><i class="fa fa-caret-up"></i></button>
                                                                                <button class="btn btn-default"><i class="fa fa-caret-down"></i></button>
                                                                            </div>
                                                                        </div>
                                                                    </td>
                                                                </tr>
                                                                <tr>
                                                                    <td><span class="SpanInTableInPayment"><?php print CommonLanguage::getMessage('Type');?></span></td>
                                                                    <td style="text-align:center">
                                                                        <div class="input-group-btn DropDownForForms Closable">
                                                                            <button type="button" class="btn btn-default btn-block dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                                                                                <span><?php print CommonLanguage::getMessage('select');?></span>
                                                                                <input type="hidden" value="" class="form-control" onkeyup="return false" onkeydown="return false"/>
                                                                            </button>
                                                                            <ul class="dropdown-menu">
                                                                                <?php for($x=0;$x<count($CreditCards);$x++){ ?>
                                                                                <li value="<?php echo $CreditCards[$x]["Payment_Type_ID"]; ?>"><a><?php echo $CreditCards[$x]["Payment_Type_Name"]; ?></a></li>
                                                                                <?php } ?>
                                                                            </ul>
                                                                        </div>
                                                                    </td>
                                                                </tr>
                                                                <tr>
                                                                    <td><span class="SpanInTableInPayment"><?php print CommonLanguage::getMessage('approval_code');?></span></td>
                                                                    <td style="text-align:center"><input type="text" class="form-control CardApproval" /></td>
                                                                </tr>
                                                            </tbody>
                                                        </table>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-sm-3 col-sm-height col-middle clearfix sm-p-b-15" style="text-align:center">
                                    <div style="text-align: left;display: inline-block;">
                                         <h5 class="font-montserrat all-caps small no-margin hint-text bold" ><?php print CommonLanguage::getMessage('vat_ten');?><span class="form-control ignore" id="InvoiceVAT"></span> </h5>
                                        <h5 class="font-montserrat all-caps small no-margin hint-text bold" ><?php print CommonLanguage::getMessage('invoice_discount');?> <input type="text" class="form-control ignore" id="InvoiceDiscountInput" /> %</h5>
                                        <h3 class="no-margin"><span class="CurrencyIndicator"></span>&nbsp;<span id="InvoiceTotalAfterDiscount">0</span></h3>
                                        <h5 class="font-montserrat all-caps small no-margin hint-text bold" ><?php print CommonLanguage::getMessage('item_discount');?></h5>
                                        <h3 class="no-margin"><span class="CurrencyIndicator"></span>&nbsp;<span id="DiscountVal">0</span></h3>
                                    </div>
                                </div>
                                <div class="col-sm-3 text-right bg-menu col-sm-height padding-15" style="text-align:left !important">
                                    <div style="text-align: left;display: inline-block;">
                                        <h5 class="font-montserrat all-caps small no-margin hint-text text-white bold"><?php print CommonLanguage::getMessage('total');?></h5>
                                        <h1 class="no-margin text-white Total"><span class="CurrencyIndicator"></span>&nbsp;<span id="NewPurchaseInvoiceTotalDetails">0</span></h1>
                                        <h5 class="font-montserrat all-caps small no-margin hint-text text-white bold"><?php print CommonLanguage::getMessage('total_paid');?></h5>
                                        <h1 class="no-margin text-white Total"><span class="CurrencyIndicator"></span>&nbsp;<span id="NewPurchaseInvoiceTotalPaid">0</span></h1>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="container-sm-height" >
                            <button class=" btn btn-primary btn-cons m-b-10 pull-right" id="InvoiceSubmitButton" style="padding-top: 10px;top: 20px;min-width:253px;" type="button"><i class="pg-form"></i> <span class="bold">Submit</span></button>
                        </div>
                        <hr>
                        <div>
                            <span class="m-l-20 text-black sm-pull-right"><?php echo $org_details[0]['Organization_Legal_Name']; ?></span>
                            <span class="m-l-20 text-black sm-pull-right"><?php echo $org_details[0]['Organization_Province']; ?> <?php echo $org_details[0]['Organization_Country']; ?> - <?php echo $org_details[0]['Organization_City']; ?></span>
                            <span class="m-l-20 text-black sm-pull-right">CR: <?php echo $org_details[0]['Organization_Commercial_Registry']; ?></span>
                            <span class="m-l-20 text-black sm-pull-right"><?php print CommonLanguage::getMessage('Phone');?>: <?php echo $org_details[0]['Organization_Phone']; ?></span>
                            <span class="m-l-40 text-black sm-pull-right"><?php print CommonLanguage::getMessage('Email');?>: <?php echo $org_details[0]['Organization_Email']; ?></span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
     
    </form>
       </div>
<script>
    // var IsSalesMode = <?php// echo $IsSales ? "true" : "false"; ?>;
    var Required_Fields = <?php echo json_encode(CommonLanguage::getMessage('Required_Fields'));?>,
        CompanyLang = <?php echo json_encode(CommonLanguage::getMessage('company'));?>,
        EmailLang = <?php echo json_encode(CommonLanguage::getMessage('Email'));?>,
        PhoneLang = <?php echo json_encode(CommonLanguage::getMessage('Phone'));?>,
        AddressLang = <?php echo json_encode(CommonLanguage::getMessage('address'));?>,
        CountryLang = <?php echo json_encode(CommonLanguage::getMessage('country'));?>,
        FinancialNbLang = <?php echo json_encode(CommonLanguage::getMessage('financial_nb'));?>,
        roadCustomerLang = <?php echo json_encode(CommonLanguage::getMessage('road_customer'));?>,
       Failed_Submit = <?php echo json_encode(CommonLanguage::getMessage('Failed_Submit'));?>,
       Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully'));?>;
    var TotalInvoice    = 0,
        TotalDiscount   = 0,
        TotalInvoiceWithoutDiscount = 0,Load_id= $("#Load_id").val();
    var Zone_ID = $("#Zone_ID").val();
    var QtyInTruck = 0,newQty = 0;

    $(function(){
        $("#newInvoicePaymentSetup .InputSpinner .btn").on('click',function(e){
            e.preventDefault();
            var Input = $("input",$(this).parent().parent()),V=parseInt(Input.val())
            Input.val($(this).hasClass("more") ? V + 1 : V == 0 ? 0 : V - 1)
            UpdateInvoiceTotalPaid()
        })
        $("#newInvoicePaymentSetup").find("input.form-control").on("keyup",function(){
            UpdateInvoiceTotalPaid()
        })

        $("body").addClass("NoSearch")
        $("body .search-link[data-toggle='search']").html("<i class='pg-search'></i>Click here to <span class='bold'>search</span>")
        $("#search_customer").autocomplete({
            source: 'xhr/ajaxCustomer',
            minLength: 2,
            select: function(event, ui){
                var Content = "";
                Content += "<strong><span class='Name'>"+ui.item.Customer_Name+"</span></strong>";
                Content += "<div><strong>"+CompanyLang+": </strong><span class='Company'>"+ui.item.Customer_Company+"</span></div>";
                Content += "<div><strong>"+EmailLang+": </strong><span class='Address'>"+ui.item.Customer_Email+"</span></div>";
                Content += "<div><strong>"+PhoneLang+": </strong><span class='Phone'>"+ui.item.Customer_Phone+"</span></div>";
                Content += "<div><strong>"+AddressLang+": </strong><span class='Discount'>"+ui.item.Customer_Address+"</span></div>";
                Content += "<div><strong>"+CountryLang+": </strong>"+ui.item.Customer_Country+"</div>";
                Content += "<div><strong>"+FinancialNbLang+": </strong>"+ui.item.Account_code+"</div>";
                Content += "<div id = 'ClassID' style='display:none;'>"+ui.item.Class_ID+"</div>";
                $("#CustomerInfoContent").html(Content)
                $("#Customer_ID-error").remove()
                $("#Customer_ID").removeClass("error").val(ui.item.Customer_ID);
            }
        })     
            .autocomplete("instance")._renderItem = function(ul,item){
            return $("<li>").html("<table cellspacing='0' cellpadding='0'><tr><td class='Column1'><i class='fa fa-file-o'></i></td><td><strong>"+item.Customer_Name + "</strong></td></tr></table>").appendTo(ul)
        }
        $("#search_customer").autocomplete("instance")._resizeMenu = function( ul, items ) {
            this.menu.element.outerWidth($("#search_customer").width() + parseFloat($("#search_customer").css("padding-left")) + parseFloat($("#search_customer").css("padding-right")) + 2);
        }
        EnableAutoComplete($("#InventoryInvoiceTable .AutoComplete.NewSalesInvoiceCODE"));
        EnableAutoComplete($("#InventoryInvoiceTable .AutoComplete.NewProductName"));
        $("#NewSalesInvoiceDueDate,#NewSalesInvoiceDate").datepicker({autoclose:true}).on("changeDate",function(e){
            $(this).keyup();
        })
        $("#InventoryInvoiceTable").delegate(".NewInvoiceQuantity,.NewUnitPrice,.NewDisc","blur keyup",function(e){
            var me = $(this),TR = me.parents("tr");
            setTimeout("UpdateTable()",100);
            if(e.which == 13){
                if(me.hasClass("NewInvoiceQuantity")){
                    TR.find(".NewUnitPrice").focus()
                }else if(me.hasClass("NewUnitPrice")){
                    TR.find(".NewDisc").focus()
                }else{
                    TR.next().find(".NewSalesInvoiceCODE").focus()
                }
            }
            if(TR.index() < $("#InventoryInvoiceTable tbody").children().length-1){
                if($.trim(me.val()).match(/^\s*?([\d]+(\.\d+)?|\.\d{1,2})\s*$/) == null){
                    me.addClass("wrong")
                }else{
                    me.removeClass("wrong")
                }
            }
        });
        $("#InventoryInvoiceTable").on("keyup",".NewInvoiceQuantity",function(e){

            var me = $(this),TR = me.parents("tr");
            newQty = parseInt($(this).val());
            if(newQty > QtyInTruck){
                console.log(newQty)
                console.log(QtyInTruck )
                $("#InvoiceSubmitButton").attr("disabled", true)
            }else

                $("#InvoiceSubmitButton").attr("disabled", false)


                })

        $("#InvoiceDiscountInput").on("blur keyup",function(){
            setTimeout("UpdateTable()",100)
        })
        $("#InventoryInvoiceTable tbody").delegate("> tr input","keydown",function(e){
            var me = $(this)
            if(e.which == 8){
                if(me.val() == "" && !me.hasClass("NewSalesInvoiceCODE")){
                    me.parents("td").prev().find("input").focus()
                }else if(me.val() == "" && me.hasClass("NewSalesInvoiceCODE")){
                    if(me.parents("tr").prev()){
                        me.parents("tr").prev().find(".NewDisc").focus()
                    }
                }
            }
        })
        $("#InventoryInvoiceTable tbody").delegate("> tr input","keyup",function(e){
            var me=$(this),Parent = me.parents("tbody"),IsLastOneEmpty = true;
            $("tr",Parent).each(function(e){
                if($("tr",Parent).length > 1){
                    var IsEmpty = true;
                    $(this).find("input").each(function(){
                        if($(this).val() != "")IsEmpty = false;
                    })
                    if(IsEmpty == true){
                        if($(this).index() <= $("#InventoryInvoiceTable tbody tr").length-2){
                            me.parents("tr").prev().find(".NewDisc").focus()
                            $(this).remove();
                        }
                    }
                }
            })
            $("tr:last-child input",Parent).each(function(e){
                if($(this).val() != "")IsLastOneEmpty = false;
            })
            if(IsLastOneEmpty == false){
                var ClonedRow = $("tr:first-child",Parent).clone()
                ClonedRow.find("input").val("")
                Parent.append(ClonedRow);
                EnableAutoComplete($(".AutoComplete.NewSalesInvoiceCODE",ClonedRow).removeClass("AutoAdded"));
                EnableAutoComplete($(".AutoComplete.NewProductName",ClonedRow).removeClass("AutoAdded"));
                $(".Hint,.Total",ClonedRow).html("")
                $("input",ClonedRow).removeClass("wrong")
                $(".select2-container",ClonedRow).empty().remove()

                UpdateTable()
            }
        })
        $("#NewCurrencyDropDown li").click(function(){
            $(".CurrencyIndicator").html($(this).attr("MySymbol"))
            setTimeout("UpdateSubmitButtonStatus()",100)
        })
        var Def = $("#NewCurrencyDropDown li").filter(function(){return $(this).attr("value") == $("#NewCurrencyDropDown input").val()})
        if(Def.length > 0){
            $(".CurrencyIndicator").html(Def.attr("MySymbol"))
            $("> button > span",$("#NewCurrencyDropDown")).html(Def.text())
        }
        $("#NewInvoiceForm").validate({
            ignore: ".ignore",
            rules: {
                NewSalesInvoiceDate:{required: true,date: true}

            }
        })
        $("#InvoiceSubmitButton").on("click",ApplyPostMethod);
        UpdateSubmitButtonStatus()
    })
    function UpdateTable(){
        TotalInvoice = TotalDiscount = TotalInvoiceWithoutDiscount = 0
        $("#InventoryInvoiceTable tr").each(function(){
            UpdateTotalForRow($(this))
        })
        var InvoiceDiscountInput = parseFloat($("#InvoiceDiscountInput").val()) || 0;
        var TotalInvoiceDisounted = TotalInvoice - (TotalInvoice * (InvoiceDiscountInput/100))
        $("#NewPurchaseInvoiceTotalDetails").attr({"MyValueNotDiscounted":TotalInvoice,"MyValueDiscounted":TotalInvoiceDisounted}).text(AddCommas(TotalInvoiceDisounted.toFixed(3)))
        var SubTotalVal = TotalInvoiceWithoutDiscount * (1 - TotalDiscount/100);
        $("#DiscountVal").html(AddCommas((TotalInvoiceWithoutDiscount - TotalInvoice).toFixed(3)))
        $("#InvoiceTotalAfterDiscount").text(AddCommas((TotalInvoiceWithoutDiscount * (InvoiceDiscountInput/100)).toFixed(3)))
        setTimeout("UpdateSubmitButtonStatus()",100)
          var vatVal=0,totalvat=0
        $("#InventoryInvoiceTable tbody tr").each(function(){
            var TRvalue = parseFloat($(".TotalTD .Total",$(this)).attr('myval'));
        if(TRvalue !=0){
            //alert(TRvalue)
            if($(this).attr('data-vat') == 1){
            vatVal = TRvalue * 0.1;
            totalvat += vatVal
            //alert(totalvat)
            $("#InvoiceVAT").html(totalvat.toFixed(3))
            }
            
        }
                                    
        })
    }
    function EnableAutoComplete(who){
        if(!who.hasClass("AutoAdded")){
            who.autocomplete({
                source: function(request, response){
                    var Class_ID=$('#ClassID').text()
                    $.getJSON('xhr/ajaxLoadingProduct?cmd=' + (who.hasClass("NewSalesInvoiceCODE") ? "1" : "2") + "&id="+Load_id+"&class="+(Class_ID), request, function( s, status, xhr ){
                        response( s );
                    });
                },
                minLength: 2,
                select: function(event, ui){
                    var TR = $(this).parents("tr");
                    TR.attr("data-id",ui.item.Product_ID)
                    TR.attr("data-vat",ui.item.Product_VAT)
                    TR.find("input.NewSalesInvoiceCODE").val(ui.item.Product_Code )            
                    TR.find("input.NewProductName").val(ui.item.Product_Name)
                    if(Zone_ID == 8 ){TR.find("input.NewUnitPrice").val(parseFloat(ui.item.Product_Price)+2)} else{TR.find("input.NewUnitPrice").val(ui.item.Product_Price )}
                    // if(!IsSalesMode)TR.find("input.NewUnitPrice").prev().text("last cost: "+(!ui.item.LAST_COST ? "NAN" : ui.item.LAST_COST) + " " + (ui.item.Currency_ID ? ui.item.Currency_ID[1] : ""));
                    TR.find("input.NewInvoiceQuantity").focus().prev().text((ui.item.Product_Quantity  ) + " in truck")
                    QtyInTruck = ui.item.Product_Quantity ;
                    return false;
                }
            }).autocomplete("instance")._resizeMenu = function( ul, items ) {
                this.menu.element.outerWidth((who.width()*(this.element.hasClass("NewSalesInvoiceCODE") ? 1 : 2.3)) + parseFloat(who.css("padding-left")) + parseFloat(who.css("padding-right")) + 2);
            }
            who.autocomplete("instance")._renderItem = function(ul,item){
                var MyType = this.element.hasClass("NewSalesInvoiceCODE") ? (item.Product_Code) : (item.Product_Name );
                return $("<li>").html("<table cellspacing='0' cellpadding='0'><tr><td class='OnlyText'>"+MyType+"</td></tr></table>").appendTo(ul)
            }
            who.addClass("AutoAdded")
        }
        $(document).keydown(function(e){
            if(e.which == 8 && e.target.tagName.toLowerCase() != "input"){
                e.preventDefault()
            }
        })
    }

    function ApplyPostMethod(){
        $("#NewInvoiceSuccess").attr("class","hidden");
        var mustpay = $("#NewPurchaseInvoiceTotalDetails").text()
        if($("#Customer_ID").val() == "" && $("#NewSetPaidFormTab_1 .InputSpinner > input").eq(0).val() < mustpay){

            $("#NewSetPaidFormTab_1 .InputSpinner > input").attr('required',true)
            alert('Please enter cash amount')
            $("#InvoiceSubmitButton").addClass("disabled")

            $("#NewSetPaidFormTab_1 .InputSpinner > input").on("keyup",function(){

                $("#InvoiceSubmitButton").removeClass("disabled")

            })

        }else

            if($("#NewInvoiceForm").valid()){
                var IsValidated=true,
                    Data = {

                        Cash_Amount : $("#NewSetPaidFormTab_1 .InputSpinner > input").eq(0).val(),
                        Cash_ID : $("#NewSetPaidFormTab_1 .DropDownForForms > button > input").eq(0).val(),
                        Check_Amount : $("#NewSetPaidFormTab_2 .InputSpinner > input").eq(0).val(),
                        Check_ID : $("#NewSetPaidFormTab_2 .DropDownForForms > button > input").eq(0).val(),
                        Check_Num : $("#NewSetPaidFormTab_2 .CheckNumValue").eq(0).val(),
                        Card_Amount:$("#NewSetPaidFormTab_3 .InputSpinner > input").eq(0).val(),
                        Card_ID : $("#NewSetPaidFormTab_3 .DropDownForForms > button > input").eq(0).val(),
                        Card_Code : $("#NewSetPaidFormTab_3 .CardApproval").eq(0).val(),
                        Products:[]

                    };


                Data.Load_Order_ID   = $("#Load_Order_ID").val();
                Data.Customer_ID = $("#Customer_ID").val();
                Data.Invoice_Date =  $("#NewSalesInvoiceDate").val();
                Data.Invoice_Due_Date =  $("#NewSalesInvoiceDueDate").val();
                Data.Invoice_Currency = $("#NewCurrencyDropDown input").val();
                Data.Invoice_Discount =  $("#InvoiceDiscountInput").val();
                Data.Invoice_Net_Total = $("#NewPurchaseInvoiceTotalDetails").attr("MyValueDiscounted");
                Data.Invoice_Sub_Total = $("#NewPurchaseInvoiceTotalDetails").attr("MyValueNotDiscounted");
                Data.Invoice_Paid_Amount = parseFloat(Data.Check_Amount) + parseFloat(Data.Card_Amount) + parseFloat(Data.Cash_Amount);
                Data.Invoice_VAT = $("#InvoiceVAT").html();
                Data.products = [];

                var Currency = $("#NewCurrencyDropDown span").text(),
                    symbol = Currency.split("-"),
                    counter =parseInt($("#SetupPayment tr").find(".Counter>span.Counter").html());
                console.log(counter)
               // alert(Data.Invoice_Paid_Amount)
                var CustName = ($("#Customer_ID").val()!=0) ? $("#CustomerInfoContent .Name").html() : roadCustomerLang;
                var TR = "<tr data-id="+counter+">"
                TR+="<td class='text-center'>"+CustName+"</td>"
                TR+="<td class='text-center TotalPaid'><span class='CurrencyPaid'></span> <span class='TotalPaid'>0</span></td>"
                TR+=" <td class='text-center Total'><span class='Currency'></span> <span class='Total'>0</span></td></tr>"
                TR=$(TR)

                $("#SetupPayment tbody:last").append(TR);




                $("#SetupPayment tbody tr:last ").find("td>span.TotalPaid").html((Data.Invoice_Paid_Amount));
                $("#SetupPayment tbody tr:last ").find("td>span.CurrencyPaid").html(symbol[1]);
                $("#SetupPayment tbody tr:last ").find("td>span.Currency").html(symbol[1]);
                $("#SetupPayment tbody tr:last ").find("td>span.Total").html(parseFloat(Data.Invoice_Sub_Total).toFixed(3));









                var Totalvaluepaid = 0 ,Totalvalue=0;
                var MyTotal = parseFloat($("#NewPurchaseInvoiceTotalPaid").text());
                
                $("#SetupPayment tr[data-id]").each(function(){

                    Totalvaluepaid +=parseFloat((($(".TotalPaid >span.TotalPaid",this).html()).replace(",","")));

                    Totalvalue += parseFloat((($(".Total>span.Total",this).html()).replace(",","")));
//                    alert(Totalvaluepaid)
//                    alert(Totalvalue)


                })
                var ResultTotalvalue = AddCommas(parseFloat(Totalvalue-Totalvaluepaid).toFixed(3));
                var ResultTotalvaluepaid = AddCommas(parseFloat(Totalvaluepaid).toFixed(3));
                    
                $("#PurchaseInvoiceTotalPaid").empty().html(ResultTotalvalue);

                $("#PurchaseInvoiceTotalDetails").empty().html(ResultTotalvaluepaid);


                $("#InventoryInvoiceTable tbody tr").each(function(e){
                    var me = $(this);
                    if(e < $(this).parent().children().length-1){



                        Data.products.push([

                            me.attr("data-id"),
                            me.find(".NewInvoiceQuantity").val(), 
                            me.find(".NewDisc").val(),
                            me.find(".NewUnitPrice").val(),
                            me.find(".TotalTD > .Total").attr("myval")


                        ]);



                        me.find(".NewSalesInvoiceCODE,.NewProductName,.NewInvoiceQuantity,.NewUnitPrice").each(function(){
                            if($.trim($(this).val()) == "" || ($(this).hasClass("isnumber") && $.trim($(this).val()).match(/^\s*?([\d]+(\.\d+)?|\.\d{1,2})\s*$/) == null)){
                                $(this).addClass("wrong")
                                IsValidated = false;
                            }else{
                                $(this).removeClass("wrong")
                            }
                        })
                    }
                })
                if(!IsValidated)return;
                $("#InvoiceDisabler").show();
                $.ajax({
                    url:"InventoryAjax/SalesOrderIvoice",
                    method:"POST",
                    data:Data,
                    complete:function(v1,v2){
                        if(v2 == "success"){
                            $("#NewInvoiceSuccess").attr("class","alert alert-success").html(Submitted_Successfully)
                        }else{
                            $("#NewInvoiceSuccess").attr("class","alert alert-danger").html(Failed_Submit)
                        }
                        $(document.body).animate({scrollTop:0},800)
                        $("#InvoiceDisabler").hide();
                        setTimeout(function(){
                            $("#SalesInvoiceModal").modal('hide')
                        },1000)
                        ClearNewInvoice();
                    }
                })
            }else{
                $(document.body).animate({scrollTop:0},800)
            }
    }
    function UpdateTotalForRow(who){
        var Single_Price    = parseFloat(who.find(".NewUnitPrice").val()) || 0,
            Qty             = parseFloat(who.find(".NewInvoiceQuantity").val()) || 0,
            Total           = Single_Price * Qty,
            Discount        = parseFloat(who.find(".NewDisc").val()) || 0,
            Net_Total       = (Total * (1 - Discount/100)) || 0;
        TotalInvoiceWithoutDiscount += Total;
        TotalDiscount   += Discount
        TotalInvoice    += Net_Total
        who.find(".Total").attr("MyVal",Net_Total.toFixed(3)).text(AddCommas(Net_Total.toFixed(3)))
    }
    function UpdateSubmitButtonStatus(){


        var Rows = $("#InventoryInvoiceTable tbody tr"),DoDisable = false
        if(Rows.length > 0){
            if(Rows.length == 1){
                if($.trim($("input.NewSalesInvoiceCODE",Rows).val()) != "" && $.trim($("input.NewProductName",Rows).val()) != "" && $.trim($("input.NewInvoiceQuantity",Rows).val()) != "" && $.trim($("input.NewUnitPrice",Rows).val()) != ""){


                    DoDisable = false;


                }else{
                    DoDisable = true;
                }
            }else{
                DoDisable = false;
            }
        }else{
            DoDisable = true;
        }
        if($.trim($("#NewCurrencyDropDown > button > input").val()) == "")DoDisable = true;
        // document.title = Rows.length
        if(DoDisable){$("#InvoiceSubmitButton").addClass("disabled")}else{$("#InvoiceSubmitButton").removeClass("disabled")}
    }
    function InputMustBeAtleastN(who,N){
        if(parseInt(who.value) < N || !parseInt(who.value))who.value = N;
        UpdateInvoiceTotalPaid();
    }
    function UpdateInvoiceTotalPaid(){
        var A1 = parseFloat($("#NewSetPaidFormTab_1 .InputSpinner > input").eq(0).val()) || 0,
            A2 = parseFloat($("#NewSetPaidFormTab_2 .InputSpinner > input").eq(0).val()) || 0,
            A3 = parseFloat($("#NewSetPaidFormTab_3 .InputSpinner > input").eq(0).val()) || 0;
        $("#NewPurchaseInvoiceTotalPaid").text(A1 + A2 + A3);
    }
    function ClearNewInvoice(){
        $("#NewInvoiceSuccess").hide()
        $("#CustomerInfoContent").empty();
        $("#NewSalesInvoiceDueDate").val('');
        $("#InventoryInvoiceTable tbody input").val('');
        $("#InventoryInvoiceTable tbody span.Hint").empty();
        $("#InventoryInvoiceTable tbody td.TotalTD span.Total").text('0');
        $("#NewPurchaseInvoiceTotalDetails ").empty().html(0);
        $("#NewPurchaseInvoiceTotalPaid ").empty().html(0);
        $("#newCashAmount,#newCheckAmount,#newCreditAmount").val(0)
        $("#Customer_ID").val(0)

    }
</script>