<?php // echo"<pre>";die(print_r($collector_data['products'])); ?>
<style type="text/css">
    #OrderTable thead tr th {
        color:#555;
        border-bottom: 1px solid rgba(0,0,0,0.1);
    }
    #OrderTable tbody tr td input{
        width:100%;
        margin:0;
        border: 1px solid rgba(0,0,0,0.02);
        background-color:#e5e5e5;
    }
    #OrderTable tbody tr td {
        border:0;
        padding:3px 1px;
        position:relative;
    }
    #OrderTable 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;
    }
    #OrderTable .Hint{
        position: absolute;
        font-size: 10px;
        font-weight: bold;
        height: 20px;
        line-height: 20px;
        bottom: 2px;
        right: 4px;
        color: rgb(153, 153, 153);
    }
    #OrderTable .TotalTD{
        width: auto;
        display: inline-block;
        text-align: center;
        font-size: 20px;
        font-weight: bold;
    }
    #OrderTable .Disc{
        width:70px;
    }
    #OrderTable 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:#ed9421 !important;
    }
    .datepicker table tr td.day:hover {
        background: #ed9421 !important;
        color:#fff;
    }
    .datepicker table tr td.active {
        background-color: #ed9421 !important;
    }
    .datepicker thead tr .datepicker-switch {
        color: #ed9421  !important;
        font-size: 13px;
    }
    .datepicker table tr td span.active {
        background-color: #ed9421 !important;
    }
    .datepicker table tr td span:hover {
        background-color: #ed9421 !important;
        color:#fff;
    }
    datepicker thead tr .next:before, .datepicker thead tr .prev:before {
        color: #ed9421 !important;
        font-family: 'FontAwesome';
        font-size: 10px;
    }
    .datepicker thead tr .next:before, .datepicker thead tr .prev:before {
        color: #ed9421 !important;
        font-family: 'FontAwesome';
        font-size: 10px;
    }
    .select2-container > .select2-choice{
        background-color: #e5e5e5;
        /*        width: 150px;*/
    }

    .InputSpinner{
        width: 60px;
    }
    .InputSpinner > .form-control{
        border-color: rgb(221, 221, 221);
        height:36px;
        margin:0;
        padding:0;
        text-align: center;
    }
    .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;
    }

</style>
<script src="<?php echo THEME_PATH; ?>plugins/jquery-validation/js/jquery.validate.min.js"></script>
<!--<div id="OrderDisabler" 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>-->
<?php echo Forms::ModalLoader('OrderDisabler'); ?>
<form method="POST" action="" onsubmit="return false" id="OrderForm">
    <div class="container-fluid container-fixed-lg">
        <div class="panel panel-default">
            <div class="panel-body">
                 <?php
                if ($is_main_transfer != 0) {
                    ?>
                    <div class="alert alert-danger" role="alert">
                        <button class="close" data-dismiss="alert"></button>
                        <strong>Danger: </strong>you can not edit this transfer! 
                        <br>
                        This transfer is transfered to the main branch.
                    </div>
                    <?php
//    die();
                }?>
                <div id="OrderSuccess" class="hidden"></div>
                <div class="invoice padding-50 sm-padding-10">
                    <div class="container-sm-height">
                        <div class="">
                            <div class="col-md-6  sm-no-padding">
                                <h2 class="font-montserrat all-caps hint-text"><?php print CommonLanguage::getMessage($is_confirmed ? 'Transfer_Goods' : 'Request_Order'); ?></h2>
                                <div>
                                    <input type="hidden" value="<?php echo $IsEdit ? $edit_arr['Request'][0]['Status_ID'] : '' ?>" id="Status_ID"/>

                                    <div class="form-group col-md-6 <?php echo $is_confirmed ? 'pull-right' : '' ?>">
                                        <label><strong><?php print CommonLanguage::getMessage($is_confirmed ? 'To' : 'From'); ?></strong><span class="red-star">*</span></label>
                                        <div class="input-group m-b">
                                            <span class="input-group-btn">
                                                <button type="button" class="btn" style="width:0 ;background-color:#ed9421" ><i class="fa fa-compass"style="color:#fff;margin-left:-7px"></i> </button> </span>
                                            <select name="Depot_Name1" id="Depot_Name1" class="full-width" data-init-plugin="select2">
                                                <option value="" disabled selected ><?php echo CommonLanguage::getMessage('select'); ?></option>
                                                <?php foreach ($All_Depots_Not_PIC as $depot): ?>
                                                    <option value="<?php echo $depot['Depot_ID']; ?>"   <?php echo $IsEdit ? ($edit_arr['Request'][0]['Request_From'] == $depot['Depot_ID'] ? 'selected' : '') : '' ?>              ><?php echo $depot['Depot_Name']; ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="form-group col-md-6 ">
                                        <label><strong><?php print CommonLanguage::getMessage($is_confirmed ? 'From' : 'To') ?></strong><span class="red-star">*</span></label>
                                        <div class="input-group m-b">
                                            <span class="input-group-btn">
                                                <button type="button" class="btn" style="width:0 ;background-color:#ed9421" ><i class="fa fa-compass"style="color:#fff;margin-left:-7px"></i> </button> </span>
                                            <select name="Depot_Name2" id="Depot_Name2" class="full-width" data-init-plugin="select2" <?php echo smc_session()['transfer_from_current_depot_only'] ? 'disabled' : ''?>>
                                                <option value="" disabled selected ><?php echo CommonLanguage::getMessage('select'); ?></option>
                                                <?php foreach ($All_Depots_Not_PIC as $depot): ?>
                                                    <option value="<?php echo $depot['Depot_ID']; ?>" <?php echo $IsEdit ? ($edit_arr['Request'][0]['Request_To'] == $depot['Depot_ID'] ? 'selected' : '') : '' ?>  ><?php echo $depot['Depot_Name']; ?></option>
                                                <?php endforeach; ?>
                                            </select>

                                        </div>
                                    </div>
                                    <div class="clearfix"></div>
                                </div>
                                <br>
                            </div>
                            <div class="col-md-4  pull-right" style="vertical-align: top;">
                                                                <div class="sm-m-t-20">
                                                                    <h4><?php print CommonLanguage::getMessage('Request'); ?> # <?php echo $IsEdit ? $edit_arr['Request'][0]['req_id'] : '--' ?></h4>
                                                                </div>
                                <div  class="form-group form-group-default input-group">
                                    <label><?php print CommonLanguage::getMessage('Date'); ?></label>
                                    <input id="loading_order_date" name="loading_order_date" class="form-control" value="<?php echo $IsEdit ? $edit_arr['Request'][0]['Request_Date'] : ($today); ?>" />
                                    <span class="input-group-addon bg-complete-darker"><i class="fa fa-calendar"></i></span>
                                </div>
                                <div  class="form-group form-group-default input-group">
                                    <label><?php print CommonLanguage::getMessage('Delivery_Date') ?></label>
                                    <input id="Delivery_Date" name="Delivery_Date" class="form-control" value="<?php echo $IsEdit ? $edit_arr['Request'][0]['Delivery_Date'] : ($today); ?>"/>
                                    <span class="input-group-addon bg-complete-darker"><i class="fa fa-calendar"></i></span>
                                </div>

                                <br>
                            </div>
                        </div>
                    </div>
                    <div>
                        <div class="clearfix"></div>
                    </div>
                    <div class="table-responsive">
                        <table class="table m-t-50" id='OrderTable'>
                            <thead>
                                <tr>
                                    <th class="text-center"><?php print CommonLanguage::getMessage('Code'); ?></th>
                                    <th class="text-center"><?php print CommonLanguage::getMessage('Name'); ?></th>
                                    <th class="text-center"><?php print CommonLanguage::getMessage('Quantity'); ?></th>
                                    <th class="text-center"><?php print CommonLanguage::getMessage('UOM'); ?></th>

                                </tr>
                            </thead>
                            <tbody>

                                <?php
                                if ($IsEdit || $is_data_collector) {
                                    $data_arr = $IsEdit ? $edit_arr['Request'] : $collector_data['products'];

                                    foreach ($data_arr as $item) {
                                        $uoms = $is_data_collector ? explode('/', $item['Product_UOM']) : array();
                                        ?>

                                        <tr data-conv="<?php echo $item[$is_data_collector ? 'uom_con' : 'conversion_amount'] ?>" data-qty="<?php echo $is_data_collector ? '' : $item['total_default_quantity'] ?>"  data-id="<?php echo $item['Product_ID'] ?>" >
                                            <td><input type="text" class="form-control AutoComplete CODE" value = "<?php echo $item[$is_data_collector ? 'Code' : 'Product_Code'] ?>"></td>
                                            <td><input type="text" class="form-control AutoComplete ProductName" value = "<?php echo $item[$is_data_collector ? 'Name' : 'Product_Name'] ?>"></td>
                                            <td><span class="Hint"></span><input type="text" class="form-control Quantity isnumber" value = "<?php echo $item[$is_data_collector ? 'Item_Quantity_Current' : 'Current_Quantity'] ?>"></td>
                                            <td>
                                                <?php if ($is_data_collector) { ?>
                                                    <select required name="UOM_ID"  class="full-width UOM_ID " data-init-plugin="select2">
                                                        <?php for ($i = 0; $i < count($uoms); $i++) { ?>
                                                            <option value="<?php echo $uoms[$i]; ?>" <?php echo $uoms[$i] == $item['UOM_ID'] ? 'selected' : '' ?>><?php echo $all_uom[$uoms[$i]]['UOM_Name']; ?></option>
                                                        <?php } ?>
                                                    </select>
                                                <?php } else { ?>
                                                    <select required name="UOM_ID"  class="full-width UOM_ID " data-init-plugin="select2">
                                                        <?php foreach ($edit_arr['uoms'][$item['Product_ID']] as $uom): ?>
                                                            <option value="<?php echo $uom; ?>"  <?php echo $IsEdit ? ($item['Request_UOM'] == $uom ? 'selected' : '') : '' ?>        ><?php echo $all_uom[$uom]['UOM_Name']; ?></option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                <?php } ?>
                                            </td>

                                        </tr>
                                        <?php
                                    }
                                } else {
                                    ?>



                                    <tr>

                                        <td><input type="text" class="form-control AutoComplete CODE"></td>
                                        <td><input type="text" class="form-control AutoComplete ProductName"></td>
                                        <td><span class="Hint"></span><input type="text" class="form-control Quantity isnumber digits"></td>
                                        <td><select required name="UOM_ID"  class="full-width UOM_ID " data-init-plugin="select2">
                                                <?php foreach ($all_uom as $uom): ?>
                                                    <option value="<?php echo $uom['UOM_ID']; ?>"><?php echo $uom['UOM_Name']; ?></option>
                                                <?php endforeach; ?>
                                            </select></td>
                                    </tr>
                                <?php } ?>
                            </tbody>
                        </table>
                    </div>
                    <br>
                    <div class="container-sm-height" >
                        <?php  if(!($is_main_transfer != 0 )){?>
                        <button class=" btn  btn-cons m-b-10 pull-right" id="OrderSubmitButton" style="color:#fff;background-color:#ed9421;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>
                        <?php }?>
                    </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>
<select required id="Select_UOM" name="Select_UOM"  class="full-width Select_UOM hidden" data-init-plugin="select2">
    <?php foreach ($all_uom as $uom): ?>
        <option value="<?php echo $uom['UOM_ID']; ?>"><?php echo $uom['UOM_Name']; ?></option>
    <?php endforeach; ?>
</select>
<script>
    var Failed_Submit = <?php echo json_encode(CommonLanguage::getMessage('Failed_Submit')); ?>,
            Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')); ?>,
            Required_Fields = <?php echo json_encode(CommonLanguage::getMessage('Required_Fields')); ?>,
            have_not_saved = <?php echo json_encode(CommonLanguage::getMessage('have_not_saved')); ?>,
            CheckSubmit = true,
            IsEditMode = <?php echo $IsEdit ? "true" : "false"; ?>,
            is_data_collector = <?php echo $is_data_collector ? "true" : "false"; ?>,
            ID_Edit = IsEditMode ? <?php echo json_encode($id); ?> : '',
            file_id = is_data_collector ? <?php echo json_encode($file_id); ?> : '',
            is_confirmed = <?php echo $is_confirmed ? 1 : 0 ?>,
            user_depot = <?php echo json_encode(smc_session()['user_accounts']['depot_id']); ?>,
            negative_sales = <?php echo json_encode(smc_session()['negative_sales']); ?>;

    $(function () {

        if (IsEditMode) {
            $("#OrderTable tbody tr").each(function () {
                EnableAutoComplete($(".AutoComplete.CODE", $(this)));
                EnableAutoComplete($(".AutoComplete.ProductName", $(this)));
            });
        } else {
            EnableAutoComplete($("#OrderTable .AutoComplete.CODE"));
            EnableAutoComplete($("#OrderTable .AutoComplete.ProductName"));
        }
        $("#loading_order_date,#Delivery_Date").datepicker({autoclose: true})
        $("#OrderTable tbody").delegate("> tr input", "keydown", function (e) {
            var me = $(this)
            if (e.which == 8) {
                if (me.val() == "" && !me.hasClass("CODE")) {
                    me.parents("td").prev().find("input").focus()
                } else if (me.val() == "" && me.hasClass("CODE")) {
                    if (me.parents("tr").prev()) {
                        me.parents("tr").prev().find(".Disc").focus()
                    }
                }
            }
        })
        $("#OrderTable").on("change", "select.UOM_ID", function () {
            var me = $(this).parents("tr");

            var UOMData = {pid: $(this).parents("tr").attr("data-id"),
                uid: $(this).val(), depot_id: $("#Depot_Name2").val()};

            $.ajax({
                url: "InventoryAjax/ReturnProductUOMPriceCon",
                data: UOMData,
                dataType: 'json',
                complete: function (v1, v2) {
                    if (v2 == "success") {
                        me.attr('data-conv', v1.responseJSON['conversion_amount'])
//                        if (IsSalesMode) {
//                            me.find("input.UnitPrice").val(v1.responseJSON['Product_Price'])
//                            me.find("input.UnitPrice").val(parseFloat(ConvertCurrency2(v1.responseJSON['Product_Price'], v1.responseJSON['Currency_ID'], $("#CurrencyDropDown input").val())).toFixed(3))
//                        }
                        me.find("input.Quantity").prev().text(AddCommas(parseFloat(v1.responseJSON['qty']).toFixed(3)) + " in stock")
//                        setTimeout('UpdateTable()', 100)
                    }
                }
            })


        })
        $("#Depot_Name2").on("change", function () {
//            alert('here')
            var item_arr = {items: [], depot_id: $("#Depot_Name2").val()}
            $("#OrderTable tbody tr").each(function (e) {
                if ($(this).attr("data-id") != 0) {
                    item_arr.items.push($(this).attr("data-id"))
                }
            })
            $.ajax({
                url: "InventoryAjax/ReturnQtyPerDepot",
                data: item_arr,
                dataType: 'json',
                complete: function (v1, v2) {
                    if (v2 == "success") {
                        var Data = (v1.responseJSON);
                        for (var i = 0; i < Data.length; i++) {
                            var me = $("#OrderTable tbody tr[data-id='" + Data[i]['Product_ID'] + "']"),
                                    tr_conv = parseFloat(me.attr("data-conv"));
//                            console.log(tr_conv)

                            me.find(".Quantity").prev().text(AddCommas(parseFloat(Data[i]['qty'] / tr_conv).toFixed(3) || 0) + " in stock")
                            me.attr('data-qty', parseFloat(Data[i]['qty']))
                        }
                    }
                }
            })
        })
        if (!IsEditMode) {
            if (is_confirmed) {
                $("#Depot_Name2").val(user_depot).select2()
                $("#Depot_Name2").trigger("change")
            } else
                $("#Depot_Name1").val(user_depot).select2()
        }
        $("#OrderTable tbody").delegate("> tr input", "keyup", function (e) {
            CheckSubmit = false;
            var me = $(this), Parent = me.parents("tbody"), IsLastOneEmpty = true, TR = me.parents("tr");

            $("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() <= $("#OrderTable tbody tr").length - 2) {
                            me.parents("tr").prev().find(".Disc").focus()
                            $(this).remove();
                        }
                    }
                }
            })
            if (is_confirmed) {
                if (me.hasClass("Quantity")) {
                    if (parseFloat(me.val()) * parseFloat(TR.attr('data-conv')) > parseFloat(TR.attr('data-qty'))) {
                        me.addClass("wrong")

                    } else {
                        me.removeClass("wrong")
                    }

                }
            }
            $("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.CODE", ClonedRow).removeClass("AutoAdded"));
                EnableAutoComplete($(".AutoComplete.ProductName", ClonedRow).removeClass("AutoAdded"));
                $(".Hint,.Total", ClonedRow).html("")
                $("input", ClonedRow).removeClass("wrong")
                $(".select2-container", ClonedRow).empty().remove()
                $(".UOM_ID", ClonedRow).empty().html($("#Select_UOM").html()).show().select2()
                ClonedRow.removeAttr('data-id data-qty data-conv')
                //                $(".Request_UOM",ClonedRow).show().select2()
            }
        })
        $("#OrderSubmitButton").on("click", ApplyPostMethod);
    })
    function EnableAutoComplete(who) {
        if (!who.hasClass("AutoAdded")) {
            who.autocomplete({
                source: function (request, response) {
                    var depot_id = $("#Depot_Name2").val();
                    //                    var SEL = $("select.UOM_ID", this.element.parents("tr")).val();
                    $.getJSON('xhr/getProducts?cmd=' + (who.hasClass("CODE") ? "1" : "2") + '&depot_id=' + depot_id, request, function (s, status, xhr) {
                        response(s);
                    });
                },
                minLength: 0,
                select: function (event, ui) {
                    var TR = $(this).parents("tr");
                    TR.attr("data-id", ui.item.ID)
                    TR.attr("data-qty", ui.item.Quantity)
                    TR.attr("data-conv", 1)
                    TR.find("input.CODE").val(ui.item.Bar_Code + '-' + ui.item.Price + '-' + ui.item.Currency_Symbol)
                    TR.find("input.ProductName").val(ui.item.Name)
                    TR.find("input.Quantity")/*.focus()*/.prev().text(AddCommas(parseFloat(ui.item.Quantity).toFixed(3)) + " in stock")
                    $("select[name=UOM_ID]", TR).empty().html($("#Select_UOM").html()).select2()
                    TR.find("select[name=UOM_ID] > option[value=" + ui.item.UOM_ID + "]").attr("selected", true)
                    TR.find("select[name=UOM_ID]").select2()
                    var units_arr = ui.item.Product_UOM.split("/");
                    $("select[name=UOM_ID] > option", TR).each(function () {
                        if ($.inArray($(this).attr("value"), units_arr) === -1) {
                            $(this).remove()
                        }
                    })
                    return false;
                }
            }).focus(function () {
                $(this).autocomplete("search", $(this).val());
            }).autocomplete("instance")._resizeMenu = function (ul, items) {
                this.menu.element.outerWidth((who.width() * (this.element.hasClass("CODE") ? 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("CODE") ? (item.Bar_Code + '-' + item.Price + '-' + item.Currency_Symbol) : (item.Name + '-' + item.Price + '-' + item.Currency_Symbol);
                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() {
        $("#OrderSuccess").attr("class", "hidden");
        $("#OrderForm").validate()
        if ($("#OrderForm").valid()) {
            var IsValidated = true,
                    Data = {
                        Request_From: $("#Depot_Name1").val(),
                        Request_To: $("#Depot_Name2").val(),
                        Delivery_Date: $("#Delivery_Date").val(),
                        Request_Date: $("#loading_order_date").val(),
                        is_confirmed: is_confirmed,
                        is_data_collector: is_data_collector,
                        Products: []
                    };
            if (!$("#Depot_Name1").val() || !$("#Depot_Name2").val()) {
                $("#OrderSuccess").attr("class", "alert alert-danger").html(Required_Fields)
                $(document.body).animate({scrollTop: 0}, 800)
                return false;
            }
            $("#OrderTable tbody tr").each(function (e) {
                var me = $(this);

                if (me.find(".Quantity").val() != '' && me.find(".ProductName").val() != '') {
                    Data.Products.push({
                        UOM_ID: me.find("select.UOM_ID").val(),
                        Product_ID: me.attr("data-id"),
                        Request_Qty: me.find(".Quantity").val(),
                        Request_UOM: 0
                    });
                    me.find(".CODE,.ProductName,.Quantity").each(function () {
                        if ($.trim($(this).val()) == "" || ($(this).hasClass("isnumber") && $.trim($(this).val()).match(/^\s*?([\d]+(\.\d+)?|\.\d{1,2})\s*$/) == null)) {
                            $(this).addClass("wrong")
                            CheckSubmit = false;
                            IsValidated = false;
                        } else {
                            $(this).removeClass("wrong")
                        }

                        if (is_confirmed == 1 && negative_sales == 0) {
//                            console.log(parseFloat($(this).val())+' >'+ parseFloat($(this).parents('tr').attr('data-qty')))
                            if ($(this).hasClass("Quantity") && parseFloat($(this).val()) > parseFloat($(this).parents('tr').attr('data-qty'))) {
//                         console.log('here')
                                IsValidated = false;
                                $(this).addClass("wrong").focus()
                            } else {
                                $(this).removeClass("wrong")
                            }

                        }
                    })

                }
            })
//            console.log(IsValidated)
//            return false;
            if (IsEditMode) {
                Data.Request_ID = ID_Edit;
                Data.Status_ID = $("#Status_ID").val();
            }
            if (is_data_collector) {
                Data.file_id = file_id;
            }
            if (!IsValidated)
                return;
            $("#OrderDisabler").removeClass('hidden');
            $.ajax({
                url: IsEditMode ? "StockAjax/editRequestOrderAjax" : "StockAjax/RequestOrderAjax",
                method: "POST",
                data: Data,
                complete: function (v1, v2) {
                    if (v2 == "success" && v1.responseText == 'OK') {
                        $("#OrderSuccess").attr("class", "alert alert-success").html(Submitted_Successfully)
                        $("#OrderSubmitButton").addClass('disabled')
                        CheckSubmit = true;
                    } else {
                        $("#OrderSuccess").attr("class", "alert alert-danger").html(Failed_Submit)
                        CheckSubmit = true;
                    }
                    $(document.body).animate({scrollTop: 0}, 800)
                    $("#OrderDisabler").addClass('hidden');
                }
            })
        } else {
            $(document.body).animate({scrollTop: 0}, 800)
        }
    }



    $(document).ready(function () {
        window.onbeforeunload = function (e) {
            if (!CheckSubmit) {
                var message = have_not_saved, e = e || window.event;
                if (e) {
                    e.returnValue = message;
                }
                return message;
            }
        }

    });
</script>
