<?php
if ($is_edit && $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 ($is_edit && empty($edit_data['details'])) {
?>
<div class="alert alert-danger" role="alert">
    <button class="close"  data-dismiss="alert"></button>
    <strong>Danger: </strong>you can not edit this project expense! 
    <br>
    This project expense is not available.
</div>
<?php
    return;
}
?>
<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;
    padding:0 !important;
    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;
    }
    */
    .diff_class{
        width:600px!important;
    }
</style>
<script src="<?php echo THEME_PATH; ?>plugins/jquery-validation/js/jquery.validate.min.js"></script>
<form method="POST" action="" onsubmit="return false" id="PaymentForm">
    <div class="container-fluid container-fixed-lg">
        <div class="panel panel-default">
            <div class="panel-body">
                <div id="paymentAlert"></div>
                <div class="invoice">
                    <div class="container-sm-height">
                        <input type="hidden" id="project_expense_id" name="project_expense_id" value="<?php echo $project_expense_id; ?>" />
                        <div class="row-sm-height">
                            <div class="col-md-9 col-sm-height sm-no-padding form-group">
                                <div class="input-group  col-md-8 center-margin pull-left" >
                                    <div class="sm-m-t-20">
                                        <h2 class="font-montserrat all-caps hint-text"><?php print $title; ?></h2>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                                <div class=" col-md-6">
                                    <label>
                                        <?php echo CommonLanguage::getMessage('project_period'); ?><span class="red-star">*</span>
                                    </label>
                                    <input class=" full-width" id="period_id" name="period_id" type="hidden"   value="<?php echo $is_edit ? $edit_data['main']['period_id'] : ''; ?>" data-select-name="<?php echo $is_edit ? ($edit_data['main']['period_title'] . ' - ' . $edit_data['main']['project_name'] . ' (' . $edit_data['main']['start_date'] . ' ' . $edit_data['main']['end_date'] . ')') : ''; ?>" required/>
                                </div> 
                                <div class=" col-md-6">
                                    <label><?php echo CommonLanguage::getMessage('supplier') ?><span class="red-star">*</span></label>
                                    <input id="supplier_id" name="supplier_id" type="hidden" class="full-width" value="<?php echo $is_edit ? $edit_data['main']['supplier_id'] : '' ?>" data-select-name='<?= json_encode($is_edit ? $edit_data['main']['Supplier_Name'] : '') ?>' required/>
                                </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">
                                    <input type="hidden" value="<?php echo $is_edit ? $edit_data['main']['project_expense_nb'] : '' ?>" id="project_expense_nb" name="project_expense_nb" />
                                    <h4> # <?php
    if (!$is_edit) {
        echo'--';
    } else {
        echo $edit_data['main']['project_expense_nb'];
    }
                                        ?></h4>
                                </div>
                                <div class="form-group col-md-12 p-l-0">
                                    <label ><?php print CommonLanguage::getMessage('Date'); ?></label>
                                    <input id="PaymentDate" name="PaymentDate" class="form-control" value="<?php echo $is_edit ? $edit_data['main']['project_expense_date'] : $today; ?>" aria-required="true" aria-invalid="false">
                                </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 $is_edit ? ($edit_data['main']['Currency_Name'] . ' - ' . $edit_data['main']['Currency_Symbol']) : $currency_symbol ?></span>
                                                <input type="hidden" name="Currency_ID" value="<?php echo $is_edit ? $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 style="width: 48%;margin-right:2%" >
                                        <div  class="form-group " >
                                            <label><?php print CommonLanguage::getMessage('exchange_rate') . '<span class="red-star">(' . 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 ($is_edit && smc_session()['local_currency'] == $edit_data['main']['currency_id']) ? 'disabled' : (!$is_edit && ($DefaultCurrencyID == smc_session()['local_currency']) ? 'disabled' : '') ?>  value="<?php echo $is_edit ? $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 " >
                                            <label><?php print CommonLanguage::getMessage('exchange_rate') . ' <span class="red-star">(' . 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 ($is_edit && smc_session()['default_setting']['second_currency'] == $edit_data['main']['currency_id']) ? 'disabled' : (!$is_edit && ($DefaultCurrencyID == smc_session()['default_setting']['second_currency']) ? 'disabled' : '') ?>   value="<?php echo $is_edit ? $edit_data['main']['second_currency_rate'] : '' ?>" />
                                        </div>
                                    </div>
                                </div>

                                <div   class="form-group " style="display: flex;">
                                    <div   class="form-group <?php echo smc_session()['default_setting']['activate_accounting_job'] == 1 ? '' : 'hidden' ?>" style="width: 48%;margin-right:2%;" >
                                        <label><?php echo CommonLanguage::getMessage('job') ?></label>
                                        <input type="hidden" class="full-width" id="job_id"  value="<?php echo $is_edit ? $edit_data['main']['job_id'] : '' ?>" data-select-name="<?= $is_edit ? $edit_data['main']['job_name'] : '' ?>"/>
                                    </div>
                                    <div class="" style="width: 50%;" >
                                        <label><?php print CommonLanguage::getMessage('branch'); ?></label>

                                        <input class=" full-width" id="branch_id" name="branch_id" type="hidden"    value="<?= $is_edit ? $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($is_edit ? $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>
                        </div>
                    </div>
                    <div>
                        <div class=""></div>
                    </div>
                    <div class="table-responsive">
                        <table class="table" id='PaymentTable' style="table-layout: fixed;">
                            <thead>
                                <tr>
                                    <!--<th class="text-center " style="width:10%"><?php // print CommonLanguage::getMessage('Currency');  ?></th>-->
                                    <th class="text-center " style="width:25%"><?php print CommonLanguage::getMessage('activity'); ?></th>
                                    <th class="text-center " style="width:10%"><?php print CommonLanguage::getMessage('amount'); ?></th>
                                    <!--<th class="text-center " style="width:10%"><?php // print CommonLanguage::getMessage('exchange_rate');  ?></th>-->
                                    <!--<th class="text-center " style="width:10%"><?php // print CommonLanguage::getMessage('amount') . '(' . smc_session()['local_currency_symbol'] . ')';  ?></th>-->
                                    <th class="text-center " style="width:30%"><?php print CommonLanguage::getMessage('note'); ?></th>
                                    <th class="text-center" style="width:5%"></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                if ($is_edit) {
                                    for ($i = 0; $i < count($edit_data['details']); $i++) {
                                ?>
                                <tr class="TableItem">
                                    <!--                                            <td class="text-center ">
<select class="full-width det_currency_id" data-init-plugin="select2" >
<option value="0"><?php echo CommonLanguage::getMessage('select'); ?></option>
<?php foreach ($currency_list as $currency): ?>
<option mysymbol="<?php echo $currency['Currency_Symbol']; ?>" <?php echo $edit_data['details'][$i]['currency_id'] == $currency['Currency_ID'] ? 'selected' : '' ?> value="<?php echo $currency['Currency_ID']; ?>"><?php echo $currency['Currency_Name'] . " - " . $currency['Currency_Code']; ?></option>
<?php endforeach; ?>
</select> 
</td>-->
                                    <td><input type="hidden"  class="full-width activity_id  " value = "<?php echo $edit_data['details'][$i]['activity_id'] ?>" data-select-name = "<?php echo $edit_data['details'][$i]['activity_title_alias'] ?>"></td>
                                    <td><input type="text"  class="form-control Amount  " value = "<?php echo $edit_data['details'][$i]['activity_total'] ?>"></td>
                                    <!--<td><input type="text"  class="form-control ex_rate  "  value = "<?php // echo $edit_data['details'][$i]['current_rate']  ?>"></td>-->
                                    <!--<td><input type="text"  class="form-control loc_amt "  ></td>-->
                                    <td class=" "><input type="text" class="form-control Payment_Note"  name="Payment_Note"  placeholder="<?php print CommonLanguage::getMessage('enter_note'); ?>" value = "<?php echo $edit_data['details'][$i]['project_expense_note'] ?>"/></td>

                                    <td>
                                        <div class="col-xs-12 AddButtons ">
                                            <span class="fa fa-plus" style="color:#4c0870;margin-top:15px;margin-right:25px"></span>
                                            <span class="fa fa-minus   " style="color:#ed9421;margin-top:15px;"></span>
                                        </div>
                                    </td>
                                </tr>
                                <?php
                                    }
                                }else {
                                    //check_here
                                ?>
                                <tr class="TableItem">
                                    <!--                                        <td class="text-center ">
<select class="full-width det_currency_id" data-init-plugin="select2">
<option value="0"><?php echo CommonLanguage::getMessage('select'); ?></option>
<?php foreach ($currency_list as $currency): ?>
<option mysymbol="<?php echo $currency['Currency_Symbol']; ?>"  value="<?php echo $currency['Currency_ID']; ?>" ><?php echo $currency['Currency_Name'] . " - " . $currency['Currency_Code']; ?></option>
<?php endforeach; ?>
</select> 
</td>-->
                                    <td><input  type="hidden"  class="full-width activity_id  " value=""></td>
                                    <td><input  type="text"  class="form-control Amount  " value=""></td>
                                    <!--<td><input type="text"  class="form-control ex_rate  " ></td>-->
                                    <!--<td><input type="text"  class="form-control loc_amt  "></td>-->
                                    <td class=""><input type="text" class="form-control Payment_Note"  name="Payment_Note"  placeholder="<?php print CommonLanguage::getMessage('enter_note'); ?>"/></td>

                                    <td>
                                        <div class="col-xs-12 AddButtons">
                                            <span class="fa fa-plus" style="color:#4c0870;margin-top:15px;margin-right:25px"></span>
                                            <span class="fa fa-minus" style="color:#ed9421;margin-top:15px;"></span>
                                        </div>
                                    </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-8 col-sm-height col-middle clearfix sm-p-b-15">
                                <div class="col-md-12 form-group">
                                    <div class="col-md-4 p-l-15">
                                        <label><?php echo CommonLanguage::getMessage('paid_amount') ?></label>
                                        <input type="number" id="paid_amount" name="paid_amount" class="form-control" min="0" step="any" value="<?php echo $is_edit ? $edit_data['main']['paid_amount'] : '' ?>"/>
                                    </div>
                                    <div class="col-md-4 p-l-15">
                                        <label><?php echo CommonLanguage::getMessage('payment_account') ?></label>
                                        <input type="hidden" id="payment_acc_id" name="payment_acc_id" class="full-width"  value="<?php echo $is_edit && !empty($edit_data['main']['payment_acc_name']) ? $edit_data['main']['payment_acc_id'] : '' ?>" data-select-name='<?= json_encode($is_edit && !empty($edit_data['main']['payment_acc_name']) ? $edit_data['main']['payment_acc_name'] : '') ?>'/>
                                    </div>
                                    <div class="col-md-4 p-l-15">
                                        <label><?php echo CommonLanguage::getMessage('check') ?>&nbsp;#</label>
                                        <input type="text" id="check_nb" name="check_nb" class="form-control" value="<?php echo $is_edit && !empty($edit_data['main']['check_nb']) ? $edit_data['main']['check_nb'] : '' ?>"/>
                                    </div>
                                </div>
                            </div>
                            <div class="col-sm-4 text-right bg-menu col-sm-height padding-15">
                                <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="PaymentTotalDetails">0</span></h1>
                                <h5 class="font-montserrat all-caps small no-margin hint-text text-white bold"><?php print CommonLanguage::getMessage('local_amount'); ?></h5>
                                <h1 class="no-margin text-white "><span ><?php echo smc_session()['local_currency_symbol'] ?></span>&nbsp;<span id="local_total_amount">0</span></h1>
                            </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 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>
                <?php echo Forms::ModalLoader('PaymentIsBusy') ?>

            </div>
        </div>
    </div>
</form>
<script>
    var Required_Fields = <?php echo json_encode(CommonLanguage::getMessage('Required_Fields')); ?>,
        local_currency = <?php echo json_encode(smc_session()['local_currency']); ?>,
        second_currency = <?php echo json_encode(smc_session()['default_setting']['second_currency']); ?>,
        activate_project_expense_full_paid = <?php echo json_encode(smc_session()['default_setting']['activate_project_expense_full_paid']); ?>,
        Paytotal = 0, CurrencyRate = <?php echo json_encode($Extable); ?>,
        unique_id = <?php echo json_encode(!$is_edit ? $unique_id : '') ?>,
        project_expense_id =<?php echo json_encode($project_expense_id) ?>; 
    $(function () {
        build_select2($('#payment_acc_id'), "xhr/accIDSearch?type=pay");
        build_select2($('#supplier_id'), 'xhr/supplierSearch');
        build_select2($('#period_id'), 'ACCAjax/searchProjectPeriod');
        build_select2($('input.activity_id'), 'ACCAjax/searchProjectPeriodActivity?period_id=' + $('#period_id').val()+'&is_alias=1', false, 'diff_class');

        $('#period_id').on('change', function () {
            build_select2($('input.activity_id'), 'ACCAjax/searchProjectPeriodActivity?period_id=' + $('#period_id').val()+'&is_alias=1', false, 'diff_class');
        });
        build_select2($("#branch_id"), "xhr/CommonSearch?col_id=branch_id&col_name=branch_name&table=tbl_organization_branches");
        build_select2($("#job_id"), "ACCAjax/JobSearch");

        $(".CurrencyIndicator").html($("#CurrencyDropDown ul li[value=" + $("#CurrencyDropDown button input").val() + "]").attr("mysymbol"))

        //        $("#PaymentTable").on("change", "select.det_currency_id", function (e) {
        //            var tr = $(this).parents('tr'),
        //                    amount = parseFloat($("input.Amount", tr).val()) || 0,
        //                    row_cur = parseFloat(tr.find("select.det_currency_id").val()) || 0,
        //                    cur_rate = parseFloat(ConvertCurrency2(1, row_cur, local_currency)) || 0;
        //            if ($(this).val() == local_currency) {
        //                $("input.ex_rate", tr).val(1).prop('readonly', true)
        //                $("input.loc_amt", tr).val($("input.Amount", tr).val()).prop('readonly', true)
        //            } else {
        //                $("input.ex_rate", tr).val(cur_rate).prop('readonly', false)
        //                $("input.loc_amt", tr).val(amount * cur_rate).prop('readonly', false)
        //            }
        //            update_total()
        //        });
        $("#PaymentTable").on("click", ".AddButtons > .fa-plus", function (e) {
            var Parent = $(this).parents(".TableItem"), NewItem = Parent.clone().insertAfter(Parent);
            NewItem.find("input").val('');
            NewItem.find("input,select").removeAttr('disabled').removeAttr('readonly');
            $(".select2-container", NewItem).empty().remove();
            NewItem.find(".AccountCode").show().select2()
            NewItem.find(".det_currency_id").show().select2();
            NewItem.find(".fa-minus").removeClass("hidden")
            build_select2($('input.activity_id', NewItem), 'ACCAjax/searchProjectPeriodActivity?period_id=' + $('#period_id').val()+'&is_alias=1', false, 'diff_class');
            $(".select2-container", NewItem).show();
        });
        $("#PaymentTable").on("click", ".AddButtons > .fa-minus", function (e) {
            if ($('.TableItem').length == 1)
                return;
            $(this).closest(".TableItem").empty().remove();
            update_total();
        });

        $("#PaymentDate").datepicker({autoclose: true});

        $("#PaymentSubmitButton").on("click", function () {
            if (!$("#PaymentForm").valid())
                return;
            var IsValidated = true;
            $("#PaymentTable .Amount").each(function () {
                if ($(this).val() == "" || ($(this).hasClass("Amount") && ($(this).val()).match(/^\s*?([\d]+(\.\d+)?|\.\d{1,2})\s*$/) == null)) {
                    IsValidated = false;
                }
            });

            if (!IsValidated) {
                $("#paymentAlert").attr("class", " alert alert-danger").empty().html(Required_Fields)
                $(document.body).animate({scrollTop: 0}, 800)
                return false;
            }
            if ((parseFloat($("#paid_amount").val())||0)>0 && $("#payment_acc_id").val()=='') {
                $("#paymentAlert").attr("class", " alert alert-danger").empty().html('<?php echo CommonLanguage::getMessage('pay_acc_req')?>')
                $(document.body).animate({scrollTop: 0}, 800)
                return false;
            }

            var Data = {
                period_id: $('#period_id').val(),
                project_id: $('#period_id').select2('data').project_id,
                project_expense_id: $("#project_expense_id").val(),
                Currency_ID: $("#PaymentForm #CurrencyDropDown  input").val(),
                project_expense_total: $("#PaymentTotalDetails").attr('myvalue'),
                expense_total: $("#local_total_amount").attr('data-total'),
                branch_id: $("#branch_id").val(),
                project_expense_date: $("#PaymentDate").val(),
                Currency_Rate: $("#current_rate").val(),
                project_expense_nb: $("#project_expense_nb").val(),
                second_currency_rate: $("#second_currency_rate").val(),
                job_id: $("#job_id").val(),
                supplier_id: $("#supplier_id").val(),
                paid_amount: $("#paid_amount").val(),
                payment_acc_id: $("#payment_acc_id").val(),
                check_nb: $("#check_nb").val(),
                Payment_Note: '',
                unique_id: unique_id,
                project_expenses: [],
                activity_ids: []
            };
            $(".TableItem").each(function () {
                var me = $(this);
                if ($("input.activity_id", me).val()) {
                    Data.project_expenses.push({
                        currency_id: $("#PaymentForm #CurrencyDropDown  input").val(), //me.find("select.det_currency_id").val(),
                        ex_rate: $("#current_rate").val(), //me.find(".ex_rate").val(),
                        activity_total: me.find(".Amount").val(),
                        activity_id: $("input.activity_id", me).val(),
                        project_expense_note: me.find(".Payment_Note").val()
                    });
                    Data.activity_ids.push($("input.activity_id", me).val());
                }
            });

            if (Data.project_expenses.length == 0) {
                $("#paymentAlert").attr("class", "alert alert-warning").html('<?php echo CommonLanguage::getMessage('choose_entry'); ?>');
                $(document.body).animate({scrollTop: 0}, 800)
                return;
            }
            $("#PaymentSubmitButton").addClass("disabled");
            $("#PaymentIsBusy").removeClass('hidden')
            $.ajax({
                url: "ACCAjax/submit_project_expense",
                method: "POST",
                data: Data,
                dataType: "json",
                complete: function (v1, v2) {
                    if (v2 == 'success') {
                        if (v1.responseJSON[1] == 'success') {
                            project_expense_id = v1.responseJSON[2];
                            $("#paymentAlert").attr("class", " alert alert-success").empty().html(v1.responseJSON[0]);
                            $('#PrintBtn').prop('disabled',false);
                        } else {
                            $("#paymentAlert").attr("class", " alert alert-danger").empty().html(v1.responseJSON[0])
                            $("#PaymentSubmitButton").removeClass("disabled");
                        }
                    } else {
                        $("#PaymentValidationAlert").attr("class", "alert alert-danger").empty().html(v1.responseJSON[0]);
                        $("#PaymentSubmitButton").removeClass("disabled");
                    }
                    $("#PaymentIsBusy").addClass("hidden")
                    $(document.body).animate({scrollTop: 0}, 800)
                }
            })
        });
        $("#PaymentTable").on("keyup", ".Amount", function () {
            //            var tr = $(this).parents("tr"),
            //                    amount = parseFloat($(this).val()) || 0,
            //                    row_cur = parseFloat(tr.find("select.det_currency_id").val()) || 0,
            //                    row_rate = parseFloat(tr.find('input.ex_rate').val()) || 0;
            //            cur_rate = tr.find('input.ex_rate').val() != '' ? row_rate : parseFloat(ConvertCurrency2(1, row_cur, local_currency)) || 0;
            //            $(".loc_amt", tr).val(amount * cur_rate)
            update_total()
        })
        //        $("#PaymentTable").on("keyup", ".ex_rate", function () {
        //            var tr = $(this).parents("tr"),
        //                    ex_rate = parseFloat($(this).val()) || 0,
        //                    row_cur = parseFloat(tr.find("select.det_currency_id").val()) || 0,
        //                    amount = parseFloat(tr.find(".Amount").val()) || 0;
        //            if ($(this).val() == '')
        //                ex_rate = parseFloat(ConvertCurrency2(1, row_cur, local_currency)) || 0
        //            $(".loc_amt", tr).val(amount * ex_rate)
        //            update_total()
        //        })
        //        $("#PaymentTable").on("keyup", ".loc_amt", function () {
        //            var tr = $(this).parents("tr"),
        //                    loc_amt = parseFloat($(this).val()) || 0,
        //                    amount = parseFloat(tr.find(".Amount").val()) || 0, rate = 0;
        //            if (amount > 0) {
        //                rate = loc_amt / amount;
        //            }
        //            $(".ex_rate", tr).val(rate)
        //            update_total()
        //        })
        $(".Amount").trigger("keyup");
        $("#PrintBtn").on("click", function () {
            var myurl = "ACC/view_project_expense/"+project_expense_id;
            printExternal(myurl)
        });
    });

    $("#CurrencyDropDown li").on("click", function () {
        $(".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")
        setTimeout(function () {
            update_total()
        }, 300);
    });
    function update_total() {
        Paytotal = 0, local_amount = 0;
        $("#PaymentTable .Amount").each(function () {
            var tr = $(this).parents("tr"),
                row_cur = $("#PaymentForm #CurrencyDropDown  input").val(), //$("select.det_currency_id", tr).val(),
                ex_rate = 1, //$("input.ex_rate", tr).val(),
                amount = parseFloat($(this).val()) || 0;
            if (row_cur == 0) {
                Paytotal += amount;
                local_amount += parseFloat(ConvertCurrency2(amount, row_cur, local_currency)) || 0;
            } else {
                Paytotal += parseFloat(ConvertCurrency2(parseFloat($(this).val() || 0), row_cur, $("#CurrencyDropDown input").val())) || 0;
                //                if ($('input.ex_rate', tr).val() == '')
                local_amount += parseFloat(ConvertCurrency2(parseFloat($(this).val() || 0), row_cur, local_currency)) || 0;
                //                else
                //                    local_amount += ((parseFloat(ex_rate) || 0) * amount);
            }


        })
        if (activate_project_expense_full_paid == 1) {
            $("#paid_amount").val(Paytotal)
        }
        $("#local_total_amount").text(AddCommas(public_round_number(local_amount))).attr('data-total',local_amount)
        $("#PaymentTotalDetails").attr({"MyValue": Paytotal}).text(AddCommas(public_round_number(Paytotal)))
    }

</script>
