<?php
/* 	
 * Author   : Dhidhik / Tanggal : 20-11-2015	
 * note     : 
 * Revisi   : 
 */
//---------Untuk privellege Print and export excel ----------//
if (isset($group_user)) {
    if ($group_user->PrintPrivillage == 1) {
        $cek_autority_print = "";
    } else {
        $cek_autority_print = "disabled";
    }

    if ($group_user->ExcelPrivillage == 1) {
        $cek_autority_excel = "";
    } else {
        $cek_autority_excel = "disabled";
    }
    if ($group_user->EditPrivillage == 1) {
        $cek_autority_edit = "";
    } else {
        $cek_autority_edit = "disabled";
    }
} else {
    $cek_autority_print = "disabled";
    $cek_autority_excel = "disabled";
    $cek_autority_edit = "disabled";
}
//---------END Untuk privellege Print and export excel ----------//
?>
<!--<link rel="stylesheet" type="text/css" href="<?php echo base_url() ?>assets/custom/css/treetable/bootstrap.css">-->
<link rel="stylesheet" type="text/css" href="<?php echo base_url() ?>assets/custom/css/treetable/jquery.treegrid.css">
<script type="text/javascript" src="<?= base_url() ?>assets/custom/js/treetable/jquery.treegrid.bootstrap3.js"></script>
<script type="text/javascript" src="<?= base_url() ?>assets/custom/js/treetable/jquery.treegrid.js"></script>
<style type="text/css">

    .margin-left5persen{
        margin-left:5%; 
    }
    .margin-right5persen{
        margin-right:5%; 
    }
    @media print {
        .noPrint { display: none; visibility: hidden; }
        .displayPrint{
            display: inline-block;
            left: 0px;
            position: fixed;
            background-color: white;
            width: 82%;
        }
        .layout-panel-west{display: none; visibility: hidden; }
        table{
            width: 100%;
        }       
    }
    /* style sheet for "A4" printing */
    @media print and (width: 21cm) and (height: 29.7cm) {
        @page {
            margin: 3cm;
        }
    }

    /* style sheet for "letter" printing */
    @media print and (width: 8.5in) and (height: 11in) {
        @page {
            margin: 1in;
        }
    }

    /* A4 Landscape*/
    @page {
        size: A4 landscape;
    }
</style>
<div id="cc" class="easyui-layout" data-options="fit:true, border:false">
    <div id="west-panel" data-options="region:'west',split:true,border:true" class="noPrint" title="Filter" style="width:190px;background-color:#CCCCFF;padding:5px;">
        <form class="form-filter noPrint" method="post" name="formFilterInv" id="formFilterInv" >
            <table width="100%" cellpadding="0" cellspacing="0">
                <!-------copy company dari sini------------------------------------------------------------------------>
                <tr>
                    <td align="left" style="padding-bottom:8px;">
                        <b>by Company</b>
                    </td>
                </tr>
                <tr>
                    <td align="left">                        
                        <select name="cmb_company" id="cmb_company" 
                                class="easyui-combobox" 
                                style="width:174px;"
                                data-options="
                                value:'<?php echo $this->session->userdata('company'); ?>',
                                valueField:'CompanyCode',
                                textField:'CompanyName',
                                url:'<?php echo base_url(); ?>custom/get_data/company_find_master',
                                onSelect: function(rec){
                                var url = '<?php echo base_url(); ?>custom/get_data/branch_by_company_new/'+rec.CompanyCode;
                                $('#cmb_branch').combobox('reload', url);
                                $('#cmb_branch').combobox('setValue', '');
                                }
                                "
                                editable="true">
                        </select>
                    </td>
                </tr>
                <!---end COMPANY select--------------------------------------------------------------------- -->

                <!--ini separator-------------------------------------------->
                <tr><td colspan="2"><div class="tr-divider"></div></td></tr>
                <!--end-------------------------------------------------------->

                <!-------copy branch dari sini------------------------------------------------------------------------>
                <tr>
                    <td align="left" style="padding-bottom:8px;">
                        <b>by Branch/Depo</b>
                    </td>
                </tr>
                <tr>
                    <td align="left">
                        <select name="cmb_branch" id="cmb_branch" 
                                class="easyui-combobox" 
                                style="width:174px;"  
                                data-options="
                                value :'<?php echo $this->session->userdata('branch'); ?>',
                                valueField:'BranchCode', 
                                textField:'BranchName', 
                                url:'<?php echo base_url(); ?>custom/get_data/branch_by_company_new/<?php echo $this->session->userdata('company'); ?>'
                                " editable="true">
                        </select>

                    </td>
                </tr>
                <!------------end copy branch dari sini---------------------------------------------------------------->

                <!--ini separator-------------------------------------------->
                <tr><td colspan="2"><div class="tr-divider"></div></td></tr>
                <!--end-------------------------------------------------------->

                <!-----------------find by date------------------------------------------------------------------------>
                <tr>
                    <td style="padding-bottom:8px;">
                        <b>by Date</b>
                        <input type="checkbox" name="chk_ByDateNew" value="1" id="chk_ByDateNew" style="float:right;" checked disabled />
                    </td>
                </tr>
                <tr>
                    <td>
                        To
                        <span style="float:right;">
                            <input name="txt_DateTo" id="txt_DateTo" type="text" class="easyui-datebox " style="width:100px;height:22px;" editable="false" disabled />
                        </span>
                    </td>
                </tr>
                <!----------------------------------------------end-------------------------------------------------------------->

                <!--ini separator-------------------------------------------->
                <tr><td colspan="2"><div class="tr-divider"></div></td></tr>
                <!--end-------------------------------------------------------->
                <!-------copy Invoice Receipt dari sini------------------------------------------------------------------------>
                <tr>
                    <td align="left" style="padding-bottom:8px;">
                        <b>by No.Invoice Receipt</b>
                    </td>
                </tr>
                <tr>
                    <td align="left">
                        <input id="txt_noInvoices" name="txt_noInvoices" placeholder="< Nomor Invoice Receipt >" style="margin:2px 0px 3px;width:100%;height:18px;border:1px solid #CCC;">
                    </td>
                </tr>
                <!------------end copy Invoice Receipt dari sini---------------------------------------------------------------->

                <!--ini separator-------------------------------------------->
                <tr><td colspan="2"><div class="tr-divider"></div></td></tr>
                <!--end-------------------------------------------------------->
                <!-------copy Invoice Receipt dari sini------------------------------------------------------------------------>
                <tr>
                    <td align="left" style="padding-bottom:8px;">
                        <b>by Customer</b>
                    </td>
                </tr>
                <tr>
                    <td align="left">
                        <input id="txt_cust" name="txt_cust" placeholder="< Customer Name >" style="margin:2px 0px 3px;width:100%;height:18px;border:1px solid #CCC;">
                    </td>
                </tr>
                <!------------end copy Invoice Receipt dari sini---------------------------------------------------------------->

                <!--ini separator-------------------------------------------->
                <tr><td colspan="2"><div class="tr-divider"></div></td></tr>
                <!--end-------------------------------------------------------->
                <!-------copy branch dari sini------------------------------------------------------------------------>
                <tr>
                    <td align="left" style="padding-bottom:8px;">
                        <b>Data in </b>
                    </td>
                </tr>
                <tr>
                    <td align="left">
                        <select name="cmb_collapse" id="cmb_collapse" 
                                class="easyui-combobox" 
                                style="width:174px;"  
                                editable="false">
                            <option value="collapseAll" selected > Collapse </option>
                            <option value="expandAll"> Expand </option>
                        </select>

                    </td>
                </tr>
                <!------------end copy branch dari sini---------------------------------------------------------------->

                <!--copy dari sini untuk button reset dan search-->
                <tr>
                    <td height="38">
                        <div style="float:right;">
                            <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-reload'" onClick="location.reload();" >Reset</a>
                            <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-search'" onClick="searching_data_aging_recv_detail('', '');" >Search</a>
                        </div>
                    </td>
                </tr>
                <!--end copy dari sini untuk button reset dan search-------------------------->

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

    <div data-options="region:'center',border:false,iconCls:'icon-ok'">
        <div style="padding:2px" id="form-header">
            <a href="#" class="easyui-linkbutton noPrint" data-options="plain:true,iconCls:'icon-print'" onClick="window.print_detail()" <?= $cek_autority_print ?>>Print</a>
            &nbsp;&nbsp;           
            <a href="#" class="easyui-linkbutton noPrint" data-options="plain:true,iconCls:'icon-excel'" onclick="actionExcel()" <?= $cek_autority_excel ?>>Export File </a>
            &nbsp;&nbsp;           
            <a href="#" class="easyui-linkbutton noPrint" data-options="plain:true,iconCls:'icon-reload'" onclick="location.reload();">Refresh</a>
        </div><br />
        <div id="databox" class="displayPrint">

        </div>	
    </div>

</div>

<script type="text/javascript">
    var shortingText = "";
    var rstTypeShorting = "ASC";
    var pre_url = base_url + 'report/index_account_receivables/pre_ajax_reloadDataAgingReceivdetail';
    var url = base_url + 'report/index_account_receivables/ajax_reloadDataAgingReceivdetail';
    var dataSend = {};
    var noTree = 1;
    var stringHTML = "";
    var pages = {limit: limitRowInPage(), pages: 1};
    var tempArSumm = [];
    function variableDefault() {
        shortingText = "";
        rstTypeShorting = "ASC";
        dataSend = {};
        noTree = 1;
        stringHTML = "";
        pages['pages'] = 1;
        tempArSumm = [];
    }

    function checkShorting(txtCheckShorting) {
        if (shortingText == txtCheckShorting) {
            rstTypeShorting == "DESC" ? rstTypeShorting = "ASC" : rstTypeShorting = "DESC";
        } else {
            rstTypeShorting = "ASC";
            shortingText = txtCheckShorting;
        }
        //alert("cek="+txtCheckShorting+"-"+rstTypeShorting);
        return rstTypeShorting;
    }
    function startLoad() {
        //========load tanggal=============//
        //$('#txt_DateFrom').datebox('enable', true);
        $('#txt_DateTo').datebox('enable', true);

//        if ($('#txt_DateFrom').datebox('getValue') == "" || $('#txt_DateFrom').datebox('getValue') == undefined) {
//            $('#txt_DateFrom').datebox('setValue', '<?= date('01-m-Y') ?>');
        //$('#txt_DateTo').datebox('setValue', 'today');
        //}
        //========END load tanggal=============//        

        var searchParameter = {};

        if ($('#cmb_company').length > 0) {
            searchParameter['cmb_company'] = $('#cmb_company').combobox('getValue');
        }
        if ($('#cmb_branch').length > 0) {
            searchParameter['cmb_branch'] = $('#cmb_branch').combobox('getValue');
        }

        if ($('#txt_DateTo').length > 0) {
            //searchParameter['txt_DateFrom'] = $('#txt_DateFrom').datebox('getValue');
            searchParameter['txt_DateTo'] = $('#txt_DateTo').datebox('getValue');
        }
        return searchParameter;
    }
    $(document).ready(function () {
        startLoad();//Load awal
        $('#txt_DateTo').datebox('setValue', 'today');
    });

    function searching_data_aging_recv_detail(txtTable, txtFieldShorting) {//(namaVariableTabelDiModel, namaField)
//        var url = base_url + 'report/index_account_receivables/ajax_reloadDataAgingReceivdetail';
        variableDefault();
        var getValue = startLoad();
        var typeShorting = checkShorting(txtFieldShorting);
        var dataIn = $('#cmb_collapse').combobox('getValue');

        dataSend = {
            pages: pages,
            predata: [],
            cmb_company: getValue['cmb_company'] == undefined ? "" : getValue['cmb_company'],
            cmb_branch: getValue['cmb_branch'] == undefined ? "" : getValue['cmb_branch'],
            txt_noInvoices: document.formFilterInv.txt_noInvoices.value,
            txt_cust: document.formFilterInv.txt_cust.value,
            txt_DateTo: getValue['txt_DateTo'],
            txtTable: txtTable,
            txtField: txtFieldShorting,
            typeShorting: typeShorting,
            dataIn: dataIn
        };
        if ($('#cmb_branch').combobox('getValue') == undefined) {
            $('#cmb_branch').combobox('clear');
            var strAlert = strMessageAlert_report('brachIsEmpty');
            messageAlertBiasa('Warning', strAlert, 'error');
        }else if ($('#cmb_company').combobox('getValue') == undefined) {
            $('#cmb_company').combobox('clear');
            var strAlert = strMessageAlert_report('companyIsEmpty');
            messageAlertBiasa('Warning', strAlert, 'error');
        } else {
            modal_open('Progress Bar', 'dlg_loading');
            $.post(pre_url, dataSend).done(function (pre_result) {//preAjax
                var preResult = JSON.parse(pre_result);
                //Array Pre_result diambil code nya saja
                var dataTopHeader = {
                    CompanyName: preResult.company.CompanyName,
                    BranchName: preResult.company.BranchName == undefined || preResult.company.BranchName == "" ? "All Branch" : preResult.company.BranchName,
                    reportLabel: " Aging Receivable Detail ",
                    startdate: preResult.startdate,
                    enddate: preResult.enddate,
                    colspan: 11
                };
                stringHTML += tableHTMLTopHeaderReport(dataTopHeader);//topHeader   

                if (preResult.datas != 0) {//jika pre ajax data ada 
                    var pre_arData = [];
                    preResult.datas.forEach(function (pre_dtResults) {//untuk mempersiapkan pre Array utk search
                        var pre_code = pre_dtResults['code'];
                        pre_arData.push(pre_code);
                    });
                    dataSend['predata'] = pre_arData;//isi preArray dengan value baru

                    $.post(url, dataSend).done(function (result) {
                        var parseResult = JSON.parse(result);
                        var arTempDatas = [];   // temporer untuk menyimpan   

                        //=== JIKA DATA DITEMUKAN ========================================//
                        if (parseResult.datas != 0) {
                            //console.log("arTempDatas="+JSON.stringify(arTempDatas));
                            arTempDatas = prepareReport(parseResult);
                            stringHTML += createReport(arTempDatas);
                            pages['pages'] = (pages['pages'] * 1) + 1;
                        }//=== END JIKA DATA DITEMUKAN ===================================//
                        else {
                            stringHTML += tableHTMLNotFound();
                        }
                        //console.log("arTempDatas="+JSON.stringify(arTempDatas));
                        $("#databox").html(stringHTML);
                        modal_close('dlg_loading');
                    }, 'json');
                } else {
                    stringHTML += tableHTMLNotFound();
                    $("#databox").html(stringHTML);
                    modal_close('dlg_loading');
                }
            }, 'json');
        }
    }

    function print_detail() {
        //var opt_print   = $("input[type='radio'][name='opt_print']:checked").val();
        var data_print = $("#databox").html();
        Popup(data_print);

    }
    function Popup(data) {
        var mywindow = window.open('', 'print-container', 'height=528,width=700');
        //var css = '<link rel="stylesheet" href="<?php echo base_url() ?>assets/custom/css/print.css" type="text/css" />';
        var varCSS = "<style>table{width: 100%;"
                + "font-family: 'Times New Roman';"
                + "font-size: small;"
                + "}"
                + ".thead{border:1px solid #333333;} .margin-left5persen{margin-left:0px;} .margin-right5persen{margin-right:0px;}"
                + ".table-summary{width:auto;}</style>";
        mywindow.document.write('<html><head><title>Print Detail</title>');
        mywindow.document.write(varCSS);
        mywindow.document.write('</head><body >');
        mywindow.document.write(data);
        mywindow.document.write('</body></html>');

        mywindow.document.close(); // necessary for IE >= 10
        mywindow.focus(); // necessary for IE >= 10

        mywindow.print();
        mywindow.close();

        return true;
    }
    function actionExcel() {
        var htmls = "";
        var delRow = "";
        htmls = $('#databox').html();
        htmls = htmls.replace(/<table border='0' /gi, "<table border='1' ");
        htmls = htmls.replace(/<table border="0" /gi, "<table border='1' ");
        htmls = htmls.replace(/border='0'/gi, " ");
        htmls = htmls.replace(/'s0 text-center'/gi, "'s0 text-center' style='font-size:7;text-align: center;font-weight: bold;' ");
        htmls = htmls.replace(/'s1 text-center'/gi, "'s1 text-center' style='font-size:9;text-align: center;font-weight: bold;' ");
        htmls = htmls.replace(/'s2'/gi, "'s2' style='text-align: center;font-weight: bold;' ");
        htmls = htmls.replace(/id='tableHeader'/gi, " style='-webkit-print-color-adjust:exact;background-color:#d5d5d5;' ");
        htmls = htmls.replace(/<script/gi, " ");
        delRow = ">$(document).ready(function () {    $('.tree-2').treegrid({        expanderExpandedClass: ' treegrid-expander-expanded ',        expanderCollapsedClass: 'treegrid-expander-collapsed'    });    $('.tree-2').treegrid('";
        htmls = htmls.replace(delRow, " ");
        delRow = "collapseAll');});</";
        htmls = htmls.replace(delRow, " ");
        delRow = "expandAll');});</";
        htmls = htmls.replace(delRow, " ");
        htmls = htmls.replace(/script>/gi, " ");
        delRow = '';
        htmls = htmls.replace(/display: none;/gi, " ");
        exportToExcel(htmls);
    }

    function prepareReport(parseResult) {
        var tempCode = "";
        var arTempDatas = [];
        // === LOOP PEMBACAAN DATA ===================================//
        parseResult.datas.forEach(function (dtResults) {
            if (tempCode == "") {//PEMBACAAN DATA PERTAMA KALI
                tempCode = dtResults.InvoiceCurrCode_IR;
                var dataJSONLevel_1 = arJSONLevel_1(dtResults);
                arTempDatas.push(dataJSONLevel_1);
            }//END PEMBACAAN DATA PERTAMA KALI
            else if (dtResults.InvoiceType_IR == 0 && dtResults.DPStatus_IR == 0) {//PEMBACAAN DATA UNTUK DATA INVOICE
                var iL1 = cekArraySummary(arTempDatas, "InvoiceCurrCode_IR", dtResults.InvoiceCurrCode_IR);//mendapatkan index array level 1 (currency)
                if (iL1 > -1) {
                    //console.log("arTempDatas="+JSON.stringify(arTempDatas));
                    var iL2 = cekArraySummary(arTempDatas[iL1]['data'], "CustomerCode_IR", dtResults.CustomerCode_IR);//index level 2(noInvoice)
                    if (iL2 > -1) {
                        var dtarJSONLevel_3 = arJSONLevel_3(dtResults);
                        arTempDatas[iL1]['data'][iL2]['data'].push(dtarJSONLevel_3);
                    } else {
                        var dtarJSONLevel_2 = arJSONLevel_2(dtResults);
                        arTempDatas[iL1]['data'].push(dtarJSONLevel_2);
                    }
                } else {
                    var dataJSONLevel_1 = arJSONLevel_1(dtResults);
                    arTempDatas.push(dataJSONLevel_1);
                }
            }//end PEMBACAAN DATA UNTUK DATA INVOICE
        });
        // === END LOOP PEMBACAAN DATA ============================/    
        return arTempDatas;
    }
    function createReport(arTempDatas) {
        var tempStringHtml = "";
        tempStringHtml += createRowReport(arTempDatas);
        tempStringHtml += tableHTMLBlankForNext();
        tempStringHtml += "</table><script>"
                + "$(document).ready(function () {"
                + "    $('.tree-2').treegrid({"
                + "        expanderExpandedClass: ' treegrid-expander-expanded ',"
                + "        expanderCollapsedClass: 'treegrid-expander-collapsed'"
                + "    });"
                + "    $('.tree-2').treegrid('" + dataSend['dataIn'] + "');"
                + "});"
                + "</script" + ">";

//        tempStringHtml += summaryHTMLAll(" ALL ITEM ", "left", tempArSumm);
        tempStringHtml += stringLegend();
        return tempStringHtml;
    }
    function createRowReport(arTempDatas) {
        var tempStringHtml = "";
        var dataFooter = {"amount": 0, "paid": 0, "notYet": 0, "r1_30": 0, "r31_60": 0, "r61_90": 0, "r91_120": 0, "blh_120": 0, CurrencySymbol: ""};
        //MULAI LOOP
        var noUrutLevel1 = 1;
        arTempDatas.forEach(function (arDataLevel1) {//MULAI LOOP  level 1  
            var noUrutLevel2 = 1;
            if (noUrutLevel1 > 1 && noUrutLevel2 == 1 && pages['pages']<2) {
                tempStringHtml += tableHTMLFooterSummary(dataFooter);
                dataFooter = {"amount": 0, "paid": 0, "notYet": 0, "r1_30": 0, "r31_60": 0, "r61_90": 0, "r91_120": 0, "blh_120": 0, CurrencySymbol: ""};
            }
            tempStringHtml += tableHTMLHeaderLevel1(arDataLevel1);

            arDataLevel1['data'].forEach(function (arDataLevel2) {//MULAI LOOP LEVEL 2
                //noUrutLevel2==1?stringHTML+=tableHTMLHeader(arDataLevel2):null;//membuat tabel header LEVEL2
                tempStringHtml += tableHTMLHeader(arDataLevel2);//membuat tabel header LEVEL2
                noTree++;

                var noUrutLevel3 = 1;
                arDataLevel2['data'].forEach(function (arDataLevel3) {//MULAI LOOP LEVEL 3 
                    ///====== SUMMARY =================================//
                    dataFooter["amount"] = (dataFooter["amount"] * 1) + (arDataLevel3.InvoiceAmount_IR * 1);
                    dataFooter["paid"] = (dataFooter["paid"] * 1) + (arDataLevel3.ReceiptTotal_IR * 1);
                    dataFooter["CurrencySymbol"] = arDataLevel3.CurrencySymbol;
                    arDataLevel3.AgeDueDate_IR <= 0 ? dataFooter["notYet"] = (dataFooter["notYet"] * 1) + (arDataLevel3.InvoiceOwing_IR * 1) : null;
                    arDataLevel3.AgeDueDate_IR >= 1 && arDataLevel3.AgeDueDate_IR <= 30 ? dataFooter["r1_30"] = (dataFooter["r1_30"] * 1) + (arDataLevel3.InvoiceOwing_IR * 1) : null;
                    arDataLevel3.AgeDueDate_IR >= 31 && arDataLevel3.AgeDueDate_IR <= 60 ? dataFooter["r31_60"] = (dataFooter["r31_60"] * 1) + (arDataLevel3.InvoiceOwing_IR * 1) : null;
                    arDataLevel3.AgeDueDate_IR >= 61 && arDataLevel3.AgeDueDate_IR <= 90 ? dataFooter["r61_90"] = (dataFooter["r61_90"] * 1) + (arDataLevel3.InvoiceOwing_IR * 1) : null;
                    arDataLevel3.AgeDueDate_IR >= 91 && arDataLevel3.AgeDueDate_IR <= 120 ? dataFooter["r91_120"] = (dataFooter["r91_120"] * 1) + (arDataLevel3.InvoiceOwing_IR * 1) : null;
                    arDataLevel3.AgeDueDate_IR > 120 ? dataFooter["blh_120"] = (dataFooter["blh_120"] * 1) + (arDataLevel3.ReceiptTotal_IR * 1) : null;
                    
                    tempStringHtml += tableHTMLContentFirst(noTree, noUrutLevel3, arDataLevel3);
                    noTree++;

                    noUrutLevel3++;
                });//END MULAI LOOP LEVEL 3 
                noUrutLevel2++;
            });//END MULAI LOOP LEVEL 2                    
            noUrutLevel1++;
        });
        //END MULAI LOOP
        tempStringHtml += tableHTMLFooterSummary(dataFooter);//MEMBUAT FOOTER SUMARY 
        return tempStringHtml;
    }
    function seeMore() {
        modal_open('Progress Bar', 'dlg_loading');
        $.post(pre_url, dataSend).done(function (pre_result) {//preAjax
            var preResult = JSON.parse(pre_result);
//            dataSend['predata'] = preResult.datas;
            if (preResult.datas != 0) {//jika pre ajax data ada                 
                //Array Pre_result diambil code nya saja
                var pre_arData = [];
                preResult.datas.forEach(function (pre_dtResults) {
                    var pre_code = pre_dtResults['code'];
                    pre_arData.push(pre_code);
                });
                dataSend['predata'] = pre_arData;//isi preArray dengan value baru
                //End Array Pre_result diambil code nya saja

                var prearTempDatas = [];
                var pre_stringHTML = "";
                $.post(url, dataSend).done(function (result) {//loadAjax
                    var parseResult = JSON.parse(result);
                    if (parseResult.datas != 0) {
                        prearTempDatas = prepareReport(parseResult);
                        pre_stringHTML += createRowReport(prearTempDatas);
                        pre_stringHTML += tableHTMLBlankForNext();

                        pages['pages'] = (pages['pages'] * 1) + 1;
                        $("#tr-see-more").replaceWith("");//clear row button 
                        $("#rowBlankForNext").replaceWith(pre_stringHTML);//mengganti row blank dengan ros data page baru
//                        $("#tableSumAll").replaceWith(summaryHTMLAll(" ALL ITEM ", "left", tempArSumm));
                        var htmlDataBox = $("#databox").html();//mengambil html pada div #databox yg data sudah baru
                        $("#databox").html(htmlDataBox);//mengisi kembali div #databox agar Tree-nya dapat work                      
                    } else {
                        $("#btn-see-more").prop("disabled", true);
                        $("#btn-see-more").val("Data Completed");
                    }
                    modal_close('dlg_loading');
                }, 'json');
            } else {
                $("#btn-see-more").prop("disabled", true);
                $("#btn-see-more").val("Data Completed");
                modal_close('dlg_loading');
            }
        }, 'json');
    }
    function tableHTMLNotFound() {
        var strHeader = "<tr><td colspan='11' class='s3' align='left'><b><u>_____</u></b></td></tr>"
                + "<tr id='tableHeader'>"//baris heading table

                + "<td width='' class='s4'><span class='small_bold' >No</span></td>"
                + "<td width='80' class='s4'><span class='small_bold'>Date</span></td>"
                + "<td width='' class='s4'><span class='small_bold'>No.Transaction</span></td>"
                + "<td width='' class='s4'><span class='small_bold'>Customer</span></td>"
                + "<td width='' class='s4'><span class='small_bold'>Term</span></td>"
                + "<td width='' class='s4'><span class='small_bold'>Due Date</span></td>"
                + "<td width='' class='s4'><span class='small_bold'>Inv.Amount</span></td>"
                + "<td width='' class='s4'><span class='small_bold'>Paid</span></td>"
                + "<td width='' class='s4' align='right'><span class='small_bold'>Outstanding</span></td>"
                + "<td width='' class='s4' align='right'><span class='small_bold'>Tax Owing</span></td>"
                + "<td width='' class='s4' align='right'><span class='small_bold'>Age fr Due</span></td>"
                + "</tr><tr>"
                + "<td width='' class='s5 text-center' colspan='11' align='center'><span class='small_bold' >Data Not Found</span></td>"
                + "</tr></table>";
        return strHeader;
    }
    function tableHTMLHeaderLevel1(data) {
        var strHeader = "<tr><td colspan='11' class='s3' align='left' style='left:-5px;position:inherit;'>--" + data.InvoiceCurrCode_IR + "</td></tr>";
        return strHeader;
    }
    function tableHTMLHeader(data) {
        var strHeader = "<tr><td colspan='11' class='s3' align='left'><a class='linkParentTab' href='#'onclick=\"parent.tab_edit('Customers','list/customers', 'icon-edit', 'edit', '" + data.CustomerCode_IR + "')\" <?= $cek_autority_edit ?>><u><b>" + data.CustomerName_IR + " </b></u></a></td></tr>"
                + "<tr id='tableHeader'>"//baris heading table
                + "<td width='' class='s4'><span class='small_bold' >No</span></td>"
                + "<td width='80' class='s4 linkParentTab' style='cursor:pointer;' onclick=\"searching_data_aging_recv_detail('at_invoicereceipt','InvoiceDate');\"><span class='small_bold'>Date</span></td>"
                + "<td width='' class='s4 linkParentTab' style='cursor:pointer;' onclick=\"searching_data_aging_recv_detail('at_invoicereceipt','InvoiceNumber');\"><span class='small_bold'>No.Transaction</span></td>"
                + "<td width='' class='s4 linkParentTab' align='right' style='cursor:pointer;' onclick=\"searching_data_aging_recv_detail('at_salesinvoice','SInvTotalAmount');\"><span class='small_bold'>Inv.Amount</span></td>"
                + "<td width='' class='s4 linkParentTab' align='right' style='cursor:pointer;' onclick=\"searching_data_aging_recv_detail('at_srecdetail','SRecAmount');\"><span class='small_bold'>Paid</span></td>"
                //+ "<td width='' class='s4' align='right'><span class='small_bold'>Outstanding</span></td>"
                + "<td width='' class='s4' align='right'><span class='small_bold'>Not Yet</span></td>"
                + "<td width='' class='s4' align='right'><span class='small_bold'>1-30</span></td>"
                + "<td width='' class='s4' align='right'><span class='small_bold'>31-60</span></td>"
                + "<td width='' class='s4' align='right'><span class='small_bold'>61-90</span></td>"
                + "<td width='' class='s4' align='right'><span class='small_bold'>91-120</span></td>"
                + "<td width='' class='s4' align='right'><span class='small_bold'>&GT;120</span></td>"
                + "</tr>";
        return strHeader;
    }
    function tableHTMLContentFirst(noTree, noUrut, data) {
        var strContent = "<tr class='treegrid-" + noTree + "' style='-webkit-print-color-adjust:exact;background-color:#F4F4FF;font-weight: bold;'>"
                + "<td width='' class='s5'><span class='small_bold' >" + noUrut + "</span></td>"
                + "<td width='' class='s5'><span class='small_bold' >" + data.InvoiceDate_IR + "</span></td>"
                + "<td width='' class=''><span class='small_bold' ><a class='linkParentTab' href=\"#\" onclick=\"parent.tab_edit('Sales Invoices','list/sales_invoice', 'icon-edit', 'edit', '" + data.InvoiceNumber_IR + "')\" <?= $cek_autority_edit ?>>" + data.InvoiceNumber_IR + "(" + data.AgeDueDate_IR + " days)</a></span></td>"
                + "<td width='' class='s5' align='right'><span class='small_bold'>" + data.CurrencySymbol + " " + formatRp(data.InvoiceAmount_IR) + "</span></td>"//amount
                + "<td width='' class='s5' align='right'><span class='small_bold'>" + data.CurrencySymbol + " " + formatRp(data.ReceiptTotal_IR) + "</span></td>"//paid
                //+ "<td width='' class='s5' align='right'><span class='small_bold'>"+formatRp(data.InvoiceAmount_IR - data.ReceiptTotal_IR) + "</span></td>"//outstanding
                + "<td width='' class='s5' align='right'><span class='small_bold'>";
        data.AgeDueDate_IR <= 0 ? strContent += data.CurrencySymbol + " " + formatRp(data.InvoiceOwing_IR) : strContent += "-";
        strContent += "</span></td>"//Not Yet
                + "<td width='' class='s5' align='right'><span class='small_bold'>";
        data.AgeDueDate_IR >= 1 && data.AgeDueDate_IR <= 30 ? strContent += data.CurrencySymbol + " " + formatRp(data.InvoiceOwing_IR) : strContent += "-";
        strContent += "</span></td>"//1-30
                + "<td width='' class='s5' align='right'><span class='small_bold'>";
        data.AgeDueDate_IR >= 31 && data.AgeDueDate_IR <= 60 ? strContent += data.CurrencySymbol + " " + formatRp(data.InvoiceOwing_IR) : strContent += "-";
        strContent += "</span></td>"//31-60
                + "<td width='' class='s5' align='right'><span class='small_bold'>";
        data.AgeDueDate_IR >= 61 && data.AgeDueDate_IR <= 90 ? strContent += data.CurrencySymbol + " " + formatRp(data.InvoiceOwing_IR) : strContent += "-";
        strContent += "</span></td>"//61-90
                + "<td width='' class='s5' align='right'><span class='small_bold'>";
        data.AgeDueDate_IR >= 91 && data.AgeDueDate_IR <= 120 ? strContent += data.CurrencySymbol + " " + formatRp(data.InvoiceOwing_IR) : strContent += "-";
        strContent += "</span></td>"//90-120
                + "<td width='' class='s5' align='right'><span class='small_bold'>";
        data.AgeDueDate_IR > 120 ? strContent += data.CurrencySymbol + " " + formatRp(data.InvoiceOwing_IR) : strContent += "-";
        strContent += "</span></td>"//&GT;120
                + "</tr>";
        return strContent;
    }
    function tableHTMLContentOther(noTree, noTreeParent, noUrut, data) {
        var strContent = "";
        strContent = "<tr  class='treegrid-" + noTree + " treegrid-parent-" + noTreeParent + "'>"
                + "<td width='' class='s5'><span class='small_bold' >" + noUrut + "</span></td>"
                + "<td width='' class='s5'><span class='small_bold' >" + data.InvoiceDate_IR + "</span></td>"
                + "<td width='' class='s5'><span class='small_bold' ><a class='linkParentTab' href=\"#\" onclick=\"parent.tab_edit('Sales Invoices','list/sales_invoice', 'icon-edit', 'edit', '" + data.InvoiceNumber_IR + "')\" <?= $cek_autority_edit ?>>" + data.InvoiceNumber_IR + "(" + data.AgeDueDate_IR + ")</a></span></td>"
                + "<td width='' class='s5' align='right'><span class='small_bold'>" + formatRp(data.InvoiceAmount_IR) + "</span></td>"//amount
                + "<td width='' class='s5' align='right'><span class='small_bold'>" + formatRp(data.ReceiptTotal_IR) + "</span></td>"//paid
                //+ "<td width='' class='s5' align='right'><span class='small_bold'>"+formatRp(data.InvoiceAmount_IR - data.ReceiptTotal_IR) + "</span></td>"//outstanding
                + "<td width='' class='s5' align='right'><span class='small_bold'>";
        data.AgeDueDate_IR <= 0 ? strContent += " " + formatRp(data.InvoiceOwing_IR) : strContent += "-";
        strContent += "</span></td>"//Not Yet
                + "<td width='' class='s5' align='right'><span class='small_bold'>";
        data.AgeDueDate_IR >= 1 && data.AgeDueDate_IR <= 30 ? strContent += " " + formatRp(data.InvoiceOwing_IR) : strContent += "-";
        strContent += "</span></td>"//1-30
                + "<td width='' class='s5' align='right'><span class='small_bold'>";
        data.AgeDueDate_IR >= 31 && data.AgeDueDate_IR <= 60 ? strContent += " " + formatRp(data.InvoiceOwing_IR) : strContent += "-";
        strContent += "</span></td>"//31-60
                + "<td width='' class='s5' align='right'><span class='small_bold'>";
        data.AgeDueDate_IR >= 61 && data.AgeDueDate_IR <= 90 ? strContent += " " + formatRp(data.InvoiceOwing_IR) : strContent += "-";
        strContent += "</span></td>"//61-90
                + "<td width='' class='s5' align='right'><span class='small_bold'>";
        data.AgeDueDate_IR >= 91 && data.AgeDueDate_IR <= 120 ? strContent += " " + formatRp(data.InvoiceOwing_IR) : strContent += "-";
        strContent += "</span></td>"//90-120
                + "<td width='' class='s5' align='right'><span class='small_bold'>";
        data.AgeDueDate_IR > 120 ? strContent += " " + formatRp(data.InvoiceOwing_IR) : strContent += "-";
        strContent += "</span></td>"//&GT;120
                + "</tr>";
        return strContent;
    }
    function tableHTMLFooterSummary(data){
        var strFooter = "<tr>"
                + "<td class='s5' align='right' colspan='11'><hr class='hrTableSummary' style='size:3px;'></td></tr>"
                + "<tr><td class='s5' align='right' colspan='3'><b>TOTAL : </b></td>"
                + "<td width='' class='s5' align='right'><span class='small_bold' ><b>" + data.CurrencySymbol + " " + formatRp(data.amount) + "</b></span></td>"
                + "<td width='' class='s5' align='right'><span class='small_bold' ><b>" + data.CurrencySymbol + " " + formatRp(data.paid) + "</b></span></td>"
                + "<td width='' class='s5' align='right'><span class='small_bold'><b>" + data.CurrencySymbol + " " + formatRp(data.notYet) + "</b></span></td>"
                + "<td width='' class='s5' align='right'><span class='small_bold'><b>" + data.CurrencySymbol + " " + formatRp(data.r1_30) + "</b></span></td>"
                + "<td width='' class='s5' align='right'><span class='small_bold'><b>" + data.CurrencySymbol + " " + formatRp(data.r31_60) + "</b></span></td>"
                + "<td width='' class='s5' align='right'><span class='small_bold'><b>" + data.CurrencySymbol + " " + formatRp(data.r61_90) + "</b></span></td>"
                + "<td width='' class='s5' align='right'><span class='small_bold'><b>" + data.CurrencySymbol + " " + formatRp(data.r91_120) + "</b></span></td>"
                + "<td width='' class='s5' align='right'><span class='small_bold'><b>" + data.CurrencySymbol + " " + formatRp(data.blh_120) + "</b></span></td>"
                + "</tr>";
        return strFooter;
    }
    function tableHTMLBlankForNext() {
        var strFooter = "<tr id='rowBlankForNext'>"
                + "<td class='s5' align='right' colspan='10'></td></tr>";
        strFooter += "<tr id='tr-see-more'><td colspan='5'><br><br><input id='btn-see-more' name='btn-see-more' type='button' onclick='seeMore()' value=' See More ' style='cursor:pointer;'></td></tr>";

        return strFooter;
    }
    function summaryHTMLAll(tempBranch, alignTo, datas) {
        var strHeader = "";
        datas.forEach(function (data) {
            strHeader = "<table align='" + alignTo + "' cellpadding='2' cellspacing='0' class='margin-" + alignTo + "5persen table-summary' style='margin-bottom:80px;'>"
                    + "<tr id='tableHeader'>"
                    + "<td width='' class='s4 text-center' colspan='10' align='center'><span class='small_bold' >Summary <u>" + tempBranch + " Currency " + data.CodeCurr + "</u></span></td>"
                    + "</tr>"
                    + "<tr id='tableHeader'>"
                    + "<td width='' class='s4 ' align='left' style='padding-left:6px; padding-right:6px;'><span class='small_bold' >No</span></td>"
                    + "<td width='' class='s4 ' align='left' style='padding-left:6px; padding-right:6px;'><span class='small_bold' >Customer </span></td>"
                    + "<td width='' class='s4 ' align='right' style='padding-left:6px; padding-right:6px;'><span class='small_bold' >Amount</span></td>"
                    + "<td width='' class='s4 ' align='right' style='padding-left:6px; padding-right:6px;'><span class='small_bold' >Paid</span></td>"
                    + "<td width='' class='s4 ' align='right' style='padding-left:6px; padding-right:6px;'><span class='small_bold' >NotYet</span></td>"
                    + "<td width='' class='s4 ' align='right' style='padding-left:6px; padding-right:6px;'><span class='small_bold' >1-30</span></td>"
                    + "<td width='' class='s4 ' align='right' style='padding-left:6px; padding-right:6px;'><span class='small_bold' >31-60</span></td>"
                    + "<td width='' class='s4 ' align='right' style='padding-left:6px; padding-right:6px;'><span class='small_bold' >61-90</span></td>"
                    + "<td width='' class='s4 ' align='right' style='padding-left:6px; padding-right:6px;'><span class='small_bold' >90-120</span></td>"
                    + "<td width='' class='s4 ' align='right' style='padding-left:6px; padding-right:6px;'><span class='small_bold' >&GT;120</span></td>"
                    + "</tr>";
            var rowNo = 1;
            data['data'].forEach(function (datadet) {
                strHeader += "<tr>"
                        + "<td class='s5 text-left' style='padding-left:6px; padding-right:6px;'><b>" + rowNo + "</b></td>"
                        + "<td class='s5' align='left' style='padding-left:6px; padding-right:6px;'><b>" + datadet['Name'] + "</b></td>"
                        + "<td class='s5' align='right' style='padding-left:6px; padding-right:6px;'><b>" + datadet['CurrencySymbol'] + " " + formatRp(datadet['amount']) + "</b></td>"
                        + "<td class='s5' align='right' style='padding-left:6px; padding-right:6px;'><b>" + datadet['CurrencySymbol'] + " " + formatRp(datadet['paid']) + "</b></td>"
                        + "<td class='s5' align='right' style='padding-left:6px; padding-right:6px;'><b>" + datadet['CurrencySymbol'] + " " + formatRp(datadet['notYet']) + "</b></td>"
                        + "<td class='s5' align='right' style='padding-left:6px; padding-right:6px;'><b>" + datadet['CurrencySymbol'] + " " + formatRp(datadet['r1_30']) + "</b></td>"
                        + "<td class='s5' align='right' style='padding-left:6px; padding-right:6px;'><b>" + datadet['CurrencySymbol'] + " " + formatRp(datadet['r31_60']) + "</b></td>"
                        + "<td class='s5' align='right' style='padding-left:6px; padding-right:6px;'><b>" + datadet['CurrencySymbol'] + " " + formatRp(datadet['r61_90']) + "</b></td>"
                        + "<td class='s5' align='right' style='padding-left:6px; padding-right:6px;'><b>" + datadet['CurrencySymbol'] + " " + formatRp(datadet['r91_120']) + "</b></td>"
                        + "<td class='s5' align='right' style='padding-left:6px; padding-right:6px;'><b>" + datadet['CurrencySymbol'] + " " + formatRp(datadet['blh_120']) + "</b></td>"
                        + "</tr>";
                rowNo++;
            });
            strHeader += "</table>";
        });
        return strHeader;
    }

    function arJSONLevel_1(dtResults) {//isi array saat data adalah invoice sesuai jenis Currency
        var tempData = {
            InvoiceCurrCode_IR: dtResults.InvoiceCurrCode_IR,
            data: []
        };
        var ardt = arJSONLevel_2(dtResults);
        tempData['data'].push(ardt);
        return tempData;
    }
    function arJSONLevel_2(dtResults) {//isi array saat data adalah invoice sesuai jenis Currency
        var tempData = {
            CustomerCode_IR: dtResults.CustomerCode_IR,
            CustomerName_IR: dtResults.CustomerName_IR,
            CurrencySymbol: dtResults.CurrencySymbol,
            data: []
        };
        var ardt = arJSONLevel_3(dtResults);
        tempData['data'].push(ardt);
        return tempData;
    }
    function arJSONLevel_3(dtResults) {//isi data iinvoices number
        var tempData = {
            InvoiceNumber_IR: dtResults.InvoiceNumber_IR,
            InvoiceDate_IR: dtResults.InvoiceDate_IR,
            DueDate_IR: dtResults.DueDate_IR,
            AgeDueDate_IR: dtResults.AgeDueDate_IR,
            InvoiceCurrCode_IR: dtResults.InvoiceCurrCode_IR,
            InvoiceCurrRate_IR: dtResults.InvoiceCurrRate_IR,
            InvoiceFiscalRate_IR: dtResults.InvoiceFiscalRate_IR,
            InvoiceAmount_IR: dtResults.InvoiceAmount_IR,
            ReceiptTotal_IR: dtResults.ReceiptTotal_IR,
            InvoiceOwing_IR: dtResults.InvoiceOwing_IR,
            InvoiceType_IR: dtResults.InvoiceType_IR,
            DPStatus_IR: dtResults.DPStatus_IR,
            CustomerName_IR: dtResults.CustomerName_IR,
            NetDueIn_SI: dtResults.NetDueIn_SI,
            CurrencySymbol: dtResults.CurrencySymbol
        };
        return tempData;
    }
    function stringLegend() {
        var strLgnd = {
            marginLeft: '2%',
            datas: [
                {boxColor: '#F4F4FF', strLabel: "Data Sales Invoices"},
                {boxColor: '', strLabel: "'Date' : Tanggal Transaksi."},
                {boxColor: '', strLabel: "'No.Transaction' : Nomor Transaksi."},
                {boxColor: '', strLabel: "'Inv.Amount' : Jumlah Nominal Sales Invoice."},
                {boxColor: '', strLabel: "'Paid' : Jumlah Nominal Pembayaran Invoice."},
                {boxColor: '', strLabel: "'Not Yet' : Jumlah Nominal yang belum dibayar sebelum jatuh Tempo."},
                {boxColor: '', strLabel: "'1-30' : Jumlah Nominal yang belum dibayar yang sudah terlewat Tempo 1 hari s/d 30 hari."},
                {boxColor: '', strLabel: "'31-60' : Jumlah Nominal yang belum dibayar yang sudah terlewat Tempo 31 hari s/d 60 hari."},
                {boxColor: '', strLabel: "'61-90' : Jumlah Nominal yang belum dibayar yang sudah terlewat Tempo 61 hari s/d 90 hari."},
                {boxColor: '', strLabel: "'91-120' : Jumlah Nominal yang belum dibayar yang sudah terlewat Tempo 91 hari s/d 120 hari."},
                {boxColor: '', strLabel: "'>120' : Jumlah Nominal yang belum dibayar yang sudah terlewat Tempo lebih dari 120 hari."}
            ]
        };
        var rst = legendsTable(strLgnd);
        return rst;
    }
</script>
