<?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>Alert: </strong>you can not edit this request! 
        <br>
        This request is not available.
    </div>
    <?php
    die();
}
if ($IsEdit && !empty($edit_arr['main']['ticketing_id'])) {
    ?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong>Alert: </strong>you can not edit this request! 
        <br>
        This request is linked to ticketing.
    </div>
    <?php
    die();
}

$stock_request_fields_to_hide = smc_session()['default_setting']['stock_request_fields_to_hide'] != '' ? explode(",", smc_session()['default_setting']['stock_request_fields_to_hide']) : [];
?>
<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;
        padding: 5px 9px 12px;
        height: 40px;
    }
    #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;
        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;
    }
    #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;
    }
    #OrderTable .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;*/
    }
    .tags{
        cursor:pointer;
    }
    .inputDiv {
        background-color: transparent;
        font-size: large;
        border: none;
        border-radius: 0;
    }
    .inputDiv input {
        position: absolute;
        left: 0px;
        top: 0px;
        width: 100%;
        height: 100%;
        opacity: 0.01;
        cursor: pointer;
    }
    #TagsTable td:not(:first-child){
        padding:0;
    }
    .tagSelected,.inputDiv:hover{
        background-color:#ed9421 !important;
        border-color:#ed9421 !important;
        color:white;
    }
    .inputDiv.tagSelected .inputDiv{
        color:white;
    }
    .removeTags{
        text-align:center;
        vertical-align:middle !important;
        width:10%;
        cursor:pointer;
    }
    #OrderTable td span.mylabel{
        font-size:10px !important;
        display: inline-table !important;
        white-space:normal !important;
        line-height: 21px !important;
    }
    #OrderTable .bootstrap-tagsinput .tag [data-role="remove"] {
        font-size:13px !important;

    }
    #OrderTable .bootstrap-tagsinput{
        max-height: 40px;
        overflow: hidden;

    }
</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('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 } ?>
                <div id="OrderSuccess" class="<?php echo ($is_invoice && !empty($edit_arr['main']['inv_transfered'])) ? 'alert alert-danger ' : 'hidden'?>"><?php echo ($is_invoice && !empty($edit_arr['main']['inv_transfered'])) ? CommonLanguage::getMessage('inv_transfered') : ''?></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 print CommonLanguage::getMessage($is_confirmed ? 'Transfer_Goods' : 'Request_Order'); ?></h2>

                            <div class="col-md-6  sm-no-padding">
                                <div class="row">
                                    <input type="hidden" value="<?php echo $IsEdit ? $edit_arr['main']['Status_ID'] : ($is_convert ? 3 : '') ?>" 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" <?php echo $is_convert ? '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['main']['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 $is_convert ? 'disabled' : '' ?> >
                                                <?php $depot_arr = smc_session()['transfer_from_current_branch_only'] == 1 ? $from_depot : $All_Depots_Not_PIC ?>
                                                <option value="" disabled selected ><?php echo CommonLanguage::getMessage('select'); ?></option>
                                                <?php foreach ($depot_arr as $depot): ?>
                                                    <option value="<?php echo $depot['Depot_ID']; ?>" <?php echo $IsEdit || $is_invoice ? ($edit_arr['main']['Request_To'] == $depot['Depot_ID'] ? 'selected' : '') : '' ?>  ><?php echo $depot['Depot_Name']; ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                <div class="row <?php echo empty(smc_session()['default_setting']['activate_customer_request_transfer']) ? 'hidden' : ''; ?>">
                                    <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 class="form-group col-md-6 "></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('Request'); ?> # <?php echo $IsEdit ? $edit_arr['main']['req_id'] : '--' ?></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="loading_order_date" name="loading_order_date" required class="form-control" value="<?php echo $IsEdit ? $edit_arr['main']['Request_Date'] : ($today); ?>"  <?php echo $is_convert ? 'disabled' : '' ?> />
                                    <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['main']['Delivery_Date'] : ($today); ?>"  <?php echo $is_convert ? 'disabled' : '' ?> />
                                    <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('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 || !$is_confirmed ) ? '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 echo in_array(1, $stock_request_fields_to_hide) ? 'hidden' : ''; ?>" style="width:7%"><?php print CommonLanguage::getMessage('lot'); ?></th>
                                    <th class="text-center <?php echo in_array(2, $stock_request_fields_to_hide) ? 'hidden' : ''; ?>" style="width:7%"><?php print CommonLanguage::getMessage('serial'); ?></th>
                                    <th class="text-center " style="width:7%"><?php print CommonLanguage::getMessage('note'); ?></th>
                                    <?php if (smc_session()['default_setting']['is_tag_active'] == 1) { ?>
                                        <th class="text-center"style="width:5%"></th>
                                        <th class="text-center"style="width:10%"></th>
                                    <?php } ?>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                if ($IsEdit || $is_data_collector || $is_invoice) {
                                    $data_arr = $IsEdit || $is_invoice ? $edit_arr['Request'] : $collector_data['products'];
                                    foreach ($data_arr as $item) {
                                        $uoms = $is_data_collector ? explode('/', $item['Product_UOM']) : array();
                                        ?>
                                        <tr data-is-lot="<?php echo $item['is_lot'] ?>"
                                            data-is-serial="<?php echo $item['is_serial'] ?>" 
                                            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'] ?>" 
                                            data-prod-status="<?php echo $item['product_status'] ?>" 
                                            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['Cat_ID'] ?>" data-select-name="<?php echo $item['Cat_Name'] ?>"  <?php echo $is_convert ? 'disabled' : '' ?> /></td>
                                            <td><input type="text" class="form-control AutoComplete CODE input-barcode-scan" value = "<?php echo $item[$is_data_collector ? 'Code' : 'Product_Code'] ?>"  <?php echo $is_convert ? 'disabled' : '' ?> ></td>
                                            <td><input type="text" class="form-control AutoComplete ProductName" value = "<?php echo $item[$is_data_collector ? 'Name' : 'Product_Name'] ?>"  <?php echo $is_convert ? 'disabled' : '' ?> ><span class="Hint"></span></td>
                                            <td class="<?php echo (smc_session()['default_setting']['activate_expiry_date'] == 0 || !$is_confirmed ) ? '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[$is_data_collector ? 'Item_Quantity_Current' : 'Current_Quantity'] ?>"  <?php echo $is_convert && !$permissions->hasPErmission('change_qty_converted_request') ? 'disabled' : '' ?> ><span class="Hint"></span></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 echo $is_convert ? 'disabled' : '' ?> >
                                                        <?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>
                                            <td class="<?php echo in_array(1, $stock_request_fields_to_hide) ? '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 in_array(2, $stock_request_fields_to_hide) ? '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>
                                            <td class="text-center " >
                                                <input type="hidden" class="full-width detail_note " value="<?php echo $item['detail_note']; ?>" />
                                            </td>
                                            <?php if (smc_session()['default_setting']['is_tag_active'] == 1) { ?>
                                                <td class="tags"><i class="fa fa-tag fa-2x"></i></td>
                                                <td class="tag-main-td">
                                                    <div class=" bootstrap-tagsinput">
                                                        <?php
                                                        if (!empty($item['criteria'])) {
                                                            foreach ($item['criteria'] as $criteria) {
                                                                ?>
                                                                <span class="tag label label-stock mylabel" data-content="<?php echo $criteria['criteria_detail_name'] ?>" 
                                                                      data-criteria-id="<?php echo $criteria['criteria_id'] ?>" data-note="<?php echo $criteria['criteria_note'] ?>" 
                                                                      data-entry="<?php echo $criteria['criteria_detail_id'] ?>">
                                                                    <?php echo $criteria['criteria_detail_name'] ?><span data-role="remove"></span></span>
                                                                <?php
                                                            }
                                                        } else {
                                                            echo'No Tags';
                                                        }
                                                        ?>
                                                    </div>
                                                </td>

                                            <?php } ?>
                                        </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 || !$is_confirmed ) ? '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="<?php echo in_array(1, $stock_request_fields_to_hide) ? 'hidden' : ''; ?>" >
                                            <input type="hidden" class="full-width lot_nb hidden" />
                                        </td>
                                        <td class="text-center <?php echo in_array(2, $stock_request_fields_to_hide) ? 'hidden' : ''; ?>" >
                                            <input type="hidden" class="full-width serial_nb hidden"  />
                                        </td>
                                        <td class="text-center " >
                                            <input type="hidden" class="full-width detail_note"  />
                                        </td>
                                        <?php if (smc_session()['default_setting']['is_tag_active'] == 1) { ?>
                                            <td class="tags"><i class="fa fa-tag  fa-2x"></i></td>
                                            <td class="tag-main-td"><div class=" bootstrap-tagsinput"> No Tags </div></td>

                                        <?php } ?>
                                    </tr>
                                <?php } ?>
                            </tbody>
                        </table>
                    </div>
                    <br>
                    <div class="container-sm-height form-group" >
                        <label><?php echo CommonLanguage::getMessage('note') ?></label>
                        <textarea id="request_note"  class="form-control NoteTextArea"  aria-invalid="false" ></textarea>
                    </div>
                    <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 } ?>
                        <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>
                        <?php if ($is_convert) { ?>
                            <button class=" btn  btn-danger m-b-10 pull-left" id="RejectTransferButton" style="color:#fff; ;padding-top: 10px;top: 20px;" type="button"><i class="fa fa-close"></i> <span class="bold"><?php print CommonLanguage::getMessage('Reject'); ?></span></button>
                        <?php } ?>
                    </div>
                    <hr>
                </div>
            </div>
        </div>
    </div>
</form>
<div class="modal fade" id="tagsModal" data-backdrop="static" data-id="" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header clearfix text-left">
                <div class="row">
                    <h4 class="text-center"><i class="fa fa-tags"></i> <?php print CommonLanguage::getMessage('criteria') ?></h4>
                </div>
            </div>
            <div class="modal-body">
                <?php echo Forms::AlertDiv('tag_Alert'); ?>
                <div class="row criteria-detail-div">      
                </div>
            </div>
            <div class="modal-footer">
                <div class="col-md-12 row ">
                    <button id="cancelTag" type="submit" data-dismiss="modal" class="btn btn-danger btn-cons"><i class="fa fa-times"></i> <?php print CommonLanguage::getMessage('Close') ?></button>
                    <button id="addTag" type="submit" class="btn bg-complete-light btn-cons"><i class="fa fa-check"></i> <?php print CommonLanguage::getMessage('Save') ?></button>
                </div>
            </div>
            <?php echo Forms::ModalLoader('Criteria_Loader'); ?>
        </div>
    </div>
</div>
<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 ?>,
            is_invoice = <?php echo $is_invoice ? 1 : 0 ?>,
            user_depot = <?php echo json_encode(smc_session()['user_accounts']['depot_id']); ?>,
            display_shelf_locations = <?php echo json_encode(smc_session()['default_setting']['display_shelf_locations']) ?>,
            negative_sales = <?php echo json_encode(smc_session()['negative_sales']); ?>,
            activate_lot = <?php echo json_encode(in_array(1, $stock_request_fields_to_hide) ? 0 : 1); ?>,
            activate_serial = <?php echo json_encode(in_array(2, $stock_request_fields_to_hide) ? 0 : 1); ?>,
            request_id, max_criteria_column = 5,
            unique_id = <?php echo json_encode(!$IsEdit ? $unique_id : '') ?>;
    var req_nb = <?php echo json_encode($is_confirmed ? CommonLanguage::getMessage('transfer_nb') : CommonLanguage::getMessage('request_nb')); ?>;
    $(function () {
        build_select2($("#customer_id"), "xhr/customerSearch");
        //        searchScannedItem('6251159044042101', $("#OrderTable 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_transfer_details/" + request_id;
            printExternal(myurl);
        });
        build_select2($('.cat_id'), "xhr/catSearch");
        if (IsEditMode) {
            $("#OrderTable 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($("#OrderTable .AutoComplete.CODE"));
            EnableAutoComplete($("#OrderTable .AutoComplete.ProductName"));
        }
        $("#loading_order_date,#Delivery_Date").datepicker({autoclose: true})


        $("#OrderTable").on("click", ".tags", function () {
            var tr = $(this).parents("tr");
            if (tr.attr("data-id") == undefined)
                return;
            getProductCriteria(tr.attr("data-id"), getCurrentTags(tr), tr)
            $("#tagsModal").attr("data-id", tr.index())
        })
        $(".criteria-detail-div").on("click", '.removeTags', function () {
            $(this).parents("tr").find("input:checked").removeAttr("checked")
            removeTags()
        });
        $(".criteria-detail-div").on("click", '#TagsTable input', function () {

            removeTags()
        });
        $(".criteria-detail-div").on("click", '#TagsTable input[type=checkbox]', function () {
            var max_count = $(this).attr('max-count'),
                    criteria_id = $(this).attr("data-criteria-id"),
                    current_selected_length = $('td.tagSelected input[data-criteria-id=' + criteria_id + ']').length

            if (current_selected_length > parseInt(max_count)) {

                $(this).parents('td.inputDiv').removeClass('tagSelected');
                this.checked = false
            }
        })
        $("#addTag").on("click", function () {
            updateTags()
        });
        $("#OrderTable").on("click", "[data-role=remove]", function () {
            var item = $(this).parents("tr").attr("data-ref"),
                    Parent = $(this).parents("tr");

            $(this).parents("span.tag").remove()
            if ($("span.tag", Parent).length == 0) {
                $("tr:eq(" + item + ")").find('div.bootstrap-tagsinput').html('No Tags')
            }
        })


        $("#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']);
                        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()}
            $("#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);
                        $.each(Data, function (index, value) {
                            var me = $("#OrderTable 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 && !is_invoice) {
            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("")
                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');
                ClonedRow.find(".mylabel").remove()
                ClonedRow.find('div.bootstrap-tagsinput').html('No Tags')
            }
        })
        $("#OrderSubmitButton").on("click", ApplyPostMethod);
        $("#RejectTransferButton").on("click", function () {
            if (!$("#request_note").val()) {
                alert("You must enter a reason of rejection!")
                IsValidated = false;
            } else {
                var Reject = {
                    Request_ID: ID_Edit,
                    Rejection_Comment: $("#request_note").val()
                }
                IsValidated = true;
            }
            if (!IsValidated)
                return;
            //            $("#OrderDisabler").removeClass('hidden');
            $.ajax({
                url: "StockAjax/TransferGoodsAjax",
                data: Reject,
                complete: function (v1, v2) {
                    if (v2 == "success") {
                        $("#OrderSuccess").attr("class", "alert alert-warning").html('<?php echo CommonLanguage::getMessage('Reject_Order') ?>')
                        $("#OrderSubmitButton,#RejectTransferButton").attr("disabled", "disabled")
                    } else {
                        $("#OrderSuccess").attr("class", "alert alert-danger").html(Failed_Submit)
                    }
                    $(document.body).animate({scrollTop: 0}, 800)
                    //                    $("#OrderDisabler").addClass('hidden');
                }
            })
        })
    })
    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");
                    var old_prod_id = TR.attr("data-id")
                    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)
                    if (display_shelf_locations == 1) {
                        TR.find("input.ProductName").next().text(ui.item.loc);
                    }
                    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").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 (ui.item.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("input.lot_nb").val('').attr("data-select-name", "")
                        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("input.serial_nb").val('').attr("data-select-name", "")
                        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()
                        }
                    })
                    if (old_prod_id != ui.item.ID) {
                        $(".mylabel", TR).remove()
                        TR.find('div.bootstrap-tagsinput').html('No Tags')
                    }
                    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() {
        $("#OrderSubmitButton").addClass('disabled')
        $("#OrderSuccess").attr("class", "hidden");
        $("#OrderTable tbody .wrong").removeClass("wrong")
        $("#OrderForm").validate()
        if ($("#OrderForm").valid()) {
            var IsValidated = true, is_empty_quantity = false,
                    Data = {
                        Request_From: $("#Depot_Name1").val(),
                        Request_To: $("#Depot_Name2").val(),
                        Delivery_Date: $("#Delivery_Date").val(),
                        Request_Date: $("#loading_order_date").val(),
                        note: $("#request_note").val(),
                        is_confirmed: is_confirmed,
                        is_data_collector: is_data_collector,
                        unique_id: unique_id,
                        customer_id: $('#customer_id').val(),
                        Products: []
                    };
            if (!$("#Depot_Name1").val() || !$("#Depot_Name2").val()) {
                $("#OrderSuccess").attr("class", "alert alert-danger").html(Required_Fields)
                $("#OrderSubmitButton").removeClass('disabled')
                $(document.body).animate({scrollTop: 0}, 800)
                return false;
            }
            $("#OrderTable tbody tr").each(function (e) {
                var me = $(this);
                if (me.find(".ProductName").val()) {
                    if (!me.find(".Quantity").val())
                        is_empty_quantity = true;
                }
                var tags = [];
                if (me.find(".Quantity").val() != '' && me.find(".ProductName").val() != '') {
                    $("td.tag-main-td .mylabel", $(this)).each(function () {
                        tags.push({
                            Quantity: me.find(".Quantity").val(),
                            criteria_detail_id: $(this).attr("data-entry"),
                            criteria_note: $(this).attr("data-note") || ''
                        });
                    });
                    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,
                        expiry_date: me.find("input.expiry_date").val(),
                        lot_nb: $("input.lot_nb", me).val(),
                        serial_nb: $("input.serial_nb", me).val(),
                        is_service: me.attr("data-is-service"),
                        criteria_details: tags,
                    });
                    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")
                            }
                        }
                    })
                    if (is_confirmed == 1 && me.attr("data-expiry") == 1 && me.find("input.expiry_date").val() == '') {
                        me.find("input.expiry_date").addClass("wrong")
                        CheckSubmit = false;
                        IsValidated = false;
                    }
                    if (is_confirmed == 1 && 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 (is_confirmed == 1 && 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.Request_ID = ID_Edit;
                Data.Status_ID = $("#Status_ID").val();
            }
            if(is_invoice){
              Data.Invoice_ID_Auto = ID_Edit;  
            }
            if (Data.Products.length == 0) {
                $("#OrderSuccess").attr("class", "alert alert-danger").html('<?php echo CommonLanguage::getMessage('input_option'); ?>')
                $("#OrderSubmitButton").removeClass('disabled')
                $(document.body).animate({scrollTop: 0}, 800)
                return;
            }
            if (is_empty_quantity) {
                $("#OrderSuccess").attr("class", "alert alert-danger").html('<?php echo CommonLanguage::getMessage('fill_quantity_alert'); ?>')
                $("#OrderSubmitButton").removeClass('disabled')
                $(document.body).animate({scrollTop: 0}, 800)
                return;
            }
            if (is_data_collector) {
                Data.file_id = file_id;
            }
            if (!IsValidated) {
                $("#OrderSubmitButton").removeClass('disabled')
                return;
            }
            $("#OrderDisabler").removeClass('hidden');
            $.ajax({
                url: IsEditMode ? "StockAjax/editRequestOrderAjax" : "StockAjax/RequestOrderAjax",
                method: "POST",
                data: Data,
                dataType: "json",
                complete: function (v1, v2) {
                    if (v2 == "success") {
                        if (v1.responseJSON[0] == 'OK') {
                            $("#OrderSuccess").attr("class", "alert alert-success").html(Submitted_Successfully + '&nbsp;<strong>' + req_nb + ' ' + v1.responseJSON[2] + '</strong>')
                            request_id = v1.responseJSON[1];
                            $("#PrintBtn").removeClass("disabled")

                            CheckSubmit = true;
                        } else {
                            if (v1.responseJSON[0] == 'expiry_error') {
                                $.each(v1.responseJSON[1], function (indx, row) {
                                    $("#OrderTable tbody tr[data-id=" + row['Product_ID'] + "]  input.expiry_date[value=" + row['expiry_date'] + "]").addClass("wrong")
                                })
                                $("#OrderSuccess").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) {
                                    $("#OrderTable tbody tr[data-id=" + row['Product_ID'] + "]  input.serial_nb[value=" + row['serial_nb'] + "]").addClass("wrong")
                                })
                                $("#OrderSuccess").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) {
                                    $("#OrderTable tbody tr[data-id=" + row['Product_ID'] + "]  input.lot_nb[value=" + row['lot_nb'] + "]").addClass("wrong")
                                })
                                $("#OrderSuccess").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) {
                                    $("#OrderTable tbody tr[data-id=" + row['Product_ID'] + "]  input.Quantity").addClass("wrong")
                                })
                                $("#OrderSuccess").attr("class", "alert alert-danger").html('<?php echo CommonLanguage::getMessage('check_qty_exist') ?>')

                            } else {
                                $("#OrderSuccess").attr("class", "alert alert-danger").html(v1.responseJSON[0])

                                CheckSubmit = false;
                            }
                            $("#OrderSubmitButton").removeClass('disabled')
                        }
                    } else {
                        $("#OrderSuccess").attr("class", "alert alert-danger").html(Failed_Submit)
                        $("#OrderSubmitButton").removeClass('disabled')
                        CheckSubmit = true;
                    }
                    $(document.body).animate({scrollTop: 0}, 800)
                    $("#OrderDisabler").addClass('hidden');
                }
            })
        } else {
            $(document.body).animate({scrollTop: 0}, 800)
            $("#OrderSubmitButton").removeClass('disabled')
            $("#OrderSuccess").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();
        //        if (IsSalesMode) {
        //            get_parameters += '&type=1';
        //        } else {
        //            get_parameters += '&type=2';
        //        }
        $.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)
                    if (display_shelf_locations == 1) {
                        TR.find("input.ProductName").next().text(Data.loc);
                    }
                    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").addClass("hidden")
                    else {
                        $("input.expiry_date", TR).removeClass("hidden")
                        build_select2($(".expiry_date", TR), 'xhr/get_product_expiry?product_id=' + Data.ID);
                    }
                    if (Data.is_lot == 1 && activate_lot == 1) {
                        TR.find(".lot_nb").removeClass("hidden");
                        build_select2($(".lot_nb", TR), 'xhr/get_product_lot?product_id=' + Data.ID);
                    } else
                        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), 'xhr/get_product_serial?product_id=' + Data.ID);
                    } else
                        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;
                }
            }

        });
    }
    function getCurrentTags(currentTR) {
        var tags = [], tag_notes = [];
        $("td.tag-main-td .mylabel", currentTR).each(function () {
            tags.push($(this).attr("data-entry"));
            if ($(this).attr("data-note") != undefined) {
                tag_notes[$(this).attr("data-criteria-id")] = $(this).attr("data-note")
            }
        });
        //        console.log(tag_notes)
        return [tags, tag_notes];
    }
    function getProductCriteria(product_id, criteria_data, SelectedTR) {
        current_criteria = criteria_data[0];
        current_criteria_notes = criteria_data[1];
        //        console.log(criteria_data)
        $("#tagsModal").modal('show')
        $("#tagsModal .criteria-detail-div").empty();
        CommonViewById('RestaurantAjax/getProductCriteria', {Product_ID: product_id, is_all: 1, category_id: SelectedTR.attr('data-category-id')}, '#Criteria_Loader', function (Response) {
            if (Object.keys(Response).length > 0) {
                var tagTable = ' <table class="col-md-12 table table-bordered table-responsive" id="TagsTable">',
                        product_criteria = '', general_criteria = '';
                //                console.log(Response)
                $.each(Response, function (key1, value) {
                    var all_details = Response[key1]['detail'], content = '', type = Response[key1]['criteria_type'] == 2 ? 'radio' : 'checkbox',
                            up_to_condition = 'Choose ' + (Response[key1]['criteria_type'] == 2 ? '1' : ' UP to ' + Response[key1]['criteria_max_count'] + ' ');
                    var rows_nb = Math.ceil(all_details.length / max_criteria_column);
                    content += '<tr max-count="' + Response[key1]['criteria_max_count'] + '" data-type="' + type + '">' +
                            '<td class="tag_note_td" rowspan="' + rows_nb + '" style="width:15%;"><textarea class="tag-note form-control" rows="1">' + (current_criteria_notes[Response[key1]['criteria_id']] || '') + '</textarea></td>' +
                            '<th class="tag_note_cond" rowspan="' + rows_nb + '"  style="width:12%"><div><span>' + up_to_condition + '</span></div></th>' +
                            '<th rowspan="' + rows_nb + '" class=" ' + (Response[key1]['product_id'] == 0 ? 'btn-primary' : 'btn-info') + ' removeTags">' +
                            '<div><i class="fa fa-times"></i> <span>' + Response[key1]['criteria_name'] + '</span></div> </th>';
                    var row_col_index = 0;
                    $.each(all_details, function (key2, value) {
                        if (row_col_index == max_criteria_column) {
                            content += '</tr><tr>';
                            row_col_index = 0;
                        }
                        row_col_index++;
                        content += '<td style="vertical-align:middle;text-align:center;" class="inputDiv ' + ($.inArray(all_details[key2]['criteria_detail_id'], current_criteria) !== -1 ? 'tagSelected' : '') + '">' +
                                '<div class="btn btn-style inputDiv" style="width:100%">' + all_details[key2]['criteria_detail_name'] +
                                '<input type="' + type + '" max-count="' + Response[key1]['criteria_max_count'] + '" data-criteria-id="' + Response[key1]['criteria_id'] + '" data-entry="' + all_details[key2]['criteria_detail_id'] + '"  tag-name="' + all_details[key2]['criteria_detail_name'] +
                                '" data-ref ="" data-tag = "" ' + ($.inArray(all_details[key2]['criteria_detail_id'], current_criteria) !== -1 ? 'checked' : '') + ' value="' + all_details[key2]['criteria_detail_id'] + '" name="' + $.trim(Response[key1]['criteria_name']) + '" id="" class="form-control multiple-checkbox"></div>' +
                                '</td>';
                    });
                    if (row_col_index < max_criteria_column)
                        content += '<td colspan="' + (max_criteria_column - row_col_index) + '">&nbsp;</td>';
                    content += '</tr>';
                    if (Response[key1]['product_id'] == 0)
                        general_criteria += content;
                    else
                        product_criteria += content;
                });
                tagTable += product_criteria + general_criteria + '</table>';
                $('#tagsModal .criteria-detail-div').append($(tagTable))
                $.each(current_criteria_notes, function (note_id, entry_id) {
                    if (entry_id != undefined) {
                        $("input[data-entry=" + note_id + "]").closest(".tag-note").val(entry_id)
                    }
                    //                        console.log(note_id + '==' + entry_id)
                })
                $('#addTag').attr('disabled', false)
            } else {
                $("#tagsModal .criteria-detail-div").append(' <div class="col-md-12 m-t-10 alert alert-warning">No criteria related to this item</div>');
                $('#addTag').attr('disabled', true)
            }
        });
    }
    function removeTags() {
        $("#TagsTable td,#TagsTable button").removeClass("tagSelected")
        $("#TagsTable tr input:checked").parents('td').addClass("tagSelected")
        $("#TagsTable tr input:checked").parents('button').addClass("tagSelected")

    }
    function updateTags() {
        var item = $("#tagsModal").attr("data-id");
        $("#OrderTable tbody tr:eq(" + item + ") div.bootstrap-tagsinput").empty();
        var row_title = '';
        $("#tagsModal .criteria-detail-div input:checked").each(function () {
            var tag_name = $(this).attr("tag-name"),
                    entry = $(this).val(),
                    criteria_id = $(this).attr("data-criteria-id"),
                    note = $(this).parents("tr").find(".tag-note").val();
            row_title += tag_name + '\n';
            var label_tag = '<span class="tag label label-stock mylabel" data-content="' + tag_name + '" data-criteria-id="' + criteria_id + '" data-note="' + note + '"  data-entry="' + entry + '">' + tag_name + '<span data-role="remove"></span></span>';
            $("#OrderTable tbody tr:eq(" + item + ") div.bootstrap-tagsinput").append($(label_tag));
        });
        $("#OrderTable tbody tr:eq(" + item + ")").attr("title", row_title)
        $("#tagsModal").modal("hide")
    }
</script>
