<?php if ($IsEdit && $check_lock != '') { ?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong>Danger: </strong><?php echo $check_lock ?>
    </div>
    <?php
    return;
}
if ($IsEdit && empty($edit_arr)) { ?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong>Danger: </strong>you can not <?php echo $is_copy ? 'copy' : 'edit'; ?> this JV! 
        <br>
        This JV  is not available.
    </div>
    <?php
    die();
}
if ($IsEdit && !$is_copy && $edit_arr[0]['main_type'] != 'mjv') {
    ?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong>Danger: </strong>you can not edit non Manual JV! 
    </div>
    <?php
    die();
}
$fields_hide = smc_session()['default_setting']['manual_jv_fields_to_hide'] != '' ? explode(",", smc_session()['default_setting']['manual_jv_fields_to_hide']) : [];
//echo"<pre>";die(print_r($fields_hide));
$close_inv_perm = $permissions->hasPermission($IsEdit ? ($IsActual ? 'edit_act_jv_close_invoice' : 'edit_jv_close_invoice') : ($IsActual ? 'add_act_jv_close_invoice' : 'add_jv_close_invoice'));
?>
<style type="text/css">
    #JVTable thead tr th {
        color:#555;
        border-bottom: 1px solid rgba(0,0,0,0.1);
    }
    #JVTable tbody tr td input, #JVTable tbody tr td .lazy-select-load{
        width:100%;
        margin:0;
        border: 1px solid rgba(0,0,0,0.02);
        background-color:#e5e5e5;
    }
    .wrong{
        border: 1px solid rgba(255, 0, 0, 0.2);
        background: rgba(255, 0, 0, 0.05);
        /*        width:100%;*/
    }
    #JVTable tbody tr td {
        border:0;
        padding:3px 1px;
    }
    #JVTable tbody tr:first-child td{
        padding-top:10px;
    }
    .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 > 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;
    }
    .dropdown-menu>li>a{
        color: #000 !Important;
        opacity: 1;
    }
    /*    .select2-container .select2-choice {
    opacity: 1;
    color: #000 !important;
    }*/
    .datepicker thead tr .dow {
        color:#ed9421 !important;
    }
    .datepicker table tr td.day:hover {
        background: #ed9421 !important;
        color:#fff;
    }
    .datepicker table tr td.active {
        background-color: #ed9421 !important;
    }
    .datepicker thead tr .datepicker-switch {
        color: #ed9421 !important;
        font-size: 13px;
    }
    .datepicker table tr td span.active {
        background-color: #ed9421 !important;
    }
    .datepicker table tr td span:hover {
        background-color: #ed9421 !important;
        color:#fff;
    }
    datepicker thead tr .next:before, .datepicker thead tr .prev:before {
        color: #ed9421 !important;
        font-family: 'FontAwesome';
        font-size: 10px;
    }
    .datepicker thead tr .next:before, .datepicker thead tr .prev:before {
        color: #ed9421 !important;
        font-family: 'FontAwesome';
        font-size: 10px;
    }
    #JVTable tbody tr td .lazy-select-load{
        min-width:100%;
        width:1px;
        overflow:hidden;
        white-space: nowrap;
    }
    .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;
    }
    .close_jv{
        font-size: 8px;
        padding: 0;
        line-height: 1;
        cursor:pointer;
    }
</style>
<div id="AddJV" style="position:absolute;left:0;right:0;top:0px;height:100%;background:rgba(255,255,255,0.9);z-index:2099;display:none">
    <img class="image-responsive-height demo-mw-50" src="img/demo/progress.svg" alt="Progress" style="position: absolute;left: 50%;top: 50%;margin: -25px 0 0 -25px;" />
</div>
<form method="POST" action="" onsubmit="return false" id="JVForm">
    <div class="container-fluid container-fixed-lg">
        <div class="panel panel-default">
            <div class="panel-body">
                <div id="JVSuccess" ></div>
                <div class="JV sm-padding-10">
                    <div class="container-sm-height">
                        <div class="row-sm-height">
                            <div class="col-md-9 col-sm-height sm-no-padding">
                                <h2 class="font-montserrat all-caps hint-text"><?php print CommonLanguage::getMessage(($IsEdit && !$is_copy) ? 'edit_jv' : ($is_copy ? 'copy_jv' : 'add_jv')); ?></h2>
                                <!--                                <div class="input-group  col-md-4 center-margin pull-left" >
<span class="input-group-addon  bg-complete">
<i class="fa fa-search"></i>
</span>
<input type="text"	name="Transaction_Reference" id="Transaction_Reference" class="form-control" placeholder="<?php print CommonLanguage::getMessage('reference'); ?>" value="<?php echo ($IsEdit) ? $edit_arr[0]['Transaction_Reference'] : '' ?>">
</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="sm-m-t-20">
                                    <h4><?php print CommonLanguage::getMessage('jv'); ?> # <?php
                                        if (!$IsEdit || $is_copy) {
                                            echo'--';
                                        } else {
                                            echo $edit_arr[0]['JV_ID'];
                                        }
                                        ?></h4>
                                </div>
                                <div  class="form-group form-group-default input-group">
                                    <label><?php print CommonLanguage::getMessage('Date'); ?></label>
                                    <input id="Date_Transaction" name="Date_Transaction" class="form-control datepicker" value="<?php echo (($IsEdit && !$is_copy) ? $edit_arr[0]['Transaction_Date'] : $today); ?>" />
                                    <span class="input-group-addon bg-complete"><i class="fa fa-calendar"></i></span>
                                </div>
                                <div class=" form-group  <?php echo $permissions->hasPermission('Branches') ? '':'hidden'; ?>">   
                                    <label><?php print CommonLanguage::getMessage('branch'); ?></label>
                                    <input class=" full-width" id="branch_id" name="branch_id" type="hidden"  value="<?php echo ($IsEdit && !$is_copy) ? $edit_arr[0]['branch_id'] : (empty(smc_session()['user_accounts']['branch_id']) ? smc_session()['default_branch_id'] : smc_session()['user_accounts']['branch_id']) ?>" data-select-name='<?php echo (($IsEdit && !$is_copy) ? $edit_arr[0]['branch_name'] : (empty(smc_session()['user_accounts']['branch_id']) ? smc_session()['default_branch_name'] : smc_session()['user_accounts']['branch_name'])) ?>'/>
                                </div>
                                <br>
                            </div>
                        </div>
                    </div>
                    <div>
                        <div class="clearfix"></div>
                    </div>
                    <div class="table-responsive">
                        <table class="table" id='JVTable'>
                            <thead>
                                <tr>
                                    <th class="text-center"style="width:3%"></th>
                                    <th class="text-center"><?php print CommonLanguage::getMessage('account_name'); ?><span class="red-star">*</span><span class="fa fa-plus-circle m-l-5" data-toggle="modal" data-target="#customer_supplier_account_modal" style="color:#4c0870;cursor:pointer"></span></th>
                                    <th class="text-center"><?php print CommonLanguage::getMessage('Code'); ?><span class="red-star">*</span></th>
                                    <th class="text-center"><?php print CommonLanguage::getMessage('currency'); ?><span class="red-star">*</span></th>

                                    <th class="text-center"><?php print CommonLanguage::getMessage('type'); ?><span class="red-star">*</span></th>
                                    <th class="text-center"><?php print CommonLanguage::getMessage('amount'); ?><span class="red-star">*</span></th>
                                    <th class="text-center <?php echo!in_array(6, $fields_hide) && $close_inv_perm ? '' : 'hidden' ?>"></th>
                                    <th class="text-center <?php echo!in_array(0, $fields_hide) ? '' : 'hidden' ?>"><?php print CommonLanguage::getMessage('description'); ?></th>
                                    <th class="text-center <?php echo smc_session()['default_setting']['activate_trans_subtype'] == 0 ? 'hidden' : '' ?>" ><?php print CommonLanguage::getMessage('ref_type'); ?></th>
                                    <th class="text-center  <?php echo!in_array(1, $fields_hide) ? '' : 'hidden' ?>"><?php print CommonLanguage::getMessage('reference'); ?></th>
                                    <th class="text-center <?php echo!in_array(2, $fields_hide) ? '' : 'hidden' ?>" ><?php print CommonLanguage::getMessage('user_ref'); ?></th>
                                    <th class="text-center <?php echo smc_session()['default_setting']['activate_accounting_job'] == 0 || in_array(4, $fields_hide) ? 'hidden' : '' ?>"><?php print CommonLanguage::getMessage('job'); ?></th>
                                    <th class="text-center <?php echo smc_session()['default_setting']['activate_project'] == 0 || in_array(5, $fields_hide) ? 'hidden' : '' ?>"><?php print CommonLanguage::getMessage('project'); ?></th>
                                    <th class="text-center <?php echo!in_array(3, $fields_hide) ? '' : 'hidden' ?>"><?php print CommonLanguage::getMessage('due_date'); ?></th>
                                    <th class="text-center"><?php print CommonLanguage::getMessage('rate') . ' ' . smc_session()['local_currency_symbol']; ?></th>
                                    <th class="text-center "><?php print CommonLanguage::getMessage('amount') . ' ' . smc_session()['local_currency_symbol']; ?></th>
                                    <th class="text-center <?php echo $activate_second_currency == 0 ? 'hidden' : '' ?>"><?php print CommonLanguage::getMessage('rate') . ' ' . smc_session()['second_currency']['symbol']; ?></th>
                                    <th class="text-center <?php echo $activate_second_currency == 0 ? 'hidden' : '' ?>"><?php print CommonLanguage::getMessage('amount') . ' ' . smc_session()['second_currency']['symbol']; ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                $is_large_data = false;
                                if ($IsEdit) {
                                    $arr_count = count($edit_arr);
                                    $is_large_data = $arr_count > 200 ? true : false;
                                    for ($i = 0; $i < $arr_count; $i++) {
                                        $curr = $edit_arr[$i];
                                        //here we exclude the first row since we clone it
                                        $row_is_large_data = ($is_large_data && $i != 0);
                                        ?>
                                        <tr class="AddRow" data-id="<?php echo $curr['main_id']; ?>" data-type = "<?php echo $curr['main_type'] ?>" 
                                            data-acc-type="<?php echo $curr['acc_main_type'] ?>" data-acc-sub="<?php echo $curr['acc_sub_type'] ?>"
                                            data-account="<?php echo $curr['Account_ID'] ?>" data-jobs="<?php echo $curr['job_ids'] ?>" 
                                            data-job-required="<?php echo $curr['job_required'] ?>" local-rate="<?php echo $curr['local_rate'] ?>" 
                                            second-rate="<?php echo $curr['second_rate'] ?>" data-trans-id="<?php echo $curr['Transaction_ID'] ?>"
                                            data-invs='<?php echo $IsEdit && !$is_copy && !empty($curr['close_data']) ? json_encode($curr['close_data']) : '' ?>'
                                            data-total-inv='<?php echo $IsEdit && !$is_copy && !empty($curr['invoices_total']) ? $curr['invoices_total'] : '' ?>'>
                                            <td>  
                                            <span class="fa fa-plus-circle addRowRequest " style="color: #4c0870;margin-left: 5px;cursor: pointer;font-size: 16px;"></span>

                                                <span class="fa fa-minus-circle deleteRowRequest " style="color: #4c0870;margin-left: 5px;cursor: pointer;font-size: 16px;"></span>
                                            </td>
                                            <td class="text-center"><input type="<?php echo $row_is_large_data ? 'hidden' : 'text' ?>" class="text-center form-control AutoComplete AccountName" value="<?php echo $curr['Account_Name']; ?>" ><?php echo $row_is_large_data ? '<span class="lazy-select-load form-control" data-input-class="AccountName" tabindex="0">' . ($curr['Account_Name']) . '</span>' : '' ?></td>
                                            <td class="text-center"><input type="<?php echo $row_is_large_data ? 'hidden' : 'text' ?>" class="text-center form-control AutoComplete CODE"  value="<?php echo $curr['Transaction_Account']; ?>"><?php echo $row_is_large_data ? '<span class="lazy-select-load form-control" data-input-class="CODE" tabindex="0">' . ($curr['Transaction_Account']) . '</span>' : '' ?></td>
                                            <td class="text-center">
                                                <select class="full-width Currency_ID" <?php echo $row_is_large_data ? '' : 'data-init-plugin="select2"' ?>>
                                                    <?php foreach ($currency_list as $currency): ?>
                                                        <option mysymbol="<?php echo $currency['Currency_Symbol']; ?>" value="<?php echo $currency['Currency_ID']; ?>" <?php echo $currency['Currency_ID'] == $curr['Currency_ID'] ? 'selected' : '' ?>><?php echo $currency['Currency_Name'] . " - " . $currency['Currency_Code']; ?></option>
                                                    <?php endforeach; ?>
                                                </select> 
                                            </td>
                                            <td class="text-center"><select class="full-width Transaction" <?php echo $row_is_large_data ? '' : 'data-init-plugin="select2"' ?>>
                                                    <option value="Credit" <?php echo ($curr['Transaction_Type'] == "Credit" ? 'selected' : '' ) ?>><?php print CommonLanguage::getMessage('credit'); ?></option>
                                                    <option value="Debit" <?php echo ($curr['Transaction_Type'] == "Debit" ? 'selected' : '' ) ?>><?php print CommonLanguage::getMessage('debit'); ?></option>
                                                </select></td>

                                            <td class="text-center"><span class="Hint"></span><input type="<?php echo $row_is_large_data ? 'hidden' : 'text' ?>" class="text-center form-control Amount isnumber" value = "<?php echo!$is_copy ? $curr['Transaction_Amount'] : '' ?>"><?php echo $row_is_large_data ? '<span class="lazy-select-load form-control" data-input-class="Amount" tabindex="0">' . ( $curr['Transaction_Amount']) . '</span>' : '' ?><span class="close_jv hidden"> <?php echo CommonLanguage::getMessage('close_jv') ?></span></td>
                                            <td class=" <?php echo!in_array(6, $fields_hide) && $close_inv_perm ? '' : 'hidden' ?>"><span class="fa fa-file get_inv <?php echo (($curr['acc_main_type'] == 'cust' && $curr['acc_sub_type'] == 'main' && $curr['Transaction_Type'] == "Credit") || ($curr['acc_main_type'] == 'supp' && $curr['acc_sub_type'] == 'main' && $curr['Transaction_Type'] == "Debit")) ? '' : 'hidden' ?>" style="color: #4c0870;margin: 5px;cursor: pointer;font-size: 16px;"></span></td>

                                            <td class="text-center  <?php echo!in_array(0, $fields_hide) ? '' : 'hidden' ?>"><span class="Hint"></span><textarea type="<?php echo $row_is_large_data ? 'hidden' : 'text' ?>" class="text-center form-control Description"  ><?php echo $curr['Transaction_Description'] ?></textarea><?php echo $row_is_large_data ? '<span class="lazy-select-load form-control" data-input-class="Description" tabindex="0">' . ($curr['Transaction_Description']) . '</span>' : '' ?></td>
                                            <td style="min-width:10%;" class="<?php echo smc_session()['default_setting']['activate_trans_subtype'] == 0 ? 'hidden' : '' ?>"><input type="hidden" class="full-width " name="ref_type" value = "<?php echo empty($curr['subtype']) ? '' : $curr['subtype'] ?>" data-select-name='<?php echo (empty($curr['subtype']) ? '' : $curr['subtype']) ?>'><?php echo $row_is_large_data ? '<span class="lazy-select-load form-control" data-input-class="ref_type" tabindex="0">' . (empty($curr['subtype']) ? '' : $curr['subtype']) . '</span>' : '' ?></td>
                                            <td class="text-center <?php echo!in_array(1, $fields_hide) ? '' : 'hidden' ?>"><input type="<?php echo $row_is_large_data ? 'hidden' : 'text' ?>" class="form-control text-center ref_nb" value = "<?php echo $curr['Transaction_Reference'] ?>"><?php echo $row_is_large_data ? '<span class="lazy-select-load form-control" data-input-class="ref_nb" tabindex="0">' . ($curr['Transaction_Reference']) . '</span>' : '' ?></td>
                                            <td class="text-center  <?php echo!in_array(2, $fields_hide) ? '' : 'hidden' ?>"><input type="<?php echo $row_is_large_data ? 'hidden' : 'text' ?>" class="form-control text-center user_ref" value = "<?php echo $curr['user_ref'] ?>"><?php echo $row_is_large_data ? '<span class="lazy-select-load form-control" data-input-class="user_ref" tabindex="0">' . ($curr['user_ref']) . '</span>' : '' ?></td>
                                            <td class="<?php echo smc_session()['default_setting']['activate_accounting_job'] == 0 || in_array(4, $fields_hide) ? 'hidden' : '' ?>"><input type="hidden" class="full-width job_id" name="job_id" value = "<?php echo empty($curr['job_id']) ? '' : $curr['job_id'] ?>" data-select-name='<?php echo (empty($curr['job_name']) ? '' : $curr['job_name']) ?>'><?php echo $row_is_large_data ? '<span class="lazy-select-load form-control" data-input-class="job_id" tabindex="0">' . (empty($curr['job_name']) ? '' : $curr['job_name']) . '</span>' : '' ?></td>
                                            <td class="<?php echo smc_session()['default_setting']['activate_project'] == 0 || in_array(5, $fields_hide) ? 'hidden' : '' ?>"><input type="hidden" class="full-width project_id" name="project_id" value = "<?php echo empty($curr['project_id']) ? '' : $curr['project_id'] ?>" data-select-name='<?php echo (empty($curr['project_name']) ? '' : $curr['project_name']) ?>'><?php echo $row_is_large_data ? '<span class="lazy-select-load form-control" data-input-class="project_id" tabindex="0">' . (empty($curr['project_name']) ? '' : $curr['project_name']) . '</span>' : '' ?></td>
                                            <td class="text-center <?php echo!in_array(2, $fields_hide) ? '' : 'hidden' ?>"><input type="<?php echo $row_is_large_data ? 'hidden' : 'text' ?>" class="form-control text-center due_date"  value = "<?php echo $curr['due_date'] ?>"><?php echo $row_is_large_data ? '<span class="lazy-select-load form-control" data-input-class="due_date" tabindex="0">' . ($curr['due_date']) . '</span>' : '' ?></td>
                                            <td class="text-center"><input type="<?php echo $row_is_large_data ? 'hidden' : 'text' ?>" class="text-center form-control exchange " <?php echo $curr['Currency_ID'] == smc_session()['local_currency'] ? 'readonly' : '' ?> value = "<?php echo!$is_copy ? $curr['Current_Ex_Rate'] : '' ?>"><?php echo $row_is_large_data ? '<span class="lazy-select-load form-control" data-input-class="exchange" tabindex="0">' . (!$is_copy ? $curr['Current_Ex_Rate'] : '!$is_copy ? ' ) . '</span>' : '' ?></td>
                                            <td class="text-center "><input type="<?php echo $row_is_large_data ? 'hidden' : 'text' ?>" class="text-center form-control amt_local " <?php echo $curr['Currency_ID'] == smc_session()['local_currency'] ? 'readonly' : '' ?> value = "<?php echo!$is_copy ? ($curr['local_amount']) : '' ?>"><?php echo $row_is_large_data ? '<span class="lazy-select-load form-control" data-input-class="amt_local" tabindex="0">' . ($curr['local_amount']) . '</span>' : '' ?></td>
                                            <td class="text-center <?php echo $activate_second_currency == 0 ? 'hidden' : '' ?>"><input type="<?php echo $row_is_large_data ? 'hidden' : 'text' ?>" class="text-center form-control ex_second " <?php echo $curr['Currency_ID'] == smc_session()['second_currency']['id'] ? 'readonly' : '' ?> value = "<?php echo!$is_copy ? $curr['second_currency_rate'] : '' ?>"><?php echo $row_is_large_data ? '<span class="lazy-select-load form-control" data-input-class="ex_second" tabindex="0">' . (!$is_copy ? $curr['second_currency_rate'] : '') . '</span>' : '' ?></td>
                                            <td class="text-center <?php echo $activate_second_currency == 0 ? 'hidden' : '' ?>"><input type="<?php echo $row_is_large_data ? 'hidden' : 'text' ?>" class="text-center form-control amt_second " <?php echo $curr['Currency_ID'] == smc_session()['second_currency']['id'] ? 'readonly' : '' ?> value = "<?php echo!$is_copy ? $curr['second_amount'] : '' ?>"><?php echo $row_is_large_data ? '<span class="lazy-select-load form-control" data-input-class="amt_second" tabindex="0">' . ($curr['second_amount']) . '</span>' : '' ?></td>
                                        </tr>
                                    <?php }
                                    ?>
                                    <tr class="AddRow" local-rate="1" second-rate="<?php echo $second_to_local_rate ?>">
                                        <td>  
                                        <span class="fa fa-plus-circle addRowRequest " style="color: #4c0870;margin-left: 5px;cursor: pointer;font-size: 16px;"></span>

                                            <span class="fa fa-minus-circle deleteRowRequest " style="color: #4c0870;margin-left: 5px;cursor: pointer;font-size: 16px;"></span>

                                        </td>
                                        <td class="text-center"><input type="text" require class="text-center form-control AutoComplete AccountName"></td>
                                        <td class="text-center"><input type="text" require class="text-center form-control AutoComplete CODE"></td>
                                        <td class="text-center">
                                            <select class="full-width Currency_ID" data-init-plugin="select2">
                                                <?php foreach ($currency_list as $currency): ?>
                                                    <option mysymbol="<?php echo $currency['Currency_Symbol']; ?>" <?php echo $DefaultCurrencyID == $currency['Currency_ID'] ? 'selected' : '' ?> value="<?php echo $currency['Currency_ID']; ?>"><?php echo $currency['Currency_Name'] . " - " . $currency['Currency_Code']; ?></option>
                                                <?php endforeach; ?>
                                            </select> 
                                        </td>
                                        <td class="text-center">
                                            <select class="full-width Transaction" data-init-plugin="select2">
                                                <option value="Credit"><?php print CommonLanguage::getMessage('credit'); ?></option>
                                                <option value="Debit"><?php print CommonLanguage::getMessage('debit'); ?></option>
                                            </select>
                                        </td>

                                        <td class="text-center"><span class="Hint"></span><input type="text" require class="text-center form-control Amount isnumber"><span class="close_jv hidden"> <?php echo CommonLanguage::getMessage('close_jv') ?></span></td>
                                        <td  class=" <?php echo!in_array(6, $fields_hide) && $close_inv_perm ? '' : 'hidden' ?>"><span class="fa fa-file get_inv hidden" style="color: #4c0870;margin: 5px;cursor: pointer;font-size: 16px;"></span></td>
                                        <td class="text-center  <?php echo!in_array(0, $fields_hide) ? '' : 'hidden' ?>"><span class="Hint"></span><textarea type="text" class="text-center form-control Description"></textarea></td>
                                        <td style="min-width:10%;" class="<?php echo smc_session()['default_setting']['activate_trans_subtype'] == 0 ? 'hidden' : '' ?>"><input type="hidden" class="full-width " name="ref_type"></td>
                                        <td class="text-center <?php echo!in_array(1, $fields_hide) ? '' : 'hidden' ?>"><input type="text" class="form-control text-center ref_nb"></td>
                                        <td class="text-center <?php echo!in_array(2, $fields_hide) ? '' : 'hidden' ?>"><input type="text" class="form-control text-center user_ref" ></td>
                                        <td class="<?php echo smc_session()['default_setting']['activate_accounting_job'] == 0 || in_array(4, $fields_hide) ? 'hidden' : '' ?>"><input type="hidden" class="full-width job_id" name="job_id"></td>
                                        <td class="<?php echo smc_session()['default_setting']['activate_project'] == 0 || in_array(5, $fields_hide) ? 'hidden' : '' ?>"><input type="hidden" class="full-width project_id" name="project_id"></td>
                                        <td class="text-center <?php echo!in_array(3, $fields_hide) ? '' : 'hidden' ?>"><input type="text" class="form-control text-center due_date"></td>
                                        <td class="text-center"><input type="text" class="text-center form-control exchange "></td>
                                        <td class="text-center"><input type="text" class="text-center form-control amt_local "></td>
                                        <td class="text-center <?php echo $activate_second_currency == 0 ? 'hidden' : '' ?>"><input type="text" class="text-center form-control ex_second "></td>
                                        <td class="text-center <?php echo $activate_second_currency == 0 ? 'hidden' : '' ?>"><input type="text" class="text-center form-control amt_second "></td>
                                    </tr>
                                <?php } else {
                                    ?>
                                    <tr class="AddRow" local-rate="1" second-rate="<?php echo $second_to_local_rate ?>">
                                        <td>  
                                        <span class="fa fa-plus-circle addRowRequest " style="color: #4c0870;margin-left: 5px;cursor: pointer;font-size: 16px;"></span>

                                            <span class="fa fa-minus-circle deleteRowRequest " style="color: #4c0870;margin-left: 5px;cursor: pointer;font-size: 16px;"></span>
                                        </td>
                                        <td class="text-center"><input type="text" require class="text-center form-control AutoComplete AccountName"></td>
                                        <td class="text-center"><input type="text" require class="text-center form-control AutoComplete CODE"></td>
                                        <td class="text-center">
                                            <select class="full-width Currency_ID" data-init-plugin="select2">
                                                <?php foreach ($currency_list as $currency): ?>
                                                    <option mysymbol="<?php echo $currency['Currency_Symbol']; ?>" <?php echo $DefaultCurrencyID == $currency['Currency_ID'] ? 'selected' : '' ?> value="<?php echo $currency['Currency_ID']; ?>"><?php echo $currency['Currency_Name'] . " - " . $currency['Currency_Code']; ?></option>
                                                <?php endforeach; ?>
                                            </select> 
                                        </td>
                                        <td class="text-center">
                                            <select class="full-width Transaction" data-init-plugin="select2">
                                                <option value="Credit"><?php print CommonLanguage::getMessage('credit'); ?></option>
                                                <option value="Debit"><?php print CommonLanguage::getMessage('debit'); ?></option>
                                            </select>
                                        </td>

                                        <td class="text-center"><span class="Hint"></span><input type="text" require class="text-center form-control Amount isnumber"><span class="close_jv hidden"> <?php echo CommonLanguage::getMessage('close_jv') ?></span></td>
                                        <td  class=" <?php echo!in_array(6, $fields_hide) && $close_inv_perm ? '' : 'hidden' ?>"><span class="fa fa-file get_inv hidden" style="color: #4c0870;margin: 5px;cursor: pointer;font-size: 16px;"></span></td>
                                        <td class="text-center  <?php echo!in_array(0, $fields_hide) ? '' : 'hidden' ?>"><span class="Hint"></span><textarea type="text" class="text-center form-control Description"></textarea></td>  
                                        <td style="min-width:10%;" class="<?php echo smc_session()['default_setting']['activate_trans_subtype'] == 0 ? 'hidden' : '' ?>"><input type="hidden" class="full-width " name="ref_type"></td>
                                        <td class="text-center <?php echo!in_array(1, $fields_hide) ? '' : 'hidden' ?>"><input type="text" class="form-control text-center ref_nb"></td>
                                        <td class="text-center <?php echo!in_array(2, $fields_hide) ? '' : 'hidden' ?>"><input type="text" class="form-control text-center user_ref" ></td>
                                        <td class="<?php echo smc_session()['default_setting']['activate_accounting_job'] == 0 || in_array(4, $fields_hide) ? 'hidden' : '' ?>"><input type="hidden" class="full-width job_id" name="job_id"></td>
                                        <td class="<?php echo smc_session()['default_setting']['activate_project'] == 0 || in_array(5, $fields_hide) ? 'hidden' : '' ?>"><input type="hidden" class="full-width project_id" name="project_id"></td>
                                        <td class="text-center <?php echo!in_array(3, $fields_hide) ? '' : 'hidden' ?>"><input type="text" class="form-control text-center due_date"></td>
                                        <td class="text-center"><input type="text" class="text-center form-control exchange " value="<?php echo $DefaultCurrencyID == smc_session()['default_setting']['local_currency'] ? '1' : '' ?>" <?php echo $DefaultCurrencyID == smc_session()['default_setting']['local_currency'] ? 'disabled' : '' ?>></td>
                                        <td class="text-center"><input type="text" class="text-center form-control amt_local " value="<?php echo $DefaultCurrencyID == smc_session()['default_setting']['local_currency'] ? '0' : '' ?>" <?php echo $DefaultCurrencyID == smc_session()['default_setting']['local_currency'] ? 'disabled' : '' ?>></td>
                                        <td class="text-center <?php echo $activate_second_currency == 0 ? 'hidden' : '' ?>"><input type="text" class="text-center form-control ex_second "  value="<?php echo $DefaultCurrencyID == smc_session()['default_setting']['second_currency'] ? '1' : '' ?>" <?php echo $DefaultCurrencyID == smc_session()['default_setting']['second_currency'] ? 'disabled' : '' ?>></td>
                                        <td class="text-center <?php echo $activate_second_currency == 0 ? 'hidden' : '' ?>"><input type="text" class="text-center form-control amt_second "  value="<?php echo $DefaultCurrencyID == smc_session()['default_setting']['second_currency'] ? '0' : '' ?>" <?php echo $DefaultCurrencyID == smc_session()['default_setting']['second_currency'] ? 'disabled' : '' ?>></td>
                                    </tr>
                                <?php } ?>
                            </tbody> 
                        </table>
                    </div>
                    <br>
                    <div class="container-sm-height" >
                        <div class="row row-sm-height b-a b-grey">
                            <div class="col-sm-6 col-sm-height  clearfix " style="padding:0 !important;">
                                <div class="col-sm-12 form-group  " style="padding-right:0">
                                    <button class="btn btn-complete" id="fill_user_ref" style="margin-top: 10px;margin-left: 10px;"><?php echo CommonLanguage::getMessage('fill_all_user_ref') ?>&nbsp;&nbsp;<span class="fa fa-info-circle" title="<?php echo CommonLanguage::getMessage('fill_all_user_ref_hint') ?>"></span></button>
                                </div>
                                <div class="col-sm-12 form-group  " style="padding-right:0">
                                    <!--<label><?php // echo CommonLanguage::getMessage('user_ref')                                                  ?></label>-->
                                    <textarea id="jv_note" name="jv_note" class="form-control NoteTextArea" placeholder="<?php echo CommonLanguage::getMessage('user_ref') ?>" aria-invalid="false"><?php echo ($IsEdit || $is_copy) ? $edit_arr[0]['user_ref'] : '' ?></textarea>
                                </div>
                            </div>
                            <div class="col-sm-6 text-right bg-menu col-sm-height padding-15">
                                <div class="col-md-6 pull-right">
                                    <h3 class="font-montserrat all-caps small no-margin hint-text text-white bold"><?php print CommonLanguage::getMessage('total_credit'); ?></h3>
                                    <h3 class="no-margin text-white Credit">
                                        <span class="CurrencyIndicator"><?php echo $local_cuurency_symbol ?></span>&nbsp;
                                        <span id="totalCredit"><?php echo ($IsEdit && !$is_copy) ? CommonFunctions::formatNumber($totals_arr['total_credit_local']) : '0' ?></span>
                                    </h3>
                                    <h3 class="font-montserrat all-caps small no-margin hint-text text-white bold"><?php print CommonLanguage::getMessage('total_debit'); ?></h3>
                                    <h3 class="no-margin text-white Debit">
                                        <span class="CurrencyIndicator"><?php echo $local_cuurency_symbol ?></span>&nbsp;
                                        <span id="totalDebit"><?php echo ($IsEdit && !$is_copy) ? CommonFunctions::formatNumber($totals_arr['total_debit_local']) : '0' ?></span>
                                    </h3>
                                    <h3 class="font-montserrat all-caps small no-margin hint-text text-white bold"><?php print CommonLanguage::getMessage('Balance'); ?></h3>
                                    <h3 class="no-margin text-white Total">
                                        <span class="CurrencyIndicator"><?php echo $local_cuurency_symbol ?></span>&nbsp;<span id="totalBalance"><?php echo ($IsEdit && !$is_copy) ? CommonFunctions::formatNumber($totals_arr['local_balance']) : '0' ?></span>
                                    </h3>
                                </div>
                                <div class="col-md-6 <?php echo $activate_second_currency == 0 ? 'hidden' : '' ?>">
                                    <h3 class="font-montserrat all-caps small no-margin hint-text text-white bold"><?php print CommonLanguage::getMessage('total_credit'); ?></h3>
                                    <h3 class="no-margin text-white Credit">
                                        <span class="CurrencyIndicator"><?php echo $SecondCurrencySymbol ?></span>&nbsp;
                                        <span id="totalCreditSecond"><?php echo ($IsEdit && !$is_copy) ? CommonFunctions::formatNumber($totals_arr['total_credit_second']) : '0' ?></span>
                                    </h3>
                                    <h3 class="font-montserrat all-caps small no-margin hint-text text-white bold"><?php print CommonLanguage::getMessage('total_debit'); ?></h3>
                                    <h3 class="no-margin text-white Debit">
                                        <span class="CurrencyIndicator"><?php echo $SecondCurrencySymbol ?></span>&nbsp;
                                        <span id="totalDebitSecond"><?php echo ($IsEdit && !$is_copy) ? CommonFunctions::formatNumber($totals_arr['total_debit_second']) : '0' ?></span>
                                    </h3>
                                    <h3 class="font-montserrat all-caps small no-margin hint-text text-white bold"><?php print CommonLanguage::getMessage('Balance'); ?></h3>
                                    <h3 class="no-margin text-white Total">
                                        <span class="CurrencyIndicator"><?php echo $SecondCurrencySymbol ?></span>&nbsp;<span id="totalBalanceSecond"><?php echo ($IsEdit && !$is_copy) ? CommonFunctions::formatNumber($totals_arr['second_balance']) : '0' ?></span>
                                    </h3>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="container-sm-height" >
                        <button class=" btn btn-complete btn-cons m-b-10 pull-right" disabled id="JVSubmitButton" 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 " 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>
</form>
<div class="modal fade" data-backdrop="static" id="invoice_modal" data-currency ="" data-customer =""  tabindex="-1" role="dialog" aria-hidden="true"style="width:80%;margin:0 auto">
    <div class="modal-dialog ">
        <div class="modal-content">
            <div class="modal-header clearfix text-left">
                <button type="button" class="close" id="close_modal" data-dismiss="modal" aria-hidden="true"><i class="pg-close fs-14"></i></button>
                <h5><span class="semi-bold"><?php print CommonLanguage::getMessage('invoices'); ?></span></h5>
            </div>
            <div class="modal-body form-group" >
                <div id="InvoicesModalAlert"></div>
                <div class="row row_head" style="border-bottom: 1px solid #eb9220;">
                    <div class="col-md-1"><label><?php echo CommonLanguage::getMessage('invoice') ?>&nbsp;#</label></div>
                    <div class="col-md-2"><label><?php echo CommonLanguage::getMessage('Date') ?></label></div>
                    <div class="col-md-2"><label><?php echo CommonLanguage::getMessage('net_total') ?></label></div>
                    <div class="col-md-2"><label><?php echo CommonLanguage::getMessage('remaining') ?></label></div>
                    <div class="col-md-2"><label><?php echo CommonLanguage::getMessage('amount') ?></label></div>
                    <div class="col-md-2"><label><?php echo CommonLanguage::getMessage('Balance') ?></label></div>

                </div>
                <div id="inv_body">

                    <?php
//                        if (($IsEdit)) {
//                            foreach ($edit_data['pay_inv'] as $inv_pay) {
                    ?>
<!--                                <div class="row m-b-10 my_tr" data-id="<?php echo $inv_pay['Invoice_ID_Auto'] ?>" data-cur = "<?php echo $inv_pay['Invoice_Currency'] ?>">
                                    <div class="col-md-1"><?php echo $inv_pay['Invoice_ID'] ?></div>
                                    <div class="col-md-2"><?php echo $inv_pay['Invoice_Date'] ?></div>
                                    <div class="col-md-2"><?php echo number_format($inv_pay['Invoice_Net_Total']) . ' ' . $edit_data['payments'][0]['Currency_Symbol'] ?></div>
                                    <div class="col-md-2 rem" ><?php echo number_format(($inv_pay['Remaining_Amount'] + $inv_pay['inv_pay_amount'])) . ' ' . $edit_data['payments'][0]['Currency_Symbol'] ?></div>
                                    <div class="col-md-2"><input type="text" class="form-control" value="<?php echo $inv_pay['inv_pay_amount'] > 0 ? $inv_pay['inv_pay_amount'] : '' ?>" data-max="<?php echo $inv_pay['Remaining_Amount'] + $inv_pay['inv_pay_amount'] ?>" /></div>
                                    <div class="col-md-2 balance" ><?php echo number_format($inv_pay['Remaining_Amount']) . ' ' . $edit_data['payments'][0]['Currency_Symbol'] ?></div>
                                </div>-->
                    <?php
//                            }
//                        }
                    ?>
                </div>
            </div>
            <div class="modal-footer">
                <div class="">
                    <button class="btn btn-complete pull-right" id="CloseInv" data-dismiss="modal"  > <?php print CommonLanguage::getMessage('continue'); ?> </button>
                    <button class="btn bg-danger white pull-left" id="ClearInv"  > <?php print CommonLanguage::getMessage('clear'); ?>   </button>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    var Required_Fields = <?php echo json_encode(CommonLanguage::getMessage('Required_Fields')); ?>,
            Failed_Submit = <?php echo json_encode(CommonLanguage::getMessage('Failed_Submit')); ?>,
            zero_balance = <?php echo json_encode(CommonLanguage::getMessage('zero_balance')); ?>,
            have_not_finish = <?php echo json_encode(CommonLanguage::getMessage('have_not_finish')); ?>,
            have_not_saved = <?php echo json_encode(CommonLanguage::getMessage('have_not_saved')); ?>,
            job_required_alert = <?php echo json_encode(CommonLanguage::getMessage('job_required_alert')); ?>,
            Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')); ?>,
            IsEditMode = <?php echo $IsEdit ? "true" : "false"; ?>,
            is_copy = <?php echo $is_copy ? "true" : "false"; ?>,
            activate_job = <?php echo json_encode(smc_session()['default_setting']['activate_accounting_job']); ?>,
            ID_Edit = IsEditMode ? <?php echo json_encode($id); ?> : '',
            is_actual = <?php echo json_encode($IsActual); ?>,
            CurrencyRate = <?php echo json_encode($Extable) ?>,
            PrimaryCurrencyID = <?php echo ($local_cuurency_id) ?>,
            second_currency_id = <?php echo json_encode(smc_session()['second_currency']['id']) ?>,
            activate_second_currency = <?php echo json_encode($activate_second_currency); ?>,
            is_large_data = <?php echo $is_large_data ? "true" : "false" ?>,
            unique_id = <?php echo json_encode(!$IsEdit ? $unique_id : '') ?>, selected_tr = '';
    $(function () {
        if (!is_large_data) {
            if ($("#JVTable tbody tr").length > 1) {
                $("#JVTable tbody tr").each(function () {
                    var job_ids = '';
                    if ($(this).attr("data-jobs") != undefined)
                        job_ids = $(this).attr("data-jobs");
                    build_select2($("input[name=job_id]:last-child", $(this)), "ACCAjax/JobSearch?job_ids=" + job_ids)
                });
            } else {
                build_select2($("input[name=job_id]"), "ACCAjax/JobSearch")
            }
            build_select2($("input.project_id"), "ACCAjax/projectSearch")
            build_select2($("input[name=ref_type]"), "xhr/CommonSearch?col_id=subtype_abbrv&col_name=subtype_abbrv&table=tbl_accounting_transaction_subtype")


        } else {
            build_select2($("input[name=job_id]:last-child"), "ACCAjax/JobSearch")
            build_select2($("input.project_id:last-child"), "ACCAjax/projectSearch")
            build_select2($("input[name=ref_type]:last-child"), "xhr/CommonSearch?col_id=subtype_abbrv&col_name=subtype_abbrv&table=tbl_accounting_transaction_subtype")


            //                    class="lazy-select-load " data-input-class="job_id"

            $(".lazy-select-load").on("mouseover focus", function (e) {
                var tr = $(this).parents('tr'),
                        input = null;

                if ($(this).attr("data-input-class") == 'job_id') {
                    var job_ids = tr.attr("data-jobs");
                    input = $("input[name=job_id]", tr);
                    build_select2(input, "ACCAjax/JobSearch?job_ids=" + (job_ids == undefined ? '' : job_ids));
                } else
                if ($(this).attr("data-input-class") == 'project_id') {
                    input = $("input.project_id", tr);
                    build_select2(input, "ACCAjax/projectSearch")
                } else
                if ($(this).attr("data-input-class") == 'ref_type') {
                    input = $("input[name=ref_type]", tr);
                    build_select2(input, "xhr/CommonSearch?col_id=subtype_abbrv&col_name=subtype_abbrv&table=tbl_accounting_transaction_subtype")
                } else {
                    var td = $(this).parents('td');
                    input = td.find('input.' + $(this).attr("data-input-class"));
                    input.attr("type", "text")
                }
                if (e.type == 'focus')
                    input.focus();
                $(this).remove();
            });
        }
//        $("#JVTable").on("focusout", "input.Amount", function () {
//            var tr = $(this).parents("tr");
//            $(".close_jv", tr).addClass("hidden")
//        })
        $("#JVTable").on("focus", "input.Amount", function () {
            $(".close_jv").addClass("hidden")
            var tr = $(this).parents("tr"),
                    length = $("#JVTable tbody tr:not([data-account=''])").not(tr).length;
            if (length > 0) {
                $(".close_jv", tr).removeClass("hidden")
            }
        })
        $("#JVTable").on("click", ".close_jv", function () {
            var tr = $(this).parents("tr"),
                    amount_elem = $("input.Amount", tr),
                    rate = $(".exchange", tr).val() != '' ? parseFloat($(".exchange", tr).val()) || 0 : parseFloat(tr.attr("local-rate")) || 0;
//            if (local_amount == 0 && second_amount == 0)
//                return;
            var totalBalance = 0, totalCredit = 0, totalDebit = 0, totalBalanceSecond = 0, totalCreditSecond = 0, totalDebitSecond = 0;

            $("#JVTable input.Amount").not(amount_elem).each(function () {
                var cur_tr = $(this).parents("tr");
                var cur_amount = cur_tr.find(".Amount").val() || 0,
                        cur_local_amount = cur_tr.find(".amt_local").val() || 0,
                        cur_second_amount = cur_tr.find(".amt_second").val() || 0,
                        type = cur_tr.find('select.Transaction').val() || 0;
                if (cur_amount != "") {
                    if (type == 'Credit') {
                        totalCredit += parseFloat(cur_local_amount);
                        totalCreditSecond += parseFloat(cur_second_amount);
                    } else
                    if (type == 'Debit') {
                        totalDebit += parseFloat(cur_local_amount);
                        totalDebitSecond += parseFloat(cur_second_amount);
                    }
                }

            })
            totalBalance = totalDebit - totalCredit;
            totalBalanceSecond = totalDebitSecond - totalCreditSecond;
//            console.log(totalBalance.toXFixed(3) + '====' + totalBalanceSecond.toXFixed(3))
            if (totalBalance > 0)
                $("select.Transaction", tr).val('Credit').select2().trigger("change")
            else
                $("select.Transaction", tr).val('Debit').select2().trigger("change")

            $("input.amt_second", tr).val(Math.abs(public_round_number(totalBalanceSecond)))
            $("input.amt_local", tr).val(Math.abs(public_round_number(totalBalance)))
            $("input.Amount", tr).val(Math.abs(public_round_number(totalBalance / rate)))//.trigger("input")
//                    build_tr_total(tr)
            refreshTotals()

        })
        $("#inv_body").on("click", ".rem", function () {
            var input = $(this).parents(".my_tr").find("input");
            input.val(input.attr("data-max")).trigger("keyup")
        })

        $("#ClearInv").on("click", function () {
            $("#inv_body input").val("").trigger("keyup")
        })

        $("#JVTable").on("click", ".get_inv", function () {
            var tr = $(this).parents("tr");
            selected_tr = tr;
            $("#invoice_modal input").val("")
            if (($("#invoice_modal").attr("data-customer") != "" && $("#invoice_modal").attr("data-customer").trim() == tr.attr("data-account").trim())
                    && ($("#invoice_modal").attr("data-currency") != "" && $("#invoice_modal").attr("data-currency").trim() == $("select.Currency_ID", tr).val().trim())) {
                if (selected_tr.attr("data-invs") != undefined && selected_tr.attr("data-invs") != '') {
                    var inv_data = JSON.parse(selected_tr.attr("data-invs"));
                    $.each(inv_data, function (indx, value) {
                        $("#inv_body .my_tr[data-id=" + value['inv_id'] + "] input").val(value['inv_amount'])
                    })
                }
                $("#invoice_modal").modal("show")
                //                alert()
                return false
            }
            //            alert()
            $("#InvoicesTotal").html('0')
            $("#invoice_modal").attr("data-customer", tr.attr("data-account"))
            $("#invoice_modal").attr("data-currency", $("select.Currency_ID", tr).val())
            $.ajax({
                url: "ACCAjax/getUnpaidInvoicesByCustomer",
                method: "GET",
                data: {account: tr.attr("data-account"), currency: $("select.Currency_ID", tr).val(), is_actual: (is_actual ? 1 : 0), type: (tr.attr("data-acc-type") == "cust" ? "cmjv" : "smjv"), is_receipt: (tr.attr("data-acc-type") == "cust" ? 1 : 0), record_id: (IsEditMode ? selected_tr.attr("data-trans-id") : 0)},
                dataType: 'json',
                complete: function (v1, v2) {
                    if (v2 == 'success') {
                        $("#inv_body").empty()
                        var data = v1.responseJSON;
                        //inv_body
                        var TR = '';
                        var symbol = $("select.Currency_ID option:selected", tr).attr("mysymbol");
                        for (var i = 0; i < data.length; i++) {
                            TR += '<div class="row m-b-10 my_tr" data-id="' + data[i]['Invoice_ID_Auto'] + '" data-cur = "' + data[i]['Invoice_Currency'] + '" data-rem-local="' + data[i]['remaining_local'] + '">' +
                                    '<div class="col-md-1">' + data[i]['Invoice_ID'] + '</div>' +
                                    '<div class="col-md-2">' + data[i]['Invoice_Date'] + '</div>' +
                                    '<div class="col-md-2">' + AddCommas(public_round_number(parseFloat(data[i]['Invoice_Net_Total']))) + ' ' + symbol + '</div>' +
                                    '<div class="col-md-2 rem" ><span class="rem_div">' + AddCommas(public_round_number(parseFloat(data[i]['Remaining_Amount']))) + '</span> ' + symbol + '</div>' +
                                    '<div class="col-md-2"><input type="text" class="form-control" data-max="' + data[i]['Remaining_Amount'] + '" /></div>' +
                                    '<div class="col-md-2 balance" >' + AddCommas(public_round_number(parseFloat(data[i]['Remaining_Amount']))) + ' ' + symbol + '</div></div>';
                        }
                        TR = $(TR)
                        $("#inv_body").append(TR)
//                        console.log(selected_tr.attr("data-invs"))
                        if (selected_tr.attr("data-invs") != undefined && selected_tr.attr("data-invs") != '') {
                            var inv_data = JSON.parse(selected_tr.attr("data-invs"));
//                            console.log(inv_data)
                            $.each(inv_data, function (indx, value) {
                                $("#inv_body .my_tr[data-id=" + value['inv_id'] + "] input").val(value['inv_amount'])
                                var max = parseFloat($("#inv_body .my_tr[data-id=" + value['inv_id'] + "] input").attr("data-max")) || 0,
                                        new_max = (IsEditMode ? (parseFloat(value['inv_amount']) || 0) : 0) + max,
                                        new_rem = (IsEditMode ? max : max - value['inv_amount']);
                                $("#inv_body .my_tr[data-id=" + value['inv_id'] + "] input").attr("data-max", new_max)
                                $("#inv_body .my_tr[data-id=" + value['inv_id'] + "] span.rem_div").text(AddCommas(public_round_number(new_max)))
                                $("#inv_body .my_tr[data-id=" + value['inv_id'] + "] .balance").text(AddCommas(public_round_number(new_rem)) + ' ' + symbol)

                            })
                        }
                        $("#invoice_modal").modal("show")

                    }
                }
            })
        })

        $("#CloseInv").on("click", function () {
            var data = [], total = 0;
            $(".my_tr").each(function () {
                var tr = $(this);
                if (tr.find("input").val() != '' && tr.find("input").val() != 0) {
                    total += parseFloat(tr.find("input").val()) || 0;
                    data.push({
                        inv_id: tr.attr("data-id"),
                        inv_amount: tr.find("input").val(),
                        inv_currency: tr.attr("data-cur"),
                        local_rem: tr.attr("data-rem-local")

                    });
                }

            })
            selected_tr.attr("data-invs", JSON.stringify(data));
            selected_tr.attr("data-total-inv", total);
        })

        $("#inv_body").on("keyup", "input", function () {
            var symbol = $("select.Currency_ID option:selected", selected_tr).attr("mysymbol");
            var amount = parseFloat($(this).val()) || 0,
                    max_amount = parseFloat($(this).attr("data-max"));
            $(this).parents(".my_tr").find(".balance").html(AddCommas(public_round_number(parseFloat(((max_amount - amount) || 0)))) + ' ' + symbol)

            if (amount > max_amount || amount < 0) {
                $(this).addClass("wrong")

            } else {
                $(this).removeClass("wrong")
            }
            var tr_total = 0, validate = true;
            $("#inv_body input").each(function () {
                tr_total += parseFloat($(this).val()) || 0;
                if ($(this).hasClass("wrong"))
                    validate = false;
            })
            if (!validate) {
                $("#CloseInv").attr("disabled", "disabled")
                $("#close_modal").addClass("hidden")
            } else {
                $("#CloseInv").removeAttr("disabled")
                $("#close_modal").removeClass("hidden")


            }
//            $("#InvoicesTotal").html(AddCommas(parseFloat(tr_total).toFXixed(3)))
        })
        $("#JVTable").on("focus", ".AutoComplete.AccountName:not(.autocomplete_done),.AutoComplete.CODE:not(.autocomplete_done)", function () {
//            console.log('here')
            //            if(!$(this).addClass("autocomplete_done"))
            EnableAutoComplete($(this));
            $(this).addClass("autocomplete_done")
        })
        $("#JVTable ").on("click", ".deleteRowRequest", function () {//to delete a row
            var numItems = $('#JVTable tr').length; //number of rows
            if (numItems > 2) {//only if number of rows is more than one row remove the deleted row
                $(this).parents("tr").remove()
            }
            refreshTotals();
        })
        build_select2($("#branch_id"), "xhr/CommonSearch?col_id=branch_id&col_name=branch_name&table=tbl_organization_branches")
        $("#Date_Transaction,.due_date").datepicker({autoclose: true})
        $("#JVTable tbody").delegate("> tr input", "keydown", function (e) {
            var me = $(this)
            if (e.which == 8) {
                if (me.val() == "" && !me.hasClass("CODE")) {
                    me.parents("td").prev().find("input").focus()
                } else if (me.val() == "" && me.hasClass("CODE")) {
                    if (me.parents("tr").prev()) {
                        me.parents("tr").prev().find(".Amount").focus()
                    }
                }
            }
        })
        $("#JVTable ").on("click", ".addRowRequest", function () {//to delete a row
            // var numItems = $('#JVTable tr').length; //number of rows
            // if (numItems > 2) {//only if number of rows is more than one row remove the deleted row
            //     $(this).parents("tr").remove()
            // }
             var me = $(this), Parent = me.parents(".AddRow"), IsLastOneEmpty = true;
                var ClonedRow =  Parent.clone().insertAfter(Parent);
                $(".select2-container", ClonedRow).remove()
                ClonedRow.find("input").val("")
                ClonedRow.find("textarea.Description").val("")
                ClonedRow.find("input.AutoComplete").removeClass("autocomplete_done")
                ClonedRow.attr("local-rate", "").attr("second-rate", "").attr("data-invs", "").attr("data-total-inv", "0").attr("data-trans-id", "")
                ClonedRow.find(".get_inv").addClass("hidden")
                // Parent.append(ClonedRow);
                ClonedRow.removeAttr('data-account')
                EnableAutoComplete($(".AutoComplete.CODE", ClonedRow).removeClass("AutoAdded"));
                EnableAutoComplete($(".AutoComplete.AccountName", ClonedRow).removeClass("AutoAdded"));
                build_select2($("input[name=job_id]", ClonedRow), "ACCAjax/JobSearch")
                build_select2($("input[name=project_id]", ClonedRow), "ACCAjax/projectSearch")
                build_select2($("input[name=ref_type]", ClonedRow), "xhr/CommonSearch?col_id=subtype_abbrv&col_name=subtype_abbrv&table=tbl_accounting_transaction_subtype")
                $(".due_date", ClonedRow).datepicker({autoclose: true})
                $("input", ClonedRow).removeClass("wrong")
                $("input.exchange", ClonedRow).removeAttr("disabled", "disabled")
                $("select.Transaction", ClonedRow).show().select2()
                $("select.Currency_ID", ClonedRow).show().select2().trigger("change")
                ClonedRow.find(".select2-container").show()
             
            //
            
            //
            refreshTotals()
            // refreshTotals();
        })

        //
        $("#JVTable tbody").on("keyup", ".exchange,.amt_local,.amt_second,.ex_second", function (e) {
            var tr = $(this).parents("tr"),
                    cur_val = parseFloat($(this).val()),
                    cur_amount = parseFloat(tr.find(".Amount").val() || 0);
            if ($(this).hasClass("exchange")) {
                tr.find(".amt_local").val(parseFloat(public_round_number((!isNaN(cur_val) ? cur_val : parseFloat(tr.attr("local-rate"))) * cur_amount)))
            } else if ($(this).hasClass("ex_second")) {
                tr.find(".amt_second").val(parseFloat(public_round_number((!isNaN(cur_val) ? cur_val : parseFloat(tr.attr("second-rate")) /*|| parseFloat(tr.attr("second-rate"))*/) * cur_amount)))
            } else if ($(this).hasClass("amt_local")) {
                //                if (tr.find(".exchange").val() == '') {
                //                    tr.find(".Amount").val(parseFloat(parseFloat(tr.find(".amt_local").val() / tr.attr("local-rate")).toXFixed(3)))
                //                    tr.find(".amt_second").val(parseFloat((tr.attr("second-rate") * tr.find(".Amount").val()).toXFixed(3)))
                //                    tr.attr("local-rate", (cur_val / cur_amount))
                //                } else {
                tr.find(".exchange").val((cur_val || 0) / cur_amount);
                //                }
            } else if ($(this).hasClass("amt_second")) {
                //                if (tr.find(".exchange").val() == '') {
                //                    tr.find(".Amount").val(parseFloat(parseFloat(tr.find(".amt_second").val() / tr.attr("second-rate")).toXFixed(3)))
                ////                    tr.find(".amt_local").val(parseFloat((tr.attr("local-rate") * tr.find(".Amount").val()).toXFixed(3)))
                //                    tr.attr("second-rate", (cur_val / cur_amount))
                //                } else {
                tr.find(".ex_second").val((cur_val || 0) / cur_amount);
                //
                //                }
            }
            refreshTotals()
        })
        $("#JVTable tbody").on("change", ".exchange,.amt_local,.amt_second,.ex_second,.Amount", function (e) {
            var tr = $(this).parents("tr");
            tr.find(".Amount").val(public_round_number(parseFloat(tr.find(".Amount").val())))
            tr.find(".exchange").val(public_round_number(parseFloat(tr.find(".exchange").val())))
            tr.find(".amt_local").val(public_round_number(parseFloat(tr.find(".amt_local").val())))
            tr.find(".amt_second").val(public_round_number(parseFloat(tr.find(".amt_second").val())))
            tr.find(".ex_second").val(public_round_number(parseFloat(tr.find(".ex_second").val())))

            refreshTotals()
        })


        $("#JVTable tbody").on("change", "select.Currency_ID", function (e) {
            var me = $(this).parents("tr"), amount = (parseFloat(me.find(".Amount").val()) || 0);
//            console.log(me.attr("data-invs"))
            if (me.attr("data-invs") != '' && me.attr("data-invs") != undefined)
                toastr.error('<?php echo CommonLanguage::getMessage('change_amounts') ?>');
            me.attr("data-invs", "").attr("data-total-inv", "0")

            if ($(this).val() == PrimaryCurrencyID) {
                $('input.exchange', me).val("1").attr("disabled", "disabled")
                $('input.amt_local', me).val(amount).attr("disabled", "disabled")
                $('input.ex_second,input.amt_second', me).val("").removeAttr("disabled")
            } else {
                $('input.exchange,input.amt_local', me).removeAttr("disabled")
            }
            if ($(this).val() == second_currency_id) {
                $('input.ex_second', me).val("1").attr("disabled", "disabled")
                $('input.amt_second', me).val(amount).attr("disabled", "disabled")
                $('input.exchange,input.amt_local', me).val("").removeAttr("disabled")
            } else {
                $('input.ex_second,input.amt_second', me).removeAttr("disabled")
            }
            $.ajax({
                url: "ACCAjax/get_jv_exchange_rate",
                method: "GET",
                dataType: "json",
                data: {currency_id: $(this).val()},
                complete: function (v1, v2) {
                    if (v2 == "success") {
                        var data = v1.responseJSON;
                        me.attr("local-rate", (data['local'][1] === '*' ? data['local'][0] : 1 / data['local'][0]) || 0)
                        me.attr("second-rate", (data['second'][1] === '*' ? data['second'][0] : 1 / data['second'][0]) || 0)
                        build_tr_total(me)
                        refreshTotals()
                    }
                }
            })
        })
        //
        $("#JVTable tbody").delegate("> tr input.Amount", "keyup", function (e) {
            var me = $(this), Parent = me.parents("tbody"), IsLastOneEmpty = true;
            $("tr", Parent).each(function (e) {
                if ($("tr", Parent).length > 1) {
                    var IsEmpty = true;
                    $(this).find("input.Amount").each(function () {
                        if ($(this).val() != "" || $(this).parents("tr").attr("data-account") != ''
                                || $(this).parents("tr").find(".CODE").val() != '' || $(this).parents("tr").find(".AccountName").val() != '')
                            IsEmpty = false;
                    })
                    if (IsEmpty == true) {
                        if ($(this).index() <= $("#JVTable tbody tr").length - 2) {
                            me.parents("tr").prev().find(".Amount").focus()
                            $(this).remove();
                        }
                    }
                }
            })
            $("tr:last-child input.Amount", Parent).each(function (e) {
                if ($(this).val() != "")
                    IsLastOneEmpty = false;
            })
            if (IsLastOneEmpty == false) {
                var ClonedRow = $("tr:first-child", Parent).clone()
                $(".select2-container", ClonedRow).remove()
                ClonedRow.find("input").val("")
                ClonedRow.find("input.AutoComplete").removeClass("autocomplete_done")
                ClonedRow.attr("local-rate", "").attr("second-rate", "").attr("data-invs", "").attr("data-total-inv", "0").attr("data-trans-id", "")
                ClonedRow.find(".get_inv").addClass("hidden")
                Parent.append(ClonedRow);
                ClonedRow.removeAttr('data-account')
                EnableAutoComplete($(".AutoComplete.CODE", ClonedRow).removeClass("AutoAdded"));
                EnableAutoComplete($(".AutoComplete.AccountName", ClonedRow).removeClass("AutoAdded"));
                build_select2($("input[name=job_id]", ClonedRow), "ACCAjax/JobSearch")
                build_select2($("input[name=project_id]", ClonedRow), "ACCAjax/projectSearch")
                build_select2($("input[name=ref_type]", ClonedRow), "xhr/CommonSearch?col_id=subtype_abbrv&col_name=subtype_abbrv&table=tbl_accounting_transaction_subtype")
                $(".due_date", ClonedRow).datepicker({autoclose: true})
                $("input", ClonedRow).removeClass("wrong")
                $("input.exchange", ClonedRow).removeAttr("disabled", "disabled")
                $("select.Transaction", ClonedRow).show().select2()
                $("select.Currency_ID", ClonedRow).show().select2().trigger("change")
                ClonedRow.find(".select2-container").show()
            }
            //
            var tr = me.parents("tr");
            build_tr_total(tr)
            //
            refreshTotals()
        })
        //        $("#JVTable tbody").delegate("> tr select.Currency_ID", "change", function (e) {
        //            if ($(this).val() == PrimaryCurrencyID) {
        //                $(this).parents("tr").find('input.exchange').attr("disabled", "disabled")
        //            } else {
        //                $(this).parents("tr").find('input.exchange').removeAttr("disabled", "disabled")
        //            }
        //            refreshTotals()
        //        })
        if (IsEditMode) {
            //            $("#JVTable tbody tr").each(function () {
            //                build_tr_total($(this))
//            refreshTotals()
            //            })
            //            refreshTotals()
            //            $("#JVTable tbody tr input.Amount").trigger('keyup')
            //            $("#JVTable tbody tr input.Amount,#JVTable tbody tr input.exchange,#JVTable tbody tr input.ex_second").trigger('keyup')
            //            $("#JVTable tbody tr select.Currency_ID").trigger("change")
        }
        $("#JVTable tbody").on("change", "tr select.Transaction", function () {
            var tr = $(this).parents('tr');
            if (($(this).val() === 'Credit' && tr.attr("data-acc-type") === 'cust' && tr.attr("data-acc-sub") === 'main') || ($(this).val() === 'Debit' && tr.attr("data-acc-type") === 'supp' && tr.attr("data-acc-sub") === 'main'))
                $(".get_inv", tr).removeClass("hidden")
            else
                $(".get_inv", tr).addClass("hidden")
            if (tr.attr("data-invs") != '' && tr.attr("data-invs") != undefined)
                toastr.error('<?php echo CommonLanguage::getMessage('change_amounts') ?>');
            tr.attr("data-invs", "").attr("data-total-inv", "0")

            refreshTotals()
        })
        $("#PrintBtn").on("click", function () {
            var myurl = "ACC/ViewJV" + (is_actual == 0 ? '' : '/act') + "/" + ID_Edit;
            printExternal(myurl)
        })
    })
    $("#fill_user_ref").on("click", function () {
        $("#JVTable tbody tr:not(:last) input.user_ref").val($("#jv_note").val())
    })
    $("#JVSubmitButton").on("click", function () {
        $("#JVSubmitButton").attr("disabled", "disabled")
        $(".wrong").removeClass("wrong")
        submitted = true;
        
 

        if (parseFloat($("#totalBalance").html().replace(/,/g, "")) != 0) {
            $("#JVSuccess").attr("class", "alert alert-danger").html(zero_balance)
            $("#JVSubmitButton").removeAttr("disabled")
            $(document.body).animate({scrollTop: 0}, 800)
            return false;
        }
        if (parseFloat($("#totalBalanceSecond").html().replace(/,/g, "")) != 0 && activate_second_currency == 1) {
            $("#JVSuccess").attr("class", "alert alert-danger").html(zero_balance)
            $("#JVSubmitButton").removeAttr("disabled")
            $(document.body).animate({scrollTop: 0}, 800)
            return false;
        }
        var valid_form=false;
        var Data = {
            Transaction_Date: $("#Date_Transaction").val(),
            unique_id: unique_id,
            is_actual: is_actual,
            JV_ID: ID_Edit,
            branch_id: $("#branch_id").val(),
            jv_note: $("#jv_note").val(),
            Accounts: []
        };
        var check_job_required = false, validate = true, validate_inv = true, inv_arr = {cust: [], supp: []}, validate_inv_amt = true;
        $("#JVTable tbody tr").each(function (e) {
            var me = $(this);
//            if (e < $(this).parent().children().length - 1) {

             if (me.find(".Amount").val() != '' && me.attr('data-account') != '' && me.attr('data-account') != 0 && me.attr('data-account') != undefined) {
                Data.Accounts.push({
                    Transaction_Description: me.find(".Description").val(),
                    Transcation_Type: me.find("select.Transaction").val(),
                    Transcation_Account: me.find(".CODE").val(),
                    Account_ID: me.attr('data-account'),
                    Currency_ID: me.find(".Currency_ID option:selected").val(),
                    Current_Ex_Rate: ((me.find(".exchange").val() || IsEditMode) ? me.find(".exchange").val() : me.attr("local-rate")),
                    second_currency_rate: ((me.find(".ex_second").val() || IsEditMode) ? me.find(".ex_second").val() : me.attr("second-rate")),
                    Transcation_Amount: me.find(".Amount").val(),
                    Transaction_Reference: me.find('.ref_nb').val(),
                    user_ref: me.find('.user_ref').val(),
                    due_date: (me.find('.due_date').val() ? me.find('.due_date').val() : $("#Date_Transaction").val()),
                    job_id: me.find('input[name=job_id]').val(),
                    project_id: me.find('input[name=project_id]').val(),
                    subtype: me.find('input[name=ref_type]').val(),
                    main_id: me.attr('data-id'),
                    main_type: me.attr('data-type'),
                    close_arr: me.attr("data-invs"),
                    acc_type: me.attr("data-acc-type"),
                    transaction_id: me.attr("data-trans-id")
                })
                if (me.attr("data-job-required") == 1 && (me.find('input[name=job_id]').val() == '' || me.find('input[name=job_id]').val() == 0) && activate_job == 1) {
                    me.find('div.job_id').addClass("wrong")
                    check_job_required = true;
                }
                if ((parseFloat(me.attr("data-total-inv")) || 0) > (parseFloat(me.find(".Amount").val()))) {
                    me.find('.Amount').addClass("wrong")
                    validate_inv = false;
                }
                if (me.attr("data-invs") != '' && me.attr("data-invs") != undefined) {
                    var temp_inv = JSON.parse(me.attr("data-invs")),
                            type = me.attr("data-acc-type");
                    $.each(temp_inv, function (indx, row) {
                        var inv_amt = (parseFloat(row['inv_amount']) || 0),
                                rate = $("input.exchange", me).val() == '' ? (parseFloat(me.attr("local-rate")) || 0) : (parseFloat($("input.exchange", me).val()) || 0),
                                local_amt = inv_amt * rate;
                        if (row['inv_id'] in inv_arr[type])
                            inv_arr[type][row['inv_id']] += local_amt
                        else
                            inv_arr[type][row['inv_id']] = local_amt
                        if (inv_arr[type][row['inv_id']] > (parseFloat(row['local_rem']) || 0)) {
                            me.find('.Amount').addClass("wrong")
                            validate_inv_amt = false;
                        }
                    })
                }
            } else if ((parseFloat(me.find(".Amount").val()) || 0) > 0) {
                validate = false;
            }
            if(me.find(".Amount").val() == '' && me.find(".CODE").val() == '' && me.find(".AccountName").val() == ''){
                console.log('');
            }
            else if(me.find(".Amount").val() == '' || (me.find(".CODE").val() == '' && me.find(".AccountName").val() == '') ){
                valid_form=true;
            }
        })
        if(valid_form){
            $("#JVSuccess").attr("class", "alert alert-danger").html(Failed_Submit)
                $("#JVSubmitButton").removeAttr("disabled")
                $("#JVSubmitButton").removeClass("permanent_disable")

            return false;

        }
       console.log('test');
//        return;
        if (!validate_inv_amt) {
            $("#JVSuccess").attr("class", "alert alert-danger").html('<?php echo CommonLanguage::getMessage('check_pay_inv_rem_amounts') ?>')
            $("#JVSubmitButton").removeAttr("disabled")
            $(document.body).animate({scrollTop: 0}, 800)
            return false;
        }
        if (!validate) {
            $("#JVSuccess").attr("class", "alert alert-danger").html('<?php echo CommonLanguage::getMessage('Required_Fields') ?>')
            $("#JVSubmitButton").removeAttr("disabled")
            $(document.body).animate({scrollTop: 0}, 800)
            return false;
        }
        if (!validate_inv) {
            $("#JVSuccess").attr("class", "alert alert-danger").html('<?php echo CommonLanguage::getMessage('check_pay_amounts') ?>')
            $("#JVSubmitButton").removeAttr("disabled")
            $(document.body).animate({scrollTop: 0}, 800)
            return false;
        }
        if (check_job_required) {
            $("#JVSuccess").attr("class", "alert alert-danger").html(job_required_alert)
            $("#JVSubmitButton").removeAttr("disabled")
            $(document.body).animate({scrollTop: 0}, 800)
            return false;
        }

        $.ajax({
            url: (IsEditMode && !is_copy) ? "ACCAjax/editJVAjax" : "ACCAjax/addJVAjax",
            method: "POST",
            data: Data,
            dataType: "json",
            complete: function (v1, v2) {
                var response = v1.responseJSON;
                if (v2 == "success") {
                    if (response[0] == "OK") {
                        ID_Edit = response[1];
                        $("#PrintBtn").removeClass("disabled");
                        $("#JVSuccess").attr("class", "alert alert-success").html(Submitted_Successfully + '&nbsp;<strong>' + '<?php echo CommonLanguage::getMessage('jv') ?>' + '# ' + response[1])
                        $("#JVSubmitButton").addClass("permanent_disable")
//                        $("#JVSubmitButton").attr("disabled","disabled")

                    } else {
                        $("#JVSuccess").attr("class", "alert alert-danger").html(v1.responseText)
                        $("#JVSubmitButton").removeAttr("disabled")
                        $("#JVSubmitButton").removeClass("permanent_disable")
                    }
                } else {
                    $("#JVSuccess").attr("class", "alert alert-danger").html(Failed_Submit)
                    $("#JVSubmitButton").removeAttr("disabled")
                    $("#JVSubmitButton").removeClass("permanent_disable")
                }
                $(document.body).animate({scrollTop: 0}, 800)
            }
        })
    })
    function refreshTotals() {
        $("#JVSubmitButton").attr("disabled", "disabled");  //disale submit button since in large rows it take time
        var totalBalance = 0, totalCredit = 0, totalDebit = 0, totalBalanceSecond = 0, totalCreditSecond = 0, totalDebitSecond = 0;
        $("#JVTable input.Amount").each(function () {
            var tr = $(this).parents("tr");
            var amount = tr.find(".Amount").val() || 0,
                    local_amount = tr.find(".amt_local").val() || 0,
                    second_amount = tr.find(".amt_second").val() || 0,
                    //                    exchange = $(this).parents("tr").find(".exchange").val(),
                    type = tr.find('select.Transaction').val() || 0;
            //                    CurrentCurrency = $(this).parents('tr').find('select.Currency_ID').val();
            //            if ($(this).parents("tr").find(".exchange").val() == "") {
            //
            //                CurVal = parseFloat(ConvertCurrency2(amount, CurrentCurrency, 84)) || 0;
            //            } else {
            //                CurVal = parseFloat(CurrentCurrency == 84 ? amount : amount * exchange);
            //            }
            if (amount != "") {
                if (type == 'Credit') {
                    totalCredit += parseFloat(local_amount);
//                    totalBalance -= parseFloat(local_amount);
                    totalCreditSecond += parseFloat(second_amount);
//                    totalBalanceSecond -= parseFloat(second_amount);
                } else
                if (type == 'Debit') {
                    totalDebit += parseFloat(local_amount);
//                    totalBalance += parseFloat(local_amount);
                    totalDebitSecond += parseFloat(second_amount);
//                    totalBalanceSecond += parseFloat(second_amount);
                }
            }

        })
        totalBalance = totalDebit - totalCredit;
        totalBalanceSecond = totalDebitSecond - totalCreditSecond;
//        console.log(totalCredit+'==='+totalDebit)
        $('#totalCredit').text(AddCommas(public_round_number(totalCredit)))
        $('#totalDebit').text(AddCommas(public_round_number(totalDebit)))
        $('#totalBalance').text(AddCommas(public_round_number(totalBalance))).attr("data-total", public_round_number(totalBalance))
        $('#totalCreditSecond').text(AddCommas(public_round_number(totalCreditSecond)))
        $('#totalDebitSecond').text(AddCommas(public_round_number(totalDebitSecond)))
        $('#totalBalanceSecond').text(AddCommas(public_round_number(totalBalanceSecond))).attr("data-total", public_round_number(totalBalanceSecond));
        if (!$("#JVSubmitButton").hasClass("permanent_disable"))
            $("#JVSubmitButton").removeAttr("disabled");
    }
    function build_tr_total(tr) {
        var second_rate_input = parseFloat(tr.find(".ex_second").val()),
                local_rate_input = parseFloat(tr.find(".exchange").val()),
//                local_rate = ((parseFloat(tr.find(".exchange").val()) || 0) == 0 ? parseFloat(tr.attr("local-rate") || 0) : parseFloat(tr.find(".exchange").val())),
                second_rate = (isNaN(second_rate_input) ? parseFloat(tr.attr("second-rate") || 0) : parseFloat(tr.find(".ex_second").val())),
                local_rate = (isNaN(local_rate_input) ? parseFloat(tr.attr("local-rate") || 0) : parseFloat(tr.find(".exchange").val())),
                cur_amount = parseFloat(tr.find("input.Amount").val() || 0);
        tr.find(".amt_local").val(public_round_number(parseFloat((local_rate * cur_amount))))
        console.log(second_rate + '===' + cur_amount)
        tr.find(".amt_second").val(public_round_number(parseFloat((second_rate * cur_amount))))
    }
    function EnableAutoComplete(who) {
        if (!who.hasClass("AutoAdded")) {
            who.autocomplete({
                source: function (request, response) {
                    var row_id = who.attr('data-account');
                    $.getJSON('xhr/ajaxAccount?cmd=' + (who.hasClass("CODE") ? "1" : "2") + (!IsEditMode ? '&Status_ID=1' : 'is_edited=' + row_id), request, function (s, status, xhr) {
                        response(s);
                    });
                },
                minLength: 0,
                select: function (event, ui) {
                    var TR = $(this).parents("tr");
                    TR.attr("data-account", ui.item.Account_ID)
                    TR.attr("data-acc-type", ui.item.main_type)
                    TR.attr("data-acc-sub", ui.item.sub_type)
//                    console.log(ui.item.main_type +'===='+$("select.Transaction").val())
                    if ((ui.item.main_type == 'cust' && $("select.Transaction", TR).val() === 'Credit') || (ui.item.main_type == 'supp' && $("select.Transaction", TR).val() === 'Debit'))
                        $(".get_inv", TR).removeClass("hidden")
                    else
                        $(".get_inv", TR).addClass("hidden")
                    //
//                    if (TR.attr("data-invs") != '' || TR.attr("data-invs") != undefined)
//                        toastr.error('<?php echo CommonLanguage::getMessage('change_amounts') ?>');
//                    TR.attr("data-invs", "")

                    TR.attr("data-total-inv", "0")
                    TR.attr("data-jobs", ui.item.job_ids)
                    TR.attr("data-job-required", ui.item.job_required)
                    TR.find("input.CODE").val(ui.item.Account_Code)
                    TR.find("input.AccountName").val(ui.item.Account_Name + (ui.item.Currency_Symbol != null && ui.item.Currency_Symbol != '' ? ' - ' + ui.item.Currency_Symbol : ''));
                    TR.find("select.Currency_ID").val(ui.item.Currency_ID != 0 ? ui.item.Currency_ID : PrimaryCurrencyID).select2().trigger("change")
                    $("input[name=job_id]", TR).val('').attr('data-select-name', '')
                    build_select2($("input[name=job_id]", TR), "ACCAjax/JobSearch?job_ids=" + ui.item.job_ids)
                    $("span[data-input-class=job_id]", TR).remove()
                    return false;
                }
            }).focus(function () {
                $(this).autocomplete("search", $(this).val());
            }).autocomplete("instance")._resizeMenu = function (ul, items) {
                this.menu.element.outerWidth((who.width() * 5) + parseFloat(who.css("padding-left")) + parseFloat(who.css("padding-right")) + 2);
            }
            who.autocomplete("instance")._renderItem = function (ul, item) {
                var MyType = (item.Account_Code + ' - ' + item.Account_Name + (item.Currency_Symbol != null && item.Currency_Symbol != '' ? ' - ' + item.Currency_Symbol : ''));
                return $("<li>").html("<table cellspacing='0' cellpadding='0'><tr><td class='OnlyText'>" + MyType + "</td></tr></table>").appendTo(ul)
            }
            who.addClass("AutoAdded")
        }
    }
    window.onbeforeunload = function (e) {
        return have_not_finish;
    }
    var submitted = false;
    $(document).ready(function () {
        window.onbeforeunload = function (e) {
            if (!submitted) {
                var message = have_not_saved, e = e || window.event;
                if (e) {
                    e.returnValue = message;
                }
                return message;
            }
        }
    });
</script>
<?php
include 'Views/Settings/supplier-customer-account-button-modal.php';

