<?php


//echo '<pre>';
//print_r($invoice_details);
$Language = @Session::getUserPreferences();
$url = explode('/', $_GET['url']);
$pos_fields_hide = smc_session()['default_setting']['pos_fields_to_hide'] != '' ? explode(",", smc_session()['default_setting']['pos_fields_to_hide']) : [];
//die('ok');
//if (count($url) == 1 || $url[1] =="" || (isset($invoice_details['main_invoice']) && array_key_exists('Close_ID',$invoice_details['main_invoice']) && $invoice_details['main_invoice']['Close_ID'] != Session::getUserID())) {
//    header('location:' . SITE_LINK . 'main_page');
//}
//if ( (smc_session()['default_setting']['activate_smart_diner'] ==  1 && ) && (count($url) == 1 || $url[1] =="" || (isset($invoice_details['main_invoice']) && array_key_exists('Close_ID',$invoice_details['main_invoice']) && $invoice_details['main_invoice']['Close_ID'] != Session::getUserID()))) {
//     header('location:' . SITE_LINK . 'main_page');
//}
$isTable = 'false';
if (is_numeric($url[1])) {
    $isTable = 'true';
}
?>
<link href="<?php echo SITE_LINK; ?>Views/files/styles<?php echo $Language == 'ar' ? '.rtl' : ''; ?>.css?v=<?php echo trusto_VERSION; ?>" rel="stylesheet">
<script src="<?php echo SITE_LINK; ?>Views/files/scroll-div.js"></script>
<script src="<?php echo SITE_LINK; ?>Views/files/scripts.js?v=<?php echo trusto_VERSION; ?>"></script>
<script src="<?php echo SITE_LINK; ?>Views/files/towords.js"></script>
<script src="<?php echo THEME_PATH; ?>plugins/jQuery-Scanner-Detection-master/jquery.scannerdetection.js"></script>
<script src="<?php echo THEME_PATH; ?>plugins/jQuery-Scanner-Detection-master/jquery.scannerdetection.compatibility.js">
</script>
<style type="text/css">
    @keyframes example {
        from {
            background-color: red;
        }

        to {
            background-color: white;
        }
    }

    .red-border {
        border: 1.5px solid red;
    }

    .diff_class {
        width: 200px !important;
    }

    .animateClass {
        width: 100px;
        height: 100px;
        background-color: red;
        /*animation-name: example;*/
        animation: example 1s infinite;
    }

    .cat {
        /*margin-top: -24px;*/
        background: #3B4752;
        width: 100%;
        height: 61px;
        /*margin-left: -15px;*/
        padding: 0px;
    }

    .cat>h4 {
        color: #fff;
        text-align: center;
    }

    ul.Categories>li {
        width: 20%;
    }

    .invoiceLOGO {
        width: 100px;
        height: 50px;
    }

    #POSInvoiceDateContainer {
        width: 261px;
        text-align: left;
    }

    #InvoiceIDTag,
    #POSInvoiceDateContainer,
    #InvoiceIDBonTag {
        margin-left: 30px;
        margin-top: 10px;
        font-size: 22pt !important;
    }

    #InvoiceCurrentDay {
        /*float: right;*/
        display: inline-block;
        margin-right: 21px;
        margin-top: 0;
        font-size: 15pt;
    }

    .hideme,
    .header {
        display: none;
    }

    .catli {
        border: 1px solid #e2e2e2;
        /*        background-color: #4c0870; */
        padding: 20px;
        text-align: center;
        width: 120px;
        cursor: pointer;
        /*margin-left: -53px;*/
    }

    /*
    .catli:nth-child(odd){
    background:#4b5a68
    }
    .catli:nth-child(even){
    background:#3B4752
    }
    */
    .catli.active {
        border: 2px Solid black;
        /*        background:#4c0870*/
    }

    .catli>a {
        color: #fff;
    }

    .borderStyle {
        border: 1px solid rgba(59, 71, 82, 0.5) !important;
    }

    .quickerleft {
        text-align: left;
    }

    .paging_simple_numbers {
        display: flex;
    }

    #defineTagBtn {
        width: 50%;
    }

    .zero-padding {
        padding: 0 !important;
    }

    select.uom {
        width: 70px;
    }

    .floors {
        padding-top: 10px;
        cursor: pointer;
        background-color: #4c0870;
        padding-bottom: 10px;
    }

    .available {
        padding-bottom: 2em;
        cursor: pointer;
        background-color: #4c0870;
        padding-top: 2em;
    }

    .reserved {
        padding-bottom: 2em;
        padding-top: 2em;
        background-color: #ed9421;
        cursor: pointer;
    }

    input[name=transfer_quantity] {
        width: 50px;
    }

    .full-width {
        width: 100% !important;
    }

    .payment-labels {
        padding: 3px;
        cursor: pointer;
    }

    .payment-color-labels {
        background-color: #3b4752;
        color: #fff;
    }

    .posDrop2:before,
    .posDrop2:after {
        right: 116px !important;
    }

    .options_box {
        position: fixed;
        width: 98% !important;
        background-color: #f54e53;
        box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.2);
        height: 7.5%;
    }

    .page-container .page-content-wrapper .content {
        padding-bottom: 10px !important;
    }

    .header-button {
        border-bottom: 2px solid #292929;
        /*        float: right;*/
        height: 45px;
        padding-left: 5px;
        padding-right: 5px;
        font-size: larger;
        /*border-right: 1px solid #292929;*/
        border-left: 2px solid #292929;
        color: #DDD !important;
        line-height: 45px;
        text-align: center;
        cursor: pointer;
        -webkit-transition-property: background;
        -webkit-transition-duration: 0.2s;
        -webkit-transition-timing-function: ease-out;
    }

    .header-button a {
        font-weight: 600;
    }

    .header-button a,
    .dd-color {
        color: white !important;
    }

    #select2-chosen-1 {
        color: #3B4752;
    }

    .m-t-8 {
        margin-top: 8px !important;
    }

    .del-tr {
        cursor: pointer;
    }

    .not-allowed {
        cursor: not-allowed;
    }

    /*
    #TagsTable{
    table-layout: fixed
    }
    #TagsTable .btn-style.inputDiv{
    padding: 2px;
    }
    */
    #TagsTable.table {
        margin-bottom: 5px;
    }

    /*#TagsTable.table tbody > tr > th, #TagsTable .table tbody > tr > td{
    padding:3px 3px;
    }
    #TagsTable .btn-style.inputDiv{
    padding: 16px;
    }*/
    /* The snackbar - position it at the bottom and in the middle of the screen */
    #snackbar,
    #scan_bar_code_bar {
        visibility: hidden;
        /* Hidden by default. Visible on click */
        min-width: 350px;
        /* Set a default minimum width */
        margin-left: -175px;
        /* Divide value of min-width by 2 */
        background-color: red;
        /* Black background color */
        color: #fff;
        /* White text color */
        text-align: center;
        /* Centered text */
        border-radius: 2px;
        /* Rounded borders */
        padding: 16px;
        /* Padding */
        position: fixed;
        /* Sit on top of the screen */
        z-index: 1;
        /* Add a z-index if needed */
        left: 50%;
        /* Center the snackbar */
        top: 50%;
        /* Center in the bottom */
        opacity: 0.9;
    }

    /* Show the snackbar when clicking on a button (class added with JavaScript) */
    #snackbar.show,
    #scan_bar_code_bar.show {
        visibility: visible;
        /* Show the snackbar */
        opacity: 0.7;
    }

    #open_online {
        padding: 7px 5px;
    }

    ul.ui-autocomplete li.ui-menu-item,
    li.ui-state-focus {
        line-height: 1;
        font-size: 12px;
        font-weight: bold;
        padding: 2px !important;
        border-bottom: 1px solid #ccc;
    }

    .expiry-icon,
    .prod-desc-icon,
    .product_description {
        font-size: 18px;
        cursor: pointer;
    }

    .f-s-10 {
        font-size: 10px;
    }

    .f-s-3e {
        font-size: 1.3em;
    }

    .header-second {
        margin: 0.5%;
    }

    .language-pos .dropdown-menu {
        width: 110px;
    }

    /*
    .available{
    background-color: #fff !important;
    }
    */
    .tr-return {
        background-color: #4c0870 !important;
    }

    .tr-gray {
        background-color: #e2e2e2 !important;
    }

    .tr-white {
        background-color: white !important;
    }

    #MainCat {
        margin-left: -34px;
    }

    .cash-cats-div {
        padding-right: 0px !important;
        padding-left: 0px !important;
    }

    .note-filled {
        color: rgb(16, 207, 189);
    }

    .InvoicesBtnRow .btn-info {
        width: 100% !important;
    }

    .InvoicesBtnRow [class*=col-] {
        padding-right: 5px !important;
        padding-left: 5px !important;
    }

    .InvoicesBtnRow button {
        padding-left: 0 !important;
        padding-right: 0 !important;
        font-size: 11px !important;
    }

    .show_all_price_keypad_height {
        height: 270px !important;
    }

    .primary-text {
        color: black !important;
    }

    .ui-autocomplete .ui-state-focus {
        font-weight: bold !important;
        border-bottom: 1px solid #ccc !important;
    }

    .tip {
        position: absolute;
        border: 1px solid #333;
        border-radius: 2px;
        padding: 3px;
        font-size: small;
        color: white;
        background-color: #333;
        z-index: 1;
    }

    .style_btn {
        -webkit-animation: glowing 1500ms infinite;
        -moz-animation: glowing 1500ms infinite;
        -o-animation: glowing 1500ms infinite;
        animation: glowing 1500ms infinite;
    }

    @-webkit-keyframes glowing {
        0% {
            background-color: #B20000;
            -webkit-box-shadow: 0 0 3px #B20000;
        }

        50% {
            background-color: #FF0000;
            -webkit-box-shadow: 0 0 40px #FF0000;
        }

        100% {
            background-color: #B20000;
            -webkit-box-shadow: 0 0 3px #B20000;
        }
    }

    @-moz-keyframes glowing {
        0% {
            background-color: #B20000;
            -moz-box-shadow: 0 0 3px #B20000;
        }

        50% {
            background-color: #FF0000;
            -moz-box-shadow: 0 0 40px #FF0000;
        }

        100% {
            background-color: #B20000;
            -moz-box-shadow: 0 0 3px #B20000;
        }
    }

    @-o-keyframes glowing {
        0% {
            background-color: #B20000;
            box-shadow: 0 0 3px #B20000;
        }

        50% {
            background-color: #FF0000;
            box-shadow: 0 0 40px #FF0000;
        }

        100% {
            background-color: #B20000;
            box-shadow: 0 0 3px #B20000;
        }
    }

    @keyframes glowing {
        0% {
            background-color: #B20000;
            box-shadow: 0 0 3px #B20000;
        }

        50% {
            background-color: #FF0000;
            box-shadow: 0 0 40px #FF0000;
        }

        100% {
            background-color: #B20000;
            box-shadow: 0 0 3px #B20000;
        }
    }

    .spinner-icons>span {
        position: absolute;
        top: 5px;
        display: block;
        /* bottom: 0; */
        width: 25%;
        height: 35px;
        background: rgb(76 8 113);
        line-height: 2.5;
        text-align: center;
        color: white
            /*font-size: 21px;*/
            /*font-weight: bold;*/
    }

    .split-icons>span {
        top: 0 !important;
        width: 15% !important;
        background-color: #3b4752 !important;
    }

    .spinner-icons>span:first-child {
        /*        content: "-";*/
        left: 0;
    }

    .spinner-icons>span:last-child {
        content: "+";
        right: 0;
    }

    .spinner-icons {
        position: relative;
    }

    .spinner-icons input {
        padding-left: 25%;
        padding-right: 25%;
    }

    #hold_fire_table {
        min-height: 40px !important;
        margin: 0;
    }

    #hold_fire_table td {
        vertical-align: middle;
        text-align: center;
        font-weight: bold;
        cursor: pointer;
        font-size: 15px !important;
        border-color: #bfbfbf;
    }

    #hold_fire_table .hold {
        background-color: rgb(76 8 113);
        color: white;
    }

    #hold_fire_table .fire {
        background-color: #cf3535;
        color: white;
    }

    #hold_fire_table .unhold {
        background-color: #e2e2e2;
        /*color:white;*/
    }

    .selected_hold {
        border: 5px solid black !important;
    }

    .hold1 {
        background-color: rgb(76 8 113) !important;
        color: white;
    }

    .hold2 {
        background-color: #cf3535 !important;
        color: white;
    }

    .hold3 {
        background-color: rgb(76 8 113) !important;
        color: white;
    }

    .submit_main_div.stop_submit_div:after {
        position: absolute;
        display: block;
        content: "";
        top: 0;
        bottom: 0;
        right: 0;
        left: 0;
        background: rgba(255, 255, 255, 0.8);
    }

    .pulsate {
        content: '';
        display: block;
        /*
        position: absolute;
        top: 0;
        */
        left: 0;
        right: 0;
        bottom: 0;
        animation: pulse 1s ease infinite;
        border-radius: 50%;
        border: 4px double lighten(red, 20%);
    }

    @keyframes pulse {
        0% {
            transform: scale(1);
            opacity: 1;
        }

        60% {
            transform: scale(1.3);
            opacity: 0.4;
        }

        100% {
            transform: scale(1.4);
            opacity: 0;
        }
    }

    .badge {
        background-color: red !important;
        border-radius: 50%;
        color: #fff;
    }

    #CurAvailableItemsContainer a.Product[data-disabled=true] {
        opacity: 0.5;
        cursor: default;
    }
</style>

<section class="content " id="MainContainer" style="margin-top:-50px;">
    <?php echo Forms::ModalLoader('main_pos_modal'); ?>
    <div class="row <?php echo (smc_session()['default_setting']['activate_cash_drawer'] == 1 && !isset(smc_session()['is_cash_drawer_active'])) ? "" : "hidden"; ?>">
        <?php if (empty($cash_drawer_logout)) { ?>
            <div class="col-md-12">
                <div class="alert alert-info ">
                    <?php echo CommonLanguage::getMessage('proceed_cash_drawer'); ?>&nbsp;&nbsp;<a role="button" data-toggle="modal" data-target="#cash-drawer-amount-modal"><?php echo CommonLanguage::getMessage('cash_drawer_amount'); ?></a>
                    <a href="<?= SITE_LINK; ?>smc/doLogout" class="pull-right"><?php print CommonLanguage::getMessage('logout'); ?></a>
                </div>
            </div>
        <?php } else { ?>
            <div class="col-md-12">
                <div class="alert alert-info ">
                    <span><?php echo CommonLanguage::getMessage('already_logged_to_cash_drawer'); ?></span>
                    <span class="red-star"><?php echo $cash_drawer_logout['cash_drawer_title']; ?></span>
                    <span><?php echo CommonLanguage::getMessage('Proceed_Delete'); ?></span>
                    <a role="button" id="continue"><?php echo CommonLanguage::getMessage('continue'); ?></a>
                    <!-- here don't use logout_cash_drawer and logout cash drawer model as not yet 
    filled in session, must continue first then logout -->
                    <!--<a role="button" href="<?= SITE_LINK; ?>smc/doLogout" class="pull-right"><?php echo CommonLanguage::getMessage('logout'); ?></a>-->
                </div>
            </div>
        <?php } ?>
    </div>
    <?php if (!empty($err_msg)) {
    ?>
        <div class="alert alert-danger" role="alert">
            <button class="close" data-dismiss="alert"></button>
            <?php echo $err_msg; ?>
        </div>
    <?php
        die();
    }
    ?>
    <div class=" row <?php echo ((smc_session()['default_setting']['activate_cash_drawer'] == 1 && isset(smc_session()['is_cash_drawer_active'])) || smc_session()['default_setting']['activate_cash_drawer'] == 0) ?: "hidden"; ?>">
        <div class=" col-xs-12 col-sm-12 col-md-12 col-lg-12 Boxed m-b-5" style="background: rgb(76, 8, 112)">
            <input type="hidden" id="invoice_auto_id" value="<?php echo (isset($invoice_details['main_invoice']['Invoice_ID_Auto']) ? $invoice_details['main_invoice']['Invoice_ID_Auto'] : 0); ?>" />
            <input type="hidden" id="is_printed_invoice" value="<?php echo (isset($invoice_details['main_invoice']['is_printed']) && $invoice_details['main_invoice']['is_printed'] == 1) ? 1 : 0; ?>" />
            <div class="row " style="min-height: 66px;">
                <?php // if (smc_session()['default_setting']['activate_smart_diner'] != 1 || $destination == 'delivery') { 
                ?>
                <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4 pull-left cust_dtl_class">
                    <div class="row">
                        <!--<div style="float:left;">-->
                        <div id="hide_class" class="col-xs-4 col-sm-3 col-md-3 col-lg-3 m-t-8 ">
                            <button class="btn-link sm-no-margin">
                                <!--data-type="1" => for invoice  data-type="2" => for return-->
                                <span id="titleSpan" data-type="1" class="dd-color" style='font-size:19px;'> <b><?php echo (smc_session()['default_setting']['activate_smart_diner'] != 1 || $destination == 0) ? 'Invoice' : 'Table ' . $table_name; ?></b><?php echo $is_actual ? '<span class="red-star">*</span>' : '' ?></span>
                            </button>
                        </div>
                        <div id="hide_class2" class="col-xs-5 col-sm-5 col-md-5 col-lg-5 m-t-5 <?php echo $permissions->hasPermission('search_customer') ? '' : 'hidden'; ?>">

                            <input type="text" placeholder="<?php print CommonLanguage::getMessage('customer_name'); ?>" id="CustomerSearch" value="" class="form-control borderStyle" style="min-height:25px;height:25px;" />


                        </div>
                        <?php

                        if ($permissions->hasPermission('add_customer')) {
                            if (smc_session()['default_setting']['add_pos_customer'] == 0) {
                        ?>
                                <div class="col-xs-1 col-sm-1 col-md-1 col-lg-1 dd-color m-t-8">
                                    <span class="fa fa-plus-circle fa-2x m-l-5 openFrame add_nonroad_pos_customer" data-src="Inventory/CustomerList?is_pop=1&new=1" style="color:#DDD;cursor:pointer"></span>
                                </div>
                                <div class="col-xs-1 col-sm-1 col-md-1 col-lg-1 dd-color m-t-8">
                                    <span class="fa fa-bars fa-2x m-l-5 openFrame " data-src="Inventory/CustomerList?is_pop=1" style="color:#DDD;cursor:pointer"></span>
                                </div>
                            <?php } else if (smc_session()['default_setting']['add_pos_customer'] == 1) { ?>
                                <div class="col-xs-1 col-sm-1 col-md-1 col-lg-1 dd-color m-t-8">
                                    <span class="fa fa-plus-circle fa-2x m-l-5 add_pos_customer" style="color:#DDD;cursor:pointer"></span>
                                </div>
                                <div class="col-xs-1 col-sm-1 col-md-1 col-lg-1 dd-color m-t-8">
                                    <span class="fa fa-bars fa-2x m-l-5  " data-toggle="modal" data-target="#road_customer_list" style="color:#DDD;cursor:pointer"></span>
                                </div>
                            <?php } else {
                            ?>
                                <div class="col-xs-1 col-sm-1 col-md-1 col-lg-1 dd-color m-t-8">
                                    <span class="fa fa-plus-circle fa-2x m-l-5 add_both_customer" data-toggle="modal" data-target="#choose_cust_type_modal" style="color:#DDD;cursor:pointer"></span>
                                </div>
                                <div class="col-xs-1 col-sm-1 col-md-1 col-lg-1 dd-color m-t-8" id="hide_elements1">
                                    <span class="fa fa-bars fa-2x m-l-5  both_customer_list" data-toggle="modal" data-target="#choose_cust_type_modal" style="color:#DDD;cursor:pointer"></span>
                                </div>
                            <?php
                            }
                        }
                        if ($permissions->hasPermission('view_caller_id')) {
                            ?>
                            <div hidden class="col-xs-1 col-sm-1 col-md-1 col-lg-1 dd-color m-t-8 " id="hide_elements2">
                                <span id="add_caller" class="fa fa-phone fa-2x m-l-5 " style="color:#DDD;cursor:pointer"></span>
                            </div>
                        <?php } ?>
                        <!-- Yousif Menu -->
                        <div class="col-xs-1 col-sm-1 col-md-1 col-lg-1 dd-color m-t-8 " id="hide_elements3">
                            <span id="left_menu" class="fa fa-caret-square-o-down fa-2x m-l-5" style="color:#DDD;cursor:pointer"></span>
                        </div>

                    </div>
                    <div class="row">
                        <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
                            <div class=" dd-color" id="CurCustomerInfo" CurCustomerID="0" customer-pos-id="0" data-is-pos="0" data-tax="<?php echo smc_session()['default_setting']['activate_card_tax'] == 1 ? smc_session()['class_tax'] : 0 ?>">
                            </div>
                        </div>
                    </div>
                </div>
                <?php // } else {  
                ?>
                <!--                    <div class="col-xs-2 col-sm-2 col-md-2 col-lg-2 m-t-20 p-l-0">
<span  class="dd-color" style='font-size:20px;'> <strong>Table <?php echo $table_name; ?></strong></span>
</div>-->
                <?php // }  
                ?>
                <!--<div class="col-xs-<?php // echo (smc_session()['default_setting']['activate_smart_diner'] == 1 && $destination != 'delivery') ? '10' : '8';                                                                                                                                                                                         
                                        ?> col-sm-<?php // echo (smc_session()['default_setting']['activate_smart_diner'] == 1 && $destination != 'delivery') ? '10' : '8';                                                                                                                                                                                         
                                                    ?> col-md-<?php // echo (smc_session()['default_setting']['activate_smart_diner'] == 1 && $destination != 'delivery') ? '10' : '8';                                                                                                                                                                                         
                                                                ?>  col-lg-<?php // echo (smc_session()['default_setting']['activate_smart_diner'] == 1 && $destination != 'delivery') ? '10' : '8';                                                                                                                                                                                         
                                                                            ?>">-->
                <div class="col-xs-8 col-sm-8 col-md-8  col-lg-8">
                    <div class="row">
                        <div class="header-button">
                            <a href="javascript:;" onclick="doLogoutSystem()">
                                <span class="fa fa-2x fa-power-off m-t-8" style="color:red;" title="<?= CommonLanguage::getMessage('logout'); ?>"></span>
                            </a>
                        </div>
                        <!--<div class="header-button" id="open_functions_modal">
<a href="javascript:;" onclick="go_full_screen()" title="<?= CommonLanguage::getMessage('full_screen'); ?>">
<span class="fa fa-arrows"></span>
</a>
</div>-->
                        <div class="header-button" id="open_functions_modal">
                            <a href="javascript:;">
                                <?php echo CommonLanguage::getMessage('functions'); ?>
                            </a>
                        </div>
                        <?php if ($permissions->hasPermission('administration')) { ?>
                            <div class="header-button">
                                <a href="<?php echo SITE_LINK . (smc_session()['default_setting']['activate_smart_diner'] == 1 ? 'main_page' : 'Inventory'); ?>">
                                    <?php echo CommonLanguage::getMessage(smc_session()['default_setting']['activate_smart_diner'] == 1 ? 'tables' : 'admin'); ?>
                                </a>
                            </div>
                        <?php
                        }
                        if (($permissions->hasPermission('table_void_pos') && smc_session()['default_setting']['activate_smart_diner'] == 1 && isset($invoice_details['main_invoice']['Invoice_ID_Auto'])) || ($permissions->hasPermission('main_void_pos') && $destination == 0)) {
                        ?>
                            <div class="header-button" id="refresh">
                                <a readonly="true">
                                    <?php echo CommonLanguage::getMessage('void'); ?>
                                </a>
                            </div>
                        <?php }
                        if ((smc_session()['default_setting']['activate_smart_diner'] != 1 || $destination == 0) && $permissions->hasPermission('retrieve_list')) { ?>
                            <div id="hide_element10" class="header-button delivery_count" onclick="$('#retrieveSales:enabled').click()">
                                <a>
                                    <i class="fa fa-bell"><span class="badge badge-danger" id="delivery_count"></span></i>
                                </a>
                            </div>
                        <?php } ?>
                        <div class="header-button <?php echo ($permissions->hasPermission('change_pos_price_class')) ? '' : 'hidden' ?>  customer_class_div" id="hide_elements5">
                            <select required id="Customer_Class_ID" name="Customer_Class_ID" class="full-width common-print " data-init-plugin="select2">
                                <?php foreach ($classes as $class) : ?>
                                    <option value="<?php echo $class['Class_ID']; ?>" <?php echo $class['Class_ID'] == smc_session()['pricing_class_id'] ? 'selected' : '' ?> data-currency="<?php echo $class['Currency_ID'] ?>"><?php echo $class['Class_Name']; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <?php if ($permissions->hasPermission('show_person_in_charge')) { ?>
                            <div class="header-button depot_pic_div" style="width:15% !important" id="hide_elements6">
                                <input required id="Depot_PIC_ID" name="Depot_PIC_ID" class="full-width Depot_PIC_ID common-print" type="hidden" />
                            </div>
                        <?php }
                        if ((smc_session()['default_setting']['activate_smart_diner'] != 1 || (smc_session()['default_setting']['activate_smart_diner'] == 1 && $destination == 0)) && $permissions->hasPermission('park')) {
                        ?>
                            <div id="hide_element11" class="header-button park_div_btn" onclick="$('#addtoPark:enabled').trigger('click')">
                                <a class="btn btn-primary btn-sm common-order-btn-to-disable">
                                    <?php echo CommonLanguage::getMessage((smc_session()['default_setting']['activate_smart_diner'] != 1 || $destination == 'delivery') ? 'park' : 'kitchen'); ?>
                                </a>
                            </div>
                        <?php }
                        if ($permissions->hasPermission('delivery') && $destination == 0) { ?>
                            <div id="hide_element12" class="header-button common_delivery_div_btn">
                                <a class="btn btn-primary btn-sm common_delivery">
                                    <?php echo CommonLanguage::getMessage('delivery'); ?>
                                </a>
                            </div>
                        <?php }
                        if ($permissions->hasPermission('order_pos') && $destination == 0) { ?>
                            <div class="header-button  order_pos_div_btn">
                                <a class="btn btn-primary btn-sm order_pos_btn" data-print-type="1">
                                    <?php echo CommonLanguage::getMessage('order'); ?>
                                </a>
                            </div>
                        <?php }
                        if ($permissions->hasPermission('order_pos_without_print') && $destination == 0) { ?>
                            <div class="header-button order_pos_div_btn">
                                <a class="btn btn-primary btn-sm order_pos_btn" data-print-type="0">
                                    <?php echo CommonLanguage::getMessage('order_no_print'); ?>
                                </a>
                            </div>
                        <?php }
                        if ($permissions->hasPermission('pos_request_transfer') && $destination == 0) { ?>
                            <div class="header-button transfer_pos_btn hidden">
                                <a class="btn btn-primary btn-sm ">
                                    <?php echo CommonLanguage::getMessage('transfer'); ?>
                                </a>
                            </div>
                        <?php }
                        if (smc_session()['default_setting']['activate_smart_diner'] == 1 && $destination != 0) { ?>
                            <div id="hide_elements4" class="header-button spinner-icons">
                                <span class="fa fa-minus"></span>
                                <input type="text" name="Persons_Count" id="Persons_Count" class="form-control borderStyle m-t-5 common-print" value="<?php echo isset($invoice_details['main_invoice']['Persons_Count']) ? $invoice_details['main_invoice']['Persons_Count'] : 0; ?>" placeholder="<?php print CommonLanguage::getMessage('persons_count'); ?>" style="width:90px;">
                                <span class="fa fa-plus"></span>
                            </div>
                        <?php }
                        if (smc_session()['default_setting']['activate_smart_diner'] == 1 && $destination == 0 && smc_session()['default_setting']['is_sync_active'] == 1 && $permissions->hasPermission('delivery_list')) { ?>
                            <div class="header-button">
                                <a class="btn btn-primary " id="open_online">
                                    <?php print CommonLanguage::getMessage('online'); ?>
                                    <span class="badge float-right" id="online_orders_count">0</span>
                                </a>
                                <div id="snackbar"></div>
                            </div>
                        <?php }
                        if ($permissions->hasPermission('add_posponted_invoice') && $destination == 0) { ?>
                            <div id="hide_element13" class="header-button postponed_div_btn">
                                <button class="btn btn-primary btn-sm add_posponted_data_btn" data-toggle="modal" data-target="#add_posponted_data"><?php echo CommonLanguage::getMessage('posponted') ?></button>
                                <!--<input type="text" id="posponted_date" class="form-control" title="<?php echo CommonLanguage::getMessage('posponted_date') ?>"/>-->
                            </div>
                        <?php }
                        if ($permissions->hasPermission('show_product_recipe')) { ?>
                            <div class="header-button " id="hide_elements7">
                                <i class="fa fa-book fa-2x show_product_recipe  m-t-8 "></i>
                            </div>
                        <?php } ?>
                        <div class="header-button language-pos">
                            <div class="dropdown " style="">
                                <a href="javascript:void(0);" id="" class="" data-toggle="dropdown" aria-expanded="true"><?php echo $Language === 'en' ? 'EN' : ($Language === 'fr' ? 'FR' : 'AR'); ?>
                                </a>
                                <div class="dropdown-menu notification-toggle" role="menu" aria-labelledby="notification-center">
                                    <div class="col-md-12" style="text-align:center">
                                        <div class="radio radio-success " id="Language">
                                            <input type="radio" value="en" <?php echo $Language === 'en' ? 'checked="checked"' : ''; ?> name="User_language" id="en">
                                            <label for="en"><?php print CommonLanguage::getMessage('english'); ?> </label>
                                            <input type="radio" value="ar" <?php echo $Language === 'ar' ? 'checked="checked"' : ''; ?> name="User_language" id="ar">
                                            <label for="ar"><?php print CommonLanguage::getMessage('arabic'); ?></label>
                                            <input type="radio" value="fr" <?php echo $Language === 'fr' ? 'checked="checked"' : ''; ?> name="User_language" id="fr">
                                            <label for="fr"><?php print CommonLanguage::getMessage('french'); ?></label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div id="scan_bar_code_bar"></div>
                        <div class="header-button transfer_split_action_submit transfer_items_details hidden">
                            <button class="btn btn-primary" data-content="2" id="transfer_action"><?php echo CommonLanguage::getMessage('transfer'); ?></button>
                            <button class="btn btn-default" id="cancel_transfer"><?php echo CommonLanguage::getMessage('cancel'); ?></button>
                        </div>
                        <div class="header-button <?php echo (smc_session()['default_setting']['activate_pos_hold_fire'] == 1 && smc_session()['default_setting']['activate_smart_diner'] == 1 && $destination > 0) ? '' : 'hidden' ?>">
                            <span id="show_fire_tab" class="fa fa-2x fa-fire" style="cyrsor:pointer"></span>
                        </div>
                        <?php if (smc_session()['default_setting']['activate_pos_orders_notification'] == 1) { ?>
                            <div class=" header-button">
                                <a href="<?php echo SITE_LINK; ?>Inventory/quotationOrderList/order/sales" class="badge pulsate m-t-10" id="total_orders_pending"></a>
                            </div>
                        <?php } ?>

                    </div>
                    <!--                    <div class="row header-second">
<div class="col-md-2 pull-right < ?php echo $permissions->hasPermission('add_posponted_invoice') ? '' : 'hidden'?>">
<button class="btn btn-primary" data-toggle="modal" data-target="#add_posponted_data">< ?php echo CommonLanguage::getMessage('posponted') ?></button>
<input type="text" id="posponted_date" class="form-control" title="< ?php echo CommonLanguage::getMessage('posponted_date') ?>"/>
</div>
</div>-->
                </div>
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
            <div id="remove_flex" class="row is-flex">



                <div class=" RightBox col-xs-6 col-sm-6 col-md-6 col-lg-6 " style="width:<?php echo 100 - smc_session()['default_setting']['pos_menu_width']; ?>%;">
                    <table id="hold_fire_table" class="table table-bordered hidden">
                        <tbody>
                            <tr>
                                <td class="hold" data-role="1"><?php echo CommonLanguage::getMessage('hold') ?>&nbsp;1</td>
                                <td class="hold" data-role="2"><?php echo CommonLanguage::getMessage('hold') ?> 2</td>
                                <td class="hold" data-role="3"><?php echo CommonLanguage::getMessage('hold') ?> 3</td>
                                <td class="fire" data-role="1"><?php echo CommonLanguage::getMessage('fire') ?> 1</td>
                                <td class="fire" data-role="2"><?php echo CommonLanguage::getMessage('fire') ?> 2</td>
                                <td class="fire" data-role="3"><?php echo CommonLanguage::getMessage('fire') ?> 3</td>
                                <td class="unhold"><?php echo CommonLanguage::getMessage('unhold') ?></td>
                            </tr>
                        </tbody>
                    </table>
                    <fieldset class="he">
                        <div class="LeftTableContainer col-xs-12 col-sm-12 col-md-12 col-lg-12  no-padding">
                            <div class="table-responsive Boxed">
                                <table class="table table-hover" cellpadding="0" cellspacing="0" id="OrderTable">
                                    <thead>
                                        <tr>
                                            <th class="hidden transfer_items_details" style="width: 2%"></th>
                                            <th style="width: 2%">#</th>
                                            <th style="width: 2%" class="<?php echo (smc_session()['default_setting']['activate_pos_hold_fire'] == 1 && smc_session()['default_setting']['activate_smart_diner'] == 1 && $destination > 0) ? '' : 'hidden' ?>"></th>
                                            <th style="width: 15%"><?php print CommonLanguage::getMessage('Name'); ?></th>
                                            <th style="width: 10%"><?php print CommonLanguage::getMessage('qty'); ?></th>
                                            <th style="width: 10%" class="<?php echo smc_session()['default_setting']['activate_uom_in_pos'] == 1 ? '' : 'hidden'; ?>"><?php print CommonLanguage::getMessage('UOM'); ?></th>
                                            <th style="width: 10%" class="price_element <?php echo $permissions->hasPermission('show_all_prices') ? '' : 'hidden'; ?>"><?php print CommonLanguage::getMessage('Price'); ?></th>
                                            <th style="width: 5%" class="<?php echo (smc_session()['default_setting']['activate_discount_pos'] == 1 && $permissions->hasPermission('show_all_prices')) ? '' : 'hidden'; ?>"><?php print CommonLanguage::getMessage('disc'); ?></th>
                                            <th style="width: 10%" class="price_element <?php echo $permissions->hasPermission('show_all_prices') ? '' : 'hidden'; ?>"><?php print CommonLanguage::getMessage('total'); ?></th>
                                            <th style="width: 10%" class="<?php echo smc_session()['default_setting']['activate_pos_product_description'] == 1 ? '' : 'hidden'; ?>"><?php print CommonLanguage::getMessage('Description'); ?></th>
                                            <th style="width: 10%" class="<?php echo smc_session()['default_setting']['is_tag_active'] == 1 ? '' : 'hidden'; ?>"><?php print CommonLanguage::getMessage('tag'); ?></th>
                                            <th style="width: 5%" class="<?php echo smc_session()['default_setting']['activate_product_duration_reservation'] == 1 ? '' : 'hidden'; ?>"><?php print CommonLanguage::getMessage('reserve_date'); ?></th>
                                            <th style="width: 5%" class="<?php echo (smc_session()['default_setting']['activate_expiry_date'] == 1 || !in_array(0, $pos_fields_to_hide) || !in_array(1, $pos_fields_to_hide)) ? '' : 'hidden'; ?>"><i class="fa fa-info-circle"></i></th>
                                            <th style="width: 5%" class="<?php // echo $permissions->hasPermission('delete_row_pos') ? '' : 'hidden';                                                                                                                                                           
                                                                            ?>"></th>
                                            <th style="width: 5%" class=""></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </fieldset>
                    <div class="LeftTableContainer col-xs-12 col-sm-12 col-md-12 col-lg-12 no-padding">
                        <div class="row is-flex p-l-5">
                            <div class="col-xs-6 col-sm-6 col-md-6 col-lg-6 m-t-5  totals_pos_btns_div">
                                <div class="row TotalTableRow Boxed price_element <?php echo $permissions->hasPermission('show_all_prices') ? '' : 'hidden'; ?>">
                                    <table class="table table-responsive full-height" cellpadding="0" cellspacing="0" id="TotalTable">
                                        <tr>
                                            <td style="width: 65%;"><span class="TotalSpanInTable"><?php print CommonLanguage::getMessage('subtotal'); ?> </span></td>
                                            <td class="SubtotalVal">0</td>
                                        </tr>
                                        <tr data-discount="0" class="invoice-discount-tr-class">
                                            <td><span class="TotalSpanInTable discount-span-input-per" style="display:flex;"><?php print CommonLanguage::getMessage('disc'); ?><input id="DiscountInput" class="form-control <?php echo (!$permissions->hasPermission('discount_on_invoice')) ? 'initial_disable current_disable' : '' ?>" <?php echo (!$permissions->hasPermission('discount_on_invoice')) ? 'disabled' : '' ?> style="max-width:50px;display:flex;min-height:22px !important;height: 22px !important;padding:2px;margin-left:5px;" /> %
                                                    <!--<span class="discount <?php echo (!$permissions->hasPermission('discount_on_invoice')) ? 'initial_disable current_disable' : '' ?>">0 %</span>-->
                                                </span></td>
                                            <!--<td class="DiscountVal">0</td>-->
                                            <td class="DiscountVal"><input type='text' style='background:#e5e5e5;border:none' class='DiscountValue <?php echo (!$permissions->hasPermission('discount_on_invoice')) ? 'initial_disable current_disable' : '' ?>' <?php echo (!$permissions->hasPermission('discount_on_invoice')) ? 'disabled' : '' ?> value='0' /> </td>
                                        </tr>
                                        <tr class="<?php echo smc_session()['default_setting']['activate_ttc'] ? '' : 'hidden' ?>">
                                            <td><span class="TotalSpanInTable"><?php print CommonLanguage::getMessage('ttc_discount'); ?> </span></td>
                                            <!--<td class="DiscountVal">0</td>-->
                                            <td class="TTCDiscountVal"><input type='text' style='background:#e5e5e5;border:none' class='TTCDiscountValue <?php echo (!$permissions->hasPermission('discount_on_invoice')) ? 'initial_disable current_disable' : '' ?>' <?php echo (!$permissions->hasPermission('discount_on_invoice')) ? 'disabled' : '' ?> value='0' /> </td>
                                        </tr>

                                        <?php

                                        if (!$isTable) {
                                            if (smc_session()['default_setting']['pos_service'] > 0) { ?>
                                                <tr>
                                                    <td><span class="TotalSpanInTable"><?php print CommonLanguage::getMessage('service'); ?></span></td>
                                                    <td class="ServiceVal"><span class="service" data-value="<?php echo smc_session()['default_setting']['pos_service']; ?>"><?php echo smc_session()['default_setting']['pos_service']; ?></span> %</td>
                                                </tr>
                                            <?php } else { ?>
                                                <tr>
                                                    <td><span class="TotalSpanInTable"><?php print CommonLanguage::getMessage('vat'); ?></span></td>
                                                    <td class="TVAVal">0 %</td>
                                                </tr>
                                            <?php }
                                        } else { ?>
                                            <tr>
                                                <td><span class="TotalSpanInTable"><?php print "Table"; ?></span></td>
                                                <td class="ServiceVal"><span class="service" data-value="<?php echo smc_session()['default_setting']['table_vat']; ?>"><?php echo smc_session()['default_setting']['table_vat']; ?></span> %</td>
                                            </tr>
                                        <?php  } ?>


                                        <tr class="<?php echo smc_session()['default_setting']['activate_card_tax'] == 0 ? 'hidden' : '' ?>">
                                            <td><span class="TotalSpanInTable"><?php print CommonLanguage::getMessage('card_tax'); ?></span></td>
                                            <td class="tax_amount">0</td>
                                        </tr>
                                        <tr>
                                            <td><span class="TotalSpanInTable"><?php print CommonLanguage::getMessage('delivery'); ?></span></td>
                                            <td class="shipping_val"></td>
                                        </tr>
                                        <tr class="">
                                            <td style="padding:0px !important;"><span class="TotalSpanInTable TotalItem" style="font-size:21px !important;color:red;"><?php print CommonLanguage::getMessage('total'); ?></span></td>
                                            <td class="TotalVal" style="padding:0px !important;font-size:21px !important;color:red;">0</td>
                                        </tr>
                                        <tr class="TotalValue1">
                                            <td style="border-top: 0"><span class="TotalSpanInTable"></span></td>
                                            <td class="SecondCurrencyVal" style="border: 0;padding-top: 0;">0</td>
                                        </tr>
                                    </table>
                                </div>
                                <div class="row InvoicesBtnRow">
                                    <div class=" col-md-12 submit_main_div">
                                        <div class="col-xs-6 col-sm-6 col-md-6 col-lg-6 ">
                                            <button id="CashInvBtn" type="submit" class="btn btn-info <?php echo !$permissions->hasPermission('cash_generate_invoice') ? 'hidden' : ((!isset($invoice_details['main_invoice']['Invoice_ID_Auto']) && (smc_session()['default_setting']['activate_smart_diner'] == 1 && $destination != 0) && smc_session()['default_setting']['open_table_cash'] == 0) ? 'hidden' : ''); ?>"><i class="fa fa-money"></i> <?php print CommonLanguage::getMessage('cash') . (smc_session()['default_setting']['activate_pos_shortcust_keys'] == 1 ? ' (alt+1 or F1)' : '') ?></button>
                                        </div>
                                        <div class="col-xs-6 col-sm-6 col-md-6 col-lg-6 ">
                                            <button id="GInvBtn" type="submit" class="btn btn-info <?php echo !$permissions->hasPermission('cash_generate_invoice') ? 'hidden' : ((!isset($invoice_details['main_invoice']['Invoice_ID_Auto']) && (smc_session()['default_setting']['activate_smart_diner'] == 1 && $destination != 0) && smc_session()['default_setting']['open_table_cash'] == 0) ? 'hidden' : ''); ?>"><i class="fa fa-money"></i> <?php print CommonLanguage::getMessage('generate') . (smc_session()['default_setting']['activate_pos_shortcust_keys'] == 1 ? ' (alt+2 or F2)' : '') ?></button>
                                        </div>
                                        <div class="col-xs-6 col-sm-6 col-md-6 col-lg-6  m-t-5">
                                            <button id="CashWithoutPrintInvBtn" type="submit" class="btn btn-info <?php echo !$permissions->hasPermission('pos_cash_without_print') ? 'hidden' : ((!isset($invoice_details['main_invoice']['Invoice_ID_Auto']) && (smc_session()['default_setting']['activate_smart_diner'] == 1 && $destination != 0) && smc_session()['default_setting']['open_table_cash'] == 0) ? 'hidden' : ''); ?>"><i class="fa fa-money"></i> <?php print CommonLanguage::getMessage('cash_without_print') . (smc_session()['default_setting']['activate_pos_shortcust_keys'] == 1 ? ' (alt+3 or F3)' : '') ?></button>
                                        </div>
                                        <?php if (smc_session()['default_setting']['activate_smart_diner'] == 1 && $destination != 0 && $permissions->hasPermission('pos_submit_to_kitchen')) { ?>
                                            <div class="col-xs-6 col-sm-6 col-md-6 col-lg-6  m-t-5">
                                                <button id="table_kitchen_btn" type="submit" class="btn btn-info" onclick="$('#addtoPark:enabled').trigger('click')"><i class="fal fa-utensils"></i><?php print CommonLanguage::getMessage('kitchen') . (smc_session()['default_setting']['activate_pos_shortcust_keys'] == 1 ? ' (alt+4 or F4)' : '') ?></button>
                                            </div>
                                        <?php } elseif ($permissions->hasPermission('delivery_takeaway_kitchen') && $permissions->hasPermission('pos_submit_to_kitchen')) { ?>
                                            <div class="col-xs-6 col-sm-6 col-md-6 col-lg-6  m-t-5">
                                                <button type="submit" class="btn btn-info" id="kitchen_delivery_takeaway" data-type="kitchen_takeaway_delivery"><i class="fal fa-utensils"></i><?php print CommonLanguage::getMessage('kitchen') . (smc_session()['default_setting']['activate_pos_shortcust_keys'] == 1 ? ' (alt+4 or F4)' : '') ?></button>
                                            </div>
                                        <?php }
                                        if ((smc_session()['user_details']['login_device'] != 2 && !empty($invoice_details['main_invoice']['table_status_id']) && $invoice_details['main_invoice']['table_status_id'] == 2) && $permissions->hasPermission('print_invoice_table_pos')) { ?>
                                            <div class="col-xs-6 col-sm-6 col-md-6 col-lg-6  m-t-5">
                                                <button type="submit" class="btn btn-info" id="print_table_invoice" data-table-id="<?php echo isset($invoice_details['main_invoice']['table_id']) ? $invoice_details['main_invoice']['table_id'] : ''; ?>"><i class="fa fa-print"></i> <?php print CommonLanguage::getMessage('print') ?></button>
                                            </div>
                                        <?php } ?>
                                        <div class="col-xs-6 col-sm-6 col-md-6 col-lg-6  m-t-5">
                                            <button type="submit" class="btn btn-info <?php echo !$permissions->hasPermission('credit_card_generate_invoice') ? 'hidden' : ((!isset($invoice_details['main_invoice']['Invoice_ID_Auto']) && (smc_session()['default_setting']['activate_smart_diner'] == 1 && $destination != 0) && smc_session()['default_setting']['open_table_cash'] == 0) ? 'hidden' : ''); ?>" id="generate_credit_card"><i class="fa fa-print"></i> <?php print CommonLanguage::getMessage('credit_card') ?></button>
                                        </div>
                                        <?php (function_exists('smc__extend_pos_buttons') ? smc__extend_pos_buttons() : ''); ?>
                                    </div>
                                </div>
                            </div>
                            <div class="col-xs-6 col-sm-6 col-md-6 col-lg-6 m-t-5 calculator_div">
                                <table id="keypad" style="<?php echo $permissions->hasPermission('show_all_prices') ? '' : 'height:270px;'; ?>">
                                    <tr>
                                        <td class="key" tabindex="0">1</td>
                                        <td class="key" tabindex="0">2</td>
                                        <td class="key" tabindex="0">3</td>
                                        <td class="key1 all-caps" data-flag="2" data-role="QTY"><?php print CommonLanguage::getMessage("qty") ?></td>
                                        <?php if ($permissions->hasPermission('delete_row_pos')) { ?>
                                            <td class="key" data-role="TRASH"><i class="fa fa-trash"></i></td>
                                        <?php } else { ?>
                                            <td class="key1 empty_key not-allowed"></td>
                                        <?php } ?>
                                        <!--<td class="key1 " data-role="TAG" ><i class="fa fa-tags"></i></td>-->
                                    </tr>
                                    <tr>
                                        <td class="key" tabindex="0">4</td>
                                        <td class="key" tabindex="0">5</td>
                                        <td class="key" tabindex="0">6</td>
                                        <?php if (smc_session()['default_setting']['activate_discount_pos'] == 1 && $permissions->hasPermission('show_all_prices')) { ?>
                                            <td class="key1 all-caps <?php echo (!$permissions->hasPermission('discount_on_item')) ? 'initial_disable current_disable not-allowed' : '' ?>" data-role="DISC"><?php print CommonLanguage::getMessage("disc") ?></td>
                                        <?php } else { ?>
                                            <td class="key1 empty_key not-allowed"></td>
                                        <?php } ?>
                                        <?php if ($permissions->hasPermission('show_all_prices')) { ?>
                                            <td class="key1 <?php echo (!$permissions->hasPermission('pos_scale') || !$permissions->hasPermission('change_pos_price')) ? 'empty_key not-allowed' : '' ?>" <?php echo ($permissions->hasPermission('change_pos_price') && $permissions->hasPermission('pos_scale')) ? 'data-role="total_price"' : '' ?>><i class="fa fa-balance-scale"></i></td>
                                        <?php } else { ?>
                                            <td class="key1 empty_key not-allowed"></td>
                                        <?php } ?>
                                    </tr>
                                    <tr>
                                        <td class="key" tabindex="0">7</td>
                                        <td class="key" tabindex="0">8</td>
                                        <td class="key" tabindex="0">9</td>
                                        <?php if ($permissions->hasPermission('show_all_prices')) { ?>
                                            <td class="key1 fa-22 key-price <?php echo !$permissions->hasPermission('change_pos_price') ? 'not-allowed empty_key ' : '' ?>" <?php echo $permissions->hasPermission('change_pos_price') ? 'data-role="PRICE"' : '' ?>><i class="fa fa-money "></i></td>
                                        <?php } else { ?>
                                            <td class="key1 empty_key not-allowed"></td>
                                        <?php } ?>
                                        <td class="key1" data-role="open-cash-drawer"><i class="fa fa-print"></i></td>
                                    </tr>
                                    <tr>
                                        <td class="key" tabindex="0">.</td>
                                        <td class="key" tabindex="0">0</td>
                                        <td class="key1 all-caps" data-role="CLR" tabindex="0"><?php print CommonLanguage::getMessage("clr") ?></td>
                                        <td class="key1" data-role="DEL" tabindex="0"><i class="fa fa-arrow-left"></i></td>
                                        <td class="key1 note-key"><i class="fa fa-sticky-note"></i></td>
                                    </tr>
                                    <tr>
                                        <?php if ($permissions->hasPermission('exchange_pos')) { ?>
                                            <td class="key1 empty not-allowed" data-role="neg">-</td>
                                        <?php } else { ?>
                                            <td class="key1 empty_key not-allowed"></td>
                                        <?php } ?>
                                        <?php if ($permissions->hasPermission('Inventory')) { ?>
                                            <td class="key1 empty_key "><a href="<?php echo SITE_LINK; ?>Inventory" class="text-black"><i class="fa fa-archive"></i></a></td>
                                        <?php } else { ?>
                                            <td class="key1 empty_key not-allowed"></td>
                                        <?php } ?>
                                        <td class="key1 empty_key not-allowed"></td>
                                        <td class="key1  <?php echo !$permissions->hasPermission('pos_split_discount_row') ? 'not-allowed empty_key ' : '' ?>" <?php echo $permissions->hasPermission('pos_split_discount_row') ? 'data-role="split_row"' : '' ?>><i class="fa fa-cut fa-2x"></i></td>
                                        <?php if (smc_session()['default_setting']['is_tag_active'] == 1) { ?>
                                            <td class="key1 " data-role="TAG"><i class="fa fa-tags"></i></td>
                                        <?php } else { ?>
                                            <td class="key1 empty_key not-allowed"></td>
                                        <?php } ?>
                                    </tr>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <div id="LeftBox" class=" LeftBox col-xs-6 col-sm-6 col-md-6  col-lg-6   <?php echo smc_session()['default_setting']['pos_menu_width'] == 0 ? 'hidden' : ''; ?>" style="text-align:right;width:<?php echo smc_session()['default_setting']['pos_menu_width']; ?>%;">
                    <div id="RightBoxContents" class="Boxed tab-content full-height" style="<?php !$permissions->hasPermission('show_scrolled_category') ? 'height:572px !important;' : ''; ?>">
                        <div class="tab-pane fade in active" id="Tab_1">
                            <div class="row p-b-5">
                                <?php if ($permissions->hasPermission('search_pos_product')) { ?>
                                    <div id="CategoriesSearch">
                                        <input type="text" placeholder="<?php print CommonLanguage::getMessage('search') ?>" id="product_search" class="form-control borderStyle common-print" />
                                        <i class="fa fa-search"></i>
                                    </div>
                                <?php }
                                if ($permissions->hasPermission('search_pos_barcode')) { ?>
                                    <div id="BarcodeSearch">
                                        <input type="text" id="barcode_search_input" placeholder="<?php print CommonLanguage::getMessage('search_barcode') ?>" class="form-control borderStyle common-print" />
                                        <i class="fa fa-barcode"></i>
                                    </div>
                                <?php } ?>
                                <ul id="CurCategory_Crumbs" class="<?php echo (smc_session()['activate_pos_select_cat'] == 1 ? "hidden" : ""); ?>"></ul>
                                <?php // if (smc_session()['activate_pos_select_cat'] == 1) { 
                                ?>
                                <div class="col-md-4 <?php echo smc_session()['activate_pos_select_cat'] == 1 ? '' : 'hidden' ?>" style="top:5px;display:inline-flex">
                                    <a href="javascript:GotoCateg(-1);"><i class="fa fa-home fa-2x"></i></a>&nbsp;&nbsp;
                                    <select id="activate_cat_id" name="activate_cat_id" class="full-width " data-init-plugin="select2">
                                        <option value="0">Home</option>
                                        <?php foreach ($active_cat as $key => $cat_id) : ?>
                                            <option value="<?php echo $cat_id[0]; ?>" <?php echo $default_cat_id == $cat_id[0] ? 'selected' : ''; ?>><?php echo $cat_id[1]; ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <?php // } 
                                ?>
                            </div>
                            <div class="row" id="CurAvailableItemsContainer">
                                <ul id="CurAvailableItems" class="Categories"></ul>
                            </div>
                            <ol id="PageIndicatorHandler" class="carousel-indicators" style="max-height:50px;overflow:hidden;width:100%;left:0;right:0;margin:0 auto;"></ol>
                        </div>
                    </div>
                    <?php if ($permissions->hasPermission('show_scrolled_category')) { ?>
                        <div id='scroll_div_main_cat'>
                            <div class="row m-t-5 scroll-div-scrollable dragscroll" style="overflow-x:scroll;">
                                <ul id="MainCat">
                                    <div class='scroll-div-contents' style="display:inline-flex;">
                                        <?php foreach ($categories as $category) : ?>
                                            <div class="catli <?php echo !empty($category[2]) ? '' : 'not-allowed'; ?>" style="background-color:#4c0871;color: white;">
                                                <span data-id="<?php echo $category[0] ?>" data-name="<?php echo $category[1] ?>" class="text-white"><?php echo $category[1] ?>
                                                </span>
                                            </div>
                                        <?php endforeach; ?>
                                        <span class='scroll-div-active-item'></span>
                                    </div>
                                </ul>
                            </div>
                        </div>
                    <?php } ?>
                </div>
            </div>
        </div>
    </div>
    <?php if ($permissions->hasPermission('show_list_in_pos') && $destination == 0) { ?>
        <div class="row m-t-10 <?php echo ((smc_session()['default_setting']['activate_cash_drawer'] == 1 && isset(smc_session()['is_cash_drawer_active'])) || smc_session()['default_setting']['activate_cash_drawer'] == 0) ?: "hidden"; ?>">
            <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 main_pos_invoice_list_div">
                <div class="table-responsive">
                    <table class="table table-hover demo-table-search" id="main_pos_invoice_list">
                        <thead>
                            <tr>
                                <th class="text-center" style="width:1%">#</th>
                                <th class="text-center" style="width:3%"><?php echo CommonLanguage::getMessage('time'); ?></th>
                                <th class="text-center" style="width:4%"><?php echo CommonLanguage::getMessage('customer'); ?></th>
                                <th class="text-center"><?php echo CommonLanguage::getMessage('address'); ?></th>
                                <th class="text-center" style="width:4%"><?php echo CommonLanguage::getMessage('phone'); ?></th>
                                <th class="text-center" style="width:4%"><?php echo CommonLanguage::getMessage('description'); ?></th>
                                <?php if (!in_array(5, $pos_fields_hide)) { ?>
                                    <th class="text-center" style="width:4%"><?php echo CommonLanguage::getMessage('driver'); ?></th>

                                <?php } ?>
                                <th class="text-center" style="width:4%"><?php echo CommonLanguage::getMessage('Type'); ?></th>
                                <th class="text-center" style="width:5%"><?php echo CommonLanguage::getMessage('Action'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    <?php } ?>
</section>
<?php if ($permissions->hasPermission('show_delivery_notification')) { ?>
    <div class="quickview-wrapper   builder hidden-sm hidden-xs <?php echo ((smc_session()['default_setting']['activate_cash_drawer'] == 1 && isset(smc_session()['is_cash_drawer_active'])) || smc_session()['default_setting']['activate_cash_drawer'] == 0) ?: "hidden"; ?>" id="builder">
        <a class="builder-toggle" data-toggle="quickview" data-toggle-element="#builder"><i class="pg pg-theme"></i></a>
        <div class="tab-content m-t-10 quickerleft p-l-10 p-r-10" style="    overflow-x: scroll;">
            <div class="row">
                <div class="col-md-12 tabe-responsive">
                    <table class=" table table-bordered" id="RemindersTable">
                        <thead>
                            <tr>
                                <th class="text-center" style="width:5%">#</th>
                                <th class="text-center" style="width:10%"><?php print CommonLanguage::getMessage('customer_name'); ?></th>
                                <th class="text-center" style="width:10%"><?php print CommonLanguage::getMessage('Date'); ?></th>
                                <th class="text-center" style="width:10%"><?php print CommonLanguage::getMessage('Action'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                    </table>
                </div>
            </div>
        </div>
        <?php echo Forms::ModalLoader('delivery_notification_loader'); ?>
    </div>
<?php } ?>
<!-- uom select -->
<select required name="UOM_Select" class="full-width UOM_Select hidden ">
    <?php foreach ($all_uom as $uom) : ?>
        <option value="<?php echo $uom['UOM_ID']; ?>"><?php echo $uom['UOM_Name']; ?></option>
    <?php endforeach; ?>
</select>
<script>
    var CompanyLang = <?php echo json_encode(CommonLanguage::getMessage('company')); ?>,
        nb_person_required = <?php echo json_encode(CommonLanguage::getMessage('nb_person_required')); ?>,
        cont_split_trans = <?php echo json_encode(CommonLanguage::getMessage('cont_split_trans')); ?>,
        kitchen_takeaway_delivery = 0,
        is_order = <?php echo json_encode($IsOrder ? 1 : 0); ?>,
        pos_orders_notification = <?php echo json_encode(smc_session()['default_setting']['activate_pos_orders_notification']); ?>,
        is_smart_diner = <?php echo json_encode(smc_session()['default_setting']['activate_smart_diner']); ?>,
        activate_pos_hold_fire = <?php echo json_encode(smc_session()['default_setting']['activate_pos_hold_fire']); ?>,
        show_product_image_pos = <?php echo json_encode(smc_session()['default_setting']['show_product_image_pos']); ?>,
        is_nb_person_required = <?php echo json_encode(smc_session()['default_setting']['pos_nb_person_is_required']); ?>,
        show_category_image_pos = <?php echo json_encode(smc_session()['default_setting']['show_category_image_pos']); ?>,
        activate_kitchen_note = <?php echo json_encode(smc_session()['default_setting']['activate_kitchen_note']); ?>,
        login_device = <?php echo json_encode(smc_session()['login_device']); ?>,
        is_active_expiry_date = <?php echo json_encode(smc_session()['default_setting']['activate_expiry_date']); ?>,
        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']); ?>,
        transfer_item_if_printed = <?php echo json_encode($permissions->hasPermission('transfer_item_if_printed')); ?>,
        transfer_table_if_printed = <?php echo json_encode($permissions->hasPermission('transfer_table_if_printed')); ?>,
        merge_table_if_printed = <?php echo json_encode($permissions->hasPermission('merge_table_if_printed')); ?>,
        show_qty_stock_perm = <?php echo json_encode($permissions->hasPermission('show_stock_quantity_pos')); ?>,
        scan_customer_card = <?php echo json_encode($permissions->hasPermission('scan_customer_card')); ?>,
        is_shown_list_in_pos = <?php echo json_encode($permissions->hasPermission('show_list_in_pos')); ?>,
        show_all_prices = <?php echo json_encode($permissions->hasPermission('show_all_prices')); ?>,
        is_pos_quotation = <?php echo json_encode($permissions->hasPermission('pos_quotation')); ?>,
        show_scrolled_category = <?php echo json_encode($permissions->hasPermission('show_scrolled_category')); ?>,
        delete_row_pos = <?php echo json_encode($permissions->hasPermission('delete_row_pos')); ?>,
        is_active_reserve_date = <?php echo json_encode(smc_session()['default_setting']['activate_product_duration_reservation']); ?>,
        is_tag_active = <?php echo json_encode(smc_session()['default_setting']['is_tag_active']); ?>,
        is_prod_desc_acive = <?php echo json_encode(smc_session()['default_setting']['activate_pos_product_description']); ?>,
        is_uom_active = <?php echo json_encode(smc_session()['default_setting']['activate_uom_in_pos']); ?>,
        void_item_pop_up_active = <?php echo smc_session()['default_setting']['activate_void_item_reason_pop_up'] == 1 ? 'true' : 'false'; ?>,
        is_discount_active = <?php echo json_encode(smc_session()['default_setting']['activate_discount_pos']); ?>,
        pos_cache_time_min = parseFloat(<?php echo json_encode(smc_session()['default_setting']['pos_cache_time_min']); ?>),
        today = <?php echo json_encode($date); ?>,
        fill_expiry_dates = <?php echo json_encode(CommonLanguage::getMessage('fill_expiry_dates')); ?>,
        AddressLang = <?php echo json_encode(CommonLanguage::getMessage('address')); ?>,
        no_data_available = <?php echo json_encode(CommonLanguage::getMessage('no_data')); ?>,
        last_orders = <?php echo json_encode(CommonLanguage::getMessage('last_orders')); ?>,
        PhoneLang = <?php echo json_encode(CommonLanguage::getMessage('Phone')); ?>,
        allergy = <?php echo json_encode(CommonLanguage::getMessage('allergy')); ?>,
        intolerance = <?php echo json_encode(CommonLanguage::getMessage('intolerance')); ?>,
        NameLang = <?php echo json_encode(CommonLanguage::getMessage('Name')); ?>,
        DiscountLang = <?php echo json_encode(CommonLanguage::getMessage('discount')); ?>,
        BalanceLang = <?php echo json_encode(CommonLanguage::getMessage('Balance')); ?>,
        ShippingLang = <?php echo json_encode(CommonLanguage::getMessage('shipping')); ?>,
        SubmittingLang = <?php echo json_encode(CommonLanguage::getMessage('submitting')); ?>,
        TotalLang = <?php echo json_encode(CommonLanguage::getMessage('total')); ?>,
        Invoice = <?php echo json_encode(CommonLanguage::getMessage('invoice')); ?>,
        Customer = <?php echo json_encode(CommonLanguage::getMessage('customer')); ?>,
        Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')); ?>,
        wrong_pass_alert = <?php echo json_encode(CommonLanguage::getMessage('wrong_pass')); ?>,
        success_alert = <?php echo json_encode(CommonLanguage::getMessage('success')); ?>,
        Required_Fields = <?php echo json_encode(CommonLanguage::getMessage('Required_Fields')); ?>,
        Failed_Submit = <?php echo json_encode(CommonLanguage::getMessage('Failed_Submit')); ?>,
        Deleted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Deleted_Successfully')); ?>,
        no_qty_lang = <?php echo json_encode(CommonLanguage::getMessage('no_qty_lang')); ?>,
        //            add_with = < ?php echo json_encode(CommonLanguage::getMessage('add_withdrawal')); ?>,
        //            add_dep = < ?php echo json_encode(CommonLanguage::getMessage('add_deposite')); ?>,
        //            add_payment_lang = < ?php echo json_encode(CommonLanguage::getMessage('add_payment')); ?>,
        //            add_receipt_lang = < ?php echo json_encode(CommonLanguage::getMessage('add_receipt')); ?>,
        check_qty_lang = <?php echo json_encode(CommonLanguage::getMessage('check_qty_lang')); ?>,
        check_prod_options = <?php echo json_encode(CommonLanguage::getMessage('check_prod_options')); ?>,
        no_tags_lang = <?php echo json_encode(CommonLanguage::getMessage('no_tags')); ?>,
        select_lang = <?php echo json_encode(CommonLanguage::getMessage('select')); ?>,
        LastPurLang = <?php echo json_encode(CommonLanguage::getMessage('last_purchase')); ?>,
        default_vat = <?php echo json_encode(smc_session()['vat_percent'] / 100) ?>,
        change_pos_currency = <?php echo json_encode(smc_session()['default_setting']['change_pos_currency']) ?>,
        hotel_data = <?php echo json_encode(smc_session()['default_setting']['hotel_database']) ?>,
        hotel_customer_id = <?php echo json_encode(smc_session()['default_setting']['default_hotel_customer']) ?>,
        sumatra_print = <?php echo smc_session()['default_setting']['sumatra_print'] == 1 ? "true" : "false" ?>,
        activate_pos_select_cat = <?php echo smc_session()['activate_pos_select_cat'] == 1 ? "true" : "false" ?>,
        user_max_discount = <?php echo json_encode(smc_session()['user_accounts']['max_discount']) ?>,
        view_cost_in_pos = <?php echo json_encode(smc_session()['default_setting']['view_cost_in_pos']) ?>,
        ignore_zero_item_disc = <?php echo json_encode(smc_session()['default_setting']['ignore_zero_item_disc']) ?>,
        view_stock_qty_in_pos = <?php echo json_encode(smc_session()['default_setting']['view_stock_qty_in_pos']); ?>,
        view_barcode_in_pos = <?php echo json_encode(smc_session()['default_setting']['view_barcode_in_pos']); ?>,
        pos_confirm_delete_row = <?php echo json_encode(smc_session()['default_setting']['pos_confirm_delete_row']); ?>,
        default_depot_id = <?php echo json_encode(smc_session()['default_depot_id']); ?>,
        user_depot_id = <?php echo json_encode($default_depot_id = (smc_session()['user_accounts']['depot_id'] ? smc_session()['user_accounts']['depot_id'] : smc_session()['default_depot_id'])) ?>,
        default_class_id = <?php echo json_encode(smc_session()['pricing_class_id']); ?>,
        activate_card_tax = <?php echo json_encode(smc_session()['default_setting']['activate_card_tax']); ?>,
        activate_allergy_intolerance = <?php echo json_encode(smc_session()['default_setting']['activate_allergy_intolerance']); ?>,
        default_row_no = parseFloat(<?php echo json_encode(smc_session()['default_setting']['default_pos_row']); ?>),
        default_column_no = parseFloat(<?php echo json_encode(smc_session()['default_setting']['default_pos_column']); ?>),
        ShowPerPage = default_row_no * default_column_no,
        change_pos_price = <?php echo json_encode($permissions->hasPermission('change_pos_price')); ?>,
        order_delivery_date = <?php echo json_encode($permissions->hasPermission('pos_order_delivery_date')); ?>,
        disable_cash_on_edit_table = <?php echo json_encode($permissions->hasPermission('disable_cash_on_edit_table')); ?>,
        overwrite_print_perm = <?php echo json_encode($permissions->hasPermission('overwrite_print')); ?>,
        void_reason_perm = <?php echo json_encode($permissions->hasPermission('void_invoice')); ?>,
        change_pos_price_class = <?php echo json_encode($permissions->hasPermission('change_pos_price_class')); ?>,
        show_total_deposite = <?php echo json_encode($permissions->hasPermission('show_total_deposite')); ?>,
        show_total_withdrawal = <?php echo json_encode($permissions->hasPermission('show_total_cash')); ?>,
        view_cost_permission = <?php echo json_encode($permissions->hasPermission('view_cost_pos') ? 1 : 0); ?>,
        view_last_price_permission = <?php echo json_encode($permissions->hasPermission('view_last_price_pos') ? 1 : 0); ?>,
        has_total_disc_permission = <?php echo json_encode($permissions->hasPermission('discount_on_invoice') ? 1 : 0); ?>,
        multi_inv_delete_per = <?php echo json_encode($permissions->hasPermission('pos_multi_inv_delete') ? 1 : 0); ?>,
        view_all_table = <?php echo json_encode($permissions->hasPermission('view_all_tables') ? 1 : 0); ?>,
        activate_cash_customer_oncredit = <?php echo json_encode($permissions->hasPermission('activate_cash_customer_oncredit') ? 1 : 0); ?>,
        pos_reason_open_drawer = <?php echo json_encode(smc_session()['default_setting']['pos_reason_open_drawer']); ?>,
        add_road_customer_pos = <?php echo json_encode(smc_session()['default_setting']['add_pos_customer']); ?>,
        show_last_customer_order_perm = <?php echo json_encode($permissions->hasPermission('view_customer_last_order')); ?>,
        default_round_type = <?php echo json_encode(smc_session()['default_setting']['round_type']); ?>,
        activate_pos_shortcust_keys = <?php echo json_encode(smc_session()['default_setting']['activate_pos_shortcust_keys']); ?>,
        change_item_row_after_edit = <?php echo json_encode($permissions->hasPermission('change_item_row_after_edit')); ?>,
        pos_return_postponed_change_item = <?php echo json_encode($permissions->hasPermission('pos_return_postponed_change_item')); ?>,
        show_balance_search_cust = <?php echo json_encode($permissions->hasPermission('show_account_balance_search_cust')); ?>,
        show_balance_search_road_cust = <?php echo json_encode($permissions->hasPermission('show_account_balance_search_road_cust')); ?>,
        pos_change_values_row_click = <?php echo json_encode($permissions->hasPermission('pos_change_values_row_click')); ?>;
    $("body").addClass("NoAutoScroll");
    var destination_type = "<?php echo $destination; ?>",
        default_cat_id = "<?php echo $default_cat_id; ?>",
        SessionLoggedID = <?php echo Session::getUserID(); ?>,
        Categories = <?php echo json_encode($categories); ?>,
        old_currency = [],
        PrimaryCurrency = <?php echo json_encode($PrimaryCurrency); ?>,
        LocalCurrency = <?php echo json_encode($local_currency_arr); ?>,
        SecondCurrency = <?php echo json_encode($SecondCurrency ? $SecondCurrency : $PrimaryCurrency); ?>,
        CurrencyRate = <?php echo json_encode($Extable); ?>,
        Org_Type = <?php echo json_encode($Org_Type); ?>,
        Note = <?php echo json_encode(CommonLanguage::getMessage('note')); ?>,
        bar_code_check = <?php echo json_encode(CommonLanguage::getMessage('bar_code_check')); ?>,
        posponed_alert = <?php echo json_encode(CommonLanguage::getMessage('posponed_alert')); ?>,
        branch_prod_alert = <?php echo json_encode(CommonLanguage::getMessage('branch_prod_alert')); ?>,
        block_title = <?php echo json_encode(CommonLanguage::getMessage('choose_items_nb', null, false)); ?>,
        check_expiry_exist_lang = <?php echo json_encode(CommonLanguage::getMessage('check_expiry_exist')); ?>,
        check_serial_exist_lang = <?php echo json_encode(CommonLanguage::getMessage('check_serial_exist')); ?>,
        check_lot_exist_lang = <?php echo json_encode(CommonLanguage::getMessage('check_lot_exist')); ?>,
        check_qty_exist_lang = <?php echo json_encode(CommonLanguage::getMessage('check_qty_exist')); ?>,
        SelectedTR = "",
        flag = 0,
        pending_status = 0,
        is_edited_invoice = 0,
        is_return_postponed = 0,
        is_ttc = <?php echo json_encode(smc_session()['class_is_ttc']); ?>,
        global_counter = 0,
        ItemTags = new Array(),
        smart_diner_server_url = '<?php echo SMART_DINER_URL; ?>',
        is_sync_active = <?php echo json_encode(smc_session()['default_setting']['is_sync_active']); ?>,
        is_open_cash_table = <?php echo json_encode(smc_session()['default_setting']['open_table_cash']); ?>,
        activate_second_vat = <?php echo json_encode(smc_session()['default_setting']['activate_second_vat']); ?>,
        is_production = <?php echo json_encode(smc_session()['default_setting']['is_production']); ?>,
        pos_postponed_return_autofill_paid = <?php echo json_encode(smc_session()['default_setting']['pos_postponed_return_autofill_paid']); ?>,
        pos_fields_to_hide = <?php echo json_encode($pos_fields_to_hide); ?>,
        is_actual = <?php echo json_encode($is_actual); ?>,
        branch_id = '<?php echo SMARTDINER_BRANCH_ID; ?>',
        inv_to_delete = [],
        ex_to_delete = 0,
        max_criteria_column = 5,
        startDueDate = '',
        endDueDate = '',
        startDate = '',
        endDate = '',
        startExDate = '',
        endExDate = '',
        startretDate = '',
        endretDate = '',
        void_item_reason_array = {},
        is_delivery = 0,
        is_closed = 0;
    var change_class_flag = false,
        primary_total = 0,
        customer_type = '',
        current_show_price = show_all_prices,
        time_now = <?php echo json_encode(date('Y-m-d H:i')) ?>,
        last_focsd_elmnt = null;
    $("body").on('click', function() {
        $('#snackbar,#scan_bar_code_bar').removeClass('show');
    });
    //we need this ft. in case of click item and qty or price or .. still input and press shortcut like alt+1 
    //to take value or it will give NaN as qty,.. since it is input and not convert to span yet
    function on_submit_blur_input() {
        //for focus use: document.activeElement or $(':focus')
        if ($(':focus').length)
            $(':focus').trigger('blur');
    }
    $(function() {
        if (pos_orders_notification == 1) {
            getTotalOrders();
        }
        build_select2($("#current_post_branch_id,#current_report_branch_id"), "xhr/CommonSearch?col_name=branch_name&col_id=branch_id&table=tbl_organization_branches");
        if (hotel_data) {
            build_select2($("#reservation_id"), "xhr/searchReservations")
        }
        $("#reservation_id").on('change', function() {
            if (hotel_customer_id && $(this).val()) {
                //                console.log('hello');
                fill_customer_by_id(hotel_customer_id);
            }
        });
        $('#print_table_invoice').on('click', function() {
            print_invoice($(this).attr('data-table-id'));
        });
        //
        if (show_scrolled_category)
            init_scroll_obj($('#scroll_div_main_cat'));
        //
        if (is_shown_list_in_pos && destination_type == 0) {
            RebuildDataTable('', [0, 1], "POSAjax/getSalesRetreiveList", {
                is_actual: is_actual
            }, '#main_pos_invoice_list')
            $('.main_pos_invoice_list_div .dataTables_filter,.main_pos_invoice_list_div .dataTables_length,.main_pos_invoice_list_div .dt-buttons,#main_pos_invoice_list thead tr.filter_columns_row').remove()
        }
        //        $('#CurCustomerInfo').on('click','.view_customer_last_orders',function(){
        //            $('#customer-last-order-modal').modal('show')
        //        })
        if (!overwrite_print_perm && $('#is_printed_invoice').val() == 1) {
            $('.common-print').prop('disabled', true)
        }
        if ($('#invoice_auto_id').val() != 0) {
            retrieveData($('#invoice_auto_id').val(), 0);
        }
        getTotalDelivery()
        if ($("#online_orders_count").length) {
            getTotalOnlinePendingOrders()
        }
        //        rebuild_inv_table()
        //        RebuildDataTable('invoices', [0, 1, 2, 3], "POSAjax/InvoiceListByLoggedUser", {date: $("#inv_list_date").val()}, "#invoiceListTable", '', {"bSort": false})
        build_select2($("#shipping_id"), ("xhr/DeliveryFeesSeacrh"))
        build_select2($('#delivery_user,#rec_user'), "xhr/CommonSearch?col_id=user_id&col_name=user_name&table=tbl_common_users")
        build_select2($("input[name=Expense_Account]"), "xhr/accIDSearch?type=Expense")
        build_select2($("#inv_cust,#delivery_cust,#rec_cust,#post_cust,#ret_cust,#report_post_cust"), "xhr/customerSearch")
        build_select2($("#inv_pos_cust,#delivery_pos_cust,#rec_pos_cust,#post_pos_cust,#postponed_pos_customer_id,#report_post_pos_cust"), "xhr/poscustomerSearch")
        build_select2($("#allergy_id"), "xhr/CommonSearch?col_id=allergy_id&col_name=allergy_name&table=tbl_allergy", 1);
        build_select2($("#postponed_category_id"), "xhr/catSearch", 1);
        build_select2($("#intolerance_id"), "xhr/CommonSearch?col_id=intolerance_id&col_name=intolerance_name&table=tbl_intolerance", 1);
        //rebuild_inv_table()
        //        fill_scanned_customer(1)
        $('#reserve_end_date').datetimepicker({
            format: 'YYYY-MM-DD HH:mm'
        });
        $('#reserve_start_date').datetimepicker({
            format: 'YYYY-MM-DD HH:mm',
            useCurrent: true
        }).on("dp.change", function(e) {
            $('#reserve_end_date').data("DateTimePicker").minDate(e.date);
        });
        $(".hold,.unhold").on("click", function() {
            if ($(this).hasClass("selected_hold")) {
                $(this).toggleClass("selected_hold")
            } else {
                $(".hold,.unhold").removeClass('selected_hold')
                $(this).addClass('selected_hold')
            }
            //            console.log(SelectedTR.length)
            if ($(this).hasClass("unhold") && SelectedTR.length > 0) {
                //                console.log(SelectedTR)
                SelectedTR.attr("data-hold", 0).find(".hold_td").html(0).removeClass("hold1 hold2 hold3")
            }
        })
        $("#show_fire_tab").on("click", function() {
            $("#hold_fire_table").toggleClass("hidden")
        })
        $("body").on("click", ".spinner-icons > span", function(e) {
            var parent = $(this).parents('.spinner-icons');
            //            alert()
            var input = $(this).parents('.spinner-icons').find('input'),
                cur_val = parseFloat(input.val()) || 0,
                max = parseFloat(input.attr("max")) || undefined;
            if ($(this).hasClass("fa-minus"))
                input.val((cur_val - 1) <= 0 ? 0 : cur_val - 1)
            else {

                input.val((max != undefined && (cur_val + 1) > max) ? max : (cur_val + 1))
            }
            if (parent.hasClass('option-spinner')) {
                var max_qty = ($(this).parents('.op-block').attr("data-qty") * (parseFloat($("#op_main_qty").val()) || 0)),
                    total_qty = 0;
                $(this).parents('.op-block').find('input.op-spinner').each(function() {
                    total_qty += parseFloat($(this).val()) || 0;
                })
                if (total_qty > max_qty) {
                    input.val(input.attr('data-old') || 0)
                }
            }
            if (parent.hasClass('op_main_qty_div')) {
                input.val(input.val() <= 0 ? 1 : input.val())
                $("#product_options_modal #op_main_qty").trigger("input")
            }
            input.attr('data-old', input.val())
        })
        //        $('#reserve_start_date,#reserve_end_date').datetimepicker({
        //            format: 'YYYY-MM-DD HH:mm'
        //        }).on("dp.change", function (e) {
        //            var is_from_change = $(e.target).attr("id") == 'reserve_start_date';
        //            setTimeout(function () {
        //                if (is_from_change)
        //                    $('#reserve_end_date').data("DateTimePicker").minDate(e.date);
        //                else
        //                    $('#reserve_start_date').data("DateTimePicker").maxDate(e.date);
        //            }, 100)
        //
        //        })
        $(".add_both_customer,.both_customer_list").on("click", function() {
            if ($(this).hasClass("add_both_customer")) {
                $(".add-cust-row").removeClass("hidden")
                $(".list-cust-row").addClass("hidden")
            } else {
                $(".add-cust-row").addClass("hidden")
                $(".list-cust-row").removeClass("hidden")
            }
        })
        //            //        $(".road_cust_btn").on("click",function(){
        //            //            if(customer_type=='add'){
        //            ////                add_pos_customer" data-toggle="modal" data-target="#addCustomerModal"
        //            //                $(this).addClass("add_pos_customer").attr("data-toggle","modal").attr("data-target","#addCustomerModal").trigger("click")
        //            //            }
        //            //        })
        $('.show_product_recipe').on('click', function() {
            if (!SelectedTR)
                return;
            $('#product_recipe_loader').removeClass('hidden');
            $('#product-recipe-modal').modal('show')
            $('#product_recipe_div').empty();
            $.ajax({
                url: "InventoryAjax/getProductRecipe",
                data: {
                    product_id: SelectedTR.attr('data-id')
                },
                dataType: "json",
                complete: function(jqXHR, status) {
                    if (status == 'success') {
                        var response = jqXHR.responseJSON,
                            content = '';
                        if (response['link_note']) {
                            content += '<h3 class="semi-bold">Note</h3><span class="f-s-3e">' + response['link_note'] + '</span>';
                        }
                        if (response['product_out'].length == 0) {
                            content += '<div class="alert alert-info">' + no_data_available + '</div>';
                        } else {
                            content += '<h3 class="semi-bold">Recipe</h3><ul>';
                            var product_out = response['product_out'];
                            $.each(product_out, function(key1, value) {
                                content += '<li class="f-s-3e">' + product_out[key1]['quantity'] + ' ( ' + product_out[key1]['UOM_Name'] + ' ) ' + product_out[key1]['Product_Name'] + '</li>';
                            });
                            content += '</ul>';
                        }
                        $('#product_recipe_div').append($(content));
                    }
                    $('#product_recipe_loader').addClass('hidden');
                }
            });
        });
        //                appendScannedItem("5280057510164")
        //                        appendScannedItem("81")
        //                        appendScannedItem("2000001009802")
        //        build_select2($(".search_sales"), "xhr/employeeSearch")
        //        EnableAutoCompleteCustomers();

        $("#delivery_date,#rec_date").datepicker({
            autoclose: true
        });
        $("#postponed_date_time").datetimepicker({
            format: 'YYYY-MM-DD HH:mm:ss'
        })
        $("#end_of_day_range").daterangepicker();
        $('#activate_cat_id').on('change', function() {
            var select_cat_id = $(this).val();
            AjaxLoadCateg(select_cat_id);
        });
        $("#invoice_list_modal").on("shown.bs.modal", function() {
            //            alert()
            rebuild_inv_table()
        })
        $("#invoice_delivery_list_modal").on("shown.bs.modal", function() {
            //            alert()
            rebuild_delivery_table();
        })
        $("#received_delivery_list_modal").on("shown.bs.modal", function() {
            //            alert()
            rebuild_received_delivery_table();
        })
        $("#return_list_modal").on("shown.bs.modal", function() {
            //            alert()
            rebuild_ret_table()
        })
        $("#postponed_list_modal").on("shown.bs.modal", function() {
            //            alert()
            rebuild_post_table()
        })
        $("#inv_cust,#invoice_status,#inv_is_delivery,#inv_pos_cust,#posponted_status_filter,#smart_status").on("change", function() {
            rebuild_inv_table()
        })
        $("#delivery_list_nb,#delivery_status,#delivery_pos_cust,#delivery_cust,#delivery_user").on("change", function() {
            rebuild_delivery_table()
        })
        $("#rec_list_nb,#rec_status,#rec_pos_cust,#rec_cust,#rec_user,#rec_driver_filter,#rec_region_filter,#received_status").on("change", function() {
            rebuild_received_delivery_table()
        })
        $("#ret_cust").on("change", function() {
            rebuild_ret_table()
        })
        $("#post_cust,#post_status,#post_is_delivery,#post_pos_cust,#posponted_status_filter,#post_is_committed,#current_post_branch_id").on("change", function() {
            rebuild_post_table()
        })
        $("#inv_list_nb").on("keyup", function() {
            rebuild_inv_table();
        })
        $("#delivery_list_nb").on("keyup", function() {
            rebuild_delivery_table();
        })
        $("#rec_list_nb").on("keyup", function() {
            rebuild_received_delivery_table();
        })
        $("#ret_list_nb").on("keyup", function() {
            rebuild_ret_table()();
        })
        $("#post_list_nb").on("keyup", function() {
            rebuild_post_table()
        })
        $("#invoiceListTable").on("click", ".printOrder", function() {
            myurl = "Inventory/pos_view_order/" + $(this).parents('.Action').attr("data-id");
            printPOSExternal(myurl)
        })
        $("#invoiceDeliveryListTable").on("click", ".printOrder", function() {
            myurl = "Inventory/pos_view_order/" + $(this).parents('.Action').attr("data-id");
            printPOSExternal(myurl)
        })
        $("#invoiceListTable").on("click", "input.inv_check_all_td", function() {
            var is_checked = $(this).is(":checked");
            //            var row = $("#ref_report_table").dataTable().fnGetNodes();
            //            for (var i = 0; i < row.length; i++) {
            $("input.inv_del_td").prop("checked", is_checked)
            //            }
        })
        $("#invoiceDeliveryListTable").on("click", "input.inv_check_all_td", function() {
            var is_checked = $(this).is(":checked");
            //            var row = $("#ref_report_table").dataTable().fnGetNodes();
            //            for (var i = 0; i < row.length; i++) {
            $("input.inv_del_td").prop("checked", is_checked)
            //            }
        })
        $("#multi_dlt_inv_btn,#multi_dlt_delv_btn").on("click", function() {
            var inv_ids = [];
            var validate = false;
            $("input.inv_del_td").each(function() {
                if ($(this).is(":checked")) {
                    validate = true;
                    inv_ids.push($(this).parents('tr').find('.Action').attr("data-id"))
                }
            })
            if (!validate)
                return false;
            inv_to_delete = inv_ids;
            $("#inv_nb").html('')
            $("#ConfirmDeleteInv").modal("show")
        })
        $("#invoiceListTable,#invoiceDeliveryListTable").on("click", ".delete_inv", function() {
            inv_to_delete = [$(this).parents(".Action").attr("data-id")];
            $("#inv_nb").html($(this).parents("tr").find("td:eq(0)").text())
            $("#ConfirmDeleteInv").modal("show")
        })
        $("#inv_delete").on("click", function() {
            var data = inv_to_delete
            $.ajax({
                url: "InventoryAjax/delete_sales_invoice",
                method: "GET",
                data: {
                    ids: data
                },
                complete: function(v1, v2) {
                    if (v2 == 'success') {
                        if (v1.responseText == 'ok') {
                            $("#delete_alert").attr("class", "alert alert-success").html(Deleted_Successfully)
                            rebuild_inv_table();
                            rebuild_delivery_table();
                            RebuildDataTable('', [0, 1], "POSAjax/getSalesRetreiveList", {
                                is_actual: is_actual
                            }, '#main_pos_invoice_list')
                            $('.main_pos_invoice_list_div .dataTables_filter,.main_pos_invoice_list_div .dataTables_length,.main_pos_invoice_list_div .dt-buttons,#main_pos_invoice_list thead tr.filter_columns_row').remove()
                            hideModalAlert('ConfirmDeleteInv', 'delete_alert');
                            if (inv_to_delete.indexOf($("#invoice_auto_id").val()) != -1) {
                                $('#OrderTable tbody,#CurCustomerInfo').empty()
                                $('#CurCustomerInfo').attr('curcustomerid', 0)
                                $('#CurCustomerInfo').attr('customer-pos-id', 0)
                                $('#CurCustomerInfo').attr('data-is-pos', 0)
                                $('#CurCustomerInfo').attr('data-account-id', 0)
                                $('#CurCustomerInfo').attr('data-tax', 0)
                                UpdateTable($("#OrderTable > tbody:last"))
                            }
                            inv_to_delete = [];
                        } else {
                            $("#delete_alert").attr("class", "alert alert-danger").html(v1.responseText)
                        }
                    }
                }
            })
        })
        $("#ReturnListTable").on("click", ".delete_ret", function() {
            var entry_value = $(this).parents('.Action').attr('data-id');
            var data = {
                id: entry_value
            };
            IncludeDeleteModal(common_delete_modal, data, function() {
                rebuild_ret_table();
                if (entry_value == $("#invoice_auto_id").val()) {
                    $('#OrderTable tbody,#CurCustomerInfo').empty()
                    $('#CurCustomerInfo').attr('curcustomerid', 0)
                    $('#CurCustomerInfo').attr('customer-pos-id', 0)
                    $('#CurCustomerInfo').attr('data-is-pos', 0)
                    $('#CurCustomerInfo').attr('data-account-id', 0)
                    $('#CurCustomerInfo').attr('data-tax', 0)
                    UpdateTable($("#OrderTable > tbody:last"))
                }
            }, "POSAjax/delete_return");
        })
        $("#exchange_list_table").on("click", ".delete_exchange", function() {
            ex_to_delete = $(this).parents(".Action").attr("data-id");
            $("#ex_nb").html($(this).parents("tr").find("td:eq(0)").text())
            $("#ConfirmDeleteEx").modal("show")
        })
        $("#ex_delete").on("click", function() {
            //            var data = ex_to_delete
            $.ajax({
                url: "POSAjax/delete_exchange",
                method: "GET",
                data: {
                    id: ex_to_delete
                },
                complete: function(v1, v2) {
                    if (v2 == 'success') {
                        if (v1.responseText == 'ok') {
                            $("#delete_ex_alert").attr("class", "alert alert-success").html(Deleted_Successfully)
                            if (ex_to_delete == $("#invoice_auto_id").val()) {
                                $('#OrderTable tbody,#CurCustomerInfo').empty()
                                $('#CurCustomerInfo').attr('curcustomerid', 0)
                                $('#CurCustomerInfo').attr('customer-pos-id', 0)
                                $('#CurCustomerInfo').attr('data-is-pos', 0)
                                $('#CurCustomerInfo').attr('data-account-id', 0)
                                $('#CurCustomerInfo').attr('data-tax', 0)
                                UpdateTable($("#OrderTable > tbody:last"))
                            }
                            ex_to_delete = 0
                            rebuild_exchange_table()
                            setTimeout(function() {
                                $("#ConfirmDeleteEx").modal("hide")
                                $("#delete_ex_alert").addClass("hidden")
                            }, 1500)
                        } else {
                            $("#delete_ex_alert").attr("class", "alert alert-danger").html(v1.responseText)
                        }
                    }
                }
            })
        })
        $('#click_exchange').on('click', function() {
            rebuild_exchange_table();
        })
        var tmp_phone_no = '';
        $('#add_caller').on('click', function() {
            $.ajax({
                url: 'xhr/getphonenumber',
                dataType: 'json',
                complete: function(v1, v2) {
                    if (v2 == 'success') {
                        var Data = v1.responseJSON;
                        tmp_phone_no = Data['item']['caller_phone_number'];
                        if (tmp_phone_no != '') {
                            if ('Customer_ID' in Data['item'])
                                customerSelectAutocomplete(Data);
                            else {
                                if (add_road_customer_pos == '1') {
                                    $("#Customer_Phone").val(tmp_phone_no);
                                    $(".add_pos_customer").trigger("click");
                                } else {
                                    //here we use .one and not .on to execute it just one time since here in each caller id icon 
                                    //click it is initialized agin
                                    $('#checkframe').one('load', function() {
                                        $('#checkframe').contents().find("#Customer_Mobile").val(tmp_phone_no);
                                    });
                                    $(".add_nonroad_pos_customer").trigger("click");
                                }
                            }
                        }
                    }
                }
            })
        })
        $(".note-key").on("click", function() {
            $("#invoice_desc_modal").modal("show")
        });
        $("#CurCustomerInfo").on("click", ".edit_road_customer", function() {
            var is_pos = $("#CurCustomerInfo").attr("data-is-pos"),
                customer_id = is_pos ? $("#CurCustomerInfo").attr("customer-pos-id") : $("#CusCustomerInfo").attr("curcustomerid");
            if (is_pos) {
                road_cust_to_edit = customer_id;
                is_road_cust_update_after_edit = true;
                is_road_cust_edit = true;
                fill_road_customer_data();
            }
        })
        //        $("input[name=inv_list_date]").daterangepicker({
        //            ranges: {
        //                'Today': [moment(), moment()],
        //                'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
        //                'Last 7 Days': [moment().subtract(6, 'days'), moment()],
        //                'Last 30 Days': [moment().subtract(29, 'days'), moment()],
        //                'This Month': [moment().startOf('month'), moment().endOf('month')],
        //                'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
        //            },
        //            startDate: start_date
        //        }, function (start, end, label) {
        //            window.startDate = start.format("YYYY-MM-DD"),
        //                    window.endDate = end.format("YYYY-MM-DD")
        //            rebuild_inv_table();
        //        });
        // rebuild_exchange_table()







        $("input[name=from_to_exchange]").daterangepicker({
            ranges: {
                'Today': [moment(), moment()],
                'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                'This Month': [moment().startOf('month'), moment().endOf('month')],
                'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
            },
            allowEmpty: true,
            //            autoApply: true,
            autoUpdateInput: false,
            locale: {
                cancelLabel: 'Clear'
            }
        }, function(start, end, label) {});
        $('input[name="from_to_exchange"]').on('apply.daterangepicker', function(ev, picker) {
            window.startExDate = picker.startDate.format('YYYY-MM-DD'),
                window.endExDate = picker.endDate.format('YYYY-MM-DD');
            $(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
            rebuild_exchange_table()
        });
        $('input[name="from_to_exchange"]').on('cancel.daterangepicker', function(ev, picker) {
            startExDate = ''
            endExDate = ''
            $(this).val('');
            rebuild_exchange_table()
        });
        //inv_list_due_date
        $("input[name=inv_list_date],input[name=delivery_list_date],input[name=post_list_date],input[name=ret_list_date],input[name=rec_list_date]").daterangepicker({
            ranges: {
                'Today': [moment(), moment()],
                'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                'This Month': [moment().startOf('month'), moment().endOf('month')],
                'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
            },
            allowEmpty: true,
            //            autoApply: true,
            autoUpdateInput: false,
            locale: {
                cancelLabel: 'Clear'
            }
        }, function(start, end, label) {});
        $('input[name="inv_list_date"]').on('apply.daterangepicker', function(ev, picker) {
            window.startDate = picker.startDate.format('YYYY-MM-DD'),
                window.endDate = picker.endDate.format('YYYY-MM-DD');
            $(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
            rebuild_inv_table()
        });
        $('input[name="inv_list_date"]').on('cancel.daterangepicker', function(ev, picker) {
            startDate = ''
            endDate = ''
            $(this).val('');
            rebuild_inv_table()
        });
        $('input[name="delivery_list_date"]').on('apply.daterangepicker', function(ev, picker) {
            window.startDate = picker.startDate.format('YYYY-MM-DD'),
                window.endDate = picker.endDate.format('YYYY-MM-DD');
            $(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
            rebuild_delivery_table()
        });
        $('input[name="delivery_list_date"]').on('cancel.daterangepicker', function(ev, picker) {
            startDate = ''
            endDate = ''
            $(this).val('');
            rebuild_delivery_table()
        });
        $('input[name="rec_list_date"]').on('apply.daterangepicker', function(ev, picker) {
            window.rec_start_date = picker.startDate.format('YYYY-MM-DD'),
                window.rec_end_date = picker.endDate.format('YYYY-MM-DD');
            $(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
            rebuild_received_delivery_table()
        });
        $('input[name="rec_list_date"]').on('cancel.daterangepicker', function(ev, picker) {
            rec_start_date = ''
            rec_end_date = ''
            $(this).val('');
            rebuild_received_delivery_table()
        });
        $('input[name="ret_list_date"]').on('apply.daterangepicker', function(ev, picker) {
            window.startretDate = picker.startDate.format('YYYY-MM-DD'),
                window.endretDate = picker.endDate.format('YYYY-MM-DD');
            $(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
            rebuild_ret_table()
        });
        $('input[name="ret_list_date"]').on('cancel.daterangepicker', function(ev, picker) {
            startretDate = ''
            endretDate = ''
            $(this).val('');
            rebuild_ret_table()
        });
        $('input[name="post_list_date"]').on('apply.daterangepicker', function(ev, picker) {
            window.startDate = picker.startDate.format('YYYY-MM-DD'),
                window.endDate = picker.endDate.format('YYYY-MM-DD');
            $(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
            rebuild_post_table()
        });
        $('input[name="post_list_date"]').on('cancel.daterangepicker', function(ev, picker) {
            startDate = ''
            endDate = ''
            $(this).val('');
            rebuild_post_table()
        });
        $("input[name=inv_list_due_date],input[name=post_list_due_date],input[name=report_post_date]").daterangepicker({
            ranges: {
                'Today': [moment(), moment()],
                'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                'This Month': [moment().startOf('month'), moment().endOf('month')],
                'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
            },
            allowEmpty: true,
            //            autoApply: true,
            autoUpdateInput: false,
            locale: {
                cancelLabel: 'Clear'
            }
        }, function(start, end, label) {});
        $('input[name="inv_list_due_date"]').on('apply.daterangepicker', function(ev, picker) {
            window.startDueDate = picker.startDate.format('YYYY-MM-DD'),
                window.endDueDate = picker.endDate.format('YYYY-MM-DD');
            $(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
            rebuild_inv_table()
        });
        $('input[name="inv_list_due_date"]').on('cancel.daterangepicker', function(ev, picker) {
            startDueDate = ''
            endDueDate = ''
            $(this).val('');
            rebuild_inv_table()
        });
        $('input[name="post_list_due_date"]').on('apply.daterangepicker', function(ev, picker) {
            window.startDueDate = picker.startDate.format('YYYY-MM-DD'),
                window.endDueDate = picker.endDate.format('YYYY-MM-DD');
            $(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
            rebuild_post_table()
        });
        $('input[name="post_list_due_date"]').on('cancel.daterangepicker', function(ev, picker) {
            startDueDate = ''
            endDueDate = ''
            $(this).val('');
            rebuild_post_table()
        });
        //        $("#inv_list_date").datepicker({autoclose: true})
        //        $("#inv_list_date").on("changeDate", function () {
        //            rebuild_inv_table()
        //            RebuildDataTable('invoices', [0, 1, 2, 3], "POSAjax/InvoiceListByLoggedUser", {date: $("#inv_list_date").val()}, "#invoiceListTable", '', {"bSort": false})
        //        })



        $("#invoiceListTable,#postponedListTable,#invoiceDeliveryListTable").on("click", ".printInv", function() {
            var is_posponed = $(this).parents('table').attr('id') == 'postponedListTable' ? 1 : 0;
            myurl = "Inventory/pos_view_invoice/" + $(this).parents('.Action').attr("data-id") + '?is_posponed=' + is_posponed;
            printPOSExternal(myurl)
        });
        $("#ReturnListTable").on("click", ".printRet", function() {
            myurl = "Inventory/pos_view_return/" + $(this).parents('.Action').attr("data-id");
            printPOSExternal(myurl)
        });
        $("#exchange_list_table").on("click", ".printEx", function() {
            myurl = "Inventory/pos_view_exchange/" + $(this).parents('.Action').attr("data-id");
            printPOSExternal(myurl)
        })
        UpdateTable($("#OrderTable > tbody:last"));
        enable_all_customers();
        build_select2($(".Depot_PIC_ID"), "xhr/employeeSearch", false, 'diff_class');
        $('#timepicker').timepicker({
            //            maxHours: 60,
            showMeridian: true,
            timeFormat: 'HH:mm:ss'
        });
        $("#customer_dob").datepicker({
            autoclose: true
        })
        $("#refresh").on("click", function() {
            if (checkPrintDisbaled())
                return;
            if (is_smart_diner == 1 && $('#invoice_auto_id').val() != 0 && destination_type != 0 && void_reason_perm) {
                $('#VoidReasonModal').modal('show');
                $('#void_reason_origin').val('table');
                $('#void_reason_invoice_id').val($('#invoice_auto_id').val());
            } else {
                location.reload();
            }
        });
        $("#barcode_search_input").on("keyup", function(e) {
            if (e.which == 13) {
                appendScannedItem($(this).val())
                $(this).val('')
            }
        })
        if (activate_pos_shortcust_keys == 1) {
            $(document).on('keydown', function(e) {
                //alt+1 or F1
                if (((e.altKey && e.which == 49) || e.which == 112) && !$("#CashInvBtn").hasClass("hidden") && !$("#CashInvBtn").hasClass("disabled")) {
                    on_submit_blur_input();
                    $("#CashInvBtn").trigger("click");
                    e.preventDefault();
                    return false;
                }
                //alt+2 or F2
                if (((e.altKey && e.which == 50) || e.which == 113) && !$("#GInvBtn").hasClass("hidden") && !$("#GInvBtn").hasClass("disabled")) {
                    on_submit_blur_input();
                    $("#GInvBtn").trigger("click");
                    e.preventDefault();
                    return false;
                }
                //alt+3 or F3
                if (((e.altKey && e.which == 51) || e.which == 114) && !$("#CashWithoutPrintInvBtn").hasClass("hidden") && !$("#CashWithoutPrintInvBtn").hasClass("disabled")) {
                    on_submit_blur_input();
                    $("#CashWithoutPrintInvBtn").trigger("click");
                    e.preventDefault();
                    return false;
                }
                //alt+4 or F4
                if (((e.altKey && e.which == 52) || e.which == 115) && !$("#kitchen_delivery_takeaway").hasClass("hidden") &&
                    !$("#kitchen_delivery_takeaway").hasClass("disabled") && destination_type == 0) {
                    on_submit_blur_input();
                    $("#kitchen_delivery_takeaway").trigger("click");
                    e.preventDefault();
                    return false;
                }
                //alt+4 or F4	
                if (((e.altKey && e.which == 52) || e.which == 115) && is_smart_diner == 1 && destination_type != 0) {
                    on_submit_blur_input();
                    $('#addtoPark:enabled').trigger('click');
                    e.preventDefault();
                    return false;
                }
                //alt+5 or F5
                if (((e.altKey && e.which == 53) || e.which == 116) && is_pos_quotation && destination_type == 0) {
                    on_submit_blur_input();
                    $('#print_order_invoice_no_save').trigger('click');
                    e.preventDefault();
                    return false;
                }
            });
        }
        $("#SubmitManagerPass").on("click", function() {
            var check_pass = chck_manager_disc_pass($("#seed_key").html(), $("#password_input").val());
            //            alert(wrong_pass_alert)
            if (check_pass) {
                $("#manager_pass_alert").attr("class", "alert alert-success").html(success_alert)
                $('.initial_disable').removeClass('current_disable')
                $('.initial_disable').removeClass('not-allowed')
                $(".DiscountValue").removeAttr("disabled", "disabled")
                $("#DiscountInput").removeAttr("disabled", "disabled")
                setTimeout(function() {
                    $("#manager_pass_modal,#FunctionsModal").modal('hide')
                    $("#manager_pass_alert").addClass('hidden')
                    //                    $("#FunctionsModal")
                }, 1500)
            } else {
                $("#manager_pass_alert").attr("class", "alert alert-danger").html(wrong_pass_alert)
            }
        })
        $("#manager_pass_modal").on("shown.bs.modal", function() {
            var random_seed = Math.floor(10000 + Math.random(Date.now() + Math.random()) * 90000)
            $("#seed_key").html(random_seed)
            //            $("#seed_key").html('15946')
        })
        $("#Customer_Class_ID").trigger('change')
        //        $("#OrderTable").live("paste","input",function(){
        //            $(this).val()
        //        })
        $("#submit_split_row").on("click", function() {
            var cloned_row = SelectedTR.clone(),
                split_qty = (parseFloat($("#split_qty").val()) || 0),
                split_disc = (parseFloat($("#split_disc").val()) || 0),
                qty = parseFloat(SelectedTR.find("span.qty_span").text()) || 0;
            if (split_qty == 0) {
                toastr.error('<?php echo CommonLanguage::getMessage('enter_valid_split_qty') ?>')
                return
            }
            if (split_qty >= qty) {
                toastr.error('<?php echo CommonLanguage::getMessage('split_no_exceed_item_qty') ?>')
                return
            }
            cloned_row.insertAfter(SelectedTR)
            cloned_row.find("span.qty_span").text(split_qty)
            cloned_row.find("span.discount").attr("data-disc", split_disc).text(round_number(split_disc) + ' %')
            cloned_row.attr("relate-entry-id", SelectedTR.attr("data-entry"))
            cloned_row.attr("data-entry", 0)
            cloned_row.attr("data-ref", Math.round(Date.now() + Math.random()))
            cloned_row.find("td.tr-gray").removeClass("tr-gray")
            EditDiscountEvent(cloned_row)
            $("select[name=uom]", cloned_row).prop('disabled', true);
            rem_qty = qty - split_qty;
            SelectedTR.find("span.qty_span").text(rem_qty)
            UpdateTable($("#OrderTable > tbody:last"))
            $("#split_row_modal").modal("hide")
        })

        //        $('#Persons_Count').on('blur', function(){
        //            if($(":focus").hasClass('key') || $(":focus").hasClass('key1'))
        //                last_focsd_elmnt = $(this);
        //            else
        //                last_focsd_elmnt = null;
        //        });
        var is_num_key_click = false;
        $('.key,.key1').on("click", function(event) {
            //
            //            if (last_focsd_elmnt !== null) {
            //                if ($(this).hasClass("key"))
            //                    last_focsd_elmnt.val(numBox.text() == '0' ? this.innerHTML : numBox.text() + this.innerHTML);
            //                last_focsd_elmnt.focus();
            //                event.stopPropagation();
            //                return false;
            //            }
            //            console.log(SelectedTR)
            if (!pos_return_postponed_change_item && is_return_postponed == 1) {
                return;
            }
            if (SelectedTR != '' && $(this).attr("data-role") != 'split_row' && SelectedTR.attr('data-entry') != '' && SelectedTR.attr("data-entry") != '0' && SelectedTR.attr("data-entry") != undefined && !change_item_row_after_edit) {
                return;
            }
            if (SelectedTR != '' && SelectedTR.attr('relate-entry-id') != '' && SelectedTR.attr("relate-entry-id") != '0' && SelectedTR.attr("relate-entry-id") != undefined && $(this).attr('data-role') == 'QTY') {
                return;
            }
            if (checkPrintDisbaled())
                return;
            //            $('.key,.key1').removeClass('not-allowed')
            if ($(this).hasClass('current_disable'))
                return false;
            if ($(this).hasClass('note-key'))
                return false;
            $('.key').removeClass('choosen');
            var tmp_is_num_key_click = false;
            var numBox = $("span.qty_span", SelectedTR);
            if ($(this).attr("data-role") == 'TAG') {
                getProductCriteria(SelectedTR.attr("data-id"), getCurrentTags(SelectedTR))
                $("#tagsModal").attr("data-id", SelectedTR.attr('data-ref'))
                //                $("#TagsTable td,#TagsTable button").removeClass("tagSelected")
                //                var item = $("#tagsModal").attr("data-id");
                //                if (item in ItemTags) {
                //                    var item_types = ItemTags[item];
                //                    for (key in item_types['types_arr']) {
                //                        $("#TagsTable tr input[data-ref=" + key + "]").prop("checked", true)
                //                        $("#TagsTable tr input[data-ref=" + key + "]").parents('td').addClass("tagSelected")
                //                        $("#TagsTable tr input[data-ref=" + key + "]").parents('button').addClass("tagSelected")
                //                    }
                //                }
                //                $("#tagsModal").modal("show")
            } else if ($(this).attr("data-role") == 'TRASH') {
                if (pos_confirm_delete_row == 1)
                    $("#ConfirmDeleteRow").modal("show")
                else {
                    if (void_item_pop_up_active && $('#invoice_auto_id').val() != 0 && SelectedTR.attr('data-entry') != 0) {
                        $('#void-item-reason-modal').modal('show')
                    } else {
                        $("#Row_Delete").trigger('click')
                    }
                }
            } else if ($(this).attr("data-role") == 'open-cash-drawer') {
                if (pos_reason_open_drawer == 1) {
                    $("#ConfirmOpenDrawer").modal("show");
                } else {
                    print_blank();
                }
            } else if ($(this).attr("data-role") == 'PRICE') {
                flag = 3
                $(".key1").removeClass("choosen")
                $(this).addClass("choosen")
                var price = $(SelectedTR).attr(is_ttc ? 'ttc-price' : 'data-price-single');
                if (login_device == 1) {
                    SelectedTR.find('.UPrice span.uprice-span').replaceWith($("<input type='number' class='input-save-on-barcodescan form-control text-center price-input-span' step='any' min='0' value='" + price + "'/>"))
                    SelectedTR.find('.price-input-span').focus().select()
                }
            } else if ($(this).attr("data-role") == 'total_price') {
                flag = 4
                $(".key1").removeClass("choosen")
                $(this).addClass("choosen")
                var price = parseFloat($(SelectedTR).find("span.price").attr('curprice'));
                if (login_device == 1) {
                    SelectedTR.find('.price').replaceWith($("<input type='number' min='0' class='input-save-on-barcodescan form-control text-center total-price-input-span' step='any' min='0' value='" + price + "'/>"))
                    SelectedTR.find('.total-price-input-span').focus().select()
                }
            } else if ($(this).attr('data-role') == 'CLR') {
                if (flag == 1) {
                    $(".discount", SelectedTR).attr('data-disc', "0")
                    EditDiscountEvent(SelectedTR)
                } else if (flag == 2) {
                    numBox.text('0')
                    UpdateTable($("#OrderTable > tbody:last"))
                } else if (flag == 3) {
                    $(SelectedTR).attr('data-price-single', "0")
                    $(SelectedTR).attr('ttc-price', "0")
                    UpdateTable($("#OrderTable > tbody:last"))
                } else if (flag == 4) {
                    $(SelectedTR).find("span.price").attr('curprice', "0").html("0")
                    $(SelectedTR).find(".qty_span").text(0)
                    UpdateTable($("#OrderTable > tbody:last"))
                }
            } else if ($(this).attr("data-role") == 'DEL') {
                if (flag == 1) {
                    var disc = $(".discount", SelectedTR).attr('data-disc');
                    $(".discount", SelectedTR).attr('data-disc', (disc.length > 1) ? disc.substring(0, disc.length - 1) : "0");
                    EditDiscountEvent(SelectedTR)
                } else if (flag == 2) {
                    numBox.text((numBox.text().length > 1) ? numBox.text().substring(0, numBox.text().length - 1) : '0');
                    UpdateTable(numBox.parents("tbody"))
                } else if (flag == 3) {
                    var price = $(SelectedTR).attr(is_ttc ? 'ttc-price' : 'data-price-single');
                    $(SelectedTR).attr((is_ttc ? 'ttc-price' : 'data-price-single'), (price.length > 1) ? price.substring(0, price.length - 1) : "0");
                    if (is_ttc) {
                        var myval = parseFloat($(SelectedTR).attr(is_ttc ? 'ttc-price' : 'data-price-single')) || 0,
                            //                        mytr = $(this).parents("tr"),
                            vat_percent = SelectedTR.attr("vat-percent") || 0,
                            vat2_percent = SelectedTR.attr("vat2-percent") || 0,
                            vat_amount2 = myval * (vat2_percent / 100) / (1 + (vat2_percent / 100)),
                            vat_amount = (myval - vat_amount2) * (vat_percent / 100) / (1 + (vat_percent / 100)),
                            amt_no_vat = myval - vat_amount - vat_amount2,
                            disc_percent = parseFloat(SelectedTR.find(".discount").attr("data-disc")) || 0,
                            unit_amt = amt_no_vat * (1 + (disc_percent / 100));
                        //                    SelectedTR.attr("ttc-price", unit_amt)
                        //            mytr.find(".VATPerItem").val(vat_amount.toFixed(3))
                        //            $(this).attr("MyVal", myval)
                        //            is_td_total = 1;
                        SelectedTR.attr("data-price-single", (myval - vat_amount - vat_amount2))
                        //                        SelectedTR.attr("ttc-price", myval)
                        SelectedTR.find(".UnitPrice").val(unit_amt) //.trigger("keydown")
                    }
                    //                    return
                    //                    $(SelectedTR).find('span.uprice-span').html((price.length > 1) ? price.substring(0, price.length - 1) : "0");
                    UpdateTable($("#OrderTable > tbody:last"))
                } else if (flag == 4) {
                    var tprice = $(SelectedTR).find("span.price").attr('curprice');
                    $(SelectedTR).find("span.price").attr('curprice', (tprice.length > 1) ? tprice.substring(0, tprice.length - 1) : "0");
                    var next_pr = parseFloat($(SelectedTR).find("span.price").attr('curprice')),
                        next_unit_price = parseFloat($(SelectedTR).attr("data-price-single")),
                        next_disc = parseFloat($(SelectedTR).find(".discount").attr("data-disc")) || 0;
                    next_pr = (next_disc == 100 ? 0 : (next_pr * 100 / (100 - next_disc)));
                    $(SelectedTR).find(".qty_span").text(next_pr / next_unit_price)
                    UpdateTable($("#OrderTable > tbody:last"))
                }
            } else if ($(this).attr("data-role") == 'DISC') {
                flag = 1;
                $(".key1").removeClass("choosen")
                $(this).addClass('choosen')
                var disc = parseFloat($(SelectedTR).find(".discount").attr("data-disc"));
                if (login_device == 1) {
                    SelectedTR.find('.discount').replaceWith($("<input type='number' min='0' class='input-save-on-barcodescan form-control text-center disc-input-span' step='any' min='0' value='" + disc + "'/>"))
                    SelectedTR.find('.disc-input-span').focus().select()
                }
            } else if ($(this).attr("data-role") == 'QTY') {
                flag = 2
                $(".key1").removeClass("choosen")
                $(this).addClass("choosen")
                var qty = parseFloat(SelectedTR.find('.qty_span').text())
                if (login_device == 1) {
                    SelectedTR.find('.qty_span').replaceWith($("<input type='number' " + ($("#titleSpan").attr("data-type") == 3 ? '' : 'min="0"') + " class='input-save-on-barcodescan form-control text-center qty-input-span' step='any' min='0' value='" + qty + "'/>"))
                    SelectedTR.find('.qty-input-span').focus().select()
                }

                //update table to fill total price if click to add new item
                UpdateTable($("#OrderTable > tbody:last"));
                checkDisableCashGenerateBtn();
            } else if ($(this).attr("data-role") == 'neg') {
                if (flag == 2 && $('#titleSpan').attr('data-type') == 3) {
                    var qty_span = parseFloat(SelectedTR.find("span.qty_span").html())
                    SelectedTR.find("span.qty_span").html(qty_span * -1)
                    UpdateTable($("#OrderTable > tbody:last"));
                }
            } else if ($(this).attr("data-role") == 'split_row') {
                var qty = parseFloat(SelectedTR.find('span.qty_span').text()) || 0;
                if (qty > 1 && parseFloat(SelectedTR.find('span.qty_span').text()) && SelectedTR.attr("data-entry") != '' && SelectedTR.attr("data-entry") != '0' && SelectedTR.attr("data-entry") != undefined) {
                    $("#split_qty").attr("max", (qty - 1)).val(1)
                    $("#split_disc").val(100)
                    $("#split_row_modal").modal("show")
                }
            } else if (!$(this).hasClass("empty_key")) { //for number keys
                tmp_is_num_key_click = true;
                if (flag == 1) {
                    var val = $(".discount", SelectedTR).attr('data-disc');
                    if (!is_num_key_click)
                        val = '';
                    $(".discount", SelectedTR).attr('data-disc', val + this.innerHTML);
                    if (this.innerHTML != '.')
                        EditDiscountEvent(SelectedTR)
                } else if (flag == 2) {
                    if (!is_num_key_click)
                        numBox.text('0');
                    $("span.qty_span", SelectedTR).text(numBox.text() == '0' ? this.innerHTML : numBox.text() + this.innerHTML);
                    //                    setTimeout(function () {
                    if (this.innerHTML != '.')
                        UpdateTable(numBox.parents("tbody"))
                    //                    }, 300)
                } else if (flag == 3) {
                    //                    $(SelectedTR).attr("price-change", "1")
                    var pr = $(SelectedTR).attr(is_ttc ? 'ttc-price' : 'data-price-single');
                    if (!is_num_key_click)
                        pr = '0';
                    pr = (pr == '0' ? this.innerHTML : pr + this.innerHTML);
                    if (this.innerHTML == '.')
                        $(SelectedTR).attr((is_ttc ? 'ttc-price' : 'data-price-single'), pr);
                    else {
                        if (is_ttc) {
                            var myval = parseFloat(pr) || 0,
                                //                        mytr = $(this).parents("tr"),
                                vat_percent = SelectedTR.attr("vat-percent") || 0,
                                vat2_percent = SelectedTR.attr("va2t-percent") || 0,
                                vat2_amount = myval * (vat2_percent / 100) / (1 + (vat2_percent / 100)),
                                vat_amount = (myval - vat2_amount) * (vat_percent / 100) / (1 + (vat_percent / 100)),
                                amt_no_vat = myval - vat_amount - vat2_amount,
                                disc_percent = parseFloat(SelectedTR.find(".discount").attr("data-disc")) || 0,
                                unit_amt = amt_no_vat * (1 + (disc_percent / 100));
                            //                    SelectedTR.attr("ttc-price", unit_amt)
                            //            mytr.find(".VATPerItem").val(vat_amount.toFixed(3))
                            //            $(this).attr("MyVal", myval)
                            //            is_td_total = 1;
                            SelectedTR.attr("data-price-single", (myval - vat_amount - vat2_amount))
                            SelectedTR.attr("ttc-price", myval)
                            SelectedTR.find(".UnitPrice").val(unit_amt) //.trigger("keydown")
                        } else {
                            $(SelectedTR).attr('data-price-single', pr);
                            //                    SelectedTR.attr("data-price-single", $(this).val())
                        }
                        //                    $(SelectedTR).attr('data-price-single', pr == '0' ? this.innerHTML : pr + this.innerHTML);
                        //                    setTimeout(function () {
                        UpdateTable(numBox.parents("tbody"))
                        //                    }, 300)
                    }
                } else if (flag == 4) {
                    var pr = $(SelectedTR).find("span.price").attr('curprice');
                    //                    alert(this.innerHTML)
                    if (!is_num_key_click)
                        pr = '0';
                    //                    alert(pr+'===='+)
                    $(SelectedTR).find("span.price").attr('curprice', pr == '0' ? this.innerHTML : pr + this.innerHTML);
                    var next_pr = parseFloat($(SelectedTR).find("span.price").attr('curprice')),
                        next_unit_price = parseFloat($(SelectedTR).attr("data-price-single")),
                        vat_amount = next_pr * (parseFloat($(SelectedTR).attr('vat-percent')) / 100) / (1 + (parseFloat($(SelectedTR).attr('vat-percent')) / 100)),
                        next_disc = parseFloat($(SelectedTR).find(".discount").attr("data-disc")) || 0;
                    next_unit_price = (next_disc == 100 ? 0 : (next_unit_price * (1 - (next_disc / 100))));
                    next_pr = (next_disc == 100 ? 0 : (next_pr - vat_amount));
                    next_pr_with_invdisc = next_unit_price * (1 - parseFloat($("#TotalTable  tr[data-discount]").attr("data-discount")) / 100);
                    //here we make round to high number to be able to get number in total price or it will be with many decimals
                    $(SelectedTR).find(".qty_span").text(round_number((next_pr / next_pr_with_invdisc), 12))
                    //                       var next_pr = parseFloat($(SelectedTR).find("span.price").attr('curprice')),
                    //                        next_unit_price = parseFloat($(SelectedTR).attr("data-price-single")),
                    //                        vat_amount = next_pr * (parseFloat($(SelectedTR).attr('vat-percent')) / 100) / (1 + (parseFloat($(SelectedTR).attr('vat-percent')) / 100)),
                    //                        next_disc = parseFloat($(SelectedTR).find(".discount").attr("data-disc")) || 0;
                    //                //                next_pr = (next_disc == 100 ? 0 : (next_pr * 100 / (100 - next_disc)));
                    //                next_unit_price = (next_disc == 100 ? 0 : (next_unit_price * (1 - (next_disc / 100))));
                    //                next_pr = (next_disc == 100 ? 0 : (next_pr - vat_amount));
                    //                next_pr_with_invdisc = next_unit_price * (1 - parseFloat($("#TotalTable  tr[data-discount]").attr("data-discount")) / 100);
                    //                $(SelectedTR).find(".qty_span").text(next_pr / next_pr_with_invdisc)
                    //                    setTimeout(function () {
                    UpdateTable(numBox.parents("tbody"))
                    //                    }, 300)
                }
            }
            is_num_key_click = tmp_is_num_key_click;
            event.stopPropagation();
        });
        $("#OrderTable tbody").on("input", ".qty-input-span,.disc-input-span,.price-input-span", function() {
            UpdateTable($("#OrderTable > tbody:last"));
        });
        $("#OrderTable tbody").on("blur", ".qty-input-span,.disc-input-span,.price-input-span,.total-price-input-span", function() {
            var input_val = parseFloat($(this).val()) || 0;
            if ($(this).hasClass("qty-input-span")) {
                $(this).replaceWith($("<span class='qty_span'>" + ($("#titleSpan").attr("data-type") == 3 ? input_val : (Math.abs(input_val))) + "</span>"))
            } else if ($(this).hasClass("disc-input-span")) {
                $(this).replaceWith($("<span class='discount' data-disc='" + Math.abs(input_val) + "'>" + AddCommas(Math.abs(input_val).toFixed(3)) + "&nbsp;%</span>"))
                EditDiscountEvent(SelectedTR)
            } else if ($(this).hasClass("price-input-span")) {
                if (is_ttc) {
                    var myval = input_val,
                        mytr = $(this).parents("tr"),
                        vat_percent = mytr.attr("vat-percent") || 0,
                        vat2_percent = mytr.attr("vat2-percent") || 0,
                        vat2_amount = myval * (vat2_percent / 100) / (1 + (vat2_percent / 100)),
                        vat_amount = (myval - vat2_amount) * (vat_percent / 100) / (1 + (vat_percent / 100)),
                        amt_no_vat = myval - vat_amount - vat2_amount,
                        disc_percent = parseFloat(mytr.find(".discount").attr("data-disc")) || 0,
                        unit_amt = amt_no_vat * (1 + (disc_percent / 100));
                    //                    SelectedTR.attr("ttc-price", unit_amt)
                    //            mytr.find(".VATPerItem").val(vat_amount.toFixed(3))
                    //            $(this).attr("MyVal", myval)
                    //            is_td_total = 1;
                    SelectedTR.attr("data-price-single", (myval - vat_amount - vat2_amount))
                    SelectedTR.attr("ttc-price", myval)
                    mytr.find(".UnitPrice").val(unit_amt) //.trigger("keydown")
                } else {
                    SelectedTR.attr("data-price-single", input_val)
                }
                $(this).replaceWith($("<span class='uprice-span'>" + AddCommas(Math.abs(input_val).toFixed(3)) + "&nbsp;</span>"))
                //        $(this).replaceWith($("<span class='uprice-span'>" + AddCommas(input_val.toFixed(3)) + "&nbsp;</span>"))
                //
                //    SelectedTR.attr("data-price-single", input_val)
            } else if ($(this).hasClass("total-price-input-span")) {
                $(this).replaceWith($("<span class='price' curprice='" + Math.abs(input_val) + "'>" + AddCommas(Math.abs(input_val).toFixed(3)) + "</span>"))
                var next_pr = parseFloat($(SelectedTR).find("span.price").attr('curprice')),
                    next_unit_price = parseFloat($(SelectedTR).attr("data-price-single")),
                    vat2_amount = next_pr * (parseFloat($(SelectedTR).attr('vat2-percent')) / 100) / (1 + (parseFloat($(SelectedTR).attr('vat2-percent')) / 100)),
                    vat_amount = (next_pr - vat2_amount) * (parseFloat($(SelectedTR).attr('vat-percent')) / 100) / (1 + (parseFloat($(SelectedTR).attr('vat-percent')) / 100)),
                    next_disc = parseFloat($(SelectedTR).find(".discount").attr("data-disc")) || 0;
                //                next_pr = (next_disc == 100 ? 0 : (next_pr * 100 / (100 - next_disc)));
                next_unit_price = (next_disc == 100 ? 0 : (next_unit_price * (1 - (next_disc / 100))));
                next_pr = (next_disc == 100 ? 0 : (next_pr - vat_amount - vat2_amount));
                next_pr_with_invdisc = next_unit_price * (1 - parseFloat($("#TotalTable  tr[data-discount]").attr("data-discount")) / 100);
                $(SelectedTR).find(".qty_span").text(round_number((next_pr / next_pr_with_invdisc), 12))
            }
            //            setTimeout(function () {
            UpdateTable($("#OrderTable tbody"))
            //            }, 300)
        });
        $("#Customer_Class_ID").on("change", function(e) {
            //setTimeout(function () {
            ChangePOSCurrency()
            //}, 1500)
        })
        $("#Customer_Class_ID").on("select2-selecting", function(e) {
            if ($(this).val() != '' && e.val != $(this).val()) {
                if ($("#OrderTable tbody tr").length > 0) {
                    //                    alert()
                    change_class_flag = true;
                }
            }
            //            if (flag) {
            //                $("#CustomerProceedModal").modal("show")
            //            }
            //setTimeout(function () {
            //    UpdateTable($("#OrderTable tbody"))
            //}, 300)
            if (activate_pos_select_cat == 'true' && $('#activate_cat_id').val() != 0)
                GotoCateg(-1);
            else
                AjaxLoadCateg($('#activate_cat_id').val());
        })
        $(".yes-btn").on("click", function() {
            var item_arr = {
                items: [],
                class_id: $("#Customer_Class_ID").val(),
                customer_id: $("#CurCustomerInfo").attr('CurCustomerID') ? $("#CurCustomerInfo").attr('CurCustomerID') : 0
            }
            $("#OrderTable tbody tr").each(function(e) {
                if ($(this).attr("data-id") > 0) {
                    item_arr.items.push({
                        pid: $(this).attr("data-id"),
                        uid: $("select[name=uom]", $(this)).val(),
                        index: $(this).index()
                    })
                }
            })
            $.ajax({
                url: "InventoryAjax/ReturnPriceByClass",
                data: item_arr,
                dataType: 'json',
                complete: function(v1, v2) {
                    if (v2 == "success") {
                        var Data = (v1.responseJSON);
                        for (var i = 0; i < Data.length; i++) {
                            var me = $("#OrderTable tbody tr:eq(" + Data[i]['index'] + ")")
                            //                                var me = $(this);
                            var tag_price = 0;
                            $(".mylabel", me).each(function() {
                                var cur_price = parseFloat($(this).attr("data-price")),
                                    local_amount = ConvertCurrency2(cur_price, old_currency[0], LocalCurrency[0]),
                                    converted_price = ConvertCurrency2(local_amount, LocalCurrency[0], PrimaryCurrency[0]);
                                $(this).attr("data-price", converted_price)
                                tag_price += converted_price;
                            });
                            //                            if (change_pos_currency == 1) {
                            //                                var con_price = ConvertCurrency2(tag_price, old_currency[0], PrimaryCurrency[0])
                            me.attr("data-price-single", (parseFloat(Data[i]['Product_Price']) + tag_price))
                            me.attr("ttc-price", (parseFloat(Data[i]['ttc_price']) + tag_price))
                            me.find("span.cost-hint ").html('(' + AddCommas((parseFloat(Data[i]['last_cost']) * parseFloat(Data[i]['conversion_amount'])).toFixed(1)) + ')')
                            me.find("span.price-hint ").html('(' + AddCommas((parseFloat(Data[i]['last_price']) * parseFloat(Data[i]['conversion_amount'])).toFixed(1)) + ')')
                            //                                me.attr("data-cost", parseFloat(Data[i]['last_cost']))
                            //                            } 
                            //                            else {
                            //                                me.attr("data-price-single", (Data[i]['price_local'] + local_amount))
                            //                                me.attr("ttc-price", (Data[i]['ttc_price_local'] + local_amount))
                            //                                me.find("span.cost-hint ").html('(' + AddCommas((parseFloat(Data[i]['local_cost']) * parseFloat(Data[i]['conversion_amount'])).toFixed(1)) + ')');
                            //                                me.find("span.price-hint ").html('(' + AddCommas((parseFloat(Data[i]['local_last_price']) * parseFloat(Data[i]['conversion_amount'])).toFixed(1)) + ')')
                            //                                //                                me.attr("data-cost",parseFloat(Data[i]['local_cost']))
                            //                            }
                            //                                console.log(Data[i]['Product_Price']+'==='+tag_price)
                            //                            })
                        }
                        UpdateTable($("#OrderTable tbody"))
                        GotoCateg(-1);
                    }
                }
            })
            $("#CustomerProceedModal").modal("hide")
        });
        $("#CustomerProceedModal").on("shown.bs.modal", function() {
            if (!show_all_prices && $("#scan_cust_qr").data('bs.modal').isShown)
                $(".yes-btn").trigger("click")
        })
        $("#transfer_action").on("click", function() {
            var tota_row_quantity = 0,
                total_selected_quantity = 0,
                is_valid = true;
            $('#OrderTable tbody tr').each(function() {
                var parent = $(this),
                    current_quantity = parseFloat(parent.find('span.qty_span').html()),
                    selected_quantity = parseFloat(parent.find('input[name=transfer_quantity]').val()) || 0;
                tota_row_quantity += current_quantity;
                if (!parent.find('input[name=transfer_quantity]').hasClass('hidden')) {
                    total_selected_quantity += selected_quantity;
                    if (selected_quantity <= 0)
                        is_valid = false;
                }
            });
            //            console.log(is_valid)
            //            return;
            if (!is_valid) {
                toastr.error('<?php echo CommonLanguage::getMessage('please_fill_qty'); ?>');
                return;
            }
            if (total_selected_quantity == 0) {
                toastr.error('<?php echo CommonLanguage::getMessage('choose_item'); ?>');
                return;
            }
            if (tota_row_quantity <= total_selected_quantity) {
                toastr.error('<?php echo CommonLanguage::getMessage('unable_select_all'); ?>');
                return;
            }
            if ($(this).attr('data-content') == 2) { //transfer
                $("#ava_rese_tbl_modal .modal-title").html("<?php echo CommonLanguage::getMessage('transfer_items'); ?>");
                build_tables(2);
            } else { //split
                var total_main_value = 0;
                $("#OrderTable input[name=entry_id]:checked").each(function() {
                    var Parent = $(this).parents("tr"),
                        quanity = parseFloat($("input[name=transfer_quantity]", Parent).val()),
                        main_qty = parseFloat($("span.qty_span", Parent).text()) || 0,
                        total_price = parseFloat($("span.price", Parent).attr("curprice")) || 0;
                    //we used total price to consider invoice discount
                    total_main_value += ((total_price / main_qty) * quanity);
                    //                    total_main_value += (quanity * parseFloat(Parent.attr('data-price-single')));
                });
                //                var final_total = total_main_value *
                $("#InvTypeMpdal input[name=main_total_value],#invoice_unpaid_amount").val(total_main_value);
                $("#InvTypeMpdal").modal("show");
            }
        });
        $("#OrderTable").on("click", ".del-tr", function() {
            if (!pos_return_postponed_change_item && is_return_postponed == 1) {
                return;
            }
            if ($(this).parents('tr').attr('data-entry') != '' && $(this).parents('tr').attr("data-entry") != '0' && $(this).parents('tr').attr("data-entry") != undefined && !change_item_row_after_edit) {
                return;
            }
            if (checkPrintDisbaled())
                return
            SelectedTR = $(this).parents('tr');
            $(".key[data-role=TRASH]").trigger('click')
        })
        $("#OrderTable").on("click", ".expiry_date", function() {
            if (parseFloat(SelectedTR.find("span.qty_span").html() || 0) < 0) {
                SelectedTR.find("td").removeClass("tr-gray tr-white").addClass("tr-return")
            } else {
                SelectedTR.find("td").removeClass("tr-gray tr-return").addClass("tr-white")
            }
            SelectedTR = $(this).parents('tr');
            if (SelectedTR.attr('expiry-active') == 1 || SelectedTR.attr('data-lot') == 1 || SelectedTR.attr('data-serial') == 1) {
                $('#expiry-date-modal').modal('show')
                if (SelectedTR.attr('expiry-active') == 1) {
                    $('#expiry-date-modal input[name=expiry_date]').val(SelectedTR.attr('data-expiry-date')).attr('data-select-name', SelectedTR.attr('data-expiry-date'))
                    if ($('#titleSpan').attr('data-type') == 1) {
                        build_select2($('#expiry_date'), function() {
                            var depot_id = $("#delivery_depot_id").val() != '' ? $("#delivery_depot_id").val() : user_depot_id;
                            return 'xhr/get_product_expiry?product_id=' + SelectedTR.attr("data-id") + '&depot=' + depot_id;
                        });
                    }
                    $(".exp-modal-div").removeClass("hidden")
                    $("#expiry_date").attr("required", "required")
                } else {
                    $(".exp-modal-div").addClass("hidden")
                    $("#expiry_date").removeAttr("required")
                }
                if (SelectedTR.attr('data-lot') == 1 && !pos_fields_to_hide.includes('0')) {
                    $(".lot-modal-div").removeClass("hidden")
                    $('#expiry-date-modal input[name=lot_nb]').val(SelectedTR.attr('data-lot-nb')).attr("data-select-name", SelectedTR.attr('data-lot-nb'))

                    if ($('#titleSpan').attr('data-type') == 1) {
                        build_select2($('#expiry-date-modal input[name=lot_nb]'), function() {
                            var depot_id = $("#delivery_depot_id").val() != '' ? $("#delivery_depot_id").val() : user_depot_id;
                            return 'xhr/get_product_lot?product_id=' + SelectedTR.attr("data-id") + '&depot=' + depot_id;
                        });
                    }
                } else {
                    $(".lot-modal-div").addClass("hidden")
                }
                if (SelectedTR.attr('data-serial') == 1 && !pos_fields_to_hide.includes('1')) {
                    $(".serial-modal-div").removeClass("hidden")
                    $('#expiry-date-modal input[name=serial_nb]').val(SelectedTR.attr('data-serial-nb')).attr("data-select-name", SelectedTR.attr('data-serial-nb'))

                    if ($('#titleSpan').attr('data-type') == 1) {
                        build_select2($('#expiry-date-modal input[name=serial_nb]'), function() {
                            var depot_id = $("#delivery_depot_id").val() != '' ? $("#delivery_depot_id").val() : user_depot_id;
                            return 'xhr/get_product_serial?product_id=' + SelectedTR.attr("data-id") + '&depot=' + depot_id;
                        });
                    }
                } else {
                    $(".serial-modal-div").addClass("hidden")
                }
            }
        })
        $("#OrderTable").on("click", ".reserve_date", function() {
            if (parseFloat(SelectedTR.find("span.qty_span").html() || 0) < 0) {
                SelectedTR.find("td").removeClass("tr-gray tr-white").addClass("tr-return")
            } else {
                SelectedTR.find("td").removeClass("tr-gray tr-return").addClass("tr-white")
            }
            SelectedTR = $(this).parents('tr');
            if (SelectedTR.attr('reserve-active') == 1) {
                $('#reservation-duration-modal').modal('show')
                $('#reservation-duration-modal #reserve_start_date').val(SelectedTR.attr('data-reserve-from'))
                $('#reservation-duration-modal #reserve_end_date').val(SelectedTR.attr('data-reserve-to'))
            }
        })
        $("#OrderTable").on("click", "input[name=entry_id]", function() {
            if ($(this).is(":checked")) {
                $(this).next().removeClass('hidden');
                $(this).next().val($(this).parents('tr').find('td:eq(3) span.qty_span').html());
            } else {
                $(this).next().addClass('hidden');
            }
        });
        $("#shipping_id").on("change", function() {
            //            setTimeout(function () {
            UpdateTable($("#OrderTable > tbody:last"))
            //            }, 300)
        });
        $("#Row_Delete").on("click", function() {
            $(SelectedTR).remove()
            $("#OrderTable > tbody:last >tr:eq(0)").trigger("click");
            UpdateTable($("#OrderTable > tbody:last"))
            $("#ConfirmDeleteRow").modal("hide")
            checkDisableCashGenerateBtn()
        });
        $("#OrderTable").on("click", "tr", function(e) {
            //            $("#OrderTable").find("td").css("background-color", "white")
            if (parseFloat(SelectedTR.find("span.qty_span").html() || 0) < 0) {
                SelectedTR.find("td").removeClass("tr-gray tr-white").addClass("tr-return")
            } else {
                SelectedTR.find("td").removeClass("tr-gray tr-return").addClass("tr-white")
            }
            SelectedTR = $(this);
            SelectedTR.find("td").removeClass("tr-return tr-white").addClass("tr-gray")
            if ($(this).attr("change-price") == 1) {
                $(".key-price").removeClass("not-allowed empty_key").attr("data-role", "PRICE")
            } else {
                if (change_pos_price)
                    $(".key-price").removeClass("not-allowed empty_key").attr("data-role", "PRICE")
                else
                    $(".key-price").addClass("not-allowed empty_key").removeAttr("data-role")
            }
            //
            if (pos_change_values_row_click) {
                var clicked_td = $(e.target);
                if ($(e.target)[0].tagName.toUpperCase() != 'TD')
                    clicked_td = $(e.target).closest('td');
                if (clicked_td.hasClass("qty-td")) {
                    //                console.log($(".key1[data-role=QTY]:not(.not-allowed)"))
                    $(".key1[data-role=QTY]:not(.not-allowed)").trigger("click")
                } else if (clicked_td.hasClass("UPrice")) {
                    $(".key1[data-role=PRICE]:not(.not-allowed)").trigger("click")
                } else if (clicked_td.hasClass("disc-td")) {
                    $(".key1[data-role=DISC]:not(.not-allowed)").trigger("click")
                } else if (clicked_td.hasClass("total-price-td")) {
                    $(".key1[data-role=total_price]:not(.not-allowed)").trigger("click")
                }
            }
        });
        $(".criteria-detail-div").on("click", '.removeTags', function() {
            if (checkPrintDisbaled())
                return;
            $(this).parents("tr").find("input:checked").removeAttr("checked")
            removeTags()
        });
        $("#addTag").on("click", function() {
            updateTags()
        });
        $("#OrderTable").on("click", "[data-role=remove]", function() {
            if (!pos_return_postponed_change_item && is_return_postponed == 1) {
                return;
            }
            if ($(this).parents("tr").attr('data-entry') != '' && $(this).parents('tr').attr("data-entry") != '0' && $(this).parents('tr').attr("data-entry") != undefined && !change_item_row_after_edit) {
                return;
            }
            var tagPr = parseFloat($(this).parents('.mylabel').attr('data-price') || 0),
                item = $(this).parents("tr").attr("data-ref"),
                singlePr = parseFloat($(this).parents("tr").attr("data-price-single") || 0),
                //curPr = parseFloat($(this).parents("tr").find("span.price").attr("curprice")),
                Parent = $(this).parents("tr"),
                qty = parseFloat(Parent.find('span.qty_span').text()) || 0,
                vat_amount = parseFloat(Parent.attr('vat-amount') || 0),
                vat2_amount = parseFloat(Parent.attr('vat2-amount') || 0),
                single_vat_amount = qty == 0 ? 0 : ((vat_amount + vat2_amount) / qty),
                vat_percent = parseFloat(Parent.attr('vat-percent') || 0),
                vat2_percent = parseFloat(Parent.attr('vat2-percent') || 0),
                removed_vat2_tag = tagPr * (vat2_percent / 100) / (1 + (vat2_percent / 100)),
                removed_vat_tag = (tagPr - removed_vat2_tag) * (vat_percent / 100) / (1 + (vat_percent / 100));
            //            var finalCur = parseFloat(curPr),
            var checked_price;
            if (is_ttc == 1)
                checked_price = (singlePr - tagPr + removed_vat_tag + removed_vat2_tag) < 0 ? 0 : (singlePr - tagPr + removed_vat_tag + removed_vat2_tag);
            else
                checked_price = (singlePr - tagPr) < 0 ? 0 : (singlePr - tagPr);
            //$(this).parents("tr").find("span.price").attr("curprice", finalCur)
            $(this).parents("tr").attr("data-price-single", (checked_price))
            //$(this).parents("tr").attr("data-price-single",(singlePr-tagPr))
            var ttc_checked_price = checked_price;
            if (is_ttc == 1)
                ttc_checked_price += (single_vat_amount - removed_vat_tag - removed_vat2_tag);
            $(this).parents("tr").attr('ttc-price', ttc_checked_price);
            //delete ItemTags[item].types_arr[$(this).parents("span.tag").attr("data-type")]
            $(this).parents("span.tag").remove()
            UpdateTable($("#OrderTable > tbody:last"))
            if ($("span.tag", Parent).length == 0) {
                $("tr[data-ref=" + item + "]").find('div.bootstrap-tagsinput').html('No Tags')
            }
        })
        $("#ava_rese_div").on("click", ".floor_divs", function() {
            var validate_postponed = check_posponed_fields();
            if (!validate_postponed)
                return false;
            check_before_post_invoice();
            var new_table_id = $(this).attr('data-id'),
                status_id = $(this).attr('data-status'),
                table_is_printed = $(this).attr('data-is-printed'),
                action_type = $(this).attr('action-type');
            if ((action_type == 1 && transfer_table_if_printed) ||
                (action_type == 3 && merge_table_if_printed) ||
                (action_type == 2 && transfer_item_if_printed) ||
                ($('#is_printed_invoice').val() == 0 && table_is_printed == 0)) {
                //                console.log('hello');
                //                console.log(action_type)
                PostInvoice(2, destination_type, new_table_id, status_id, action_type, '#ava_rese_tbl_disabler', 1);
            } else {
                //                console.log('hiii');
                toastr.error('<?php echo CommonLanguage::getMessage('invoice_printed_current_table'); ?>');
            }
            //            PostInvoice(2, destination_type, new_table_id, status_id, action_type, '#ava_rese_tbl_disabler', 1);
        });
        $("#Daily_Date").datepicker({
            autoclose: true
        })
        $("#Daily_Date").on("changeDate", function(e) {
            setTimeout(function() {
                ActualAjax(); //Rebuild table based on selected date
            }, 200)
        })
        $("#GInvBtn").on("click", function() {
            if ($("#OrderTable tbody tr").length > 0) {
                var main_amount = parseFloat($("#TotalTable tbody tr td.TotalVal").attr('data-total')) + parseFloat($("#shipping_id").val() || 0),
                    unpaid_amount = main_amount - parseFloat($("#cash_amount").val() || 0) - parseFloat($("#other_amount").val() || 0);
                $("#invoice_unpaid_amount").val(unpaid_amount);
                $("#InvTypeMpdal input[name=main_total_value]").val(main_amount);
                //                $("#InvTypeMpdal input[name=customer_id],#customer_id").attr('curcustomerid', $('#CurCustomerInfo').attr('curcustomerid'));
                $("#InvTypeMpdal").modal("show");
            }
        });
        //cash or cash no print
        $("#CashInvBtn,#CashWithoutPrintInvBtn,#generate_credit_card").on("click", function() {
            //            alert(is_delivery)
            var validate_postponed = check_posponed_fields();
            if (!validate_postponed)
                return false;
            check_before_post_invoice();
            var with_print = $(this).attr('id') == 'CashWithoutPrintInvBtn' ? 0 : 1;
            if ($("#OrderTable tbody tr").length > 0) {
                if (validateExpiryDates()) {
                    toastr.error(fill_expiry_dates)
                    return;
                }
                $("#InvTypeMpdal input[name=main_total_value],#invoice_unpaid_amount").val(parseFloat($("#TotalTable tbody tr td.TotalVal").attr('data-total')) + parseFloat($("#shipping_id").val() || 0));
                //                $("#InvTypeMpdal input[name=customer_id],#customer_id").attr('curcustomerid', $('#CurCustomerInfo').attr('curcustomerid'));
                $(".payment-labels").removeClass('payment-color-labels');
                var main_value = parseFloat($("#TotalTable tbody tr td.TotalVal").attr('data-total')) + parseFloat($("#shipping_id").val() || 0); //$("#InvTypeMpdal input[name=main_total_value]").val();
                //                $(this).addClass('payment-color-labels');
                $("#InvTypeMpdal .payment-inputs").val(0);
                $(".cash-return-span").html("0")
                if ($(this).attr("id") == 'generate_credit_card') {
                    $("#credit_input_label").trigger("click")
                    $("#other_amount").val(main_value)
                } else {
                    $("#cash_amount").val(main_value);
                }
                //                return;
                PostInvoice(2, destination_type, 0, 0, 'generate_invoice', '#Payment_Loader', with_print);
                //                return
                $("#InvTypeMpdal").modal("show");
                $("#InvTypeMpdal").modal("hide");
             }
         });
         






        //        $("#print_kitchen").on("click", function () {
        //            if (destination_type == 'takeaway' || destination_type == 'delivery') {
        //                $(".takeaway_delivary_details").removeClass('hidden');
        //                if (destination_type == 'takeaway') {
        //                    $(".delivary_details").addClass('hidden');
        //                } else {
        //                    $(".delivary_details").removeClass('hidden');
        //                }
        //            } else {
        //                $(".takeaway_delivary_details,.delivary_details").addClass('hidden');
        //            }
        //            if ($("#OrderTable tbody tr").length > 0) {
        //                is_delivery = 0;
        //                $("#addNoteModal").modal("show");
        //            }
        //        });
        $("#add_invoice_desc").on("click", function() {
            $("#invoice_desc_modal").modal("hide");
        })
        $("#text_note").on("keyup", function() {
            $("#text_note_delivery").val($("#text_note").val())
        })
        $("#text_note_delivery").on("keyup", function() {
            $("#text_note").val($("#text_note_delivery").val())
        })
        //for delivery submit
        $(".AddNote").on("click", function() {
            //             console.log(validate_postponed)
            var validate_postponed = check_posponed_fields();
            if (!validate_postponed)
                return false;
            check_before_post_invoice();
            //            if ($('#is_delivery_field').val() == 1)
            //                is_delivery = 1;
            if ($(this).hasClass("delivery"))
                is_delivery = 1;
            else
                is_delivery = 2;
            //            console.log($(this).hasClass("delivery"))
            //            console.log(is_delivery)
            $("#addNoteModal,#FunctionsModal").modal("hide");
            //            if (destination_type == "delivery" || destination_type == "takeaway") {
            //                var total = parseFloat($("#TotalTable tbody tr td.TotalVal").attr('data-total'));
            //                if (destination_type == "delivery") {
            //                    total += parseFloat($("#shipping_id").val());
            //                }
            //                $("#InvTypeMpdal input[name=main_total_value],#invoice_unpaid_amount").val(total);
            //                $("#InvTypeMpdal").modal('show');
            //            } else {
            if (validateExpiryDates()) {
                toastr.error(fill_expiry_dates)
                return;
            }
            //            $('#is_delivery_field').val('')
            PostInvoice(1, destination_type, 0, 0, 'park', '#note_loader', 1);
            //            }
        });
        $('#print_order_invoice_no_save').on('click', function() {
            printOrderInvoiceNoSave()
        });
        $('#open_functions_modal').on('click', function() {
            if (checkPrintDisbaled())
                return;
            $('#FunctionsModal').modal('show')
        })
        $("#addtoPark,#kitchen_delivery_takeaway").on("click", function() {
            var validate_postponed = check_posponed_fields();
            if (!validate_postponed)
                return false;
            check_before_post_invoice();
            is_delivery = 0;
            if ($(this).attr('data-type') == 'kitchen_takeaway_delivery')
                kitchen_takeaway_delivery = 1;
            if (checkPrintDisbaled())
                return;
            if ($("#OrderTable tbody tr").length > 0) {
                //                console.log('jj')
                if (validateExpiryDates()) {
                    toastr.error(fill_expiry_dates)
                    return;
                }
                if (activate_kitchen_note == 1) {
                    $('#order_note_modal').modal('show')
                    return;
                }
                pending_status = 3;
                $(".common_delivery").addClass("disabled")
                $("#InvTypeMpdal input[name=customer_id],#customer_id").attr('curcustomerid', $('#CurCustomerInfo').attr('curcustomerid'));
                var main_value = $("#InvTypeMpdal input[name=main_total_value]").val();
                $("#InvTypeMpdal .payment-inputs").val(0);
                $(".cash-return-span").html("0")
                //                $("#cash_amount").val(main_value);
                PostInvoice(2, destination_type, 0, 0, 'park', '#Payment_Loader', 1);
                $("#FunctionsModal").modal("hide")
            }
        });
        $('#submit_kitchen_note').on('click', function() {
            var validate_postponed = check_posponed_fields();
            if (!validate_postponed)
                return false;
            check_before_post_invoice();
            pending_status = 3;
            PostInvoice(2, destination_type, 0, 0, 'park', '#note_loader', 1);
            $('#order_note_modal').modal('hide')
        });
        $('.kitchen_note').on('click', function() {
            var validate_postponed = check_posponed_fields();
            if (!validate_postponed)
                return false;
            check_before_post_invoice();
            $('#order_note_description').val($(this).html())
            pending_status = 3;
            PostInvoice(2, destination_type, 0, 0, 'park', '#note_loader', 1);
            $('#order_note_modal').modal('hide')
        });
        $('.inv_desc_note').on('click', function() {
            $('#text_note').val($(this).html())

        });
        $('.post_desc_note').on('click', function() {
            $('#postponed_note').val($(this).html())

        });
        $(".common_delivery").on('click', function() {
            if ($("#OrderTable tbody tr").length > 0) {
                //                $('#is_delivery_field').val(1)
                $("#addNoteModal").modal('show')
            }
        })
        $(".cash-cats-div").on("click", ".cash-btn", function() {
            $("#cash_cat_amount").val(parseFloat($("#cash_cat_amount").val() || 0) + parseFloat($(this).attr("data-val")) || 0)
            //cash-return-span
            $("#cash_cat_amount").trigger("keyup")
        })
        $("#cash_cat_amount,#cash_amount").on("keyup", function() {
            $(".payment-labels[data-type='cash_amount']").addClass('payment-color-labels');
            var cash_amount = parseFloat($("#cash_amount").val()),
                cash_cat_amount = parseFloat($("#cash_cat_amount").val()),
                cash_return = cash_cat_amount - cash_amount;
            $(".cash-return-span").html(AddCommas(public_round_number(cash_return) || 0))
        })
        $("#clear-cash-cat").on("click", function() {
            $("#cash_cat_amount").val(0).trigger("keyup")
            //            $("#cash_cat_amount").trigger("keyup")
        })
        $("#retrieveSales").on("click", function() {
            RebuildDataTable('', [0, 1], "POSAjax/getSalesRetreiveList", {
                is_actual: is_actual
            }, '#retreiveListTable')
            $("#retrieve_list_modal").modal("show")
            $("#retreiveListTable").width('100%')
        })
        $("#retreiveListTable,#invoiceListTable,#postponedListTable,#main_pos_invoice_list,#invoiceDeliveryListTable").on("click", ".get_retrieved_data", function() {
            //            $(".common_delivery").addClass("disabled")
            var invoice_id_park = $(this).parents('.Action').attr('data-id');
            //            alert(invoice_id_park)
            retrieveData(invoice_id_park, 0);
        });
        $("#postponedListTable,#invoiceListTable").on("click", ".transfer_inv", function() {
            var invoice_id_park = $(this).parents('.Action').attr('data-id');
            retrieveData(invoice_id_park, 4);
        })
        $("#postponedListTable").on("click", ".return_postponed", function() {
            //            $(".common_delivery").addClass("disabled")
            var invoice_id_park = $(this).parents('.Action').attr('data-id');
            //            alert(invoice_id_park)
            //            $("#retunPOS").trigger("click")
            retrieveData(invoice_id_park, 3);
        });
        $("#retreiveListTable,#invoiceListTable,#main_pos_invoice_list").on("click", ".void_current_invoice", function() {
            //            $(".common_delivery").addClass("disabled")
            $("#VoidReasonModal .void_reason").prop("disabled", false);
            $('#void_reason_origin').val($(this).attr('data-origin'));
            $('#void_reason_invoice_id').val($(this).attr('data-invoice-id'));
        });
        $("#exchange_list_table").on("click", ".get_ex_data", function() {
            //            $(".common_delivery").addClass("disabled")
            var invoice_id_park = $(this).parents('.Action').attr('data-id');
            retrieveData(invoice_id_park, 1); //getExchangeDetails
        });
        $("#ReturnListTable").on("click", ".get_retrieved_ret_data", function() {
            //            $(".common_delivery").addClass("disabled")
            var invoice_id_park = $(this).parents('.Action').attr('data-id');
            retrieveData(invoice_id_park, 2); //getExchangeDetails
        });
        $("#reset_cache").on("click", function() {
            pos_db.remove_all_cat(function(is_succ) {
                alert(is_succ);
            });
        });
        $('#retreiveListTable,#main_pos_invoice_list').on('click', '.print_delivery_order', function() {
            var invoice_id = $(this).parents('div.Action').attr('data-id');
            $('#retrieve_list_modal_loader').removeClass('hidden')
            $.ajax({
                url: "POSAjax/reprintOrder",
                data: {
                    Invoice_ID_Auto: invoice_id,
                    pending_status: 3,
                    is_edited_invoice: 0,
                    invoice_type: 1
                },
                methd: "POST",
                dataType: "json",
                complete: function(v1, v2) {
                    if (v2 == "success") {
                        var response = v1.responseJSON;
                        if (response[0] == 'OK') {
                            $('#retrieve_list_modal_loader').addClass('hidden');
                            toastr.success('<?php echo CommonLanguage::getMessage('order_submitted_kitchen'); ?>');
                            hideModalAlert('retrieve_list_modal', '');
                        }
                    }
                }
            });
        });
        $('.fire').on('click', function() {
            var invoice_id = $('#invoice_auto_id').val(),
                fire_level = $(this).attr("data-role");
            $('#note_loader').removeClass('hidden')
            $.ajax({
                url: "POSAjax/print_fire",
                data: {
                    Invoice_ID_Auto: invoice_id,
                    pending_status: 3,
                    is_edited_invoice: 0,
                    invoice_type: 1,
                    fire_level: fire_level
                },
                methd: "POST",
                dataType: "json",
                complete: function(v1, v2) {
                    if (v2 == "success") {
                        var response = v1.responseJSON;
                        if (response[0] == 'OK') {
                            $('#note_loader').addClass('hidden');
                        }
                    }
                }
            });
        });
        $("#retreiveListTable,#main_pos_invoice_list").on("click", ".PrintInvoice", function() {
            myurl = "Inventory/pos_view_invoice/" + $(this).parents(".Action").attr("data-id");
            printPOSExternal(myurl)
        })
        $("#retreiveListTable,#main_pos_invoice_list").on("click", ".DeleteInvoice", function() {
            var invoice_id = $(this).parents('.Action').attr('data-id')
            $.ajax({
                url: "POSAjax/deleteParkedInvoice",
                data: {
                    invoice_id: invoice_id
                },
                methd: "GET",
                complete: function(v1, v2) {
                    if (v2 == "success") {
                        if (v1.responseText == 'OK') {
                            RebuildDataTable('', [0, 1], "POSAjax/getSalesRetreiveList", {
                                is_actual: is_actual
                            }, '#retreiveListTable');
                            if (is_shown_list_in_pos && destination_type == 0) {
                                RebuildDataTable('', [0, 1], "POSAjax/getSalesRetreiveList", {
                                    is_actual: is_actual
                                }, '#main_pos_invoice_list')
                                $('.main_pos_invoice_list_div .dataTables_filter,.main_pos_invoice_list_div .dataTables_length,.main_pos_invoice_list_div .dt-buttons,#main_pos_invoice_list thead tr.filter_columns_row').remove()
                            }
                            if (show_delivery_notification) {
                                RebuildDataTable('Delivery List', [], "POSAjax/getRemindersInv", {}, "#RemindersTable", '', {
                                    buttons: []
                                });
                                $('#builder .dt-buttons').remove()
                            }
                            if ($("#invoice_auto_id").val() == invoice_id) {
                                $('#OrderTable tbody,#CurCustomerInfo').empty()
                                $('#CurCustomerInfo').attr('curcustomerid', 0)
                                $('#CurCustomerInfo').attr('customer-pos-id', 0)
                                $('#CurCustomerInfo').attr('data-is-pos', 0)
                                $('#CurCustomerInfo').attr('data-account-id', 0)
                                $('#CurCustomerInfo').attr('data-tax', 0)
                                UpdateTable($("#OrderTable > tbody:last"))
                            }
                            $("#RetreiveListAlert").attr("class", "alert alert-success").html(Submitted_Successfully)
                            setTimeout(function() {
                                $("#RetreiveListAlert").addClass("hidden")
                            }, 5000)
                        } else {
                            $("#RetreiveListAlert").attr("class", "alert alert-danger").html(Failed_Submit)
                        }
                    }
                }
            })
        })
        $("#Tag_Select").on("change", function() {
            $(this).find("option[value=0]").remove()
            $('#DefineTagsForm input:checked').prop('checked', false)
            $('#DefineTagsForm input.tag_type_value').val('')
            $.ajax({
                url: "POSAjax/getTypesByTag",
                method: "GET",
                dataType: 'json',
                data: {
                    id: $(this).val()
                },
                complete: function(v1, v2) {
                    var tag_data = v1.responseJSON;
                    for (var i = 0; i < tag_data.length; i++) {
                        $('.tagCheck[value=' + tag_data[i]['Type_ID'] + ']').prop("checked", true)
                        $('.tagCheck[value=' + tag_data[i]['Type_ID'] + ']').parents(".tagRow").find(".tag_type_value ").val(tag_data[i]['Tag_Price'] != 0 ? tag_data[i]['Tag_Price'] : '')
                    }
                }
            })
        });
        $("#submit_user_transfer").on("click", function() {
            var Data = new FormData(document.getElementById("transfer_user_form"));
            $("#transfer_user_disabler").removeClass('hidden');
            $.ajax({
                url: "RestaurantAjax/submittransferUser",
                method: "POST",
                data: Data,
                processData: false,
                contentType: false,
                dataType: "JSON",
                complete: function(jqXHR, v2) {
                    if (v2 == "success") {
                        if (jqXHR.responseJSON[1] == "success") {
                            AddAlert('#transfer_user_alert', jqXHR.responseJSON[0], jqXHR.responseJSON[1]);
                            hideModalAlert('transfer_user_modal', 'transfer_user_alert');
                            hideModalAlert('FunctionsModal', '');
                            $("#OrderTable > tbody ").empty();
                            UpdateTable($("#OrderTable > tbody:last"));
                            setTimeout(function() {
                                window.location = site_link + 'main_page';
                            }, 2000);
                        }
                        $("#transfer_user_disabler").addClass('hidden');
                    }
                }
            });
        });
        $(".check_new").on("click", function() {
            if (is_edited_invoice == 1) {
                $("#confirm_empty_data_modal").modal("show")
            }
        })
        $("#empty_data_yes").on("click", function() {
            emptyPOSData()
            $("#confirm_empty_data_modal").modal("hide")
        })
        $("#exchange_pos").on("click", function() {
            if (is_edited_invoice == 1)
                return false;
            $('.calculator_div').removeClass('col-xs-12 col-sm-12 col-md-12 col-lg-12').addClass('col-xs-6 col-sm-6 col-md-6 col-lg-6')
            $('#keypad').removeClass('show_all_price_keypad_height')
            $('.totals_pos_btns_div').removeClass('hidden')
            if (change_pos_price_class) {
                $('.customer_class_div').removeClass('hidden')
            }
            $(".common_delivery_div_btn,.park_div_btn,.order_pos_div_btn").addClass("hidden")
            $(".transfer_pos_btn").addClass("hidden")
            $(".common_delivery,#addtoPark").addClass("disabled").attr('disabled', 'disabled')
            $("#titleSpan").html('<b class="red-star">Exchange</b>' + (is_actual == 1 ? '<span class="red-star">*</span>' : ''))
            $('#expiry_date_main_div').empty().append('<input class="form-control" id="expiry_date" name="expiry_date" type="text" required />');
            $('#lot_main_div').empty().append('<input type="text" class="form-control " id="lot_nb" name="lot_nb"   />');
            $('#serial_main_div').empty().append('<input type="text" class="form-control " id="serial_nb" name="serial_nb"   />');
            $('#expiry_date').datepicker({
                autoclose: true
            })
            $("#titleSpan").attr("data-type", 3).addClass("animateClass")
            $("td[data-role='neg']").removeClass("empty not-allowed")
            if (is_shown_list_in_pos && destination_type == 0)
                $(".main_pos_invoice_list_div").removeClass("hidden")
            $("#FunctionsModal").modal("hide")
        })
        $("#retunPOS").on("click", function() {
            if (is_edited_invoice == 1)
                return false;
            $('.calculator_div').removeClass('col-xs-12 col-sm-12 col-md-12 col-lg-12').addClass('col-xs-6 col-sm-6 col-md-6 col-lg-6')
            $('#keypad').removeClass('show_all_price_keypad_height')
            $('.totals_pos_btns_div,.depot_pic_div').removeClass('hidden')
            if (change_pos_price_class) {
                $('.customer_class_div').removeClass('hidden')
            }
            $('.transfer_pos_btn').addClass('hidden')
            $(".common_delivery_div_btn,.postponed_div_btn,.park_div_btn,.order_pos_div_btn").addClass("disabled hidden").attr('disabled', 'disabled')
            $(".common_delivery,#addtoPark").addClass("disabled").attr('disabled', 'disabled')
            $("#titleSpan").html('<b class="red-star">Return</b>' + (is_actual == 1 ? '<span class="red-star">*</span>' : ''))
            $('#expiry_date_main_div').empty().append('<input class="form-control" id="expiry_date" name="expiry_date" type="text" required />');
            $('#lot_main_div').empty().append('<input type="text" class="form-control " id="lot_nb" name="lot_nb"   />');
            $('#serial_main_div').empty().append('<input type="text" class="form-control " id="serial_nb" name="serial_nb"   />');
            $('#expiry_date').datepicker({
                autoclose: true
            })
            $("#titleSpan").attr("data-type", 2).addClass("animateClass")
            $("td[data-role='neg']").addClass("empty not-allowed")
            update_qty_to_positive()
            if (is_shown_list_in_pos && destination_type == 0)
                $(".main_pos_invoice_list_div").removeClass("hidden")
            $("#FunctionsModal").modal("hide")
        })
        $('#invoicePOS').on("click", function() {
            if (is_edited_invoice == 1)
                return false;
            $('.calculator_div').removeClass('col-xs-12 col-sm-12 col-md-12 col-lg-12').addClass('col-xs-6 col-sm-6 col-md-6 col-lg-6')
            $('#keypad').removeClass('show_all_price_keypad_height')
            $('.totals_pos_btns_div,.depot_pic_div').removeClass('hidden')
            if (change_pos_price_class) {
                $('.customer_class_div').removeClass('hidden')
            }
            $(".park_div_btn,.common_delivery_div_btn,.postponed_div_btn").removeClass("hidden")
            $(".order_pos_div_btn,.transfer_pos_btn").addClass("hidden")
            $(".common_delivery,#addtoPark").removeClass("disabled").removeAttr('disabled')
            $("#titleSpan").html('<b class="">Invoice</b>' + (is_actual == 1 ? '<span class="red-star">*</span>' : ''))
            $('#expiry_date_main_div').empty().append('<input class="full-width" id="expiry_date" name="expiry_date" type="hidden" required />');
            build_select2($('#expiry_date'), 'xhr/get_product_expiry?product_id=');
            $('#lot_main_div').empty().append('<input type="hidden" class="full-width " id="lot_nb" name="lot_nb"   />');
            build_select2($('#lot_nb'), 'xhr/get_product_lot?product_id=');
            $('#serial_main_div').empty().append('<input type="hidden" class="full-width " id="serial_nb" name="serial_nb"   />');
            build_select2($('#serial_nb'), 'xhr/get_product_serial?product_id=');
            $("#titleSpan").attr("data-type", 1).removeClass("animateClass")
            $("td[data-role='neg']").addClass("empty not-allowed")
            update_qty_to_positive()
            if (is_shown_list_in_pos && destination_type == 0)
                $(".main_pos_invoice_list_div").removeClass("hidden")
            show_prices()
            $("#FunctionsModal").modal("hide")
        })
        $('#order_pos').on("click", function() {
            if (is_edited_invoice == 1)
                return false;
            $(".park_div_btn,.postponed_div_btn,.common_delivery_div_btn,.totals_pos_btns_div").addClass("hidden")
            $(".transfer_pos_btn").addClass("hidden")
            $('.order_pos_div_btn,.depot_pic_div').removeClass("hidden")
            if (change_pos_price_class) {
                $('.customer_class_div').removeClass('hidden')
            }
            $(".common_delivery,#addtoPark").addClass("disabled").attr('disabled', 'disabled')
            $("#titleSpan").html('<b class="">Order</b>' + (is_actual == 1 ? '<span class="red-star">*</span>' : ''))
            $("#titleSpan").attr("data-type", 4).removeClass("animateClass")
            $('.calculator_div').removeClass('col-xs-6 col-sm-6 col-md-6 col-lg-6').addClass('col-xs-12 col-sm-12 col-md-12 col-lg-12')
            if (show_all_prices)
                $('#keypad').addClass('show_all_price_keypad_height')
            else
                $('#keypad').removeClass('show_all_price_keypad_height')
            if (is_shown_list_in_pos && destination_type == 0)
                $("#main_pos_invoice_list_div").removeClass("hidden")
            $("#FunctionsModal").modal("hide")
        });
        $('#request_transfer').on('click', function() {
            if (is_edited_invoice == 1)
                return false;
            $(".park_div_btn,.postponed_div_btn,.common_delivery_div_btn,.customer_class_div,.depot_pic_div").addClass("hidden")
            $(".totals_pos_btns_div,.order_pos_div_btn").addClass("hidden")
            $('.transfer_pos_btn').removeClass("hidden")
            $(".common_delivery,#addtoPark").addClass("disabled").attr('disabled', 'disabled')
            $("#titleSpan").html('<b class="">Transfer</b>' + (is_actual == 1 ? '<span class="red-star">*</span>' : ''))
            $("#titleSpan").attr("data-type", 5).removeClass("animateClass")
            $('.calculator_div').removeClass('col-xs-6 col-sm-6 col-md-6 col-lg-6').addClass('col-xs-12 col-sm-12 col-md-12 col-lg-12')
            if (show_all_prices)
                $('#keypad').addClass('show_all_price_keypad_height')
            else
                $('#keypad').removeClass('show_all_price_keypad_height')
            $(".main_pos_invoice_list_div").addClass("hidden")
            $(".price_element").addClass("hidden")
            hide_prices()
            $('#FunctionsModal').modal('hide')
        });
        $('.order_pos_btn').on('click', function() {
            if ($("#OrderTable tbody tr").length > 0) {
                var with_print = $(this).attr('data-print-type')
                if (scan_customer_card || order_delivery_date) {
                    $("#cust_card_alert").addClass("hidden");
                    if ($("#CurCustomerInfo").attr('CurCustomerID') == '' || $("#CurCustomerInfo").attr('CurCustomerID') == 0) {
                        $("#scanned_cust_name").addClass("hidden");
                        $('#fill_scanned_customer').removeClass("style_btn");
                        $('#generate_scan').addClass("style_btn");
                    } else {
                        $("#scanned_cust_name").removeClass("hidden").html($("#CurCustomerInfo span.Name").html());
                        $('#generate_scan').removeClass("style_btn");
                        $('#fill_scanned_customer').addClass("style_btn");
                    }
                    $("#scan_cust_qr").attr("with_print", with_print).modal("show")
                    //                
                } else {
                    PostInvoice(1, 0, 0, 0, '', '#main_pos_modal', with_print)
                }
            }
        });
        $('.transfer_pos_btn').on('click', function() {
            if ($("#OrderTable tbody tr").length > 0) {
                $('#request_transfer_modal').modal('show');
            }
        });
        $('#fill_scanned_customer').on('click', function() {
            if (($("#CurCustomerInfo").attr('CurCustomerID') == '' || $("#CurCustomerInfo").attr('CurCustomerID') == 0) && scan_customer_card) {
                $("#cust_card_alert").attr("class", "alert alert-danger").html(Required_Fields)
                return false;
            }
            //            $("#scan_cust_qr").modal("show")
            var with_print = $("#scan_cust_qr").attr("with_print")
            PostInvoice(1, 0, 0, 0, '', '#main_pos_modal', with_print)
        });
        $(is_order == 1 ? '#order_pos' : '#invoicePOS').trigger('click');
        $("#view_customer_list").on("click", function() {
            setTimeout(function() {
                RebuildPOSDataTable("POSAjax/POSCustomerListRequest", 1, "#Customertable")
            }, 300)
            $("#CustListModal").modal("show")
        })
        $("#Customertable tbody").on("click", ".editCust", function() {
            var cust_id = $(this).attr("data-id");
            $("#addCustomerModal").attr("data-edit", 1);
            $("#addCustomerModal").attr("data-customer", cust_id);
            var tr = $(this).parents('tr');
            $("#Customer_Name").val(tr.find("td:eq(0)").html());
            $("#Customer_Phone").val(tr.find("td:eq(2)").html());
            $("#Customer_Address").val(tr.find("td:eq(1)").html());
            $("#addCustomerModal").modal("show");
        });
        $(".add_pos_customer").on("click", function() {
            $("#addCustomerModal").attr("data-edit", 0);
            is_road_cust_edit = false;
            road_cust_to_edit = 0;
            $("#addCustomerModal").modal("show")
        });
        $(".payment-labels").on("click", function() {
            $(".payment-labels").removeClass('payment-color-labels');
            var main_value = $("#InvTypeMpdal input[name=main_total_value]").val(),
                payment_type = $(this).attr('data-type');
            $("#" + payment_type).val(parseFloat(main_value));
            CashUnpaidAmount();
            $("#cash_amount").trigger('keyup');
            $(this).addClass('payment-color-labels');
        });
        //generate submit
        $("#submit_payment").on("click", function() {
            var validate_postponed = check_posponed_fields();
            if (!validate_postponed)
                return false;
            check_before_post_invoice();
            var with_print = $("#inv_with_print").is(":checked") ? 1 : 0;
            if (validateExpiryDates()) {
                toastr.error(fill_expiry_dates)
                return;
            }
            var cust = $("#CurCustomerInfo").attr('CurCustomerID') ? $("#CurCustomerInfo").attr('CurCustomerID') : ($('#customer_id').attr('data-id') ? $('#customer_id').attr('data-id') : 0);
            if ($("#invoice_unpaid_amount").val() > 0 && cust == 0 && ($("#CurCustomerInfo").attr('customer-pos-id') == '' || $("#CurCustomerInfo").attr('customer-pos-id') == undefined || $("#CurCustomerInfo").attr('customer-pos-id') == 0) && !activate_cash_customer_oncredit) {
                AddAlert("#Payment_Alert", "Please choose customer", "danger");
                return false;
            }
            //            if (destination_type == 'takeaway' || destination_type == 'delivery') {
            //                //                alert(1)
            //                var dest_type = destination_type == 'takeaway' ? 3 : 1;
            //                PostInvoice(dest_type, 0, 0, 0, 0, '#Payment_Loader', with_print);
            //            } else {
            var split_generate;
            if (!$("#OrderTable .transfer_items_details").hasClass('hidden')) {
                //                    alert(2)
                split_generate = 4;
            } else {
                //                    if($("#invoice_unpaid_amount").val() > 0 )
                //                   alert(3)
                split_generate = 'generate_invoice';
            }
            PostInvoice(2, destination_type, 0, 0, split_generate, '#Payment_Loader', with_print);
            //            }
        });
        $("#cancel_transfer").on("click", function() {
            $(".transfer_items_details").addClass('hidden');
            $('.submit_main_div').removeClass('stop_submit_div');
            $(this).parents('.options_box').addClass('hidden');
        });
        $(".key_pad_actions").on("click", function() {
            if ($("#OrderTable tbody tr").length > 0) {
                var actionType;
                if ($(this).attr("data-role") == 'TRANSFERITEMS' || $(this).attr("data-role") == "SPLITITEMS") {
                    $('.submit_main_div').addClass('stop_submit_div');
                    $('.transfer_split_action_submit').removeClass('hidden')
                    $("#OrderTable .transfer_items_details,.options_box").removeClass('hidden');
                    //                    $(".options_box h4.option_title").html($(this).attr("data-role") == 'TRANSFERITEMS' ? '< ?php echo CommonLanguage::getMessage('choose_item_to_transfer'); ?>' : '< ?php echo CommonLanguage::getMessage('choose_item_to_split'); ?>');
                    $("#transfer_action").html($(this).attr("data-role") == 'TRANSFERITEMS' ? '<?php echo CommonLanguage::getMessage('transfer'); ?>' : '<?php echo CommonLanguage::getMessage('split'); ?>');
                    $("#transfer_action").attr('data-content', $(this).attr("data-role") == 'TRANSFERITEMS' ? 2 : 4);
                    $('#FunctionsModal').modal('hide')
                } else if ($(this).attr("data-role") == "MERGETABLES" || $(this).attr("data-role") == "TRANSFER") {
                    if ($(this).attr("data-role") == "TRANSFER") {
                        actionType = 1;
                        $("#ava_rese_tbl_modal .modal-title").html("<?php echo CommonLanguage::getMessage('transfer_table'); ?>");
                    } else {
                        actionType = 3;
                        $("#ava_rese_tbl_modal .modal-title").html("<?php echo CommonLanguage::getMessage('merge_tables'); ?>");
                    }
                    build_tables(actionType);
                }
            }
        });
        $('#reprint_order_kitchen').on('click', function() {
            $('#FunctionsModalDisabler').removeClass('hidden')
            $.ajax({
                url: "POSAjax/reprintOrder",
                data: {
                    Invoice_ID_Auto: $("#invoice_auto_id").val(),
                    pending_status: 3,
                    is_edited_invoice: 0,
                    invoice_type: 2,
                    printed_before: 1
                },
                methd: "POST",
                dataType: "json",
                complete: function(v1, v2) {
                    if (v2 == "success") {
                        var response = v1.responseJSON;
                        if (response[0] == 'OK') {
                            $('#FunctionsModalDisabler').addClass('hidden')
                            hideModalAlert('FunctionsModal', '');
                        }
                    }
                }
            })
        });
        $('#VoidReasonModal .void_reason').on('click', function() {
            $('#VoidReasonModalDisabler').removeClass('hidden')
            $.ajax({
                url: "RestaurantAjax/submitVoidInvoice",
                data: {
                    Invoice_ID_Auto: $("#void_reason_invoice_id").val(),
                    reason_id: $(this).attr('data-id')
                },
                dataType: "json",
                complete: function(v1, v2) {
                    if (v2 == "success") {
                        var response = v1.responseJSON;
                        if (v1.responseJSON[1] == 'success') {
                            $("#OrderTable > tbody ").empty();
                            UpdateTable($("#OrderTable > tbody:last"));
                            $("#VoidReasonModal .void_reason").attr('disabled', true)
                            hideModalAlert('VoidReasonModal');
                            if ($('#void_reason_origin').val() == 'table') {
                                setTimeout(function() {
                                    window.location = site_link + 'main_page';
                                }, 1600);
                            } else {
                                rebuild_inv_table();
                                rebuild_delivery_table();
                                RebuildDataTable('', [0, 1], "POSAjax/getSalesRetreiveList", {
                                    is_actual: is_actual
                                }, '#retreiveListTable')
                                RebuildDataTable('', [0, 1], "POSAjax/getSalesRetreiveList", {
                                    is_actual: is_actual
                                }, '#main_pos_invoice_list')
                                $('.main_pos_invoice_list_div .dataTables_filter,.main_pos_invoice_list_div .dataTables_length,.main_pos_invoice_list_div .dt-buttons,#main_pos_invoice_list thead tr.filter_columns_row').remove()
                            }
                        } else {
                            toastr.error(v1.responseJSON[0]);
                        }
                        $('#VoidReasonModalDisabler').addClass('hidden')

                    }
                }
            })
        });
        $("#pos_actual").on("click", function() {
            if (destination_type == 0) {
                if (is_actual == 1)
                    window.location = site_link + 'main_pos';
                else
                    window.location = site_link + 'main_pos/act';
            } else {
                if (is_actual == 1)
                    window.location = site_link + 'main_pos/' + destination_type;
                else
                    window.location = site_link + 'main_pos/act/' + destination_type;
            }
        })
        $(".criteria-detail-div").on("click", '#TagsTable input', function() {
            //            var parent_row = $(this).parents('tr');
            //            if(parent_row.attr('data-type') == 'checkbox'){
            //                var max_count = parseInt(parent_row.attr('max-count')),checked_tds = parseInt($('td.tagSelected',parent_row).length);
            //                console.log(max_count)
            //                console.log(checked_tds)
            //                if(checked_tds > max_count){
            //                    if($(this).closest('td').hasClass('tagSelected')){
            //                        $(this).closest('td').removeClass('tagSelected') 
            //                    }else{
            //                        return;
            //                    }
            //                }
            //
            //            }
            removeTags()
        });
        $('#open_online').on('click', function() {
            $('#checkNewFrame').attr('src', smart_diner_server_url + '?is_pop=1');
            $('#OnlineframeModal').modal('show');
        });
        $('#get_orders').on('click', function() {
            $('#online_loader').removeClass('hidden')
            $.ajax({
                type: 'POST',
                dataType: 'json',
                url: 'RestaurantAjax/getOfflineIds',
                complete: function(data, vv) {
                    if (vv == "success") {
                        var response = data.responseJSON;
                        if ($.type(response) == 'object') {
                            getOnlineOrders(response);
                        }
                    }
                }
            });
        });
        $('#retreiveListTable').on('click', '.generate_invoice', function() {
            var invoice_id = $(this).parents('div.Action').attr('data-id');
            $('#retrieve_list_modal_loader').removeClass('hidden')
            $.ajax({
                url: "POSAjax/generateInvoice",
                data: {
                    Invoice_ID_Auto: invoice_id
                },
                methd: "POST",
                dataType: "json",
                complete: function(v1, v2) {
                    if (v2 == "success") {
                        var response = v1.responseJSON;
                        if (response[0] == 'OK') {
                            RebuildDataTable('', [0, 1], "POSAjax/getSalesRetreiveList", {
                                is_actual: is_actual
                            }, '#retreiveListTable')
                            toastr.success('<?php echo CommonLanguage::getMessage('invoice_generated'); ?>')
                            $('#retrieve_list_modal_loader').addClass('hidden')
                        }
                    }
                }
            });
        });
        $('#retreiveListTable,#main_pos_invoice_list').on('click', '.cash_cash_no_print_invoice', function() {
            var invoice_id = $(this).parents('div.Action').attr('data-id');
            $('#main_pos_modal').removeClass('hidden')
            $.ajax({
                url: "POSAjax/generateCashInvoice",
                data: {
                    Invoice_ID_Auto: invoice_id,
                    with_print: $(this).attr('data-print')
                },
                methd: "POST",
                dataType: "json",
                complete: function(v1, v2) {
                    if (v2 == "success") {
                        var response = v1.responseJSON;
                        if (response[0] == 'OK') {
                            RebuildDataTable('', [0, 1], "POSAjax/getSalesRetreiveList", {
                                is_actual: is_actual
                            }, '#retreiveListTable')
                            toastr.success('<?php echo CommonLanguage::getMessage('invoice_generated'); ?>')
                            if (is_shown_list_in_pos && destination_type == 0) {
                                RebuildDataTable('', [0, 1], "POSAjax/getSalesRetreiveList", {
                                    is_actual: is_actual
                                }, '#main_pos_invoice_list')
                                $('.main_pos_invoice_list_div .dataTables_filter,.main_pos_invoice_list_div .dataTables_length,.main_pos_invoice_list_div .dt-buttons,#main_pos_invoice_list thead tr.filter_columns_row').remove()
                            }
                            $('#main_pos_modal').addClass('hidden')
                        }
                    }
                }
            });
        });
        $("#continue").on('click', function() {
            var myLocation = "<?php echo SITE_LINK . 'main_pos' . ($is_actual ? '/act' : ''); ?>";
            $('#main_pos_modal').removeClass('hidden');
            $.ajax({
                url: "ACCAjax/continueWithCurrentCashDrawer",
                complete: function(jqXHR, status) {
                    if (status == 'success') {
                        if (jqXHR.responseText == "success") {
                            setTimeout(function() {
                                window.location = myLocation;
                            }, 500)
                        }
                    }
                    $("#main_pos_modal").addClass('hidden');
                }
            });
        });
        $("#logout_cash_drawer").on('click', function() {
            $("#logout-amount-modal input[name=cash_drawer_id_ref]").val($(this).attr('data-cash-drawer-id'));
            $("#logout-amount-modal").modal("show");
        });
        $("#CurCustomerInfo").on("click", '.view_customer_last_orders', function() {
            $('#customer_last_order_loader').removeClass('hidden');
            $('#customer-last-order-modal').modal('show');
            //            $('#last_orders_div').empty();
            $.ajax({
                url: "POSAjax/getCustomerLastOrders",
                data: {
                    limit: 3,
                    customer_is_pos: $("#CurCustomerInfo").attr("data-is-pos"),
                    Customer_ID: $("#CurCustomerInfo").attr('CurCustomerID'),
                    pos_customer_id: $("#CurCustomerInfo").attr('customer-pos-id')
                },
                dataType: "json",
                complete: function(jqXHR, status) {
                    if (status == 'success') {
                        var response = jqXHR.responseJSON,
                            content = '',
                            responseLength = Object.keys(response).length;
                        //                        //                        console.log(responseLength)
                        if (responseLength == 0) {
                            content += '<tr style="font-size:15px;font-weight:bold;"><td colspan="4" style="background-color:#e5e5e5;" class="text-center"><div class="alert alert-info">' + no_data_available + '</div></td></tr>';
                        } else {
                            $.each(response, function(key1, value) {
                                content += '<tr style="font-size:15px;font-weight:bold;"><td colspan="4" style="background-color:#e5e5e5;" class="text-center">' + response[key1]['current_date'] + ' / ' + response[key1]['inv_num'] + '</td></tr>';
                                $.each(response[key1]['items'], function(key2, value) {
                                    var details = response[key1]['items'][key2];
                                    content += '<tr><td>' + details['Name'] + '</td><td class="text-center">' + details['Item_Quantity_Current'] + '</td><td class="text-center" style="white-space:nowrap;">' + details['Product_Net_Price'] + ' ' + response[key1]['cur_symbol'] + '</td><td>' + (details['TAG'] ? (details['TAG']) : '--- ---') + '</td></tr>';
                                });
                            });
                        }
                        $('#tbl_last_orders tbody').empty().append($(content));
                    }
                    $('#customer_last_order_loader').addClass('hidden');
                }
            });
        });
        $(".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
            }
        })
        $("#SubmitOpenReason").on("click", function() {
            if ($("#open_reason").val() == '') {
                $("#open_reason_alert").attr("class", "alert alert-danger").html(Required_Fields);
                return;
            }
            $.ajax({
                url: "POSAjax/insertOpenDrawerReason",
                data: {
                    open_reason: $("#open_reason").val()
                },
                methd: "GET",
                complete: function(v1, v2) {
                    if (v2 == "success") {
                        if (v1.responseText == 'OK') {
                            print_blank();
                            setTimeout(function() {
                                $("#ConfirmOpenDrawer").modal('hide');
                                $("#open_reason_alert").addClass('hidden');
                                $("#open_reason").val('');
                            }, 1500);
                        } else {
                            $("#open_reason_alert").attr("class", "alert alert-danger").html(v1.responseText);
                        }
                    }
                }
            });
        });
        $('#submit_expiry_date').on('click', function() {
            if (!$("#expiry-date-form").valid()) {
                return;
            }
            console.log(SelectedTR.attr("data-is-lot"))
            console.log(activate_lot)
            console.log($("#lot_nb").select2("data"))
            if (SelectedTR.attr("data-lot") == 1 && activate_lot == 1 && $("#lot_nb").select2("data") == null) {
                toastr.error(check_lot_exist_lang)
                return;
            }
            if (SelectedTR.attr("data-serial") == 1 && activate_serial == 1 && $("#serial_nb") && $("#serial_nb").select2("data") == null) {
                toastr.error(check_serial_exist_lang)
                return;
            }
            SelectedTR.attr('data-expiry-date', $('#expiry_date').val());
            SelectedTR.attr('data-lot-nb', $('#lot_nb').val());
            SelectedTR.attr('data-serial-nb', $('#serial_nb').val());
            $('#expiry-date-modal').modal('hide');
        });
        $('#submit_reservation_duration').on('click', function() {
            if (!$("#reservation_duration-form").valid()) {
                return;
            }
            SelectedTR.attr('data-reserve-from', $('#reserve_start_date').val());
            SelectedTR.attr('data-reserve-to', $('#reserve_end_date').val());
            $('#reservation-duration-modal').modal('hide');
        });
        $('.void_item_btn').on('click', function() {
            if (!$("#void-item-form").valid()) {
                return;
            }
            var entry_id = SelectedTR.attr('data-entry'),
                data_arr = [];
            void_item_reason_array[entry_id] = {
                reason_title: $('#item_void_reason').val(),
                type_id: $(this).attr('data-type')
            };
            $('#void-item-reason-modal').modal('hide')
            $("#Row_Delete").trigger('click')
        });
        $("#OrderTable").on("click", ".show_date_created", function() {
            var parent = $(this).parents('tr');
            $('.tip').not($('.tip', parent)).addClass('hidden');
            if ($('.tip', parent).hasClass('hidden')) {
                $('.tip', parent).removeClass('hidden')
            } else {
                $('.tip', parent).addClass('hidden')
            }
        });
        $("#OrderTable tbody").on("click", ".option-tr", function() {
            var tr = $(this).parents("tr"),
                ref = tr.attr("data-ref"),
                option_arr = tr.attr("data-option-arr") != undefined ? JSON.parse(tr.attr("data-option-arr")) : [];
            build_optional_link(ref, function(arr) {
                $.each(arr, function(indx, row) {
                    $(".op-div[data-id=" + row['product_id'] + "][data-option-id=" + row['option_id'] + "]").find('input.op-spinner').val(row['qty'])
                });
            }, [option_arr]);
            //            setTimeout(function () {

            //            }, 2000)

            $("#product_options_modal").attr("data-ref", ref)
        })
    });

    function checkPrintDisbaled() {
        if (!overwrite_print_perm && $('#is_printed_invoice').val() == 1) {
            $('.common-print').prop('disabled', true)
            return true;
        }
        return false
    }

    function removeTags() {
        $("#TagsTable td,#TagsTable button").removeClass("tagSelected")
        $("#TagsTable tr input:checked").parents('td').addClass("tagSelected")
        $("#TagsTable tr input:checked").parents('button').addClass("tagSelected")
        UpdateTable($("#OrderTable > tbody:last"))
    }

    function updateTags() {
        //        console.log('here')
        var item = $("#tagsModal").attr("data-id");
        //        ItemTags[item] = {Item_ID: item, types_arr: []};
        var tr = $("#OrderTable tbody tr[data-ref=" + item + "]"),
            total_tr_tag = parseFloat(tr.attr("data-price-single") || 0),
            vat_percent = parseFloat(tr.attr("vat-percent") || 0),
            vat2_percent = parseFloat(tr.attr("vat2-percent") || 0),
            qty = parseFloat(tr.find('span.qty_span').text()) || 0;
        var total_removed_tag_vat = 0;
        //        console.log($(".mylabel", tr))
        $(".mylabel", tr).each(function() {
            //            console.log('heree')
            var tag_price = parseFloat($(this).attr("data-price") || 0),
                tag_vat2 = tag_price * (vat2_percent / 100) / (1 + (vat2_percent / 100)),
                tag_vat = (tag_price - tag_vat2) * (vat_percent / 100) / (1 + (vat_percent / 100));
            //               console.log('tag-vat:'+tag_vat)
            total_tr_tag -= (is_ttc == 1 ? (tag_price - tag_vat - tag_vat2) : tag_price);
            total_removed_tag_vat += (tag_vat + tag_vat2);
            console.log(tag_vat + '===' + tag_vat2 + '===' + total_removed_tag_vat)
        });
        var totalTRPrice = total_tr_tag < 0 ? 0 : total_tr_tag
        tr.attr("data-price-single", totalTRPrice)
        $("#OrderTable tbody tr[data-ref=" + item + "] div.bootstrap-tagsinput").empty();
        //var totalTRPrice = parseFloat($("#OrderTable tbody tr[data-ref=" + item + "]").attr("data-price-single"));
        var total_added_tag_vat = 0;
        $("#tagsModal .criteria-detail-div input:checked").each(function() {
            var tag_name = $(this).attr("tag-name"),
                tag_price = parseFloat($(this).attr("tag-price") || 0),
                entry = $(this).val(),
                criteria_id = $(this).attr("data-criteria-id"),
                note = $(this).parents("tr").find(".tag-note").val(),
                vat_tag2 = tag_price * (vat2_percent / 100) / (1 + (vat2_percent / 100)),
                vat_tag = (tag_price - vat_tag2) * (vat_percent / 100) / (1 + (vat_percent / 100));
            total_added_tag_vat += (vat_tag + vat_tag2);
            totalTRPrice += (is_ttc == 1 ? (parseFloat(tag_price - vat_tag - vat_tag2)) : parseFloat(tag_price));
            var label_tag = '<span class="tag label label-info mylabel" data-content="' + tag_name + '" data-criteria-id="' + criteria_id + '" data-note="' + note + '" data-price="' + tag_price + '" data-entry="' + entry + '">' + tag_name + '<span data-role="remove"></span></span>';
            $("#OrderTable tbody tr[data-ref=" + item + "] div.bootstrap-tagsinput").append($(label_tag));
        });
        $("#OrderTable tbody tr[data-ref=" + item + "]").attr('data-price-single', totalTRPrice);
        var vat_amount = parseFloat($("#OrderTable tbody tr[data-ref=" + item + "]").attr('vat-amount') || 0);
        vat_amount += parseFloat($("#OrderTable tbody tr[data-ref=" + item + "]").attr('vat2-amount') || 0);
        var single_vat_amount = qty == 0 ? 0 : (vat_amount / qty);
        //we need to subtract remove tag vat amount since vat-amount on tr include the tag vat
        single_vat_amount -= total_removed_tag_vat;
        var ttc_single = is_ttc == 1 ? (totalTRPrice + single_vat_amount + total_added_tag_vat) : totalTRPrice;
        $("#OrderTable tbody tr[data-ref=" + item + "]").attr('ttc-price', ttc_single);
        UpdateTable($("#OrderTable > tbody:last"))
        $("#tagsModal").modal("hide")
    }

    function ActualAjax() {
        var CurrentDate = {
            Date: $("#Daily_Date").val()
        };
        RebuildPOSDataTable("POSAjax/POSInvoiceListRequests", CurrentDate)
    }

    function CashUnpaidAmount() {
        var main_value = parseFloat($("#InvTypeMpdal input[name=main_total_value]").val()),
            cash_value = parseFloat($("#cash_amount").val() || 0),
            other_value = parseFloat($("#other_amount").val() || 0);
        cash_value == 0 ? $('label.payment-labels[data-type=cash_amount]').removeClass('payment-color-labels') : '';
        other_value == 0 ? $('label.payment-labels[data-type=other_amount]').removeClass('payment-color-labels') : '';
        if ((cash_value < 0 || other_value < 0) && $("#titleSpan").attr("data-type") != 3) {
            AddAlert("#Payment_Alert", "Cash  and other amount should be greater than zero", "danger");
            $("#submit_payment").attr('disabled', true);
            return false;
        }
        if (Math.abs(cash_value) + Math.abs(other_value) > Math.abs(main_value)) {
            AddAlert("#Payment_Alert", "Cash  and other amount should be less than unpaid amount", "danger");
            $("#submit_payment").attr('disabled', true);
            return false;
        } else {
            $("#submit_payment").attr('disabled', false);
        }
        $("#invoice_unpaid_amount").val(main_value - (cash_value + other_value));
    }

    function getTotalDelivery() {
        $.ajax({
            url: "POSAjax/getTotalDelivery",
            data: {
                is_actual: is_actual
            },
            complete: function(v1, v2) {
                if (v2 == "success") {
                    $("#delivery_count").html(v1.responseText)
                    setTimeout(function() {
                        getTotalDelivery()
                    }, 60000)
                }
            }
        })
    }

    function getTotalOnlinePendingOrders() {
        $.ajax({
            dataType: "json",
            url: smart_diner_server_url + 'sync/get_total_orders',
            data: {
                branch_id: branch_id
            },
            complete: function(v1, v2) {
                if (v2 == "success") {
                    $("#online_orders_count").html(v1.responseJSON)
                    if (parseFloat(v1.responseJSON) > 0) {
                        $("#snackbar").html("<b>There are " + v1.responseJSON + " pending orders.</b>");
                        playSuccessAudio();
                    }
                    setTimeout(function() {
                        getTotalOnlinePendingOrders();
                    }, 300000);
                }
            }
        })
    }

    function build_tables(actionType) {
        var user_id = <?php echo json_encode(SESSION::getUserID()); ?>;
        $("#ava_rese_tbl_modal").modal("show");
        CommonViewById('RestaurantAjax/get_all_tables', {
            table_id: destination_type,
            type_id: actionType
        }, '#ava_rese_tbl_disabler', function(Response) {
            $("#ava_rese_div").empty();
            $.each(Response, function(key1, value) {
                if ('tables' in Response[key1]) {
                    $("#ava_rese_div").append(' <div class="col-md-12"><h2>' + Response[key1]['floor_name'] + '</h2></div>');
                    var all_tables = Response[key1]['tables']
                    $.each(all_tables, function(key2, value) {
                        if (all_tables[key2]['status_id'] == 1) {
                            var table = '<div class="col-sm-2 col-md-2 col-lg-2 m-b-10 " >' +
                                '<div class="floor_divs available" action-type="' + actionType + '" data-is-printed="0" data-id="' + all_tables[key2]['table_id'] + '" data-status="' + all_tables[key2]['status_id'] + '" >' +
                                '<div class="panel-heading">' +
                                '<div class="panel-title text-black f-s-50 hint-text text-center"><b>' + all_tables[key2]['table_name'] + '</b></div>' +
                                '</div>' +
                                '</div>' +
                                '</div>';
                        } else {
                            if (all_tables[key2]['user_id'] == user_id || view_all_table) {
                                var table = '<div class="col-sm-2 col-md-2 col-lg-2 m-b-10 " >' +
                                    '<div class="floor_divs reserved" action-type="' + actionType + '" data-is-printed="' + all_tables[key2]['is_printed'] + '" data-id="' + all_tables[key2]['table_id'] + '" data-status="' + all_tables[key2]['status_id'] + '" >' +
                                    '<div class="panel-heading">' +
                                    '<div class="panel-title text-black f-s-50 hint-text text-center"><b>' + all_tables[key2]['table_name'] + '</b></div>' +
                                    '</div>' +
                                    '</div>' +
                                    '</div>';
                            }
                        }
                        $("#ava_rese_div").append($(table));
                    });
                    $("#ava_rese_div").append('<div class="col-md-12"></div>');
                }
            });
        });
    }

    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) {
        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,
            currency_id: PrimaryCurrency[0],
            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-price="' + all_details[key2]['criteria_detail_price'] + '" 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 ChangePOSCurrency() {
        if (change_pos_currency == 1) {
            $('#main_pos_modal').removeClass('hidden')
            $.ajax({
                url: "POSAjax/ReturnClassCurrency",
                data: {
                    class_id: $("#Customer_Class_ID").val()
                },
                dataType: 'json',
                complete: function(v1, v2) {
                    if (v2 == "success") {
                        var data = v1.responseJSON;
                        is_ttc = data['is_ttc'];
                        old_currency = PrimaryCurrency;
                        PrimaryCurrency = [data['Currency_ID'], data['Currency_Symbol'], data['Currency_Code'], data['currency_round']];
                        $('.cash-return-currency').html(data['Currency_Symbol'])
                        var taxamount = (activate_card_tax ? data['tax_amount'] : 0);
                        $("#CurCustomerInfo").attr("data-tax", taxamount);
                        $("tr[data-tax=1]").attr("tax-amount", taxamount)
                        // setTimeout(function () {
                        UpdateTable($("#OrderTable tbody"))
                        changeCashBtnsWithCurrency()
                        $('#main_pos_modal').addClass('hidden')
                        if (change_class_flag && $("#OrderTable tbody tr").length > 0)
                            $("#CustomerProceedModal").modal("show")
                        if (($('#CurCustomerInfo').attr('data-is-pos') == 1 && show_balance_search_road_cust) ||
                            ($('#CurCustomerInfo').attr('data-is-pos') == 0 && show_balance_search_cust)) {
                            getAccBalance('#search_customer_balance', $('#CurCustomerInfo').attr('data-account-id'), $('#CurCustomerInfo').attr('data-is-pos') == 0 ? '' : $('#CurCustomerInfo').attr('customer-pos-id'));
                        }
                        //
                        // }, 300)
                    }
                }
            });
        }
    }

    function changeCashBtnsWithCurrency() {
        $.ajax({
            url: "POSAjax/get_cash_btns_by_cur",
            data: {
                currency_id: PrimaryCurrency[0]
            },
            dataType: 'json',
            complete: function(v1, v2) {
                if (v2 == "success") {
                    var cashs = v1.responseJSON;
                    $(".cash-cats-div").empty()
                    var cash_div = ' ';
                    for (var i = 0; i < cashs.length; i++) {
                        cash_div +=
                            '<div class="col-md-2">' +
                            '   <button class="btn cash-btn" type="button" data-val = "' + cashs[i]['Cash_Category_Value'] + '">' + cashs[i]['Cash_Category_Value'] + '</button>' +
                            '</div>';
                    }
                    $(".cash-cats-div").append($(cash_div))
                }
            }
        })
    }

    function retrieveData(invoice_id_park, type) {


        $.ajax({
            url: type == 0 || type == 3 || type == 4 ? "POSAjax/getInvoiceDetails?invoice_id_auto=" + invoice_id_park : (type == 1 ? "POSAjax/getExchangeDetails?id=" + invoice_id_park : "POSAjax/getReturnDetails?id=" + invoice_id_park),
            dataType: "json",
            complete: function(v1, v2) {
                if (v2 == "success") {
                    var response = v1.responseJSON,
                        responseDetails = response.Details;
                    if (type == 0 && response['pay_inv_link'] !== '') {
                        toastr.error('<?php echo CommonLanguage::getMessage('inv_pay_link_alert') ?>' + ' ' + response['pay_inv_link'])
                        return false;
                    }
                    $("#invoice_auto_id").val(invoice_id_park)
                    $('#main_pos_modal').removeClass('hidden')
                    is_ttc = response.Main.is_ttc;
                    if ('Is_Closed' in response.Main)
                        is_closed = response.Main.Is_Closed;
                    if (is_closed == 1)
                        $("#kitchen_delivery_takeaway").prop('disabled', true)
                    else {
                        $("#kitchen_delivery_takeaway").prop('disabled', false)
                    }
                    $("#shipping_id").val(response.Main.shipping).attr('data-select-name', response.Main.delivery_fees_view);
                    build_select2($("#shipping_id"), ("xhr/DeliveryFeesSeacrh"));
                    //                    console.log(response);
                    if (response.Person.customer_is_pos == 1) {
                        $("#postponed_pos_customer_id").val(response.Person.customer_pos_id).attr('data-select-name', response.Person.Customer_Name + ' - ' + response.Person.Phone)
                        build_select2($("#postponed_pos_customer_id"), "xhr/poscustomerSearch")
                    }
                    if (type != 3 || pos_postponed_return_autofill_paid == 1) {
                        var is_payment = false;
                        if ('Credit_Card' in response.Payment) {
                            is_payment = true;
                            $("#other_description").val(response.Payment['Credit_Card'].Transaction_Description)
                            $("#credit_input_label").prop("checked", true)
                            $("#other_amount").val(response.Payment['Credit_Card'].Transaction_Amount)
                        } else if ('Cheque' in response.Payment) {
                            is_payment = true;
                            $("#other_description").val(response.Payment['Cheque'].Transaction_Description)
                            $("#check_input_label").prop("checked", true)
                            $("#other_amount").val(response.Payment['Cheque'].Transaction_Amount)
                        }
                        if ('Cash' in response.Payment) {
                            is_payment = true;
                            $("#cash_amount").val(response.Payment['Cash'].Transaction_Amount);
                            //                        console.log(response.Main);
                        }
                        if (!is_payment) {
                            $("#cash_amount").val(response.Main.Paid_Amount)
                        }
                    }
                    if (response.Main.reservation_id) {
                        var invoice_note = response.Main.Invoice_Note.split("\n");
                        if (invoice_note instanceof Array) {
                            $('#reservation_id').val(response.Main.reservation_id).attr('data-select-name', invoice_note[0] + ' - ' + invoice_note[1] + ' - ' + response.Main.customer_name_alias)
                            build_select2($("#reservation_id"), "xhr/searchReservations");
                        }
                    }

                    $("#postponed_note").val(response.Main.postponed_note)
                    $("#postponed_date_time").val(response.Main.postponed_date_time)
                    $("#order_note_description").val(response.Main.order_note)
                    $("#posponted_status").val(response.Main.posponted_type == 0 ? '' : response.Main.posponted_type).select2()
                    $("#CurCustomerInfo").attr("data-tax", response.Main.class_tax)
                    $("#delivery_depot_id").val(response.Main.Depot_ID).attr("data-select-name", response.Main.Depot_Name)
                    $("#driver_id").val(response.Main.driver_id).attr("data-select-name", response.Main.driver_name).trigger("change")
                    build_select2($("#delivery_depot_id"), "xhr/depotSearch")
                    if (response.Main.Is_Delivery == 1 || response.Main.invoice_type == 6) {
                        is_delivery = response.Main.invoice_type == 6 ? 2 : 1
                        $('#timepicker').val(time_convert_24_to_12(response.Main.Delivery_Time.substr(11, 5)))
                    }
                    // console.log(is_delivery)
                    $(".Depot_PIC_ID").val(response.Main.Sales_ID ? response.Main.Sales_ID : 0).attr("data-select-name", (response.Main.Employee_Name ? response.Main.Employee_Name : ''))
                    build_select2($(".Depot_PIC_ID"), "xhr/employeeSearch", false, 'diff_class')
                    $("#OrderTable > tbody").empty();
                    PrimaryCurrency = [response.Main.Currency_ID, response.Main.Currency_Symbol, response.Main.Currency_Name, response.Main.currency_round];
                    for (i = 0; i < responseDetails.length; i++) {
                        var T = $("#OrderTable > tbody:last");
                        var Data = responseDetails[i];
                        var Row = $("<tr data-entry='" + Data['Entery_ID'] + "'  price-change='0' data-conv='1' data-product-ref='" + Data['Product_ID'] + "' data-ref='" + Math.round(Date.now() + Math.random()) + "' data-cid='" + 0 + "'data-id='" + Data['Product_ID'] + "' data-discount='" + Data['Product_Discount'] + "' data-price-single='" + Data['Product_Net_Price'] + "' data-qty='" + Data['Product_Quantity'] + "' data-vat='" + Data['VAT'] + "' vat-percent='" + Data['vat_percent'] + "' vat2-percent='" + Data['vat2_percent'] + "' data-is-option='" + Data['has_option'] + "' recipe-qty='" + Data['recipe_qty'] + "' data-option-arr='" + JSON.stringify(Data['options']) + "' data-last-qty='" + (Data['def_in_qty']) + "' ttc-price='" + Data['ttc_price'] + "' expiry-active ='" + Data['is_expiry'] + "' data-lot='" + Data['is_lot'] + "' data-serial='" + Data['is_serial'] + "' data-lot-nb='" + Data['lot_nb'] + "' data-serial-nb='" + Data['serial_nb'] + "' reserve-active ='" + Data['duration_reservation'] + "' change-price='" + Data['force_change_price'] + "' data-expiry-date='" + (Data['expiry_date'] ? Data['expiry_date'] : '') + "' data-reserve-from='" + (Data['reserve_from'] ? Data['reserve_from'] : '') + "' data-reserve-to='" + (Data['reserve_to'] ? Data['reserve_to'] : '') + "' data-cost='" + Data['unit_cost'] + "' data-max-discount='" + Data['Product_Limit_Discount'] + "' data-tax='" + Data['is_tax'] + "' tax-amount='" + Data['unit_tax'] + "' data-category-id='" + Data['Category_ID'] + "' data-service='" + Data['is_service'] + "'></tr>"),
                            T2 = RowTemp,
                            qty_changed = parseFloat($(this).find('span.price').attr("CurPrice")) / parseFloat($(this).attr("data-price-single"));
                        $(this).find('.InputSpinner > span.qty_span').html(qty_changed)
                        T2 = T2.replace("$CHECKBOX$", "hidden")
                        T2 = T2.replace("$ID$", "1")
                        T2 = T2.replace("$NAME$", Data['Name'])
                        T2 = T2.replace("$QTY$", Data['Item_Quantity_Current']);
                        T2 = T2.replace("$QTYHINT$", '(' + AddCommas(parseFloat(Data['Quantity']).toFixed(1)) + ')');
                        T2 = T2.replace("$COSTHINT$", '(' + AddCommas(parseFloat(Data['unit_cost']).toFixed(1)) + ')');
                        T2 = T2.replace("$PRICEHINT$", '');
                        /*end edit*/
                        T2 = T2.replace("$BARCODE$", Data['Bar_Code'])
                        T2 = T2.replace("$VAT$", Data['Product_VAT'])
                        T2 = T2.replace("$TAX$", Data['is_tax'])
                        T2 = T2.replace("$VATPERCENT$", Data['vat_percent'])
                        T2 = T2.replace("$VAT2PERCENT$", Data['vat2_percent'])
                        T2 = T2.replace("$TTCPRICE$", Data['ttc_price'])
                        //                        T2 = T2.replace("$EXPIRYACTIVE$", Data['is_expiry'])
                        //                        T2 = T2.replace("$RESERVEACTIVE$", Data['duration_reservation'])
                        T2 = T2.replace("$CHANGEPRICE$", Data['force_change_price'])
                        T2 = T2.replace("$CATEGORY_ID$", Data['Category_ID'])
                        if ((Data['is_expiry'] == 1 && is_active_expiry_date == 1) || (!pos_fields_to_hide.includes('0') && Data['is_lot'] == 1) || (!pos_fields_to_hide.includes('1') && Data['is_serial'] == 1))
                            T2 = T2.replace("$EXPIRYICON$", '<i class="fa fa-calendar expiry-icon"></i>');
                        else
                            T2 = T2.replace("$EXPIRYICON$", '');
                        if (Data['duration_reservation'] == 1 && is_active_reserve_date == 1) {
                            T2 = T2.replace("$RESERVEICON$", '<i class="fa fa-calendar reserve-icon"></i>');
                        } else
                            T2 = T2.replace("$RESERVEICON$", '');
                        //                        T2 = T2.replace("$EXPIRYDATE$", Data['expiry_date'])
                        T2 = T2.replace("$MAXDISC$", Data['Product_Limit_Discount'])
                        T2 = T2.replace("$UNITPRICE$", Data['Product_Net_Price'])
                        //                            T2 = T2.replace("$PRICE$", Data['Product_Total_Price'])
                        T2 = T2.replace("$PRICE$", 10)
                        T2 = T2.replace(/\$CURRENCY\$/g, PrimaryCurrency[1]);
                        if (Data['force_change_price'] == 1) {
                            $(".key-price").removeClass("not-allowed empty_key").attr("data-role", "PRICE")
                        } else {
                            if (change_pos_price)
                                $(".key-price").removeClass("not-allowed empty_key").attr("data-role", "PRICE")
                            else
                                $(".key-price").addClass("not-allowed empty_key").removeAttr("data-role")
                        }
                        var hold = 0;
                        Row.attr("data-hold", Data['hold'])
                        T2 = T2.replace("$holdclass$", "hold" + Data['hold']);
                        T2 = T2.replace("$holdlevel$", Data['hold']);
                        T.prepend(Row);
                        Row.append(T2);
                        if (Data['has_option'] == 1) {
                            $(".option-tr", $(Row)).removeClass("hidden")
                        }
                        Row.find("span.qty_span").html(Data['Item_Quantity_Current'])
                        if (!delete_row_pos)
                            Row.find('.del-tr .red-star').addClass("hidden")
                        //    Row.find('select.uom').show().select2()
                        Row.find("select[name=uom] > option[value=" + Data['UOM_ID'] + "]").attr("selected", true)
                        //    Row.find("select[name=uom]").select2()
                        var units_arr = Data['Product_UOM'].split("/");
                        $("select[name=uom] > option", Row).each(function() {
                            if ($.inArray($(this).attr("value"), units_arr) === -1) {
                                $(this).remove()
                            }
                        });
                        if ($('#titleSpan').attr('data-type') == 1 && !pos_fields_to_hide.includes('3') && Data['details_date_created']) {
                            Row.find('span.item-name').append(' <i class="fa fa-info-circle show_date_created pull-right prod-desc-icon"></i><div class="tip hidden">Data added:<br>' + Data['details_date_created'] + '</div>');
                        }
                        Row.attr('product-description', Data['product_description'])
                        if (checkPrintDisbaled()) {
                            $("select[name=uom]").prop('disabled', true)
                        }
                        if ('criteria' in Data) {
                            var label_tag = '';
                            for (k = 0; k < Data['criteria'].length; k++) {
                                label_tag += '<span class="tag label label-info mylabel" data-content="' + Data['criteria'][k]['criteria_detail_name'] + '" data-criteria-id="' + Data['criteria'][k]['criteria_id'] + '"  data-note="' + Data['criteria'][k]['criteria_note'] + '" data-price="' + Data['criteria'][k]['criteria_price'] + '" data-entry="' + Data['criteria'][k]['criteria_detail_id'] + '" >' + Data['criteria'][k]['criteria_detail_name'] + '<span data-role="remove"></span></span>';
                            }
                            Row.find('div.bootstrap-tagsinput').html(label_tag)
                            //                            console.log('hello')
                        }
                        //                        $("#OrderTable").find("td").css("background-color", "white");
                        //                        $(Row).find("td").css("background-color", "#e2e2e2");
                        $(Row).find("span.discount").attr("data-disc", Data['Product_Discount']).html(round_number(Data['Product_Discount']) + ' %')
                        window.SelectedTR = $(Row);
                        flag = 2
                        $(".key1").removeClass("choosen");
                        $(".key1[data-flag=2]").addClass("choosen");
                    }
                    if (type == 1)
                        $("#exchange_pos").trigger("click")
                    else if (type == 2 || type == 3) //if retutn or return postponed
                        $("#retunPOS").trigger("click")
                    else if (type == 4)
                        $("#request_transfer").trigger("click")
                    else
                        $("#invoicePOS").trigger("click")
                    $("#OrderTable tbody tr:first td").removeClass("tr-white tr-return").addClass("tr-gray") //css("background-color", "#e2e2e2");
                    $('#DiscountInput').val(response['Main']['Discount']);
                    var DIS = parseFloat(response['Main']['Discount']);
                    var Max = parseFloat($("#EditDiscount").attr("data-max"));
                    DIS = DIS < 0 ? 0 : DIS;
                    if (Max > 0)
                        DIS = DIS > Max ? Max : DIS;
                    $("#TotalTable .TotalSpanInTable.discount-span-input-per").parents("tr").attr("data-discount", DIS);
                    $("#TotalTable .TotalSpanInTable > .discount").html(DIS + " %");
                    $('#DiscountInput').val(DIS)
                    var customerData = response.Person;
                    //                    UpdateTable(T);
                    $("#CurCustomerInfo").attr("CurCustomerID", 0).attr("customer-pos-id", 0).attr("data-is-pos", 0).attr('data-account-id', 0)
                    $("#CurCustomerInfo").empty();
                    $("#InvTypeMpdal input[name=customer_id],#customer_id").val('');
                    if (customerData != null) {
                        var Content = "";
                        Content += "<div class='row m-t-5'><strong>" + NameLang + ": </strong><span class='Name'>" + customerData.Name + "</span>&nbsp/&nbsp<strong>" + PhoneLang + ": </strong><span class='Phone'>" + customerData.Phone + "</span>&nbsp/&nbsp";
                        //            Content += "<div><strong>" + CompanyLang + ": </strong><span class='Company'>" + ui.item.Customer_Company + "</span></div>";
                        Content += "<strong>" + AddressLang + ": </strong><span class='Address'>" + customerData.Address + "</span>  <span id='search_customer_balance' class='bold'></span>";
                        if ((customerData.customer_is_pos == 1 && show_balance_search_road_cust) || (customerData.customer_is_pos == 0 && show_balance_search_cust)) {
                            $("#CurCustomerInfo").attr("data-account-id", customerData.customer_is_pos == 0 ? customerData.Account_ID : customerData.account_id);
                            getAccBalance('#search_customer_balance', customerData.customer_is_pos == 0 ? customerData.Account_ID : customerData.account_id, customerData.customer_is_pos == "0" ? '' : customerData.customer_pos_id);
                        }
                        Content += "</div>";
                        Content += "<div id='Customer_Account' ></div>";
                        $("#CurCustomerInfo").html(Content).attr("CurCustomerID", response.Main.Customer_ID)
                            .attr("customer-pos-id", customerData.customer_pos_id).attr("data-is-pos", customerData.customer_is_pos).attr('data-account-id', customerData.account_id)
                        //                            $("#CurCustomerInfo").html(Content).attr("data-account", customerData.Account_Code);
                        Customer_ID = response.Main.Customer_ID;
                        change_class_flag = false
                        $("#Customer_Class_ID").val(response.Main.Class_ID).select2().trigger("change")
                        $("#InvTypeMpdal input[name=customer_id],#customer_id").val(customerData.Name + " - " + customerData.Phone);
                        $("#postponed_customer_id").val(Customer_ID).attr("data-select-name", customerData.Name + " - " + customerData.Phone)
                        build_select2($("#postponed_customer_id"), "xhr/customerSearch");
                        $("#postponed_customer_id").prop("disabled", response.Person.customer_is_pos == 1 ? true : false)

                        //                            $("#InvTypeMpdal input[name=customer_id],#customer_id").attr("data-account", customerData.Account_Code);
                    }
                    $("#text_note,#text_note_delivery").val(response.Main.Invoice_Description)
                    $("#retrieve_list_modal,#FunctionsModal,#invoice_list_modal,#invoice_delivery_list_modal,#exchange_list,#postponed_list_modal,#return_list_modal").modal("hide");
                    is_edited_invoice = type == 3 || type == 4 ? 0 : 1;
                    is_return_postponed = type == 3 ? 1 : 0;
                    $('#main_pos_modal').addClass('hidden')
                    if (type == 4 && response.Main.inv_transfered == 1) {
                        alert('<?php echo CommonLanguage::getMessage('inv_transfered') ?>');
                    }
                }
                UpdateTable(T);
            }
        });
    }

    function rebuild_inv_table() {
        var inv_data = {
            IsVendor: false,
            customer_supplier_id: $("#inv_cust").val(),
            invoice_status: $("#invoice_status").val(),
            inv_is_delivered: $("#inv_is_delivered").val(),
            inv_list_nb: $("#inv_list_nb").val(),
            is_delivery: $("#inv_is_delivery").val(),
            Date_From: window.startDate ? window.startDate : start_date,
            Date_To: window.endDate ? window.endDate : today,
            due_date_from: window.startDueDate,
            due_date_to: window.endDueDate,
            pos_customer: $("#inv_pos_cust").val(),
            is_actual: is_actual,
            smart_status: $("#smart_status").val(),
            type: 1
        }
        $.ajax({
            url: "POSAjax/get_sales_invoices_total",
            data: inv_data,
            dataType: 'json',
            complete: function(v1, v2) {
                if (v2 == "success") {
                    RebuildDataTable('invoices', [0, 1, 2, 3, 4], "POSAjax/InvoiceListByLoggedUser", inv_data, "#invoiceListTable", '', {
                        "bSort": false
                    });
                    $("#invoiceListTable #total").html(AddCommas(parseFloat(v1.responseJSON['net_total'] || 0).toFixed(3)));
                    $("#invoiceListTable #inv_paid_total").html(AddCommas(parseFloat(v1.responseJSON['paid_amount'] || 0).toFixed(3)));
                    $("#invoiceListTable #inv_rem_total").html(AddCommas(parseFloat(v1.responseJSON['remaining'] || 0).toFixed(3)));
                }
            }
        })
        setTimeout(function() {
            if (multi_inv_delete_per)
                $(".multi_delete").removeClass("hidden")
            else
                $(".multi_delete").addClass("hidden")
        }, 200)
    }

    function rebuild_delivery_table() {
        var delivery_data = {
            IsVendor: false,
            delivery_user: $("#delivery_user").val(),
            customer_supplier_id: $("#delivery_cust").val(),
            invoice_status: $("#delivery_status").val(),
            inv_list_nb: $("#delivery_list_nb").val(),
            is_delivery_list: 1,
            Date_From: window.startDate ? window.startDate : start_date,
            Date_To: window.endDate ? window.endDate : today,
            pos_customer: $("#delivery_pos_cust").val(),
            is_actual: is_actual
        }
        $.ajax({
            url: "POSAjax/get_sales_invoices_total",
            data: delivery_data,
            dataType: 'json',
            complete: function(v1, v2) {
                if (v2 == "success") {
                    RebuildDataTable('Delivery Invoice', [0, 1, 2, 3, 4], "POSAjax/InvoiceListByLoggedUser", delivery_data, "#invoiceDeliveryListTable", '', {
                        "bSort": false
                    });
                    $("#invoiceDeliveryListTable #delivery_total").html(AddCommas(parseFloat(v1.responseJSON['net_total'] || 0).toFixed(3)));
                    $("#invoiceDeliveryListTable #delivery_fees_total").html(AddCommas(parseFloat(v1.responseJSON['fees_amount'] || 0).toFixed(3)));
                    $("#invoiceDeliveryListTable #delivery_paid_total").html(AddCommas(parseFloat(v1.responseJSON['paid_amount'] || 0).toFixed(3)));
                }
            }
        })
        setTimeout(function() {
            if (multi_inv_delete_per)
                $(".multi_delete").removeClass("hidden")
            else
                $(".multi_delete").addClass("hidden")
        }, 200)
    }

    function rebuild_received_delivery_table() {
        var delivery_data = {
            IsVendor: false,
            delivery_user: $("#rec_user").val(),
            customer_supplier_id: $("#rec_cust").val(),
            invoice_status: $("#rec_status").val(),
            inv_list_nb: $("#rec_list_nb").val(),
            //            is_delivery_list: 1,
            Date_From: window.rec_start_date ? window.rec_start_date : start_date,
            Date_To: window.rec_end_date ? window.rec_end_date : today,
            pos_customer: $("#rec_pos_cust").val(),
            rec_region_filter: $("#rec_region_filter").val(),
            rec_driver_filter: $("#rec_driver_filter").val(),
            received_status: $("#received_status").val(),
            is_actual: is_actual
        }
        //        $.ajax({
        //            url: "POSAjax/get_sales_invoices_total",
        //            data: delivery_data,
        //            dataType: 'json',
        //            complete: function (v1, v2) {
        //                if (v2 == "success") {
        RebuildDataTable('Delivery Invoice', [0, 1, 2, 3, 4], "POSAjax/received_delivery_ajax", delivery_data, "#received_delivery_list", '', {
            "bSort": false
        });
        //                    $("#invoiceDeliveryListTable #delivery_total").html(AddCommas(parseFloat(v1.responseJSON['net_total'] || 0).toFixed(3)));
        //                    $("#invoiceDeliveryListTable #delivery_fees_total").html(AddCommas(parseFloat(v1.responseJSON['fees_amount'] || 0).toFixed(3)));
        //                    $("#invoiceDeliveryListTable #delivery_paid_total").html(AddCommas(parseFloat(v1.responseJSON['paid_amount'] || 0).toFixed(3)));
        //                }
        //            }
        //        })

    }

    function rebuild_post_table() {
        var inv_data = {
            IsVendor: false,
            customer_supplier_id: $("#post_cust").val(),
            invoice_status: $("#post_status").val(),
            inv_is_delivered: $("#post_is_delivered").val(),
            inv_list_nb: $("#post_list_nb").val(),
            is_delivery: $("#post_is_delivery").val(),
            Date_From: window.startDate ? window.startDate : start_date,
            Date_To: window.endDate ? window.endDate : today,
            due_date_from: window.startDueDate,
            due_date_to: window.endDueDate,
            pos_customer: $("#post_pos_cust").val(),
            is_actual: is_actual,
            posponted_status: $("#posponted_status_filter").val(),
            is_committed: $("#post_is_committed").val(),
            type: 2,
            branch_id: $("#current_post_branch_id").val()
        }
        $.ajax({
            url: "POSAjax/get_sales_invoices_total",
            data: inv_data,
            dataType: 'json',
            complete: function(v1, v2) {
                if (v2 == "success") {
                    RebuildDataTable('Postponed invoices', [0, 1, 2, 3, 4], "POSAjax/PostponedListByLoggedUser", inv_data, "#postponedListTable", '', {
                        "bSort": false
                    });
                    $("#postponedListTable #total").html(AddCommas(parseFloat(v1.responseJSON['net_total'] || 0).toFixed(3)));
                    $("#postponedListTable #post_paid_total").html(AddCommas(parseFloat(v1.responseJSON['paid_amount'] || 0).toFixed(3)));
                    $("#postponedListTable #post_rem_total").html(AddCommas(parseFloat(v1.responseJSON['remaining'] || 0).toFixed(3)));
                }
            }
        })
    }

    function rebuild_exchange_table() {
        var data = {
            Date_From: window.startExDate ? window.startExDate : start_date,
            Date_To: window.endExDate ? window.endExDate : today,
            is_actual: is_actual
        }
        RebuildDataTable('exchanges', [0, 1], "POSAjax/exchange_list_ajax", data, "#exchange_list_table", '', {
            "bSort": false
        });
    }

    function getOnlineOrders(data_ids) {
        $.ajax({
            dataType: 'json',
            url: smart_diner_server_url + 'sync/get_order_data',
            data: {
                branch_id: branch_id,
                order_id: data_ids['order_id'],
                account_id: data_ids['account_id'],
                address_id: data_ids['address_id']
            },
            complete: function(data, vv) {
                if (vv == "success") {
                    var response = data.responseJSON
                    if ($.type(response) == 'object' && Object.keys(response).length == 3) {
                        postOnlineInvoice(data.responseJSON);
                    }
                }
            }
        });
    }

    function postOnlineInvoice(data) {
        $.ajax({
            url: "POSAjax/ajaxOnlineOrders",
            method: "POST",
            data: data,
            dataType: "json",
            complete: function(v1, v2) {
                if (v2 == 'success') {
                    if (v1.responseJSON[0] == 'OK') {
                        hideModalAlert('OnlineframeModal');
                        getTotalOnlinePendingOrders();
                        getTotalDelivery();
                    }
                    $('#online_loader').addClass('hidden');
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                $('#online_loader').addClass('hidden');
                alert("Status: " + textStatus);
                alert("Error: " + errorThrown);
            }
        });
    }

    function playSuccessAudio() {
        var audioElement = new Audio();
        audioElement.setAttribute('src', '<?php echo SITE_LINK; ?>Views/files/success.wav');
        $("#snackbar").addClass('show');
        audioElement.play();
    }

    function print_blank() {
        printPOSExternal('POSAjax/openDrawerReasonPrint');
        //        printPOSExternal('', '<html><body onload="window.print();">&nbsp;</body></html>');
        //        var mywindow = window.open();
        //        mywindow.document.write('<div></div>');
        //        mywindow.print();
        //        mywindow.close();
        //        return false;
    }

    function validateExpiryDates() {
        var is_expiry_empty = false;
        $("#OrderTable tbody tr").each(function(e) {
            var me = $(this);
            if ((me.attr('data-expiry-date') == null || !me.attr('data-expiry-date')) && is_active_expiry_date == 1 && me.attr('expiry-active') == 1) {
                is_expiry_empty = true;
            }
        });
        return is_expiry_empty;
    }

    function update_qty_to_positive() {
        //        $("#OrderTable tbody tr td").addClass("tr-return") 
        if ($("#OrderTable tbody tr").length > 0) {
            $("#OrderTable tbody tr").each(function() {
                var qty = parseFloat($("span.qty_span", $(this)).html());
                if (qty < 0) {
                    $("span.qty_span", $(this)).html(qty * -1)
                    $(this).find("td").removeClass("tr-return tr-gray").addClass("tr-white")
                }
            })
            SelectedTR.find("td").removeClass("tr-white tr-return").addClass("tr-gray")
            UpdateTable($("#OrderTable > tbody:last"));
        }
    }

    function checkDisableCashGenerateBtn() {
        if (is_smart_diner && disable_cash_on_edit_table && $('#invoice_auto_id').val() != 0 && destination_type != 0)
            $('#CashInvBtn,#GInvBtn,#CashWithoutPrintInvBtn').addClass('disabled')
    }

    function rebuild_ret_table() {
        var ret_data = {
            customer_id: $("#ret_cust").val(),
            ret_list_nb: $("#ret_list_nb").val(),
            Date_From: window.startretDate ? window.startretDate : start_date,
            Date_To: window.endretDate ? window.endretDate : today,
            is_actual: is_actual
        }
        $.ajax({
            url: "POSAjax/get_return_invoices_total",
            data: ret_data,
            dataType: 'json',
            complete: function(v1, v2) {
                if (v2 == "success") {
                    RebuildDataTable('returns', [0, 1, 2, 3, 4], "POSAjax/ReturnListByLoggedUser", ret_data, "#ReturnListTable", '', {
                        "bSort": false
                    });
                    $("#ReturnListTable #ret_total").html(AddCommas(parseFloat(v1.responseJSON['net_total'] || 0).toFixed(3)));
                    $("#ReturnListTable #ret_paid_total").html(AddCommas(parseFloat(v1.responseJSON['paid_amount'] || 0).toFixed(3)));
                }
            }
        })
    }

    function print_invoice(table_id) {
        $.ajax({
            url: "RestaurantAjax/print_table_invoice",
            method: "GET",
            data: {
                id: table_id
            },
            complete: function(v1, v2) {
                if (v2 == 'success') {
                    if (!sumatra_print) {
                        myurl = "Inventory/pos_view_invoice/" + v1.responseText;
                        printExternal(myurl)
                    }
                }
            }
        })
    }

    function getTotalOrders() {
        $.ajax({
            url: "POSAjax/getTotalOrders",
            complete: function(v1, v2) {
                if (v2 == "success") {
                    if (v1.responseText == 0) {
                        $("#total_orders_pending").addClass('hidden')
                    } else {
                        $("#total_orders_pending").html(v1.responseText);
                        $("#total_orders_pending").removeClass('hidden');
                    }
                    setTimeout(function() {
                        getTotalOrders()
                    }, 60000)
                }
            }
        })
    }
     function getAccBalance(current_target, customer_id, pos_customer_id) {
        
        customer_id = customer_id == undefined ? '' : customer_id;
        pos_customer_id = pos_customer_id == undefined ? '' : pos_customer_id;
        if (current_target == '#rec_acc_balance') {
            if (($("#search_supplier").val() == '' && $("#pay_pos_customers").val() == '') ||
                $("#CurrencyDropDownPOS button input").val() == '') {
                $("#rec_acc_balance").addClass("hidden")
                return;
            }
            var data = {
                account: $("#search_supplier").val(),
                currency: $("#CurrencyDropDownPOS button input").val(),
                is_actual: is_actual,
                pos_customer: $("#pay_pos_customers").val()
            };
        } else {
            var data = {
                account: customer_id,
                currency: PrimaryCurrency[0],
                is_actual: is_actual,
                pos_customer: pos_customer_id
            };
        }
        $.ajax({
            url: "ACCAjax/getAccountBalance",
            method: "GET",
            data: data,
            dataType: 'json',
            complete: function(v1, v2) {
                if (v2 == 'success') {
                     
                    $(current_target).removeClass("hidden")
                    $(current_target).text('(' + '<?php echo CommonLanguage::getMessage('Balance') ?>:' + AddCommas(parseFloat(v1.responseJSON['Balance']).toFixed(3)) + ' ' + (current_target == '#rec_acc_balance' ? ($("#CurrencyDropDownPOS ul li[value=" + $("#CurrencyDropDownPOS button input").val() + "]").attr("mysymbol")) : PrimaryCurrency[1]) + ' )');
                    
                    
                }
            }
        })
    }


    //yousif script for menu
    $(document).ready(function() {
        $(window).resize(function() {
            
            var width = $(window).width();
            //Assuming X=550   
            if (width <= 1000) {
                //  $('.RightBox ').css('width','100%');
                //  $('#RightBoxContents').removeClass('full-height');
            }
            /*else{
                $('#RightBoxContents').addClass('full-height');
                $('.m-t-8, .col-xs-3, .col-sm-3, .col-md-3, .col-lg-3, .dd-color').removeClass('col-xs-3 col-sm-3 col-md-3 col-lg-3 dd-color').addClass('col-xs-1 col-sm-1 col-md-1 col-lg-1 dd-color');
            }*/
        });
        //id="hide_elements" hide_trash show_this
        $("#show_this").show();


        var NotOpen = true;

        $(".page-sidebar").hide();

        $("#left_menu").click(function() {
            if (NotOpen) {
                NotOpen = false;
                $(".page-sidebar").show();
            } else {
                NotOpen = true;
                $(".page-sidebar").hide();
            }
        });

    });
</script>
<?php
include 'Views/POS/pos_modals.php';
include "Views/Inventory/allergy-intolerance-modal.php";
include "Views/POS/end-of-day-modal.php";
