
<style type="text/css">
    #Invoice_Details{
        padding-top:20px;
    }
    #ReturnItemTable td{
        position:relative;
        vertical-align:middle;
    }
    #ReturnItemTable .Quantity,#ReturnItemTable .Total,#ReturnItemTable .UnitPrice{
        text-align:center;
    }
    .EditRow{
        font-size:20px;
        cursor:pointer;
    }
    .EditRow:hover{
        color: rgb(0, 144, 217);
    }
    .table-responsive{
        overflow:visible;
        -webkit-transform: perspective(100px);
        -moz-transform: perspective(100px);
        transform: perspective(100px);
    }
    #ReturnItemTable tr{
        -webkit-transition:-webkit-transform 0.2s linear;
        -moz-transition:-moz-transform 0.2s linear;
        transition:transform 0.2s linear;
    }
    #ReturnItemTable tr.Edit{
        -webkit-transform: scale(1.1) rotate(0);
        -moz-transform: scale(1.1) rotate(0);
        transform: scale(1.1) rotate(0);
    }
    #ReturnItemTable tr.Faded > td{
        opacity:0.5;
        cursor:default;
    }
    #ReturnItemTable tr.Faded,#ReturnItemTable tr.Faded > td{
        background-color:#fff !important;
    }
    #ReturnItemTable tr.Edit > td{
        background-color:#eee !important;
    }
    #ReturnItemTable .Hint{
        position: absolute;
        font-size: 10px;
        font-weight: bold;
        height: 20px;
        line-height: 20px;
        bottom: 2px;
        right: 4px;
        color: rgb(153, 153, 153);
    }
    .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;
    }
    .hideme{
        display:none;
    }
    #InvoicePaymentSetup .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;
    }
    #InvoicePaymentSetup .table tbody > tr:last-child > td{
        border:0;
    }
</style>
<form method="POST" action="" onsubmit="return false" id="ReturnItemForm">
    <div class="container-fluid container-fixed-lg">
        <div class="panel panel-default">
            <div class="panel-body">
                <h4 class="bold"><?php echo CommonLanguage::getMessage($IsVendor ? 'vendor_return' : 'customer_return'); ?> </h4>
                <div id="ReturnItemSuccess" class="alert alert-success hidden"></div>
                <div class="invoice padding-50 sm-padding-10">
                    <div class="container-sm-height">
                        <div class="row-sm-height">
                            <div class="col-md-9 col-sm-height sm-no-padding">
                                <div>
                                    <div class="input-group  col-md-4 center-margin pull-left" >
                                        <span class="input-group-addon primary ">
                                            <?php print CommonLanguage::getMessage('invoice'); ?> #
                                        </span>
                                        <input type="text" id="Invoice_Purchase_ID" class="form-control" placeholder="search by number,customer,date">
                                    </div>
                                    <div class="col-md-2">
                                        <button class=" btn btn-primary btn-cons   " id="generate"  type="button"><i class="pg-form"></i> <span class="bold"><?php print CommonLanguage::getMessage('generate_invoice'); ?></span></button>

                                    </div>
                                    <div class="clearfix"></div>
                                    <div id="Invoice_Details"></div>
                                </div>
                                <br>
                            </div>
                            <div class="col-md-4 col-sm-height col-bottom sm-no-padding sm-p-b-20" style="vertical-align: top;">
                                <div  class="form-group form-group-default input-group">
                                    <label><?php print CommonLanguage::getMessage('Date'); ?></label>
                                    <input id="Return_Invoice_Date" name="Return_Invoice_Date" class="form-control" value="<?php echo ($today); ?>" />
                                    <span class="input-group-addon primary"><i class="fa fa-calendar"></i></span>
                                </div>
                                <br>
                                <div  id="depot" class="form-group " >

                                    <div class="input-group m-b" >
                                        <label><?php print CommonLanguage::getMessage('Depot'); ?></label>
                                        <span class="fa fa-plus-circle m-l-5 openFrame" data-src="Stock/ListDepot?is_pop=1" style="color:#8a7dbe;cursor:pointer"></span>

                                        <div class="input-group" style="    width: 311px;">
                                            <input required id="Depot_Loc" name="Depot_Loc" class="full-width Depot_Loc" type="hidden"  />

                                            <!--                                            <select required id="Depot_Loc" name="Depot_Loc" class="full-width Depot_Loc" data-init-plugin="select2">
<?php foreach ($all_depots as $Depot): ?>
<option value="<?php echo $Depot['Depot_ID']; ?>"><?php echo $Depot['Depot_Name']; ?></option>
<?php endforeach; ?>

</select>-->
                                            <span class="input-group-btn"><button type="button" class="btn btn-primary"><i class="fa fa-certificate"></i> </button> </span>
                                        </div>
                                    </div>

                                </div>
                            </div>
                        </div>
                    </div>
                    <div>
                    </div>
                    <div class="table-responsive" style="position:relative;margin-bottom: 15px;">
                        <div ID="ReturnItemTableLoader" style="display:none;position:absolute;left:0;right:0;top:0px;height:100%;background:rgba(255,255,255,0.9);z-index:999"><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>
                        <table class="table table-hover" id='ReturnItemTable'>
                            <thead>
                                <tr>
                                    <th> </th>
                                    <th><?php print CommonLanguage::getMessage('Code'); ?></th>
                                    <th style="width:30%" class="hidden-xs"><?php print CommonLanguage::getMessage('Item'); ?></th>
                                    <th style="text-align:center;width:20%;"><?php print CommonLanguage::getMessage('Quantity'); ?></th>
                                    <th style="text-align:center;width:10%;"><?php print CommonLanguage::getMessage('UOM'); ?></th>
                                    <th style="text-align:center;width:10%"><?php print CommonLanguage::getMessage('unit_cost'); ?></th>
                                    <th style="width:10%"><?php print CommonLanguage::getMessage('discount'); ?></th>
                                    <th style="text-align:center;"><?php print CommonLanguage::getMessage('total'); ?></th>
                                    <!--<th style="text-align:center;"></th>-->
                                </tr>
                            </thead>
                            <tbody>
                            </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'); ?><span class="fa fa-plus-circle m-l-5 openFrame" data-src="ACC/viewlibrary/1?is_pop=1" style="color:#8a7dbe;cursor:pointer"></span></h5>
                                <div id="InvoicePaymentSetup" class="no-print">
                                    <div class="Body">
                                        <div class="">
                                            <ul class="nav nav-tabs">
                                                <li class="active"><a data-toggle="tab" href="#SetPaidFormTab_1"><i class="fa fa-money"></i>&nbsp;&nbsp;<?php print CommonLanguage::getMessage('cash'); ?></a></li>
                                                <li><a data-toggle="tab" href="#SetPaidFormTab_2"><i class="fa fa-file-text-o"></i>&nbsp;&nbsp;<?php print CommonLanguage::getMessage('check'); ?></a></li>
                                                <li><a data-toggle="tab" href="#SetPaidFormTab_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="SetPaidFormTab_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" class="form-control" value="0" onblur="InputMustBeAtleastN(this, 0);" />
                                                                        <div class="input-group-btn-vertical">
                                                                            <button class="btn btn-default more" type='button'><i class="fa fa-caret-up"></i></button>
                                                                            <button class="btn btn-default" type='button'><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">-->
                                                                    <input class="cash_account full-width" id="cash_account" name="cash_account" type="hidden"   value="<?php echo smc_session()['user_accounts']['cash_account_id']?>" data-select-name=<?php echo smc_session()['user_accounts']['c_name'] ?>/>

                                                                    <!--                                                                        <button type="button" class="btn btn-default btn-block dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
<span>< ?php echo CommonLanguage::getMessage('select'); ?></span>
<input type="hidden" value="0" 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]["Account_Code"]; ?>"><a><?php echo $Cashes[$x]["Payment_Type_Name"]; ?></a></li>
<?php } ?>
</ul>-->
                                                                    <!--                                                                    </div>-->
                                                                </td>
                                                            </tr>
                                                        </tbody>
                                                    </table>
                                                </div>
                                                <div id="SetPaidFormTab_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" class="form-control" value="0" onblur="InputMustBeAtleastN(this, 0);" />
                                                                        <div class="input-group-btn-vertical">
                                                                            <button class="btn btn-default more" type='button'><i class="fa fa-caret-up"></i></button>
                                                                            <button class="btn btn-default" type='button'><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">-->
                                                                    <input class="check_account full-width" id="check_account" name="check_account" type="hidden" />

                                                                    <!--                                                                        <button type="button" class="btn btn-default btn-block dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
<span><?php echo CommonLanguage::getMessage('select'); ?></span>
<input type="hidden" value="0" 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]["Account_Code"]; ?>"><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="SetPaidFormTab_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" class="form-control" value="0" onblur="InputMustBeAtleastN(this, 0);" />
                                                                        <div class="input-group-btn-vertical">
                                                                            <button class="btn btn-default more" type='button'><i class="fa fa-caret-up"></i></button>
                                                                            <button class="btn btn-default" type='button'><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">-->
                                                                    <input class="credit_account full-width" id="credit_account" name="credit_account" type="hidden"  />

                                                                    <!--                                                                        <button type="button" class="btn btn-default btn-block dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
<span><?php echo CommonLanguage::getMessage('select'); ?></span>
<input type="hidden" value="0" 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]["Account_Code"]; ?>"><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-2 col-sm-height col-middle clearfix sm-p-b-15">
                                <textarea id="Return_Invoice_Note" name="Return_Invoice_Note" class="form-control NoteTextArea" placeholder="<?php print CommonLanguage::getMessage('enter_note'); ?>"></textarea>
                            </div>
                            <div class="col-sm-4 text-right bg-menu col-sm-height padding-15">
                                <div>
                                    <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="ReturnTotalDetails">0</span></h1>
                                </div>
                                <div>
                                    <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="PurchaseInvoiceTotalPaid">0</span></h1>
                                </div>
                                <div>
                                    <h5 class="font-montserrat all-caps small no-margin hint-text text-white bold"><?php print CommonLanguage::getMessage('total_taxable'); ?></h5>
                                    <h1 class="no-margin text-white Total"><span class="CurrencyIndicator"></span>&nbsp;<span id="TotalTax">0</span></h1>
                                </div>
                            </div>

                        </div>
                    </div>
                    <div class="container-sm-height" >
                        <button class=" btn btn-primary btn-cons m-b-10 pull-right disabled" id="ReturnSubmitButton" style="padding-top: 10px;top: 20px;min-width:253px;" type="button"><i class="pg-form"></i> <span class="bold"><?php print CommonLanguage::getMessage('Save'); ?></span></button>
                    </div>
                    <hr>
                </div>
            </div>
        </div>
    </div>
</form>

<script>
    var No_Changes = <?php echo json_encode(CommonLanguage::getMessage('no_changes')); ?>,
        Failed_Submit = <?php echo json_encode(CommonLanguage::getMessage('Failed_Submit')); ?>,
            cannot_add_row = <?php echo json_encode(CommonLanguage::getMessage('cannot_add_row')); ?>,
                discountLang = <?php echo json_encode(CommonLanguage::getMessage('discount')); ?>,
                    totalLang = <?php echo json_encode(CommonLanguage::getMessage('total')); ?>,
                        duedateLang = <?php echo json_encode(CommonLanguage::getMessage('due_date')); ?>,
                            NameLang = <?php echo json_encode(CommonLanguage::getMessage('Name')); ?>,
                                DateLang = <?php echo json_encode(CommonLanguage::getMessage('Date')); ?>,
                                    rem = <?php echo json_encode(CommonLanguage::getMessage('ret')); ?>,
                                        Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')); ?>;
                                        var CurrentCurrencySymbol = "", Currency_ID,
                                            IsVendor = <?php echo $IsVendor ? "true" : "false"; ?>, CurInvoiceID,
                                                is_actual = <?php echo $is_actual ? "true" : "false"; ?>,
                                                CurrentInvoiceDiscount = 0,
                                                    UpdateTableTimeout, ReturnItemTableBody = $("#ReturnItemTable tbody");
    $(function () {
        EnableAutoComplete($("#Invoice_Purchase_ID"))
        build_select2($(".Depot_Loc"),"xhr/depotSearch")
        build_select2($("#cash_account"),( "xhr/accSearch?type=cash"))
        build_select2($("#check_account"),( "xhr/accSearch?type=check"))
        build_select2($("#credit_account"),( "xhr/accSearch?type=credit_card"))
        $("body").addClass("NoSearch")
        $("body .search-link[data-toggle='search']").html("<i class='pg-search'></i>Click here to <span class='bold'>search</span>")
        $("#Return_Invoice_Date").datepicker({autoclose: true}).on("changeDate", function (e) {
            $(this).keyup();
        });
        $("#InvoicePaymentSetup .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)
            UpdatePurchaseInvoiceTotalPaid()
        })
        $("#InvoicePaymentSetup").find("input.form-control").on("keyup", function () {
            UpdatePurchaseInvoiceTotalPaid()
        })


    });
    $("#generate").on("click", function (e) {
        clearTimeout(UpdateTableTimeout);
        ChangeInvoice();

    });
    //    $("#Invoice_Purchase_ID").on("keyup", function (e) {
    //        clearTimeout(UpdateTableTimeout);
    //        if (e.which == 13) {
    //            ChangeInvoice();
    //            return;
    //        }
    //        UpdateTableTimeout = setTimeout(function () {
    //            ChangeInvoice();
    //        }, 1000)
    //    });
    $("#ReturnSubmitButton").on("click", function () {
        var flag = false;
        //        var maintax=$("#TotalTax").text().split(" ");
        var Changes = {
            Products: [],
            Person_ID : $("#Person_ID").val(),
            Invoice_Purchase_ID: CurInvoiceID,
            Return_Invoice_Total: $("#ReturnTotalDetails").attr("data-net"),
            Return_Invoice_Note: $("#Return_Invoice_Note").val(),
            Return_Invoice_Date: $("#Return_Invoice_Date").val(),
            Auto_ID: $("#Auto_ID").val(),
            Is_Customer_Invoice: IsVendor ? 0 : 1,
            Depot_ID: $("#Depot_Loc").val(),
            TotalTax: $("#TotalTax").html().replace(/,/g, ""),
            Currency_ID: Currency_ID,
            Cash_Amount: $("#SetPaidFormTab_1 .InputSpinner > input").eq(0).val(),
            Cash_Account: $("#cash_account").val(),
            Check_Amount: $("#SetPaidFormTab_2 .InputSpinner > input").eq(0).val(),
            Check_Account: $("#credit_account").val(),
            Card_Amount: $("#SetPaidFormTab_3 .InputSpinner > input").eq(0).val(),
            Card_Account: $("#check_account").val(),
            Check_Num: $("#SetPaidFormTab_2 .CheckNumValue").eq(0).val(),
            Card_Code: $("#SetPaidFormTab_3 .CardApproval").eq(0).val(),
            is_actual : (is_actual ? 1 : 0)
        };
        $("#ReturnItemSuccess").hide()
        $("#ReturnItemTable tr").each(function () {
            if (parseFloat($.trim($(">.Quantity>.QuantityVal", this).text())) > 0) {
                var NewObject = {
                    //                    Entery_ID: $(this).attr("data-code"),
                    Product_ID: $(this).attr("data-pid"),
                    UOM_ID: $(this).attr("data-uom"),
                    Product_Code: $(".Product_Code", this).text(),
                    Product_Name: $(".Product_Name", this).text(),
                    Unit_Cost: $(".UnitPrice", this).attr("data-unit-price"),
                    Return_Product_Quantity: $.trim($(">.Quantity>.QuantityVal", this).text()),
                    Return_Product_Total: $(".Total > .TotalPrice", this).attr("data-val")
                }
                Changes.Products.push(NewObject)
                //alert($(this).attr("data-pid"))
            }
            var myTR = $(this).find('.Quantity');
            if (parseFloat($.trim($(".QuantityVal", this).text())) > parseFloat(myTR.attr('data-input'))) {
                flag = true;
                //                console.log(myTR.attr('data-max'))


            }

        })
        if (Changes.Products.length == 0) {
            $("#ReturnItemSuccess").attr("class", "alert alert-warning").show().html(No_Changes)
            //            alert("There are no changes has been made");
            return
        }
        if (flag) {
            $("#ReturnItemSuccess").attr("class", "alert alert-warning").show().html('Returned quantities are more than invoiced quantities')
            $(document.body).animate({scrollTop: 0})
            return
        }
        $("#ReturnItemTableLoader").show().appendTo("#ReturnItemForm .panel-body")


        $.ajax({
            url: "InventoryAjax/ReturnCustomerAjax",
            method: "post",
            data: Changes,
            complete: function (v, vv) {
                if (vv == "success") {
                    if (v.responseText == "OK") {
                        $("#ReturnItemSuccess").attr("class", "alert alert-success").show().html(Submitted_Successfully)
                    } else {
                        $("#ReturnItemSuccess").attr("class", "alert alert-danger").show().html(v.responseText)

                    }
                } else {
                    $("#ReturnItemSuccess").attr("class", "alert alert-danger").show().html(Failed_Submit)
                }
                $("#ReturnItemTableLoader").hide().insertBefore("#ReturnItemTable")
                $(document.body).animate({scrollTop: 0})

            }
        })



    })
    function ChangeInvoice() {
        var ID = parseInt($("#Invoice_Purchase_ID").val());
        var Auto_ID = parseInt($("#Invoice_Purchase_ID").attr("data-id"));
        if (ID == CurInvoiceID) {
            return
        }
        ReturnItemTableBody.empty();
        if (!isNaN(ID)) {
            CurInvoiceID = ID;
            $("#ReturnItemSuccess").addClass("hidden")
            $("#ReturnItemTableLoader").css({display: "block", opacity: 0}).animate({opacity: 1});
            $("#ReturnTotalDetails").text(CurrentCurrencySymbol + " 0");
            $("#ReturnSubmitButton").addClass("disabled")

            $.ajax({
                url: "InventoryAjax/ReturnCustomerAjax",
                data: {GetInvoiceData: ID, IsVendor: IsVendor,is_actual : (is_actual ? 1 : 0),auto_id :Auto_ID},
                dataType: "json",
                complete: function (v, vv) {
                    var Products = v.responseJSON,
                        PrLength = Object.keys(Products).length

                    $("#ReturnItemTableLoader").hide()
                    if (Products.length == 0)
                        return
                        CurrentCurrencySymbol = Products[0]["Currency_Symbol"];
                    Currency_ID = Products[0]["Currency_ID"];
                    var Invoice_Details = "";
                    Invoice_Details += "<strong>" + NameLang + ": </strong>" + (Products[0]["Person_Name"] == null ? "-- --" : Products[0]["Person_Name"]) + "<br/>";
                    Invoice_Details += "<strong>" + DateLang + ": </strong>" + Products[0]["Inv_Pur_Date"] + "<br/>";
                    Invoice_Details += "<strong>" + totalLang + ": </strong>" + CurrentCurrencySymbol + " " + AddCommas(parseFloat(Products[0]["Net_Total"]).toFixed(3)) + "<br/>";
                    Invoice_Details += " <strong >" + discountLang + ":</strong> " + Products[0]["Main_Discount"] + " % <br/>";
                    Invoice_Details += " <input type='hidden' id='Auto_ID' value=" + Products[0]["Auto_ID"] + ">   <br/>";
                    Invoice_Details += " <input type='hidden' id='Person_ID' value=" + Products[0]["Person_ID"] + ">   <br/>";


                    $('#Depot_Loc').val(Products[0]["Depot_ID"]);
                    $('#Depot_Loc').attr('data-select-name',Products[0]["Depot_Name"]);
                    $("#Invoice_Details").html(Invoice_Details)
                    for (var x = 0; x < PrLength; x++) {
                        //                        var UnitPrice = Products[x]["Product_Net_Price"],

                        var UnitPrice = Products[x]["Item_Price"],
                            Discount = AddCommas(parseFloat($.trim((Products[x]["Item_Discount"]))).toFixed(3)),
                            TotalPrice = AddCommas(parseFloat($.trim(Products[x]["Total_Item_Price"])).toFixed(3)),
                            Quantity = Products[x]["Quantity"],
                            TR = "<tr data-uom='" + Products[x]["UOM_ID"] + "' data-vat='" + Products[x]["Item_VAT"] + "'  data-pid = '" + Products[x]["Product_ID"] + "'>";
                        TR += "<td style='text-align:center'><div class='EditRow' onclick='EditMe(this)'><i class='fa fa-edit'></i></div></td>"
                        TR += "<td  class='Product_Code'>" + Products[x]["Code"] + "</td>"
                        TR += "<td class='Product_Name'>" + Products[x]["Name"] + "</td>"
                        TR += "<td data-max='" + Products[x]["Item_Quantity"] + "'  data-input='" + Products[x]['Remain_Main'] + "' class='Quantity'><span class='QuantityVal'>" + Products[x]['Remaining_Quantity'] + "</span><span class='Hint'>" + rem + Products[x]['Product_Return_Quantity'] + '/' + totalLang + Quantity + "</span></td>"//Quantity
                        TR += "<td style='text-align:center'><span class='uomspan'>" + Products[x]['UOM_Name'] + "</span></td>"//Quantity
                        TR += "<td class='UnitPrice' data-unit-price='" + UnitPrice + "' >" + CurrentCurrencySymbol + " " + AddCommas(parseFloat(UnitPrice).toFixed(3)), +"</td>"
                        TR += "<td class='Discount'><span class='DiscountVal'></span><span class='DiscountPercentage Hint' data-val='" + Discount + "'>%" + Discount + "</span></td>"
                        TR += "<td class='Total'>" + CurrentCurrencySymbol + " <span class='TotalPrice'>" + TotalPrice + "</span></td>"
                        //                        TR += "<td class='ExpiryDate'><span class='fa fa-plus-circle' style='color:#4c0870;margin-top:10px'></span></td>"


                        TR += "</tr>";
                        TR = $(TR);
                        UpdateRowValues(TR.get(0));
                        ReturnItemTableBody.append(TR);


                    }
                    $("#ReturnSubmitButton").removeClass("disabled")
                    CurrentInvoiceDiscount = parseFloat(Products[0]["Main_Discount"]);
                    $('.CurrencyIndicator').text(CurrentCurrencySymbol);
                    $("#ReturnTotalDetails").text(AddCommas(parseFloat(Products[0]["Net_Total"]).toFixed(3)))
                    UpdateInvoiceTotal()

                }
            })
        }
    }
    function EditMe(who) {
        var TR = $(who).parents("tr");
        $("tr.Edit", ReturnItemTableBody).each(function () {
            UpdateRowValues(this);
            UpdateInvoiceTotal()
        });
        if (TR.hasClass("Edit")) {
            $("tr", ReturnItemTableBody).attr("class", "")
        } else {
            $("tr", ReturnItemTableBody).attr("class", "Faded")
            TR.attr("class", "Edit").stop().css({opacity: 0}).animate({opacity: 1})
            $(".Quantity > .Hint", TR).hide()
            var TheInput = $("<input type='text' class='form-control' style='position:relative;z-index:99;width:70%;margin:0;display:inline-block' value='" + $.trim($(".QuantityVal", TR).text()) + "' />")
            $(".QuantityVal", TR).empty().append(TheInput)
            TheInput.on("keyup", function (e) {
                if (e.which == 13) {
                    EditMe($(this).parent());
                }
            }).focus()
            TheInput.get(0).selectionStart = 0;
            TheInput.get(0).selectionEnd = TheInput.val().length;
        }
    }
    function UpdateRowValues(who) {
        if ($(".QuantityVal>input", who).length > 0) {
            var NewQuantity = parseFloat($.trim($(".QuantityVal>input", who).val())) || 0,
                MaxVal = parseFloat($(".QuantityVal", who).attr("data-max"));
            if (NewQuantity > MaxVal) {
                $(this).val(MaxVal)
                $(".QuantityVal>input", who).val(MaxVal)
                NewQuantity = MaxVal;
                $("#ReturnItemSuccess").attr("class", "alert alert-warning").show().html(cannot_add_row)
                //				alert("You can't add more items to the invoice");cannot_add_row
            }
        } else {
            var NewQuantity = parseFloat($.trim($(".QuantityVal", who).text())) || 0;
        }
        var DiscountPercentage = parseFloat($(".DiscountPercentage", who).attr("data-val")) || 0,
            UnitPrice = parseFloat($("td[data-unit-price]", who).attr("data-unit-price")) || 0,
            TotalValWithDiscount = (NewQuantity * UnitPrice) * (1 - (DiscountPercentage / 100)),
            DiscountVal = ((NewQuantity * UnitPrice) - TotalValWithDiscount);
        $(".Discount > .DiscountVal", who).html(CurrentCurrencySymbol + " " + AddCommas(DiscountVal.toFixed(3)))
        $(".TotalPrice", who).attr({"data-val": TotalValWithDiscount}).text(AddCommas(TotalValWithDiscount.toFixed(3)));
        $(".Quantity > .Hint", who).show()
        $(".QuantityVal", who).empty().html(NewQuantity);



    }
    function UpdateInvoiceTotal() {
        var TotalInvoice = 0,
            totalvat = 0;
        var vatVal = 0;
        $("tr", ReturnItemTableBody).each(function () {

            TotalInvoice += parseFloat($(".Total > .TotalPrice", this).attr("data-val"))
            var TRvalue = parseFloat($(this).attr('data-vat'));
            if (TRvalue != 0) {
                vatVal = TotalInvoice * 0.1;
                totalvat += vatVal;
                //                console.log(vatVal)
                //                console.log(totalvat)
                $('#TotalTax').html(AddCommas(vatVal.toFixed(3)))
                $('.CurrencyIndicator').html(CurrentCurrencySymbol)

            }

        })
        var TotalInvoiceDisounted = TotalInvoice - (TotalInvoice * (CurrentInvoiceDiscount / 100))
        $("#ReturnTotalDetails").attr({"data-total": TotalInvoiceDisounted}).html(AddCommas((TotalInvoiceDisounted + vatVal).toFixed(3)));
        $("#ReturnTotalDetails").attr({"data-net": (TotalInvoiceDisounted + vatVal).toFixed(3)})
        $("#ReturnItemSuccess").addClass("hidden")
    }

    function UpdateSubmitButtonStatus() {
        var DoDisable = false

        if (parseFloat($("#PurchaseInvoiceTotalPaid").html().replace(",", "")) > parseFloat($("#ReturnTotalDetails").html().replace(",", "")))
        {
            DoDisable = true;
        }

        if (DoDisable) {
            $("#ReturnSubmitButton").addClass("disabled")
        } else {
            $("#ReturnSubmitButton").removeClass("disabled")
        }
    }
    function UpdatePurchaseInvoiceTotalPaid() {
        var A1 = parseFloat($("#SetPaidFormTab_1 .InputSpinner > input").eq(0).val()) || 0,
            A2 = parseFloat($("#SetPaidFormTab_2 .InputSpinner > input").eq(0).val()) || 0,
            A3 = parseFloat($("#SetPaidFormTab_3 .InputSpinner > input").eq(0).val()) || 0;
        $("#PurchaseInvoiceTotalPaid").text(AddCommas(A1 + A2 + A3));
        UpdateSubmitButtonStatus();


    }
    function InputMustBeAtleastN(who, N) {
        if (parseInt(who.value) < N || !parseInt(who.value))
            who.value = N;
        UpdatePurchaseInvoiceTotalPaid();
    }
    function EnableAutoComplete(who) {

        if (!who.hasClass("AutoAdded")) {
            who.autocomplete({
                source: 'xhr/cutomerReturn?is_actual='+(is_actual ? 1 : 0)+'&is_vendor='+(IsVendor ? 1 : 0),
                minLength: 1,
                select: function (event, ui) {
                    $("#Invoice_Purchase_ID").val(ui.item.Invoice_ID)
                    $("#Invoice_Purchase_ID").attr("data-id",ui.item.Auto_ID)
                    return false;
                }
            }).autocomplete("instance")._resizeMenu = function (ul, items) {
                this.menu.element.outerWidth((who.width()) + parseFloat(who.css("padding-left")) + parseFloat(who.css("padding-right")) + 2);
            }
            who.autocomplete("instance")._renderItem = function (ul, item) {
                var MyType = item.Inv_Info;
                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()
            }
        })
    }

</script>
