<?php 

/*If the loaded invoice is not confirmed after return it will echo an alert msg and die*/
if(count($ListProducts )-1 ==0){?>
<div class="alert alert-danger" role="alert">
    <button class="close" data-dismiss="alert"></button>
    <strong>Danger: </strong>you should confirm return load first! <a href="<?php echo SITE_LINK; ?>Inventory/ReturnDamagedLoad/<?php echo $Load_ID; ?>">Return Load</a>
</div>
<?php die();}


?>
<link href="<?php echo THEME_PATH; ?>css/style.css" rel="stylesheet" type="text/css"/>
<link href="<?php echo THEME_PATH; ?>css/style-responsive.css" rel="stylesheet">
<style type="text/css">
    #SetPaidForm{
        display:none;
        position: fixed;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-color:rgba(0,0,0,0.3);
        z-index: 99999;
        -webkit-transition:opacity 0.3s linear;
        -moz-transition:opacity 0.3s linear;
        transition:opacity 0.3s linear;
    }
    #paymentTable tbody input{
        color:#000;
        opacity:1;
    }
    #SetPaidForm.Closed{
        opacity:0;
    }
    #SetPaidForm > .Body{
        width: 30%;
        padding:13px;
        margin: 130px auto;
        background-color: #fff;
        -webkit-box-shadow: 0 0 40px #888;
        -moz-box-shadow: 0 0 40px #888;
        box-shadow: 0 0 40px #888;
        -webkit-transition:-webkit-transform 0.2s linear;
        -moz-transition:-moz-transform 0.2s linear;
        transition:transform 0.2s linear;
    }
    #SetPaidForm.Closed > .Body{
        -webkit-transform:scale(0);
    }
    .DropDownForForms > .dropdown-menu{
        z-index:2000;
    }
    #SetPaidForm .nav.nav-tabs a {
        padding: 7px 14px;
        font-size: 11px;
    }
    h1{font-size: 3.2em !important;}
    .ValSpan{
        opacity:0;
    }
    .line{
        border: 2px solid #4c0870;
    }
    .bg-master-lighter {
        border: none;
        background-color: #fff;
        border-top: 1px solid #ddd;
    }
    .modal-backdrop.in{
        z-index: 999;
    }
    .TotaltoPay{
        font-weight:700;
        font-size:1.2em;
    }
    .select2-container > .select2-choice{
        background-color: #e5e5e5;
        width: 262px;
    }
    #InvoicePaymentSetup .nav.nav-tabs a {
        padding: 7px 14px;
        font-size: 11px;
    }
    .InputSpinner{
        width: 60px;
    }
    .InputSpinner > .form-control{
        border-color: rgb(221, 221, 221);
        height:36px;
        margin:0;
        padding:0;
        text-align: center;
        /*
        -webkit-border-radius: 3px 0px 0px 3px !important;
        -moz-border-radius: 3px 0px 0px 3px !important;
        border-radius: 3px 0px 0px 3px !important;
        */
    }
    .InputSpinner > .input-group-btn-vertical {
        position: relative;
        white-space: nowrap;
        width: 25px;
        vertical-align: middle;
        display: table-cell;
    }
    .InputSpinner > .input-group-btn-vertical > .btn {
        height:19px;
        display: block;
        float: none;
        width: 100%;
        max-width: 100%;
        padding: 8px;
        margin-left: -1px;
        position: relative;
        border-radius: 0;
    }
    .InputSpinner > .input-group-btn-vertical > .btn:first-child {
        border-top-right-radius: 4px;
    }
    .InputSpinner > .input-group-btn-vertical > .btn:last-child {
        margin-top: -2px;
        border-bottom-right-radius: 4px;
    }
    .InputSpinner > .input-group-btn-vertical i{
        position: absolute;
        top: 50%;
        left: 6px;
        margin-top:-9px;
        font-size: 18px;
    }
    .InputSpinner .input-group-btn-vertical .btn.btn-default{
        font-size: 10px;
        padding: 6px 10px;
    }
    #InvoicePaymentSetup .table tbody > tr:last-child > td{
        border:0;
    }
    .invoice h1 {
        text-align: start;
    }
    .AnItem{
        margin:5px 0;
    }
    #SetPaymentMainContainer td{
        vertical-align:middle;
    }
    #PaymentSubmitter{
        float:right;
    }
    #PaymentSubmitterConfirmModal .modal-header{
        position: absolute;
        width: 100%;
    }
    #PaymentSubmitterConfirmModal .modal-header > .close{
        position: absolute;
        right: 10px;
        left: auto;
        top: 6px;
    }
    #PaymentSubmitterConfirmModal > .modal-dialog{
        border-width: 3px !important;
        border-radius: 6px;        
    }
    #PaymentSubmitterConfirmModal > .modal-dialog > .modal-content{
        border:0;
    }
    #PaymentSubmitterConfirmModal .modal-body{
        padding: 0 0 20px 0;
    }
    #PaymentSubmitterConfirmModal .modal-body > h5{
        text-align: center;
        background: rgb(109,92,174);
        padding: 10px;
        color: #fff;
        font-weight: bold;
    }
    #PaymentSubmitterConfirmModal .modal-body .col-md-12{
        padding: 20px 20px 0 20px;
    }
    body.modal-open{
        overflow: visible !important;
    }
    @media (min-width: 768px){
        .modal-dialog{
            margin-top: 100px;
        }
    }
</style>
<script>
    function AddCommas(val){
        val = parseFloat(val.toString()).toString();
        while (/(\d+)(\d{3})/.test(val.toString())){
            val = val.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
        }
        return val.replace(/\.0$|\.00$/,"") || "0";
    }
    function FixNumber(val){
        return AddCommas(parseFloat(val+"").toFixed(2));
    }
    $(function(){$(".ValSpan").each(function(){$(this).html(AddCommas(parseFloat($.trim($(this).text())).toFixed(3))).animate({opacity:1})})})
</script>
<!--body wrapper start-->
<div class="wrapper">
    <div class="panel invoice">
        <div class="panel-body">
            <div class="row">
                <div id="paymentSubmittedAlert"></div>
                <div class="col-xs-3">
                    <div class="invoice-logo">
                        <img src="<?= upload_url;?>org_logo/invoice_logo.jpg" alt=""style="max-width:250px"/>
                        <input type="hidden" id="Zone_ID" value="<?php echo $Load_details[0]['Zone_ID'];?>">
                        <input type="hidden" id="Vehicle_ID" value="<?php echo $Load_details[0]['Vehicle_ID'];?>">
                        <input type="hidden" id="Driver_ID" value="<?php echo $Load_details[0]['Driver_ID'];?>">
                        <input type="hidden" id="Driver_Name" value="<?php echo $Load_details[0]['Driver_Name'];?>">
                        <input type="hidden" id="Currency_ID" value="<?php echo $DefaultCurrencyID;?>">
                        <input type="hidden" id="Date_Cash" value="<?php echo $today?>">
                    </div>
                </div>
                <div class="col-xs-2">
                </div>
                <div class="col-xs-7">
                    <h1><?php print CommonLanguage::getMessage('payment_of_loading_order');?> </h1>
                </div>
            </div>
            <div class="row">
                <div class="col-xs-4">
                    <br/> <label><span class="bold"><?php print CommonLanguage::getMessage('Name');?> :</span></label><span class="text-center" ><?php echo $org_details[0][ "Organization_Name"]; ?></span>
                    <br/> <label><span class="bold"><?php print CommonLanguage::getMessage('address');?> :</span></label><span class="text-center" ><?php echo $org_details[0][ "Country_Name"] .'-'. $org_details[0]["Name"];?></span>
                    <br/><label><span class="bold"><?php print CommonLanguage::getMessage('Email');?> :</span> </label><span class="text-center" ><?php echo $org_details[0][ "Organization_Email"] ?></span>
                    <br/><label><span class="bold"><?php print CommonLanguage::getMessage('Phone');?> :</span></label><span class="text-center" ><?php echo $org_details[0]["Organization_Phone"] ?></span>
                </div>
                <div class="col-xs-4">
                    <br/> <label><span class="bold"><?php print CommonLanguage::getMessage('truck');?> # : </span></label><?php echo $Load_details[0]['Vehicle_Registration_Number'];?>
                    <br/> <label><span class="bold"><?php print CommonLanguage::getMessage('driver');?> : </span> </label><?php echo $Load_details[0]['Driver_Name'];?>
                    <br/><label><span class="bold"><?php print CommonLanguage::getMessage('salesman');?> :</span> </label><?php echo $Load_details[0]['Sales_Man_Name'];?>
                </div>
                <div class="col-xs-4 inv-info">
                    <br/><label><span class="bold"><?php print CommonLanguage::getMessage('loading_order');?> # :</span> </label><span id="Load_id"><?php echo $Load_ID?></span>
                    <br/><label><span class="bold"><?php print CommonLanguage::getMessage('zone');?> : </span></label><?php echo $Load_details[0]['Zone_Name'];?>
                    <br/><label><span class="bold"><?php print CommonLanguage::getMessage('Date');?> : </span></label><?php echo $Load_details[0]['Loading_Order_Date'];?>
                </div>
            </div>
            <hr>
            <div class="col-md-12">
                <div class="col-md-12 line clearfix">
                    <h5 class="font-montserrat all-caps small no-margin hint-text bold">Total Product Quantity</h5>
                    <table class="table" id="LoadingTableDetails" cellpadding="0" cellspacing="0">
                        <thead>
                            <tr>
                                <th class="text-center">#</th>
                                <th class="text-center"><?php print CommonLanguage::getMessage('Code');?></th>
                                <th class="text-center"><?php print CommonLanguage::getMessage('Item');?></th>
                                <th class="text-center"><?php print CommonLanguage::getMessage('Quantity');?></th>
                                <?php if($ListProducts['count'] ==1){?>
                                <th class="text-center"><?php print CommonLanguage::getMessage('unit_price');?></th>
                                <th class="text-center"><?php print CommonLanguage::getMessage('Price');?></th>
                                <?php }else{ ?>
                                <th class="text-center"><?php print CommonLanguage::getMessage('returned_quantity');?></th>
                                <th class="text-center"><?php print CommonLanguage::getMessage('Damaged_Quantity');?></th>
                                <?php } ?>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                                for($i=0;$i<count($ListProducts)-1;$i++){?>
                            <tr>
                                <td class="text-center"><?php echo $i+1;?></td>
                                <td class="text-center"><?php echo $ListProducts[$i]['Product_Code'];?></td>
                                <td class="text-center"><?php echo $ListProducts[$i]['Product_Name'];?></td>
                                <td class="text-center"><strong><script> document.write(FixNumber(<?php echo $ListProducts[$i]['Total_Remaining_Qty'];?>))</script></strong></td>
                                <?php if($ListProducts['count'] ==1){ ?>
                                <td class="text-center"><?php echo $ListProducts[$i]['Product_Price'].' '. $ListProducts[$i]['Currency_Symbol'];?></td>
                                <td class="text-center"><strong><script> document.write(FixNumber(<?php echo $ListProducts[$i]['Total_Price'];?>))
                                    </script></strong> <?php echo $ListProducts[$i]['Currency_Symbol'];?></td>
                                <?php }else{ ?> 
                                <td class="text-center"><?php echo $ListProducts[$i]['Return_Quantity'];?></td>
                                <td class="text-center"><?php echo $ListProducts[$i]['Damaged_Quantity'];?></td>
                                <?php } }
if($ListProducts['count'] ==1){?>
                            <tr>
                                <th class="text-center" colspan="5">
                                    <?php print CommonLanguage::getMessage('total');?>
                                </th>
                                <th class="text-center" ><span class="TotaltoPay"><?php 
    $totalToPay = 0;
    $sum = 0;
    foreach($ListProducts as $key=>$value)
    {
        $sum+= ($value['Product_Price'])*$value['Total_Remaining_Qty'];
    }
                                    ?>
                                    <script> document.write(FixNumber(<?php echo $sum;?>))</script>
                                    </span> <?php echo $ListProducts[0]['Currency_Symbol']; ?></th>
                            </tr>
                            <?php }?>
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="col-md-12">
                <h4></h4>
                <div class="container-sm-height" >
                    <div class="row row-sm-height">
                        <div id="SetPaymentMainContainer" class="line col-sm-6 col-sm-height col-middle clearfix" style="padding:10px;bord2er: 1px solid #eee;bor2der-right: 1px solid #eee;width:68%">
                            <h5 class="font-montserrat all-caps small no-margin hint-text bold"><?php print CommonLanguage::getMessage('payment');?></h5><br/>
                            <div class="row" style="padding: 0 5px;">
                                <div class="col-md-6">
                                    <strong><?php print CommonLanguage::getMessage('total_loading_value');?>: </strong><strong id="Total_Loading_Value" data-val="<?php echo $loadOrderValue;?>"></strong><br/>
                                </div>
                                <?php if(!$paidClosedInvoice){?>
                                <div class="col-md-6" style="text-align:right">
                                    <?php print CommonLanguage::getMessage('current_payment_value');?>: <strong id="TXT_CurrentPaymentValue" >0</strong><br/>
                                </div>
                                <?php }?>
                            </div>
                            <hr style="margin: 10px;"/>
                            
                            <table class="table" id = "paymentTable" style="">
                            <?php for($i = 0;$i<count($payment_Types); $i++){ ?>
                         <?php if(!$LoadPayment){ ?>
                                <tr>
                                    <td style="width:30%"><strong><?php echo $payment_Types[$i]['Type_Name']; ?></strong></td>
                                    <td>
                                        <div class="AnItem">
                                        
                                            <input type="text" value="0" class="PaymentVal form-control" value="" data-payment-id="<?php echo $payment_Types[$i]['Type_ID'];?>" style="max-width:70px;display:inline-block" aria-invalid="false">
                                            <div Default-Currency="<?php echo $DefaultCurrencyID; ?>" class="input-group-btn DropDownForForms Closable small">
                                                <button type="button" class="btn btn-primary btn-block dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                                                    <i class="fa fa-money"></i> <span><strong><?php print CommonLanguage::getMessage('Select_Currency');?></strong></span>
                                                    <input type="hidden"  value="<?php echo $DefaultCurrencyID; ?>" class="form-control ignore" name="Currency_ID" id="DetailCurrency_ID" onkeyup="return false" onkeydown="return false" required/>
                                                </button>
                                                <ul class="dropdown-menu" style="width: 100%;">
                                                    <?php echo($currencyList); ?>
                                                    <li class="divider"></li>
                                                    <li><a class="LoadMore"><?php print CommonLanguage::getMessage('More');?>..</a></li>
                                                </ul>
                                            </div>
                                            <?php if($payment_Types[$i]['Type_ID'] == 2){?>
                                            <div class="input-group-btn DropDownForForms Closable small PaymentType" style="display: inline-block; width: 262px;">
                                                <button type="button" class="btn btn-default btn-block dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                                                    <span><?php print CommonLanguage::getMessage('select');?></span>
                                                    <input type="hidden" value="" class="form-control" onkeyup="return false" onkeydown="return false"/>
                                                </button>
                                                <ul class="dropdown-menu">
                                                    <?php for($x=0;$x<count($Checks);$x++){ ?>
                                                    <li value="<?php echo $Checks[$x]["Account_Code"]; ?>"><a><?php echo $Checks[$x]["Payment_Type_Name"]; ?></a></li>
                                                    <?php } ?>
                                                </ul>
                                            </div>
                                            <?php }else if($payment_Types[$i]['Type_ID'] == 1){ ?>
                                             <div class="input-group-btn DropDownForForms Closable small PaymentType" style="display: inline-block; width: 262px;">
                                                <button type="button" class="btn btn-default btn-block dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                                                    <span><?php print CommonLanguage::getMessage('select');?></span>
                                                    <input type="hidden" value="" class="form-control" onkeyup="return false" onkeydown="return false"/>
                                                </button>
                                                <ul class="dropdown-menu">
                                                    <?php for($x=0;$x<count($Cashes);$x++){ ?>
                                                    <li value="<?php echo $Cashes[$x]["Account_Code"]; ?>"><a><?php echo $Cashes[$x]["Payment_Type_Name"]; ?></a></li>
                                                    <?php } ?>
                                                </ul>
                                            </div>
                                            <?php } ?>
                                                <?php if($payment_Types[$i]['Type_ID'] == 3){ ?>
                                            <select required id="Vehicle_Expense_Account" name="Vehicle_Expense_Account" style="display:inline-block"  class="Vehicle_Expense_Account " data-init-plugin="select2">
                                                <?php foreach ($all_accounts as $account):?>
                                                <option value="<?php echo $account['Account_Code']; ?>"><?php echo $account['Account_Name']; ?></option>
                                                <?php endforeach; ?>
                                                <option value="more"><?php print CommonLanguage::getMessage('More');?>...</option>
                                            </select>
                                            <?php } ?>
                                        </div>
                                    </td>
                                </tr>
                                <?php }else{ ?>
                                        <tr>
                                    <td style="width:30%"><strong><?php echo $payment_Types[$i]['Type_Name']; ?></strong></td>
                                    <td>
                                    <?php   if($payment_Types[$i]['Type_ID'] == 1){
                                                if($LoadPayment['Cash'])
                                                for($j=0; $j<count($LoadPayment['Cash']); $j++){
                                                    echo '<span><strong>' . $LoadPayment['Cash'][$j]['Payment_Amount'] . ' ' . $LoadPayment['Cash'][$j]['Currency_Symbol'] . '</strong> '. $LoadPayment['Cash'][$j]['Account_Name'] . '<span><br/>';
                                                }
                                                else echo CommonLanguage::getMessage('no_cash');
                                            }else if($payment_Types[$i]['Type_ID'] == 2){
                                                if($LoadPayment['Cheque'])
                                                for($j=0; $j<count($LoadPayment['Cheque']); $j++){ 
                                                echo '<span><strong>' . $LoadPayment['Cheque'][$j]['Payment_Amount'] . ' ' . $LoadPayment['Cheque'][$j]['Currency_Symbol'] . '</strong> '. $LoadPayment['Cheque'][$j]['Account_Name'] . '<span><br/>';
                                                }
                                                else echo CommonLanguage::getMessage('no_check');
                                                }
                                            else if($payment_Types[$i]['Type_ID'] == 3){
                                                if($LoadPayment['Expense'])
                                                for($j=0; $j<count($LoadPayment['Expense']); $j++){
                                                    echo '<span><strong>' . $LoadPayment['Expense'][$j]['Payment_Amount'] . ' ' . $LoadPayment['Expense'][$j]['Currency_Symbol'] . '</strong> '. $LoadPayment['Expense'][$j]['Account_Name'] . '<span><br/>';
                                                }
                                                else echo CommonLanguage::getMessage('no_expenses');
                                            }
                                            else if($payment_Types[$i]['Type_ID'] == 4){
                                                if($LoadPayment['Customers'])
                                                for($j=0; $j<count($LoadPayment['Customers']); $j++){
                                                    echo '<span><strong>' . $LoadPayment['Customers'][$j]['Payment_Amount'] . ' ' . $LoadPayment['Customers'][$j]['Currency_Symbol'] . '</strong> '. $LoadPayment['Customers'][$j]['Account_Name'] . '<span><br/>';
                                                }
                                                else echo CommonLanguage::getMessage('no_credit');
                                            }
                                        ?>
                                    </td>
                                </tr>
                                <?php } ?>
                                <?php }?>
                           
                                <?php if(!$paidClosedInvoice){?>
                                <tr>
                                    <td style="width:30%;"></td>
                                    <td>
                                        <div style="font-size: 14px;background:rgba(0,0,0,0.1);color: #eb9220;padding:7px;line-height: 26px;">
                                            <?php print CommonLanguage::getMessage('remaining');?>: <strong id="TXT_Remaining"></strong>
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <td style="width:30%;"></td>
                                    
                                    <td>
                                        <button id="PaymentSubmitter" class="btn btn-primary disabled"><?php print CommonLanguage::getMessage('Save');?></button>
                                    </td>

                                </tr>
                                <?php } ?>
                            </table>
                        </div>
                        
                    </div>
                </div>
            </div>
        </div>
<!--
        <nav class="navbar navbar-default bg-master-lighter sm-padding-10" role="navigation">
             <div class="container-fluid">
                <div class="collapse navbar-collapse" id="sub-nav">
                    <div class="row"> 
                        <div class="col-sm-4 ">
                            <ul class="nav navbar-nav navbar-center">
                                <li><a href="#" data-toggle="tooltip" title="Print" class="PrintThisTableButton" data-table="#tableWithSearch" data-date="" data-title="Return List"><i class="fa fa-print"></i></a></li>
                                <li><a href="#" data-toggle="tooltip" data-placement="bottom" title="Download"><i class="fa fa-download"></i></a></li>
                            </ul>
                        </div>
                        <div class="col-sm-4 pull-right">
                            <ul class="nav navbar-nav navbar-right">
                                <li>
                                    <a href="#" class="p-r-10"><img width="25" height="25" alt="" class="icon-pdf" data-src-retina="<?php echo SITE_LINK; ?>img/invoice/pdf2x.png" data-src="<?php echo SITE_LINK; ?>img/invoice/pdf2x.png" src="<?php echo SITE_LINK; ?>img/invoice/pdf2x.png"></a>
                                </li>
                                <li>
                                    <a href="#" class="p-r-10"><img width="25" height="25" alt="" class="icon-image" data-src-retina="<?php echo SITE_LINK; ?>img/invoice/image2x.png" data-src="<?php echo SITE_LINK; ?>img/invoice/image2x.png" src="<?php echo SITE_LINK; ?>img/invoice/image2x.png"></a>
                                </li>
                                <li>
                                    <a href="#" class="p-r-10"><img width="25" height="25" alt="" class="icon-doc" data-src-retina="<?php echo SITE_LINK; ?>img/invoice/doc2x.png" data-src="<?php echo SITE_LINK; ?>img/invoice/doc2x.png" src="<?php echo SITE_LINK; ?>img/invoice/doc2x.png"></a>
                                </li>
                                <li><a href="#" class="p-r-10" onclick="$.Pages.setFullScreen(document.querySelector('html'));return false"><i class="fa fa-expand"></i></a></li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </nav>
-->
    </div>
</div>


<div class="modal fade" id="PaymentSubmitterConfirmModal" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
    <div class="modal-dialog line" style="width:50%">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                <br>
                <br>
                <div id="PaymentSubmitterConfirmModalAlertDiv"></div>
            </div>
            <div class="modal-body">
                <h5 class="modal-title"><?php print CommonLanguage::getMessage('confirm_action');?></h5>
                <div class="row">
                    <div class="col-md-12">

                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <div class="pull-right">
                    <button class="btn btn-default" data-dismiss="modal"><?php print CommonLanguage::getMessage('Close');?></button>
                    <button class="btn btn-primary" id="PaymentSubmitterConfirmModalSubmitter"><?php print CommonLanguage::getMessage('Save');?></button>
                </div>

            </div>
        </div>
    </div>
</div>
<div class="modal fade stick-up " id="addExpense" tabindex="-1" role="dialog" aria-hidden="true" style="width:30%;margin:0 auto">
    <div class="modal-dialog  width:5px;">
        <div class="modal-content width: 494px;">
            <div class="modal-header clearfix text-left">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="pg-close fs-14"></i></button>
                <h5><span class="semi-bold"><?php print CommonLanguage::getMessage('new_expense');?></span></h5>
                <div id="addExpenseAlert"></div>
            </div>
            <div class="modal-body">
                <form id="AddExpensePostForm" method="POST" onsubmit="return false">
                    <div class="row">
                        <div class="col-md-12" >
                            <div class="col-md-8 ">
                                <div><label><?php print CommonLanguage::getMessage('expense');?></label></div>
                                <div class="input-group required">
                                    <span class="input-group-addon bg-primary">
                                        <i class="fa fa-money inputIcon" ></i>
                                    </span>
                                    <input type="text" placeholder="<?php print CommonLanguage::getMessage('expense');?>" id="ExpenseID" name="Expense" class="form-control "  style="width: 252px; " required>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer ">
                <div class="pull-right">
                    <button class="btn btn-default" id="CloseExpense"   > <?php print CommonLanguage::getMessage('Close');?> </button>
                    <button class="btn btn-primary" id="SubmitExpense"  > <?php print CommonLanguage::getMessage('Save');?>   </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'));?>,
        confirm_action = <?php echo json_encode(CommonLanguage::getMessage('confirm_action'));?>,
        complete_action = <?php echo json_encode(CommonLanguage::getMessage('complete_action'));?>,
        caution_still_have = <?php echo json_encode(CommonLanguage::getMessage('caution_still_have'));?>,
        payment_load_hint = <?php echo json_encode(CommonLanguage::getMessage('payment_load_hint'));?>,
        Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully'));?>;
    <?php 
//$Extable = $currency->getExchangeRateTable();
echo("var CurrencyRate = ".json_encode($Extable).";");
    ?>
    var IsPaid = <?php echo $paidClosedInvoice ? "true" : "false";?>;
    var ListProducts = <?php array_pop($ListProducts);echo json_encode($ListProducts); ?>;
        var PrimaryCurrencySymbol = <?php echo json_encode($CurrencySymbol) ;?>;
    /*Payment form for cash recieved from the driver */
    /*The amount maybe notr equal to the cash amount in the invoice*/
    /*The system must calculate the differences and make that diff. advance on the driver*/
    var Cash_Amount =0,TotalPaid=0,TotalAmount=0;
    var ExpenseSelect;
    $(function(){

        $("#paymentTable >").on("change","select.Vehicle_Expense_Account",function(){
            var val = $(this).val();
            if(val === "more"){
                $(".Vehicle_Expense_Account").removeAttr('selected').find('option:first').attr('selected', 'selected');
                $("#addExpense").modal('show')
                ExpenseSelect = $(this)
            }
        })
          $("#SubmitExpense").on("click",function(){
            $("#addExpenseAlert").attr("class","").html("")
            $("#AddExpensePostForm").validate()
            if(!$("#AddExpensePostForm").find("input").blur().end().valid()){
                $("#addExpenseAlert").attr("class","alert alert-danger").show().html(Required_Fields)
                return
            }

            $("#ExpenseIsBusy").remove();
            $("#addExpense").append('<div id="ExpenseIsBusy" style="position:absolute;left:0;right:0;top:0px;height:100%;background:rgba(255,255,255,0.9);z-index:9999;opacity:0"><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>');
            $("#ExpenseIsBusy").animate({opacity:1});
            
           
            var Data = {
                Expense : $("#ExpenseID").val()
            }
            $.ajax({
                url:"InventoryAjax/PaymentOfLoadingOrderAjax",
                method:"POST",
                data:Data,
                dataType:"JSON",
                complete:function(v1,v2){
                    if(v2 == 'success'){
                        
                        console.log(ExpenseSelect)
                        var newAccount= "<option value='"+v1.responseJSON['Account_Code']+"'>"+v1.responseJSON['Account_Name']+"</option>";
                        $("select.Vehicle_Expense_Account").append($(newAccount))
                        ExpenseSelect.find('option[value="'+v1.responseJSON['Account_Code']+'"]').attr('selected','selected')
                        ExpenseSelect.parents('.AnItem').find('#s2id_Vehicle_Expense_Account a span:eq(0)').html(v1.responseJSON['Account_Name'])
                        $("#ExpenseIsBusy").remove();
                        $("#addExpenseAlert").addClass("alert alert-success").show().html(Submitted_Successfully);
                        setTimeout(function(){
                            $("#addExpense").modal('hide')
                        },1500)
                        setTimeout(function(){
                            $("#addExpenseAlert").hide()
                        },1500)
                    }else{

                        $("#addExpenseAlert").addClass("alert alert-danger").show().html(Failed_Submit);
                    }
                    $("#ExpenseIsBusy").remove();
                }
            })
        });
        $("#CloseExpense").on("click",function(){
            $("#addExpense input").val('');
            //$("#AddProductPostForm").validate().resetForm();
            $("#addExpense").modal("hide");
        })
        $("#addExpense input").val('');
        /***********************************************************************************************/
//        var PrimaryCurrencySymbol = $("#SetPaymentMainContainer .AnItem:eq(0) .DropDownForForms[Default-Currency]").eq(0).attr("Default-Currency");
//        PrimaryCurrencySymbol = $("#SetPaymentMainContainer .AnItem:eq(0) .DropDownForForms[Default-Currency]:eq(0) li[value='"+PrimaryCurrencySymbol+"']").attr("MySymbol")

        $("#Total_Loading_Value").text(AddCommas((parseFloat($("#Total_Loading_Value").attr("data-val")) || 0).toFixed(3)) + PrimaryCurrencySymbol);
        
        function RefreshAnItemButtonsInContainer(init){
            $("#SetPaymentMainContainer .AnItem").each(function(){
                if(init){
                    $(this).append('<span class="fa fa-plus-circle" style="color: #4c0870;margin-left: 10px;cursor: pointer;font-size: 16px;"></span><span class="fa fa-minus-circle" style="color: #ed9421;margin-left: 5px;cursor: pointer;font-size: 16px;"></span>')
                }
                $(".AnItem>.fa-minus-circle",$(this).parent()).css({"display":$(".AnItem",$(this).parent()).length <= 1 ? "none" : "inline-block"})
            })
            CalculateSetPaymentContainer();
        }
    
        $("#PaymentSubmitterConfirmModal").on("show.bs.modal shown.bs.modal",function(e){
            $('body').scrollTop(CurrentScrollTop)
        })
        $("#PaymentSubmitter").on("click",function(e){
            e.preventDefault();
            window.CurrentScrollTop = $('body').scrollTop();
            var Calcs = CalculateSetPaymentContainer(),Submitter = $("#PaymentSubmitterConfirmModalSubmitter");
            $("#PaymentSubmitterConfirmModal .modal-body .col-md-12").html(complete_action+" "+((Calcs.Val < Calcs.Total) ? "<br/><br/><div style='color: #d00;font-weight: bold;'>"+caution_still_have+" "+(AddCommas((Calcs.Total - Calcs.Val).toFixed(3)) + PrimaryCurrencySymbol)+" "+payment_load_hint : ""))
            clearInterval(window.PaymentSubmitterConfirmModalSubmitCaption)
            Submitter.text("3").addClass("disabled")
            PaymentSubmitterConfirmModalSubmitCaption = setInterval(function(){
                var CurCount = parseInt(Submitter.text())
                if(CurCount > 1){
                    Submitter.text(--CurCount);
                }else{
                    Submitter.text("submit").removeClass("disabled")
                    clearInterval(window.PaymentSubmitterConfirmModalSubmitCaption)
                }
            },1000)
            $("#PaymentSubmitterConfirmModal").modal("show");
        })
        function CalculateSetPaymentContainer(){
            var PrimaryCurrencyID = $("#SetPaymentMainContainer .AnItem:eq(0) .DropDownForForms[Default-Currency]").eq(0).attr("Default-Currency"),
                TotalVal = (parseFloat($("#Total_Loading_Value").attr("data-val")) || 0),
                CurVal = 0;
            TotalAmount = AddCommas((TotalVal - CurVal).toFixed(3))
            
            $("#SetPaymentMainContainer .AnItem").each(function(){
                var V = parseFloat($(this).find(".PaymentVal").val()),
                    CurCurrency = parseFloat($(this).find(".DropDownForForms[Default-Currency] > button > input").val());
                CurVal+= parseFloat(ConvertCurrency2(V,CurCurrency,PrimaryCurrencyID)) || 0;
            });
            $("#TXT_CurrentPaymentValue").text(AddCommas(CurVal.toFixed(3)) + PrimaryCurrencySymbol);
            $("#TXT_CurrentPaymentValue").attr('data-value', AddCommas(CurVal.toFixed(3)));
            $("#TXT_Remaining").text(AddCommas((TotalVal - CurVal).toFixed(3)) + PrimaryCurrencySymbol);
            $("#PaymentSubmitter")[(CurVal > 0 && CurVal <= TotalVal) ? "removeClass" : "addClass"]("disabled");
            $("#SetPaymentMainContainer .PaymentType").each(function(){
                var inputVal = $(this).parents('.AnItem').find('input.PaymentVal').val(),
                    PaymentSelect = $(this).find('input').val();
                console.log(PaymentSelect)
                if(inputVal !=0 && PaymentSelect == 0){
                    
                    $('#PaymentSubmitter').addClass('disabled')
                }
        
                
                
            })
            $("#TXT_Remaining").css("color",CurVal <= TotalVal ? "" : "#f00")
            return {Val:CurVal,Total:TotalVal}
        }
        if(!IsPaid){
        RefreshAnItemButtonsInContainer(true);
    }
        $("#SetPaymentMainContainer").on("click",".DropDownForForms li > a:not(.LoadMore)",function(e){
            setTimeout(function(){
                CalculateSetPaymentContainer();
            },50)
        })
        $("#SetPaymentMainContainer").on("keyup blur",".AnItem .PaymentVal",function(e){
            CalculateSetPaymentContainer();
        })
        $("#SetPaymentMainContainer").on("click",".AnItem > .fa-plus-circle",function(e){
            var Parent = $(this).closest(".AnItem"),NewItem = Parent.clone(false).insertAfter(Parent);
            NewItem.find("input").val("0");
            NewItem.find(".DropDownForForms").each(function(){
                var MyItem = $("ul > li[value='"+$(this).attr("Default-Currency")+"']",this)
                if(MyItem.length > 0){
                    $("> button > span",this).html(MyItem.text())
                    $("button > input",this).val(MyItem.attr("value")).attr({value:MyItem.attr("value")})
                }
            })
            NewItem.find(".select2-container").empty().remove();
            NewItem.find("select[data-init-plugin='select2']").show().select2();
            NewItem.find(".PaymentType button span").html("Select")
            if(!IsPaid){
            RefreshAnItemButtonsInContainer();
            }
        })
        $("#SetPaymentMainContainer").on("click",".AnItem > .fa-minus-circle",function(e){
            $(this).closest(".AnItem").empty().remove();
            if(!IsPaid){
            RefreshAnItemButtonsInContainer();
            }
        })
        
        
        /***********************************************************************************************/
        
        
        
        
//        $("#SalesInvoiceModal").on("show.bs.modal",function(){
//            var ItemTemplate =      '<tr data-id="$PRODUCT_ID$" data-vat="0">'+
//                '    <td><input type="text" value="$CODE$" class="form-control AutoComplete NewSalesInvoiceCODE ui-autocomplete-input AutoAdded" autocomplete="off" aria-invalid="false"></td>'+
//                '    <td><input type="text" value="$PRODUCT_NAME$" class="form-control AutoComplete NewProductName ui-autocomplete-input AutoAdded" autocomplete="off" aria-invalid="false"></td>'+
//                '    <td><span class="Hint"></span><input value="$QUANTITY$" type="text" class="form-control NewInvoiceQuantity isnumber" aria-invalid="false"></td>'+
//                '    <td><span class="Hint"></span><input value="$PRODUCT_PRICE$" type="text" class="form-control NewUnitPrice isnumber" disabled="" style="color: #000;"></td>  '+
//                '    <td><input type="text" value="0" class="form-control NewDisc" value="" aria-invalid="false"></td>'+
//                '    <td class="TotalTD"><span class="CurrencyIndicator">$</span>&nbsp;<span class="Total"></span></td>'+
//                '</tr>',TargetTable = $("#InventoryInvoiceTable > tbody").empty();
//            for(var x=0;x<ListProducts.length;x++){
//                var CurItem = ItemTemplate.replace(/\$CODE\$/,ListProducts[x].Product_Code)
//                .replace(/\$PRODUCT_NAME\$/,ListProducts[x].Product_Name)
//                .replace(/\$QUANTITY\$/,ListProducts[x].Total_Remaining_Qty)
//                .replace(/\$PRODUCT_ID\$/,ListProducts[x].Product_ID)
//                .replace(/\$PRODUCT_PRICE\$/,ListProducts[x].Product_Price)
//                TargetTable.prepend(CurItem);
//            }
//            TargetTable.find("input").eq(0).trigger("keyup");
//            UpdateTable()
//        })
        CalculateSetPaymentContainer();
//        $(".CloseMeButton").on("click",function(e){
//            $("#SetPaidForm").clearQueue().addClass("Closed").delay(300).queue(function(){$(this).css("display","none")})
//        }).end().find(".SaveMeButton").on("click",function(e){
//            $(".CloseMeButton",$(this).parent()).trigger("click")
//            Cash_Amount = parseFloat($("#NewSetPaidCashFormTab_1 .InputSpinner > input").eq(0).val());
//            TotalPaid = parseFloat($("#PurchaseInvoiceTotalDetails").html().replace(",",""));
//            TotalAmount = TotalPaid - Cash_Amount ;
//            console.log(Cash_Amount)
//            console.log(TotalPaid)
//            console.log(TotalAmount)
//        })
        $("#SetPaidForm .InputSpinner .btn").on('click',function(){
            var Input = $("input",$(this).parent().parent()),V=parseInt(Input.val())
            Input.val($(this).hasClass("more") ? V + 1 : V == 0 ? 0 : V - 1)
        })
        $(".SetPaid").on("click",function(e){
            e.preventDefault();
            $("#SetPaidForm").css({"display":"block"}).clearQueue().delay(10).queue(function(){$(this).removeClass("Closed")})
        })
        $("#PaymentSubmitterConfirmModalSubmitter").on("click",function(){
            
                var Data = {
                    Date        : $("#Date_Cash").val(),
                    Driver_ID   : $("#Driver_ID").val(),
                    Driver_Name : $("#Driver_Name").val(),
                    Load_ID     : $("#Load_id").val(),
                    Currency_ID : $("#Currency_ID").val(),
                    Amount      : TotalAmount.replace(/,/g, ''),
                    Total_Paid_Amount: $("#TXT_CurrentPaymentValue").attr('data-value').replace(/,/g, ''),
                    Details     : [],
                    Expenses    : [],
                    Types       : []
                };
        
             $('#paymentTable .PaymentVal').each(function(){
                if($(this).val() != 0){
                Data.Details.push({
                    Type_ID:$(this).attr('data-payment-id'),
                    Payment_Amount:$(this).val(),
                    Currency_ID:$(this).parents('.AnItem').find('#DetailCurrency_ID').val(),
                    Payment_Code:($(this).attr('data-payment-id') != 3) ? $(this).parents('.AnItem').find('.PaymentType input').val() : $(this).parents('.AnItem').find('#Vehicle_Expense_Account').val()
                })
                Data.Types.push(
                    $(this).attr('data-payment-id')
                    
                )
            }
                
            })
            $('[data-payment-id = "3"]').each(function(){
                if($(this).val() != 0){
                Data.Expenses.push({
                    Truck_Code :$("#Vehicle_ID").val(),
                    Type_ID:$(this).attr('data-payment-id'),
                    Truck_Expense_Amount:$(this).val(),
                    Truck_Expense_Date:$("#Date_Cash").val(),
                    ExpenseCurrency_ID:$(this).parents('.AnItem').find('#DetailCurrency_ID').val(),
                    Truck_Expense_Account:$(this).parents('.AnItem').find('#Vehicle_Expense_Account').val(),
                    Truck_Expense_Description: $(this).parents('.AnItem').find('#Vehicle_Expense_Account option:selected').html()
                })
            }
                
            })
                
                $.ajax({
                    url:"InventoryAjax/PaymentOfLoadingOrderAjax",
                    data:Data,
                    method:"POST",
                    complete:function(v1,v2){
                        
                        $('#PaymentSubmitterConfirmModal').modal('hide')
                        if(v2 == "success"){
                            $("#paymentSubmittedAlert").attr("class","alert alert-success").html(Submitted_Successfully)
                            
                        }else{
                            $("#paymentSubmittedAlert").attr("class","alert alert-danger").html(Failed_Submit)
                        }
                         $(document.body).animate({scrollTop:0},800)
                    }
                })
            
//            else{
//                var Data = {
//                    Load_ID     : $("#Load_id").val()
//                };
//                $.ajax({
//                    url:"Views/Inventory/PaymentofLoadingOrder.php",
//                    data:Data,
//                    method:"POST",
//                    complete:function(v1,v2){
//                        if(v2="success"){
//                            //                            alert("ok")
//                        }
//                        else{
//                            alert("false")
//                            alert("Total Cash Valid")
//                        }
//                    }
//                })
//            }
        })
    })
</script>