<?php
/* 	
 * Author   : Dhidhik / Tanggal : 24-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 Payment dari sini------------------------------------------------------------------------>
<!--                <tr>
                    <td align="left" style="padding-bottom:8px;">
                        <b>by No.Invoice Payables</b>
                    </td>
                </tr>
                <tr>
                    <td align="left">
                        <input id="txt_noInvoices" name="txt_noInvoices" placeholder="< Nomor Invoice Payables >" style="margin:2px 0px 3px;width:100%;height:18px;border:1px solid #CCC;">
                    </td>
                </tr>-->
                <!------------end copy Invoice Payment dari sini---------------------------------------------------------------->

                <!--ini separator-------------------------------------------->
                <tr><td colspan="2"><div class="tr-divider"></div></td></tr>
                <!--end-------------------------------------------------------->
                <!-------copy Invoice Payment dari sini------------------------------------------------------------------------>
                <tr>
                    <td align="left" style="padding-bottom:8px;">
                        <b>by Vendor</b>
                    </td>
                </tr>
                <tr>
                    <td align="left">
                        <input id="txt_vendor" name="txt_vendor" placeholder="< Vendor Name >" style="margin:2px 0px 3px;width:100%;height:18px;border:1px solid #CCC;">
                    </td>
                </tr>
                <!------------end copy Invoice Payment 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_outstanding_invoices_payables('', '');" >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_payables/pre_ajax_reloadDataOutstandingInvoicesPayables';
    var url = base_url + 'report/index_account_payables/ajax_reloadDataOutstandingInvoicesPayables';
    var dataSend = {};
    var noTree = 1;
    var noUrutLevel_0 = 1;
    var stringHTML = "";
    var pages = {limit: limitRowInPage(), pages: 1};
    var tempArSumm = [];
    function variableDefault() {
        shortingText = "";
        rstTypeShorting = "ASC";
        dataSend = {};
        noTree = 1;
        noUrutLevel_0 = 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_outstanding_invoices_payables(txtTable, txtFieldShorting) {//(namaVariableTabelDiModel, namaField)
//        var url          = base_url + 'report/index_account_payables/ajax_reloadDataOutstandingInvoicesPayables';
        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_vendor: document.formFilterInv.txt_vendor.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('branchIsEmpty');
            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: " Outstanding Invoice (Payables) ",
                    startdate: preResult.startdate,
                    enddate: preResult.enddate,
                    colspan: 12
                };
                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='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, " ");

//        delRow="<tr>"
//            +"<td class='s5' align='right' colspan='9'><hr></td>"
//            +"</tr>";
//        htmls = htmls.replace(delRow, " ");
        //console.log("htmls = "+htmls);
        exportToExcel(htmls);
    }

    function prepareReport(parseResult) {
        var tempCode = "";
        var arTempDatas = [];
        // === LOOP PEMBACAAN DATA ===================================//
        parseResult.datas.forEach(function (dtResults) {
            if (tempCode == "") {//PEMBACAAN DATA PERTAMA KALI INVOICE
                if (dtResults.VendorCode != null && dtResults.VendorCode != "" && dtResults.VendorCode != undefined) {
                    tempCode = dtResults.Journal_Number;
                    var dataJSONLevel0 = arJSONLevel0(dtResults);
                    arTempDatas.push(dataJSONLevel0);
                }
            }//END PEMBACAAN DATA PERTAMA KALI                    
            else {//PEMBACAAN DATA UNTUK DATA PAYMENT
                var indexCodeLevel_0 = cekArraySummary(arTempDatas, "VendorCode", dtResults.VendorCode);//mendapatkan index array VENDOR
                //console.log("indexCodeLevel_0="+indexCodeLevel_0);
                if (indexCodeLevel_0 > -1) {//jika VENDOR ditemukan data yg sama
                    if ((dtResults.PInvNumber == null || dtResults.PInvNumber == "" || dtResults.PInvNumber == undefined) && dtResults.TransStatus == '1') {//invoice
                        var indexCodeLevel_1 = cekArraySummary(arTempDatas[indexCodeLevel_0]['data'], "Journal_Number", dtResults.Journal_Number);
                        if (indexCodeLevel_1 > -1) {//jika ditemukan invoice yang sama
                            if (arTempDatas[indexCodeLevel_0]['data'][indexCodeLevel_1]['invoicesOri'] == 1) {//cek data invoicenya temporer ato ori
                                //null
                            } else {
                                arTempDatas[indexCodeLevel_0]['TotalAllAmount'] = (arTempDatas[indexCodeLevel_0]['TotalAllAmount'] * 1) + (dtResults.totalAmount * 1);
                                arTempDatas[indexCodeLevel_0]['TotalAllFiscal'] = (arTempDatas[indexCodeLevel_0]['TotalAllFiscal'] * 1) + (dtResults.totalFiscal * 1);
                                arTempDatas[indexCodeLevel_0]['TransStatus'] = get_status(dtResults.TransStatus);

                                arTempDatas[indexCodeLevel_0]['data'][indexCodeLevel_1]['invoicesOri'] = 1;//1=beneran invoice, 0=invoices temporer
                                arTempDatas[indexCodeLevel_0]['data'][indexCodeLevel_1]['totalAmount'] = dtResults.totalAmount;
                                arTempDatas[indexCodeLevel_0]['data'][indexCodeLevel_1]['totalFiscal'] = dtResults.totalFiscal;
                                arTempDatas[indexCodeLevel_0]['data'][indexCodeLevel_1]['PInvNumber'] = dtResults.PInvNumber;
                                arTempDatas[indexCodeLevel_0]['data'][indexCodeLevel_1]['PPayFiscalStatus'] = dtResults.PPayFiscalStatus;
                                arTempDatas[indexCodeLevel_0]['data'][indexCodeLevel_1]['Journal_Date'] = dateSqlToIndo(dtResults.Journal_Date);
                                arTempDatas[indexCodeLevel_0]['data'][indexCodeLevel_1]['Journal_Number'] = dtResults.Journal_Number;
                                arTempDatas[indexCodeLevel_0]['data'][indexCodeLevel_1]['Sub_Type_Name'] = dtResults.Sub_Type_Name;
                                arTempDatas[indexCodeLevel_0]['data'][indexCodeLevel_1]['Acc_Type_Name'] = dtResults.Acc_Type_Name;
                                arTempDatas[indexCodeLevel_0]['data'][indexCodeLevel_1]['Amount_Currency'] = dtResults.Amount_Currency;
                                arTempDatas[indexCodeLevel_0]['data'][indexCodeLevel_1]['CurrencyCode'] = dtResults.CurrencyCode;
                                arTempDatas[indexCodeLevel_0]['data'][indexCodeLevel_1]['TransStatus'] = get_status(dtResults.TransStatus);
                            }
                        } else {
                            arTempDatas[indexCodeLevel_0]['TotalAllAmount'] = (arTempDatas[indexCodeLevel_0]['TotalAllAmount'] * 1) + (dtResults.totalAmount * 1);
                            arTempDatas[indexCodeLevel_0]['TotalAllFiscal'] = (arTempDatas[indexCodeLevel_0]['TotalAllFiscal'] * 1) + (dtResults.totalFiscal * 1);

                            var dataJSONLevel1 = arJSONLevel1(dtResults);
                            arTempDatas[indexCodeLevel_0]['data'].push(dataJSONLevel1);
                        }
                    } else if ((dtResults.PInvNumber != null && dtResults.PInvNumber != "" && dtResults.PInvNumber != undefined) && dtResults.TransStatus == '2') {//payment

                        if (dtResults.PPayFiscalStatus == 0) {
                            arTempDatas[indexCodeLevel_0]['TotalAllPaymentInv'] = (arTempDatas[indexCodeLevel_0]['TotalAllPaymentInv'] * 1) + (dtResults.totalAmount * 1);
                        } else if (dtResults.PPayFiscalStatus == 1) {
                            arTempDatas[indexCodeLevel_0]['TotalAllPaymentFiscal'] = (arTempDatas[indexCodeLevel_0]['TotalAllPaymentFiscal'] * 1) + (dtResults.PaymentFiscal * 1);
                        }

                        var indexCodeLevel_1 = cekArraySummary(arTempDatas[indexCodeLevel_0]['data'], "Journal_Number", dtResults.PInvNumber);
                        if (indexCodeLevel_1 > -1) {//jika Pinv sudah ada di data yang telah dibaca
                            var dataJSONLevel2 = arJSONLevel2(dtResults);
                            arTempDatas[indexCodeLevel_0]['data'][indexCodeLevel_1]['data'].push(dataJSONLevel2);
                        } else {
                            var dataJSONLevel1 = arJSONLevel3(dtResults);//karena invoice belum terbaca sebelumnya maka akan dibuat invoice termporernya
                            arTempDatas[indexCodeLevel_0]['data'].push(dataJSONLevel1);
                        }
                    }
                } else {
                    if (dtResults.VendorCode != null && dtResults.VendorCode != "" && dtResults.VendorCode != undefined) {
                        tempCode = dtResults.Journal_Number;
                        var dataJSONLevel0 = arJSONLevel0(dtResults);
                        arTempDatas.push(dataJSONLevel0);
                    }
                }
            }//end PEMBACAAN DATA UNTUK DATA PAYMENT

        });
        // === END LOOP PEMBACAAN DATA ============================/ 
        arTempDatas = cekTempDataOri(arTempDatas);
        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 = "";
        //MULAI LOOP
        pages['pages']<2?tempStringHtml += tableHTMLHeader():"";//membuat tabel header
        arTempDatas.forEach(function (arDataLevel_0) {//MULAI LOOP UNTUK DAPAT NAMA VENDOR 
            if (arDataLevel_0.TotalAllAmount == 0) {
            } else {
                tempStringHtml += tableHTMLContentFirst(noTree, noUrutLevel_0, arDataLevel_0);
                noUrutLevel_0++;
            }
        });
        //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);
            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='12' class='s3' align='left'><b><u>_____</u></b></td></tr>"
        var strHeader = "<tr id='tableHeader'>"//baris heading table
                + "<td width='' class='s4 text-left'><span class='small_bold' >No</span></td>"
                //+ "<td width='' class='s4 text-center'><span class='small_bold'>Date</span></td>"
                + "<td width='' class='s4 text-center'><span class='small_bold'>Vendor</span></td>"
                //+ "<td width='' class='s4 text-center'><span class='small_bold'>No.Transaction</span></td>"
                + "<td width='' class='s4 text-left'><span class='small_bold'>Total Amount</span></td>"
                + "<td width='' class='s4' align='right'><span class='small_bold'>Total Payment</span></td>"
                + "<td width='' class='s4' align='right'><span class='small_bold'>OutStanding<br>Inv.</span></td>"
                + "<td width='' class='s4' align='right'><span class='small_bold'>Tax PPN 10%</span></td>"
                + "<td width='' class='s4' align='right'><span class='small_bold'>Total Pay Tax</span></td>"
                + "<td width='' class='s4' align='right'><span class='small_bold'>OutStanding<br>Fiscal</span></td>"
                + "<td width='' class='s4' align='right'><span class='small_bold'>Balance</span></td>"
                //+ "<td width='' class='s4 text-left'><span class='small_bold' >Status</span></td>"
                + "</tr>"
                + "<tr>"
                + "<td width='' class='s5 text-center' colspan='9' align='center'><span class='small_bold' >Data Not Found</span></td>"
                + "</tr></table>";
        return strHeader;
    }
    function tableHTMLHeader() {
        var strHeader = "<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_outstanding_invoices_payables('avtrans_1','Journal_Date');\"><span class='small_bold'>Date</span></td>"
                + "<td class='s4 linkParentTab' style='cursor:pointer;' onclick=\"searching_data_outstanding_invoices_payables('amvendor_1','VendorName');\"><span class='small_bold'>Vendor</span></td>"
                //+ "<td width='' class='s4 linkParentTab' style='cursor:pointer;' onclick=\"searching_data_outstanding_invoices_payables('avtrans_1','Journal_Number');\"><span class='small_bold'>No.Transaction</span></td>"
                + "<td width='' class='s4' align='right' ><span class='small_bold'>Amount</span></td>"
                + "<td width='' class='s4' align='right'><span class='small_bold'>Payment</span></td>"
                + "<td width='' class='s4' align='right'><span class='small_bold'>Outstanding<br>Inv.</span></td>"
                + "<td width='' class='s4' align='right'><span class='small_bold'>Tax PPN 10%</span></td>"
                + "<td width='' class='s4' align='right'><span class='small_bold'>Pay Tax</span></td>"
                + "<td width='' class='s4' align='right'><span class='small_bold'>Outstanding<br>Tax</span></td>"
                + "<td width='' class='s4' align='right'><span class='small_bold'>Balance DP</span></td>"
                //+ "<td width='' class='s4 linkParentTab' align='right' style='cursor:pointer;' onclick=\"searching_data_outstanding_invoices_payables('avtrans_1','TransStatus');\"><span class='small_bold' >Status</span></td>"
                + "</tr>";
        return strHeader;
    }
    function tableHTMLContentFirst(noTree, noUrut, data) {
        strContent = "";
        if (data.PInvNumber == null || data.PInvNumber == "" || data.PInvNumber == undefined) {
            var strContent = "<tr class='s5 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.Journal_Date + "</span></td>"
                    + "<td class=' linkParentTab' style='cursor:pointer;' onclick=\"parent.tab_edit('Vendors','list/vendors', 'icon-edit', 'edit', '" + data.VendorCode + "')\" <?= $cek_autority_edit ?>><u><b>" + data.VendorName + " </b></u></td>"
                    //+ "<td width='' class='s5'><span class='small_bold' ><a class='linkParentTab' href=\"#\" onclick=\"parent.tab_edit('Purchase Invoices','list/purchases_invoice', 'icon-edit', 'edit', '" + data.Journal_Number + "')\" <?= $cek_autority_edit ?>>" +data.Journal_Number + "</a></span></td>"
                    + "<td width='' class=' linkParentTab' align='right' title='Detail Amount Invoices' style='cursor:pointer;' onclick=\"parent.tab_edit('Report Detail Total Amount','report/index_account_payables', 'icon-edit','detail_totalamount_outstanding_invoices_report','" + data.CompanyName + "/" + data.CompanyCode + "/" + data.BranchCode + "/" + data.VendorCode + "/" + data.VendorName +"/"+dataSend['txt_DateTo']+"')\"><span class='small_bold' >"+data.CurrencySymbol+" " + formatRp(data.TotalAllAmount) + "</span></td>"
                    + "<td width='' class=' linkParentTab' align='right' title='Detail Payment Invoices' style='cursor:pointer;' onclick=\"parent.tab_edit('Report Detail Payment Invoices','report/index_account_payables', 'icon-edit','detail_payment_outstanding_invoices_report','" + data.CompanyName + "/" + data.CompanyCode + "/" + data.BranchCode + "/" + data.VendorCode + "/" + data.VendorName + "/"+dataSend['txt_DateTo']+"')\"><span class='small_bold' >"+data.CurrencySymbol+" " + formatRp(data.TotalAllPaymentInv) + "</span></td>"
                    + "<td width='' class='s5' align='right'><span class='small_bold' >"+data.CurrencySymbol+" " + formatRp((data.TotalAllAmount * 1) - (data.TotalAllPaymentInv * 1)) + "</span></td>"
                    + "<td width='' class=' linkParentTab' align='right' title='Detail Amount Invoices' style='cursor:pointer;' onclick=\"parent.tab_edit('Report Detail Total Amount','report/index_account_payables', 'icon-edit','detail_totalamount_outstanding_invoices_report','" + data.CompanyName + "/" + data.CompanyCode + "/" + data.BranchCode + "/" + data.VendorCode + "/" + data.VendorName + "/"+dataSend['txt_DateTo']+"')\"><span class='small_bold' >Rp. " + formatRp(data.TotalAllFiscal) + "</span></td>"
                    + "<td width='' class=' linkParentTab' align='right' title='Detail Payment Invoices' style='cursor:pointer;' onclick=\"parent.tab_edit('Report Detail Payment Invoices','report/index_account_payables', 'icon-edit','detail_payment_outstanding_invoices_report','" + data.CompanyName + "/" + data.CompanyCode + "/" + data.BranchCode + "/" + data.VendorCode + "/" + data.VendorName + "/"+dataSend['txt_DateTo']+"')\"><span class='small_bold' >Rp. " + formatRp(data.TotalAllPaymentFiscal) + "</span></td>"
                    + "<td width='' class='s5' align='right'><span class='small_bold' >Rp. " + formatRp((data.TotalAllFiscal * 1) - (data.TotalAllPaymentFiscal * 1)) + "</span></td>"
                    + "<td width='' class='s5' align='right'><span class='small_bold' >"+data.CurrencySymbol+" " + formatRp((data.totalBalances * 1)) + "</span></td>"
                    //+ "<td width='' class='s5' align='right'><span class='small_bold' >" +data.TransStatus + "</span></td>"
                    + "</tr>";
        }
        return strContent;
    }
    function tableHTMLContentOther(noTree, noTreeParent, noUrut, data) {
        var strContent = "";
        if (data.PInvNumber != null && data.PInvNumber != "" && data.PInvNumber != undefined) {
            strContent = "<tr  class='treegrid-" + noTree + " treegrid-parent-" + noTreeParent + "' style='-webkit-print-color-adjust:exact;background-color:#EAFFFB;'>"
                    + "<td width='' class='s5'><span class='' >" + noUrut + "</span></td>"
                    //+ "<td width='' class='s5'><span class='' ></span>"+data.Journal_Date+"</td>"
                    + "<td width='' class='s5'><span class='' ><a class='linkParentTab' href=\"#\" onclick=\"parent.tab_edit('Purchase Payment','list/purchases_payment', 'icon-edit', 'edit', '" + data.Journal_Number + "')\"  <?= $cek_autority_edit ?>>" + data.Journal_Number + "</a></span></td>"
                    + "<td width='' class='s5'><span class='' ></span></td>";//total amount
            data.PPayFiscalStatus == 0 ? strContent += "<td width='' class='s5' align='right'><span class='' >" + formatRp(data.totalAmount) + "</span></td>" : strContent += "<td width='' class='s5'><span class='' ></span></td>";//payment invoice
            strContent += "<td width='' class='s5'><span class='' ></span></td>"//outstanding Invoice
                    + "<td width='' class='s5'><span class='' ></span></td>";//total Fiscal
            data.PPayFiscalStatus == 1 ? strContent += "<td width='' class='s5' align='right'><span class='' >" + formatRp(data.PaymentFiscal) + "</span></td>" : strContent += "<td width='' class='s5'><span class='' ></span></td>";//payment invoice
            strContent += "<td width='' class='s5'><span class='' ></span></td>"//outstanding Fiscal
                    + "<td width='' class='s5' align='right'><span class='' >balance</span></td>"//balace
                    + "<td width='' class='s5' align='right'><span class='' >" + data.TransStatus + "</span></td>"
                    + "</tr>";
        }
        return strContent;
    }
    function tableHTMLFooterSummary(TotalAmount, TotalFiscal, TotalPayInv, TotalPayFiscal) {
        var amount = TotalAmount >= 0 ? TotalAmount : 0;
        var payInv = TotalPayInv >= 0 ? TotalPayInv : 0;
        var payFiscal = TotalPayFiscal >= 0 ? TotalPayFiscal : 0;
        TotalFiscal = TotalFiscal >= 0 ? TotalFiscal : 0;
        var strFooter = "<tr>"
                + "<td class='s5' align='right' colspan='9'><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>" + formatRp(amount) + "</b></span></td>"
                + "<td width='' class='s5' align='right'><span class='small_bold'><b>" + formatRp(payInv) + "</b></span></td>"
                + "<td width='' class='s5' align='right'><span class='small_bold'><b></b></span></td>"
                + "<td width='' class='s5' align='right'><span class='small_bold'><b></b></span></td>"
                + "<td width='' class='s5' align='right'><span class='small_bold'><b>" + formatRp(payFiscal) + "</b></span></td>"
                + "</tr>"
                + "<tr><td colspan='7'><span> </span></td></tr>"
        return strFooter;
    }
    function tableHTMLFooter() {
        var strFooter = "<tr>"
                + "<td class='' align='right' colspan='9'><hr class='hrTableSummary'></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 arJSONLevel0(dtResults) {
        var arData = 0;
        var tempData = 0;
        tempData = {
            VendorCode: dtResults.VendorCode,
            VendorName: dtResults.VendorName,
            CompanyCode : dtResults.CompanyCode,
            BranchCode : dtResults.BranchCode,
            CurrencySymbol : dtResults.CurrencySymbol,
//            totalBalances_0           : dtResults.totalBalances_0,
//            totalBalances_1           : dtResults.totalBalances_1,
            totalBalances: dtResults.totalBalances,
            TransStatus: get_status(dtResults.TransStatus),
            TotalAllAmount: 0,
            TotalAllPaymentInv: 0,
            TotalAllFiscal: 0,
            TotalAllPaymentFiscal: 0,
            data: []
        };
        if (dtResults.PInvNumber == null || dtResults.PInvNumber == "" || dtResults.PInvNumber == undefined) { // jika PInvNumber kosong, berarti data invoice 
            if (dtResults.TransStatus == 1) {
                tempData['TotalAllAmount'] = (tempData['TotalAllAmount'] * 1) + (dtResults.totalAmount * 1);
                tempData['TotalAllFiscal'] = (tempData['TotalAllFiscal'] * 1) + (dtResults.totalFiscal * 1);
                arData = arJSONLevel1(dtResults);
                tempData['data'].push(arData);
            }
        } else {//data payment            
            if (dtResults.TransStatus == 2) {
                if (dtResults.PPayFiscalStatus == 0) {
                    tempData['TotalAllPaymentInv'] = (tempData['TotalAllPaymentInv'] * 1) + (dtResults.totalAmount * 1);
                } else if (dtResults.PPayFiscalStatus == 1) {
                    tempData['TotalAllPaymentFiscal'] = (tempData['TotalAllPaymentFiscal'] * 1) + (dtResults.PaymentFiscal * 1);
                }
            }
            arData = arJSONLevel3(dtResults);
            tempData['data'].push(arData);
        }
        return tempData;
    }
    function arJSONLevel1(dtResults) {//Data Invoice
        var tempData = {
            invoicesOri: 1, //1=beneran invoice, 0=invoices temporer
            VendorCode: dtResults.VendorCode,
            VendorName: dtResults.VendorName,
            totalAmount: dtResults.totalAmount,
            totalFiscal: dtResults.totalFiscal,
            PInvNumber: dtResults.PInvNumber,
            PPayFiscalStatus: dtResults.PPayFiscalStatus,
            Journal_Date: dateSqlToIndo(dtResults.Journal_Date),
            Journal_Number: dtResults.Journal_Number,
            Sub_Type_Name: dtResults.Sub_Type_Name,
            Acc_Type_Name: dtResults.Acc_Type_Name,
            Amount_Currency: dtResults.Amount_Currency,
            CurrencyCode: dtResults.CurrencyCode,
            TransStatus: get_status(dtResults.TransStatus),
            data: []
        };
        var arData = arJSONLevel2(dtResults);
        arData == 0 ? '' : tempData['data'].push(arData);
        return tempData;
    }
    function arJSONLevel2(dtResults) {//Data Payment dari invoice
        var tempData = 0;
        if (dtResults.PInvNumber != null && dtResults.PInvNumber != "" && dtResults.PInvNumber != undefined && dtResults.TransStatus == '2') {
            tempData = {
                totalAmount: dtResults.totalAmount,
                totalFiscal: dtResults.totalFiscal,
                PaymentFiscal : dtResults.PaymentFiscal,
                PInvNumber: dtResults.PInvNumber,
                PPayFiscalStatus: dtResults.PPayFiscalStatus,
                Journal_Date: dateSqlToIndo(dtResults.Journal_Date),
                Journal_Number: dtResults.Journal_Number,
                Sub_Type_Name: dtResults.Sub_Type_Name,
                Acc_Type_Name: dtResults.Acc_Type_Name,
                TransStatus: get_status(dtResults.TransStatus)
            };
        }

        return tempData;
    }
    function arJSONLevel3(dtResults) {//Data Invoice Temporer
        var tempData = {
            invoicesOri: 0, //1=beneran invoice, 0=invoices temporer
            VendorCode: dtResults.VendorCode,
            VendorName: dtResults.VendorName,
            totalAmount: dtResults.totalAmount,
            totalFiscal: dtResults.totalFiscal,
            PInvNumber: "",
            PPayFiscalStatus: dtResults.PPayFiscalStatus,
            Journal_Date: dateSqlToIndo(dtResults.Journal_Date),
            Journal_Number: dtResults.PInvNumber,
            Sub_Type_Name: dtResults.Sub_Type_Name,
            Acc_Type_Name: dtResults.Acc_Type_Name,
            Amount_Currency: dtResults.Amount_Currency,
            CurrencyCode: dtResults.CurrencyCode,
            TransStatus: get_status(dtResults.TransStatus),
            data: []
        };
        var arData = arJSONLevel2(dtResults);
        arData == 0 ? '' : tempData['data'].push(arData);
        return tempData;
    }
    function cekTempDataOri(arTempDatas) {
        var arTempDatas_copy = arTempDatas;
        var indexLevel_0 = 0;
        arTempDatas_copy.forEach(function (arDataLevel_0) {
            var indexLevel_1 = 0;
            arDataLevel_0['data'].forEach(function (arDataLevel_1) {
                if (arDataLevel_1['invoicesOri'] == 0) {
                    var indexLevel_2 = 0;
                    arDataLevel_1['data'].forEach(function (arDataLevel_2) {
                        if (arDataLevel_2['PPayFiscalStatus'] == 0) {
                            arTempDatas[indexLevel_0]['TotalAllPaymentInv'] = (arTempDatas[indexLevel_0]['TotalAllPaymentInv'] * 1) - (arDataLevel_2['totalAmount'] * 1);
                        } else if (arDataLevel_2['PPayFiscalStatus'] == 1) {
                            arTempDatas[indexLevel_0]['TotalAllPaymentFiscal'] = (arTempDatas[indexLevel_0]['TotalAllPaymentFiscal'] * 1) - (arDataLevel_2['PaymentFiscal'] * 1);
                        }
                        indexLevel_2++;
                    });
                }
                indexLevel_1++;
            });
            indexLevel_0++;
        });
        return arTempDatas;
    }
    function stringLegend() {
        var strLgnd = {
            marginLeft: '2%',
            datas: [
                {boxColor: '#F4F4FF !important', strLabel: "Data Outstanding Vendor Per Purchase Invoices"},
                {boxColor: '', strLabel: "'Vendor' : Nama Customer. "},
                {boxColor: '', strLabel: "'Amount' : Jumlah Nominal dari Sales Invoice. "},
                {boxColor: '', strLabel: "'Payment' : Jumlah Nominal dari pembayaran Invoice(termasuk DP dan Rounded, termasuk Discount)."},
                {boxColor: '', strLabel: "'Outstanding Inv' : Jumlah Nominal kekurangan dari Invoice yang belum dibayar. "},
                {boxColor: '', strLabel: "'Tax PPN 10%' : Jumlah Nominal dari Pajak 10%(dalam mata uang Rupiah,IDR). "},
                {boxColor: '', strLabel: "'Pay Tax' : Jumlah Nominal pembayaran untuk 'Tax PPN 10%'. "},
                {boxColor: '', strLabel: "'Outstanding Tax' : Jumlah Nominal kekurangan 'Tax PPN 10%' yang belum dibayar. "},
                {boxColor: '', strLabel: "'Balance DP' : Jumlah Nominal DP Customer yang belum digunakan. "}
            ]
        };
        var rst = legendsTable(strLgnd);
        return rst;
    }
</script>
