<style>
    /* enable absolute positioning */
    .inner-addon { 
        position: relative; 
    }

    /* style icon */
    .inner-addon .glyphicon {
        position: absolute;
        padding: 10px;
        pointer-events: none;
    }

    /* align icon */
    .left-addon .glyphicon  { left:  0px;}
    .right-addon .glyphicon { right: 0px;}

    /* add padding  */
    .left-addon input  { padding-left:  30px; }
    .right-addon input { padding-right: 30px; }

    .loader {
        position: fixed;
        left: 0px;
        top: 0px;
        width: 100%;
        height: 100%;
        z-index: 9999;
        background: url('<?php echo base_url(); ?>assets/images/page-loader-1.gif') 50% 50% no-repeat ;
        display: none;
    }


    table.dataTable tr.group td{font-weight:bold;background-color:#e0e0e0}
    
     table.dataTable tr.group,
        tr.group:hover {
            background-color: #ddd !important;
        }
    
</style>

<div class="wrapper">
    <div class="container">
        <!-- Page-Title -->
        <div class="row">
            <div class="col-sm-12">
                <div class="btn-group pull-right m-t-15">
                    <form method="get" action="<?php echo base_url(); ?>accounting_controller/accountvoucheradd">
                        <input type="hidden" name="voucher_add_csrf" id="voucher_add_csrf" value=""/>
<!--                        <button type="submit" onclick="$('#voucher_add_csrf').val($('#cook').val());" class="btn btn-custom waves-effect waves-light" >Add Account Voucher <span class="m-l-5"><i class="fa fa-plus"></i></span></button>-->
                    </form>
                </div>
                <h4 class="page-title">Trial <?php echo $trial_type;?> (<?php echo $business[0]['business_name'];?>):</h4>
            </div>
        </div>

        <div class="row" id="divselection">
            <div class="col-sm-12">
                <div class="card-box ">
                    <h4 class="header-title m-t-0 m-b-10">Filters:</h4>
                     <div class="row m-b-10" id="div-filters">
                        <form class="form-horizontal" method="post" id='glform' action="<?php echo base_url();?>trial_balance">
                            <input name="trial_type" type="hidden" value="<?php echo $trial_type; ?>">
                            <div class="row">
                                <div class="col-md-6">    
                                    <input type="hidden" name="csrf_test_name" id="accounting_voucher_csrf" value=""/>
                                    <div class="form-group">
                                        <label class="control-label col-md-4">Start Date Range</label>
                                        <div class="col-md-8">
                                            <input onchange="checkdaterange();" style="background-color: white;" required readonly class="form-control" type="text" name="startdate" id="startdate" value="<?php if(isset($startdate)){echo $startdate;}?>"/>                                
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="control-label col-md-4">End Date Range</label>
                                        <div class="col-lg-8">                                            
                                            <input onchange="checkdaterange();" style="background-color: white;" required readonly class="form-control" type="text" name="enddate" id="enddate" value="<?php if(isset($enddate)){echo $enddate;}?>"/>
                                        </div>
                                    </div>
                                    
                                    
                                    <div class="form-group">                                        
                                        <label class="control-label col-md-4">Sub Control Account</label>
                                        <div class="col-lg-8">
                                            <select class="form-control " id="selected_account_sub_control" name="selected_account_sub_control">
                                                <option value="0">All</option>
                                                <?php foreach($account_sub_control as $asc){?>
                                                <option <?php if(isset($selected_account_sub_control)){if($selected_account_sub_control== $asc['id_account_sub_control']){echo " selected='selected' ";}}?> value="<?php echo $asc['id_account_sub_control'];?>"><?php echo $asc['account_sub_control'] ;?></option>
                                                <?php } ?>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        
                                        <label class="control-label col-md-4">Start Account Range</label>
                                        <div class="col-lg-8">
                                            <select onchange="ahselected();" class="form-control" id="fromAccount" name="from_accounts">

                                                <option value="0">All</option>
                                                <?php foreach($account_heads as $ba){?>
                                                <option <?php if(isset($from_account)){if($from_account== $ba['id_account_heads']){echo " selected='selected' ";}}?> value="<?php echo $ba['id_account_heads'];?>"><?php echo $ba['account_head'].' ('.$ba['business_name'].')';?></option>
                                                <?php } ?>
                                            </select>
                                            <input type="hidden" id="to_accounts" name="to_accounts" value="<?php if(isset($to_account)){ echo $to_account; }?>">
                                        </div>
                                    </div>
<!--                                    <div class="form-group">                                        
                                        <label class="control-label col-md-4">End Account Range</label>
                                        <div class="col-lg-8">
                                            <select class="form-control " id="toAccount" name="to_accounts">

                                                <option value="0">All</option>
                                                <?php // foreach($account_heads as $ba){?>
                                                <option <?php // if(isset($to_account)){if($to_account== $ba['id_account_heads']){echo " selected='selected' ";}}?> value="<?php // echo $ba['id_account_heads'];?>"><?php // echo $ba['account_head'].' ('.$ba['business_name'].')';?></option>
                                                <?php // } ?>
                                            </select>
                                        </div>
                                    </div>-->
                                </div>      
                                <div class="col-md-6">
                                    <div class="form-group">                                        
                                        <label class="control-label col-md-4">Business Partner Type:</label>
                                        <div class="col-lg-8">
                                            <select class="form-control" onchange="partnertypechange();" id="business_partner_type" name="bptype">
                                                <option value="0">All</option>
                                                
                                                <?php  foreach($bptypes as $bp){?>
                                                <option <?php if(isset($bp['id_account_business_partner'])){if($bp['id_account_business_partner']== $business_partner_selected){echo " selected='selected' ";}}?> value="<?php echo $bp['id_account_business_partner'];?>"><?php echo $bp['account_business_partner'];?></option>
                                                <?php } ?>
                                            </select>
                                        </div>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label class="control-label col-md-4">Business Partner Name </label>
                                        <div class="col-md-8">
                                            <select <?php if($business_partner_selected!=2){?>disabled="disabled" style="display: none;"<?php } ?> class='form-control'  name='business_partner' id='business_partner_supplier'>
                                                <?php foreach($suppliers as $supplier){?>
                                                <option value="<?php echo $supplier['id_business_supplier']; ?>" <?php if($business_partner_id_selected== $supplier['id_business_supplier']){echo "selected='selected'";} ?>><?php echo $supplier['supplier_name']; ?> </option>
                                                <?php } ?>
                                            </select>                                            
                                        </div>
                                        <div class="col-md-8">
                                            <select <?php if($business_partner_selected!=3){?>disabled="disabled" style="display: none;"<?php } ?> class='form-control' name='business_partner' id='business_partner_staff'>
                                                <?php foreach($staffs as $staff){?>
                                                <option value="<?php echo $staff['id_staff']; ?>" <?php if($business_partner_id_selected== $staff['id_staff']){echo "selected='selected'";} ?>><?php echo $staff['staff_fullname']; ?> </option>
                                                <?php } ?>
                                            </select>                                            
                                        </div>
                                        <div class="col-md-8">
                                            <select <?php if($business_partner_selected!=4){?>disabled="disabled" style="display: none;"<?php } ?> class='form-control' name='business_partner' id='business_partner_franchise'>
                                                <?php foreach($franchises as $franchise){?>
                                                <option value="<?php echo $franchise['id_franchises']; ?>" <?php if($business_partner_id_selected== $franchise['id_franchises']){echo "selected='selected'";} ?>><?php echo $franchise['franchise_name']; ?> </option>
                                                <?php } ?>
                                            </select>                                            
                                        </div>
                                        <div class="col-md-8">
                                            <select <?php if($business_partner_selected!=5){?>disabled="disabled" style="display: none;"<?php } ?> class='form-control' name='business_partner' id='business_partner_branch'>
                                                <?php foreach($branches as $branch){?>
                                                <option value="<?php echo $branch['id_business']; ?>" <?php if($business_partner_id_selected== $branch['id_business']){echo "selected='selected'";} ?>><?php echo $branch['business_name']; ?> </option>
                                                <?php } ?>
                                            </select>                                            
                                        </div>
                                        <div class="col-md-8">
                                            <input <?php if($business_partner_selected > 1 ){?>disabled="disabled" style="display: none;"<?php } ?> class='form-control' name='business_partner' id='business_partner'/>
                                            <input type='hidden' name='business_partner_id' id='business_partner_id'/>
                                        </div>
                                    </div>
                                    
                                    <div class="form-group">    
                                        <!--Cost Center Type-->
                                        <label class="control-label col-md-4">Cost Center Type</label>

                                        <div class="col-md-8">
                                            <select onchange="costcentertypechange();" class="form-control" name="cost_center_type" id="cost_center_type">
                                                <option value="0">Select</option>
                                                <?php foreach($cost_center_types as $cct){?>
                                                <option <?php if($cost_center_type_selected==$cct['id_account_cost_center']){echo 'selected="selected"';} ?> value="<?php echo $cct['id_account_cost_center'];?>"><?php echo $cct['account_cost_center'];?></option>
                                                <?php } ?>
                                            </select>
                                         </div>
                                    </div>
                                    <div class="form-group">    
                                        <!--Cost Center-->

                                        <label class="control-label col-md-4">Cost Center</label>                                   
                                        <div class="col-md-8">
                                            <input class="form-control" name="cost_center_name" id="cost_center" value="<?php echo $cost_center_name_selected; ?>"/>
                                        </div>

                                    </div>
                                    <?php if($this->session->userdata('ho')=='Yes'){?>
                                    <div class="form-group">    
                                        <!--Cost Center Type-->
                                        <label class="control-label col-md-4">Branch</label>

                                        <div class="col-md-8">
                                            <select class="form-control" name="business_id" id="business_id">
                                                <option value="">Select</option>
                                                <?php foreach($businesses as $b){?>
                                                <option <?php if($businessselected==$b['id_business']){echo 'selected="selected"';} ?> value="<?php echo $b['id_business'];?>"><?php echo $b['business_name'];?></option>
                                                <?php } ?>
                                            </select>
                                         </div>
                                    </div>    
                                    <?php } ?>
                                    <div class="col-lg-12" style="text-align: right;">
                                        <button type="button"  onclick="$('#accounting_voucher_csrf').val($('#cook').val()); runreport();" class="btn btn-pink btn-bordred waves-effect w-md waves-light m-b-5">Run</button>
                                    </div>
                                    <div class="col-lg-12" style="text-align: right;">
                                        <button type="button"  onclick="removeblanks();" class="btn btn-danger btn-bordred waves-effect w-md waves-light m-b-5">Remove 0 balance items</button>
                                    </div>
                                </div>
                            </div>    
                        </form>
                    </div>
                    
                    <div class="row">
                        <div class="col-lg-12">
                        <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                            <a class="btn btn-warning m-l-10" onclick="tableToExcel('sheet1', 'Trial Balance')" style="float:right">Export to Excel</a>
                        <?php } ?>   
                            <h4 class="header-title m-t-30 m-b-10">Trail <?php echo $trial_type;?></h4>
                            <table id="sheet1" class="table table-bordered dt-responsive nowrap" cellspacing="0" width="100%">
                                 <thead>
                                    <tr role="row" style="border-bottom: 1px solid #ddd;">
                                       <th colspan="5"></th>
                                        <th colspan="2" style="text-align: center;">Opening Balance</th>
                                        <th colspan="2" style="text-align: center;">Current Balance</th>
                                        <th colspan="2" style="text-align: center;">Net Balance</th>
                                    </tr>
                                    <tr role="row">                                        
                                        <th>Sys. ID</th>
                                        <th>Branch</th>
                                        <th>Account Type</th>
                                        <th>Account #</th>
                                        <th>Title</th>
                                        <th>Debit</th>
                                        <th>Credit</th>
                                        <th>Debit</th>
                                        <th>Credit</th>
                                        <th>Debit</th>
                                        <th>Credit</th>
                                    </tr>
                                </thead>
                                <tbody>
                                <?php $tod=0;$toc=0;$tcd=0;$tcc=0;$tnd=0;$tnc=0;  foreach($trial_data as $row){  ?>
                                    <tr>
                                        <td><?php echo $row['id_account_heads']; ?></td>
                                        <td><?php echo $row['business_name']; ?></td>
                                        <td><?php if($row['account_main']=='Assets') {echo '1-';} else if($row['account_main']=='Liabilities' || $row['account_main']=='Equity' ){ echo '2-';}else if($row['account_main']=='Revenue'){echo '3-';}else if($row['account_main']=='Expenses'){echo '4-';}else{echo '5-';} echo $row['account_main']; ?></td>
                                        <td><?php echo $row['account_number']; ?></td>
                                        <td><?php echo $row['account_head']; ?></td>
                                        
                                        <!--Opening -->
                                        <?php if($trial_type=='Movement'){ ?>
                                            <td class="text-right"><?php echo number_format($row['opening_debit'],2); $tod += $row['opening_debit']; ?></td>
                                            <td class="text-right"><?php echo number_format($row['opening_credit'],2); $toc += $row['opening_credit'];?></td>
                                        <?php }else{ ?>
                                            <td class="text-right">
                                            <?php if($row['account_type']=="debit"){ 
                                                $opening_balance = $row['opening_balance'] >= 0 ?  $row['opening_balance'] : 0; 
                                                echo number_format($opening_balance,2); 
                                                $tod += $opening_balance; 
                                            }else{ 
                                                $opening_balance = $row['opening_balance'] < 0 ?  $row['opening_balance']*-1 : 0; 
                                                echo number_format($opening_balance,2); 
                                                $tod += $opening_balance; 
                                            }
                                            ?>
                                            </td>                                       
                                            <td class="text-right">
                                            <?php if($row['account_type']=="credit"){ 
                                                $opening_balance = $row['opening_balance'] >= 0 ?  $row['opening_balance'] : 0; 
                                                echo number_format($opening_balance,2); 
                                                $toc += $opening_balance; 
                                            }else{ 
                                                $opening_balance = $row['opening_balance'] < 0 ?  $row['opening_balance']*-1 : 0; 
                                                echo number_format($opening_balance,2); 
                                                $toc += $opening_balance; 
                                            }
                                            ?>
                                            </td>
                                        <?php } ?>
                                        <!--Current -->
                                         <?php if($trial_type=='Movement'){ ?>
                                        <td class="text-right"><?php echo number_format($row['current_debit'],2); $tcd += $row['current_debit'];?></td>
                                        <td class="text-right"><?php echo number_format($row['current_credit'],2); $tcd += $row['current_credit'];?></td>
                                        <?php }else{ ?>
                                            <td class="text-right">
                                            <?php if($row['account_type']=="debit"){ 
                                                $current_balance = $row['current_balance'] >= 0 ?  $row['current_balance'] : 0; 
                                                echo number_format($current_balance,2); 
                                                $tcd += $current_balance; 
                                            }else{ 
                                                $current_balance = $row['current_balance'] < 0 ?  $row['current_balance']*-1 : 0; 
                                                echo number_format($current_balance,2); 
                                                $tcd += $current_balance; 
                                            }
                                            ?>
                                            </td>                                       
                                            <td class="text-right">
                                            <?php if($row['account_type']=="credit"){ 
                                                $current_balance = $row['current_balance'] >= 0 ?  $row['current_balance'] : 0; 
                                                echo number_format($current_balance,2); 
                                                $tcc += $current_balance; 
                                            }else{ 
                                                $current_balance = $row['current_balance'] < 0 ?  $row['current_balance']*-1 : 0; 
                                                echo number_format($current_balance,2); 
                                                $tcc += $current_balance; 
                                            }
                                            ?>
                                            </td>
                                        <?php } ?>
                                        <!--Net -->
                                        <td class="text-right"><?php
                                        if($row['account_type']=="debit"){
                                            $net_debit = $row['net_balance'] >= 0 ? $row['net_balance'] : 0;
                                            echo number_format($net_debit,2); $tnd += $net_debit;
                                        } else {
                                            $net_debit = $row['net_balance'] < 0 ? $row['net_balance']*-1 : 0;
                                            echo number_format($net_debit,2); $tnd += $net_debit;
                                        }
                                        ?></td>
                                        <td class="text-right"><?php 
                                        if($row['account_type']=="credit"){
                                            $net_credit = $row['net_balance'] >= 0 ? $row['net_balance'] : 0;
                                            echo number_format($net_credit,2);  $tnc += $net_credit; 
                                        } else {
                                           $net_credit = $row['net_balance'] < 0 ? $row['net_balance']*-1 : 0;
                                           echo number_format($net_credit,2);  $tnc += $net_credit; 
                                        }
                                        ?></td>
                                    </tr>
                                <?php 
                                    //$tod=$tod+$od;
                                    //$toc=$toc+$oc;
                                    //$tcd=$tcd+$cd;
                                    //$tcc=$tcc+$cc;
                                    //$tnd=$tnd+$nd;
                                    //$tnc=$tnc+$nc;
                                        } ?>   
                                </tbody>
                                <tfoot>
                                    <tr>
                                        <th class="search">Sys. ID</th>
                                        <th class="search">Branch</th>
                                        <th class="search">Account Type</th>
                                        <th class="search">Account #</th>
                                        <th class="search">Title</th>
                                        <td class="text-right" id="opendebit"><?php echo  number_format($tod,2) ?></td>
                                        <td class="text-right" id="opencredit"><?php echo  number_format($toc,2) ?></td>
                                        <td class="text-right" id="currentdebit"><?php echo  number_format($tcd,2) ?></td>
                                        <td class="text-right" id="currentcredit"><?php echo  number_format($tcc,2) ?></td>
                                        <td class="text-right" id="netdebit"><?php echo  number_format($tnd,2) ?></td>
                                        <td class="text-right" id="netcredit"><?php echo  number_format($tnc,2) ?></td>
                                    </tr>
                                </tfoot>
                            </table>
                            <br />
                        </div>
                    </div>
                </div>
            </div>
        </div>    
    </div>
</div>

<script>
    $(document).ready(function() {
        $("#fromAccount").select2();
        $("#toAccount").select2();
        
        $("#business_partner_franchise, #business_partner_supplier, #business_partner_staff, #selected_account_sub_control").select2();
        
        $("#startdate").datepicker({autoclose:true, format:'yyyy-mm-dd'});
        $("#enddate").datepicker({autoclose:true, format:'yyyy-mm-dd'});

        toastr.options = {
            "closeButton": true,
            "debug": true,
            "newestOnTop": true,
            "progressBar": true,
            "positionClass": "toast-bottom-center",
            "preventDuplicates": true,
            "onclick": null,
            "showDuration": "300",
            "hideDuration": "1000",
            "timeOut": "5000",
            "extendedTimeOut": "1000",
            "showEasing": "swing",
            "hideEasing": "linear",
            "showMethod": "fadeIn",
            "hideMethod": "fadeOut"
        }

        $(".numeric").keypress(function(e) {
            //if the letter is not digit then display error and don't type anything
            if (e.which != 13 && e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
                return false;
            }
        });
        
        
        ////////
        
        // Setup - add a text input to each footer cell
        $('#sheet1 tfoot th').each( function () {
            var title = $(this).text();
            if(title!==''){
                $(this).html( '<input style="width:80px;" type="text" placeholder="'+title+'" />' );
            }
        } );

        // DataTable
        var table = $('#sheet1').DataTable({
            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
            paging: false,
            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                dom: "Bfrtlip",
                    buttons: [{extend: "copy", className: "btn-sm btn-custom btn-trans"}, {extend: "csv", className: "btn-sm btn-pink btn-trans", footer: true}, {
                            extend: "excel",
                            className: "btn-sm btn-warning btn-trans"
                        }, {extend: "pdf", className: "btn-sm btn-purple btn-trans", footer: true}
                    , {extend: "print", className: "btn-sm btn-primary btn-trans", footer: true}],
            <?php } else { ?>
                dom: "frtlip",
            <?php } ?>             
            responsive: !0,
            stateSave: true,
            initComplete: function () {
                // Apply the search
                this.api().columns().every( function () {
                    var that = this;

                    $( 'input', this.footer() ).on( 'keyup change clear', function () {
                        if ( that.search() !== this.value ) {
                            that
                                .search( this.value )
                                .draw();
                        }
                    } );
                } );
            },
            drawCallback: function(){
                
                var api = this.api(), data;
 
                // Remove the formatting to get integer data for summation
                var intVal = function ( i ) {
                    return typeof i === 'string' ?
                        i.replace(/[\$,]/g, '')*1 :
                        typeof i === 'number' ?
                            i : 0;
                };
                
                // Total over this page
                var pageTotal = api.column( 5, { page: 'current'} ).data()
                    .reduce( function (a, b) {
                        return intVal(a) + intVal(b);
                    }, 0 );
                    
                // Update footer
                $( api.column( 5 ).footer() ).html(
                    '<b>'+pageTotal.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")+'</b>'
                );
        
                // Total over this page
                var pageTotal = api.column( 6, { page: 'current'} ).data()
                    .reduce( function (a, b) {
                        return intVal(a) + intVal(b);
                    }, 0 );
                    
                // Update footer
                $( api.column( 6 ).footer() ).html(
                    '<b>'+pageTotal.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")+'</b>'
                );
                
                // Total over this page
                var pageTotal = api.column( 7, { page: 'current'} ).data()
                    .reduce( function (a, b) {
                        return intVal(a) + intVal(b);
                    }, 0 );
                    
                // Update footer
                $( api.column( 7 ).footer() ).html(
                    '<b>'+pageTotal.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")+'</b>'
                );
        
                // Total over this page
                var pageTotal = api.column( 8, { page: 'current'} ).data()
                    .reduce( function (a, b) {
                        return intVal(a) + intVal(b);
                    }, 0 );
                    
                // Update footer
                $( api.column( 8 ).footer() ).html(
                    '<b>'+pageTotal.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")+'</b>'
                );
                
                // Total over this page
                var pageTotal = api.column( 9, { page: 'current'} ).data()
                    .reduce( function (a, b) {
                        return intVal(a) + intVal(b);
                    }, 0 );
                    
                // Update footer
                $( api.column( 9 ).footer() ).html(
                    '<b>'+pageTotal.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")+'</b>'
                );
        
                // Total over this page
                var pageTotal = api.column( 10, { page: 'current'} ).data()
                    .reduce( function (a, b) { 
                        return intVal(a) + intVal(b);
                    }, 0 );
                    
                // Update footer
                $( api.column( 10 ).footer() ).html(
                   '<b>'+pageTotal.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")+'</b>'
                );
            }
        });
        
        
        /////////
        
        
    });



     function runreport() {
        
         var business_partner;
            
            if($("#business_partner_type").val()==1){
                business_partner = $("#business_partner").select2('data');
                $("#business_partner_id").val(business_partner.id_customers);
            } else if ($("#business_partner_type").val()==2){
               $("#business_partner_id").val($("#business_partner_supplier option:selected").val());
            } else if ($("#business_partner_type").val()==3){
                $("#business_partner_id").val($("#business_partner_staff option:selected").val());
            }  else if ($("#business_partner_type").val()==4){
                $("#business_partner_id").val($("#business_partner_franchise option:selected").val());
            }  else if ($("#business_partner_type").val()==5){
                $("#business_partner_id").val($("#business_partner_branch option:selected").val());
            }
            
            
       
        voucher_list();

    }

    function voucher_list(){
       
        $("#glform").submit();
            
    }

     function partnertypechange(){
        
        $("#business_partner").select2('destroy'); 
        $('#business_partner_franchise').select2('destroy');
        $('#business_partner_supplier').select2('destroy');
        $('#business_partner_staff').select2('destroy');
        
        
        var partnertypeid = $("#business_partner_type option:selected").val();
        //console.log(partnertypeid);
        if(partnertypeid=='1'){
            $("#business_partner_supplier").hide();
            $("#business_partner_staff").hide();
            $('#business_partner_franchise').hide();
            $("#business_partner_branch").hide();
            $("#business_partner").show();
            enable_customers();
        } else if (partnertypeid=='2'){
            $("#business_partner_supplier").attr('disabled',false);
            $("#business_partner_supplier").show();
            $('#business_partner_supplier').select2();
            $("#business_partner_staff").hide();
            $('#business_partner_franchise').hide();
            $("#business_partner").hide();
            $("#business_partner_branch").hide();
            //enable_suppliers();
        } else if (partnertypeid=='3'){
            $("#business_partner_staff").attr('disabled',false);
            $("#business_partner_staff").show();
            $('#business_partner_staff').select2();
            $("#business_partner_supplier").hide();
            $("#business_partner").hide();
            $('#business_partner_franchise').hide();
            $("#business_partner_branch").hide();
          //  enable_staff();
        } else if (partnertypeid=='4'){
            $("#business_partner_franchise").attr('disabled',false);
            $('#business_partner_franchise').show();
            $('#business_partner_franchise').select2();
            $("#business_partner_supplier").hide();
            $("#business_partner_staff").hide();
            $("#business_partner").hide();
            $("#business_partner_branch").hide();
          //  enable_franchise();
        } else if (partnertypeid=='5'){
            $("#business_partner_branch").attr('disabled',false);
            $("#business_partner_branch").show();
            $('#business_partner_franchise').hide();
            $("#business_partner_supplier").hide();
            $("#business_partner_staff").hide();
            $("#business_partner").hide();
          //  enable_franchise();
        }else {
            $("#business_partner_staff").attr('disabled',true);
            $("#business_partner_supplier").attr('disabled',true);
            $("#business_partner").attr('disabled',false);             
            $("#business_partner_staff").hide();
            $("#business_partner_supplier").hide();
            $('#business_partner_franchise').hide();
            $("#business_partner_branch").hide();
            $("#business_partner").show();
            
        }
        
    }
    
    
    function enable_customers(){
       $("#business_partner").select2({
            ajax: {
              url: '<?php echo base_url();?>customer_controller/searchnameforco',
              dataType: 'json',
              quietMillis: 1000,
              data: function (term, page) {
                  
                return {
                    customername: term, // search term
                    page_limit: 30, // page size
                    page: page // page number
                };
              },
              results: function (data, page) {
                 
                    var more = (page * 30) < data.length;
                    return {results: data, more: more};
                }
              },
            escapeMarkup: function (m) { return m; }, // let our custom formatter work
            minimumInputLength: 3,
            formatResult: function (option) {
               return option.customer_name+" | "+option.customer_cell ;
            },
            formatSelection: function (option) {
                
                return option.customer_name+" | "+option.customer_cell;
            }
          });
         
    }
    
    
    function costcentertypechange(){
        if($("#cost_center_type option:selected").text()!=="Staff"){
            $("#cost_center").select2('destroy'); 
            $("#cost_center").val($("#cost_center_type option:selected").text()); 
        } else {
            enable_costcenterstaff();
        }
            
    }
    function enable_costcenterstaff(){
       $("#cost_center").select2({
            ajax: {
              url: '<?php echo base_url();?>staff_controller/searchnameforstaff',
              dataType: 'json',
              quietMillis: 1000,
              data: function (term, page) {
                  
                return {
                    staffname: term, // search term
                    page_limit: 30, // page size
                    page: page // page number
                };
              },
              results: function (data, page) {
                 
                    var more = (page * 30) < data.length;
                    return {results: data, more: more};
                }
              },
            escapeMarkup: function (m) { return m; }, // let our custom formatter work
            minimumInputLength: 1,
            formatResult: function (option) {
               return option.staff_fullname+" | "+option.staff_cell ;
            },
            formatSelection: function (option) {
                
                return option.staff_fullname+" | "+option.staff_cell;
            }
          });
         
    }
    
    function removeblanks(){
        $('#sheet1 tr').each(function(row, tr) {
            var aa = $(tr).find('td:eq(09)').text();
            var bb = $(tr).find('td:eq(10)').text();
            console.log(aa);
            console.log(bb);
            if(aa  == '0.00' && bb =='0.00'){
                $(this).css('display','none');          
            }
        });
    }

    var tableToExcel = (function () {
          //  application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
            var uri = 'data:application/vnd.ms-excel;base64,'
              , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></head><body><table>{table}</table></body></html>'
              , base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) }
              , format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) }
            return function (table, name) {
                if (!table.nodeType) table = document.getElementById(table)
                var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }
                var link = document.createElement("a");
                
                var d = new Date();
                var datestring = ("0" + d.getDate()).slice(-2) + "-" + ("0"+(d.getMonth()+1)).slice(-2) + "-" +
                d.getFullYear() + " " + ("0" + d.getHours()).slice(-2) + ":" + ("0" + d.getMinutes()).slice(-2);
    
                link.download = ctx.worksheet + ' ' + datestring;
                link.href = uri + base64(format(template, ctx));
                link.click();
                //window.location.href = uri + base64(format(template, ctx))
            }
        })();
        
        
        function checkdaterange(){

            const startdate = new Date($("#startdate").val());
            const enddate = new Date($("#enddate").val());
            
            if($("#enddate").val()==''){
                var d = new Date();
                d.setDate(startdate.getDate() + 1);           
                var mMonth = ((d.getMonth()+1) <10 ? '0' : '') + (d.getMonth()+1);
                var mDay = (d.getDate() < 10 ? '0' : '') + d.getDate();
                $("#enddate").val(d.getFullYear() +'-'+ mMonth + '-' + mDay); 
            }else if($("#startdate").val()==''){
                var d = new Date();
                d.setDate(enddate.getDate() - 1);           
                var mMonth = ((d.getMonth()+1) <10 ? '0' : '') + (d.getMonth()+1);
                var mDay = (d.getDate() < 10 ? '0' : '') + d.getDate();
                $("#startdate").val(d.getFullYear() +'-'+ mMonth + '-' + mDay);                 
            }
            
            if($("#startdate").val()!='' && $("#enddate").val()!=''){  
                var selecteddays = date_diff_indays(startdate, enddate);
                console.log(selecteddays);
                if(selecteddays < 0){
                    swal({
                        title: 'Invalid Date Selected',
                        text: "End Date cannot be less then you start date",
                        type: 'warning',
                        showCancelButton: false,
                        confirmButtonColor: '#ff5b5b !important'
                    });
                } else if(selecteddays > 450){
                    swal({
                        title: 'Date Range Is Too Big',
                        text: "It is advisable to use date range of maximum 6 Months at a time",
                        type: 'warning',
                        showCancelButton: false,
                        confirmButtonColor: '#ff5b5b !important'
                    });
                    
                    var e = new Date(startdate);
                    e.setDate(startdate.getDate() + 450);
                    var eMonth = ((e.getMonth()+1) <10 ? '0' : '') + (e.getMonth()+1);
                    var eDay = (e.getDate() < 10 ? '0' : '') + e.getDate();
                    $("#enddate").val(e.getFullYear() +'-'+ eMonth + '-' + eDay); 
                    
                }
            }
            
        }
        
        
        var date_diff_indays = function(date1, date2) {
            dt1 = new Date(date1);
            dt2 = new Date(date2);
            return Math.floor((Date.UTC(dt2.getFullYear(), dt2.getMonth(), dt2.getDate()) - Date.UTC(dt1.getFullYear(), dt1.getMonth(), dt1.getDate()) ) /(1000 * 60 * 60 * 24));
        }
        
        function ahselected(){

           $("#to_accounts").val($("#fromAccount option:selected").val());

           if($("#fromAccount option:selected").val() != 'All'){
               $("#selected_account_sub_control").val();
           }
       }


</script>