<?php 
if ($IsEdit && $check_lock != '') { ?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong>Danger: </strong><?php echo $check_lock ?>
    </div>
    <?php
    return;
}
if ($IsEdit && empty($edit_arr)) { ?>
    <!--<div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong>Danger: </strong>you can not edit this request! 
        <br>
        This request is not available.
    </div>-->
    <?php
    die();
}
?>
<style type="text/css">
    #damage_table thead tr th {
        color:#555;
        border-bottom: 1px solid rgba(0,0,0,0.1);
    }
    #damage_table tbody tr td input{
        width:100%;
        margin:0;
        border: 1px solid rgba(0,0,0,0.02);
        background-color:#e5e5e5;
        padding: 5px 9px 12px;
        height: 40px;
    }
    #damage_table tbody tr td {
        border:0;
        padding:3px 1px;
        position:relative;
    }
    #damage_table 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;
    }
    #damage_table .Hint{
        position: absolute;
        font-size: 10px;
        display: block;
        font-weight: bold;
        height: 12px;
        line-height: 11px;
        cursor: default;
        background: #ccc;
        padding: 0 2px;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
        bottom: 3px;
        right: 1px;
        left: 1px;
        color: #4c0870;
    }
    #damage_table .TotalTD{
        width: auto;
        display: inline-block;
        text-align: center;
        font-size: 20px;
        font-weight: bold;
    }
    #damage_table .Disc{
        width:70px;
    }
    #damage_table 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;
    }
    #damage_table .select2-container .select2-choice {
        background-image: none;
        border-radius: 2px;
        border: 1px solid rgba(0,0,0,0.07);
        padding: 5px 9px 16px;
        transition: border 0.2s linear 0s;
        height: 40px;
        background-color: #e5e5e5;
        /*width: 150px;*/
    }
</style>
<script src="<?php echo THEME_PATH; ?>plugins/jquery-validation/js/jquery.validate.min.js"></script>
<script src="<?php echo THEME_PATH; ?>plugins/jQuery-Scanner-Detection-master/jquery.scannerdetection.js?v=<?php echo trusto_VERSION; ?>"></script>
<script src="<?php echo THEME_PATH; ?>plugins/jQuery-Scanner-Detection-master/jquery.scannerdetection.compatibility.js"></script>

<?php echo Forms::ModalLoader('damage_loader'); ?>
<form method="POST" action="" onsubmit="return false" id="damage_form">
    <div class="container-fluid container-fixed-lg">
        <div class="panel panel-default">
            <div class="panel-body">

                <div id="damage_alert" class="hidden"></div>
                <div class="invoice padding-20 sm-padding-10">
                    <div class="container-sm-height">
                        <div class="row">
                            <h2 class="font-montserrat all-caps hint-text"><?php echo $title; ?></h2>
                            <div class="col-md-6  sm-no-padding">
                                <div class="row ">
                                    <div class="form-group col-md-6 " style="padding-left:7px;">
                                        <label><strong><?php print CommonLanguage::getMessage('customer') ?></strong></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>
                                            <input type="hidden" id="customer_id" name="customer_id" class="full-width" value="<?php echo $IsEdit ? $edit_arr['main']['customer_id'] : ''; ?>" data-select-name="<?php echo ($IsEdit && !empty($edit_arr['main']['Customer_Name'])) ? $edit_arr['main']['Customer_Name'] : ''; ?>" />
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4  pull-right" style="vertical-align: top;">
                                <div class="sm-m-t-20">
                                    <h4><?php print CommonLanguage::getMessage('Damage'); ?> # <?php echo $IsEdit ? $edit_arr['main']['damage_nb'] : '--' ?></h4>
                                </div>
                                <div  class="form-group form-group-default input-group">
                                    <label><?php print CommonLanguage::getMessage('Date'); ?><span class="red-star">*</span></label>
                                    <input id="damage_date" name="damage_date" required class="form-control" value="<?php echo $IsEdit ? $edit_arr['main']['damage_date'] : ($today); ?>"   />
                                    <span class="input-group-addon bg-complete-darker"><i class="fa fa-calendar"></i></span>
                                </div>
                                <div  class="form-group  p-l-0 p-r-5" >
                                    <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:#4c0870;cursor:pointer"></span>
                                    <input required id="Depot_Name2" name="Depot_Name2" class="full-width Depot_Name2" type="hidden"  value="<?= ($IsEdit) ? $edit_arr['main']['Depot_ID'] : ((smc_session()['user_accounts']['depot_id'] ? smc_session()['user_accounts']['depot_id'] : smc_session()['default_depot_id'])) ?>" data-select-name='<?= json_encode(($IsEdit) ? $edit_arr['main']['Depot_Name'] : ((smc_session()['user_accounts']['Depot_Name'] ? smc_session()['user_accounts']['Depot_Name'] : smc_session()['default_depot_name']))) ?>' />

                                </div>
                            </div>
                        </div>
                    </div>
                    <div>
                        <div class="clearfix"></div>
                    </div>
                    <div class="table-responsive">
                        <table class="table m-t-50" id='damage_table'>
                            <thead>
                                <tr>
                                    <th class="text-center"><?php print CommonLanguage::getMessage('Category'); ?></th>
                                    <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 echo (smc_session()['default_setting']['activate_expiry_date'] == 0) ? 'hidden' : ''; ?>"><?php print CommonLanguage::getMessage('Expiry_Date'); ?></th>
                                    <th class="text-center"><?php print CommonLanguage::getMessage('quantity'); ?></th>
                                    <th class="text-center"><?php print CommonLanguage::getMessage('UOM'); ?></th>
                                    <th class="text-center"><?php print CommonLanguage::getMessage('note'); ?></th>
                                    <th class="text-center <?php echo smc_session()['default_setting']['activate_product_lot_nb'] ? '' : 'hidden' ?>" style="width:7%"><?php print CommonLanguage::getMessage('lot'); ?></th>
                                    <th class="text-center <?php echo smc_session()['default_setting']['activate_product_serial_nb'] ? '' : 'hidden' ?> " style="width:7%"><?php print CommonLanguage::getMessage('serial'); ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                if ($IsEdit) {
                                    $data_arr = $edit_arr['details'];
                                    foreach ($data_arr as $item) {
                                        ?>
                                        <tr data-is-lot="<?php echo $item['is_lot'] ?>"
                                            data-is-serial="<?php echo $item['is_serial'] ?>" 
                                            data-conv="<?php echo $item['conversion_amount'] ?>" 
                                            data-qty="<?php echo $item['total_default_quantity'] ?>"  
                                            data-id="<?php echo $item['product_id'] ?>" 
                                            data-expiry="<?php echo $item['is_expiry'] ?>"
                                            data-is-service="<?php echo $item['is_service'] ?>">
                                            <td><input type="hidden" class="full-width  cat_id" value="<?php echo $item['Category_ID'] ?>" data-select-name="<?php echo $item['Cat_Name'] ?>" /></td>
                                            <td><input type="text" class="form-control AutoComplete CODE input-barcode-scan" value = "<?php echo $item['Product_Code'] ?>"   ></td>
                                            <td><input type="text" class="form-control AutoComplete ProductName" value = "<?php echo $item['Product_Name'] ?>"   ><span class="Hint"></span></td>
                                            <td class="<?php echo (smc_session()['default_setting']['activate_expiry_date'] == 0 ) ? 'hidden' : ''; ?>"><input type="hidden" class="full-width  expiry_date  <?php echo $item['is_expiry'] ? '' : 'hidden' ?>" value = "<?php echo $item['expiry_date'] ?>" data-select-name="<?php echo $item['expiry_date'] ?>"></td>
                                            <td><input type="text" class="form-control Quantity isnumber" value = "<?php echo $item['current_quantity'] ?>" ><span class="Hint"></span></td>
                                            <td>

                                                <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['uom_id'] == $uom ? 'selected' : '') : '' ?>        ><?php echo $all_uom[$uom]['UOM_Name']; ?></option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </td>
                                            <td class="" >
                                                <input type="text" class="full-width detail_note"  value="<?php echo $item['detail_note']; ?>" />
                                            </td>
                                            <td class=" <?php echo smc_session()['default_setting']['activate_product_lot_nb'] ? '' : 'hidden' ?>" >
                                                <input type="hidden" class="full-width lot_nb hidden"  value="<?php echo $item['lot_nb']; ?>" data-select-name="<?php echo $item['lot_nb']; ?>"/>
                                            </td>
                                            <td class="text-center  <?php echo smc_session()['default_setting']['activate_product_serial_nb'] ? '' : 'hidden' ?>" >
                                                <input type="hidden" class="full-width serial_nb hidden" value="<?php echo $item['serial_nb']; ?>" data-select-name="<?php echo $item['serial_nb']; ?>"/>
                                            </td>
                                        </tr>
                                        <?php
                                    }
                                } else {
                                    ?>
                                    <tr>
                                        <td><input type="hidden" class="full-width cat_id" /></td>
                                        <td><input type="text" class="form-control AutoComplete CODE input-barcode-scan"></td>
                                        <td><input type="text" class="form-control AutoComplete ProductName"><span class="Hint"></span></td>
                                        <td class="<?php echo (smc_session()['default_setting']['activate_expiry_date'] == 0) ? 'hidden' : ''; ?>"><input  name="expiry_date"  class="full-width expiry_date hidden" type="hidden"/></td>
                                        <td><input type="text" class="form-control Quantity isnumber digits"><span class="Hint"></span></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>
                                        <td class="" >
                                            <input type="text" class="full-width detail_note"/>
                                        </td>
                                        <td class=" <?php echo smc_session()['default_setting']['activate_product_lot_nb'] ? '' : 'hidden' ?>" >
                                            <input type="hidden" class="full-width lot_nb hidden" />
                                        </td>
                                        <td class="text-center  <?php echo smc_session()['default_setting']['activate_product_serial_nb'] ? '' : 'hidden' ?>" >
                                            <input type="hidden" class="full-width serial_nb hidden"  />
                                        </td>
                                    </tr>
                                <?php } ?>
                            </tbody>
                        </table>
                    </div>
                    <br>
                    <div class="container-sm-height form-group" >
                        <label><?php echo CommonLanguage::getMessage('note') ?></label>
                        <textarea id="damage_note"  class="form-control NoteTextArea"  aria-invalid="false" ></textarea>
                    </div>
                    <div class="container-sm-height" >
                        <button class=" btn  btn-cons m-b-10 pull-right" id="damage_submit" 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>
                        <button class=" btn btn-danger btn-cons m-b-10 pull-right disabled" id="PrintBtn" style="padding-top: 10px;top: 20px;min-width:253px;" type="button"><i class="fa fa-print"></i> <span class="bold"><?php print CommonLanguage::getMessage('print'); ?></span></button>
                    </div>
                    <hr>
                </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"; ?>,
            ID_Edit = IsEditMode ? <?php echo json_encode($id); ?> : '',
            is_actual =<?php echo json_encode($is_actual); ?>,
//            negative_sales = <?php // echo json_encode(smc_session()['negative_sales']);           ?>,
            negative_sales = 1,
            activate_lot = <?php echo json_encode(smc_session()['default_setting']['activate_product_lot_nb']); ?>,
            activate_serial = <?php echo json_encode(smc_session()['default_setting']['activate_product_serial_nb']); ?>,
//            request_id,
            unique_id = <?php echo json_encode(!$IsEdit ? $unique_id : '') ?>;
    var damage_nb = <?php echo json_encode(CommonLanguage::getMessage('damage_nb')); ?>;

    $(function () {
        build_select2($(".Depot_Name2"), "xhr/depotSearch")

        build_select2($("#customer_id"), "xhr/customerSearch");
        //        searchScannedItem('6251159044042101', $("#damage_table tbody tr:eq(0)"));
        $(window).ready(function (e) {
            $(window).scannerDetection({
                focusInputClass: 'input-barcode-scan', minLength: default_barcode_length
            });
            $(window).bind('scannerDetectionComplete', 'input.CODE', function (e, data) {
                ID = data.string;
                var parent = $(data.my_event.target).parents('tr')
                searchScannedItem(ID, parent);
            }).bind('scannerDetectionError', function (e, data) {
            }).bind('scannerDetectionReceive', function (e, data) {
            });
        });
       $("#PrintBtn").on("click", function () {
           var myurl = "Stock/view_damage/" + request_id;
           console.log('myurl'+myurl);
            printExternal(myurl);
       });
        build_select2($('.cat_id'), "xhr/catSearch");
        if (IsEditMode) {
            $("#damage_table tbody tr").each(function () {
                EnableAutoComplete($(".AutoComplete.CODE", $(this)));
                EnableAutoComplete($(".AutoComplete.ProductName", $(this)));
                build_select2($("input.expiry_date", $(this)), function () {
                    return 'xhr/get_product_expiry?product_id=' + this.parents('tr').attr('data-id') + '&depot=' + $("#Depot_Name2").val();
                });
                if ($(this).attr('data-is-lot') == 1 && activate_lot == 1) {
                    $("input.lot_nb", $(this)).removeClass("hidden");
                    build_select2($("input.lot_nb", $(this)), function () {
                        return 'xhr/get_product_lot?product_id=' + this.parents('tr').attr('data-id') + '&depot=' + $("#Depot_Name2").val();
                    });

                } else
                    $("input.lot_nb", $(this)).addClass("hidden");

                if ($(this).attr('data-is-serial') == 1 && activate_serial == 1) {
                    $("input.serial_nb", $(this)).removeClass("hidden");
                    build_select2($("input.serial_nb", $(this)), function () {
                        return 'xhr/get_product_serial?product_id=' + this.parents('tr').attr('data-id') + '&depot=' + $("#Depot_Name2").val();
                    });
                } else
                    $("input.serial_nb", $(this)).addClass("hidden");
            });
        } else {
            EnableAutoComplete($("#damage_table .AutoComplete.CODE"));
            EnableAutoComplete($("#damage_table .AutoComplete.ProductName"));
        }
        $("#damage_date").datepicker({autoclose: true})
        $("#damage_table 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()
                    }
                }
            }
        })
        $("#damage_table").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']);
                        me.find("input.Quantity").next().text(AddCommas(parseFloat(v1.responseJSON['qty']).toFixed(3)) + " in stock");
                    }
                }
            })
        })
        $("#Depot_Name2").on("change", function () {
            //            alert('here')
            var item_arr = {items: [], depot_id: $("#Depot_Name2").val()}
            $("#damage_table 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);
                        $.each(Data, function (index, value) {
                            var me = $("#damage_table tbody tr[data-id='" + value['Product_ID'] + "']"),
                                    tr_conv = parseFloat(me.attr("data-conv"));
                            me.find(".Quantity").next().text(AddCommas(parseFloat(value['qty'] / tr_conv).toFixed(3)) + " in stock");
                            me.find("input.ProductName").next().text(value['loc']);
                            me.attr('data-qty', parseFloat(value['qty']));
                        });
                    }
                }
            });
        });
//        if (!IsEditMode) {
//            if (is_confirmed) {
//                $("#Depot_Name2").val(user_depot).select2()
//                $("#Depot_Name2").trigger("change")
//            } else
//                $("#Depot_Name1").val(user_depot).select2()
//        }
        $("#damage_table 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() <= $("#damage_table 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("")
                ClonedRow.attr("data-is-service", 0)
                ClonedRow.attr("data-is-lot", 0)
                ClonedRow.attr("data-is-serial", 0)
                Parent.append(ClonedRow);
                EnableAutoComplete($(".AutoComplete.CODE", ClonedRow).removeClass("AutoAdded"));
                EnableAutoComplete($(".AutoComplete.ProductName", ClonedRow).removeClass("AutoAdded"));
                $(".Hint,.Total", ClonedRow).html("")
                $("input", ClonedRow).removeClass("wrong")
                $("input.lot_nb,input.serial_nb", ClonedRow).addClass("hidden")
                $(".select2-container", ClonedRow).empty().remove()
                $(".UOM_ID", ClonedRow).empty().html($("#Select_UOM").html()).show().select2()
                ClonedRow.removeAttr('data-id data-qty data-conv data-expiry data-prod-status')
                $(".expiry_date", ClonedRow).addClass('hidden');
                build_select2($(".expiry_date", ClonedRow), function () {
                    return 'xhr/get_product_expiry?product_id=' + this.parents('tr').attr('data-id') + '&depot=' + $("#Depot_Name2").val();
                });
                build_select2($("input.lot_nb", ClonedRow), function () {
                    return 'xhr/get_product_lot?product_id=' + this.parents('tr').attr('data-id') + '&depot=' + $("#Depot_Name2").val();
                });
                build_select2($("input.serial_nb", ClonedRow), function () {
                    return 'xhr/get_product_serial?product_id=' + this.parents('tr').attr('data-id') + '&depot=' + $("#Depot_Name2").val();
                });
                //                $(".Request_UOM",ClonedRow).show().select2()
                ClonedRow.find(".cat_id").show();
                ClonedRow.find(".cat_id").attr('data-select-name', '').val('')
                build_select2(ClonedRow.find(".cat_id"), 'xhr/catSearch');
            }
        })
        $("#damage_submit").on("click", ApplyPostMethod);


    })
    function EnableAutoComplete(who) {
        if (!who.hasClass("AutoAdded")) {
            who.autocomplete({
                source: function (request, response) {
                    var depot_id = $("#Depot_Name2").val(),
                            cat_id = who.parents('tr').find("input.cat_id").val(),
                            product_id = who.parents('tr').attr('data-id'),
                            product_status_id = who.parents('tr').attr('data-prod-status'),
                            status_cond = !IsEditMode ? '&Status_ID=1' : (product_status_id == 0 ? ('&is_edited=' + product_id) : '&Status_ID=1');
                    //                    var SEL = $("select.UOM_ID", this.element.parents("tr")).val();
                    $.getJSON('xhr/getProducts?cmd=' + (who.hasClass("CODE") ? "1" : "2") + '&depot_id=' + depot_id + '&cat_id=' + cat_id + status_cond, request, function (s, status, xhr) {
                        var response_length = Object.keys(s).length;
                        if (response_length == 1) {
                            $(who).trigger({type: 'keypress', which: 13});
                        }
                        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-expiry", ui.item.is_expiry)
                    TR.attr("data-prod-status", ui.item.Status_ID)
                    TR.attr("data-is-service", ui.item.is_service)
                    TR.attr("data-is-serial", ui.item.is_serial)
                    TR.attr("data-is-lot", ui.item.is_lot)
                    TR.attr("data-conv", 1)
                    TR.find("input.CODE").val(ui.item.Bar_Code + '-' + ui.item.Price)
                    TR.find("input.ProductName").val(ui.item.Name)

                    TR.find("input.Quantity").focus().next().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()
                    if (ui.item.is_expiry == 0)
                        TR.find("input.expiry_date").addClass("hidden")
                    else {
                        $("input.expiry_date", TR).removeClass("hidden")
                        build_select2($(".expiry_date", TR), function () {
                            return  'xhr/get_product_expiry?product_id=' + this.parents('tr').attr('data-id') + '&depot=' + $("#Depot_Name2").val();
                        });
                    }
                    if (ui.item.is_lot == 1 && activate_lot == 1) {
//                        console.log('here')
                        TR.find(".lot_nb").removeClass("hidden");
                        build_select2($(".lot_nb", TR), function () {
                            return 'xhr/get_product_lot?product_id=' + this.parents('tr').attr('data-id') + '&depot=' + $("#Depot_Name2").val();
                        });

                    } else
                        TR.find(".lot_nb").addClass("hidden");

                    if (ui.item.is_serial == 1 && activate_serial == 1) {
                        TR.find(".serial_nb").removeClass("hidden");
                        build_select2($(".serial_nb", TR), function () {
                            return 'xhr/get_product_serial?product_id=' + this.parents('tr').attr('data-id') + '&depot=' + $("#Depot_Name2").val();
                        });

                    } else
                        TR.find(".serial_nb").addClass("hidden");

                    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.ttc_price + ' ' + item.Currency_Symbol) : (item.Name + '-' + item.ttc_price + ' ' + item.Currency_Symbol)
                //                        $(this).focus().trigger({ type : 'keypress', which : 13 });
                return $("<li>").html("<table cellspacing='0' cellpadding='0'><tr><td class='OnlyText'>" + MyType + "</td></tr></table>").appendTo(ul)
            }
            who.addClass("AutoAdded")
        }
    }
    function ApplyPostMethod() {
        $("#damage_submit").addClass('disabled')
        $("#damage_alert").attr("class", "hidden");
        $("#damage_table tbody .wrong").removeClass("wrong")
        $("#damage_form").validate()
        if ($("#damage_form").valid()) {
            var IsValidated = true, is_empty_quantity = false,
                    Data = {
                        customer_id: $("#customer_id").val(),
                        damage_date: $("#damage_date").val(),
                        Depot_ID: $("#Depot_Name2").val(),
                        note: $("#damage_note").val(),
                        unique_id: unique_id,
                        is_actual: is_actual,
                        Products: []
                    };
            if (!$("#Depot_Name2").val() || !$("#damage_date").val()) {
                $("#damage_alert").attr("class", "alert alert-danger").html(Required_Fields)
                $("#damage_submit").removeClass('disabled')
                $(document.body).animate({scrollTop: 0}, 800)
                return false;
            }
            $("#damage_table tbody tr").each(function (e) {
                var me = $(this);
                if (me.find(".ProductName").val()) {
                    if (!me.find(".Quantity").val())
                        is_empty_quantity = true;
                }
                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"),
                        quantity: me.find(".Quantity").val(),
                        expiry_date: me.find("input.expiry_date").val(),
                        lot_nb: $("input.lot_nb", me).val(),
                        serial_nb: $("input.serial_nb", me).val(),
                        note: $("input.detail_note", me).val(),
                        is_service: me.attr("data-is-service"),
                    });
                    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 (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")
                            }
                        }
                    })
                    if (me.attr("data-expiry") == 1 && me.find("input.expiry_date").val() == '') {
                        me.find("input.expiry_date").addClass("wrong")
                        CheckSubmit = false;
                        IsValidated = false;
                    }
                    if (me.attr("data-is-serial") == 1 && me.find("input.serial_nb").select2("data") == null) {
                        me.find("input.serial_nb").addClass("wrong")
                        CheckSubmit = false;
                        IsValidated = false;
                    }
                    if (me.attr("data-is-lot") == 1 && me.find("input.lot_nb").select2("data") == null) {
                        me.find("input.lot_nb").addClass("wrong")
                        CheckSubmit = false;
                        IsValidated = false;
                    }
                }
            })
            //            console.log(IsValidated)
            //            return false;
            if (IsEditMode) {
                Data.damage_id = ID_Edit;
            }
            if (Data.Products.length == 0) {
                $("#damage_alert").attr("class", "alert alert-danger").html('<?php echo CommonLanguage::getMessage('input_option'); ?>')
                $("#damage_submit").removeClass('disabled')
                $(document.body).animate({scrollTop: 0}, 800)
                return;
            }
            if (is_empty_quantity) {
                $("#damage_alert").attr("class", "alert alert-danger").html('<?php echo CommonLanguage::getMessage('fill_quantity_alert'); ?>')
                $("#damage_submit").removeClass('disabled')
                $(document.body).animate({scrollTop: 0}, 800)
                return;
            }

            if (!IsValidated) {
                $("#damage_submit").removeClass('disabled')
                return;
            }
            $("#damage_loader").removeClass('hidden');
            $.ajax({
                url: IsEditMode ? "StockAjax/edit_damage_ajax" : "StockAjax/add_damage_ajax",
                method: "POST",
                data: Data,
                dataType: "json",
                complete: function (v1, v2) {
                    console.log(v1);
                    console.log(v1.responseJSON[1]);
                    if (true) {
                        if (true) {
                            $("#damage_alert").attr("class", "alert alert-success").html(Submitted_Successfully)
                            request_id = v1.responseJSON[1];
                            $("#PrintBtn").removeClass("disabled")

                            CheckSubmit = true;
                        } else {
//                            if (v1.responseJSON[0] == 'expiry_error') {
//                                $.each(v1.responseJSON[1], function (indx, row) {
//                                    $("#damage_table tbody tr[data-id=" + row['Product_ID'] + "]  input.expiry_date[value=" + row['expiry_date'] + "]").addClass("wrong")
//                                })
//                                $("#damage_alert").attr("class", "alert alert-danger").html('<?php echo CommonLanguage::getMessage('check_expiry_exist') ?>')
//
//                            } else
//                            if (v1.responseJSON[0] == 'serial_error') {
//                                $.each(v1.responseJSON[1], function (indx, row) {
//                                    $("#damage_table tbody tr[data-id=" + row['Product_ID'] + "]  input.serial_nb[value=" + row['serial_nb'] + "]").addClass("wrong")
//                                })
//                                $("#damage_alert").attr("class", "alert alert-danger").html('<?php echo CommonLanguage::getMessage('check_serial_exist') ?>')
//
//                            } else
//                            if (v1.responseJSON[0] == 'lot_error') {
//                                $.each(v1.responseJSON[1], function (indx, row) {
//                                    $("#damage_table tbody tr[data-id=" + row['Product_ID'] + "]  input.lot_nb[value=" + row['lot_nb'] + "]").addClass("wrong")
//                                })
//                                $("#damage_alert").attr("class", "alert alert-danger").html('<?php echo CommonLanguage::getMessage('check_lot_exist') ?>')
//
//                            } else
//                            if (v1.responseJSON[0] == 'qty_error') {
//                                $.each(v1.responseJSON[1], function (indx, row) {
//                                    $("#damage_table tbody tr[data-id=" + row['Product_ID'] + "]  input.Quantity").addClass("wrong")
//                                })
//                                $("#damage_alert").attr("class", "alert alert-danger").html('<?php echo CommonLanguage::getMessage('check_qty_exist') ?>')
//
//                            } else {
                            $("#damage_alert").attr("class", "alert alert-danger").html(v1.responseJSON[0])

                            CheckSubmit = false;
//                            }
                            $("#damage_submit").removeClass('disabled')
                        }
                    } else {
                        $("#damage_alert").attr("class", "alert alert-danger").html(Failed_Submit)
                        $("#damage_submit").removeClass('disabled')
                        CheckSubmit = true;
                    }
                    $(document.body).animate({scrollTop: 0}, 800)
                    $("#damage_loader").addClass('hidden');
                }
            })
        } else {
            $(document.body).animate({scrollTop: 0}, 800)
            $("#damage_submit").removeClass('disabled')
            $("#damage_alert").attr("class", "alert alert-danger").html(Required_Fields)
        }
    }
    $(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;
            }
        }
    });
    function searchScannedItem(barcode, TR) {
        var get_parameters = 'Status_ID=1&barcode=' + barcode + '&depot_id=' + $('#Depot_Name2').val();
        $.ajax({
            url: "POSAjax/searchBarcodeforPOS?" + get_parameters,
            method: 'GET',
            dataType: 'json',
            complete: function (v1, v2) {
                var Data = v1.responseJSON;
                if ($.type(Data) === "object") {
                    $("select[name=UOM_ID]", TR).empty();
                    TR.attr("data-id", Data.ID)
                    TR.attr("data-qty", Data.Quantity)
                    TR.attr("data-expiry", Data.is_expiry)
                    TR.attr("data-is-serial", Data.is_serial)
                    TR.attr("data-is-lot", Data.is_lot)
                    TR.attr("data-prod-status", Data.Status_ID)
                    TR.attr("data-conv", 1)
                    TR.find("input.CODE").val(Data.Bar_Code + '-' + Data.Price)
                    TR.find("input.ProductName").val(Data.Name)

                    TR.find("input.Quantity").focus().next().text(AddCommas(parseFloat(Data.Quantity).toFixed(3)) + " in stock")
                    $("select[name=UOM_ID]", TR).empty().html($("#Select_UOM").html()).select2()
                    TR.find("select[name=UOM_ID] > option[value=" + Data.UOM_ID + "]").attr("selected", true)
                    TR.find("select[name=UOM_ID]").select2()
                    if (Data.is_expiry == 0) {
                        TR.find("input.expiry_date").val("").attr("data-select-name", "")
                        TR.find("input.expiry_date").addClass("hidden")
                    } else {
                        $("input.expiry_date", TR).removeClass("hidden")
                        build_select2($(".expiry_date", TR), function () {
                            return 'xhr/get_product_expiry?product_id=' + this.parents('tr').attr('data-id') + '&depot=' + $("#Depot_Name2").val();
                        });
                    }
                    if (Data.is_lot == 1 && activate_lot == 1) {
                        TR.find(".lot_nb").removeClass("hidden");
                        build_select2($(".lot_nb", TR), function () {
                            return 'xhr/get_product_lot?product_id=' + this.parents('tr').attr('data-id') + '&depot=' + $("#Depot_Name2").val();
                        });

                    } else {
                        TR.find(".lot_nb").val("").attr("data-select-name", "")
                        TR.find(".lot_nb").addClass("hidden");
                    }

                    if (Data.is_serial == 1 && activate_serial == 1) {
                        TR.find(".serial_nb").removeClass("hidden");
                        build_select2($(".serial_nb", TR), function () {
                            return 'xhr/get_product_serial?product_id=' + this.parents('tr').attr('data-id') + '&depot=' + $("#Depot_Name2").val();
                        });

                    } else {
                        TR.find(".serial_nb").val("").attr("data-select-name", "")
                        TR.find(".serial_nb").addClass("hidden");
                    }
                    var units_arr = Data.Product_UOM.split("/");
                    $("select[name=UOM_ID] > option", TR).each(function () {
                        if ($.inArray($(this).attr("value"), units_arr) === -1) {
                            $(this).remove()
                        }
                    })
                    return false;
                } else {
                    if (Data.is_expiry == 0)
                        TR.find(".expiry_date").addClass("hidden")
                    else {
                        TR.find(".expiry_date").removeClass("hidden")
                        TR.find("input.expiry_date").datepicker({autoclose: true});
                    }
                    if (has_purchase_cost_perm) {
                        TR.find("input.UnitPrice").next().text("last cost: " + (!Data.last_cost ? "0" : AddCommas(parseFloat(ConvertCurrency2(Data.last_cost, local_currency, $("#CurrencyDropDown input").val())).toFixed(3))));
                    }
                    UpdateTable()
                    return false;
                }
            }

        });
    }
</script>
