<?php if ($IsEdit && $check_lock != '') { ?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong>Danger: </strong><?php echo $check_lock ?>
    </div>
    <?php
    return;
}
if ($IsEdit && empty($edit_data['Main']['Expense_ID'])) {
    ?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong>Danger: </strong>you can not edit this expense! 
        <br>
        This expense  is not available.
    </div>
    <?php
    die();
}
$fields_hide = smc_session()['default_setting']['expense_fields_to_hide'] != '' ? explode(",", smc_session()['default_setting']['expense_fields_to_hide']) : [];
?>
<style type="text/css">
    #PayementTable thead tr th {
        color:#555;
        border-bottom: 1px solid rgba(0,0,0,0.1);
    }
    #PayementTable tbody tr td input{
        width:100%;
        margin:0;
        border: 1px solid rgba(0,0,0,0.02);
        background-color:#f0f0f0;
    }
    #PayementTable tbody tr td {
        border:0;
        padding:3px 1px;
        position:relative;
    }
    #PayementTable tbody tr:first-child td{
        padding-top:10px;
    }
    #PayementTable .Hint{
        position: absolute;
        font-size: 10px;
        font-weight: bold;
        height: 20px;
        line-height: 20px;
        bottom: 2px;
        right: 4px;
        color: rgb(153, 153, 153);
    }
    #PayementTable .TotalTD{
        width: auto;
        display: inline-block;
        text-align: center;
        font-size: 20px;
        text-indent:10px;
        font-weight: bold;
    }
    #PayementTable .Disc{
        width:50px;
    }
    #PayementTable input.wrong{
        border: 1px solid rgba(255, 0, 0, 0.2);
        background: rgba(255, 0, 0, 0.05);
    }
    .DropDownForForms > .dropdown-menu{
        width:100%;
        height:200px;
        max-height:200px;
        overflow-y:scroll;
    }
    .DropDownForForms > .dropdown-menu{
        height:auto;
        cursor: pointer;
        overflow-y:auto;
    }
    .DropDownForForms > button{
        position:relative;
        z-index:999;
    }
    .DropDownForForms > button > input{
        position: absolute;
        left:5;
        top: 0;
        width:90%;
        cursor: pointer;
        -webkit-user-select:none;
        -moz-user-select:none;
        user-select:none;
        padding: 0;
        border: 0;
        background: transparent;
    }
    .Disabled{
        cursor:default;
        opacity:0.5;
    }
    #AdvanceValue{
        width: 102px;
        display: inline-block;
    }

    .my_tr{
        border-bottom: 1px solid rgba(0,0,0,0.07);
        padding:10px;
    }
    .wrong{
        border: 1px solid rgba(255, 0, 0, 0.2);
        background: rgba(255, 0, 0, 0.05);
    }
    .rem{
        color:#eb9220;
        cursor:pointer;
        font-weight:700;
    }
    .balance{
        color:red;
        font-weight:700;
    }
    .AddRow{

        background: #4c0870;
        padding: 10px;
        border-radius: 6px;
        margin-bottom: 10px;

    }
    .total_div{
        margin-top:0px;
    }
    .InputSpinner{
        width: 60px;
    }
    .InputSpinner > .form-control{
        border-color: rgb(221, 221, 221);
        height:36px;
        margin:0;
        padding:0;
        text-align: center;

    }
    .InputSpinner > .input-group-btn-vertical {
        position: relative;
        white-space: nowrap;
        width: 25px;
        vertical-align: middle;
        display: table-cell;
    }
    .InputSpinner > .input-group-btn-vertical > .btn {
        height:19px;
        display: block;
        float: none;
        width: 100%;
        max-width: 100%;
        padding: 8px;
        margin-left: -1px;
        position: relative;
        border-radius: 0;
    }
    .InputSpinner > .input-group-btn-vertical > .btn:first-child {
        border-top-right-radius: 4px;
    }
    .InputSpinner > .input-group-btn-vertical > .btn:last-child {
        margin-top: -2px;
        border-bottom-right-radius: 4px;
    }
    .InputSpinner > .input-group-btn-vertical i{
        position: absolute;
        top: 50%;
        left: 6px;
        margin-top:-9px;
        font-size: 18px;
    }
    .InputSpinner .input-group-btn-vertical .btn.btn-default{
        font-size: 10px;
        padding: 6px 10px;
    }
</style>
<script src="<?php echo THEME_PATH; ?>plugins/jquery-validation/js/jquery.validate.min.js"></script>
<form method="POST" action="" onsubmit="return false" id="expense_from">
    <div class="container-fluid container-fixed-lg">
        <div class="panel panel-default">
            <div class="panel-body">
                <?php echo Forms::ModalLoader('expense_isbusy') ?>
                <div id="paymentAlert"></div>
                <div class="">
                    <div class="">
                        <div class="">
                            <div class="invoice">
                                <div class="container-sm-height">
                                    <div class="row-sm-height form-group">
                                        <div class="col-md-9 col-sm-height sm-no-padding">
                                            <div>
                                                <div class="input-group  col-md-4 center-margin pull-left" >
                                                    <div class="sm-m-t-20">
                                                        <h2 class="font-montserrat all-caps hint-text"><?php print CommonLanguage::getMessage('expenditures'); ?></h2>
                                                    </div>
                                                </div>
                                                <div class="clearfix"></div>
                                            </div>

                                            <div class="  col-md-5 center-margin pull-left " >
                                                <div class="input-group  col-md-12 center-margin pull-left <?php echo!in_array(($is_cash ? '11' : '12'), $fields_hide) && (smc_session()['default_setting']['expense_account_type'] == 0 || smc_session()['default_setting']['expense_account_type'] == 2) ? '' : 'hidden' ?>" >
                                                    <label><?php print CommonLanguage::getMessage('choose_supplier'); ?><span class="red-star <?php echo empty(smc_session()['default_setting']['supplier_required_expense']) && !$is_cash ? 'hidden' : '' ?>">*</span></label><span class="fa fa-plus-circle m-l-5 openFrame" data-src="<?php echo "Inventory/ViewVendorList?is_pop=1" ?>" style="color:#4c0870;cursor:pointer"></span>
                                                    <input class="search_supplier full-width" id="search_supplier" name="search_supplier" type="hidden" value="<?= $IsEdit ? $edit_data['Main']['Supplier_ID'] : ""; ?>" data-select-name='<?= json_encode($IsEdit ? $edit_data['Person']['Name'] : ""); ?>' />

                                                </div> 
                                                <div class="input-group  col-md-12 center-margin pull-left   <?php echo (smc_session()['default_setting']['expense_account_type'] == 1 || smc_session()['default_setting']['expense_account_type'] == 2) ? '' : 'hidden' ?>" >
                                                    <label><?php print CommonLanguage::getMessage('account'); ?></label>
                                                    <input class="main_acc_id full-width" id="main_acc_id" name="main_acc_id" type="hidden" value="<?= $IsEdit ? $edit_data['Main']['main_acc_id'] : ""; ?>" data-select-name='<?= json_encode($IsEdit ? $edit_data['Main']['main_acc_name'] : ""); ?>' />

                                                </div> 
                                                <div class="input-group  col-md-12 center-margin pull-left   <?php echo (smc_session()['default_setting']['expense_account_type'] == 1 || smc_session()['default_setting']['expense_account_type'] == 2) ? '' : 'hidden' ?>" >
                                                    <label><?php print CommonLanguage::getMessage('vat_account'); ?></label>
                                                    <input class="vat_acc_id full-width" id="vat_acc_id" name="vat_acc_id" type="hidden" value="<?= $IsEdit ? $edit_data['Main']['vat_acc_id'] : ""; ?>" data-select-name='<?= json_encode($IsEdit ? $edit_data['Main']['vat_acc_name'] : ""); ?>' />

                                                </div> 
                                            </div> 
                                            <div class="col-md-3 <?php echo in_array('0', $fields_hide) ? 'hidden' : '' ?>">
                                                <label><?php echo CommonLanguage::getMessage('payment_account') ?><span class="red-star ">*</span></label>
                                                <input class="pay_method full-width" id="pay_method" name="pay_method" type="hidden" value="<?= $IsEdit ? $edit_data['Main']['pay_method_acc_id'] : smc_session()['user_accounts']['cash_account_id']; ?>" data-select-name='<?= json_encode($IsEdit ? $edit_data['Main']['pay_method'] : smc_session()['user_accounts']['c_name']); ?>' <?php echo $is_cash && !$permissions->hasPermission($is_actual ? ($is_pending ? 'can_change_pay_acc_act_pen_cash_exp' : 'can_change_pay_acc_act_cash_exp' ) : ($is_pending ? 'can_change_pay_acc_pen_cash_exp' : 'can_change_pay_acc_cash_exp' )) ? 'readonly' : '' ?>/>

                                            </div>



                                        </div>
                                        <div class="col-md-4 col-sm-height col-bottom sm-no-padding sm-p-b-20" style="vertical-align: top;">
                                            <div class="form-group form-group-default input-group">
                                                <label class="fade"><?php print CommonLanguage::getMessage('Date'); ?></label>
                                                <input id="ExpenseDate" name="ExpenseDate" class="form-control" value="<?php echo $IsEdit ? $edit_data['Main']['Expense_Date'] : $today; ?>" aria-required="true" aria-invalid="false">
                                                <span class="input-group-addon bg-complete"><i class="fa fa-calendar"></i></span>
                                            </div>
                                            <div class="form-group form-group-default input-group <?php echo in_array('1', $fields_hide) || $is_cash ? 'hidden' : '' ?>">
                                                <label class="fade"><?php print CommonLanguage::getMessage('due_date'); ?></label>
                                                <input id="ExpenseDueDate" name="ExpenseDueDate" class="form-control" value="<?php echo $IsEdit ? $edit_data['Main']['Expense_DueDate'] : $today; ?>" aria-required="true" aria-invalid="false">
                                                <span class="input-group-addon bg-complete"><i class="fa fa-calendar"></i></span>
                                            </div>
                                            <div id="CurrencyIDContainer" class=" m-t-10" >
                                                <div class="form-group form-material floating ">
                                                    <div class="input-group-btn DropDownForForms Closable  " id="CurrencyDropDown">
                                                        <button type="button" class="btn btn-complete btn-block dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                                                            <span><?php echo $IsEdit ? ($edit_data['Main']['Currency_Name'] . ' - ' . $edit_data['Main']['Currency_Symbol']) : $currency_symbol ?></span>
                                                            <input type="hidden" name="Currency_ID" value="<?php echo $IsEdit ? $edit_data['Main']['Currency_ID'] : $DefaultCurrencyID ?>" class="form-control ignore" onkeyup="return false" onkeydown="return false"/>
                                                        </button>
                                                        <ul class="dropdown-menu">
                                                            <?php echo $CurList ?>
                                                            <li class="divider"></li>
                                                            <li><a class="LoadMore">More..</a></li>
                                                        </ul>
                                                    </div>
                                                </div>
                                            </div>
                                            <div style="display:flex;">
                                                <div  class="form-group supInv <?php echo in_array('2', $fields_hide) ? 'hidden' : '' ?>" id="SupplierInv" style="width:48%;margin-right:2%">
                                                    <label> <?php print CommonLanguage::getMessage('supplier_invoice'); ?>#</label>
                                                    <input id="Supplier_Invoice" name="Supplier_Invoice" class="form-control" value="<?php echo $IsEdit ? $edit_data['Main']['supplier_inv_id'] : '' ?>" />

                                                </div>
                                                <div   class="form-group <?php echo smc_session()['default_setting']['activate_accounting_job'] == 1 && !in_array('3', $fields_hide) ? '' : 'hidden' ?>" style="width: 50%;" >
                                                    <label><?php echo CommonLanguage::getMessage('job') ?></label>
                                                    <input type="hidden" class="full-width" id="job_id" value="<?php echo $IsEdit ? $edit_data['Main']['job_id'] : '' ?>" data-select-name="<?= $IsEdit ? $edit_data['Main']['job_name'] : '' ?>"/>
                                                </div>
                                            </div>
                                            <div style="display:flex;">
                                                <div  style="width:48%;margin-right:2%">   
                                                    <div class=" form-group <?php echo in_array('5', $fields_hide) ? 'hidden' : '' ?>" >   
                                                        <label><?php print CommonLanguage::getMessage('exchange_rate'); ?><span class="red-star">(<?php echo smc_session()['local_currency_symbol']; ?>)</span></label>
                                                        <input type="number" step="any" min="0" id="current_rate" name="current_rate" class="form-control full-width current_rate" <?php echo ($IsEdit && ($edit_data['Main']['Currency_ID'] == smc_session()['local_currency']) ? 'disabled' : ($DefaultCurrencyID == smc_session()['local_currency']) ? 'disabled' : '') ?>  value="<?php echo $IsEdit ? $edit_data['Main']['current_rate'] : '' ?>" />


                                                    </div>
                                                </div>
                                                <div <?php echo smc_session()['default_setting']['activate_second_currency'] == 1 ? '':'hidden'; ?> style="width: 50%;" >
                                                    <div  class="form-group  <?php echo in_array('6', $fields_hide) ? 'hidden' : '' ?>" >
                                                        <label><?php print CommonLanguage::getMessage('exchange_rate'); ?><span class="red-star">(<?php echo smc_session()['second_currency']['symbol'] ?>)</span></label>
                                                        <input type="number" step="any" min="0" id="second_currency_rate" name="second_currency_rate" class="form-control full-width second_currency_rate" <?php echo ($IsEdit && ($edit_data['Main']['Currency_ID'] == smc_session()['default_setting']['second_currency']) ? 'disabled' : ($DefaultCurrencyID == smc_session()['default_setting']['second_currency']) ? 'disabled' : '') ?>  value="<?php echo $IsEdit ? $edit_data['Main']['second_currency_rate'] : '' ?>" />
                                                    </div>
                                                </div>
                                            </div>
                                            <div   class="form-group " style="display: flex;">
                                                <div  style="width:48%;margin-right:2%" class=" <?php echo $permissions->hasPermission('Branches') ? '':'hidden'; ?>">   
                                                    <div class=" form-group" >   
                                                        <label><?php print CommonLanguage::getMessage('branch'); ?></label>

                                                        <input class=" full-width" id="branch_id" name="branch_id" type="hidden"  value="<?= $IsEdit ? $edit_data['Main']['branch_id'] : (empty(smc_session()['user_accounts']['branch_id']) ? smc_session()['default_branch_id'] : smc_session()['user_accounts']['branch_id']) ?>" data-select-name='<?= json_encode($IsEdit ? $edit_data['Main']['branch_name'] : (empty(smc_session()['user_accounts']['branch_id']) ? smc_session()['default_branch_name'] : smc_session()['user_accounts']['branch_name'])) ?>'/>


                                                    </div>
                                                </div>
                                                <div class="<?php echo smc_session()['default_setting']['activate_project'] == 1 && !in_array('4', $fields_hide) ? '' : 'hidden' ?>"  style="width: 50%;" >
                                                    <label><?php echo CommonLanguage::getMessage('project') ?></label>
                                                    <input type="hidden" class="full-width" id="project_id" value="<?php echo ($IsEdit && !empty($edit_data['Main']['project_id'])) ? $edit_data['Main']['project_id'] : '' ?>" data-select-name="<?= $IsEdit ? $edit_data['Main']['project_name'] : '' ?>"/>
                                                </div>

                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div>
                                    <div class=""></div>
                                </div>
                                <div class="table-responsive exp_div">
                                    <?php
                                    if ($IsEdit) {
                                        foreach ($edit_data['details'] as $exp) {
                                            ?>
                                            <div class="col-md-12 AddRow m-b-10 form-group"  >
                                                <div class="col-md-11">
                                                    <div class="row">
                                                        <div class="col-xs-3">
                                                            <label style="color:white;"><?php echo CommonLanguage::getMessage('description') ?></label>
                                                            <input type="text" class="form-control exp_desc  " value="<?php echo $exp['description'] ?>">
                                                        </div>
                                                        <div class="col-xs-2  ">
                                                            <label style="color:white;"><?php echo CommonLanguage::getMessage('account') ?><span class="red-star">*</span><span class="fa fa-plus-circle m-l-5 openFrame" data-src="ACC/viewlibrary/1?is_pop=1" style="color:#4c0870;cursor:pointer"></span></label>
                                                            <input class=" full-width" name="exp_acc" type="hidden"  value="<?php echo $exp['Account_ID'] ?>" data-select-name='<?= json_encode($exp['Account_Name'] . ' - ' . $exp['Account_Code']) ?>'/>

                                                        </div>

                                                        <div class="col-xs-1 <?php echo in_array('7', $fields_hide) ? 'hidden' : '' ?>">
                                                            <label style="color:white;"><?php echo CommonLanguage::getMessage('qty') ?><span class="red-star">*</span></label>
                                                            <input type="text" class="form-control exp_qty digits " value="<?php echo $exp['quantity'] ?>" >
                                                        </div>
                                                        <div class="col-xs-2">
                                                            <label style="color:white;"><?php echo CommonLanguage::getMessage('unit_cost') ?><span class="red-star">*</span></label>
                                                            <input type="text" class="form-control unit_cost  " value="<?php echo $exp['unit_price'] ?>">
                                                        </div>
                                                        <div class="col-xs-1 <?php echo in_array('8', $fields_hide) ? 'hidden' : '' ?>">
                                                            <label style="color:white;" class="auto-vat" style="cursor: pointer;font-weight:700;"><span class="fa fa-pencil"></span>&nbsp;<?php echo CommonLanguage::getMessage('vat_percent') ?></label>
                                                            <input type="text" class="form-control vat_percent  " value="<?php echo $exp['vat_percent'] ?>">
                                                        </div>
                                                        <div class="col-xs-1 <?php echo in_array('9', $fields_hide) ? 'hidden' : '' ?>">
                                                            <label style="color:white;"><?php echo CommonLanguage::getMessage('vat') ?></label>
                                                            <input type="text" class="form-control vat_amount  " value="<?php echo $exp['vat_amount'] ?>">
                                                        </div>
                                                        <div class="col-xs-1 <?php echo in_array('10', $fields_hide) || $is_cash ? 'hidden' : '' ?>">
                                                            <label style="color:white;"><?php echo CommonLanguage::getMessage('p_amount') ?><span class="red-star <?php echo empty(smc_session()['default_setting']['supplier_required_expense']) ? '' : 'hidden' ?>">*</span></label>
                                                            <input type="text" class="form-control paid_amount  " value="<?php echo $exp['paid_amount'] ?>">
                                                        </div>
                                                        <div class="col-xs-1">
                                                            <label style="color:white;"><?php echo CommonLanguage::getMessage('total') ?></label>
                                                            <h5 style="color:white;"  class="total_div"><strong><span class="tr-total">0</span>&nbsp;<span class="CurrencyIndicator"></span></strong></h5>
                                                        </div>
                                                    </div>
                                                    <div class="row <?php echo!empty($exp['Depreciation_Rate_Percent']) ? '' : 'hidden' ?> dep_div">
                                                        <div class="col-xs-2 ">
                                                            <label><?php // echo CommonLanguage::getMessage('depreciation')                                                                  ?></label>
                                                            <h5><strong><?php echo CommonLanguage::getMessage('depreciation') . ': ' ?></strong></h5>
                                                        </div>

                                                        <div class="col-xs-2">
                                                            <label><?php echo CommonLanguage::getMessage('depreciation_rate') ?></label>
                                                            <input type="text" class="form-control dep_rate  " value="<?php echo $exp['Depreciation_Rate_Percent'] ?>">
                                                        </div>
                                                        <div class="col-xs-3">
                                                            <label style="color:white;"><?php echo CommonLanguage::getMessage('description') ?></label>
                                                            <input type="text" class="form-control dep_desc  " value="<?php echo $exp['Depreciation_Rate_Description'] ?>">
                                                        </div>
                                                        <div class="col-xs-3">
                                                            <label><?php echo CommonLanguage::getMessage('depreciation_period') ?></label>
                                                            <select required  name="Dep_Period" class="full-width Dep_Period" data-init-plugin="select2">
                                                                <?php foreach ($all_periods as $periods): ?>
                                                                    <option value="<?php echo $periods['Period_ID']; ?>" <?php echo ($periods['Period_ID'] == $exp['Depreciation_Period_ID']) ? 'selected' : '' ?>><?php echo $periods['Period_Name']; ?></option>
                                                                <?php endforeach; ?>
                                                            </select>
                                                        </div>
                                                    </div>

                                                </div>

                                                <div class="col-md-1 AddButtons">

                                                    <span class="fa fa-plus-circle" style="color:#ed9421;margin-top:15px;margin-right:25px"></span>
                                                    <span class="fa fa-minus-circle" style="color:#ed9421;margin-top:15px;"></span>
                                                </div>
                                            </div>
                                            <?php
                                        }
                                    }else {
                                        ?>
                                        <div class="col-md-12 AddRow m-b-10 form-group"  >
                                            <div class="col-md-11">
                                                <div class="row">
                                                    <div class="col-xs-3">
                                                        <label style="color:white;"><?php echo CommonLanguage::getMessage('description') ?></label>
                                                        <input type="text" class="form-control exp_desc  " >
                                                    </div>
                                                    <div class="col-xs-2  test">
                                                        <label style="color:white;"><?php echo CommonLanguage::getMessage('account') ?><span class="red-star">*</span><span class="fa fa-plus-circle m-l-5 openFrame" data-src="ACC/viewlibrary/1?is_pop=1" style="color:#4c0870;cursor:pointer"></span></label>
                                                        <input class=" full-width" name="exp_acc" type="hidden"  />

                                                    </div>

                                                    <div class="col-xs-1 <?php echo in_array('7', $fields_hide) ? 'hidden' : '' ?>">
                                                        <label style="color:white;"><?php echo CommonLanguage::getMessage('qty') ?><span class="red-star">*</span></label>
                                                        <input type="text" class="form-control exp_qty digits " value=" <?php echo in_array('7', $fields_hide) ? '1' : '' ?>">
                                                    </div>
                                                    <div class="col-xs-2">
                                                        <label style="color:white;"><?php echo CommonLanguage::getMessage('unit_cost') ?><span class="red-star">*</span></label>
                                                        <input type="text" class="form-control unit_cost  " >
                                                    </div>
                                                    <div class="col-xs-1 <?php echo in_array('8', $fields_hide) ? 'hidden' : '' ?>">
                                                        <label style="color:white;" class="auto-vat" style="cursor: pointer;font-weight:700;"><span class="fa fa-pencil"></span>&nbsp;<?php echo CommonLanguage::getMessage('vat_percent') ?></label>
                                                        <input type="text" class="form-control vat_percent  " >
                                                    </div>
                                                    <div class="col-xs-1 <?php echo in_array('9', $fields_hide) ? 'hidden' : '' ?>">
                                                        <label style="color:white;"><?php echo CommonLanguage::getMessage('vat') ?></label>
                                                        <input type="text" class="form-control vat_amount  " >
                                                    </div>
                                                    <div class="col-xs-1 <?php echo in_array('10', $fields_hide) || $is_cash ? 'hidden' : '' ?>">
                                                        <label style="color:white;"><?php echo CommonLanguage::getMessage('p_amount') ?><span class="red-star <?php echo empty(smc_session()['default_setting']['supplier_required_expense']) ? '' : 'hidden' ?>">*</span></label>
                                                        <input type="text" class="form-control paid_amount  " >
                                                    </div>
                                                    <div class="col-xs-1">
                                                        <label style="color:white;"><?php echo CommonLanguage::getMessage('total') ?></label>
                                                        <h5 style="color:white;" class="total_div"><strong><span class="tr-total">0</span>&nbsp;<span style="color:white;" class="CurrencyIndicator"></span></strong></h5>
                                                    </div>
                                                </div>
                                                <div class="row hidden dep_div xx">
                                                    <div class="col-xs-2 ">
                                                        <label><?php // echo CommonLanguage::getMessage('depreciation')                                                                  ?></label>
                                                        <h5><strong><?php echo CommonLanguage::getMessage('depreciation') . ': ' ?></strong></h5>
                                                    </div>

                                                    <div class="col-xs-2">
                                                        <label><?php echo CommonLanguage::getMessage('depreciation_rate') ?></label>
                                                        <input type="text" class="form-control dep_rate  " >
                                                    </div>
                                                    <div class="col-xs-3">
                                                        <label style="color:white;"><?php echo CommonLanguage::getMessage('description') ?></label>
                                                        <input type="text" class="form-control dep_desc  " >
                                                    </div>
                                                    <div class="col-xs-3">
                                                        <label><?php echo CommonLanguage::getMessage('depreciation_period') ?></label>
                                                        <select required  name="Dep_Period" class="full-width Dep_Period" data-init-plugin="select2">
                                                            <?php foreach ($all_periods as $periods): ?>
                                                                <option value="<?php echo $periods['Period_ID']; ?>"><?php echo $periods['Period_Name']; ?></option>
                                                            <?php endforeach; ?>
                                                        </select>
                                                    </div>
                                                </div>

                                            </div>

                                            <div class="col-md-1 AddButtons">

                                                <span style="color:white;" class="fa fa-plus-circle" style="color:#ed9421;margin-top:15px;margin-right:25px"></span>
                                                <span style="color:white;" class="fa fa-minus-circle" style="color:#ed9421;margin-top:15px;"></span>
                                            </div>
                                        </div>
                                    <?php } ?>

                                </div>
                                <br>
                                <div class="container-sm-height" >
                                    <div class="row  b-a b-grey"><div class="col-md-6"></div>

                                        <!--                                        <div class="col-sm-6    clearfix" style="border-left: 1px solid #eee;border-right: 1px solid #eee;padding-right:0">

<div class="col-sm-12  " style="padding-right:0">
<h5 class="font-montserrat all-caps small no-margin hint-text bold"><?php print CommonLanguage::getMessage('payment'); ?><span class="fa fa-plus-circle m-l-5 openFrame" data-src="ACC/viewlibrary/1?is_pop=1" style="color:#8a7dbe;cursor:pointer"></span></h5>
<div id="InvoicePaymentSetup" class="no-print">
<div class="Body">
<div class="">
<ul class="nav nav-tabs">
<li class="active"><a data-toggle="tab" href="#SetPaidFormTab_1"><i class="fa fa-money"></i>&nbsp;&nbsp;<?php print CommonLanguage::getMessage('cash'); ?></a></li>
<li><a data-toggle="tab" href="#SetPaidFormTab_2"><i class="fa fa-file-text-o"></i>&nbsp;&nbsp;<?php print CommonLanguage::getMessage('check'); ?></a></li>
<li><a data-toggle="tab" href="#SetPaidFormTab_3"><i class="fa fa-cc-visa"></i>&nbsp;&nbsp;<?php print CommonLanguage::getMessage('credit_card'); ?></a></li>
</ul>
<div class="tab-content" style="padding:0;overflow:visible">
<div id="SetPaidFormTab_1" class="tab-pane fade in active">
<table class="table" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td style="width: 65%;"><span class="SpanInTableInPayment"><?php print CommonLanguage::getMessage('amount'); ?></span></td>
<td>
<div class="input-group InputSpinner" style="width:120px">
<input type="text" class="form-control" value="<?php echo ($IsEdit && array_key_exists('Cash', $edit_data['Payment'])) ? $edit_data['Payment']['Cash']['Transaction_Amount'] : '0' ?>" onblur="InputMustBeAtleastN(this, 0);" />
<div class="input-group-btn-vertical">
<button class="btn btn-default more" type='button'><i class="fa fa-caret-up"></i></button>
<button class="btn btn-default" type='button'><i class="fa fa-caret-down"></i></button>
</div>
</div>
</td>
</tr>
<tr>
<td><span class="SpanInTableInPayment"><?php print CommonLanguage::getMessage('Type'); ?></span></td>
<td style="text-align:center">
<input class="cash_account full-width" id="cash_account" name="cash_account" type="hidden"  value="<?php echo ($IsEdit && array_key_exists('Cash', $edit_data['Payment'])) ? $edit_data['Payment']['Cash']['Account_ID'] : smc_session()['user_accounts']['cash_account_id'] ?>" data-select-name='<?php echo ($IsEdit && array_key_exists('Cash', $edit_data['Payment'])) ? $edit_data['Payment']['Cash']['P_Name'] : smc_session()['user_accounts']['c_name'] ?>' />
</td>
</tr>
</tbody>
</table>
</div>
<div id="SetPaidFormTab_2" class="tab-pane fade in">
<table class="table" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td style="width: 65%;"><span class="SpanInTableInPayment"><?php print CommonLanguage::getMessage('amount'); ?></span></td>
<td>
<div class="input-group InputSpinner" style="width:120px">
<input type="text" class="form-control" value="<?php echo ($IsEdit && array_key_exists('Cheque', $edit_data['Payment'])) ? $edit_data['Payment']['Cheque']['Transaction_Amount'] : "0" ?>" onblur="InputMustBeAtleastN(this, 0);" />
<div class="input-group-btn-vertical">
<button class="btn btn-default more" type='button'><i class="fa fa-caret-up"></i></button>
<button class="btn btn-default" type='button'><i class="fa fa-caret-down"></i></button>
</div>
</div>
</td>
</tr>
<tr>
<td><span class="SpanInTableInPayment"><?php print CommonLanguage::getMessage('Type'); ?></span></td>
<td style="text-align:center">
<div class="input-group-btn DropDownForForms Closable">
<input class="check_account full-width" id="check_account" name="check_account" type="hidden" value="<?php echo ($IsEdit && array_key_exists('Cheque', $edit_data['Payment'])) ? $edit_data['Payment']['Cheque']['Account_ID'] : smc_session()['user_accounts']['cheque_account_id'] ?>" data-select-name='<?php echo ($IsEdit && array_key_exists('Cheque', $edit_data['Payment'])) ? $edit_data['Payment']['Cheque']['P_Name'] : "" ?>' />

<button type="button" class="btn btn-default btn-block dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
<span><?php echo CommonLanguage::getMessage('select'); ?></span>
<input type="hidden" value="0" class="form-control" onkeyup="return false" onkeydown="return false"/>
</button>
<ul class="dropdown-menu">
                                        <?php for ($x = 0; $x < count($Checks); $x++) { ?>
                                                                                                <li value="<?php echo $Checks[$x]["Account_Code"]; ?>"><a><?php echo $Checks[$x]["Payment_Type_Name"]; ?></a></li>
                                        <?php } ?>
</ul>
</div>
</td>
</tr>
<tr>
<td><span class="SpanInTableInPayment"> <?php print CommonLanguage::getMessage('check'); ?>#</span></td>
<td style="text-align:center"><input type="text" class="form-control CheckNumValue" /></td>
</tr>
</tbody>
</table>
</div>
<div id="SetPaidFormTab_3" class="tab-pane fade in">
<table class="table" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td style="width: 65%;"><span class="SpanInTableInPayment"><?php print CommonLanguage::getMessage('amount'); ?></span></td>
<td>
<div class="input-group InputSpinner" style="width:120px">
<input type="text" class="form-control" value="<?php echo ($IsEdit && array_key_exists('Credit_Card', $edit_data['Payment'])) ? $edit_data['Payment']['Credit_Card']['Transaction_Amount'] : "" ?>" onblur="InputMustBeAtleastN(this, 0);" />
<div class="input-group-btn-vertical">
<button class="btn btn-default more" type='button'><i class="fa fa-caret-up"></i></button>
<button class="btn btn-default" type='button'><i class="fa fa-caret-down"></i></button>
</div>
</div>
</td>
</tr>
<tr>
<td><span class="SpanInTableInPayment"><?php print CommonLanguage::getMessage('Type'); ?></span></td>
<td style="text-align:center">
<div class="input-group-btn DropDownForForms Closable">
<input class="credit_account full-width" id="credit_account" name="credit_account" type="hidden"  value="<?php echo ($IsEdit && array_key_exists('Credit_Card', $edit_data['Payment'])) ? $edit_data['Payment']['Credit_Card']['Account_ID'] : "" ?>" data-select-name='<?php echo ($IsEdit && array_key_exists('Credit_Card', $edit_data['Payment'])) ? $edit_data['Payment']['Credit_Card']['P_Name'] : "" ?>' />

<button type="button" class="btn btn-default btn-block dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
<span><?php echo CommonLanguage::getMessage('select'); ?></span>
<input type="hidden" value="0" class="form-control" onkeyup="return false" onkeydown="return false"/>
</button>
<ul class="dropdown-menu">
                                        <?php for ($x = 0; $x < count($CreditCards); $x++) { ?>
                                                                                                <li value="<?php echo $CreditCards[$x]["Account_Code"]; ?>"><a><?php echo $CreditCards[$x]["Payment_Type_Name"]; ?></a></li>
                                        <?php } ?>
</ul>
</div>
</td>
</tr>
<tr>
<td><span class="SpanInTableInPayment"><?php print CommonLanguage::getMessage('approval_code'); ?></span></td>
<td style="text-align:center"><input type="text" class="form-control CardApproval" /></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>-->
                                        <div class="col-sm-3  " style="padding-right:0">
                                            <div class="row">
                                                <textarea id="invoice_note" name="invoice_note" class="form-control NoteTextArea" placeholder="<?php print CommonLanguage::getMessage('enter_note'); ?>..." aria-invalid="false"><?php echo $IsEdit ? $edit_data['Main']['Expense_Note'] : '' ?></textarea>
                                            </div>
                                            <div class="row">
                                                <h5 class="font-montserrat all-caps small no-margin hint-text bold" ><?php print CommonLanguage::getMessage('vat_ten'); ?><span class="form-control ignore" id="InvoiceVAT"></span> </h5>

                                            </div>
                                        </div>
                                        <div class="col-sm-3 text-right bg-menu col-sm-height padding-15" style="text-align:left !important">
                                            <div style="text-align: left;display: inline-block;">
                                                <h5 class="font-montserrat all-caps small no-margin hint-text text-white bold"><?php print CommonLanguage::getMessage('total'); ?></h5>
                                                <h1 class="no-margin text-white Total"><span class="CurrencyIndicator"></span>&nbsp;<span id="ExpenseTotalAmount">0</span></h1>
                                                <h5 class="font-montserrat all-caps small no-margin hint-text text-white bold"><?php print CommonLanguage::getMessage('taxable_amount'); ?></h5>
                                                <h1 class="no-margin text-white Total"><span class="CurrencyIndicator"></span>&nbsp;<span id="taxable_amount">0</span></h1>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="container-sm-height" >
                                    <button class=" btn btn-complete btn-cons m-b-10 pull-right " name="PaymentSubmitButton" id="PaymentSubmitButton" style="padding-top: 10px;top: 20px;min-width:253px;" type="button"><i class="pg-form"></i> <span class="bold"><?php print CommonLanguage::getMessage('Save'); ?></span></button>
                                    <button class=" btn btn-danger btn-cons m-b-10 pull-right disabled <?php echo $permissions->hasPermission($is_actual ? ($is_pending ? ($is_cash ? 'print_act_pen_cash_expense' : 'print_act_pen_expense') : ($is_cash ? 'print_act_cash_expense' : 'print_act_expense')) : ($is_pending ? ($is_cash ? 'print_pen_cash_expense' : 'print_pen_expense') : ($is_cash ? 'print_cash_expense' : 'print_expense'))) ? '' : 'hidden' ?>" id="PrintBtn" style="padding-top: 10px;top: 20px;min-width:253px;" type="button"><i class="fa fa-print"></i> <span class="bold"><?php print CommonLanguage::getMessage('print'); ?></span></button>

                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>


<script>
    var Required_Fields = <?php echo json_encode(CommonLanguage::getMessage('Required_Fields')); ?>,
            Failed_Submit = <?php echo json_encode(CommonLanguage::getMessage('Failed_Submit')); ?>,
            change_amounts = <?php echo json_encode(CommonLanguage::getMessage('change_amounts')); ?>,
            expense_view_all_accounts = <?php echo json_encode(smc_session()['default_setting']['expense_view_all_accounts']); ?>,
            //            check_pay_amounts = <?php // echo json_encode(CommonLanguage::getMessage('check_pay_amounts'));                           ?>,
            pay_method_alert = <?php echo json_encode(CommonLanguage::getMessage('pay_method_alert')); ?>,
            fa_parent_id = <?php echo json_encode(smc_session()['account_setting']['fixed_asset_parent_acc_id']); ?>,
            Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')); ?>;
    var CurrencySymbol = '',
            local_currency = <?php echo json_encode(smc_session()['local_currency']); ?>,
            second_currency = <?php echo json_encode(smc_session()['default_setting']['second_currency']); ?>,
            supplier_required_expense = <?php echo json_encode(smc_session()['default_setting']['supplier_required_expense']); ?>,
            supp_show =<?php echo in_array(($is_cash ? '11' : '12'), $fields_hide) ? 0 : 1 ?>,
            vat_percent = <?php echo json_encode(smc_session()['vat_percent']); ?>,
            IsActual = <?php echo $is_actual ? "true" : "false" ?>,
            IsEdit = <?php echo $IsEdit ? "true" : "false" ?>,
            is_pending = <?php echo json_encode($is_pending); ?>,
            is_cash = <?php echo json_encode($is_cash); ?>,
            edit_id = <?php echo $id; ?>,
            expense_account_type = <?php echo json_encode(smc_session()['default_setting']['expense_account_type']); ?>,
            Paytotal = 0,
            cash_supplier_arr = <?php echo json_encode($cash_supplier); ?>,
            unique_id = <?php echo json_encode(!$IsEdit ? $unique_id : '') ?>;
    $(function () {
        build_select2($(".search_supplier"), ("xhr/supplierSearch?" + (IsEdit ? ("is_edited=" + $(".search_supplier").val()) : "Status_ID=1")))
        build_select2($("input[name=exp_acc]"), "xhr/accIDSearch?type=" + (expense_view_all_accounts == 1 ? 'Payment' : 'Expense'))
        $(".AddRow input[name=exp_acc]").each(function () {
            build_select2($(this), "xhr/accIDSearch?type=" + (expense_view_all_accounts == 1 ? 'Payment' : 'Expense') + "&" + ($(this).val() ? "is_edited=" + $(this).val() : "Status_ID=1"))
        })
        build_select2($("#job_id"), "ACCAjax/JobSearch")
        build_select2($("#project_id"), "ACCAjax/projectSearch")

        build_select2($("#pay_method"), ("xhr/accIDSearch?type=pay"))
        build_select2($("#main_acc_id,#vat_acc_id"), ("xhr/accIDSearch?type=Payment"))

        //                build_select2($("#job_id"), "xhr/CommonSearch?col_id=job_id&col_name=job_name&table=tbl_accounting_jobs")

        //        build_select2($("#cash_account"), ("xhr/accIDSearch?type=cash"))
        //        build_select2($("#check_account"), ("xhr/accIDSearch?type=check"))
        //        build_select2($("#credit_account"), ("xhr/accIDSearch?type=credit_card"))

        //        build_select2($("#accountId"), ("xhr/accIDSearch?type=Payment"))
        build_select2($("#branch_id"), "xhr/CommonSearch?col_id=branch_id&col_name=branch_name&table=tbl_organization_branches")


        $("input.search_supplier").on("change", function () {

            $("#main_acc_id,#vat_acc_id").val('').attr("data-select-name", '')
            $("#main_acc_id,#vat_acc_id").prop("disabled", $(this).val() != '' ? true : false)
            build_select2($("#main_acc_id,#vat_acc_id"), ("xhr/accIDSearch?type=Payment"))
        })
        $("#main_acc_id,#vat_acc_id").on("change", function () {
            if ($("#main_acc_id").val() != '' || $("#vat_acc_id").val() != '') {
                $("input.search_supplier").val('0').attr("data-select-name", cash_supplier_arr['Account_Name'])
                $("input.search_supplier").prop("disabled", true)
            } else {
                $("input.search_supplier").val('').attr("data-select-name", '')
                $("input.search_supplier").prop("disabled", false)
            }
            build_select2($(".search_supplier"), ("xhr/supplierSearch?" + (IsEdit ? ("is_edited=" + $(".search_supplier").val()) : "Status_ID=1")))

        })
        $(".CurrencyIndicator").html($("#CurrencyDropDown ul li[value=" + $("#CurrencyDropDown button input").val() + "]").attr("mysymbol"))
        $("#PrintBtn").on("click", function () {
            var myurl = "ACC/view_expense/" + edit_id;
            printExternal(myurl)

        })
        $(".exp_div").on("change", "input[name=exp_acc]", function () {

            var row = $(this).parents(".AddRow").find(".dep_div");
            if (fa_parent_id == $(this).val()) {
                row.removeClass("hidden")
                return false;
            }
            $.ajax({
                url: "ACCAjax/check_if_fa_child",
                method: "GET",
                dataType: 'json',
                data: {id: $(this).val()},
                complete: function (v1, v2) {
                    if (v2 == 'success') {
                        flag = v1.responseJSON;
                        if (flag == 1) {
                            row.removeClass("hidden")
                        } else {
                            row.addClass("hidden")
                            row.find(".dep_rate,.dep_desc").val("")
                            row.find("select.Dep_Period").val("").select2()
                        }

                    }
                }
            })
        })

        $(".exp_div").on("click", ".auto-vat", function (e) {
            $(this).parents(".AddRow").find('.vat_percent').val(vat_percent).trigger("keyup")
            //            $(this).trigger("keyup")
        })
        $(".exp_div").on("click", ".AddButtons > .fa-plus-circle", function (e) {
            $(".AddButtons > .fa-minus-circle").css("display", "")
            var Parent = $(this).parents(".AddRow"), NewItem = Parent.clone().insertAfter(Parent);
            $(".select2-container", NewItem).remove()
            //            $(".select2-container", NewItem).remove()

            NewItem.find("input").val('');
            NewItem.find(".tr-total").text("0").attr("tr-total", 0)
            NewItem.find("input[name=exp_acc]").val('')
            NewItem.find("input[name=exp_acc]").attr('data-select-name', '')
            build_select2($("input[name=exp_acc]", NewItem), "xhr/accIDSearch?type=" + (expense_view_all_accounts == 1 ? 'Payment' : 'Expense') + "&Status_ID=1")
            NewItem.find(".dep_div").addClass('hidden')
            NewItem.find("select.Dep_Period").val("").select2()
            NewItem.find(".select2-container").show().select2()
        })
        $(".exp_div").on("click", ".AddButtons > .fa-minus-circle", function (e) {
            $(this).closest(".AddRow").empty().remove();
            $(".exp_div").each(function () {
                $(".AddButtons > .fa-minus-circle", $(this).parent()).css({"display": $(".AddButtons", $(this).parent()).length <= 1 ? "none" : "inline-block"})
            });
            updateTable();
        });
        $("#add_payment").on("show.bs.modal", function () {
            $("#PaymentValidationAlert").remove();
            $("#ExpenseTotalAmount").html("0");
            //            $("#PaymentTable input").val("")
        });
        $("#ExpenseDate,#ExpenseDueDate").datepicker({autoclose: true})

        $("#PaymentSubmitButton").on("click", function () {
            validate = true;
            var validate_fields = false;
            pay_validate = false;
            if (expense_account_type == 0 && $("#main_acc_id").val() == '' && $("#search_supplier").val() == '')
                validate = false;
            if (expense_account_type == 1 && $("#main_acc_id").val() == '')
                validate = false;
            if (expense_account_type == 1 && $("#vat_acc_id").val() == '' && $("#InvoiceVAT").attr("total-vat") != '0')
                validate = false;
            if (expense_account_type == 2 && ((supplier_required_expense == 1 && $("#search_supplier").val() == '' && !is_cash && supp_show == 1) || ((supplier_required_expense == 0 || is_cash && supp_show == 1) && $("#pay_method").val() == '')))
                validate = false;


            var Data = {
                Expense_Date: $("#ExpenseDate").val(),
                main_acc_id: $("#main_acc_id").val(),
                vat_acc_id: $("#vat_acc_id").val(),
                Expense_DueDate: $("#ExpenseDueDate").val(),
                Currency_ID: $("#expense_from #CurrencyDropDown  input").val(),
                Supplier_ID: $("#search_supplier").val(),
                total_expense: $("#ExpenseTotalAmount").attr('exp_total'),
                expense_no_vat: $("#ExpenseTotalAmount").attr('exp_no_vat'),
                Expense_VAT: $("#InvoiceVAT").attr("total-vat"),
                branch_id: $("#branch_id").val(),
                is_actual: IsActual ? 1 : 0,
                Currency_Rate: $("#current_rate").val(),
                second_currency_rate: $("#second_currency_rate").val(),
                Supplier_Invoice: $("#Supplier_Invoice").val(),
                Expense_Note: $("#invoice_note").val(),
                job_id: $("#job_id").val(),
                project_id: $("#project_id").val(),
                pay_method_acc_id: $("#pay_method").val(),
                total_paid: 0,
                unique_id: unique_id,
                is_pending: is_pending,
                is_cash: is_cash,
                expense: []
            };
            var total_paid = 0, is_negative_value = false;
            $(".AddRow").each(function () {
                var me = $(this);
                //                console.log(me.find(".exp_acc").val())
                if (me.find(".exp_qty").val() != '' && me.find(".unit_cost").val() != '' && me.find("input[name=exp_acc]").val() != '') {
                    Data.expense.push({
                        exp_qty: me.find(".exp_qty").val(),
                        unit_cost: me.find(".unit_cost").val(),
                        vat_percent: me.find(".vat_percent").val(),
                        vat_amount: me.find(".vat_amount").val(),
                        exp_acc: me.find("input[name=exp_acc]").val(),
                        exp_desc: me.find(".exp_desc").val(),
                        dep_rate: me.find(".dep_rate").val(),
                        dep_desc: me.find(".dep_desc").val(),
                        Dep_Period: me.find("select.Dep_Period").val(),
                        paid_amount: me.find(".paid_amount").val(),
                        total: me.find(".tr-total").attr("tr-total")
                    });
                    total_paid += parseFloat(me.find(".paid_amount").val());
                    if (me.find(".paid_amount").val() != '')
                        pay_validate = true;
                    if (me.find(".paid_amount").val() == '' && (supplier_required_expense == 0 || is_cash))
                        validate_fields = true;
                    //                    console.log(total_paid)
                } else {
                    validate = false;
                }
                if (parseFloat($("input.exp_qty ", me).val()) < 0 ||
                        parseFloat($("input.unit_cost ", me).val()) < 0 ||
                        parseFloat($("input.unit_cost ", me).val()) < 0 || ($.trim($('input.exp_qty', me).val()).match(/^\s*?([\d]+(\.\d+)?|\.\d{1,2})\s*$/) == null && $('input.exp_qty', me).val() != '') || ($.trim($('input.unit_cost', me).val()).match(/^\s*?([\d]+(\.\d+)?|\.\d{1,2})\s*$/) == null && $('input.unit_cost', me).val() != '') || ($.trim($('input.vat_percent', me).val()).match(/^\s*?([\d]+(\.\d+)?|\.\d{1,2})\s*$/) == null && $('input.vat_percent', me).val() != '' && $('input.vat_percent', me).val() != 0) || ($.trim($('input.paid_amount', me).val()).match(/^\s*?([\d]+(\.\d+)?|\.\d{1,2})\s*$/) == null && $('input.paid_amount', me).val() != '' && $('input.paid_amount', me).val() != 0)) {
                    is_negative_value = true;
                }
            })
            //            console.log(total_paid)
            Data.total_paid = total_paid;

            if (!validate || validate_fields) {
                $("#paymentAlert").attr("class", " alert alert-danger").empty().html(Required_Fields);
                $("#expense_isbusy").addClass('hidden')
                $(document.body).animate({scrollTop: 0}, 800)
                return false;
            }
            if (Data.expense.length == 0) {
                $("#paymentAlert").attr("class", "alert alert-warning").html('<?php echo CommonLanguage::getMessage('choose_entry'); ?>');
                $(document.body).animate({scrollTop: 0}, 800)
                return;
            }
            if (is_negative_value) {
                $("#paymentAlert").attr("class", "alert alert-warning").html('<?php echo CommonLanguage::getMessage('negative_value'); ?>');
                $(document.body).animate({scrollTop: 0}, 800)
                return;
            }
            if (pay_validate && $("#pay_method").val() == '') {
                $("#paymentAlert").attr("class", " alert alert-danger").empty().html(pay_method_alert);
                $("#expense_isbusy").addClass('hidden')
                $(document.body).animate({scrollTop: 0}, 800)
                return false;
            }

            if (IsEdit) {
                Data.exp_id = edit_id;
            }
            $("#expense_isbusy").removeClass('hidden')
            //            return false;
            $.ajax({
                url: IsEdit ? "ACCAjax/edit_expense" : "ACCAjax/add_expense",
                method: "POST",
                data: Data,
                dataType: 'json',
                complete: function (v1, v2) {
                    if (v2 == 'success') {
                        if (v1.responseJSON[0] == 'success') {
                            $("#paymentAlert").attr("class", " alert alert-success").empty().html(Submitted_Successfully + '&nbsp;<strong>' + '<?php echo CommonLanguage::getMessage('exp_nb') ?>' + ' ' + v1.responseJSON[2]);
                            $("#PaymentSubmitButton").addClass('disabled')
                            edit_id = v1.responseJSON[1]
                            $("#PrintBtn").removeClass("disabled");
                        } else {
                            $("#paymentAlert").attr("class", " alert alert-danger").empty().html(v1.responseJSON)
                        }
                    } else {
                        $("#PaymentValidationAlert").attr("class", "alert alert-danger").empty().html(Failed_Submit);
                    }
                    $("#expense_isbusy").addClass("hidden")
                    $(document.body).animate({scrollTop: 0}, 800)
                }
            })
        });
        $(".exp_div").on("keyup", ".unit_cost,.exp_qty,.vat_amount,.vat_percent", function () {
            var tr = $(this).parents('.AddRow'),
                    quantity = parseFloat(tr.find(".exp_qty").val()) || 0,
                    unit_price = parseFloat(tr.find(".unit_cost").val()) || 0,
                    tr_total = (quantity * unit_price) || 0,
                    vat_percent = 0, vat_amount = 0;
//                    console.log('tr total='+tr_total+' quantity = '+quantity+' unit_price= '+unit_price)
            if ($(this).hasClass("vat_percent")) {
                vat_percent = parseFloat(tr.find(".vat_percent").val()) || 0;
                vat_amount = tr_total * vat_percent / 100;
//                console.log(vat_amount)
                tr.find(".vat_amount").val(vat_amount).attr("vat-amount", vat_amount)
            } else if ($(this).hasClass('vat_amount')) {
                vat_amount = parseFloat(tr.find(".vat_amount").val()) || 0;
                vat_percent = (vat_amount * 100) / tr_total;
//                console.log(vat_percent)

                tr.find(".vat_percent").val(vat_percent)
            }
            updateTable();
        })
        $(".exp_div").on("change", ".unit_cost,.exp_qty,.vat_amount,.vat_percent", function () {
            var tr = $(this).parents('.AddRow');
            tr.find(".unit_cost").val(public_round_number((tr.find(".unit_cost").val())))
            tr.find(".exp_qty").val(public_round_number((tr.find(".exp_qty").val())))
            tr.find(".vat_amount").val(public_round_number((tr.find(".vat_amount").val())))
            tr.find(".vat_percent").val(public_round_number((tr.find(".vat_percent").val())))
            updateTable();
        })


        $(".unit_cost").trigger("keyup")
        $("#CurrencyDropDown li").on("click", function () {

            CurrencySymbol = $(this).attr("mysymbol")
            $(".CurrencyIndicator").html($(this).attr("mysymbol"))
            if ($(this).attr("value") == local_currency) {
                $("#current_rate").val(1).attr("disabled", "disabled")
            } else
                $("#current_rate").val("").removeAttr("disabled")
            if ($(this).attr("value") == second_currency) {
                $("#second_currency_rate").val(1).attr("disabled", "disabled")
            } else
                $("#second_currency_rate").val("").removeAttr("disabled")

        })

    })
    function updateTable() {
        var total = 0, taxable_total = 0, vat_total = 0, total_no_vat = 0;
        $(".exp_div .AddRow").each(function () {
            var tr = $(this),
                    quantity = parseFloat(tr.find(".exp_qty").val()) || 0,
                    unit_price = parseFloat(tr.find(".unit_cost").val()) || 0,
                    tr_total = (quantity * unit_price) || 0,
                    vat_percent = parseFloat(tr.find(".vat_percent").val()) || 0,
                    vat_amount = parseFloat(tr.find(".vat_amount").val()) || 0;//tr_total * vat_percent / 100;
            tr.find(".tr-total").text(AddCommas(public_round_number(tr_total + vat_amount))).attr("tr-total", tr_total);
            total += (tr_total + vat_amount);
            total_no_vat += tr_total;
//            tr.find(".vat_amount").val(vat_amount).attr("vat-amount", vat_amount);
            if (vat_percent > 0) {
                taxable_total += tr_total;
                vat_total += vat_amount;
            }
            if (is_cash) {
                $("input.paid_amount").val(total)
            }
//            console.log(total)
        })

        $("#ExpenseTotalAmount").text(AddCommas(public_round_number(total))).attr("exp_total", public_round_number(total)).attr("exp_no_vat", public_round_number(total_no_vat))
        $("#taxable_amount").text(AddCommas(public_round_number(taxable_total)))
        $("#InvoiceVAT").text(AddCommas(public_round_number(vat_total))).attr("total-vat", public_round_number(vat_total))
    }
</script>
