// ADDED BY PRAWIRA TGL 9 September 2015

// PINDAHAN DARI BASE_URL.JS
var base_url = "/accounting/";

// PINDAHAN DARI VALIDATE.JS
$(function () {
    $('input.currency').autoNumeric({aSep: '.', aDec: ',', aSign: '', vMax: '99999999999999.99'});
    $.fn.window.defaults.closable = false;
    $('.panel-tool-close').hide();
    // $.fn.combobox.onChange=function(newValue,oldValue){
    // 	alert('hallo');
    // }
});

//PINDAHAN DARI LINK.JS
function link_to(url) {
    location.href = base_url + url;
}

function link_print(url) {
    location.reload();
    uri = base_url + url;
    window.open(uri, '_blank', 'directories=0,titlebar=0,toolbar=0,location=0,status=0,menubar=0,scrollbars=no,resizable=no, width=1200, height=600, top=20, left=80');
}

function link_delete(title, url, icon, id) {
    location.href = base_url + url + "/delete/" + param;
}

// PINDAHAN DARI TAB.JS
function tab_reload() {
    $('#tt').datagrid('reload');
    //updateSize(); //memanggil function untuk tampilan lebih responsive
}

function tab_add(title, url, icon, func) {
    if (func != undefined) {
        url = base_url + url + '/' + func;
    }
    else {
        url = base_url + url;
    }

    if ($('#tt').tabs('exists', title)) {
        $('#tt').tabs('close', title);

        if(title =='New Variant'){
            /*================== CLose Tab Edit Delivery Order =======================*/
            $('#tt').tabs('close','Edit Delivery Order');
            /*================== end close tab edit delivery order ===================*/
        }
        
        var content = '<iframe scrolling="no"  id="ifmWindow" frameborder="0" src="' + url + '" style="width:100%;height:100%;"></iframe>';

        $('#tt').tabs('add', {
            title: title,
            content: content,
            icon: icon,
            closable: true
        });
    }
    else {

        if(title =='New Variant'){
            /*================== CLose Tab Edit Delivery Order =======================*/
            $('#tt').tabs('close','Edit Delivery Order');
            /*================== end close tab edit delivery order ===================*/
        }

        var content = '<iframe scrolling="no"  id="ifmWindow" frameborder="0" src="' + url + '" style="width:100%;height:100%;"></iframe>';

        $('#tt').tabs('add', {
            title: title,
            content: content,
            icon: icon,
            closable: true
        });
    }
    //updateSize(); //memanggil function untuk tampilan lebih responsive
}

function tab_edit(title, url, icon, func, id) {
    url = base_url + url + '/' + func + '/' + id;

    if ($('#tt').tabs('exists', title)) {
        $('#tt').tabs('close', title);

        var content = '<iframe scrolling="no"  id="ifmWindow" frameborder="0" src="' + url + '" style="width:100%;height:100%;"></iframe>';

        $('#tt').tabs('add', {
            title: title,
            content: content,
            icon: icon,
            closable: true
        });
    }
    else {
        var content = '<iframe scrolling="no"  id="ifmWindow" frameborder="0" src="' + url + '" style="width:100%;height:100%;"></iframe>';

        $('#tt').tabs('add', {
            title: title,
            content: content,
            icon: icon,
            closable: true
        });
    }
    //updateSize(); //memanggil function untuk tampilan lebih responsive
}

function tab_print_list(title, url, icon, func, company, branch) {
    url = base_url + url + '/' + func + '/' + company + '/' + branch;

    if ($('#tt').tabs('exists', title)) {
        $('#tt').tabs('close', title);

        var content = '<iframe scrolling="no"  id="ifmWindow" frameborder="0" src="' + url + '" style="width:100%;height:100%;"></iframe>';

        $('#tt').tabs('add', {
            title: title,
            content: content,
            icon: icon,
            closable: true
        });
    }
    else {
        var content = '<iframe scrolling="no"  id="ifmWindow" frameborder="0" src="' + url + '" style="width:100%;height:100%;"></iframe>';

        $('#tt').tabs('add', {
            title: title,
            content: content,
            icon: icon,
            closable: true
        });
    }
    //updateSize(); //memanggil function untuk tampilan lebih responsive
}

function tab_close(tabid) {
    var tab = $('#' + tabid).tabs('getSelected');
    var index = $('#' + tabid).tabs('getTabIndex', tab);

    $('#' + tabid).tabs('close', index);
    //updateSize(); //memanggil function untuk tampilan lebih responsive
}

// Bisa dibuang tapi harus ganti codingan di files dulu, abis itu di test.
function tab_close_this(tabid) {
    var tab = $('#' + tabid).tabs('getSelected');
    var index = $('#' + tabid).tabs('getTabIndex', tab);

    $('#' + tabid).tabs('close', index);
    //updateSize(); //memanggil function untuk tampilan lebih responsive
}

/*
 Rev By : Fachri
 Tgl : 15/04/2016
 */
function tab_close_all() {
    $.messager.confirm('Confirm', 'Are your sure to close all window tabs?', function (r) {
        if (r) {
            location.reload();
        }
        //updateSize(); //memanggil function untuk tampilan lebih responsive
    });
}

function get_in_tab() {
    var tab = $('#tt').tabs('getSelected');
    var index = $('#tt').tabs('getTabIndex', tab);

    return index;
}

// PINDAHAN DARI MODAL.JS
function modal_open(title, divid) {
    $('#' + divid).dialog('open').dialog('setTitle', title);
}

function modal_close(divid) {
    clear_data();
    $('#' + divid).dialog('close');
}

// PINDAHAN DARI DATA.JS
function clear_data() {
    $('#fm').form('clear');
}

function save_data(url, form_id, clear) {
    url = base_url + url;

    $(form_id).form('submit', {
        url: url + '/insert',
        onSubmit: function () {

            var isValid = $(this).form('validate');
            if (!isValid) {
                return $(this).form('validate');
            } else {
                modal_open('Progress Bar', 'dlg_loading');
            }

        },
        success: function (result) {
            var result = eval('(' + result + ')');

            if (result.status == true) {
                $.messager.alert('Success', result.message, 'info', function () {
                    location.reload();
                });

                if (clear == 1) {
                    $(form_id).form('clear');
                }
            }
            else if(result.status == 'session'){
                $.messager.alert('Unsuccessfull', result.message, 'info', function () {
                    location.reload();
                });
            }
            else {
                $.messager.alert('Unseccessfull', result.message, 'info', function () {

                });
            }
            modal_close('dlg_loading');
        },
        statusCode: {
            404: function () {
                alert("Page Not Found");
            }
        }
    });
}

function save_transaction(url, form_id) {
    url = base_url + url;

    $(form_id).form('submit', {
        url: url + '/insert',
        onSubmit: function () {
            var isValid = $(this).form('validate');
            if (!isValid) {
                return $(this).form('validate');
            } else {
                $('.easyui-linkbutton').linkbutton('disable');
                modal_open('Progress Bar', 'dlg_loading');
            }
        },
        success: function (result) {
            var result = eval('(' + result + ')');
            //console.log(result);
            if (result.status == true) {
                $.messager.alert('Success', result.message, 'info', function () {
                    location.reload();
                });
				
				if(result.chk_no == true){
					parent.tab_close('tt');
				}
            }
            else if(result.status == 'session'){
                $.messager.alert('Unsuccessfull', result.message, 'info', function () {
                    location.reload();
                });
            }
            else {
                $.messager.alert('Unsuccessfull', result.message, 'info', function () {
                    location.reload();
                });
            }
            modal_close('dlg_loading');
        }
    });
}

function save_transaction_other(url, form_id) {
    url = base_url + url;

    $(form_id).form('submit', {
        url: url + '/insert_other',
        onSubmit: function () {
            var isValid = $(this).form('validate');
            if (!isValid) {
                return $(this).form('validate');
            } else {
                $('.easyui-linkbutton').linkbutton('disable');
                modal_open('Progress Bar', 'dlg_loading');
            }
        },
        success: function (result) {
            var result = eval('(' + result + ')');
            //console.log(result);
            if (result.status == true) {
                $.messager.alert('Success', result.message, 'info', function () {
                    parent.tab_close('tt');
                });
            }
            else if(result.status == 'session'){
                $.messager.alert('Unsuccessfull', result.message, 'info', function () {
                    location.reload();
                });
            }
            else {
                $.messager.alert('Unsuccessfull', result.message, 'info', function () {
                    location.reload();
                });
            }
            modal_close('dlg_loading');
        }
    });
}

function save_preferen(url, form_id) {
    url = base_url + url;

    $(form_id).form('submit', {
        url: url + '/insert',
        onSubmit: function () {
            return $(this).form('validate');
        },
        success: function (result) {
            var result = eval('(' + result + ')');

            if (result.status == true) {
                $.messager.alert('Success', result.message, 'info', function () {
                    location.reload();
                });
            }
            else if(result.status == 'session'){
                $.messager.alert('Unsuccessfull', result.message, 'info', function () {
                    location.reload();
                });
            }
            else {
                $.messager.alert('Unseccessfull', result.message, 'info', function () {

                });
            }
        },
        statusCode: {
            404: function () {
                alert("Page Not Found");
            }
        }
    });
}

function edit_data(url, form_id, created_by, login_as, department_by, department_session, job_title_status) {
    if (job_title_status == 0) {
        proses_edit_data(url, form_id);
    }
    else if ((job_title_status == 1) && (department_by == department_session)) {
        proses_edit_data(url, form_id);
    }
    else if (created_by == login_as) {
        proses_edit_data(url, form_id);
    }
    else {
        $.messager.alert('Warning', 'Maaf anda tidak berhak merubah transaksi ini, silahkan cek hak akses anda', 'warning', function () {

        });
    }
}

function proses_edit_data(url, form_id) {
    url = base_url + url;

    $(form_id).form('submit', {
        url: url + '/update',
        onSubmit: function () {
            var isValid = $(this).form('validate');
            if (!isValid) {
                return $(this).form('validate');
            } else {
                modal_open('Progress Bar', 'dlg_loading');
            }
        },
        success: function (result) {
            var result = eval('(' + result + ')');

            if (result.status == true) {
                $.messager.alert('Success', result.message, 'info', function () {
                    location.reload();
                });
            }
            else if(result.status == 'session'){
                $.messager.alert('Unsuccessfull', result.message, 'info', function () {
                    location.reload();
                });
            }else{
                $.messager.alert('Unsuccessfull', result.message, 'info');
            }
            modal_close('dlg_loading');
      },
        statusCode: {
            404: function () {
                alert("Page Not Found");
            }
        }
    });
}

function delete_grid_job(url, id) {
    url = base_url + url;
    $.messager.confirm('Confirm', 'Are you sure you want to remove this data ?',
            function (r) {
                if (r) {
                    $.post(url + '/delete_grid', {id: id}, function (result) {
                        if (result.status == true) {
                            $.messager.show({// show error message
                                title: 'Succesfull',
                                msg: result.message,
                                style: {
                                    right: '',
                                    bottom: ''
                                }
                            });
                            $('#dg_job').datagrid('reload'); // reload the user data
                        }
                        else if(result.status == 'session'){
                            $.messager.alert('Unsuccessfull', result.message, 'info', function () {
                                location.reload();
                            });
                        }
                        else {
                            $.messager.show({// show error message
                                title: 'Error',
                                msg: result.message,
                                style: {
                                    right: '',
                                    bottom: ''
                                }
                            });
                        }
                    }, 'json');
                }
            });
}

function delete_data(url, id) {
    url = base_url + url;
    $.messager.confirm('Confirm', 'Are you sure you want to remove this data ?',
        function (r) {
            if (r) {
                $.post(url + '/delete', {id: id}, function (result) {
                    if (result.status == true) {
                        $.messager.alert('Success', result.message, 'info', function () {
                            location.reload();
                        });
                    }
                    else if(result.status == 'session'){
                        $.messager.alert('Unsuccessfull', result.message, 'info', function () {
                            location.reload();
                        });
                    }
                    else {
                        $.messager.alert('Error', result.message, 'error', function () {
                            //location.reload();							
                        });
                    }
                }, 'json');
        }
    });
}

function import_data_coa(url, form_id, dialog_id) {
    url = base_url + url;
    $(form_id).form('submit', {
        url: url + '/import',
        onSubmit: function () {
            return $(this).form('validate');
        },
        success: function (result) {
            var result = eval('(' + result + ')');
            if (result.status == true) {
                $.messager.alert('Succesfull', result.message, 'info', function () {
                    location.reload();
                });
            }
            else if(result.status == 'session'){
                $.messager.alert('Unsuccessfull', result.message, 'info', function () {
                    location.reload();
                });
            }
            else {
                $.messager.alert('Unseccessfull', result.message, 'info', function () {
                    location.reload();
                });
            }
            modal_close(dialog_id);
            $('#tt').datagrid('reload'); // reload the user data
        }
    });
}

function import_data(url, form_id, dialog_id) {
    url = base_url + url;
    $(form_id).form('submit', {
        url: url + '/import',
        onSubmit: function () {
            return $(this).form('validate');
        },
        success: function (result) {
            var result = eval('(' + result + ')');
            if (result.status == true) {
                $.messager.alert('Succesfull', result.message, 'info', function () {
                    location.reload();
                });
            }
            else if(result.status == 'session'){
                $.messager.alert('Unsuccessfull', result.message, 'info', function () {
                    location.reload();
                });
            }
            else {
                $.messager.alert('Unseccessfull', result.message, 'info', function () {

                });
            }
            modal_close(dialog_id);
            $('#tt').datagrid('reload'); // reload the user data
        }
    });
}

function import_transaksi(url, form_id, dialog_id) {
    url = base_url + url;

    $(form_id).form('submit', {
        url: url + '/insert',
        onSubmit: function () {
            return $(this).form('validate');
        },
        success: function (result) {
            var result = eval('(' + result + ')');
            if (result.status == true) {
                $.messager.alert('Succesfull', result.message, 'info', function () {
                    location.reload();
                });
            }
            else if(result.status == 'session'){
                $.messager.alert('Unsuccessfull', result.message, 'info', function () {
                    location.reload();
                });
            }
            else {
                $.messager.alert('Unseccessfull', result.message, 'info', function () {

                });
            }
            modal_close(dialog_id);
            $('#tt').datagrid('reload'); // reload the user data
        }
    });
}

function check_data(url, form_id) {
    url = base_url + url;

    $(form_id).form('submit', {
        url: url,
        onSubmit: function () {
            return $(this).form('validate');
        },
        success: function (result) {
            var result = eval('(' + result + ')');


        },
        statusCode: {
            404: function () {
                alert("Page Not Found");
            }
        }
    });
}

/*
 Add By Fachri
 */
function custom_data(url, form_id) {
    url = base_url + url;

    $(form_id).form('submit', {
        url: url,
        onSubmit: function () {
            return $(this).form('validate');
        },
        success: function (result) {
            var result = eval('(' + result + ')');

            if (result.status == true) {
                $.messager.alert('Successful', result.message, 'info', function () {
                    location.reload();
                });
            }
            else if(result.status == 'session'){
                $.messager.alert('Unsuccessfull', result.message, 'info', function () {
                    location.reload();
                });
            }
            else {
                $.messager.alert('Unsuccessfull', result.message, 'info', function () {

                });
            }
        },
        statusCode: {
            404: function () {
                alert("Page Not Found");
            }
        }
    });
}
/*===============================END==========================================*/

/* Wahyu Payment Karyawan */
function save_payment(url, form_id, clear, idgrid) {
    url = base_url + url;
    $(form_id).form('submit', {
        url: url + '/insert',
        onSubmit: function () {
            return $(this).form('validate');
        },
        success: function (result) {
            var result = eval('(' + result + ')');
            if (result.status == true) {
                $.messager.show({
                    title: 'Succesfull',
                    msg: result.message,
                    style: {
                        right: '',
                        bottom: ''
                    }
                });

                if (clear == 1) {
                    $(form_id).form('clear');
                }

                if (idgrid) {
                    $(idgrid).datagrid('reload');
                    location:reload();
                }

                $('#print_button').linkbutton('enable');
                $('#save_button').linkbutton('disable');
            }
            else if(result.status == 'session'){
                $.messager.alert('Unsuccessfull', result.message, 'info', function () {
                    location.reload();
                });
            }
            else {
                $.messager.show({
                    title: 'Unseccessfull',
                    msg: result.message,
                    style: {
                        right: '',
                        bottom: ''
                    }
                });

                $('#print_button').linkbutton('disable');
                $('#save_button').linkbutton('enable');
            }
        },
        statusCode: {
            404: function () {
                alert("Page Not Found");
            }
        }
    });
}

// kemungkinan akan di pindah ke section search.js
function search_data_department_no() {
    $('#txt_find_dep_no').keyup(function () {
        $("#search_no_department").submit();
    });
}

function search_data_department_name() {
    $('#txt_find_department_name').keyup(function () {
        $("#search_department_name").submit();
    });
}

function SearchData() {
    $('#txt_journal_voucher_no').keyup(function () {
        $('#tt').datagrid('reload');
    });
}
// end

// harus di buang, cek konsistensi di coding karena masih di pakai. harusnya memakai suspend_data_new pada semua codingan.
function suspend_data(url, datagrid_id, id) {
    url = base_url + url;

    $.messager.confirm('Confirm', 'Anda Yakin Akan Membatalkan Transaksi ?',
            function (r) {
                if (r) {
                    $.post(url + '/suspend', {id: id}, function (result) {
                        if (result.status == true) {
                            $.messager.alert('Berhasil', result.message, 'info', function () {
                                $(datagrid_id).datagrid('reload');
                            });
                        }
                        else if(result.status == 'session'){
                            $.messager.alert('Unsuccessfull', result.message, 'info', function () {
                                location.reload();
                            });
                        }
                        else {
                            $.messager.alert('Maaf', result.message, 'error', function () {
                                $(datagrid_id).datagrid('reload');
                            });
                        }
                    }, 'json');
                }
            });
}

/*Added by Hasan on 12/02/2015*/
/*Rev by Fachri on 14/12/2015*/
function suspend_check_trans(location, type, url, id, action, url_check, created_by, login_as, job_title){
	if(job_title == 0){
		suspend_data_new_check(location, type, url, id, action, url_check);
	}
	else if((job_title == 1)){
		suspend_data_new_check(location, type, url, id, action, url_check);
	}
	else if(created_by == login_as){
		suspend_data_new_check(location, type, url, id, action, url_check);
	}
	else{
		$.messager.alert('Warning','Maaf anda tidak berhak merubah transaksi ini, karena transaksi yang dibuat tidak sesuai dengan akun login','warning',function(){
			//$('#dtg_list_invoice').edatagrid('reload');
		});
		$('#chk_suspended').prop('checked', false);
	}
}

function suspend_data_new(location, type, url, id, action) {
    $.messager.confirm('Confirm', 'Anda Yakin Akan Membatalkan Transaksi ?', function (r) {
        if (r) {
            url = base_url + url;

            if (type == 1) { // If type is 1=> Default Suspend
                trans_status = 3;
            }
            else if (type == 2) { // If type is 2=> Cancel by Dir.
                trans_status = 9;
            }

            $.post(url + '/suspend_data', {id: id, trans_status: trans_status}, function (result) {
                if (result.status == true) {
                    $.messager.alert('Berhasil', result.message, 'info', function () {
                        if (location == 'L') { // If Suspend is triggered in Form
                            $(action).datagrid('reload');
                        }
                        else if (location == 'F') { // If Suspend is triggered in List
                            parent.tab_close('tt');
                        }
                    });
                }
                else if(result.status == 'session'){
                    $.messager.alert('Unsuccessfull', result.message, 'info', function () {
                        location.reload();
                    });
                }
                else {
                    $.messager.alert('Unseccessfull', result.message, 'error', function () {
                        parent.tab_close('tt');
                    });
                }
            }, 'json');
        }
        else {
            $('#chk_suspended').prop('checked', false);
        }
    });
}

/*
 New Suspen Data with Check trans status
 */
function suspend_data_new_check(location, type, url, id, action, url_check) {
    var no_transaksi = id;

    $.messager.confirm('Confirm', 'Anda Yakin Akan Membatalkan Transaksi ?', function (r) {
        if (r) {
            $.post(url_check, {no_transaksi: no_transaksi}, function (result) {
                if (result.status === true) {
                    proses_suspend_data(location, type, url, id, action);
                }
                else {
                    $.messager.alert('Unseccessfull', result.message, 'error', function () {
                        parent.tab_close('tt');
                    });
                }
            }, 'json');
        }
        else {
            $('#chk_suspended').prop('checked', false);
        }
    });
}

function proses_suspend_data(location, type, url, id, action) {

    url = base_url + url;

    if (type == 1) { // If type is 1=> Default Suspend
        trans_status = 3;
    }
    else if (type == 2) { // If type is 2=> Cancel by Dir.
        trans_status = 9;
    }

    $.post(url + '/suspend_data', {id: id, trans_status: trans_status}, function (result) {
        if (result.status == true) {
            $.messager.alert('Berhasil', result.message, 'info', function () {
                if (location == 'L') { // If Suspend is triggered in Form
                    $(action).datagrid('reload');
                }
                else if (location == 'F') { // If Suspend is triggered in List
                    parent.tab_close('tt');
                }
            });
        }
        else if(result.status == 'session'){
            $.messager.alert('Unsuccessfull', result.message, 'info', function () {
                location.reload();
            });
        }
        else {
            $.messager.alert('Maaf', result.message, 'error', function () {
                parent.tab_close('tt');
            });
        }
    }, 'json');
}
/*===================================End========================================================*/

/*
 Edit transsaction with check trans status
 */
function edit_transaction_not_check(url, form_id, no_transaksi, url_check, status,created_by, login_as, job_title){
	if(job_title == 0){
		proses_edit_transaction(url, form_id);
	}
	else if((job_title == 1)){
		proses_edit_transaction(url, form_id);
	}
	else if(created_by == login_as){
		proses_edit_transaction(url, form_id);
	}
	else{
		$.messager.alert('Warning','Maaf anda tidak berhak merubah transaksi ini, karena transaksi yang dibuat tidak sesuai dengan akun login','warning',function(){
			//$('#dtg_list_invoice').edatagrid('reload');
		});
		$('#chk_suspended').prop('checked', false);
	} 
}

function edit_transaction_check(url, form_id, no_transaksi, url_check, status,created_by, login_as, job_title){
	if(job_title == 0){
		edit_transaction(url, form_id, no_transaksi, url_check, status);
	}
	else if((job_title == 1)){
		edit_transaction(url, form_id, no_transaksi, url_check, status);
	}
	else if(created_by == login_as){
		edit_transaction(url, form_id, no_transaksi, url_check, status);
	}
	else{
		$.messager.alert('Warning','Maaf anda tidak berhak merubah transaksi ini, karena transaksi yang dibuat tidak sesuai dengan akun login','warning',function(){
			//$('#dtg_list_invoice').edatagrid('reload');
		});
		$('#chk_suspended').prop('checked', false);
	} 
}

function edit_transaction(url, form_id, no_transaksi, url_check, status) {
    $.post(url_check, {no_transaksi: no_transaksi, status: status}, function (result) {
        if (result.status === true) {
            proses_edit_transaction(url, form_id);
        }
        else {
            $.messager.alert('Unseccessfull', result.message, 'error', function () {
                location.reload();
            });
        }
    }, 'json');
}

function proses_edit_transaction(url, form_id) {
    url = base_url + url;

    $(form_id).form('submit', {
        url: url + '/update',
        onSubmit: function () {
            var isValid = $(this).form('validate');
            if (!isValid) {
                return $(this).form('validate');
            } else {
                $('.easyui-linkbutton').linkbutton('disable');
                modal_open('Progress Bar', 'dlg_loading');
            }
        },
        success: function (result) {
            var result = eval('(' + result + ')');

            if (result.status == true) {
                $('.easyui-linkbutton').linkbutton('disable');
                $.messager.alert('Success', result.message, 'info', function () {
                    location.reload();
                });
            }
            else if(result.status == 'session'){
                $.messager.alert('Unsuccessfull', result.message, 'info', function () {
                    location.reload();
                });
            }
            else {
                $.messager.alert('Unseccessfull', result.message, 'info', function () {
                    location.reload();
                });
            }
            modal_close('dlg_loading');
        },
        statusCode: {
            404: function () {
                alert("Page Not Found");
            }
        }
    });
}

/*
 Custome App Add By Fachri
 */
function app_custom(url, form_id, no_transaksi, url_check) {
    $.post(url_check, {no_transaksi: no_transaksi}, function (result) {
        if (result.status === false) {
            proses_custom_data(url, form_id);
        }
        else {
            $.messager.alert('Unseccessfull', result.message, 'error', function () {
                location.reload();
            });
        }
    }, 'json');
}

function proses_custom_data(url, form_id) {
    url = base_url + url;

    $(form_id).form('submit', {
        url: url,
        onSubmit: function () {
            var isValid = $(this).form('validate');
            if (!isValid) {
                return $(this).form('validate');
            } else {
                modal_open('Progress Bar', 'dlg_loading');
            }
        },
        success: function (result) {
            var result = eval('(' + result + ')');

            if (result.status == true) {
                $.messager.alert('Successful', result.message, 'info', function () {
                    location.reload();
                });
            }
            else if(result.status == 'session'){
                $.messager.alert('Unsuccessfull', result.message, 'info', function () {
                    location.reload();
                });
            }
            else {
                $.messager.alert('Unsuccessfull', result.message, 'info', function () {

                });
            }
            modal_close('dlg_loading');
        },
        statusCode: {
            404: function () {
                alert("Page Not Found");
            }
        }
    });
}
/*===============================END==========================================*/
/*End of added by Hasan on 12/02/2015*/

/*Added by daswan on 29/09/2015*/
function reverse_data_by_detail(url, form_id) {
    url = base_url + url;

    $(form_id).form('submit', {
        url: url + '/reverse_data_detail',
        onSubmit: function () {
            return $(this).form('validate');
        },
        success: function (result) {
            var result = eval('(' + result + ')');

            if (result.status == true) {
                $.messager.alert('Success', result.message, 'info', function () {
                    location.reload();
                });
            }
            else if(result.status == 'session'){
                $.messager.alert('Unsuccessfull', result.message, 'info', function () {
                    location.reload();
                });
            }
            else {
                $.messager.alert('Unsuccessfull', result.message, 'info');
            }
			
			modal_close('dlg_loading');
      },
        statusCode: {
            404: function () {
                alert("Page Not Found");
            }
        }
    });
}

/*Added by fachri on 11/09/2015*/
function suspend_data_new_master(location, type, url, id, action) {
    $.messager.confirm('Confirm', 'Anda Yakin Akan Non Active Master Ini?', function (r) {
        if (r) {
            url = base_url + url;

            if (type == 1) { // If type is 1=> Default Suspend
                trans_status = 2;
            }
            else if (type == 2) { // If type is 2=> Cancel by Dir.
                trans_status = 5;
            }

            $.post(url + '/suspend_data', {id: id, trans_status: trans_status}, function (result) {
                if (result.status == true) {
                    $.messager.alert('Berhasil', 'Data berhasil di suspend', 'info', function () {
                        if (location == 'L') { // If Suspend is triggered in Form
                            $(action).datagrid('reload');
                        }
                        else if (location == 'F') { // If Suspend is triggered in List
                            parent.tab_close('tt');
                        }
                    });
                }
                else if(result.status == 'session'){
                    $.messager.alert('Unsuccessfull', result.message, 'info', function () {
                        location.reload();
                    });
                }
                else {
                    $.messager.alert('Maaf', result.message, 'error', function () {
                        $('#chk_suspended').prop('checked', false);
                    });
                }
            }, 'json');
        }
        else {
            $('#chk_suspended').prop('checked', false);
        }
    });
}

// cek kembali codingan untuk konsistensi. kemungkinan besar tidak dipakai.
function suspend_data_on_new_form(url, id/*, trans_status*/) {
    url = base_url + url;

    /*if(trans_status==3)
     confirm_message = "Anda Yakin Akan Mengaktifkan Kembali Transaksi ini?";
     else
     confirm_message = "Anda Yakin Akan Membatalkan Transaksi ini?";*/

    $.messager.confirm('Confirm', 'Anda Yakin Akan Mengaktifkan Kembali Transaksi ?'/*confirm_message*/,
            function (r) {
                if (r) {
                    $.post(url + '/suspend', {id: id}, function (result) {
                        if (result.status == true) {
                            $.messager.show({// show sucess message
                                title: 'Success',
                                msg: result.message,
                                style: {
                                    right: '',
                                    bottom: ''
                                }
                            });
                        }
                        else if(result.status == 'session'){
                            $.messager.alert('Unsuccessfull', result.message, 'info', function () {
                                location.reload();
                            });
                        }
                        else {
                            $.messager.show({// show error message
                                title: 'Error',
                                msg: result.message,
                                style: {
                                    right: '',
                                    bottom: ''
                                }
                            });
                        }
                    }, 'json');
                }
                else {
                    if ($("#chk_status").prop("checked")) {
                        $("#chk_status").prop("checked", false);
                    }
                    else {
                        $("#chk_status").prop("checked", true);
                    }
                }
            });
}

// PINDAHAN DARI SEARCH.JS
// COMMENTED BY PRAWIRA TGL 9 SEPTEMBER 2015
// TOLONG DIBUANG KALAU SEARCH FUNCTION UNTUK FILTERING SUDAH OK UNTUK SETIAP FORM!!
// URGENT !!!!
/* Cash and Bank */
// Payment <=250rb
function search_payment() {
    TransStatus = new Array();
    $.each($('input[name="TransStatus"]:checked'), function () {
        TransStatus.push($(this).val());
    });

    $('#tt').datagrid('load', {
        payment_number: $('#txt_no').val(),
        payment_dsc: $('#txt_description').val(),
        date_from: $('#txt_from_date').datebox('getValue'),
        date_to: $('#txt_to_date').datebox('getValue'),
        status: TransStatus
    });
}
// Deposit
function search_deposit() {
    TransStatus = new Array();
    $.each($('input[name="TransStatus"]:checked'), function () {
        TransStatus.push($(this).val());
    });

    $('#tt_deposit').datagrid('load', {
        deposit_no: $('#txt_deposit_no').val(),
        deposit_memo: $('#txt_deposit_memo').val(),
        from_date: $('#txt_from_date').datebox('getValue'),
        to_date: $('#txt_to_date').datebox('getValue'),
        status: TransStatus
    });
}

// Sweep Bank
function search_swapbank() {
    TransStatus = new Array();
    $.each($('input[name="TransStatus"]:checked'), function () {
        TransStatus.push($(this).val());
    });

    $('#tt_swapbank').datagrid('load', {
        swapbank_no: $('#txt_swapbank_no').val(),
        swapbank_memo: $('#txt_swapbank_memo').val(),
        from_date: $('#txt_from_date').datebox('getValue'),
        to_date: $('#txt_to_date').datebox('getValue'),
        status: TransStatus
    });
}

// Piutang Afiliasi
function search_afiliasi() {
    TransStatus = new Array();
    $.each($('input[name="TransStatus"]:checked'), function () {
        TransStatus.push($(this).val());
    });

    $('#tt').datagrid('load', {
        transfer_from: $('#txt_transferfrom').val(),
        transfer_to: $('#txt_transferto').val(),
        date_from: $('#txt_from_date').datebox('getValue'),
        date_to: $('#txt_to_date').datebox('getValue'),
        status: TransStatus
    });
}

// Payment Afiliasi
function search_payment_afiliasi() {
    TransStatus = new Array();
    $.each($('input[name="TransStatus"]:checked'), function () {
        TransStatus.push($(this).val());
    });

    $('#tt').datagrid('load', {
        transfer_from: $('#txt_transferfrom').val(),
        transfer_to: $('#txt_transferto').val(),
        date_from: $('#txt_from_date').datebox('getValue'),
        date_to: $('#txt_to_date').datebox('getValue'),
        status: TransStatus
    });
}

// Piutang Karyawan
function search_piutang_karyawan() {
    TransStatus = new Array();
    $.each($('input[name="TransStatus"]:checked'), function () {
        TransStatus.push($(this).val());
    });

    $('#tt_piutang').datagrid('load', {
        piutang_no: $('#txt_piutang_no').val(),
        piutang_memo: $('#txt_piutang_memo').val(),
        date_from: $('#txt_from_date').datebox('getValue'),
        date_to: $('#txt_to_date').datebox('getValue'),
        status: TransStatus
    });
}

// Payment Karyawan
function search_payment_karyawan() {
    TransStatus = new Array();
    $.each($('input[name="TransStatus"]:checked'), function () {
        TransStatus.push($(this).val());
    });

    $('#tt_payment').datagrid('load', {
        payment_karyawan_no: $('#txt_payment_karyawan_no').val(),
        payment_karyawan_memo: $('#txt_payment_karyawan_memo').val(),
        from_date: $('#txt_from_date').datebox('getValue'),
        to_date: $('#txt_to_date').datebox('getValue'),
        status: TransStatus
    });
}


// Transfer to Petty Cash
function search_trasfer_to_petty_cash() {
    $('#tt').datagrid('load', {
        transfer_from: $('#txt_transferfrom').val(),
        transfer_to: $('#txt_transferto').val(),
        from_date: $('#txt_from_date').datebox('getValue'),
        to_date: $('#txt_to_date').datebox('getValue'),
        status: $('input[name=rdo_status]:checked').val()
    });
}
/*End of Cash and Bank*/

/* Purchase */
function search_purchase() {
    TransStatus = new Array();

    $.each($("input[name='TransStatus']:checked"), function () {
        TransStatus.push($(this).val());
    });

    $('#tt').datagrid('load', {
        id: $('#txt_no').val(),
        desc: $('#txt_desc').val(),
        vendor_id: $('#cmb_vendor').val(),
        date_from: $('#txt_date_from').datebox('getValue'),
        date_to: $('#txt_date_to').datebox('getValue'),
        status: TransStatus
    });
}
/* End of Purchase */

/* Sales */
function search_sales() {
    TransStatus = new Array();
    $.each($("input[name='chk_transstatus']:checked"), function () {
        TransStatus.push($(this).val());
    });

    $('#tt').datagrid('load', {
        id: $('#txt_no').val(),
        desc: $('#txt_desc').val(),
        date_from: $('#txt_date_from').datebox('getValue'),
        date_to: $('#txt_date_to').datebox('getValue'),
        status: TransStatus
    });
}
/* End of Sales */

/* Ferry / 01/01/2015 / fro Search COA by AccountSubType */
function search_coa() {
    var account_type = $('#account_type').combogrid('grid');	// get datagrid object
    var type_selected = account_type.datagrid('getSelected');// get the selected row

    var month_type = $('#cbo_period_month').combobox('getValue');
    var year_type = $('#nsp_period_year').val();

    var type = null;
    var trans_status = new Array();

    $.each($('input:checkbox[name="TransStatus[]"]:checked'), function () {
        trans_status.push($(this).val());
    });

    if (type_selected !== null) {
        type = type_selected.AccountSubTypeID;
    }

    $('#tt').datagrid('load', {
        account: $('#account_no').val(),
        name: $('#account_name').val(),
        type: type,
        status: trans_status,
        month: month_type,
        year: year_type
    });
}

function search_bank() {
    chk_TransStatus = new Array();

    $.each($('input[name="chk_TransStatus"]:checked'), function () {
        chk_TransStatus.push($(this).val());
    });

    $('#tt').datagrid('load', {
        BankCode: $('#txt_BankCode').val(),
        BankName: $('#txt_BankName').val(),
        TransStatus: chk_TransStatus
    });
}

function search_pricelist() {
    $('#dtg_price_list').datagrid('load', {
        item_name: $('#txt_item_name').val(),
        branch_name: $('#txt_branch_name').val()
    });
}

function search_branch() {
    trans_status = new Array();

    $.each($("input[name='chk_status[]']:checked"), function () {
        trans_status.push($(this).val());
    });

    $('#tt').datagrid('load', {
        branch_code: $('#txt_find_branch_code').val(),
        branch_name: $('#txt_find_branch_name').val(),
        status: trans_status
    });
}

//search company branch fine master
function search_company_branch_new(company_code) {
    trans_status = new Array();

    $.each($("input[name='chk_status[]']:checked"), function () {
        trans_status.push($(this).val());
    });

    $('#tt').datagrid('load', {
        branch_code: $('#txt_find_branch_code').val(),
        branch_name: $('#txt_find_branch_name').val(),
        status: trans_status
    });
}

// Commented By Prawira : function untuk listing search di sebelah kiri interface customer.
// Return Data Customer to Datagrid.
// Tanggal 9 September 2015
function search_customers() {
    chk_TransStatus = new Array();
    $.each($("input[name='chk_TransStatus']:checked"), function () {
        chk_TransStatus.push($(this).val());
    });

    $('#tt').datagrid('load', {
        CustomerCode: $('#txt_CustomerCode').val(),
        CustomerName: $('#txt_CustomerName').val(),
        CustomerCity: $('#cmb_CustomerCity').combobox('getValue'),
        CurrencyCode: $('#cmb_CurrencyCode').combobox('getValue'),
        BranchCode: $('#cmb_branch').combobox('getValue'),
        TransStatus: chk_TransStatus
    });
}

function search_vendors() {
    TransStatus = new Array();

    $.each($('input:checkbox[name="TransStatus[]"]:checked'), function () {
        TransStatus.push($(this).val());
    });

    $('#tt').datagrid('load', {
        vendor_no: $('#vendorno').val(),
        vendor_name: $('#vendorname').val(),
        currency: $('#cmb_currency').combobox('getValue'),
        VendorCity: $('#cmb_VendorCity').combobox('getValue'),
        status: TransStatus
    });
}

function search_inv_adjustment() {
    /* var adjust_type = new Array();
     $.each($("input[name='chk_adjusttype[]']:checked"), function() {
     adjust_type.push($(this).val());	 
     }); */

    $('#tt').datagrid('load', {
        adjust_no: $('#adjustment_no').val(),
        type_name: $('#type_name').val(),
        adj_val: $('input[name=chk_adjust_type_value]:checked').val(),
        adj_qty: $('input[name=chk_adjust_type_qty]:checked').val(),
        from_date: $('#txt_from_date').datebox('getValue'),
        to_date: $('#txt_to_date').datebox('getValue'),
        status: $('input[name=rdo_status]:checked').val()
    });
}

function search_reconcile() {
    $('#tt').datagrid('load', {
        AccountNo: $('#cmb_bank_account').combobox('getValue'),
        from_date: $('#txt_from_date').datebox('getValue'),
        to_date: $('#txt_to_date').datebox('getValue')
    });
}

function search_payment_account_popup() {
    $('#tt_choose_payment').datagrid('load', {
        AccountNo: $('#txt_account_number').val(),
        AccountName: $('#txt_account_name').val()
    });
}

function search_payment_department_popup() {
    $('#tt_choose_department_payment').datagrid('load', {
        CodeDepartment: $('#txt_department_code').val(),
        NameDepartment: $('#txt_department_name').val()
    });
}
//==== END 15 10 2014 TAGOR

/*
 Author 		  : Wahyu
 Last update   : 11/10/2014
 Desc          : for search expense cashbon
 */
function search_expense_cashbon() {
    if ($('#ByDate').is(':checked')) {
        $("#filter_date").show();
        var cashbon_from_date = $('#cashbon_from_date').datebox('getValue');
        var cashbon_to_date = $('#cashbon_to_date').datebox('getValue');
    } else {
        $("#filter_date").hide();
    }

    $('#grid_expense_cashbon').datagrid('load', {
        expense_cashbon_no: $('#txt_cashbon_no').val(),
        expense_cashbon_memo: $('#txt_cashbon_memo').val(),
        TransStatus: $('input[name=TransStatus]:checked').val(),
        cashbon_from_date: cashbon_from_date,
        cashbon_to_date: cashbon_to_date
    });
}

function search_payment_cashbon() {
    TransStatus = new Array();

    $.each($("input[name='TransStatus']:checked"), function () {
        TransStatus.push($(this).val());
    });

    $('#list_expense_payment').datagrid('load', {
        id: $('#txt_no').val(),
        memo: $('#txt_memo').val(),
        date_from: $('#txt_date_from').datebox('getValue'),
        date_to: $('#txt_date_to').datebox('getValue'),
        status: TransStatus
    });
}

function search_currency() {
    TransStatus = new Array();

    $.each($("input[name='TransStatus[]']:checked"), function () {
        TransStatus.push($(this).val());
    });

    $('#tt').datagrid('load', {
        currency_code: $('#txt_currency_code').val(),
        currency_name: $('#txt_currency_name').val(),
        TransStatus: TransStatus
    });
}

function search_department() {
    TransStatus = new Array();

    $.each($("input[name='TransStatus[]']:checked"), function () {
        TransStatus.push($(this).val());
    });

    $('#tt').datagrid('load', {
        department_code: $('#txt_department_code').val(),
        department_name: $('#txt_department_name').val(),
        TransStatus: TransStatus
    });
    //alert(TransStastus);
}

function search_journal_voucher() {
    txt_DateFrom = ''
    txt_DateTo = '';
    if ($('#ByDate').is(':checked')) {
        txt_DateFrom = $('#txt_DateFrom').datebox('getValue');
        txt_DateTo = $('#txt_DateTo').datebox('getValue');
    }

    $('#journal_voucher').datagrid('load', {
        JVchNumber: $('#txt_JVchNumber').val(),
        JVchDesc: $('#txt_JVchDesc').val(),
        JVchDateFrom: txt_DateFrom,
        JVchDateTo: txt_DateTo
    });
}

function search_account_balance() {
    /* var TransStatus = new Array();
     $.each($("input[name='TransStatus[]']:checked"), function() {
     TransStatus.push($(this).val());	 
     }); */
    $('#t_account_balance').datagrid('load', {
        account_number: $('#txt_account_no').val(),
        account_name: $('#txt_account_name').val(),
        account_type: $('#type_account').val()
    });
}

function search_payment_listing_cashbon() {
    var TransStatus = new Array();
    $.each($("input[name='TransStatus[]']:checked"), function () {
        TransStatus.push($(this).val());
    });

    if ($('#ByDate').is(':checked')) {
        $("#filter_date").show();
        var listing_from_date = $('#listing_from_date').datebox('getValue');
        var listing_to_date = $('#listing_to_date').datebox('getValue');
    } else {
        $("#filter_date").hide();
    }

    $('#grid_payment_list_cashbon').datagrid('load', {
        TransStatus: TransStatus,
        listing_from_date: listing_from_date,
        listing_to_date: listing_to_date
    });
}

function search_choose_item() {
    var item_category = $('#cmb_item_category').combobox('getValue');

    if (item_category) {
        $('#tt_choose_item').datagrid('load', {
            item_categori: item_category,
            item_code: $('#txt_item_code').val(),
            item_desc: $('#txt_item_desc').val()
        });

        $('#cmb_item_category').combobox('readonly');
    }
}

function search_choose_item2() {
    var item_category = $('#cmb_item_category').combobox('getValue');

    $('#tt_choose_item').datagrid('load', {
        item_categori: item_category,
        item_code: $('#txt_item_code').val(),
        item_desc: $('#txt_item_desc').val()
    });
}

/*================================search pop up di PR================================*/
function search_choose_item_new() {
    searchParameter = {};

    searchParameter['cmb_ItemCategoryID'] = $('#cmb_ItemCategoryID').combobox('getValue');
    searchParameter['txt_ItemCode'] = $('#txt_ItemCode').val();
    searchParameter['txt_ItemDesc'] = $('#txt_ItemDesc').val();

    $('#tt_choose_item').datagrid('load', {
        param: searchParameter
    });
}
/*=======================================end=====================================================*/

function search_choose_item3() {
    $('#tt_choose_servis').datagrid('load', {
        item_code: $('#txt_item_code_servis').val(),
        item_desc: $('#txt_item_desc_servis').val()
    });
}

function search_choose_item4() {
    $('#tt_choose_advance').datagrid('load', {
        item_code: $('#txt_item_code_advance').val(),
        item_desc: $('#txt_item_desc_advance').val()
    });
}

function search_inventory() {
    $('#tt_choose_inventory').datagrid('load', {
        item_categori: $('#cmb_inventory_category').combobox('getValue'),
        item_code: $('#txt_inventory_code').val(),
        item_desc: $('#txt_inventory_desc').val()
    });
}

/* Author : Fachri / fungsi untuk search job cos, daily production dan daily production amount */
function search_production() {
    var item_category = $('#cmb_item_category_production').combobox('getValue');
    if (item_category) {
        $('#tt_choose_production').datagrid('load', {
            item_categori: item_category,
            item_code: $('#txt_item_code_production').val(),
            item_desc: $('#txt_item_desc_production').val()
        });
    }
}
function search_production_amount() {
    var item_category = $('#cmb_item_category_production_amount').combobox('getValue');
    if (item_category) {
        $('#tt_choose_production_amount').datagrid('load', {
            item_categori: item_category,
            item_code: $('#txt_item_code_production').val(),
            item_desc: $('#txt_item_desc_production').val()
        });
    }
}

function search_job_costing(id_item) {
    var item_category = $('#cmb_item_job_costing').combobox('getValue');
    if (item_category) {
        $('#tt_choose_job_costing').datagrid('load', {
            item_categori: id_item,
            item_code: $('#txt_item_code_job_costing').val(),
            item_desc: $('#txt_item_desc_job_costing').val()
        });
    }
}

/* end */

/*
 Author 		  : Herpan
 Last update   : 23/7/2014
 Desc          : for search purchase requisition
 */
function search_purchase_requisition() {
    var PReqDateStart = '';
    var PReqDateEnd = '';
    var TransStatus = new Array();
    //var approval		= $('input[name=rdo_approval]:checked').val();
    $.each($("input[name='TransStatus[]']:checked"), function () {
        TransStatus.push($(this).val());
    });
    if ($('#ByDate').is(':checked')) {
        PReqDateStart = $('#PReqDateStart').datebox('getValue');
        PReqDateEnd = $('#PReqDateEnd').datebox('getValue');
    }
    $('#tt').datagrid('load', {
        PReqNumber: $('#PReqNumber').val(),
        PReqDesc: $('#PReqDesc').val(),
        TransStatus: TransStatus,
        PReqDateStart: PReqDateStart,
        PReqDateEnd: PReqDateEnd,
        approval: $('input[name=rdo_approval]:checked').val()
    });
}

/*
 Author 		  : Ladur
 Last update   : 23/7/2014
 Desc          : for search sales quotatin
 */
function search_sales() {
    var customer = '';
    var SQuoDateStart = '';
    var SQuoDateEnd = '';
    var TransStatus = new Array();
    $.each($("input[name='TransStatus[]']:checked"), function () {
        TransStatus.push($(this).val());
    });
    //console.log(TransStatus);
    if ($('#ByDate').is(':checked')) {
        SQuoDateStart = $('#SQuoDateStart').datebox('getValue');
        SQuoDateEnd = $('#SQuoDateEnd').datebox('getValue');
    }
    $('#tt').datagrid('load', {
        customer: $('#cmb_sales_order_by').val(),
        SQuoNumber: $('#SQuoNumber').val(),
        SQuoDesc: $('#SQuoDesc').val(),
        TransStatus: TransStatus,
        SQuoDateStart: SQuoDateStart,
        SQuoDateEnd: SQuoDateEnd
    });
}

/*
 Author 		  : Ladur
 Last update   : 23/7/2014
 Desc          : for search sales order
 */
function search_sales_order() {
    var customer = '';
    var SOrdDateStart = '';
    var SOrdDateEnd = '';
    var TransStatus = new Array();
    $.each($("input[name='TransStatus[]']:checked"), function () {
        TransStatus.push($(this).val());
    });
    //console.log(TransStatus);
    if ($('#ByDate').is(':checked')) {
        SOrdDateStart = $('#SOrdDateStart').datebox('getValue');
        SOrdDateEnd = $('#SOrdDateEnd').datebox('getValue');
    }
    $('#tt').datagrid('load', {
        customer: $('#cmb_sales_order_by').val(),
        SOrdNumber: $('#SOrdNumber').val(),
        SOrdDesc: $('#SOrdDesc').val(),
        TransStatus: TransStatus,
        SOrdDateStart: SOrdDateStart,
        SOrdDateEnd: SOrdDateEnd
    });
}

/*
 Author          : Ladur
 Last update     : 23/7/2014
 Desc            : for search delivery order
 */
function search_delivery_order() {
    var customer = '';
    var DOrdDateStart = '';
    var DOrdDateEnd = '';
    var TransStatus = new Array();

    $.each($("input[name='TransStatus[]']:checked"), function () {
        TransStatus.push($(this).val());
    });

    //console.log(TransStatus);

    if ($('#ByDate').is(':checked')) {
        DOrdDateStart = $('#DOrdDateStart').datebox('getValue');
        DOrdDateEnd = $('#DOrdDateEnd').datebox('getValue');
    }

    $('#tt').datagrid('load', {
        customer: $('#cmb_sales_order_by').val(),
        DOrdNumber: $('#DOrdNumber').val(),
        DOrdDesc: $('#DOrdDesc').val(),
        TransStatus: TransStatus,
        DOrdDateStart: DOrdDateStart,
        DOrdDateEnd: DOrdDateEnd
    });
}

/*
 Author 		  : Ladur
 Last update   : 23/7/2014
 Desc          : for search sales receipt
 */
function search_sales_receipt() {
    var customer = '';
    var SRecDateStart = '';
    var SRecDateEnd = '';
    var TransStatus = new Array();
    $.each($("input[name='TransStatus[]']:checked"), function () {
        TransStatus.push($(this).val());
    });
    //console.log(TransStatus);
    if ($('#ByDate').is(':checked')) {
        SRecDateStart = $('#SRecDateStart').datebox('getValue');
        SRecDateEnd = $('#SRecDateEnd').datebox('getValue');
    }
    $('#tt').datagrid('load', {
        customer: $('#cmb_sales_receipt_by').val(),
        SRecNumber: $('#SRecNumber').val(),
        SRecDesc: $('#SRecDesc').val(),
        TransStatus: TransStatus,
        SRecDateStart: SRecDateStart,
        SRecDateEnd: SRecDateEnd
    });
}

/*
 Author          : Ladur
 Last update     : 23/7/2014
 Desc            : for search sales return
 */
function search_sales_return() {
    var customer = '';
    var SRetDateStart = '';
    var SRetDateEnd = '';
    var TransStatus = new Array();

    $.each($("input[name='TransStatus[]']:checked"), function () {
        TransStatus.push($(this).val());
    });

    //console.log(TransStatus);

    if ($('#ByDate').is(':checked')) {
        SRetDateStart = $('#SRetDateStart').datebox('getValue');
        SRetDateEnd = $('#SRetDateEnd').datebox('getValue');
    }

    $('#tt').datagrid('load', {
        customer: $('#cmb_sales_order_by').val(),
        SRetNumber: $('#SRetNumber').val(),
        SRetDesc: $('#SRetDesc').val(),
        TransStatus: TransStatus,
        SRetDateStart: SRetDateStart,
        SRetDateEnd: SRetDateEnd
    });
}

/*
 Author 		  : Ladur
 Last update   : 23/7/2014
 Desc          : for search sales invoice
 */
function search_sales_invoice() {
    var customer = '';
    var SInvDateStart = '';
    var SInvDateEnd = '';
    var TransStatus = new Array();
    $.each($("input[name='TransStatus[]']:checked"), function () {
        TransStatus.push($(this).val());
    });
    //console.log(TransStatus);
    if ($('#ByDate').is(':checked')) {
        SInvDateStart = $('#SInvDateStart').datebox('getValue');
        SInvDateEnd = $('#SInvDateEnd').datebox('getValue');
    }
    $('#tt').datagrid('load', {
        customer: $('#cmb_sales_order_by').val(),
        SInvNumber: $('#SInvNumber').val(),
        SInvDesc: $('#SInvDesc').val(),
        TransStatus: TransStatus,
        SInvDateStart: SInvDateStart,
        SInvDateEnd: SInvDateEnd
    });
}

/*
 Author          : Ferry
 Last update     : 29/10/2014
 Desc            : for search Item Product
 */
function search_item() {
    var ItemType = new Array();
    var TransStatus = new Array();
    $.each($("input[name='ItemType']:checked"), function () {
        ItemType.push($(this).val());
    });
    $.each($("input[name='TransStatus']:checked"), function () {
        TransStatus.push($(this).val());
    });

    $('#tt').datagrid('load', {
        no: $('#txt_no').val(),
        desc: $('#txt_desc').val(),
        item_category: $('#cmb_item_category').val(),
        item_type: ItemType,
        status: TransStatus
    });
}

/*
 Author 		  : Fachri
 Last update   : 15/01/2015
 Desc          : for search purchase requisition
 */
function search_import_type() {
    $('#tt').datagrid('load', {
        type: $('input[name=rdo_transaction_type]:checked').val()
    });
}

/*
 
 /*
 Author          : Ladur
 Last update     : 29/10/2014
 Desc            : for search Item Product
 */
function search_master() {
    //	var DateFrom = $('#txt_date_from').datebox('getValue');
    //	var DateTo   = $('#txt_date_to').datebox('getValue');
    //	
    //	if($('#ByDate').is(':checked')){
    //		SInvDateStart=$('#DateStart').datebox('getValue');
    //		DateEnd  =$('#DateStart').datebox('getValue');			
    //	}
    txt_DateFrom = '';
    txt_DateTo = '';
    if ($('#ByDate').is(':checked')) {
        txt_DateFrom = $('#txt_date_from').datebox('getValue');
        txt_DateTo = $('#txt_date_to').datebox('getValue');
    }

    TransStatus = new Array();
    $.each($('input[name="TransStatus"]:checked'), function () {
        TransStatus.push($(this).val());
    });

    $('#tt').datagrid('load', {
        id: $('#txt_no').val(),
        desc: $('#txt_desc').val(),
        date_from: txt_DateFrom,
        date_to: txt_DateTo,
        status: TransStatus
    });
}

function search_inventories() {
    $('#tt').datagrid('load', {
        ItemCode: $('#txt_item_code').val(),
        ItemDesc: $('#txt_item_desc').val(),
        BranchCode: $('#cmb_branch').val()
    });
}

function search_account_history() {
    var DateStart = '';
    var DateEnd = '';
    if ($('#ByDate').is(':checked')) {
        DateStart = $('#txt_DateFrom').datebox('getValue');
        DateEnd = $('#txt_DateTo').datebox('getValue');
    }

    var chk_TransType = new Array();
    $.each($("input[name='chk_TransType']:checked"), function () {
        chk_TransType.push($(this).val());
    });

    $('#gd_account_history').datagrid('load', {
        AccountNumber: $('#txt_AccountNo').val(),
        CustomerCode: $('#cmb_Customer').combobox('getValue'),
        VendorCode: $('#cmb_Vendor').combobox('getValue'),
        DepartmentCode: $('#cmb_Department').combobox('getValue'),
        TransType: chk_TransType,
        DateFrom: txt_DateFrom,
        DateTo: txt_DateTo
    });
}

function search_warehouse() {
    WarehouseName = $('#txt_warehouse_name').val();
    Description = $('#txt_description').val();
    TransStatus = new Array();

    $.each($('input[name="chk_trans_status[]"]:checked'), function () {
        TransStatus.push($(this).val());
    });

    $('#tt').datagrid('load', {
        warehouse_name: WarehouseName,
        warehouse_desc: Description,
        TransStatus: TransStatus
    });
}

function search_data() {
    searchParameter = {};

    // For textbox ID or Code
    if ($('#txt_IDNumber').val() != '') {
        searchParameter['txt_IDNumber'] = $('#txt_IDNumber').val();
    }

    // For textbox Name
    if ($('#txt_Name').val() != '') {
        searchParameter['txt_Name'] = $('#txt_Name').val();
    }

    // For textbox Description
    if ($('#txt_Description').val() != '') {
        searchParameter['txt_Description'] = $('#txt_Description').val();
    }

    // For textbox Transfer From
    if ($('#txt_TransferFrom').val() != '') {
        searchParameter['txt_TransferFrom'] = $('#txt_TransferFrom').val();
    }

    // For textbox Transfer To
    if ($('#txt_TransferTo').val() != '') {
        searchParameter['txt_TransferTo'] = $('#txt_TransferTo').val();
    }

    // For combobox Customer
    if ($('#cmb_Customer').length > 0 && $('#cmb_Customer').combobox('getValue') != '') {
        searchParameter['cmb_Customer'] = $('#cmb_Customer').combobox('getValue');
    }

    // For combobox Customer
    if ($('#cmb_Vendor').length > 0 && $('#cmb_Vendor').val() != '') {
        searchParameter['cmb_Vendor'] = $('#cmb_Vendor').val();
    }

    // For combobox Department
    if ($('#cmb_Department').length > 0 && $('#cmb_Department').combobox('getValue') != '') {
        searchParameter['cmb_Department'] = $('#cmb_Department').combobox('getValue');
    }

    // For combobox Department
    if ($('#cmb_Bank').length > 0 && $('#cmb_Bank').combobox('getValue') != '') {
        searchParameter['cmb_Bank'] = $('#cmb_Bank').combobox('getValue');
    }

    // For combobox Item Category
    if ($('#cmb_ItemCategory').length > 0 && $('#cmb_ItemCategory').val() != '') {
        searchParameter['cmb_ItemCategory'] = $('#cmb_ItemCategory').val();
    }

    // For combobox Customer Location
    if ($('#cmb_CustomerCity').length > 0 && $('#cmb_CustomerCity').combobox('getValue') != '') {
        searchParameter['cmb_CustomerCity'] = $('#cmb_CustomerCity').combobox('getValue');
    }

    // For combobox Currency Code
    if ($('#cmb_CurrencyCode').length > 0 && $('#cmb_CurrencyCode').combobox('getValue') != '') {
        searchParameter['cmb_CurrencyCode'] = $('#cmb_CurrencyCode').combobox('getValue');
    }

    // for combogrid Account Type
    if ($('#cmb_AccountType').length > 0 && $('#cmb_AccountType').combogrid('grid').datagrid('getSelected') != null) {
        searchParameter['cmb_AccountType'] = $('#cmb_AccountType').combogrid('grid').datagrid('getSelected').AccountSubTypeID;
    }

    // For textbox Date From and Date To
    if ($('#chk_ByDate').is(':checked')) {
        searchParameter['txt_DateFrom'] = $('#txt_DateFrom').datebox('getValue');
        searchParameter['txt_DateTo'] = $('#txt_DateTo').datebox('getValue');
    }

    // For checkbox Item Type
    if ($('input[name="chk_ItemType"]').length > 0) {
        searchParameter['chk_ItemType'] = new Array();

        $.each($('input[name="chk_ItemType"]:checked'), function () {
            searchParameter['chk_ItemType'].push($(this).val());
        });
    }

    // For checkbox Adjustment Type
    if ($('input[name="chk_AdjustmentType"]').length > 0) {
        searchParameter['chk_AdjustmentType'] = new Array();

        $.each($('input[name="chk_AdjustmentType"]:checked'), function () {
            searchParameter['chk_AdjustmentType'].push($(this).val());
        });
    }

    // For checkbox Transaction Type
    if ($('input[name="chk_TransType"]').length > 0) {
        searchParameter['chk_TransType'] = new Array();

        $.each($('input[name="chk_TransType"]:checked'), function () {
            searchParameter['chk_TransType'].push($(this).val());
        });
    }

    // For checkbox TransStatus
    if ($('input[name="chk_TransStatus"]').length > 0) {
        searchParameter['chk_TransStatus'] = new Array();

        $.each($('input[name="chk_TransStatus"]:checked'), function () {
            searchParameter['chk_TransStatus'].push($(this).val());
        });
    }

    // Load data grid with given parameter
    $('#grid').datagrid('loadData', {'total': 0, 'rows': []});
    $('#grid').datagrid('load', {
        param: searchParameter
    });
}

/*================================search pop up di job costing================================*/
function search_all_item() {
    searchParameter = {};

    searchParameter['cmb_ItemCategoryID'] = $('#cmb_ItemCategoryID').combobox('getValue');
    searchParameter['txt_ItemCode'] = $('#txt_ItemCode').val();
    searchParameter['txt_ItemDesc'] = $('#txt_ItemDesc').val();

    $('#grid_pop_up').datagrid('load', {
        param: searchParameter
    });
}

function search_all_item_adjust(akun_number) {
    searchParameter = {};

    searchParameter['cmb_ItemCategoryID'] = $('#cmb_ItemCategoryID').combobox('getValue');
    searchParameter['txt_ItemCode'] = $('#txt_ItemCode').val();
    searchParameter['txt_ItemDesc'] = $('#txt_ItemDesc').val();
    searchParameter['akun_number'] = akun_number;

    $('#grid_pop_up').datagrid('load', {
        param: searchParameter
    });
}
/*=======================================end=====================================================*/

/*================================search pop up di servis================================*/
function search_servis_item() {
    searchParameter = {};

    searchParameter['txt_ItemCode_Servis'] = $('#txt_ItemCode_Servis').val();
    searchParameter['txt_ItemDesc_Servis'] = $('#txt_ItemDesc_Servis').val();

    $('#tt_choose_servis').datagrid('load', {
        param: searchParameter
    });
}
/*=======================================end=====================================================*/

/*================================search pop up di servis================================*/
function search_adv() {
    searchParameter = {};

    searchParameter['txt_ItemCode_Adv'] = $('#txt_ItemCode_Adv').val();
    searchParameter['txt_ItemDesc_Adv'] = $('#txt_ItemDesc_Adv').val();

    $('#tt_choose_advance').datagrid('load', {
        param: searchParameter
    });
}
/*=======================================end=====================================================*/

/*
 jangan lupa ini ditaro dibawah di setaip list untuk search
 taro di luar documen ready jangan didalam doc ready
 jangan lupa hapus fungsi on key up di setiap find
 jangan lupa cek id gridnya
 ini contoh untuk master by company
 created by : fachri 
 */
function searching_data_transaksi() {
    if ($('#cmb_branch').combobox('getValue') == "") {
        $.messager.alert('Info', 'Branch tidak boleh kosong, silahkan pilih');
    }
    else {
        /*
         disini masing masing form list berbeda cek find diatas bisa by name by code
         */
        searchParameter = {};

        // For textbox Transfer From
        if ($('#txt_TransferFrom').val() != '') {
            searchParameter['txt_TransferFrom'] = $('#txt_TransferFrom').val();
        }

        // For textbox Transfer To
        if ($('#txt_TransferTo').val() != '') {
            searchParameter['txt_TransferTo'] = $('#txt_TransferTo').val();
        }

        searchParameter['txt_IDNumber'] = $('#txt_IDNumber').val();
        searchParameter['txt_Description'] = $('#txt_Description').val();


        var txt_payment_no = $('#txt_IDNumber').val();
        var txa_desc = $('#txt_Description').val();
        //-----------------end--------------------------------------------------------

        /*
         disini hanya ada dua search, pakai company atau branch
         */

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

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

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

        if ($('#cmb_VendorCode').length > 0 && $('#cmb_VendorCode').val() != '') {
            searchParameter['cmb_VendorCode'] = $('#cmb_VendorCode').combobox('getValue');
        }

        if ($('#cmb_CustomerCode').length > 0 && $('#cmb_CustomerCode').val() != '') {
            searchParameter['cmb_CustomerCode'] = $('#cmb_CustomerCode').combobox('getValue');
        }

        if ($('#cmb_Payment').length > 0 && $('#cmb_Payment').val() != '') {
            searchParameter['cmb_PaymentStatus'] = $('#cmb_Payment').combobox('getValue');
        }

        searchParameter['chk_DO_Direct'] = new Array();
        $.each($('input[name="chk_DO_Direct"]:checked'), function () {
            searchParameter['chk_DO_Direct'].push($(this).val());
        });

        searchParameter['chk_TransStatus'] = new Array();
        $.each($('input[name="chk_TransStatus"]:checked'), function () {
            searchParameter['chk_TransStatus'].push($(this).val());
        });

        if ($('#txt_DateFrom').length > 0) {
            searchParameter['txt_DateFrom'] = $('#txt_DateFrom').datebox('getValue');
            searchParameter['txt_DateTo'] = $('#txt_DateTo').datebox('getValue');
        }

        // Load data grid with given parameter
        $('#grid').datagrid('load', {
            param: searchParameter
        });
    }
}
//------------------end--------------------------------------

/*
 search akun ini dipake disetiap pemakaian pop up yg harus ambil langsing dari am coa
 yang tidak lewat preference jangan lupa id di data grid kasinya nama (grid_akun)
 created by fahri
 */
function search_akun() {
    searchParameter = {};

    searchParameter['txt_AccountName'] = $('#txt_AccountName').val();
    searchParameter['txt_AccountNumber'] = $('#txt_AccountNumber').val();

    $('#grid_akun').datagrid('load', {
        param: searchParameter
    });
}
/*====================================end============================================*/

// END COMMENTED SEARCH.JS BY PRAWIRA

// END

// DOCUMENT READY
$(document).ready(function () {
    page_width = parseInt($(document).width());
    left_menu_width = 180 // Value from v_mainpage.php(custom/views/v_mainpage.php)
    mainframe_width = page_width - left_menu_width;

    box_left_pos = 0;
    $('.status-box').each(function () {
        temp = mainframe_width / 2;
        temp = temp - $(this).width();
        box_left_pos = left_menu_width + temp;
    });
    $('.status-box').css('left', box_left_pos);

    /*$('#cmb_customer').combogrid({
     onChange: function(){
     item = $(this).combogrid('grid').datagrid('getSelected');			
     }
     });*/

    /*Datebox setValue to today*/
    $('.valToday').each(function () {
        datebox_id = '#' + $(this).attr('id');
        $(datebox_id).datebox('setValue', 'today');
    });
    /*End of Datebox setValue to today*/

    /*Datebox validation: Backward*/
    $('.validBackward').datebox({
        onSelect: function () {
            today = new Date();
            //today       = Date.parse(today.getMonth()+1+'/'+today.getDate()+'/'+today.getFullYear());
            today = parseInt(today.getFullYear()) + '' + parseInt(today.getMonth() + 1);

            datebox_value = $(this).datebox('getValue').split('-');
            //datebox_value = datebox_value[1] +'-'+ datebox_value[0] +'-'+ datebox_value[2];
            datebox_value = parseInt(datebox_value[2]) + '' + parseInt(datebox_value[1]) /*+ '' + parseInt(datebox_value[0])*/;
            //datebox_value 	= Date.parse(datebox_value);
			datebox_value_real = parseInt(datebox_value[2]) + '-' + parseInt(datebox_value[1]) + '-' + parseInt(datebox_value[2]);
			
			var flag = false;
			var url = base_url + 'custom/get_data/check_period_end_custom';
			datebox_id = $(this).attr('id');
			
			$.post(url, {datebox_value: datebox_value}, function (result) {
				datecompany_value = result.CompDate.split('-');
				datecompany_value = parseInt(datecompany_value[0]) + '' + parseInt(datecompany_value[1]);
				
				if (datebox_value == result.value) {
					$.messager.alert('Perhatian', 'Maaf tanggal ini tidak bisa dipilih karena sudah di End Periode', 'info', function () {
						$('#' + datebox_id).datebox('setValue', 'today');
					});
				}
				else if(datebox_value < parseInt(datecompany_value)){
					$.messager.alert('Perhatian', 'Maaf tanggal ini Company belum terbentuk', 'info', function () {
						$('#' + datebox_id).datebox('setValue', 'today');
					});
				}
					
			}, 'json');
        }
    });
    /*End of Datebox Validation: Backward*/


    $('form').on('change keyup paste', ':input', function () {
        $('.app-button').linkbutton('disable');
    });

    Array.prototype.array_unique = function (a) {
        return function () {
            return this.filter(a)
        }
    }(function (a, b, c) {
        return c.indexOf(a, b + 1) < 0
    });


});

/* Author : Herpan / Last update : 23/7/2014 / for new coa */
function form_coa() {
    $('#chk_sub_of').click(function () {
        if ($(this).is(':checked')) {
            $('#cmb_sub_account_wrapper').show();
        }
        else {
            $('#cmb_sub_account_wrapper').hide();
            $('#cmb_account_parent').combogrid('clear');

            $.post(base_url + 'list/coa/ajax_account_number', {AccountParent: ''}, function (result) {
                if (result.status == true) {
                    $('#txt_account_no').val(result.AccountNumber); // reload the user data
                }
            }, 'json');
        }
    });

    $('#cmb_account_parent').combogrid({
        onSelect: function (rowIndex, rowData) {
            $.post(base_url + 'list/coa/ajax_account_number', {AccountParent: rowData.AccountNumber}, function (result) {
                if (result.status == true) {
                    $('#txt_account_no').val(result.AccountNumber);
                }
            }, 'json');
        }
    });
}

/* Author  : Herpan / Last update : 04/08/2014 / for import journal */
function form_importjurnal() {
    if ($('#rdo_source:checked').val() == "local") {
        $('#fil_databaselocation').show();
        $('#txt_databaselocation').hide();
        $('#servername').hide();
    }
    else {
        $('#fil_databaselocation').hide();
        $('#txt_databaselocation').show();
        $('#servername').show();
    }
}

/* Author   : Herpan / Last update : 06/08/2014 / Desc : for new company */
function new_company() {
    location.href = 'file/new_company/quick_setup';
}

/*
 Author  : Tagor / Last update : 18/08/2014 / Desc : for popup roll over */
$(function () {
    $('#tt_rollover').datagrid('appendRow', {});
    $('#tt_toaccount').datagrid('appendRow', {});
    $('#cmb_itemcategory').prop('disabled', true);

    //$('#wrappaccount').hide();

    $('#rdo_toaccount').click(function () {
        //$('#wrappaccount').removeClass('hideWrapDiv');
        $('#wrappaccount').show();
        //$('#wrappitem').removeClass('showWrapDiv');
        $('#wrappitem').hide();

        $('#tt_rollover').datagrid('clear');
    });

    $('#rdo_toitem').click(function () {
        //$('#wrappaccount').removeClass('showWrapDiv');
        $('#wrappaccount').hide();
        //$('#wrappitem').removeClass('hideWrapDiv');
        $('#wrappitem').show();

        $('#tt_toaccount').datagrid('clear');
    });
});

/* Author : Tagor / Tanggal : 18/08/2014 / for popup update password */
function update_password() {
    if ($('#txt_oldpassword').val() == '' || $('#txt_newpassword').val() == '' || $('#txt_confirmation').val() == '') {
        $.messager.alert('Info', 'Please fill all field');
        return false;
    }
    else if ($('#txt_oldpassword').val() != $('#old_pwd').val()) {
        $.messager.alert('Info', 'Please enter right old password');
        return false;
    }
    else if ($('#txt_newpassword').val() != $('#txt_confirmation').val()) {
        $.messager.alert('Info', 'Password and confirmation must match');
        return false;
    }
    else {
        $.messager.confirm('Confirm', 'Redirect login', function (r) {
            if (r) {
                $('form#fm_changepassword').submit();
            }
        });
    }
}

function formatRp(a) {
    if (a === undefined || a === null || isNaN(a)) {
        return '0.00';
    }
    else {
        a = parseFloat(a).toFixed(2);
        temp = a.split('.');

        if (temp.length > 1) {
            decimal = temp[1];
        }
        else {
            decimal = '00';
        }

        e = function (f) {
            return f.split('').reverse().join('')
        };

        b = e(parseInt(a).toString());

        for (c = 0, d = ''; c < b.length; c++) {
            d += b[c];

            if ((c + 1) % 3 === 0 && c !== (b.length - 1)) {
                d += '.';
            }
        }

        return '\t' + e(d) + ',' + decimal;
    }
}

function formatRp_bank(a, b, c, d, e) {
    if (a === undefined) {
        return 0;
    }
    else {
        a = parseFloat(a).toFixed(2);
        temp = a.split('.');

        if (temp.length > 1) {
            decimal = temp[1];
        }
        else {
            decimal = '00';
        }

        e = function (f) {
            return f.split('').reverse().join('');
        };

        b = e(parseInt(a).toString());

        for (c = 0, d = ''; c < b.length; c++) {
            d += b[c];

            if ((c + 1) % 3 === 0 && c !== (b.length - 1) && !isNaN(b[c + 1])) {
                d += '.';
            }
        }

        var nominal = e(d);

        if (nominal.indexOf('-') === 0) {
            nominal = nominal.substring(1, nominal.length);
            nominal = '(' + nominal + ',' + decimal + ')';
        }
        else {
            nominal = nominal + ',' + decimal;
        }

        return nominal;
//        return '\t'+e(d) +','+ decimal;
    }
}

/* Author : Herpan / 23/7/2014 / for set now all datebox */
function formatDate(date) {
    if (date === undefined) {
        return '';
    }
    else {
        format_date = /^\d{4}\-\d{1,2}\-\d{1,2}$/;

        if (!format_date.test(date)) {
            temp = date.split('-');
            var y = parseInt(temp[0], 10);
            var m = parseInt(temp[1], 10);
            var d = parseInt(temp[2], 10);
            date = new Date(d, m - 1, y);
        }

        if (isNaN(date)) {
            date = new Date(date);
        }

        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        var d = date.getDate();

        //return y+'-'+(m<10?('0'+m):m)+'-'+(d<10?('0'+d):d);
        return (d < 10 ? ('0' + d) : d) + '-' + (m < 10 ? ('0' + m) : m) + '-' + y;
    }
}

function formatDates(dates) {
    if (dates === undefined) {
        return '';
    }
    else {
        date = dates.split(",");

        for (i = 0; i < date.length; i++) {
            temp = date[i].split("-");
            date[i] = temp[2] + "-" + temp[1] + "-" + temp[0];
        }
        return date.join();
    }
}

function beginEditRow(value, row, index) {
    if (row.editing) {
        input = '<a href="javascript:void(0)" onClick="saverow(this)">Save</a> ';
        input += '<a href="javascript:void(0)" onClick="cancelrow(this)">Cancel</a> ';
    } else {
        input = '<a href="javascript:void(0)" onClick="editrow(this)">Edit</a>';
    }

    return input;
}

function getRowIndex(target) {
    var tr = $(target).closest('tr.datagrid-row');
    return parseInt(tr.attr('datagrid-row-index'));
}

function editrow(target, value) {
    $('#dg_item').datagrid('beginEdit', getRowIndex(target));
}

function saverow(target) {
    $('#dg_item').datagrid('endEdit', getRowIndex(target));
}

function cancelrow(target) {
    $('#dg_item').datagrid('cancelEdit', getRowIndex(target));
}

function toAngka(rp) {
    return parseInt(rp.replace(/,.*|\D/g, ''), 10);
}

function onDblClickCellRollOver(index, field, value) {
    $('#tt_rollover').datagrid({
        url: 'custom/ajax/m_roll_over'
    });

    if (value == null) {
        modal_open('Item', 'dlg_searchitem');
    }
    else {
        $(this).datagrid('beginEdit', index);
        var ed = $(this).datagrid('getEditor', {index: index, field: field});
        //$(ed.target).focus();
    }
}

function filterInItemPopup() {
    if ($('#cmb_itemsearchby').val() !== '') {
        $('#cmb_itemcategory').prop('disabled', false);
    }
    else {
        $('#cmb_itemcategory').prop('disabled', true);
        $('#cmb_itemcategory').val(' ');
    }
}

function doItemSearch() {
    $('#dg_item').datagrid('load', {
        itemno: $('#txt_filteritemno').val(),
        itemdesc: $('#txt_filteritemdesc').val()
    });
}

function onDblClickRowItem(rowIndex, rowData) {
    var ids = [];
    var id;
    var rows = $('#dg_item').datagrid('getSelections');

    for (var i = 0; i < rows.length; i++) {
        ids.push(rows[i].ItemId);
    }

    id = ids.toString();

    $('#tt_rollover').datagrid('load', {
        itemid: id
    });

    modal_close('dlg_searchitem');
}


$.fn.datebox.defaults.formatter = function (date) {
    if (isNaN(date)) {
        date = new Date(date);
    }

    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    var d = date.getDate();

    //return y+'-'+(m<10?('0'+m):m)+'-'+(d<10?('0'+d):d);
    return (d < 10 ? ('0' + d) : d) + '-' + (m < 10 ? ('0' + m) : m) + '-' + y;
};

$.fn.datebox.defaults.parser = function (s) {
    if (!s)
        return new Date();

    format_date = /^\d{4}\-\d{1,2}\-\d{1,2}$/;

    var ss = (s.split('-'));

    if (!format_date.test(s)) {
        var y = parseInt(ss[0], 10);
        var m = parseInt(ss[1], 10);
        var d = parseInt(ss[2], 10);
    }
    else {
        var y = parseInt(ss[2], 10);
        var m = parseInt(ss[1], 10);
        var d = parseInt(ss[0], 10);
    }

    if (!isNaN(y) && !isNaN(m) && !isNaN(d)) {
        //return new Date(y,m-1,d);
        return new Date(d, m - 1, y);
    }
    else {
        return new Date();
    }
};

/* Author  : Herpan / Last update : 23/7/2014 / fungsi untuk pop up item */
function open_item() {
    modal_open('Item', 'dialog-item');
}

/*  Added By   : Hasan / Added Date : 9 December 2014 */
function open_item2() {
    modal_open('Item', 'dialog-item');

    table_row = $("tr[id^='datagrid-row-r11-2-']").length;

    if (table_row > 1) {
        first_row = $("#datagrid-row-r11-2-0 td[field=ItemCategoryID] div");
        ItemCategoryID = first_row.text();

        $("#hdn_item_category").val(ItemCategoryID);
        $("#cmb_item_category").combobox("select", ItemCategoryID);
        $('#cmb_item_category').combobox('readonly');
    }
}
/*End of Added*/


$.extend($.fn.datagrid.defaults.editors, {
    item: {
        init: function (container, options) {
            var input = $('<input type="text" class="item" onClick="open_item()" style="height:18px;" readonly/>').appendTo(container);
            return input.validatebox(options);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).val();
        },
        setValue: function (target, value) {
            $(target).val(value);
        },
        resize: function (target, width) {
            $(target)._outerWidth(width);
        }
    },
    item2: {
        init: function (container, options) {
            var input = $('<input type="text" id="modalTabItem" class="item" onKeyDown="if(event.keyCode == 13) {setArrayTabModalTab1();open_item2();}" onClick="setArrayTabModalTab1();open_item2()" style="height:18px;" readonly/>').appendTo(container);
            return input.validatebox(options);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).val();
        },
        setValue: function (target, value) {
            $(target).val(value);
        },
        resize: function (target, width) {
            $(target)._outerWidth(width);
        }
    },
    item_type: {
        init: function (container, options) {
            var input = $('<input type="easyui-numberbox" class="item_type" style="height:18px;" readonly />').appendTo(container);
            return input.validatebox(options);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).val();
        },
        setValue: function (target, value) {
            $(target).val(value);
        },
        resize: function (target, width) {
            $(target)._outerWidth(width);
        }
    },
    item_production: {
        init: function (container, options) {
            var input = $('<input type="text" class="item_production" onClick="open_production()" style="height:18px;" readonly/>').appendTo(container);
            return input.validatebox(options);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).val();
        },
        setValue: function (target, value) {
            $(target).val(value);
        },
        resize: function (target, width) {
            $(target)._outerWidth(width);
        }
    },
    item_production_amount: {
        init: function (container, options) {
            var input = $('<input type="text" class="item_production_amount" onClick="open_production_amount()" style="height:18px;" readonly/>').appendTo(container);
            return input.validatebox(options);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).val();
        },
        setValue: function (target, value) {
            $(target).val(value);
        },
        resize: function (target, width) {
            $(target)._outerWidth(width);
        }
    },
    item_job_costing: {
        init: function (container, options) {
            var input = $('<input type="text" class="item_job_costing" onClick="open_job_costing()" style="height:18px;" readonly/>').appendTo(container);
            return input.validatebox(options);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).val();
        },
        setValue: function (target, value) {
            $(target).val(value);
        },
        resize: function (target, width) {
            $(target)._outerWidth(width);
        }
    },
    item_inventory: {
        init: function (container, options) {
            var input = $('<input type="text" class="item_inventory" onClick="open_inventory()" style="height:18px;" readonly/>').appendTo(container);
            return input.validatebox(options);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).val();
        },
        setValue: function (target, value) {
            $(target).val(value);
        },
        resize: function (target, width) {
            $(target)._outerWidth(width);
        }
    },
    item_category: {
        init: function (container, options) {
            var input = $('<input type="text" class="item_category" style="height:18px;" readonly/>').appendTo(container);
            return input.validatebox(options);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).val();
        },
        setValue: function (target, value) {
            $(target).val(value);
        },
        resize: function (target, width) {
            $(target)._outerWidth(width);
        }
    },
    description: {
        init: function (container, options) {
            var input = $('<input type="text" class="description" style="width:350px;height:18px;" readonly/>').appendTo(container);
            return input.validatebox(options);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).val();
        },
        setValue: function (target, value) {
            $(target).val(value);
        },
        resize: function (target, width) {
            $(target)._outerWidth(width);
        }
    },
    unit: {
        init: function (container, options) {
            var input = $('<input type="text" class="unit" style="width:82px;height:18px;text-align:center;" readonly/>').appendTo(container);
            return input.validatebox(options);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).val();
        },
        setValue: function (target, value) {
            $(target).val(value);
        },
        resize: function (target, width) {
            $(target)._outerWidth(width);
        }
    },
    price: {
        init: function (container, options) {
            var input = $('<input type="text" class="price" style="height:18px;" onChange="get_amount(this.value)" />').appendTo(container);
            return input.validatebox(options);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).val();
        },
        setValue: function (target, value) {
            $(target).val(value);
        },
        resize: function (target, width) {
            $(target)._outerWidth(width);
        }
    },
    price2: {
        init: function (container, options) {
            var input = $('<input type="text" class="price" style="height:18px;" onChange="get_amount2(this.value)" />').appendTo(container);
            return input.validatebox(options);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).val();
        },
        setValue: function (target, value) {
            $(target).val(value);
        },
        resize: function (target, width) {
            $(target)._outerWidth(width);
        }
    },
    qty: {
        init: function (container, options) {
            var input = $('<input type="text" class="qty" onChange="get_amount(this.value)" style="height:18px;" />').appendTo(container);
            return input.validatebox(options);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).val();
        },
        setValue: function (target, value) {
            $(target).val(value);
        },
        resize: function (target, width) {
            $(target)._outerWidth(width);
        }
    },
    pph22_status: {
        init: function (container, options) {
            var input = $('<input type="text" class="pph22_status" style="height:18px;" readonly/>').appendTo(container);
            return input.validatebox(options);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).val();
        },
        setValue: function (target, value) {
            $(target).val(value);
        },
        resize: function (target, width) {
            $(target)._outerWidth(width);
        }
    },
    pph23_status: {
        init: function (container, options) {
            var input = $('<input type="text" class="pph23_status" style="height:18px;" readonly/>').appendTo(container);
            return input.validatebox(options);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).val();
        },
        setValue: function (target, value) {
            $(target).val(value);
        },
        resize: function (target, width) {
            $(target)._outerWidth(width);
        }
    },
    adv_netduein: {
        init: function (container, options) {
            var input = $('<input type="text" class="easyui-validatebox adv_netduein" style="height:18px;" readonly/>').appendTo(container);
            return input.validatebox(options);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).val();
        },
        setValue: function (target, value) {
            $(target).val(value);
        },
        resize: function (target, width) {
            $(target)._outerWidth(width);
        }
    },
    category_code: {
        init: function (container, options) {
            var input = $('<input type="text" class="category_code" style="height:18px;" readonly/>').appendTo(container);
            return input.validatebox(options);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).val();
        },
        setValue: function (target, value) {
            $(target).val(value);
        },
        resize: function (target, width) {
            $(target)._outerWidth(width);
        }
    },
    item_status: {
        init: function (container, options) {
            var input = $('<input type="text" class="item_status" style="height:18px;" readonly/>').appendTo(container);
            return input.validatebox(options);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).val();
        },
        setValue: function (target, value) {
            $(target).val(value);
        },
        resize: function (target, width) {
            $(target)._outerWidth(width);
        }
    },
    amount: {
        init: function (container, options) {
            var input = $('<input type="text" class="amount" style="height:18px;" readonly />').appendTo(container);
            return input.validatebox(options);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).val();
        },
        setValue: function (target, value) {
            $(target).val(value);
        },
        resize: function (target, width) {
            $(target)._outerWidth(width);
        }
    },
    memo: {
        init: function (container, options) {
            var input = $('<input type="text" class="memo" style="height:18px;" readonly />').appendTo(container);
            return input.validatebox(options);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).val();
        },
        setValue: function (target, value) {
            $(target).val(value);
        },
        resize: function (target, width) {
            $(target)._outerWidth(width);
        }
    },
    max_item: {
        init: function (container, options) {
            var input = $('<input type="text" class="max_item" style="height:18px;" readonly />').appendTo(container);
            return input.validatebox(options);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).val();
        },
        setValue: function (target, value) {
            $(target).val(value);
        },
        resize: function (target, width) {
            $(target)._outerWidth(width);
        }
    },
    warehouse_id: {
        init: function (container, options) {
            var input = $('<input type="text" class="warehouse_id" style="height:18px;" readonly />').appendTo(container);
            return input.validatebox(options);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).val();
        },
        setValue: function (target, value) {
            $(target).val(value);
        },
        resize: function (target, width) {
            $(target)._outerWidth(width);
        }
    },
    item_return: {
        init: function (container, options) {
            var input = $('<input type="text" class="item_return" onClick="open_item_return()" style="height:18px;" readonly/>').appendTo(container);
            return input.validatebox(options);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).val();
        },
        setValue: function (target, value) {
            $(target).val(value);
        },
        resize: function (target, width) {
            $(target)._outerWidth(width);
        }
    },
    itemhpp: {
        init: function (container, options) {
            var input = $('<input type="text" class="itemhpp" style="height:18px;" readonly />').appendTo(container);
            return input.validatebox(options);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).val();
        },
        setValue: function (target, value) {
            $(target).val(value);
        },
        resize: function (target, width) {
            $(target)._outerWidth(width);
        }
    },
    itemkategori: {
        init: function (container, options) {
            var input = $('<input type="text" class="itemkategori" style="height:18px;" readonly />').appendTo(container);
            return input.validatebox(options);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).val();
        },
        setValue: function (target, value) {
            $(target).val(value);
        },
        resize: function (target, width) {
            $(target)._outerWidth(width);
        }
    },
    qty_return: {
        init: function (container, options) {
            var input = $('<input type="text" class="easyui-numberbox qty_return" />').appendTo(container);
            return input.numberbox(options);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).val();
        },
        setValue: function (target, value) {
            $(target).val(value);
        },
        resize: function (target, width) {
            $(target)._outerWidth(width);
        }
    },
    price_return: {
        init: function (container, options) {
            var input = $('<input type="text" class="easyui-numberbox price_return" style="width:200px;" />').appendTo(container);
            return input.numberbox(options);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).val();
        },
        setValue: function (target, value) {
            $(target).val(value);
        },
        resize: function (target, width) {
            $(target)._outerWidth(width);
        }
    },
    amount_return: {
        init: function (container, options) {
            var input = $('<input type="text" class="easyui-numberbox amount_return" style="width:200px" />').appendTo(container);
            return input.numberbox(options);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).val();
        },
        setValue: function (target, value) {
            $(target).val(value);
        },
        resize: function (target, width) {
            $(target)._outerWidth(width);
        }
    },
    id_field: {
        init: function (container, options) {
            var input = $('<input type="text" class="easyui-validatebox id_field" style="height:18px;" readonly/>').appendTo(container);
            return input.validatebox(options);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).val();
        },
        setValue: function (target, value) {
            $(target).val(value);
        },
        resize: function (target, width) {
            $(target)._outerWidth(width);
        }
    },
    item_qty_do: {
        init: function (container, options) {
            var input = $('<input type="text" class="easyui-validatebox item_qty_do" style="height:18px;" readonly/>').appendTo(container);
            return input.validatebox(options);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).val();
        },
        setValue: function (target, value) {
            $(target).val(value);
        },
        resize: function (target, width) {
            $(target)._outerWidth(width);
        }
    },
    item_qty_so: {
        init: function (container, options) {
            var input = $('<input type="text" class="easyui-numberbox item_qty_so" style="height:18px;" readonly/>').appendTo(container);
            return input.validatebox(options);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).val();
        },
        setValue: function (target, value) {
            $(target).val(value);
        },
        resize: function (target, width) {
            $(target)._outerWidth(width);
        }
    },
    pord_number_on_pp: {
        init: function (container, options) {
            var input = $('<input type="text" id="modalTabItem" class="item"  onClick="open_data_dp()" style="height:18px;" readonly/>').appendTo(container);
            return input.validatebox(options);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).val();
        },
        setValue: function (target, value) {
            $(target).val(value);
        },
        resize: function (target, width) {
            $(target)._outerWidth(width);
        }
    }
});

//>>>>>>>>>>>>>> TAMBAHAN DHIDHIK, 26 / 01 / 2016 <<<<<<<<<<<<<<<<<<<<<<<<< //
$.extend($.fn.datagrid.methods, {//untuk focus pada field yang invalid
    focusInvalidField: function (jq, index) {
        return jq.each(function () {
            var target = this;
            var tr = $.data(target, 'datagrid').options.finder.getTr(target, index);
            if (!tr.hasClass('datagrid-row-editing')) {
                return true;
            }
            var invalidbox = tr.find('.validatebox-invalid');
            invalidbox.filter(':not(:disabled):first').focus();
        });
    }
});
function qtyRowDatagrid(idname) { //untuk mencari banyak baris yang ada pada datagrid
    idname = "#" + idname;
    var qty = $(idname).edatagrid('getRows').length;
    return qty;
}
function indexSelectedRowDatagrid(idname) { //untuk mencari baris ke-berapa yg aktif, klo ga ada yg aktif/selected nilainya = -1
    idname = "#" + idname;
    var selectedrow = $(idname).datagrid("getSelected");
    var rowIndex = $(idname).datagrid("getRowIndex", selectedrow);
    return rowIndex;
}
function focusCellDatagrid(rowIndex, idName, fieldName) { //untuk focus ke sell baris yg aktif (khusus onEdit utk text) 
    idName = "#" + idName;
    var ed = $(idName).edatagrid('getEditor', {index: rowIndex, field: fieldName});
    if (!$.isEmptyObject(ed)) {
        $(ed.target).focus();
    }
    //$(ed.target).focus();
}
function focusCellDateDatagrid(rowIndex, idName, fieldName) { //untuk focus ke cell dengan type datebox pada datagrid baris yg aktif
    idName = "#" + idName;
    var ed = $(idName).datagrid('getEditor', {index: rowIndex, field: fieldName});
    $(ed.target).datebox('textbox').focus();
}
function checkValidDatagrid(formId) {//untuk mengecek valid tidaknya isi dari row grid nya
    formId = "#" + formId;
    var rstValid = $(formId).form('validate');
    return rstValid;
}
function deleteRowDatagrid(editedIndex, idName) {//untuk hapus data 1 row sesuai rowIndex,   editedIndex adalah index dari baris/row yg ter-edit-ing/editornya row sedang terbuka utk pengeditan 
    var row_Index = indexSelectedRowDatagrid(idName);
    idName = "#" + idName;
    if (editedIndex > -1) {
        var dtg_item_grid = $(idName).edatagrid('getEditors', editedIndex);  // get the first editor
        dtg_item_grid.forEach(function (eachRow, eachIndex) {
            var cellField = dtg_item_grid[eachIndex]['field'];
            var coll = $(idName).datagrid("getEditor", {index: editedIndex, field: cellField});
            var valueCell = $(coll.target).val();
            if (valueCell == null || valueCell == "" || valueCell == undefined) {
                if (coll.type == "datebox") {
                    $(coll.target).datebox('setValue', '06/01/2012');
                } else {
                    $(coll.target).val('10');
                }
            }
        });
        $(idName).datagrid('endEdit', editedIndex); //biarken seperti ini ye 
        $(idName).datagrid('deleteRow', editedIndex);
    } else {
        if (row_Index > -1) {
            $(idName).datagrid('deleteRow', row_Index);
        }
    }
}
function messageAlertBiasa(titleAlert, contentAlert, typeAlert) {//untuk memunculcal alert tanpa function, ini berfungsi untuk memper-efisien true-false isStatusShortKey-nya
    isStatusShortKey = false;
    $.messager.alert(titleAlert, contentAlert, typeAlert, function () {
        isStatusShortKey = true;
    });
}
function strMessageAlert_report(strAlert){
    var showStr = "";
    switch(strAlert){
        case 'dateFrom>dateTo' : showStr = "'Date From' Tidak Boleh Lebih Besar dari 'Date To'.";
            break;
        case 'dateFrom>now' : showStr = "'Date From' Maksimal tanggal hari ini !";
            break;
        case 'dateTo>now' : showStr = "'Date From' Maksimal tanggal hari ini !";
            break;
        case 'companyIsEmpty' : showStr = "'Company' Tidak Boleh Kosong.";
            break;
        case 'branchIsEmpty' : showStr = "'Branch' Tidak Boleh Kosong.";
            break;
        case 'bankIsEmpty' : showStr = "'Bank' Tidak Boleh Kosong.";
            break;
        default : showStr = "Maaf, Terjadi Kesalahan Data.";
            break;
    }
    return showStr;
}
function strDateIndToEng(strDate){
    var splitDate =  strDate.split('-');
    var rstDate = splitDate[2]+"-"+splitDate[1]+"-"+splitDate[0];
    return rstDate;
}
function mustBeChooseRowDatagrid(idGrid) {//untuk checking row datagrid sudah terpilih/terselect atau belum,,,
    isStatusShortKey = false;
    if (indexSelectedRowDatagrid(idGrid) > -1) {//<<<<======== dhidhik, 11 feb 2016
        isStatusShortKey = true;
        return true;
    } else {//<<<<======== dhidhik, 11 feb 2016
        messageAlertBiasa('Warning', 'Pilih data terlebih dahulu !', 'error');
        isStatusShortKey = true;
        return false;
    }
}

//(function(){
Array.prototype.allIndexOf = function (searchElement) { //untuk mendapatkan nilai index yang valuenya sama
    if (this === null) {
        return [-1];
    }
    var len = this.length,
            hasIndexOf = Array.prototype.indexOf, // you know, because of IE
            i = (hasIndexOf) ? this.indexOf(searchElement) : 0,
            n,
            indx = 0,
            result = [];
    if (len === 0 || i === -1) {
        return [-1];
    }
    if (hasIndexOf) {
        // Array.indexOf does exist
        for (n = 0; n <= len; n++) {
            i = this.indexOf(searchElement, indx);
            if (i !== -1) {
                indx = i + 1;
                result.push(i);
            } else {
                return result;
            }
        }
        return result;
    } else {
        // Array.indexOf doesn't exist
        for (n = 0; n <= len; n++) {
            if (this[n] === searchElement) {
                result.push(n);
            }
        }
        return (result.length > 0) ? result : [-1];
    }
};
//})();
function asciiToString(asciiIndex) { //untuk mendapatkan String dari kode ascii
    var keyboardMap = [
        "", // [0]
        "", // [1]
        "", // [2]
        "CANCEL", // [3]
        "", // [4]
        "", // [5]
        "HELP", // [6]
        "", // [7]
        "BACK_SPACE", // [8]
        "TAB", // [9]
        "", // [10]
        "", // [11]
        "CLEAR", // [12]
        "ENTER", // [13]
        "ENTER_SPECIAL", // [14]
        "", // [15]
        "SHIFT", // [16]
        "CONTROL", // [17]
        "ALT", // [18]
        "PAUSE", // [19]
        "CAPS_LOCK", // [20]
        "KANA", // [21]
        "EISU", // [22]
        "JUNJA", // [23]
        "FINAL", // [24]
        "HANJA", // [25]
        "", // [26]
        "ESCAPE", // [27]
        "CONVERT", // [28]
        "NONCONVERT", // [29]
        "ACCEPT", // [30]
        "MODECHANGE", // [31]
        "SPACE", // [32]
        "PAGE_UP", // [33]
        "PAGE_DOWN", // [34]
        "END", // [35]
        "HOME", // [36]
        "LEFT", // [37]
        "UP", // [38]
        "RIGHT", // [39]
        "DOWN", // [40]
        "SELECT", // [41]
        "PRINT", // [42]
        "EXECUTE", // [43]
        "PRINTSCREEN", // [44]
        "INSERT", // [45]
        "DELETE", // [46]
        "", // [47]
        "0", // [48]
        "1", // [49]
        "2", // [50]
        "3", // [51]
        "4", // [52]
        "5", // [53]
        "6", // [54]
        "7", // [55]
        "8", // [56]
        "9", // [57]
        "COLON", // [58]
        "SEMICOLON", // [59]
        "LESS_THAN", // [60]
        "EQUALS", // [61]
        "GREATER_THAN", // [62]
        "QUESTION_MARK", // [63]
        "AT", // [64]
        "A", // [65]
        "B", // [66]
        "C", // [67]
        "D", // [68]
        "E", // [69]
        "F", // [70]
        "G", // [71]
        "H", // [72]
        "I", // [73]
        "J", // [74]
        "K", // [75]
        "L", // [76]
        "M", // [77]
        "N", // [78]
        "O", // [79]
        "P", // [80]
        "Q", // [81]
        "R", // [82]
        "S", // [83]
        "T", // [84]
        "U", // [85]
        "V", // [86]
        "W", // [87]
        "X", // [88]
        "Y", // [89]
        "Z", // [90]
        "OS_KEY", // [91] Windows Key (Windows) or Command Key (Mac)
        "", // [92]
        "CONTEXT_MENU", // [93]
        "", // [94]
        "SLEEP", // [95]
        "NUMPAD0", // [96]
        "NUMPAD1", // [97]
        "NUMPAD2", // [98]
        "NUMPAD3", // [99]
        "NUMPAD4", // [100]
        "NUMPAD5", // [101]
        "NUMPAD6", // [102]
        "NUMPAD7", // [103]
        "NUMPAD8", // [104]
        "NUMPAD9", // [105]
        "MULTIPLY", // [106]
        "ADD", // [107]
        "SEPARATOR", // [108]
        "SUBTRACT", // [109]
        "DECIMAL", // [110]
        "DIVIDE", // [111]
        "F1", // [112]
        "F2", // [113]
        "F3", // [114]
        "F4", // [115]
        "F5", // [116]
        "F6", // [117]
        "F7", // [118]
        "F8", // [119]
        "F9", // [120]
        "F10", // [121]
        "F11", // [122]
        "F12", // [123]
        "F13", // [124]
        "F14", // [125]
        "F15", // [126]
        "F16", // [127]
        "F17", // [128]
        "F18", // [129]
        "F19", // [130]
        "F20", // [131]
        "F21", // [132]
        "F22", // [133]
        "F23", // [134]
        "F24", // [135]
        "", // [136]
        "", // [137]
        "", // [138]
        "", // [139]
        "", // [140]
        "", // [141]
        "", // [142]
        "", // [143]
        "NUM_LOCK", // [144]
        "SCROLL_LOCK", // [145]
        "WIN_OEM_FJ_JISHO", // [146]
        "WIN_OEM_FJ_MASSHOU", // [147]
        "WIN_OEM_FJ_TOUROKU", // [148]
        "WIN_OEM_FJ_LOYA", // [149]
        "WIN_OEM_FJ_ROYA", // [150]
        "", // [151]
        "", // [152]
        "", // [153]
        "", // [154]
        "", // [155]
        "", // [156]
        "", // [157]
        "", // [158]
        "", // [159]
        "CIRCUMFLEX", // [160]
        "EXCLAMATION", // [161]
        "DOUBLE_QUOTE", // [162]
        "HASH", // [163]
        "DOLLAR", // [164]
        "PERCENT", // [165]
        "AMPERSAND", // [166]
        "UNDERSCORE", // [167]
        "OPEN_PAREN", // [168]
        "CLOSE_PAREN", // [169]
        "ASTERISK", // [170]
        "PLUS", // [171]
        "PIPE", // [172]
        "HYPHEN_MINUS", // [173]
        "OPEN_CURLY_BRACKET", // [174]
        "CLOSE_CURLY_BRACKET", // [175]
        "TILDE", // [176]
        "", // [177]
        "", // [178]
        "", // [179]
        "", // [180]
        "VOLUME_MUTE", // [181]
        "VOLUME_DOWN", // [182]
        "VOLUME_UP", // [183]
        "", // [184]
        "", // [185]
        "SEMICOLON", // [186]
        "EQUALS", // [187]
        "COMMA", // [188]
        "MINUS", // [189]
        "PERIOD", // [190]
        "SLASH", // [191]
        "BACK_QUOTE", // [192]
        "", // [193]
        "", // [194]
        "", // [195]
        "", // [196]
        "", // [197]
        "", // [198]
        "", // [199]
        "", // [200]
        "", // [201]
        "", // [202]
        "", // [203]
        "", // [204]
        "", // [205]
        "", // [206]
        "", // [207]
        "", // [208]
        "", // [209]
        "", // [210]
        "", // [211]
        "", // [212]
        "", // [213]
        "", // [214]
        "", // [215]
        "", // [216]
        "", // [217]
        "", // [218]
        "OPEN_BRACKET", // [219]
        "BACK_SLASH", // [220]
        "CLOSE_BRACKET", // [221]
        "QUOTE", // [222]
        "", // [223]
        "META", // [224]
        "ALTGR", // [225]
        "", // [226]
        "WIN_ICO_HELP", // [227]
        "WIN_ICO_00", // [228]
        "", // [229]
        "WIN_ICO_CLEAR", // [230]
        "", // [231]
        "", // [232]
        "WIN_OEM_RESET", // [233]
        "WIN_OEM_JUMP", // [234]
        "WIN_OEM_PA1", // [235]
        "WIN_OEM_PA2", // [236]
        "WIN_OEM_PA3", // [237]
        "WIN_OEM_WSCTRL", // [238]
        "WIN_OEM_CUSEL", // [239]
        "WIN_OEM_ATTN", // [240]
        "WIN_OEM_FINISH", // [241]
        "WIN_OEM_COPY", // [242]
        "WIN_OEM_AUTO", // [243]
        "WIN_OEM_ENLW", // [244]
        "WIN_OEM_BACKTAB", // [245]
        "ATTN", // [246]
        "CRSEL", // [247]
        "EXSEL", // [248]
        "EREOF", // [249]
        "PLAY", // [250]
        "ZOOM", // [251]
        "", // [252]
        "PA1", // [253]
        "WIN_OEM_CLEAR", // [254]
        "" // [255]
    ];
    return keyboardMap[asciiIndex];
}
function setArrayTrue(dataArray) { //untuk memunculkan string ASCII di footer
    if ($.isArray(dataArray)) {
        var rstTrue = dataArray.allIndexOf(true);
        var rstStr = [];
        $.each(rstTrue, function (xkey, xvalue) {
            var stringkey = asciiToString(xvalue);
            rstStr.push(stringkey);
        });
        var rstActive = ", Active Key [<b style='color:red;'>" + rstStr.toString() + "</b>]";
        var xtipePage = self;
        $("#tt").length ? xtipePage = self : xtipePage = parent;
        xtipePage.document.getElementById("footerKey").innerHTML = rstActive;
    }

    return true;
}

function enterCheckedTranstatus(e, classChecked) {
    if (e.keyCode == 13) {
        if (classChecked == "chk_all") {
            if ($("." + classChecked).val() == 0) {
                $("." + classChecked).val(1);
                $("." + classChecked).prop('checked', true);
                $('input[name="chk_TransStatus"]').prop('checked', true);
            } else {
                $("." + classChecked).val(0);
                $("." + classChecked).prop('checked', false);
                $('input[name="chk_TransStatus"]').prop('checked', false);
            }
        } else {
            if ($("." + classChecked).is(":checked")) {
                $("." + classChecked).prop('checked', false);
            } else {
                $("." + classChecked).prop('checked', true);
            }
        }
    }
}

function datagrid_item_type_status(gridName) {

    $('#' + gridName).datagrid({
        rowStyler: function (index, row) {
            return color_rowgrid_item_type_status(row.ItemStatus);
        }
    });

}

function color_rowgrid_item_type_status(ItemType) {
    //* ItemType   : 0=Item, 1=Service/Expense, 2=Adv. Payment
    //* ItemStatus : 0=Inv, 1=FAsset, 2=Expense
    var bg_row = bgcolor_rowgrid_item();
    var color = "";
    if (ItemType == 0) {//fixasset           
		color = "background-color:"+bg_row['item_bg_bottom']+";color:"+bg_row['item_color']+";"
				+ "background: -webkit-linear-gradient("+bg_row['item_bg_top']+", "+bg_row['item_bg_bottom']+");"
				+ "background: -o-linear-gradient("+bg_row['item_bg_top']+", "+bg_row['item_bg_bottom']+");"
				+ "background: -moz-linear-gradient("+bg_row['item_bg_top']+", "+bg_row['item_bg_bottom']+");"
				+ "background: linear-gradient("+bg_row['item_bg_top']+", "+bg_row['item_bg_bottom']+");";
	} else if(ItemType == 2) {//item
		color = "background-color:"+bg_row['advance_bg_bottom']+";color:"+bg_row['advance_color']+";"
                    + "background: -webkit-linear-gradient("+bg_row['advance_bg_top']+", "+bg_row['advance_bg_bottom']+");"
                    + "background: -o-linear-gradient("+bg_row['advance_bg_top']+", "+bg_row['advance_bg_bottom']+");"
                    + "background: -moz-linear-gradient("+bg_row['advance_bg_top']+", "+bg_row['advance_bg_bottom']+");"
                    + "background: linear-gradient("+bg_row['advance_bg_top']+", "+bg_row['advance_bg_bottom']+");";
	}
			
    return color;
}

function datagrid_item_type(gridName) {

    $('#' + gridName).datagrid({
        rowStyler: function (index, row) {
            return color_rowgrid_item_type(row.ItemType, row.ItemStatus);
        }
    });

}

function color_rowgrid_item_type(ItemType, ItemStatus) {
    //* ItemType   : 0=Item, 1=Service/Expense, 2=Adv. Payment
    //* ItemStatus : 0=Inv, 1=FAsset, 2=Expense
    var bg_row = bgcolor_rowgrid_item();
    var color = "";
    ItemType = (ItemType * 1);
    switch (ItemType)
    {
        case 0:
            if (ItemStatus == 1) {//fixasset           
                color = "background-color:"+bg_row['fixasset_bg_bottom']+";color:"+bg_row['fixasset_color']+";"
                        + "background: -webkit-linear-gradient("+bg_row['fixasset_bg_top']+", "+bg_row['fixasset_bg_bottom']+");"
                        + "background: -o-linear-gradient("+bg_row['fixasset_bg_top']+", "+bg_row['fixasset_bg_bottom']+");"
                        + "background: -moz-linear-gradient("+bg_row['fixasset_bg_top']+", "+bg_row['fixasset_bg_bottom']+");"
                        + "background: linear-gradient("+bg_row['fixasset_bg_top']+", "+bg_row['fixasset_bg_bottom']+");";
            } else {//item
                color = "background-color:"+bg_row['item_bg_bottom']+";color:"+bg_row['item_color']+";"
                        + "background: -webkit-linear-gradient("+bg_row['item_bg_top']+", "+bg_row['item_bg_bottom']+");"
                        + "background: -o-linear-gradient("+bg_row['item_bg_top']+", "+bg_row['item_bg_bottom']+");"
                        + "background: -moz-linear-gradient("+bg_row['item_bg_top']+", "+bg_row['item_bg_bottom']+");"
                        + "background: linear-gradient("+bg_row['item_bg_top']+", "+bg_row['item_bg_bottom']+");";
            }
            break;
        case 1:
            color = "background-color:"+bg_row['expense_bg_bottom']+";color:"+bg_row['expense_color']+";"
                    + "background: -webkit-linear-gradient("+bg_row['expense_bg_top']+", "+bg_row['expense_bg_bottom']+");"
                    + "background: -o-linear-gradient("+bg_row['expense_bg_top']+", "+bg_row['expense_bg_bottom']+");"
                    + "background: -moz-linear-gradient("+bg_row['expense_bg_top']+", "+bg_row['expense_bg_bottom']+");"
                    + "background: linear-gradient("+bg_row['expense_bg_top']+", "+bg_row['expense_bg_bottom']+");";
            //color = 'background-color:#fcf8e3;color:#000000;';
            break;
        case 2:
            color = "background-color:"+bg_row['advance_bg_bottom']+";color:"+bg_row['advance_color']+";"
                    + "background: -webkit-linear-gradient("+bg_row['advance_bg_top']+", "+bg_row['advance_bg_bottom']+");"
                    + "background: -o-linear-gradient("+bg_row['advance_bg_top']+", "+bg_row['advance_bg_bottom']+");"
                    + "background: -moz-linear-gradient("+bg_row['advance_bg_top']+", "+bg_row['advance_bg_bottom']+");"
                    + "background: linear-gradient("+bg_row['advance_bg_top']+", "+bg_row['advance_bg_bottom']+");";
            //color = 'background-color:#fcf8e3;color:#000000;';
            break;
    }
    return color;
}
function legend_grid_itemtype(){
    var bgclr_box = bgcolor_rowgrid_item();
    var html_div_legend = "<div class='legend-boxbg' style='background-color:"+bgclr_box['fixasset_bg_bottom']+";border:1px solid "+bgclr_box['fixasset_color']+";'></div> <div class='legend-label'> Fixasset</div><div style='clear:both;'></div>"
        +"<div class='legend-boxbg' style='background-color:"+bgclr_box['item_bg_bottom']+";border:1px solid "+bgclr_box['item_color']+";'></div> <div class='legend-label'> Item Inventory</div><div style='clear:both;'></div>"
        +"<div class='legend-boxbg' style='background-color:"+bgclr_box['expense_bg_bottom']+";border:1px solid "+bgclr_box['expense_color']+";'></div> <div class='legend-label'> Service / Expense</div><div style='clear:both;'></div>"
        +"<div class='legend-boxbg' style='background-color:"+bgclr_box['advance_bg_bottom']+";border:1px solid "+bgclr_box['advance_color']+";'></div> <div class='legend-label'> Advances Payment</div><div style='clear:both;'></div>";
    
    $("#legend-grid-item").html(html_div_legend);
}
function bgcolor_rowgrid_item(){    
    var bgcolor_griditem = {
        fixasset_bg_top     : "#e1f1da",
        fixasset_bg_bottom  : "#d2eac8",
        fixasset_color      : "#196600",
        item_bg_top         : "#ffe5f2",
        item_bg_bottom      : "#ffcce6",
        item_color          : "#5b2424",
        expense_bg_top      : "#f8eded",
        expense_bg_bottom   : "#f0dbdb",
        expense_color       : "#491d1d",
        advance_bg_top      : "#faf4d1",
        advance_bg_bottom   : "#f8eeba",
        advance_color       : "#453b07"
    };
    return bgcolor_griditem;
}
function sendParamJson(){
    // For checkbox TransStatus
     var arTransStatus = new Array();
    if ($.find('input[name="chk_TransStatus"]').length > 0) {
        $.each($('input[name="chk_TransStatus"]:checked'), function () {
            arTransStatus.push($(this).val());
        });
    }
    
    var arItemType = new Array();
    if ($.find('input[name="chk_TransStatus"]').length > 0) {
        $.each($('input[name="chk_ItemType"]:checked'),function(){
                arItemType.push($(this).val());
        });
    }

    var sendParam = {
        cmb_company     : $.find('#cmb_company').length >0&&$('#cmb_company').combobox('getValue')!=undefined?$('#cmb_company').combobox('getValue'):"",//inventories item,adjustment
        cmb_branch      : $.find('#cmb_branch').length >0&&$('#cmb_branch').combobox('getValue')!=undefined?$('#cmb_branch').combobox('getValue'):"",//inventories item,adjustment
        txt_item_code   : $.find('#txt_item_code').length >0?$('#txt_item_code').val():"",//inventories item
        txt_item_desc   : $.find('#txt_item_desc').length >0?$('#txt_item_desc').val():"",//inventories item,fixedAssetList
        txt_IDNumber    : $.find('#txt_IDNumber').length >0?$('#txt_IDNumber').val():"",//adjustment
        txt_Description : $.find('#txt_Description').length >0?$('#txt_Description').val():"",//adjustment,item
        txt_DateFrom    : $.find('#txt_DateFrom').length >0?$('#txt_DateFrom').val():"",//adjustment
        txt_DateTo      : $.find('#txt_DateTo').length >0?$('#txt_DateTo').val():"",//adjustment
        chk_TransStatus : arTransStatus //adjustment
        ,txt_desc       : $.find('#txt_desc').length >0?$('#txt_desc').val():""//itemCategory,fixedAssetType
        ,txt_no         : $.find('#txt_no').length >0?$('#txt_no').val():""//itemCategory,employee
        ,cmb_category   : $.find('#cmb_category').length >0&&$('#cmb_category').combobox('getValue')!=undefined?$('#cmb_category').combobox('getValue'):""//item,
        ,chk_ItemType   : arItemType //item        
        ,txt_code       : $.find('#txt_code').length >0?$('#txt_code').val():""//fixedAssetType,
        ,txt_asset_code : $.find('#txt_asset_code').length >0?$('#txt_asset_code').val():""//fixedAssetList,
        ,txt_VendorCode : $.find('#txt_VendorCode').length >0?$('#txt_VendorCode').val():""//vendor,
        ,txt_VendorName : $.find('#txt_VendorName').length >0?$('#txt_VendorName').val():""//vendor,
        ,cmb_CurrencyCode   : $.find('#cmb_CurrencyCode').length >0&&$('#cmb_CurrencyCode').combobox('getValue')!=undefined?$('#cmb_CurrencyCode').combobox('getValue'):""//vendor,
        ,txt_CustomerCode   : $.find('#txt_CustomerCode').length >0?$('#txt_CustomerCode').val():""//customer,
        ,txt_CustomerName   : $.find('#txt_CustomerName').length >0?$('#txt_CustomerName').val():""//vendor,
        ,txt_department_code: $.find('#txt_department_code').length >0?$('#txt_department_code').val():""//departement,
        ,txt_department_name: $.find('#txt_department_name').length >0?$('#txt_department_name').val():""//departement,
        ,txt_currency_code  : $.find('#txt_currency_code').length >0?$('#txt_currency_code').val():""//curency,
        ,txt_currency_name  : $.find('#txt_currency_name').length >0?$('#txt_currency_name').val():""//currency,
        ,txt_BankCode       : $.find('#txt_BankCode').length >0?$('#txt_BankCode').val():""//bank,
        ,txt_BankName       : $.find('#txt_BankName').length >0?$('#txt_BankName').val():""//bank,
        ,cmb_Bank           : $.find('#cmb_Bank').length >0&&$('#cmb_Bank').combobox('getValue')!=undefined?$('#cmb_Bank').combobox('getValue'):""//bank reconcile,
        ,txt_TransferFrom   : $.find('#txt_TransferFrom').length >0?$('#txt_TransferFrom').val():""//bank,
        ,txt_TransferTo     : $.find('#txt_TransferTo').length >0?$('#txt_TransferTo').val():""//bank,
        ,cmb_VendorCode     : $.find('#cmb_VendorCode').length >0&&$('#cmb_VendorCode').combobox('getValue')!=undefined?$('#cmb_VendorCode').combobox('getValue'):""//purchase order,
        ,cmb_PaymentStatus  : $.find('#cmb_PaymentStatus').length >0&&$('#cmb_PaymentStatus').combobox('getValue')!=undefined?$('#cmb_PaymentStatus').combobox('getValue'):""//purchase order,
                
    };  
    
    sendParam = JSON.stringify(sendParam); 
    sendParam = sendParam.replace(/-/g,'%2D');
    sendParam = encodeURIComponent(sendParam); 
    return sendParam;
}
function strTrim(x) {
    return x.replace(/^\s+|\s+$/gm,'');
}
function cekArraySummary(masterAr, cekName,cekValue){
    var checkIndexSumAll       = -1;
    var checkIndexArAll        = 0;
    masterAr.forEach(function (dtStatusAll) {//cek nilai status pada array statusAll ada ato tidak
        var str_loop = dtStatusAll[cekName]!=null&&dtStatusAll[cekName]!=undefined?strTrim(dtStatusAll[cekName]):dtStatusAll[cekName];
        var str_cek  = cekValue!=null&&cekValue!=undefined?strTrim(cekValue):cekValue;
        if (str_loop == str_cek) {
            checkIndexSumAll = checkIndexArAll;
        }
        checkIndexArAll++;
    });
    return checkIndexSumAll;
}

function enterCheckedTranstatus_report(e,keyClick, classChecked) {    
    if(keyClick == 'key'){
        if (e.keyCode == 13) {
            exeCheckedTranstatus_report(classChecked);
        }
    }else if(keyClick == 'click'){
        exeCheckedTranstatus_report(classChecked);
    }
}
function exeCheckedTranstatus_report(classChecked) {
    if (classChecked == "chk_allTranstatus") {
        if ($("." + classChecked).val() == 0) {
            $("." + classChecked).val(1);
            $("." + classChecked).prop('checked', true);
            $('input[name="chk_TransStatus"]').prop('checked', true);
        } else {
            $("." + classChecked).val(0);
            $("." + classChecked).prop('checked', false);
            $('input[name="chk_TransStatus"]').prop('checked', false);
        }
    } else{
        if ($("." + classChecked).is(":checked")) {
            $("." + classChecked).val(0);
            $("." + classChecked).prop('checked', false);
        } else {
            $("." + classChecked).val(1);
            $("." + classChecked).prop('checked', true);
        }
    }
}

function enterCheckedItemType(e,keyClick, classChecked) {
    if(keyClick == 'key'){
        if (e.keyCode == 13) {
            exeCheckedItemType(classChecked);
        }
    }else if(keyClick == 'click'){
        exeCheckedItemType(classChecked);
    }
    
}
function exeCheckedItemType(classChecked){
    if (classChecked == "chk_allItemType") {
        if ($("." + classChecked).val() == 0) {
            $("." + classChecked).val(1);
            $("." + classChecked).prop('checked', true);
            $('input[name="chk_itemType"]').prop('checked', true);
        } else {
            $("." + classChecked).val(0);
            $("." + classChecked).prop('checked', false);
            $('input[name="chk_itemType"]').prop('checked', false);
        }
    } else {
        if ($("." + classChecked).is(":checked")) {
            $("." + classChecked).val(0);
            $("." + classChecked).prop('checked', false);
        } else {
            $("." + classChecked).val(1);
            $("." + classChecked).prop('checked', true);
        }
    }
}
function toHTMLTranstatusReport(divClassName, data){
    var toHtml = "";
    data.forEach(function (dtResults){
        toHtml = toHtml + ""+ trTranstatusReport(dtResults['status'], dtResults['checked']);
    });
    $("."+divClassName).replaceWith(toHtml);
}
function trTranstatusReport(strTrans, checkTrans){    
    var htmlTrans = {
        all         : '<tr>'
                    +'<td style="padding-bottom:8px;">'
                        +'<div style="float:left;"><b>by Status Item</b></div>'
                        +'<div style="float:right;">'
                            +'<b><input type="checkbox" name="chk_allTranstatus" value="all" class="chk_allTranstatus" '+checkTrans
                                +' onkeyup="enterCheckedTranstatus_report(event,\'key\',\'chk_allTranstatus\')" '
                                +' onclick="enterCheckedTranstatus_report(event,\'click\',\'chk_allTranstatus\')" style="margin-left:0px;"/> All</b>'
                        +'</div></td></tr>',
        no_all         : '<tr><td style="padding-bottom:8px;">'
                        +'<div style="float:left;"><b>by Status Item</b></div></td></tr>',
                
        dp          : '<tr><td><input type="checkbox" name="chk_TransStatus" value="0" style="margin-left:0px;" class="chk_DP" '
                        +'onkeyup="enterCheckedTranstatus_report(event,\'key\',\'chk_DP\')"  '+checkTrans+' /> Waiting For DP </td></tr>',
                
        onprogress  : '<tr><td><input type="checkbox" name="chk_TransStatus" value="1" style="margin-left:0px;" class="chk_onProgress" '
                        +'onkeyup="enterCheckedTranstatus_report(event,\'key\',\'chk_onProgress\')"  '+checkTrans+' /> On Progress </td></tr>',
                
        finish  : '<tr><td><input type="checkbox" name="chk_TransStatus" value="2" style="margin-left:0px;" class="chk_finish" '
                        +'onkeyup="enterCheckedTranstatus_report(event,\'key\',\'chk_finish\')"  '+checkTrans+' /> Finished </td></tr>',
                
        suspend  : '<tr><td><input type="checkbox" name="chk_TransStatus" value="3" style="margin-left:0px;" class="chk_suspend" '
                        +'onkeyup="enterCheckedTranstatus_report(event,\'key\',\'chk_suspend\')"  '+checkTrans+' /> Suspended </td></tr>',
                
        app_mgr  : '<tr><td><input type="checkbox" name="chk_TransStatus" value="4" style="margin-left:0px;" class="chk_appMgr" '
                        +'onkeyup="enterCheckedTranstatus_report(event,\'key\',\'chk_appMgr\')"  '+checkTrans+' /> Need App. Mgr. </td></tr>',
                
        app_dir  : '<tr><td><input type="checkbox" name="chk_TransStatus" value="5" style="margin-left:0px;" class="chk_appDir" '
                        +'onkeyup="enterCheckedTranstatus_report(event,\'key\',\'chk_appDir\')"  '+checkTrans+' /> Need App. Dir. </td></tr>',
                
        app_dirmgr  : '<tr><td><input type="checkbox" name="chk_TransStatus" value="6" style="margin-left:0px;" class="chk_appDirMgr" '
                        +'onkeyup="enterCheckedTranstatus_report(event,\'key\',\'chk_appDirMgr\')"  '+checkTrans+' /> App. Dir & Mgr </td></tr>',
                
        app_limit  : '<tr><td><input type="checkbox" name="chk_TransStatus" value="7" style="margin-left:0px;" class="chk_appLimit" '
                        +'onkeyup="enterCheckedTranstatus_report(event,\'key\',\'chk_appLimit\')"  '+checkTrans+' /> App. Limit </td></tr>',
                
        suspend_item  : '<tr><td><input type="checkbox" name="chk_TransStatus" value="8" style="margin-left:0px;" class="chk_suspendItem" '
                        +'onkeyup="enterCheckedTranstatus_report(event,\'key\',\'chk_suspendItem\')"  '+checkTrans+' /> Suspend Item </td></tr>',
                
        cancel_dir  : '<tr><td><input type="checkbox" name="chk_TransStatus" value="9" style="margin-left:0px;" class="chk_cancelDir" '
                        +'onkeyup="enterCheckedTranstatus_report(event,\'key\',\'chk_cancelDir\')"  '+checkTrans+' /> Cancel By Dir. </td></tr>',
                
        master_active  : '<tr><td><input type="checkbox" name="chk_TransStatus" value="1" style="margin-left:0px;" class="chk_active" '
                        +'onkeyup="enterCheckedTranstatus_report(event,\'key\',\'chk_active\')"  '+checkTrans+' /> Active </td></tr>',
                
        master_nonactive  : '<tr><td><input type="checkbox" name="chk_TransStatus" value="3" style="margin-left:0px;" class="chk_noActive" '
                        +'onkeyup="enterCheckedTranstatus_report(event,\'key\',\'chk_noActive\')"  '+checkTrans+' /> Non Active </td></tr>',
                
        master_app_dir  : '<tr><td><input type="checkbox" name="chk_TransStatus" value="4" style="margin-left:0px;" class="chk_appDir" '
                        +'onkeyup="enterCheckedTranstatus_report(event,\'key\',\'chk_appDir\')"  '+checkTrans+' /> Need App. Dir </td></tr>' ,
                
        //==== master Fixasset =======//        
        inventories  : '<tr><td><input type="checkbox" name="chk_TransStatus" value="0" style="margin-left:0px;" class="chk_inventories" '
                        +'onkeyup="enterCheckedTranstatus_report(event,\'key\',\'chk_appDir\')"  '+checkTrans+' /> Inventories </td></tr>' ,
                
        sold  : '<tr><td><input type="checkbox" name="chk_TransStatus" value="1" style="margin-left:0px;" class="chk_sold" '
                        +'onkeyup="enterCheckedTranstatus_report(event,\'key\',\'chk_appDir\')"  '+checkTrans+' /> Sold </td></tr>' ,
                
        return  : '<tr><td><input type="checkbox" name="chk_TransStatus" value="3" style="margin-left:0px;" class="chk_return" '
                        +'onkeyup="enterCheckedTranstatus_report(event,\'key\',\'chk_appDir\')"  '+checkTrans+' /> Return </td></tr>' ,
                
        dispose  : '<tr><td><input type="checkbox" name="chk_TransStatus" value="4" style="margin-left:0px;" class="chk_dispose" '
                        +'onkeyup="enterCheckedTranstatus_report(event,\'key\',\'chk_appDir\')"  '+checkTrans+' /> Dispose </td></tr>' 
        //==== end master Fixasset =======//                                                  
    };
    return htmlTrans[strTrans];
}

function toHTMLItemTypeReport(divClassName, data){
    var toHtml = "";
    data.forEach(function (dtResults){
        toHtml = toHtml + ""+ trItemTypeReport(dtResults['status'], dtResults['checked']);
    });
    $("."+divClassName).replaceWith(toHtml);
}
function trItemTypeReport(strTrans, checkTrans){    
    var htmlTrans = {
        all         : '<tr>'
                    +'<td style="padding-bottom:8px;">'
                        +'<div style="float:left;"><b>by Item Type</b></div>'
                        +'<div style="float:right;">'
                            +'<b><input type="checkbox" name="chk_allItemType" value="all" class="chk_allItemType" '+checkTrans
                                +' onkeyup="enterCheckedItemType(event,\'key\',\'chk_allItemType\')" '
                                +' onclick="enterCheckedItemType(event,\'click\',\'chk_allItemType\')" style="margin-left:0px;"/> All</b>'
                        +'</div></td></tr>',
        no_all         : '<tr><td style="padding-bottom:8px;">'
                        +'<div style="float:left;"><b>by Item Type</b></div></td></tr>',
                
        inv          : '<tr><td><input type="checkbox" name="chk_itemType" value="0" style="margin-left:0px;" class="chk_inv" '
                        +'onkeyup="enterCheckedItemType(event,\'key\',\'chk_inv\')"  '+checkTrans+' /> Inventory </td></tr>',
                
        exp  : '<tr><td><input type="checkbox" name="chk_itemType" value="1" style="margin-left:0px;" class="chk_exp" '
                        +'onkeyup="enterCheckedItemType(event,\'key\',\'chk_exp\')"  '+checkTrans+' /> Expense </td></tr>',
                
        adv  : '<tr><td><input type="checkbox" name="chk_itemType" value="2" style="margin-left:0px;" class="chk_adv" '
                        +'onkeyup="enterCheckedItemType(event,\'key\',\'chk_adv\')"  '+checkTrans+' /> Adv. Payment </td></tr>'
            };                
        
    return htmlTrans[strTrans];
}

function formatRpRoundDec(a,b) { //a = angka yang akan di format, b= jumlah digit dibelakang koma,sifatnya pembulatan   
    if (a === undefined || a === null || isNaN(a)) {
        return '0.00';
    }
    else {
        a = parseFloat(a);
        a = a.toFixed(b);
        temp = a.split('.');

        if (temp.length > 1) {
            decimal = temp[1];
        }
        else {
            decimal = '00';
        }

        e = function (f) {
            return f.split('').reverse().join('')
        };

        b = e(parseInt(a).toString());

        for (c = 0, d = ''; c < b.length; c++) {
            d += b[c];

            if ((c + 1) % 3 === 0 && c !== (b.length - 1)) {
                d += '.';
            }
        }

        return '\t' + e(d) + ',' + decimal;
    }
}
function limitRowInPage(){
    return 150;
}
function tableHTMLTopHeaderReport(data) {
    var tempStringHTML = "";
    tempStringHTML += "<table border='0' cellspacing='0' cellpadding='3' width='96%' align='center' class='tree-2' style='margin-bottom:30px;'>"
            + "<tr>"
            + "<td colspan='" + data.colspan + "' class='s0 text-center'><span class='normal_bold span_block ' ><small>" + data.CompanyName + "</small></span></td>"
            + "</tr>"
            + "<tr>"
            + "<td colspan='" + data.colspan + "' class='s0 text-center'><span class='normal_bold span_block ' ><small>";
    tempStringHTML += data.BranchName;
    tempStringHTML += "</small></span></td>"
            + "</tr>"
            + "<tr>"
            + "<td colspan='" + data.colspan + "' class='s1 text-center'><span class='normal_bold span_block ' ><small>" + data.reportLabel + "</small></span></td>"
            + "</tr>";
    if(data.startdate!="" && data.startdate!=null && data.startdate!=undefined
       && data.enddate!="" && data.enddate!=null && data.enddate!=undefined){
        tempStringHTML += "<tr><td colspan='" + data.colspan + "' class='s2'>From : " + data.startdate + "&nbsp;&nbsp; To &nbsp;&nbsp; " + data.enddate + "</td></tr>";
    }else if((data.startdate!="" && data.startdate!=null && data.startdate!=undefined)
       && (data.enddate=="" || data.enddate==null || data.enddate==undefined)){
        tempStringHTML += "<tr><td colspan='" + data.colspan + "' class='s2'> As " + data.startdate + "</td></tr>";
    }else if((data.startdate=="" || data.startdate==null || data.startdate==undefined)
       && (data.enddate!="" && data.enddate!=null && data.enddate!=undefined)){
        tempStringHTML += "<tr><td colspan='" + data.colspan + "' class='s2'> As " + data.enddate + "</td></tr>"; 
    }else{
        tempStringHTML += "<tr><td colspan='" + data.colspan + "' class='s2'></td></tr>"; 
    }
            tempStringHTML += "<tr>"
            + "<td colspan='" + data.colspan + "' class='s1'>&nbsp;</td>"
            + "</tr>";
    return tempStringHTML;
}
//>>>>>>>>>>>>>>END TAMBAHAN DHIDHIK, 26 / 01 / 2016 <<<<<<<<<<<<<<<<<<<<<<<<< //
function get_amount(value) {
    var temp_amount = $('.amount').val();
    var sub_total = $('#sub_total').val();
    var max_item = $('.max_item').val();

    var qty = $('.qty').val();
    var price = $('.price').val();

    var amount = parseInt(qty) * parseInt(price);

    if (isNaN(amount)) {
        $('.amount').val(0);
        $('.qty').val(0);
        $('#sub_total').val(0);
    }
    else if (isNaN(price)) {
        $('.amount').val(0);
        $('.qty').val(0);
        $('#sub_total').val(0);
    }
    else {
        $('.amount').val(amount);
        if (temp_amount != "") {
            sub_total = sub_total - temp_amount;
        }

        sub_total = parseInt(sub_total) + parseInt(amount);
        $('#sub_total').val(sub_total);
    }

    $('#dg_item').edatagrid('saveRow');
}

function get_amount2(value) {
    sub_total = $('#sub_total').val();
    qty = $('.qty').val();
    price = $('.price').val();
    // max_item	= $('.max_item').val();

    if ((qty != 0 || qty != null) || (price != 0 || price != null)) {
        amount = parseInt(qty) * parseInt(price);

        if (!isNaN(amount)) {
            sub_total = parseInt(sub_total) + amount;
            $('.amount').val(amount);
            $('#sub_total').val(sub_total);
        }
    }
}

/* Author : Herpan / Last update   : 23/7/2014 / fungsi untuk pop up expense group */

function open_expense_group() {
    modal_open('Select Expense', 'dialog-expense');
}

function choose_expense() {
    modal_close('dialog-expense');
}

$.extend($.fn.datagrid.defaults.editors, {
    expense_group: {
        init: function (container, options) {
            var input = $('<input type="text" class="expense_editor" onClick="open_expense_group()" style="height:18px;"/>').appendTo(container);
            return input.validatebox(options);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).val();
        },
        setValue: function (target, value) {
            $(target).val(value);
        },
        resize: function (target, width) {
            $(target)._outerWidth(width);
        }
    }
});

/* Author : Ladur / 08/10/2014 / fungsi untuk pop up inventory */

function open_inventory() {
    modal_open('Inventory', 'dialog-inventory');
}

function choose_inventory() {
    var selected_data = $('#tt_choose_inventory').datagrid('getSelected');

    flag = true;
    item = $('#dtg_item').datagrid('getRows');

    $.each(item, function (index, value) {
        if (selected_data.ItemCode == value.ItemCode) {
            $.messager.alert('Unseccessfull', 'Item sudah tersedia.', 'error', function () {
                $('#tt_choose_inventory').datagrid('reload');
            });
            flag = false;
        }
    });

    if (flag != false) {
        $('.item_inventory').val(selected_data.ItemCode);
        $('.description').val(selected_data.ItemDesc);
        $('.unit').val(selected_data.ItemUnit);
        $('.price').val(selected_data.ItemPrice);
        $('.max_item').val(selected_data.ItemQty - selected_data.ItemBooks);
        $('.item_category').val(selected_data.ItemCategoryID);
        $('.category_code').val(selected_data.ItemCategoryCode);
        $('.item_status').val(selected_data.ItemStatus);

        modal_close('dialog-inventory');
    }
}

/* Author : Fachri / fungsi untuk pop up job cost, daily production , daily production amount */
function open_production() {
    modal_open('Item', 'dialog-production');
}

function open_production_amount() {
    modal_open('Item', 'dialog-production-amount');
}

function open_job_costing() {
    modal_open('Item', 'dialog-job-costing');
}

function choose_production() {
    var selected_data = $('#tt_choose_production').datagrid('getSelected');

    flag = true;
    item = $('#dg_item').datagrid('getRows');

    $.each(item, function (index, value) {
        if (selected_data.ItemCode == value.ItemCode) {
            $.messager.alert('Unseccessfull', 'Item sudah tersedia.', 'error', function () {
                $('#tt_choose_production').datagrid('reload');
            });

            flag = false;
        }
    });

    if (flag != false) {
        $('.item_production').val(selected_data.ItemCode);
        $('.description').val(selected_data.ItemDesc);
        $('.unit').val(selected_data.ItemUnit);
        $('.warehouse_id').val(selected_data.ItemWHTypeID);
        modal_close('dialog-production');
    }
}

function choose_production_amount() {
    var selected_data = $('#tt_choose_production_amount').datagrid('getSelected');

    flag = true;
    item = $('#dg_item').datagrid('getRows');

    $.each(item, function (index, value) {
        if (selected_data.ItemCode == value.ItemCode) {
            $.messager.alert('Unseccessfull', 'Item sudah tersedia.', 'error', function () {
                $('#tt_choose_production_amount').datagrid('reload');
            });

            flag = false;
        }
    });

    if (flag != false) {
        $('.item_production_amount').val(selected_data.ItemCode);
        $('.description').val(selected_data.ItemDesc);
        $('.unit').val(selected_data.ItemUnit);
        $('.warehouse_id').val(selected_data.ItemWHTypeID);
        modal_close('dialog-production-amount');
    }
}


function choose_job_costing() {
    var selected_data = $('#tt_choose_job_costing').datagrid('getSelected');

    flag = true;
    item = $('#dg_job').datagrid('getRows');

    $.each(item, function (index, value) {
        if (selected_data.ItemCode == value.ItemCode) {
            $.messager.alert('Unseccessfull', 'Item sudah tersedia.', 'error', function () {
                $('#tt_choose_job_costing').datagrid('reload');
            });

            flag = false;
        }
    });

    if (flag != false) {
        $('.item_job_costing').val(selected_data.ItemCode);
        $('.description').val(selected_data.ItemDesc);
        $('.unit').val(selected_data.ItemUnit);
        $('.warehouse_id').val(selected_data.WHTypeName);
        $('.itemhpp').val(selected_data.ItemAverage);
        $('.itemkategori').val(selected_data.ItemCategoryID);
        $('.qty').val(selected_data.ItemQty);
        $('#txt_hidden_reload_status').val(1);
        modal_close('dialog-job-costing');
    }
}

/* end */

/* Author : Tagor / Tanggal : 05/11/2014 / fungsi untuk pop up account payment < 250rb */

function open_payment_account() {
    modal_open('Account List', 'dialog-payment-account');
}

function choose_account_payment() {
    var selected_data = $('#tt_choose_account_payment').datagrid('getSelected');

    $('.PaymentAccountName').val(selected_data.AccountName);
    modal_close('dialog-payment-account');
}

function open_payment_department() {
    modal_open('Department List', 'dialog-payment-department');
}

function choose_department_payment() {
    var selected_data = $('#tt_choose_department_payment').datagrid('getSelected');

    $('.DepartmentAccountName').val(selected_data.DepartmentName);
    $('.DepartmentAccountCode').val(selected_data.DepartmentCode);

    modal_close('dialog-payment-department');
}

$.extend($.fn.datagrid.defaults.editors, {
    PaymentAccountName: {
        init: function (container, options) {
            var input = $('<input type="text" class="PaymentAccountName" onClick="open_payment_account()" style="height:18px;" readonly/>').appendTo(container);
            return input.validatebox(options);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).val();
        },
        setValue: function (target, value) {
            $(target).val(value);
        },
        resize: function (target, width) {
            $(target)._outerWidth(width);
        }
    },
    DepartmentAccountName: {
        init: function (container, options) {
            var input = $('<input type="text" class="DepartmentAccountName" onClick="open_payment_department()" style="height:18px;" readonly/>').appendTo(container);
            return input.validatebox(options);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).val();
        },
        setValue: function (target, value) {
            $(target).val(value);
        },
        resize: function (target, width) {
            $(target)._outerWidth(width);
        }
    },
    DepartmentAccountCode: {
        init: function (container, options) {
            var input = $('<input type="text" class="DepartmentAccountCode" onClick="open_payment_department()" style="height:18px;" readonly/>').appendTo(container);
            return input.validatebox(options);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return $(target).val();
        },
        setValue: function (target, value) {
            $(target).val(value);
        },
        resize: function (target, width) {
            $(target)._outerWidth(width);
        }
    }
});
//**===== End Tagor ====

function convert_to_dmy(tanggal) {
    var day = tanggal.substr(8, 2);
    var month = tanggal.substr(5, 2);
    var year = tanggal.substr(0, 4);

    var date = day + '-' + month + '-' + year;

    return date;
}

function convert_to_ymd(tanggal) {
    var year = tanggal.substr(6, 4);
    var month = tanggal.substr(3, 2);
    var day = tanggal.substr(0, 2);

    var date = year + '-' + month + '-' + day;

    return date;
}

/* Created by Hasan on 2015/02/28 for Refresh Datagrid in List Page. */
function refresh_datagrid(id) {
    $('.form-filter')[0].reset();
    $('.filter_date').datebox('disable', true);

    $('.easyui-combobox').combobox('select', '');

    $(id).datagrid('reload', {});
}

function status_datagrid(TransStatus) {
    var color = "";
    switch (TransStatus)
    {
        case 'Active':
            color = "background-color:#f0dbdb;color:#491d1d;"
                    + "background: -webkit-linear-gradient(#f8eded, #f0dbdb); "
                    + "background: -o-linear-gradient(#f8eded, #f0dbdb);"
                    + "background: -moz-linear-gradient(#f8eded, #f0dbdb);"
                    + "background: linear-gradient(#f8eded, #f0dbdb);";
            break;
        case 'Waiting For DP':
            color = "background-color:#f0dbdb;color:#491d1d;"
                    + "background: -webkit-linear-gradient(#f8eded, #f0dbdb); "
                    + "background: -o-linear-gradient(#f8eded, #f0dbdb);"
                    + "background: -moz-linear-gradient(#f8eded, #f0dbdb);"
                    + "background: linear-gradient(#f8eded, #f0dbdb);";
            //color = 'background-color:#fcf8e3;color:#000000;';
            break;
        case 'On Progress':
            color = "background-color:#f8eeba;color:#453b07;"
                    + "background: -webkit-linear-gradient(#faf4d1, #f8eeba);"
                    + "background: -o-linear-gradient(#faf4d1, #f8eeba);"
                    + "background: -moz-linear-gradient(#faf4d1, #f8eeba);"
                    + "background: linear-gradient(#faf4d1, #f8eeba);";
            //color = 'background-color:#fcf8e3;color:#000000;';
            break;
        case 'Finished':
            color = "background-color:#d2eac8;color:#196600;"
                    + "background: -webkit-linear-gradient(#e1f1da, #d2eac8);"
                    + "background: -o-linear-gradient(#e1f1da, #d2eac8);"
                    + "background: -moz-linear-gradient(#e1f1da, #d2eac8);"
                    + "background: linear-gradient(#e1f1da, #d2eac8);";
            //color = 'background-color:#dff0d8;color:#000000;';
            break;
        case 'Suspended':
            color = "background-color:#ffcce6;color:#5b2424;"
                    + "background: -webkit-linear-gradient(#ffe5f2, #ffcce6);"
                    + "background: -o-linear-gradient(#ffe5f2, #ffcce6);"
                    + "background: -moz-linear-gradient(#ffe5f2, #ffcce6);"
                    + "background: linear-gradient(#ffe5f2, #ffcce6);";
            //color = 'background-color:#f2dede;color:#000000;';
            break;
        case 'Need App. Mgr.':
            color = "background-color:#d5ebf6;color:#0d2f3f;"
                    + "background: -webkit-linear-gradient(#eaf5fa, #d5ebf6);"
                    + "background: -o-linear-gradient(#eaf5fa, #d5ebf6);"
                    + "background: -moz-linear-gradient(#eaf5fa, #d5ebf6);"
                    + "background: linear-gradient(#eaf5fa, #d5ebf6);";
            //color = 'background-color:#d9edf7;color:#000000;';
            break;
        case 'Need App. Dir.':
            color = "background-color:#e5ccff;color:#26004d;"
                    + "background: -webkit-linear-gradient(#f2e5ff, #e5ccff);"
                    + "background: -o-linear-gradient(#f2e5ff, #e5ccff);"
                    + "background: -moz-linear-gradient(#f2e5ff, #e5ccff);"
                    + "background: linear-gradient(#f2e5ff, #e5ccff);";
            //color = 'background-color:#E6E6FA;color:#000000;';
            break;
        case 'App. Dir & Mgr':
            color = "background-color:#fff;color:#333333;"
                    + "background: -webkit-linear-gradient(#ffffff, #fff);"
                    + "background: -o-linear-gradient(#ffffff, #fff);"
                    + "background: -moz-linear-gradient(#ffffff, #fff);"
                    + "background: linear-gradient(#ffffff, #fff); ";
            //color = 'background-color:#fff;color:#000000;';
            break;
        case 'App. Limit':
            color = "background-color:#e6e6e6;color:#262626;"
                    + "background: -webkit-linear-gradient(#f2f2f2, #e6e6e6);"
                    + "background: -o-linear-gradient(#f2f2f2, #e6e6e6);"
                    + "background: -moz-linear-gradient(#f2f2f2, #e6e6e6);"
                    + "background: linear-gradient(#f2f2f2, #e6e6e6);";
            //color = 'background-color:#ccc;color:#000000;';
            break;
        case 'Suspend Item':
            color = "background-color:#ffcce6;color:#5b2424;"
                    + "background: -webkit-linear-gradient(#ffe5f2, #ffcce6);"
                    + "background: -o-linear-gradient(#ffe5f2, #ffcce6);"
                    + "background: -moz-linear-gradient(#ffe5f2, #ffcce6);"
                    + "background: linear-gradient(#ffe5f2, #ffcce6);";
            //color = 'background-color:#f2dede;color:#000000;';
            break;
        case 'Cancel By Dir.':
            color = "background-color:#ffcce6;color:#5b2424;"
                    + "background: -webkit-linear-gradient(#ffe5f2, #ffcce6);"
                    + "background: -o-linear-gradient(#ffe5f2, #ffcce6);"
                    + "background: -moz-linear-gradient(#ffe5f2, #ffcce6);"
                    + "background: linear-gradient(#ffe5f2, #ffcce6);";
            //color = 'background-color:#f2dede;color:#000000;';
            break;
    }
    return color;
}

//====================EXPORT TO EXCEL ==============================================================//
function exportToExcel(htmls) {
    var uri = 'data:application/vnd.ms-excel;base64,';
    var template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>';
    var base64 = function (s) {
        return window.btoa(unescape(encodeURIComponent(s)))
    };

    var format = function (s, c) {
        return s.replace(/{(\w+)}/g, function (m, p) {
            return c[p];
        })
    };

    var ctx = {
        worksheet: 'Worksheet',
        table: htmls
    }
    var link = document.createElement("a");
    link.download = "export.xls";
    link.href = uri + base64(format(template, ctx));
    link.click();
}
//====================END EXPORT TO EXCEL ==============================================================//

//====ADDED DHIDHIK 26-11-2015 ========================//
function get_depreciate_method(status) {
    switch (status * 1) {
        case 0 :
            status = "Non Depreciable Method";
            break;
        case 1 :
            status = "Straight Line Method";
            break;
        case 2 :
            status = "Double Declining Method";
            break;
    }

    return status;
}

function get_status(status) {
    switch (status * 1) {
        case 0 :
            status = "Waiting For DP";
            break;
        case 1 :
            status = "On Progress";
            break;
        case 2 :
            status = "Finished";
            break;
        case 3 :
            status = "Suspended";
            break;
        case 4 :
            status = "Need App. Mgr.";
            break;
        case 5 :
            status = "Need App. Dir.";
            break;
        case 6 :
            status = "App. Dir & Mgr";
            break;
        case 7 :
            status = "App. Limit";
            break;
        case 8 :
            status = "Suspend Item";
            break;
        case 9 :
            status = "Cancel By Dir.";
            break;
    }

    return status;
}

function get_statusInvent(status) {
    switch (status) {
        case '0' :
            status = "Inventories";
            break;
        case '1' :
            status = "Sold";
            break;
        case '2' :
            status = "-";
            break;
        case '3' :
            status = "Return";
            break;
        case '4' :
            status = "Dispose";
            break;
    }
    return status;
}

function get_statusRankingAging(status) {
    switch (true) {
        case (status < 0) :
            status = "<div style='color:green;'>Very Good &nbsp;&nbsp;</div>";
            break;
        case (status >= 0) && (status <= 14) :
            status = "<div>Normal &nbsp;&nbsp;</div>";
            break;
        case (status >= 14) && (status <= 30) :
            status = "<div style='color:orange;'>Bad &nbsp;&nbsp;</div>";
            break;
        case (status > 30) :
            status = "<div style='color:red;'>Very Bad &nbsp;&nbsp;</div>";
            break;
        default :
            status = "<div>- &nbsp;&nbsp;</div>";
            break;

    }
    return status;
}

function dateSqlToIndo(txtDate) {
    var indoDate = "-";
    if (txtDate != null && txtDate != "" && txtDate != undefined) {
        var arDate = txtDate.split("-");
        indoDate = arDate[2] + "-" + arDate[1] + "-" + arDate[0];
    }
    return indoDate;
}

function dateSqlToYear(txtDate) {
    var indoDate = "-";
    if (txtDate != null && txtDate != "" && txtDate != undefined) {
        var arDate = txtDate.split("-");
        indoDate = arDate[0];
    }
    return indoDate;
}

function dateYMToYear(txtDate) {
    var indoDate = "-";
    if (txtDate != null && txtDate != "" && txtDate != undefined) {
        var arDate = txtDate.substr(0, 4);
        indoDate = arDate;
    }
    return indoDate;
}
function dateYMToString(txtDate) {
    var arMonth = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Des'];
    var indoDate = "-";
    if (txtDate != null && txtDate != "" && txtDate != undefined) {
        var vYear = txtDate.substr(0, 4);
        var vMonth = txtDate.substr(4, 2);
        var arDate = arMonth[vMonth] + " " + vYear;
        indoDate = arDate;
    }
    return indoDate;
}
function legendsTable(datas){
    var rstString = "";
    rstString += rstString+"<div style='clear:both;'></div>";
    rstString += '<div style="margin-left:' + datas['marginLeft'] + ';margin-bottom:15px; padding:10px;border:1px solid #CCC; display: inline-block; color:#666;">'
            + '<div style="-webkit-print-color-adjust:exact; color: #666; border-bottom: 1px #999 solid; font-weight: bold; margin-bottom: 7px; padding-bottom:5px;">Legends</div><div style="clear: both;"></div>';
    datas.datas.forEach(function (data) {
        rstString += '<div style=" margin-bottom:2px;"><div style="-webkit-print-color-adjust:exact; width: 10px;height:10px;border:1px #CCC solid; background-color: ' + data['boxColor'] + '; float: left; margin-right: 10px;">&nbsp;</div><div style="float: left;">' + data['strLabel'] + '</div><div style="clear: both;"></div></div>';
    });
    if (datas.dataDesc != undefined) {
        var noLoop = 1;
        datas.dataDesc.forEach(function (data) {
            if (noLoop == 1) {
                rstString += "<div style='border-bottom:1px dotted black;margin-bottom:15px;'> &nbsp; </div><u> <b> Desc <b> </u>";
            }
            rstString += '<div style=" margin-bottom:2px;">'
                        +'<div style="float: left; margin-right: 10px; width:70px;">' + data['strRange'] + '</div>'
                        +'<div style="float: left;">' + data['strDesc'] + '</div>'
                        + '<div style="clear: both;"></div>'
                        +'</div>';
            noLoop++;
        });
    }
    rstString += '</div>';
    return rstString;
}

//====END ADDED DHIDHIK 26-11-2015 ========================//

function grid_navigation(transaksi,menu_link) {
    //grid navigation
    $('#grid').datagrid('getPanel').panel('panel').attr('tabindex', 1).bind('keydown', function (e) {
        switch (e.keyCode) {
            case 38:	// up
                var selected = $('#grid').datagrid('getSelected');
                if (selected) {
                    var index = $('#grid').datagrid('getRowIndex', selected);
                    $('#grid').datagrid('selectRow', index - 1);
                } else {
                    $('#grid').datagrid('selectRow', 0);
                }
                break;
            case 40:	// down
                var selected = $('#grid').datagrid('getSelected');
                if (selected) {
                    var index = $('#grid').datagrid('getRowIndex', selected);
                    $('#grid').datagrid('selectRow', index + 1);
                } else {
                    $('#grid').datagrid('selectRow', 0);
                }
           		break;
			case 13:
				//if(transaksi == 'COA'){
					var selected = $('#grid').datagrid('getSelected');
					//alert(menu_link);
					if(transaksi == 'COA'){
						parent.tab_edit('Edit Account', menu_link, 'icon-edit', 'edit', selected.AccountNumber + '_' + selected.BranchCode + '_' + selected.BranchName);
					}
					else if(transaksi == 'History'){
						parent.tab_edit('Edit ' + selected.Source, selected.TransLink, 'icon-edit', 'edit', selected.SourceNo);
					}
					else if(transaksi == 'Balance'){
						parent.tab_edit('Edit Account', menu_link, 'icon-edit', 'edit', selected.AccountNumber + '_' + selected.BranchCode + '_' + selected.BranchName);
					}
					else if(transaksi == 'Import_Recur'){
						parent.tab_edit('Edit Purchase Invoice', 'list/purchases_invoice', 'icon-edit', 'edit', selected.NoTransaction);
					}
					//alert();
				//}
			break;
        }
    });
    //end grid navigation
}

function grid_navigation_in_edit() {
    //grid navigation
    $('#dtg_item').datagrid('getPanel').panel('panel').attr('tabindex', 1).bind('keydown', function (e) {
        switch (e.keyCode) {
            case 38:	// up
                var selected = $('#dtg_item').datagrid('getSelected');
                if (selected) {
                    var index = $('#dtg_item').datagrid('getRowIndex', selected);
                    $('#dtg_item').datagrid('selectRow', index - 1);
                } else {
                    $('#dtg_item').datagrid('selectRow', 0);
                }
                break;
            case 40:	// down
                var selected = $('#dtg_item').datagrid('getSelected');
                if (selected) {
                    var index = $('#dtg_item').datagrid('getRowIndex', selected);
                    $('#dtg_item').datagrid('selectRow', index + 1);
                } else {
                    $('#dtg_item').datagrid('selectRow', 0);
                }
                break;
        }
    });
    //end grid navigation
}


function save_button_endedit(SavePrivillage) {
    if (SavePrivillage == 1) {
        /*====================on beg in edit saat grid di klik maka tombol save disable===================*/
        $('.save-button').linkbutton('enable');
        /*=================================end============================================================*/
    }
}

function save_button_begendedit(SavePrivillage) {
    if (SavePrivillage == 1) {
        /*====================on beg in edit saat grid di klik maka tombol save disable===================*/
        $('.save-button').linkbutton('disable');
        /*=================================end============================================================*/
    }
}


/*================================ Daswan ====================================================*/

function reversed_data(location, url, id, action) {
    url = base_url + url;

	$.post(url + '/reversed_data', {id: id}, function (result) {
		if (result.status == true) {
			$.messager.alert('Berhasil', result.message, 'info', function () {
				if (location == 'L') { // If Suspend is triggered in Form
					$(action).datagrid('reload');
				}
				else if (location == 'F') { // If Suspend is triggered in List
					parent.tab_close('tt');
				}
			});
			modal_close('dlg_loading');
        }
        else if(result.status == 'session'){
            $.messager.alert('Unsuccessfull', result.message, 'info', function () {
                location.reload();
            });
		}
		else {
			$.messager.alert('Unsuccessfull', result.message, 'info');
			modal_close('dlg_loading');
		}
	}, 'json');
}
/*End of added by Daswan on 29/09/2015*/

/*Added by daswan on 29/09/2015*/
function approved_data(url, form_id) {
    url = base_url + url;

    $(form_id).form('submit', {
        url: url + '/approved_mgr',
        onSubmit: function () {
            var isValid = $(this).form('validate');
            if (!isValid) {
                return $(this).form('validate');
            } else {
                // modal_open('Progress Bar','dlg_loading');
            }
        },
        success: function (result) {
            var result = eval('(' + result + ')');

            if (result.status == true) {
                $.messager.alert('Success', result.message, 'info', function () {
                    location.reload();
                });
            }
            else if(result.status == 'session'){
                $.messager.alert('Unsuccessfull', result.message, 'info', function () {
                    location.reload();
                });
            }
            else {
                $.messager.alert('Unsuccessfull', result.message, 'info');
            }
            modal_close('dlg_loading');
      },
        statusCode: {
            404: function () {
                alert("Page Not Found");
            }
        }
    });
}
/*End of added by Daswan on 29/09/2015*/

/*Added by daswan on 29/09/2015*/
function approved_dir(url, form_id) {
    url = base_url + url;

    $(form_id).form('submit', {
        url: url + '/approved_dir',
        onSubmit: function () {
            var isValid = $(this).form('validate');
            if (!isValid) {
                return $(this).form('validate');
            } else {
                // modal_open('Progress Bar','dlg_loading');
            }
        },
        success: function (result) {
            var result = eval('(' + result + ')');

            if (result.status == true) {
                $.messager.alert('Success', result.message, 'info', function () {
                    location.reload();
                });
            }
            else if(result.status == 'session'){
                $.messager.alert('Unsuccessfull', result.message, 'info', function () {
                    location.reload();
                });
            }
            else {
                $.messager.alert('Unsuccessfull', result.message, 'info');
            }
            modal_close('dlg_loading');
      },
        statusCode: {
            404: function () {
                alert("Page Not Found");
            }
        }
    });
}
/*End of added by Daswan on 29/09/2015*/

function change_month_indonesia(month) {
    var arr_month = ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];
    return arr_month[month];
}

function findWithAttr(array, attr, value) {
    for (var i = 0; i < array.length; i += 1) {
        if (array[i][attr] === value) {
            return i;
        }
    }
}

function search_arr_object(array, val_arr) {
    var result = null;
    $.each(array, function (index, value) {
        $.each(value, function (ind, val) {
            switch (ind) {
                case 'PReqNumber':
                    if (val == val_arr) {
                        result = index;
                    }
                    break;
                case 'POrdNumber':
                    if (val == val_arr) {
                        result = index;
                    }
                    break;
                case 'PRecNumber':
                    if (val == val_arr) {
                        result = index;
                    }
                    break;
                case 'PPayNumber':
                    if (val == val_arr) {
                        result = index;
                    }
                    break;

            }
        })
    })

    return result;
}

function open_transaction(journal_number, type_journal) {

    if (type_journal == 'PRec') {
        link = 'list/receive_item/';
        title = 'Edit Receive Item';
    } else if (type_journal == 'PInv') {
        link = 'list/purchases_invoice/';
        title = 'Edit Purchase Invoice';
    } else if (type_journal == 'PRet') {
        link = 'list/purchases_return/';
        title = 'Edit Purchase Return';
    } else if (type_journal == 'PPay') {
        link = 'list/purchases_payment/';
        title = 'Edit Purchase Payment';
    } else if (type_journal == 'PPaj') {
        link = 'list/purchases_payment/';
        title = 'Edit Purchase Payment Journal';
    } else if (type_journal == 'DOrd') {
        link = 'list/delivery_order/';
        title = 'Edit Delivery Order';
    } else if (type_journal == 'SInv') {
        link = 'list/sales_invoice/';
        title = 'Edit Sales Invoice';
    } else if (type_journal == 'SRet') {
        link = 'list/sales_return/';
        title = 'Edit Sales Return';
    } else if (type_journal == 'SRec') {
        link = 'list/sales_receipt/';
        title = 'Edit Sales Receipt';
    } else if (type_journal == 'SRej') {
        link = 'list/sales_receipt/';
        title = 'Edit Sales Receipt';
    } else if (type_journal == 'CPay') {
        link = 'list/payment/';
        title = 'Edit Payment';
    } else if (type_journal == 'CDep') {
        link = 'list/deposit/';
        title = 'Edit Deposit';
    } else if (type_journal == 'BSweep') {
        link = 'list/swift_bank/';
        title = 'Edit Sweep Bank';
    } else if (type_journal == 'ADebt') {
        link = 'list/piutang_afiliasi/';
        title = 'Edit Piutang Afiliasi';
    } else if (type_journal == 'AIns') {
        link = 'list/payment_afiliasi/';
        title = 'Edit Payment Afiliasi';
    } else if (type_journal == 'AInj') {
        link = 'list/payment_afiliasi_journal/';
        title = 'Edit Payment Afiliasi Journal';
    } else if (type_journal == 'EDebt') {
        link = 'list/piutang_karyawan/';
        title = 'Edit Piutang Karyawan';
    } else if (type_journal == 'EIns') {
        link = 'list/payment_karyawan/';
        title = 'Edit Payment Karyawan';
    } else if (type_journal == 'EInj') {
        link = 'list/payment_karyawan_journal/';
        title = 'Edit Payment Karyawan Journal';
    } else if (type_journal == 'IBank') {
        link = 'list/ibank_transfer/';
        title = 'Edit Ibank Transfer';
    } else if (type_journal == 'OInc') {
        link = 'list/other_income/';
        title = 'Edit Other Income';
    } else if (type_journal == 'OPay') {
        link = 'list/other_payment/';
        title = 'Edit Other Payment';
    } else if (type_journal == 'TCash') {
        link = 'list/transaksi_antar_kas/';
        title = 'Edit Transfer To Petty Cash';
    } else if (type_journal == 'EBon') {
        link = 'list/purchases_expense_cashbon';
        title = 'Edit Expense Cash-BOn';
    } else if (type_journal == 'EPReal') {
        link = 'list/purchases_expense_real';
        title = 'Edit Expense Payment';
    } else if (type_journal == 'FDis') {
        link = 'list/fixed_asset_dispose';
        title = 'Edit Dispose Fixed Asset';
    } else if (type_journal == 'FSis') {
        link = 'list/fixed_asset_selling';
        title = 'Edit Selling Fixed Asset';
    } else if (type_journal == 'LJay') {
        link = 'list/loan_payment_journal';
        title = 'Edit Loan Payment Journal';
    } else if (type_journal == 'LPay') {
        link = 'list/loan_payment';
        title = 'Edit Loan Payment';
    } else if (type_journal == 'LFun') {
        link = 'list/loan_funding';
        title = 'Edit Loan Funding';
    }


    parent.tab_edit(title, link, 'icon-edit', 'edit', journal_number);

}

//Daswan Untuk Show Hide Field - field print
function ShowHide(element) {
    if ($("#" + element).is(":checked") == true) {
        $("." + element).show();
    } else {
        $("." + element).hide();
    }
}

function get_bank_balance(AccountNumber, CurrencyCode) {
    var url = base_url + 'custom/custom/get_bank_balance';
    $.ajax({
        type: "POST",
        dataType: "JSON",
        url: url,
        data: $.param({AccountNumber: AccountNumber}),
        success: function (data) {
            $('#txt_bank_balance').numberbox('setValue', data.value);
            $('.bank_balance_currency').html(CurrencyCode);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            if (jqXHR.status == 500) {
                alert('Internal error: ' + jqXHR.responseText);
            } else {
                alert('Unexpected error.');
            }
        }
    });
}

function get_master_rate(CurrencyCode) {
    var url = base_url + 'custom/custom/get_master_rate';
    $.ajax({
        type: "POST",
        dataType: "JSON",
        url: url,
        data: $.param({CurrencyCode: CurrencyCode}),
        success: function (data) {
            $('#txt_rate').numberbox('setValue', data.value);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            if (jqXHR.status == 500) {
                alert('Internal error: ' + jqXHR.responseText);
            } else {
                alert('Unexpected error.');
            }
        }
    });
}

function get_master_rate_on_grid(CurrencyCode,myCallback) {
    var url = base_url + 'custom/custom/get_master_rate';
    $.ajax({
        type: "POST",
        dataType: "JSON",
        url: url,
        data: $.param({CurrencyCode: CurrencyCode}),
        success: function (data) {
            myCallback(data);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            if (jqXHR.status == 500) {
                alert('Internal error: ' + jqXHR.responseText);
            } else {
                alert('Unexpected error.');
            }
        }
    });
}

function checking_payment_save(no_piutang, period, type_trans, myCallback) {
    var url = base_url + 'custom/custom/checking_payment_save';
    $.ajax({
        type: "POST",
        dataType: "JSON",
        url: url,
        data: $.param({no_piutang: no_piutang, period_to: period, type_trans: type_trans}),
        success: function (data) {
            myCallback(data);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            if (jqXHR.status == 500) {
                alert('Internal error: ' + jqXHR.responseText);
            } else {
                alert('Unexpected error.');
            }
        }
    });
}

function checking_approval(no_transaksi, myCallback) {
    modal_open('Progress Bar', 'dlg_loading');
    var url = base_url + 'custom/custom/checking_approval';
    $.ajax({
        type: "POST",
        dataType: "JSON",
        url: url,
        data: $.param({no_transaksi: no_transaksi}),
        success: function (data) {
            myCallback(data);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            if (jqXHR.status == 500) {
                alert('Internal error: ' + jqXHR.responseText);
            } else {
                alert('Unexpected error.');
            }
        }
    });
}

function checking_suspend(no_transaksi, myCallback) {
    var url = base_url + 'custom/custom/checking_suspend';
    $.ajax({
        type: "POST",
        dataType: "JSON",
        url: url,
        data: $.param({no_transaksi: no_transaksi}),
        success: function (data) {
            myCallback(data);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            if (jqXHR.status == 500) {
                alert('Internal error: ' + jqXHR.responseText);
            } else {
                alert('Unexpected error.');
            }
        }
    });
}

function checking_reverse(no_transaksi, myCallback) {
    $.messager.confirm('Confirm', 'Anda Yakin Akan Membatalkan Transaksi ?', function (r) {
		if (r) {
			modal_open('Progress Bar', 'dlg_loading');
			var url = base_url + 'custom/custom/checking_reverse';
			$.ajax({
				type: "POST",
				dataType: "JSON",
				url: url,
				data: $.param({no_transaksi: no_transaksi}),
				success: function (data) {
					myCallback(data);
				}, error: function (jqXHR, textStatus, errorThrown) {
					if (jqXHR.status == 500) {
						alert('Internal error: ' + jqXHR.responseText);
					} else {
						alert('Unexpected error.');
					}
				}
			});
		}
	});
}

function checking_update(no_transaksi, status, myCallback) {
    var url = base_url + 'custom/custom/checking_update';
    $.ajax({
        type: "POST",
        dataType: "JSON",
        url: url,
        data: $.param({no_transaksi: no_transaksi, status: status}),
        success: function (data) {
            myCallback(data);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            if (jqXHR.status == 500) {
                alert('Internal error: ' + jqXHR.responseText);
            } else {
                alert('Unexpected error.');
            }
        }
    });
}

function checking_payment(no_transaksi, type_trans, myCallback) {
    var url = base_url + 'custom/custom/checking_payment';
    $.ajax({
        type: "POST",
        dataType: "JSON",
        url: url,
        data: $.param({no_transaksi: no_transaksi, type_trans: type_trans}),
        success: function (data) {
            myCallback(data);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            if (jqXHR.status == 500) {
                alert('Internal error: ' + jqXHR.responseText);
            } else {
                alert('Unexpected error.');
            }
        }
    });
}

function get_data_session(myCallback) {
    var url = base_url + 'custom/custom/get_data_session';
    $.ajax({
        type: "POST",
        dataType: "JSON",
        url: url,
        success: function (data) {
            myCallback(data);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            if (jqXHR.status == 500) {
                alert('Internal error: ' + jqXHR.responseText);
            } else {
                alert('Unexpected error.');
            }
        }
    });
}

function css_print() {
//  var css ="<style type='text/css'>"
//  		+".header{width:100%;padding: 0px;border-spacing: 0px;margin-bottom: 3px;margin-top: 0px;font-size: 8pt; line-height:7px}"
//  		+"#list-print-container{background: #ffffff;width: 100%;height: auto;max-height: 450px;margin: 0 auto;padding: 20px 20px 50px 20px;overflow: auto;border:3px inset black;}"
//		+".list-header{width: 100%;padding: 0;border-spacing: 0;margin-bottom: 5px;margin-top: 0;}"
//		+".company-name{font-weight: bold;font-size: 12pt;}"
//		+".branch-name{font-weight: bold;font-size: 12pt;}"
//		+".list-title{font-weight: bold;font-size: 10pt;color: #8B0000;}"
//		+".list-header-top > td{border-bottom:3px solid black;color: #191970;font-size: 8pt;font-weight: bold;}"
//		+".list-header-middle > td{font-size: 7pt;font-weight: 400px;}"
//		+".list-header-bottom > td {font-weight: bold;font-size: 8pt;}"
//  		+".head-left{width: 55%;text-align: left;vertical-align: top;}"
//  		+".head-left-bottom-1{width: 25%;text-align: left;vertical-align: top;font-size: 7pt;}"
//  		+".head-left-bottom-2{width: 30%;text-align: left;vertical-align: top;font-size: 7pt;}"
//  		+".head-left-bottom{width: 55%;text-align: left;vertical-align: top;font-size: 7pt;}"
//		+".head-right {width: 45%;line-height: 10px;text-align: center;vertical-align: middle;}"
//		+".head-right > h2{font-size:9pt;display:inline}"
//		+".head-right-bottom{width:25%;font-size:7pt;}"
//		+".content{width:100%;padding: 0px;border-spacing: 0px;margin-top: 0px;}"
//		+".content-top{font-size: 8pt;}"
//		+".th-desc{width: 20%;text-align: left;}"
//		+".th-amount{width: 20%;}"
//		+".content-middle{font-size: 7pt;line-height:6px}"
//		+".content-bottom{}"
//		+".content-bottom-desc{vertical-align: top;text-align: left;font-size:7pt}"
//		+".content-bottom-amount{vertical-align:top;}"
//		+".content-bottom-amount > table{width: 100%;line-height:6px}"
//		+".content-bottom-amount-label{text-align: left;font-size: 7pt;}"
//		+".content-bottom-amount-value{text-align: right;font-size: 7pt;}"
//		+".footer{width:100%;padding: 0px;border-spacing: 0px;}"
//		+".footer-paraf{width: 15%;font-size: 8pt;text-align: center;}"
//		+".footer-status{width: 30%;font-size: 10pt;text-align:center;vertical-align:middle;color:red}"
//		+".footer-bottom{}"
//		+".footer-bottom > td > table{width: 100%;}"
//		+".footer-bottom-all{width: 100%;text-align: right;font-size:7pt;}"
//		+".footer-bottom-left{width: 15%;text-align: center;}"
//		+".footer-bottom-center{width: 70%;text-align: center;font-size: 7pt}"
//		+".footer-bottom-right{width: 15%;text-align: center;font-size: 7pt}"
//  		+".bdr-right{border-right:1px solid black;}"
//		+".bdr-left{border-left:1px solid black;}"
//		+".bdr-top{border-top:1px solid black;}"
//		+".bdr-bottom{border-bottom:1px solid black;}"
//		+".text-top{vertical-align: top;}"
//		+".text-bottom{vertical-align: bottom;}"
//		+".text-left{text-align: left;}"
//		+".text-right{text-align: right;}"
//		+".text-center{text-align: center;}"
//		+".text-middle{vertical-align: middle;}"
//		+".text-underline{text-decoration: underline;}"
//		+".span_block{display: block;}"
//  		+"</style>";
    var css = "<style>"
            + "body{background: #cccccc;}"
            //======== Tambahan Dhidhik, 22 April 2016 ===========================//
            + ".padding3px{padding : 3px ;}"
            + ".header tr td, .content tr td,"
            + ".header tr th, .content tr th{padding : 3px ;}//klo nilai padding ini dirubah, rubah juga padding di .span_block"
            + ".header tr th, .content tr th{text-align: center;}"
            + ".clear-float{clear: both;}"
            + ".footer-top{"
            + "    margin-bottom: 7px;"
            + "}"
            // + ".content-bottom td{"
            // + "   line-height: 8px;"
            // + "}"
            + "//======== End Tambahan Dhidhik, 22 April 2016 ===========================//"
            + "#limit-container{"
            + "	width: 100%;"
            + "	margin-bottom: 50px;"
            + "}"
            + "#print-container{"
            + "	background: #ffffff;"
            + "	width: 90%;"
            + "	height: auto;"
            + "	max-height: 450px;"
            + "	margin: 0 auto;"
            + "	padding: 20px 20px 50px 20px;"
            + "	overflow: auto;"
            + "	border:3px inset black;"
            + "}"
             + "#print-container-pp{"
            + " background: #ffffff;"
            + " width: 90%;"
            + " height: auto;"
            + " max-height: 500px;"
            + " margin: 0 auto;"
            + " padding: 20px 20px 50px 20px;"
            + " overflow: auto;"
            + " border:3px inset black;"
            + "}"
            + "#list-print-container{"
            + "	background: #ffffff;"
            + "	width: 90%;"
            + "	height: auto;"
            + "	max-height: 450px;"
            + "	margin: 0 auto;"
            + "	padding: 20px 20px 50px 20px;"
            + "	overflow: auto;"
            + "	border:3px inset black;"
            + "}"
            + "#list-print-container-small{"
            + "	background: #ffffff;"
            + "	width: 60%;"
            + "	height: auto;"
            + "	max-height: 450px;"
            + "	margin: 0 auto;"
            + "	padding: 20px 20px 50px 20px;"
            + "	overflow: auto;"
            + "	border:3px inset black;"
            + "}"
            + ".list-header{"
            + "	width: 100%;"
            + "	padding: 0;"
            + "	border-spacing: 0;"
            + "	margin-bottom: 5px;"
            + "	margin-top: 0;"
            + "}"
            + ".company-name{"
            + "	font-weight: bold;"
            + "	font-size: 14pt;"
            + "}"
            + ".branch-name{"
            + "	font-weight: bold;"
            + "	font-size: 14pt;"
            + "}"
            + ".list-title{"
            + "	font-weight: bold;"
            + "	font-size: 12pt;"
            + "	color: #8B0000;"
            + "}"
            + ".list-header-top > td{"
            + "	border-bottom:3px solid black;"
            + "	color: #191970;"
            + "	font-size: 10pt;"
            + "	font-weight: bold;"
            + "}"
            + ".list-header-middle > td{"
            + "	font-size: 7pt;"
            + "	font-weight: 400px;"
            + "}"
            + ".list-header-bottom > td {"
            + "	font-weight: bold;"
            + "	font-size: 12pt;"
            + "}"
            + ".header{"
            + "	width:100%;"
            + "	padding: 0px;"
            + "	border-spacing: 0px;"
            + "	margin-bottom: 5px;"
            + "	margin-top: 0px;"
            + "	font-size: 10pt;"
            + "}"
            +".header-pp{"
            +" width:100%;"
            +" padding: 0px;"
            +" border-spacing: 0px;"
            +" margin-bottom: 5px;"
            +" margin-top: 0px;"
            +" font-size: 10pt;"
            +" }"
            + ".header tr td{"
            + " line-height:8px"
            + "}"
            + ".head-left{"
            + "	width: 50%;"
            + "	text-align: left;"
            + "	vertical-align: top"
            + "}"
             + ".head-left > span{"
            + " font-size:12px;"
            + "}"
            + ".head-left-bottom{"
            + "	width: 50%;"
            + "	text-align: left;"
            + "	vertical-align: top;"
            + "	font-size: 10px;"
            + "}"
            + ".head-left-bottom-1{"
            + "	width: 25%;"
            + "	text-align: left;"
            + "	vertical-align: top;"
            + "	font-size: 8pt;"
            + "}"
             + ".head-left-bottom-2{"
            + " width: 30%;"
            + " text-align: left;"
            + " vertical-align: top;"
            + " font-size: 8pt;"
            + "}"
            + ".head-left-bottom-1 >span{"
            + " line-height:8px;"
            + "}"
            + ".head-left-bottom-2 >span{"
            + " line-height:8px;"
            + "}"
            + ".head-left-bottom-1 >p{"
            + " line-height:8px;"
            + "}"
            + ".head-left-bottom-2 >p{"
            + " line-height:8px;"
            + "}"
            + ".head-right {"
            + "	width: 50%;"
            + "	font-size: 14pt;"
            // + "	line-height: 15px;"
            + "	text-align: center;"
            + "	vertical-align: middle;"
            + "}"
            + ".head-right > h2{"
            + "	display: inline; font-size:15px;"
            + "}"
            + ".head-right-bottom{"
            + "	width:25%;"
            + "	font-size: 8pt;"
            + " text-align:top;"
            + "}"
            + ".head-right-bottom  table tr td{"
            + "	width:25%;"
            + "	font-size: 8pt; vertical-align: top;"
            + "}"
            + " .head-right-bottom > p{"
            + " line-height:3px;"
            + "}"
            + ".content{"
            + "	width:100%;"
            + "	//padding: 0px;"
            + "	border-spacing: 0px;"
            + "}"
            +" .content-pp{"
            +" width:100%;"
            +" padding: 0px;"
            +" border-spacing: 0px;"
            +"}"
            + ".content-top{"
            + "	font-size: 8pt; text-align: center;"
            + "}"
            + ".content-top > th{"
            + " line-height:8px"
            + "}"
            + ".item-group {"
            + " font-weight:bold;"
            + "}"
            + ".content-middle{"
            + "	font-size: 7pt;"
            + " vertical-align: top;"
            + "}"
            + ".content-middle td{"
            + " line-height:5px"
            + "}"
            + ".content-middle-purchase{"
            + " font-size: 8pt;"
            + " vertical-align: top;"
            + "}"
            + ".content-middle > td:nth-child(1){"
            + " border-right:1px solid black;"
            + " }"
            + ".content-middle > td:nth-child(2){"
            + " border-right:1px solid black;"
            + "}"
            + ".content-middle > td:nth-child(3){"
            + " border-right:1px solid black;"
            + "}"
            + ".content-middle > td:nth-child(4){"
            + "border-right:1px solid black;"
            + "}"
            + ".content-middle > td:nth-child(5){"
            + "border-right:1px solid black;"
            + "}"
            + ".content-middle > td:nth-child(6){"
            + "border-right:1px solid black;"
            + "}"
            + ".content-middle > td:nth-child(7){"
            + "border-right:1px solid black;"
            + "}"
            + ".content-middle > td:nth-child(8){"
            + "border-right:1px solid black;"
            + "}"
            + ".content-middle > td:nth-child(9){"
            + "border-right:1px solid black;"
            + "}"
            + ".content-middle > td:nth-child(10){"
            + "border-right:1px solid black;"
            + "}"
            + ".content-middle > td:nth-child(11){"
            + ".border-right:1px solid black;"
            + "}"
            + ".content-middle > td:nth-child(12){"
            + "border-right:1px solid black;"
            + "}"
            + ".content-middle > td:nth-child(13){"
            + "border-right:1px solid black;"
            + "}"
            + ".content-middle > td:nth-child(14){"
            + "border-right:1px solid black;"
            + "}"
            + ".content-middle > td:nth-child(15){"
            + ".border-right:1px solid black;"
            + "}"
            + ".content-middle > td:nth-child(16){"
            + "border-right:1px solid black;"
            + "}"
            + ".content-middle-purchase td{"
            + " line-height:5px"
            + "}"
            + ".no-item{"
            + " height:12px"
            + "}"
            + ".content-bottom{"
            + "	font-size: 8pt;"
            + "}"
            + ".content-bottom-desc{"
            + "	vertical-align: top;"
            + "	text-align: left;"
            + "	font-size: 8pt;"
            + " line-height: 8px;"
            + "}"
             + ".content-bottom-desc-purchase{"
            + " vertical-align: top;"
            + " text-align: left;"
            + " font-size: 8pt;"
            + " line-height: 8px;"
            + "}"
            + ".content-bottom-amount{"
            + "	vertical-align: top;"
            + "}"
            + ".content-bottom-amount > table{"
            + "	width: 100%;"
            + "	line-height: 8px;"
            + "}"
            + ".content-bottom-amount-label{"
            + "	text-align: left;"
            + "	font-size: 8pt;"
            + "}"
            + ".content-bottom-amount-value{"
            + "	text-align: right;"
            + "	font-size: 8pt;"
            + "}"
            + ".margin-page{"
            + " width:100%;"
            + " border-spacing: 0px;"
            + " margin-top: 5px;"
            + " margin-bottom: 180px;"
            + "}"
            + ".footer{"
            + "	width:100%;"
            + "	border-spacing: 0px;"
            + " margin-top: 5px;"
            + "}"
            + ".footer-paraf{"
            + "	width: 15%;"
            + "	font-size: 10pt;"
            + "	text-align: center;"
            + "}"
            + ".footer-status{"
            + "	width: 30%;"
            + "	font-size: 10pt;"
            + "	text-align: center;"
            + "	vertical-align: top;"
            + "	color: red;"
            + "       float: right;"
            + "        margin-left: 15px;"
            + "}"
            + ".footer-bottom{"
            + "	font-size: 10pt;"
            + "}"
            + ".footer-bottom > td> table{"
            + "	width: 100%;"
            + "}"
            + ".footer-bottom-all{"
            + "	width: 100%;"
            + "	text-align: right;"
            + "	font-size: 7pt;"
            + "}"
            + ".footer-bottom-left{"
            + "	width: 15%;"
            + "	text-align: center;"
            + "}"
            + ".footer-bottom-center{"
            + "	width: 70%;"
            + "	text-align: center;"
            + "}"
            + ".footer-bottom-right{"
            + "	width: 15%;"
            + "	text-align: center;"
            + "}"
            + ".footer-paraf-div{"
            + "   display: inline-block;"
            + "    float: left !important;"
            + "    font-size: 9pt;"
            + "    text-align: center;"
            + "    margin-left: 15px;"
            + "}"
            + ".footer-paraf-name{"
            + "    font-weight: bold;"
            + "}"
            + ".footer-paraf-by{"
            + "    margin-bottom: 45px;"
            + "}"
            + ".footer-bottom{"
            + "    margin-top: 10px;"
            + "}"
            + ".footer-bottom-company{"
            + "    vertical-align: bottom;"
            + "    text-align: center;"
            + "    position: relative;"
            + "   font-size: 9pt;"
            + "}"
            + ".footer-bottom-page{"
            + "    position: relative;"
            + "    display: inline-block;"
            + "   float: right;"
            + "    vertical-align: bottom;"
            + "   font-size: 7pt;"
            + " }"
            + ".content-bottom table, .content-bottom table tr, .content-bottom table tr td{"
            + "   padding-bottom: 0px;"
            + "   padding-top: 1px;"
            + "}"
            + ".bdr-right{"
            + "	border-right:1px solid black;"
            + "}"
            + ".bdr-left{"
            + "	border-left:1px solid black;"
            + "}"
            + ".bdr-top{"
            + "	border-top:1px solid black;"
            + "}"
            + ".bdr-bottom{"
            + "	border-bottom:1px solid black;"
            + "}"
            + ".text-top{"
            + "	vertical-align: top;"
            + "}"
            + ".text-bottom{"
            + "	vertical-align: bottom;"
            + "}"
            + ".text-left{"
            + "	text-align: left;"
            + "}"
            + ".text-right{"
            + "	text-align: right;"
            + "}"
            + ".text-center{"
            + "	text-align: center;"
            + "}"
            + ".text-middle{"
            + "	vertical-align: middle;"
            + "}"
            + ".text-underline{"
            + "	text-decoration: underline;"
            + "}"
            // + " .small_bold{"
            // + " font-size:10px;"
            // + " font-weight:bold;"
            // + "}"
            // + " .normal_bold{"
            // + " font-size:10px;"
            // + " font-weight:bold;"
            // + "}"
            + ".th-desc{"
            + " width: 180px;"
            + " text-align: left;"
            + "}"
            + ".th-amount{"
            + " width: 150px;"
            + "}"
            + ".th-code{"
            + " width: 80px;"
            + "}"
            + ".th-name{"
            + " width: 150px;"
            + "}"
             + ".th-name-long{"
            + " width: 300px;"
            + "}"
            + ".th-number{"
            + " width: 150px;"
            + "}"
            + ".th-qty{"
            + " width: 50px;"
            + "}"
            + ".th-disc{"
            + " width: 50px;"
            + "}"
            + ".span_block{"
            + "	display: block;"
            + " padding: 3px ;"
            + "}"
            + ".lbl-a{"
            + " display:inline-block;"
            + " width:45px"
            + "}"
            + ".lbl-aright{"
            + " display:inline-block;"
            + " width:50px"
            + "}"
             + ".lbl-abon{"
            + " display:inline-block;"
            + " width:70px"
            + "}"
            + ".lbl-b{"
            + " display:inline-block;"
            + " width:5px;"
            + "}"
            + ".lbl-c{"
            + " display:inline-block;"
            + " width:125px;"
            + ".lbl-cright{"
            + " display:inline-block;"
            + " width:120px;"
            + "}"
            + "</style>";
    return css;
}

function css_print_lama(){
    var css = "<style>"
            +" #print_paper {"
            +" margin:2px;"
            +" width:725px;" 
            +" height:950px;" 
            +" border:0px solid;"
            +" }"
            +" hr {"
            +" border:1px dashed grey;"
            +" }"
            +" table{"
            +" border-collapse:collapse;"
            +" width:100%;"
            +"}"
            +" th {"
            +" border-left: 1px solid #a1a1a1;"
            +" border-right: 1px solid #a1a1a1;"
            +" border-top: 1px solid #a1a1a1;"
            +" border-bottom: 1px solid #a1a1a1;"
            +" }"
            +" tr.list {"
            +" border-bottom: 1px dashed grey;"
            +" }"
            +" tr.last {"
            +" border-bottom: 0px dashed grey;"
            +" }"
            +" td.list {"
            +" padding:2px;"
            +" border-left: 1px solid #a1a1a1;"
            +" border-right: 1px solid #a1a1a1;"
            +" }"
            +" td.last {"
            +" border-left: 1px solid #a1a1a1;"
            +" border-right: 1px solid #a1a1a1;"
            +" border-bottom: 1px solid #a1a1a1;"
            +" }"
            +" .div_company {"
            +" height:60px;"
            +" border: 1px solid #a1a1a1;"
            +" padding: 0 3px 0 3px;"
            +" text-wrap:none;"
            +" -webkit-border-radius: 5px;"
            +" -moz-border-radius: 5px;"
            +" border-radius: 5px;"
            +" }"
            +" .div_vendor {"
            +" border: 1px solid #a1a1a1;"
            +" padding: 0 3px 0 3px;"
            +" text-wrap:none;"
            +" -webkit-border-radius: 5px;"
            +" -moz-border-radius: 5px;"
            +" border-radius: 5px;"
            +" }"
            +" .div_kanan {"
            +" margin-top: 10px;"
            +" border: 1px solid #a1a1a1;"
            +" padding: 0 3px 0 3px;"
            +" text-wrap:none;"
            +" -webkit-border-radius: 5px;"
            +" -moz-border-radius: 5px;"
            +" border-radius: 5px;"
            +" }"
            +" .div_kanan .left {"
            +" border-right:1px dashed grey;"
            +" }"
            +" .div_kanan .right {"
            +" border-left:1px dashed grey;"
            +" }"
            +" .div_salesman {"
            +" height:50px;"
            +" margin-top: 10px;"
            +" border: 1px solid #a1a1a1;"
            +" padding: 0 3px 0 3px;"
            +" text-wrap:none;"
            +" -webkit-border-radius: 5px;"
            +" -moz-border-radius: 5px;"
            +" border-radius: 5px;"
            +" }"
            +" .div_subtotal {"
            +" height:50px;"
            +" margin-top: 10px;"
            +" border: 1px solid #a1a1a1;"
            +" padding: 0 3px 0 3px;"
            +" text-wrap:none;"
            +" -webkit-border-radius: 5px;"
            +" -moz-border-radius: 5px;"
            +" border-radius: 5px;"
            +" }"  
            +" .div_downpayment {"
            +" height:25px;"
            +" margin-top: 10px;"
            +" border: 1px solid #a1a1a1;"
            +" padding: 0 3px 0 3px;"
            +" text-wrap:none;"
            +" -webkit-border-radius: 5px;"
            +" -moz-border-radius: 5px;"
            +" border-radius: 5px;"
            +" }"
            +" fieldset {"
            +" margin-bottom:10px;"
            +" height:98px;"
            +" border: 1px solid #a1a1a1;"
            +" padding: 0 3px 0 3px;"
            +" text-wrap:none;"
            +" -webkit-border-radius: 5px;"
            +"-moz-border-radius: 5px;"
            +" border-radius: 5px;"
            +" }"
            +" .big {"
            +" font-size: 24px;"
            +" }"
            +" .big_bold {"
            +" font-size: 24px;"
            +" font-weight: bold;"
            +" }"
            +" .normal {"
            +" font-size: 10px;"
            +" }"
            +" .normal_bold {"
            +" font-size: 10px;"
            +" font-weight: bold;"
            +" }"
            +" .small {"
            +" font-size: 8px;"
            +" }"
            +" .small_bold {"
            +" font-size: 8px;"
            +" font-weight: bold;"
            +" }"
            +" .easyui-combobox td_input {"
            +" }"
            +" #print-container {"
            +" min-width:90%;"
            +" max-width:90%;"
            +" min-height:528px;"
            +" max-height:528px;"
            +" margin-top: 0px;"
            +" margin-left: 5px;"
            +" margin-right: 5px;"
            +" margin-bottom: 10px;"
            +" font-family: 'Times New Roman';"
            +" overflow: auto;"
            +" }"
            +" .form-header {"
            +" width: 99.5%;"
            +" }"
            +" .form-header-si {"
            +" width: 100%;"
            +" }"
            +" .form-header-si td{"
            +" line-height: 7px;"
            +" }"
            +" .customer-header {"
            +" width: 60%;"
            +" vertical-align: top;"
            +" }"
            +" .title-form {"
            +" width: 40%;"
            +" text-align: center;"
            +" vertical-align: top;"
            +" }"
            +" .title-form-si {"
            +" width: 40%;"
            +" text-align: center;"
            +" vertical-align: middle;"
            +" }"
            +" #title-form {"
            +" margin-top: 5px;"
            +" margin-bottom: 4px;"
            +" }"
            +" .shipping-sq {"
            +" text-align: left;"
            +" vertical-align: top;"
            +" width: 30%;"
            +" }"
            +" .shipping-dp {"
            +" text-align: left;"
            +" vertical-align: top;"
            +" width: 20%"
            +" }"
            +" .shipping-do {"
            +" text-align: left;"
            +" vertical-align: top;"
            +" width: 60%"
            +" }"
            +" .billing {"
            +" text-align: left;"
            +" vertical-align: top;"
            +" width: 30%;"
            +" }"
            +" .no-form {"
            +" text-align: left;"
            +" vertical-align: top;"
            +" width: 20%;"
            +" }"
            +" .description-sq {"
            +" width: 100%;"
            +" vertical-align: top;"
            +" text-align: left;"
            +" }"
            +" .description-so {"
            +" width: 70%;"
            +" vertical-align: top;"
            +" text-align: left;"
            +" }"
            +" .subtotal {"
            +" width: 50%;"
            +" text-align: right;"
            +" vertical-align: top;"
            +" }"
            +" .subtotal-si {"
            +" width: 50%;"
            +" text-align: right;"
            +" vertical-align: top;"
            +" }"
            +" .form-footer {"
            +" margin-top: -6px;"
            +" width: 100%;"
            +" }"
            +" .footer-paraf {"
            +" width: 10%;"
            +" text-align: center;"
            +" vertical-align: top;"
            +" }"
            +" .footer-paraf-customer {"
            +" width: 20%;"
            +" text-align: center;"
            +" vertical-align: center;"
            +" }"
            +" .footer-left {"
            +" width: 20%;"
            +" text-align: right;"
            +" vertical-align: top;"
            +" }"
            +" .footer-center {"
            +" width: 60%;"
            +" text-align: center;"
            +" vertical-align: top;"
            +" }"
            +" .footer-right {"
            +" width: 20%;"
            +" text-align: right;"
            +" vertical-align: top;"
            +" }"
            +" .span_block {"
            +" display: block;"
            +" margin-bottom: 3px;"
            +" }"
            +" .in_div {"
            +" padding:2px; "
            +" border: 1px solid black;"
            +" height: 100%;"
            +" }"
            +" .in_span{"
            +" height: 3px;"
            +" }"
            +" .tbl {"
            +" margin-bottom: 2px;"
            +" }"
            +" .tbl th {"
            +" border: 1px solid black;" 
            +" line-height: 8px;"
            +" text-align: center;"
            +" vertical-align: top;"
            +" }"
            +" .tbl-item {"
            +" width: 99.5%;"
            +" }"
            +" .tbl-item td {"
            +" line-height: 8px;"
            +" vertical-align: top;"
            +" }"
            +" .tbl-item-si td {"
            +" line-height: 6px;"
            +" vertical-align: top;"
            +" }"
            +" .item-no {"
            +" width: 20%;"
            +" }"
            +" .item-code {"
            +" width: 15%;"
            +" }"
            +" .item-unit {"
            +" width: 5%;"
            +" }"
            +" .item-date {"
            +" width: 8%"
            +" }"
            +" .item-qty {"
            +" width: 5%;"
            +" }"
            +" .item-disc {"
            +" width: 5%;"
            +" }"
            +" .item-desc {"
            +" width: 30%;"
            +" }"
            +" .item-price {"
            +" width: 10%;"
            +" }"
            +" .bdr-left {"
            +" border-left:1px solid black;"
            +" }"
            +" .bdr-right {"
            +" border-right:1px solid black;"
            +" }"
            +" .bdr-top {"
            +" border-top:1px solid black;"
            +" }"
            +" .bdr-bottom {"
            +" border-bottom:1px solid black;"
            +" }"
            +" .no_border {"
            +" border : 0px;"
            +" }"
            +" .no-bdr-bottom {"
            +" border-bottom: 0px;"
            +" }"
            +" .no-bdr-top {"
            +" border-top: 0px;"
            +" }"
            +" .no-bdr-left {"
            +" border-left: 0px;"
            +" }"
            +" .no-bdr-right {"
            +" border-right: 0px;"
            +" }"
            +" .text-left {"
            +" text-align: left;"
            +" }"
            +" .text-right {"
            +" text-align: right;"
            +" }"
            +" .text-center {"
            +" text-align: center;"
            +" }"
            +" .text-top {"
            +" vertical-align: top;"
            +" }"
            +" .text-bottom {"
            +" vertical-align: bottom;"
            +" }"
            +" .text-middle {"
            +" vertical-align: middle;"
            +" }"
            +" .text-underline {"
            +" text-decoration: underline;"
            +" }"
            +" .s4{"
            +" border-bottom: 3px solid black;"
            +" }"
            +" #list-print-container {"
            +" min-width:100%;"
            +" max-width:100%;"
            +" min-height:528px;"
            +" max-height:528px;"
            +" margin-top: 0px;"
            +" margin-left: 5px;"
            +" margin-right: 5px;"
            +" margin-bottom: 10px;"
            +" font-family: 'Times New Roman';"
            +" overflow: auto;"
            +" }"
            +" #journal-print-container {"
            +" min-width:80%;"
            +" max-width:80%;"
            +" min-height:528px;"
            +" max-height:528px;"
            +" margin-top: 0px;"
            +" margin-left: 5px;"
            +" margin-right: 5px;"
            +" margin-bottom: 10px;"
            +" font-family: 'Times New Roman';"
            +" overflow: auto;"
            +" }"
            +" .suspended{"
            +" color:red;"
            +" }"
            +"</style>";
    return css;
}

function suspend_transaction(type, menu_link, no_transaksi, id) {

    if (no_transaksi != '' || typeof no_transaksi != 'undefined') {
        checking_suspend(no_transaksi, function (check) {

            if (check.status == true) {
                if (id == '#grid') {
                    suspend_data_new('L', type, menu_link, no_transaksi, id);
                } else {
                    suspend_data_new('F', type, menu_link, no_transaksi, id);
                }
            } else {
                $.messager.alert('Unseccessfull', check.message, 'error', function () {
                    location.reload();
                });
            }
        });
    } else {
        $.messager.alert('Unseccessfull', 'Pleas, Choose data in grid.', 'warning');
    }
}

var arrayLables = {'button':
            [
                {'new':
                            [{'lable': '<u>N</u>ew'}, {'classKey': 'keyBtnNew'}]
                },
                {'edit':
                            [{'lable': 'Ed<u>i</u>t'}, {'classKey': 'keyBtnEdit'}]
                },
                {'delete':
                            [{'lable': 'De<u>l</u>ete'}, {'classKey': 'keyBtnDelete'}]
                },
                {'save':
                            [{'lable': '<u>S</u>ave'}, {'classKey': 'keyBtnSave'}]
                },
                {'search':
                            [{'lable': '<u>S</u>earch'}, {'classKey': 'keyBtnSearch'}]
                },
                {'reset':
                            [{'lable': 'Rese<u>t</u>'}, {'classKey': 'keyBtnReset'}]
                },
                {'refresh':
                            [{'lable': '<u>R</u>efresh'}, {'classKey': 'keyBtnRefresh'}]
                },
                {'ok':
                            [{'lable': 'O<u>k</u>'}, {'classKey': 'keyBtnOk'}]
                },
                {'cancel':
                            [{'lable': 'C<u>a</u>ncel'}, {'classKey': 'keyBtnCancel'}]
                },
                {'close':
                            [{'lable': '<u>C</u>lose'}, {'classKey': 'keyBtnClose'}]
                },
                {'preview':
                            [{'lable': 'Pre<u>v</u>iew'}, {'classKey': 'keyBtnPreview'}]
                },
                {'print':
                            [{'lable': '<u>P</u>rint'}, {'classKey': 'keyBtnPrint'}]
                },
                {'journal':
                            [{'lable': '<u>J</u>ournal'}, {'classKey': 'keyBtnJournal'}]
                },
                {'help':
                            [{'lable': '<u>H</u>elp'}, {'classKey': 'keyBtnHelp'}]
                },
                {'suspend':
                            [{'lable': 'Suspend'}, {'classKey': ''}]
                }
            ]
};

function list_master_datagrid(menu, menu_link, menu_label, status_privelage_edit, status_privelage_delete, status_privelage_add, label_approval) {
    var branch_status = '';
    var branch = '';
    var data_preview = [];
    get_data_session(function (check) {
        branch_status = check.status_branch;
        branch = check.branch;
    });

    /*=================================== setting datagrid view =================================*/
    $('#grid').datagrid({
        onLoadSuccess: function (data) {
            data_preview = data.rows;
        },
        onBeforeLoad: function (param) {
            if ((param.page == 1) && (param.rows == 150)) {
                return false;
            }
        },
        onDblClickRow: function (index, value) {
            if (status_privelage_edit == 1) {
                parent.tab_edit('Edit ' + menu_label, menu_link, 'icon-edit', 'edit', $('#grid').datagrid('getSelected').TransNumber);
            }
        },
        onClickRow: function (index, value) {
            if (value.TransStatus == 'Suspended') {
                $('#suspend-linkbutton').linkbutton('disable');
            }
            else {
                if (status_privelage_delete == 1) {
                    $('#suspend-linkbutton').linkbutton('enable');
                }
                else {
                    $('#suspend-linkbutton').linkbutton('disable');
                }

                if (status_privelage_edit == 1) {
                    $('#edit-linkbutton').linkbutton('enable');
                }
                else {
                    $('#edit-linkbutton').linkbutton('disable');
                }
            }

        },
        rowStyler: function (index, row) {
            return status_datagrid(row.TransStatus);
        }
    });
    /*================================= end setting datagrid view ==================================*/

    /*=========================== function to top button master ==============================*/

    var html_button_top = '<a href="#" class="easyui-linkbutton ' + arrayLables.button[0].new[1].classKey + '" id="new-linkbutton">' + arrayLables.button[0].new[0].lable + '</a>';
    html_button_top += '<a href="#" class="easyui-linkbutton ' + arrayLables.button[1].edit[1].classKey + '" id="edit-linkbutton">' + arrayLables.button[1].edit[0].lable + '</a>';
    html_button_top += '<a href="#" class="easyui-linkbutton" id="suspend-linkbutton">Suspend</a>';

    html_button_top += '<a href="#" class="easyui-linkbutton ' + arrayLables.button[6].refresh[1].classKey + '" id="refresh-linkbutton">' + arrayLables.button[6].refresh[0].lable + '</a>';
    html_button_top += '<a href="#" class="easyui-linkbutton ' + arrayLables.button[10].preview[1].classKey + '" id="preview-linkbutton">' + arrayLables.button[10].preview[0].lable + '</a>';

    $('#button-top').append(html_button_top);

    /*======================= initializ button new ===============================*/


    if (status_privelage_add == 1) {
        $('#new-linkbutton').linkbutton({
            iconCls: 'icon-add',
            disabled: false,
            plain: true,
            onClick: function () {
                parent.tab_add('New ' + menu_label, menu_link, 'icon-add', 'add');
            }
        });
    } else {
        $('#new-linkbutton').linkbutton({
            iconCls: 'icon-add',
            disabled: true,
            plain: true,
            onClick: function () {
                parent.tab_add('New ' + menu_label, menu_link, 'icon-add', 'add');
            }
        });
    }


    /*======================= end initializ button new  ===============================*/

    /*======================= initializ button edit  ===============================*/

    if (status_privelage_edit == 1) {
        $('#edit-linkbutton').linkbutton({
            iconCls: 'icon-edit',
            disabled: false,
            plain: true,
            onClick: function () {
                parent.tab_edit('Edit ' + menu_label, menu_link, 'icon-edit', 'edit', $('#grid').datagrid('getSelected').TransNumber);
            }
        });
    } else {
        $('#edit-linkbutton').linkbutton({
            iconCls: 'icon-edit',
            disabled: true,
            plain: true,
            onClick: function () {
                parent.tab_edit('Edit ' + menu_label, menu_link, 'icon-edit', 'edit', $('#grid').datagrid('getSelected').TransNumber);
            }
        });
    }

    /*======================= end nitializ button edit ===============================*/

    /*======================= initializ button suspend  ===============================*/
    if (status_privelage_delete == 1) {
        $('#suspend-linkbutton').linkbutton({
            iconCls: 'icon-remove',
            disabled: false,
            plain: true,
            onClick: function () {
                suspend_data_new('L', 1, menu_link, $('#grid').datagrid('getSelected').TransNumber, '#grid');
            }
        });
    } else {
        $('#suspend-linkbutton').linkbutton({
            iconCls: 'icon-remove',
            disabled: true,
            plain: true,
            onClick: function () {
                suspend_data_new('L', 1, menu_link, $('#grid').datagrid('getSelected').TransNumber, '#grid');
            }
        });
    }
    /*===================================== end nitializ button suspend ===========================================*/

    /*==================================== initializ button refresh =============================================*/

    $('#refresh-linkbutton').linkbutton({
        iconCls: 'icon-reload',
        disabled: false,
        plain: true,
        onClick: function () {
            $('#grid').datagrid('reload');
        }
    });

    /*==================================== end initializ button refresh =============================================*/

    /*==================================== initializ button preview =============================================*/
//	$('#preview-linkbutton').linkbutton({
//    	iconCls:'icon-print',
//    	disabled:false,
//    	plain:true,
//    	onClick:function(){
//    		if(menu == 'vendor' || menu == 'customer'){
//    			parent.tab_add('Print '+menu_label,menu_link, 'icon-print', 'to_preview');
//    		}else{
//    			parent.tab_print_list('Print '+menu_label,menu_link, 'icon-edit', 'to_preview', $('#cmb_company').combobox('getValue'),$('#cmb_branch').combobox('getValue'));
//    		}
//    	}
//	});
//
//    $('#preview-linkbutton').linkbutton({
//        iconCls: 'icon-print',
//        disabled: false,
//        plain: true,
//        onClick: function () {
//            var item = $('#grid').datagrid('getRows');
//            var arr_string = '';
//            if (item.length > 0) {
//                var data_string = JSON.stringify(data_preview);
//                $.each(data_preview, function (ind, val) {
//                    var count_item = Object.keys(val).length - 1;
//                    var ind_arr = 0;
//                    $.each(val, function (index, value) {
//                        if (ind_arr < count_item) {
//                            arr_string += index + ':' + value + 'spasi';
//                        } else {
//                            arr_string += index + ':' + value + 'linebaru';
//                        }
//                        ind_arr++;
//                    });
//                });
//
//                arr_string = arr_string.replace(/\//g, "__");
//            }
//
////                parent.tab_add('Print '+menu_label,menu_link, 'icon-print', 'to_preview/'+arr_string);
//
//            if (menu == 'vendor' || menu == 'customer') {
//                parent.tab_add('Print ' + menu_label, menu_link, 'icon-print', 'to_preview/' + arr_string);
//            } else {
//                parent.tab_print_list('Print ' + menu_label, menu_link, 'icon-edit', 'to_preview/' + arr_string, $('#cmb_company').combobox('getValue'), $('#cmb_branch').combobox('getValue'));
//            }
//        }
//    });

    $('#preview-linkbutton').linkbutton({//dhidhik, 2 Mei 2016, untuk printview List
    	iconCls:'icon-print',
    	disabled:false,
    	plain:true,
    	onClick:function(){
            var arr_string = sendParamJson();
            parent.tab_add('Print '+menu_label,menu_link, 'icon-print', 'to_preview/'+arr_string);
    	}
    });
    /*==================================== end initializ button preview =============================================*/
    /*================================== end function top button master ==================================*/

    /*==================================== function transstatus master =====================================*/

    if (menu == 'ItemInven') {
        var html_transstatus = ''
                + '<tr><td colspan="2"><div class="tr-divider"></div></td></tr>'
                + '<tr>'
                + '<td height="38"><div style="float:right;">'
                + '<a href="#" class="easyui-linkbutton keyBtnReset ' + arrayLables.button[5].reset[1].classKey + '"  id="button_reset">' + arrayLables.button[5].reset[0].lable + '</a>'
                + '<a href="#" class="easyui-linkbutton keyBtnSearch ' + arrayLables.button[4].search[1].classKey + '" id="button_search">' + arrayLables.button[4].search[0].lable + '</a>'
                + '</div></td>'
                + '</tr>';

        $('#tab_transstatus').append(html_transstatus);

    } else {

        var html_transstatus = ''
                + '<tr>'
                + '<td>'
                + '<input onkeyup="enterCheckedTranstatus(event,' + "'chk_all'" + ')" type="checkbox" name="chk_all" style="margin-left:0px;" class="Chk chk_all" id="chk_all" value="0"/>'
                + '<span class="LblStatus" style="font-size:12px;font-weight:bold;font-family:arial;padding-top:3px">Check / (Un) Check All</span>'
                + '</td>'
                + '</tr>'
                + '<tr><td><div class="tr-divider"></div></td></tr>'
                + '<tr>'
                + '<td width="283" align="left" colspan="2">'
                + '<input onkeyup="enterCheckedTranstatus(event,' + "'chkActive'" + ')" type="checkbox" name="chk_TransStatus" value="1" style="margin-left:0px;" class="Chk chkActive" checked />'
                + '<span class="LblStatus LblActive">Active</span>'
                + '</td>'
                + '</tr>'
                + '<tr>'
                + '<td width="283" align="left" colspan="2">'
                + '<input onkeyup="enterCheckedTranstatus(event,' + "'chkSuspended'" + ')" type="checkbox" name="chk_TransStatus" value="3" style="margin-left:0px;" class="Chk chkSuspended"/>'
                + '<span class="LblStatus LblSuspended">Suspended</span>'
                + '</td>'
                + '</tr>'
                + '<tr>'
                + '<td width="283" align="left" colspan="2">'
                + '<input onkeyup="enterCheckedTranstatus(event,' + "'chkNAM'" + ')" type="checkbox" name="chk_TransStatus" value="4" style="margin-left:0px;"  class="Chk chkNAM"/>'
                + '<span class="LblStatus LblNAM">Need App. Mgr.</span>'
                + '</td>'
                + '</tr>'
                + '<tr>'
                + '<td width="283" align="left" colspan="2">'
                + '<input onkeyup="enterCheckedTranstatus(event,' + "'chkNAD'" + ')" type="checkbox" name="chk_TransStatus" value="5" style="margin-left:0px;"  class="Chk chkNAD"/>'
                + '<span class="LblStatus LblNAD">Need App. Dir.</span>'
                + '</td>'
                + '</tr>'
                + '<tr>'
                + '<td width="283" align="left" colspan="2">'
                + '<input onkeyup="enterCheckedTranstatus(event,' + "'chkNAD_M'" + ')" type="checkbox" name="chk_TransStatus" value="6" style="margin-left:0px;" class="Chk chkNAD_M"/>'
                + '<span class="LblStatus LblNAD_M">App. Dir &amp; Mgr</span>'
                + '</td>'
                + '</tr>'
                + '<tr><td colspan="2"><div class="tr-divider"></div></td></tr>'
                + '<tr>'
                + '<td height="38"><div style="float:right;">'
                + '<a href="#" class="easyui-linkbutton keyBtnReset ' + arrayLables.button[5].reset[1].classKey + '" id="button_reset">' + arrayLables.button[5].reset[0].lable + '</a>'
                + '<a href="#" class="easyui-linkbutton keyBtnSearch ' + arrayLables.button[4].search[1].classKey + '" id="button_search">' + arrayLables.button[4].search[0].lable + '</a>'
                + '</div></td>'
                + '</tr>';

        $('#tab_transstatus').append(html_transstatus);

        $('#chk_all').click(function () {
            if ($(this).val() == 0) {
                $(this).val(1);
                $('input[name="chk_TransStatus"]').prop('checked', true);
            } else {
                $(this).val(0);
                $('input[name="chk_TransStatus"]').prop('checked', false);
            }
        });
    }

    $('#button_reset').linkbutton({
        iconCls: 'icon-reload',
        onClick: function () {
            location.reload();
        }
    });

    $('#button_search').linkbutton({
        iconCls: 'icon-search',
        onClick: function () {
            searching_data();
        }
    });

    /*=========================== end function transstatus master =======================================*/
}

function list_datagrid(menu, label_approval, menu_link, menu_label, status_privelage_edit, status_privelage_delete, status_privelage_add, om) {

    var branch_status = '';
    var data_preview = [];

    get_data_session(function (check) {
        branch_status = check.status_branch;
    });
    /*=================================== setting datagrid view =================================*/
    $('#grid').datagrid({
        onBeforeLoad: function (param) {
            if ((param.page == 1) && (param.rows == 150)) {
                return false;
            }
        },
        onLoadSuccess: function (data) {
            data_preview = data.rows;
        },
        onDblClickRow: function () {
            if (menu == 'ADebt' || menu == 'AInj') {
                edit_transaction();
            } else {
                if (status_privelage_edit == 1) {
                    parent.tab_edit('Edit ' + menu_label, menu_link, 'icon-edit', 'edit', $('#grid').datagrid('getSelected').TransNumber);
                }
            }
        },
        onClickRow: function (index, value) {
            if (menu == 'SOrd') {
                if (value.TransStatus == "App. Limit") {
                    $('#suspend-linkbutton').linkbutton('enable');
                }
                else if (value.TransStatus != label_approval) {
                    $('#suspend-linkbutton').linkbutton('disable');
                } else {
                    if (status_privelage_delete == 1) {
                        $('#suspend-linkbutton').linkbutton('enable');
                    }
                    else {
                        $('#suspend-linkbutton').linkbutton('disable');
                    }

                    if (status_privelage_edit == 1) {
                        $('#edit-linkbutton').linkbutton('enable');
                    }
                    else {
                        $('#edit-linkbutton').linkbutton('disable');
                    }
                }
            }
            else {
                if (value.TransStatus != label_approval) {
                    $('#suspend-linkbutton').linkbutton('disable');
                } else {
                    if (status_privelage_delete == 1) {
                        $('#suspend-linkbutton').linkbutton('enable');
                    }
                    else {
                        $('#suspend-linkbutton').linkbutton('disable');
                    }

                    if (status_privelage_edit == 1) {
                        $('#edit-linkbutton').linkbutton('enable');
                    }
                    else {
                        $('#edit-linkbutton').linkbutton('disable');
                    }
                }
            }
        },
        rowStyler: function (index, row) {
            return status_datagrid(row.TransStatus);
        }
    });
    /*================================= end setting datagrid view ==================================*/

    /*========================= html button top ========================================*/
    var html_button_top = '<a href="#" class="easyui-linkbutton ' + arrayLables.button[0].new[1].classKey + '" id="new-linkbutton">' + arrayLables.button[0].new[0].lable + '</a>';
    html_button_top += '<a href="#" class="easyui-linkbutton ' + arrayLables.button[1].edit[1].classKey + '" id="edit-linkbutton">' + arrayLables.button[1].edit[0].lable + '</a>';
    /*html_button_top += '<a href="#" class="easyui-linkbutton" id="suspend-linkbutton">Suspend</a>';*/
    html_button_top += '<a href="#" class="easyui-linkbutton ' + arrayLables.button[6].refresh[1].classKey + '" id="refresh-linkbutton">' + arrayLables.button[6].refresh[0].lable + '</a>';
    html_button_top += '<a href="#" class="easyui-linkbutton ' + arrayLables.button[10].preview[1].classKey + '" id="preview-linkbutton">' + arrayLables.button[10].preview[0].lable + '</a>';

    $('#button-top').append(html_button_top);

    if (status_privelage_add == 1) {
        if (menu == 'IBank') {
            if (branch_status == 0) {
                $('#new-linkbutton').linkbutton({
                    iconCls: 'icon-add',
                    disabled: false,
                    plain: true,
                    onClick: function () {
                        parent.tab_add('New ' + menu_label, menu_link, 'icon-add', 'add');
                    }
                });
            } else {
                $('#new-linkbutton').linkbutton({
                    iconCls: 'icon-add',
                    disabled: true,
                    plain: true,
                    onClick: function () {
                        parent.tab_add('New ' + menu_label, menu_link, 'icon-add', 'add');
                    }
                });
            }
        } else {
            $('#new-linkbutton').linkbutton({
                iconCls: 'icon-add',
                disabled: false,
                plain: true,
                onClick: function () {
                    parent.tab_add('New ' + menu_label, menu_link, 'icon-add', 'add');
                }
            });
        }

    } else {
        $('#new-linkbutton').linkbutton({
            iconCls: 'icon-add',
            disabled: true,
            plain: true,
            onClick: function () {
                parent.tab_add('New ' + menu_label, menu_link, 'icon-add', 'add');
            }
        });
    }

    if (status_privelage_edit == 1) {
        $('#edit-linkbutton').linkbutton({
            iconCls: 'icon-edit',
            disabled: false,
            plain: true,
            onClick: function () {
                if(mustBeChooseRowDatagrid('grid')){
                    parent.tab_edit('Edit ' + menu_label, menu_link, 'icon-edit', 'edit', $('#grid').datagrid('getSelected').TransNumber);
                }
            }
        });
    } else {
        $('#edit-linkbutton').linkbutton({
            iconCls: 'icon-edit',
            disabled: true,
            plain: true,
            onClick: function () {
                if(mustBeChooseRowDatagrid('grid')){
                    parent.tab_edit('Edit ' + menu_label, menu_link, 'icon-edit', 'edit', $('#grid').datagrid('getSelected').TransNumber);
                }
            }
        });
    }

    if (status_privelage_delete == 1) {
        $('#suspend-linkbutton').linkbutton({
            iconCls: 'icon-remove',
            disabled: true,
            plain: true,
            onClick: function () {
                if ((typeof om) != 'undefined') {

                } else {
                    if ((menu == 'ADebt') || (menu == 'AIns') || (menu == 'AInj')) {
                        suspend(1);
                    } else {
                        suspend_transaction(1, menu_link, $('#grid').datagrid('getSelected').TransNumber, '#grid');
                    }
                }
            }
        });
    } else {
        $('#suspend-linkbutton').linkbutton({
            iconCls: 'icon-remove',
            disabled: true,
            plain: true,
            onClick: function () {
                suspend_transaction(1, menu_link, $('#grid').datagrid('getSelected').TransNumber, '#grid');
            }
        });
    }

    $('#refresh-linkbutton').linkbutton({
        iconCls: 'icon-reload',
        disabled: false,
        plain: true,
        onClick: function () {
            searching_data_transaksi();
        }
    });

//    $('#preview-linkbutton').linkbutton({
//        iconCls: 'icon-print',
//        disabled: false,
//        plain: true,
//        onClick: function () {
//            var item = $('#grid').datagrid('getRows');
//            var arr_string = '';
//            if (item.length > 0) {
//                var data_string = JSON.stringify(data_preview);
//                $.each(data_preview, function (ind, val) {
//                    var count_item = Object.keys(val).length - 1;
//                    var ind_arr = 0;
//                    $.each(val, function (index, value) {
//                        if (ind_arr < count_item) {
//                            arr_string += index + ':' + value + 'spasi';
//                        } else {
//                            arr_string += index + ':' + value + 'linebaru';
//                        }
//                        ind_arr++;
//                    });
//                });
//
//                arr_string = arr_string.replace(/\//g, "__");
//            }
//
//            parent.tab_add('Print ' + menu_label, menu_link, 'icon-print', 'to_preview/' + arr_string);
//        }
//    });
    
    $('#preview-linkbutton').linkbutton({//Dhidhik, 2 Mei 2016, printview List
        iconCls: 'icon-print',
        disabled: false,
        plain: true,
        onClick: function () {
            var arr_string = sendParamJson();
            parent.tab_add('Print '+menu_label,menu_link, 'icon-print', 'to_preview/'+arr_string);
        }
    });
    /*======================== end html button top ==========================================*/

    /*================================= Label TransStatus 	  ============================================*/

    var html_transstatus = '<tr>'
            + '<td style="padding-bottom:8px;">'
            + '<b>by Date</b>'
            + '<input type="checkbox" name="chk_ByDateNew" value="1" id="chk_ByDateNew" style="float:right;" />'
            + '</td>'
            + '</tr>'
            + '<tr>'
            + '<td>'
            + 'From'
            + '<span style="float:right;">'
            + '<input name="txt_DateFrom" id="txt_DateFrom" type="text" class="easyui-datebox " style="width:100px;height:22px;" editable="false" disabled />'
            + '</span>'
            + '</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>'
            + '<tr><td><div class="tr-divider"></div></td></tr>'
            + '<tr>'
            + '<td style="padding-bottom:8px;"><b>by Status</b></td>'
            + '</tr>'
            + '<tr>'
            + '<td>'
            + '<input onkeyup="enterCheckedTranstatus(event,' + "'chk_all'" + ')" type="checkbox" name="chk_all" style="margin-left:0px;" class="Chk chk_all" id="chk_all" value="0"/>'
            + '<span class="LblStatus" style="font-size:12px;font-weight:bold;font-family:arial;padding-top:3px">Check / (Un) Check All</span>'
            + '</td>'
            + '</tr>'
            + '<tr><td><div class="tr-divider"></div></td></tr>'
            + '<tr>'
            + '<td>'
            + '<input onkeyup="enterCheckedTranstatus(event,' + "'chkWaiting'" + ')" type="checkbox" name="chk_TransStatus" value="0" style="margin-left:0px;" class="Chk chkWaiting" checked/>'
            + '<span class="LblStatus LblWaiting">Waiting For DP</span>'
            + '</td>'
            + '</tr>'
            + '<tr>'
            + '<td>'
            + '<input onkeyup="enterCheckedTranstatus(event,' + "'chkOnProg'" + ')" type="checkbox" name="chk_TransStatus" value="1" style="margin-left:0px;" class="Chk chkOnProg" checked/>'
            + '<span class="LblStatus LblOnProg">On Progress</span>'
            + '</td>'
            + '</tr>'
            + '<tr>'
            + '<td>'
            + '<input onkeyup="enterCheckedTranstatus(event,' + "'chkFinished'" + ')" type="checkbox" name="chk_TransStatus" value="2" style="margin-left:0px;" class="Chk chkFinished"/>'
            + '<span class="LblStatus LblFinished">Finished</span>'
            + '</td>'
            + '</tr>'
            + '<tr>'
            + '<td>'
            + '<input onkeyup="enterCheckedTranstatus(event,' + "'chkSuspended'" + ')" type="checkbox" name="chk_TransStatus" value="3" style="margin-left:0px;" class="Chk chkSuspended"  />'
            + '<span class="LblStatus LblSuspended">Suspended</span>'
            + '</td>'
            + '</tr>'
            + '<tr>'
            + '<td>'
            + '<input onkeyup="enterCheckedTranstatus(event,' + "'chkNAM'" + ')" type="checkbox" name="chk_TransStatus" value="4" style="margin-left:0px;" class="Chk chkNAM" checked/>'
            + '<span class="LblStatus LblNAM">Need App. Mgr.</span>'
            + '</td>'
            + '</tr>'
            + '<tr>'
            + '<td>'
            + '<input onkeyup="enterCheckedTranstatus(event,' + "'chkNAD'" + ')" type="checkbox" name="chk_TransStatus" value="5" style="margin-left:0px;"  class="Chk chkNAD" checked/>'
            + '<span class="LblStatus LblNAD">Need App. Dir.</span>'
            + '</td>'
            + '</tr>'
            + '<tr>'
            + '<td>'
            + '<input onkeyup="enterCheckedTranstatus(event,' + "'chkNAD_M'" + ')" type="checkbox" name="chk_TransStatus" value="6" style="margin-left:0px;" class="Chk chkNAD_M" checked/>'
            + '<span class="LblStatus LblNAD_M">App. Dir &amp; Mgr</span>'
            + '</td>'
            + '</tr>'
            + '<tr>'
            + '<td>'
            + '<input onkeyup="enterCheckedTranstatus(event,' + "'chkNAL'" + ')" type="checkbox" name="chk_TransStatus" value="7" style="margin-left:0px;" class="Chk chkNAL" checked/>'
            + '<span class="LblStatus LblNAL">App. Limit</span>'
            + '</td>'
            + '</tr>'
            + '<tr>'
            + '<td>'
            + '<input onkeyup="enterCheckedTranstatus(event,' + "'chkSuspendItem'" + ')" type="checkbox" name="chk_TransStatus" value="8" style="margin-left:0px;"  class="Chk chkSuspendItem chkCancelDir" />'
            + '<span class="LblStatus LblCancelDir">Suspend Item</span>'
            + '</td>'
            + '</tr>'
            + '<tr>'
            + '<td>'
            + '<input onkeyup="enterCheckedTranstatus(event,' + "'chkCancelDir'" + ')" type="checkbox" name="chk_TransStatus" value="9" style="margin-left:0px;"  class="Chk chkCancelDir" />'
            + '<span class="LblStatus LblCancelDir">Cancel By Dir.</span>'
            + '</td>'
            + '</tr>'
            + '<tr>'
            + '<td height="38"><div style="float:right;">'
            + '<a href="#" class="easyui-linkbutton keyBtnReset ' + arrayLables.button[5].reset[1].classKey + '" id="button_reset" onClick="location.reload();" >' + arrayLables.button[5].reset[0].lable + '</a>'
            + '<a href="#" class="easyui-linkbutton keyBtnSearch ' + arrayLables.button[4].search[1].classKey + '" id="button_search" onClick="searching_data_transaksi();" >' + arrayLables.button[4].search[0].lable + '</a>'
            + '</div></td>'
            + '</tr>';

    $('#tab_transstatus').append(html_transstatus);

    $('#chk_all').click(function () {
        if ($(this).val() == 0) {
            $(this).val(1);
            $('input[name="chk_TransStatus"]').prop('checked', true);
        } else {
            $(this).val(0);
            $('input[name="chk_TransStatus"]').prop('checked', false);
        }
    });

    /*================================= end label TransStatus ============================================*/
    $('#button_reset').linkbutton({
        iconCls: 'icon-reload'
    });

    $('#button_search').linkbutton({
        iconCls: 'icon-search'
    });

    $('#txt_DateFrom').datebox();
    $('#txt_DateTo').datebox();

    /*======================= event click filter by date ===================================*/
    $('.filter_date').datebox({
        onSelect: function (date) {
            search_data();
        }
    });
    /*======================== en event ======================================*/

    /*===========================chk_ByDateNew jangan lupa ganti =============================*/
    var start_date = new Date();
    var date_full = '01-' + (start_date.getMonth() + 1) + '-' + start_date.getFullYear();

    $('#chk_ByDateNew').click(function () {
        if ($(this).is(':checked')) {
            $('#txt_DateFrom').datebox('enable', true);
            $('#txt_DateTo').datebox('enable', true);
            $('#txt_DateFrom').datebox('setValue', date_full);
            $('#txt_DateTo').datebox('setValue', 'today');
        }
        else {
            $('#txt_DateFrom').datebox('disable', true);
            $('#txt_DateTo').datebox('disable', true);
            $('#txt_DateFrom').datebox('setValue', '');
            $('#txt_DateTo').datebox('setValue', '');
        }

    });
    /*==================end=========================*/

}

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Function Clear ComboGrid <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<//
/* arrIDCombo di gunakan untuk menampung ID Combogrid sebelumnya */
$(document).ready(function () {
    legend_grid_itemtype();//untuk legend warna pada grid item (untuk purchase n sales)
    
    $(".combo-grid").combogrid().next().children(":text").blur(function () {
        var txtValue = $(this).val();
        var ortu = $(this).parent().prev();
        var combo_html = ortu[0];
        var combo_id = combo_html.id;
        clearComboGrid(txtValue, combo_id);
        save_button_endedit(SavePrivillage);
    }).focus(function () {
        save_button_begendedit(SavePrivillage);
    }).focusout(function () {

    });

    $('.over_report').on('mouseover',function(){
        $(this).css({'background-color':'hsla(0, 100%, 70%, 0.3)'});
    }).on('mouseout',function(){
        $(this).css({'background-color':'white'});
    });

});

var arrIDCombo = [];

function clearComboGrid(txtValue, idCombo) {

    /*===== countCMB digunakan untuk menghitung jumlah combogrid dalam page aktiv ===================*/
    /*===== valueCMB di gunakan untuk menampung setiap value combogrid dalam page aktiv, yang nantinya akan di compare dengan value combogrid aktiv =========*/
    /*===== idCombo digunakan untuk menampung nama id combogrid aktiv =====*/
    /*===== indCombo digunakan untuk menampung ind combogrid yang akan dikenakan action clear */
    /*===== Vdata digunakan untuk menampung list value combogird */

    var valueCMB = '';

    if (txtValue != '') {

        if (idCombo != '') {

            var cmbgrid = $('#' + idCombo).combogrid('grid').datagrid('getData');
            var Vdata = cmbgrid.rows;
            arrIDCombo.push(idCombo);

            if (Vdata.length > 0) {

                // if((idCombo == 'cmb_tocompany') || (idCombo == 'cmb_fromcompany')){
                // 	/*=============== fungsi untuk compare value yang di input ada tidak di list value combogird =================*/
                // 	var indexes1 	= $.map(Vdata, function(obj, index){
                // 		if(obj.CompanyName == txtValue) {
                // 			return index;
                // 		}
                // 	});

                // 	var indexes2 	= $.map(Vdata, function(obj, index){
                // 		if(obj.CompanyCode == txtValue) {
                // 			return index;
                // 		}
                // 	});
                // 	/*====================== end fungsi =========================================*/
                // }else if((idCombo == 'cmb_karyawan') || (idCombo == 'cmb_salesman')){
                // 	/*=============== fungsi untuk compare value yang di input ada tidak di list value combogird =================*/
                // 	var indexes1 	= $.map(Vdata, function(obj, index) {
                // 		if(obj.EmployeeCode == txtValue) {
                // 			return index;
                // 		}
                // 	});

                // 	var indexes2 	= $.map(Vdata, function(obj, index) {
                // 		if(obj.EmployeeName == txtValue) {
                // 			return index;
                // 		}
                // 	});
                // 	====================== end fungsi =========================================
                // }else if(idCombo == 'cmb_customer'){
                // 	/*=============== fungsi untuk compare value yang di input ada tidak di list value combogird =================*/
                // 	var indexes1 	= $.map(Vdata, function(obj, index) {
                // 		if(obj.CustomerCode == txtValue) {
                // 			return index;
                // 		}
                // 	});

                // 	var indexes2 	= $.map(Vdata, function(obj, index) {
                // 		if(obj.CustomerName == txtValue) {
                // 			return index;
                // 		}
                // 	});
                // 	/*====================== end fungsi =========================================*/
                // }else{
                // 	/*=============== fungsi untuk compare value yang di input ada tidak di list value combogird =================*/
                // 	var indexes1 	= $.map(Vdata, function(obj, index) {
                // 		if(obj.AccountNumber == txtValue) {
                // 			return index;
                // 		}
                // 	});

                // 	var indexes2 	= $.map(Vdata, function(obj, index) {
                // 		if(obj.AccountName == txtValue) {
                // 			return index;
                // 		}
                // 	});
                // 	/*====================== end fungsi =========================================*/
                // }

                var arrVdata = [];
                $.each(Vdata, function (index, value) {
                    $.each(value, function (ind, val) {
                        switch (ind) {
                            case 'AccountNumber':
                                arrVdata.push(val);
                                break;
                            case 'AccountName':
                                arrVdata.push(val);
                                break;
							case 'JobTitleCode':
                                arrVdata.push(val);
                                break;
                            case 'JobTitleName':
                                arrVdata.push(val);
                                break;
							case 'DepartmentCode':
                                arrVdata.push(val);
                                break;
                            case 'DepartmentName':
                                arrVdata.push(val);
                                break;
                            case 'CompanyCode':
                                arrVdata.push(val);
                                break;
                            case 'CompanyName':
                                arrVdata.push(val);
                                break;
                            case 'BranchCode':
                                arrVdata.push(val);
                                break;
                            case 'BranchName':
                                arrVdata.push(val);
                                break;
                            case 'EmployeeCode':
                                arrVdata.push(val);
                                break;
                            case 'EmployeeName':
                                arrVdata.push(val);
                                break;
                            case 'CustomerName':
                                arrVdata.push(val);
                                break;
                            case 'CustomerCode':
                                arrVdata.push(val);
                                break;
                            case 'VendorCode':
                                arrVdata.push(val);
                                break;
                            case 'VendorName':
                                arrVdata.push(val);
                                break;
							case 'CityCode':
                                arrVdata.push(val);
                                break;
                            case 'CityName':
                                arrVdata.push(val);
                                break;
							case 'CountryCode':
                                arrVdata.push(val);
                                break;
                            case 'CountryName':
                                arrVdata.push(val);
                                break;
							case 'StateCode':
                                arrVdata.push(val);
                                break;
                            case 'StateName':
                                arrVdata.push(val);
                                break;
							case 'AccountSubTypeID':
                                arrVdata.push(val);
                                break;
                            case 'AccountTypeName':
                                arrVdata.push(val);
                                break;
							case 'BankID':
                                arrVdata.push(val);
                                break;
                            case 'BankName':
                                arrVdata.push(val);
                                break;
							case 'TermspaymentID':
                                arrVdata.push(val);
                                break;
                            case 'TermDesc':
                                arrVdata.push(val);
                                break;
							case 'TaxesCode':
                                arrVdata.push(val);
                                break;
                            case 'TaxesName':
                                arrVdata.push(val);
                                break;
							case 'TaxTypeID':
                                arrVdata.push(val);
                                break;
                            case 'TaxTypeName':
                                arrVdata.push(val);
                                break;
							case 'RegionCode':
                                arrVdata.push(val);
                                break;
                            case 'RegionName':
                                arrVdata.push(val);
                                break;
							case 'ShipmentID':
                                arrVdata.push(val);
                                break;
                            case 'ShipmentName':
                                arrVdata.push(val);
                                break;
							case 'FobID':
                                arrVdata.push(val);
                                break;
                            case 'FobName':
                                arrVdata.push(val);
                                break;
							case 'ItemCategoryID':
                                arrVdata.push(val);
                                break;
                            case 'ItemCategoryName':
                                arrVdata.push(val);
                                break;
							case 'DepreciateID':
                                arrVdata.push(val);
                                break;
                            case 'DepreciateName':
                                arrVdata.push(val);
                                break;
                            case 'CurrencyCode':
                                if (typeof value.CurrencyName != 'undefined') {
                                    arrVdata.push(val);
                                }
                                break;
                            case 'CurrencyName':
                                arrVdata.push(val);
                                break;
                        }
                    });
                });

                var indexes1 = 'undefined';

                for (i = 0; i < arrVdata.length; i++) {
                    if (arrVdata[i] == txtValue) {
                        indexes1 = i;
                        return;
                    }
                }

                /*===================== if hasil compare undefined, comborid di clear ==================*/
                if (indexes1 == 'undefined') {
                    $('#' + idCombo).combogrid('clear');
                }
                /*============================ end =================================*/

            } else {

                $('#' + idCombo).combogrid('clear');
            }

        } else {

            var CountarrIDCombo = arrIDCombo.length;
            $('#' + arrIDCombo[CountarrIDCombo - 1]).combogrid('clear');
        }
    }
}

/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>> end Function Clear COmboGrid <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/

/*======================= function Clear COmboBox in Grid ===========================================*/
function clearComboBoxInGrid(txt_value, account_name) {

    var data_combo = account_name.combobox('getData');

    if (txt_value != '') {
        if (data_combo.length > 0) {

            var indexes = $.map(data_combo, function (obj, index) {
                if (obj.AccountName == txt_value) {
                    return index;
                }
            });

            if ((typeof indexes[0]) == 'undefined') {
                account_name.combobox('clear');
            }

        } else {
            account_name.combobox('clear');
        }
    }
}

function load_page_new(menu_label) {
    var button_top_new = '<tr>'
            + '<td align="left">'
            + '<a href="javascript:void(0)" class="easyui-linkbutton" id="new-linkbutton">New</a>'
            + '<a href="javascript:void(0)" class="easyui-linkbutton" id="refresh-linkbutton">Refresh</a>'
            + '</td>'
            + '<td height="25" align="right" valign="middle">'
            + '<span class="form-title" style="margin-left:7px;">'
            + menu_label
            + '</span>'
            + '</td>'
            + '</tr>';
    $('#tab_transstatus').append(button_top_new);

    $('#new-linkbutton').linkbutton({
        iconCls: 'icon-document',
        disabled: false,
        plain: true,
        onClick: function () {
            location.reload();
        }
    });

    $('#refresh-linkbutton').linkbutton({
        iconCls: 'icon-reload',
        disabled: false,
        plain: true,
        onClick: function () {
            location.reload();
        }
    });
}

/*==================== get paging ==============================*/
function get_paging(nm_table, nm_field, TransNumber, CreatedAt, myCallback) {
    var url = base_url + 'custom/custom/get_paging';
    $.ajax({
        type: "POST",
        dataType: "JSON",
        url: url,
        data: $.param({nm_table: nm_table, nm_field: nm_field, TransNumber: TransNumber, CreatedAt: CreatedAt}),
        success: function (data) {
            myCallback(data);
        }, error: function (jqXHR, textStatus, errorThrown) {
            if (jqXHR.status == 500) {
                alert('Internal error: ' + jqXHR.responseText);
            } else {
                alert('Unexpected error.');
            }
        }
    });
}

function load_page_edit(menu_label, menu_link, nm_table, nm_field, TransNumber, CreatedAt, JournalPrivillage, DeletePrivillage, TransStatus, status_suspend) {

    get_paging(nm_table, nm_field, TransNumber, CreatedAt, function (check) {
        var prev = check.prev;
        var next = check.next;

        var top_button = '<a href="javascript:void(0)" class="easyui-linkbutton" id="prev-linkbutton"></a>';
        top_button += '<a href="javascript:void(0)" class="easyui-linkbutton" id="next-linkbutton"></a>';
        top_button += '<input type="checkbox" class="easyui-checkbox" name="chk_suspended" id="chk_suspended" style="margin-top:0px;margin-right:1px;">';
        top_button += '<span style="display:inline-block;margin-top:2px;" class="suspend_span">Suspend</span>';
        top_button += '<a href="javascript:void(0)" class="easyui-linkbutton" id="journal-linkbutton">Journal</a>';
        top_button += '<a href="javascript:void(0)" class="easyui-linkbutton" id="refresh-linkbutton">Refresh</a>';

        $('#top_button').append(top_button);

        if ((TransStatus == 3) || (TransStatus == 9)) {

            $('#chk_suspended').prop('checked', true);
            $('#chk_suspended').prop('disabled', true);
            $('.suspend_span').css({'color': 'gray'});

        } else {

            if (DeletePrivillage == 1) {
                if (TransStatus == status_suspend) {
                    $('#chk_suspended').prop('checked', false);
                    $('#chk_suspended').prop('disabled', false);
                    $('#chk_suspended').on('click', function () {
                        suspend_transaction(1, menu_link, TransNumber, menu_label);
                    });
                    $('.suspend_span').css({'color': 'black'});
                } else {
                    $('#chk_suspended').prop('checked', false);
                    $('#chk_suspended').prop('disabled', true);
                    $('.suspend_span').css({'color': 'black'});
                }
            } else {
                $('#chk_suspended').prop('checked', false);
                $('#chk_suspended').prop('disabled', true);
                $('.suspend_span').css({'color': 'black'});
            }
        }

        if (JournalPrivillage != 1) {
            $('#journal-linkbutton').linkbutton({
                iconCls: 'icon-journal',
                disabled: true,
                plain: true
            });
        } else {
            $('#journal-linkbutton').linkbutton({
                iconCls: 'icon-journal',
                disabled: false,
                plain: true,
                onClick: function () {
                    parent.tab_edit('Journal ' + menu_label, menu_link, 'icon-journal', 'to_journal', TransNumber);
                }
            });
        }

        $('#refresh-linkbutton').linkbutton({
            iconCls: 'icon-reload',
            disabled: false,
            plain: true,
            onClick: function () {
                location.reload();
            }
        });

        if (prev == 'none') {
            $('#prev-linkbutton').linkbutton({
                iconCls: 'icon-back',
                disabled: true,
                plain: true
            });
        } else {
            $('#prev-linkbutton').linkbutton({
                iconCls: 'icon-back',
                disabled: false,
                plain: true,
                onClick: function () {
                    parent.tab_edit('Edit ' + menu_label, menu_link, 'icon-edit', 'edit', prev);
                }
            });
        }

        if (next == 'none') {
            $('#next-linkbutton').linkbutton({
                iconCls: 'icon-next',
                disabled: true,
                plain: true,
                // onClick:function(){
                // 	var title_tab 	= 'Edit '+menu_label;
                // 	parent.change_tab(title_tab,menu_label,menu_link,'New','icon-add','add');
                // }
            });
        } else {
            $('#next-linkbutton').linkbutton({
                iconCls: 'icon-next',
                disabled: false,
                plain: true,
                onClick: function () {
                    parent.tab_edit('Edit ' + menu_label, menu_link, 'icon-edit', 'edit', next);
                }
            });
        }
    });
}

function change_tab(title, menu_label, url, pre_title, icon, func) {
    if (func != undefined) {
        url = base_url + url + '/' + func;
        var title_new = pre_title + ' ' + menu_label;
    }
    else {
        url = base_url + url;
        var title_new = menu_label;
    }

    $('#tt').tabs('close', title);

    var content = '<iframe scrolling="no"  id="ifmWindow" frameborder="0" src="' + url + '" style="width:100%;height:100%;"></iframe>';

    $('#tt').tabs('add', {
        title: title_new,
        content: content,
        icon: icon,
        closable: true
    });
}

function checking_transstatus(no_transaksi, myCallback) {
    var url = base_url + 'custom/custom/checking_transstatus';
    $.ajax({
        type: "POST",
        dataType: "JSON",
        url: url,
        data: $.param({no_transaksi: no_transaksi}),
        success: function (data) {
            myCallback(data);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            if (jqXHR.status == 500) {
                alert('Internal error: ' + jqXHR.responseText);
            } else {
                alert('Unexpected error.');
            }
        }
    });
}

function getCharacterOffsetWithin(range, node) {
    var treeWalker = document.createTreeWalker(
            node,
            NodeFilter.SHOW_TEXT,
            function (node) {
                var nodeRange = document.createRange();
                nodeRange.selectNodeContents(node);
                return nodeRange.compareBoundaryPoints(Range.END_TO_END, range) < 1 ?
                        NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
            },
            false
            );

    var charCount = 0;
    while (treeWalker.nextNode()) {
        charCount += treeWalker.currentNode.length;
    }
    if (range.startContainer.nodeType == 3) {
        charCount += range.startOffset;
    }
    return charCount;
}

function get_character_position(node) {
    var el = document.getElementById(node);
    var range = window.getSelection().getRangeAt(0);
    pos_char = getCharacterOffsetWithin(range, el);
    return pos_char;
}

function formatTransStatus(status) {
    status = parseInt(status);
    var TransStatus = '';

    switch (status) {
        case 0:
            TransStatus = 'Waiting For DP';
            break;
        case 1:
            TransStatus = 'On Progress';
            break;
        case 2:
            TransStatus = 'Finished';
            break;
        case 3:
            TransStatus = 'Suspended';
            break;
        case 4:
            TransStatus = 'Need App. Mgr.';
            break;
        case 5:
            TransStatus = 'Need App. Dir.';
            break;
        case 6:
            TransStatus = 'App. Dir & Mgr';
            break;
        case 7:
            TransStatus = 'App. Limit';
            break;
        case 8:
            TransStatus = 'Suspend Item';
            break;
        case 9:
            TransStatus = 'Cancel By Dir.';
            break;
    }

    return TransStatus;
}

/*==================== SERVER SENT EVENTS =====================================*/ 
window.onload = function setDataSource() {
    if (!!window.EventSource) {
        var source = new EventSource(base_url+"custom/sse_server/checking_session");

        source.addEventListener("message", function(e) {
            if(e.data == "fail"){
                var urlnow = window.location.href;
                if(urlnow.search('login') == -1){
                     window.location.href= base_url+'login/process_logout';
                }
            }
        }, false);
        
        source.addEventListener("open", function(e) {
           
        }, false);

        source.addEventListener("error", function(e) {
            
            if (e.readyState == EventSource.CLOSED) {
               
            }
        }, false);
    } else {
        alert("Sorry, your browser does not support server-sent events...");
        window.location.href= base_url+'login/process_logout';
    }
}
/*==================== END SERVER SENT EVENTS =====================================*/ 
/*============================================ End Daswan ======================================================*/

function show_legend(){
	modal_open('Legend','dialog-legend');
}