var coy_obj = null ;
var m_workflow_idx = 0;
var no_Wf	= 0;
var C_DELETE_LOGO = "dl";
var m_interidx 		= 0;
var invoice_title_idx = 0;

$(document).ready(function() 
{ 
	$('#formCompany').hide() ;

	$('input').css('marginTop', 0); 
	$('input').css('marginBottom',0);
	$('select').css('marginTop',0) ;
	$('select').css('marginBottom',0) ;
	
	// $('#company-tabs').tabs() ;
	$('#btnCoyClear').button().bind('click',clearCompany) ;
	$('#btnCoyUpdate').button().bind('click',updateCompany) ;
	$('#btnCoyAdd').button().bind('click',addCompany) ;
	$('#btnCoyPrint').button().bind('click',printCompany) ;
	$('#btnCompanyLogoUpload').button().bind('click',uploadCompanyLogo) ;
	$('#btnCompanyLogoRemove').button().bind('click',removeCompanyLogo) ;
	$('#btnBankPayNowQRUpload').button().bind('click',uploadBankPayNowQRCode) ;
	$('#btnBankPayNowQRRemove').button().bind('click',removeBankPayNowQRCode) ;

	$('#txtCoyCpfRef').keypress(function() { numericInput(0,'',0,0) ; }) ;
	$('#txtCoyEgm').keypress(function() { numericInput(0,'',0,0) ; }) ;
	$('#txtCoyBonus').keypress(function() { numericInput(0,'',0,0) ; }) ;
	$(window).resize(resizeCoyGrid) ;
	resizeCoyGrid() ;
	clearCompany();
    filterCompany();   
}) ;

function closeFormCompany(){
	clearCompany();
	$('#formCompany').hide('slow') ;
}	

function showFormCompany(){
	clearCompany();
	$('#formCompany').show('slow') ;
}

function filterCompany() {
	var data = { "type": C_LIST} ;
	var url = "request.pzx?c=" + coy_url + "&d=" + new Date().getTime() ;		
	callServer(url,"json",data,showCompanyFilterList,coy_obj) ;
}

function showCompanyFilterList(obj,resp) {
	dataJSONArray = resp;
	$('.sbg-company-table').KTDatatable('destroy');
	init_dt();
}

function init_dt() {
	var datatable = $('.sbg-company-table').KTDatatable({
		// datasource definition
		data: {
			type: 'local',
			source: dataJSONArray,
			pageSize: 5, // display 20 records per page
			serverPaging: true,
			serverFiltering: true,
			serverSorting: true,
		},

		// layout definition
		layout: {
			scroll: true, // enable/disable datatable scroll both horizontal and vertical when needed.
			height: 'auto', // datatable's body's fixed height
			footer: false, // display/hide footer
		},

		// column sorting
		sortable: true,

		// toolbar
		toolbar: {
			// toolbar placement can be at top or bottom or both top and bottom repeated
			placement: ['bottom'],

			// toolbar items
			items: {
				// pagination
				pagination: {
					// page size select
					pageSizeSelect: [5, 10, 20, 30, 50], // display dropdown to select pagination size. -1 is used for "ALl" option
				},
			},
		},

		search: {
			input: $('#generalSearch'),
		},

		columns: [
			{
				field: "id",
				title: "ID",
				width: 30,
			}, {
				field: "desc",
				title: "Description",
				width: 280,
			}, {
				field: 'actions',
				title: 'Actions',
				width:600,
				sortable: true,
				overflow: 'visible',
		}],
	});
}

function resizeCoyGrid() {
	var h = $("#sbg-center-panel").outerHeight() - $("#sbg-company-entry").outerHeight() - 55;
	$("div#sbg-company-data").css("height", h +'px') ;		
}

$('#cmbProration').change(function(){
	if($('#cmbProration').val() == '1'){
		$('#cmbProrationMonth').val('0');
		$('#cmbProrationMonth').attr("disabled", false); 
	} else {
		$('#cmbProrationMonth').attr("disabled", true); 
	}
});
//logo
function removeCompanyLogo(){
    if($('#txtCoyId').val() == "Auto"){
		swal('System Message','Unable to remove the image.') ;
        return;
    }
    if($('#imgLogo').attr('src') == ""){
		swal('System Message','No image to remove.') ;
        return;
    }
	// if (confirm("Confirm you want to remove the logo?")) {
	// 	var data = {"type": C_DELETE_LOGO, "id" : $('#txtCoyId').val()} ;
	// 	var url = "request.pzx?c=" + coy_url + "&d=" + new Date().getTime() ;
	// 	callServer(url,"json",data,onCompanyResponse,coy_obj) ;
	// }
	//=========================
	swal("Confirm you want to remove the logo?", {
		buttons: {
			ok: true,
		  cancel: "Cancel",
		},
	  })
	  .then((value) => {
		switch (value) {
		  case "ok":
			  var data = {"type": C_DELETE_LOGO,"id": $('#txtCoyId').val()} ;
			  var url = "request.pzx?c=" + coy_url + "&d=" + new Date().getTime() ;
			  callServer(url,"json",data,onCompanyResponse,coy_obj) ;
		  break;
		}
	});
}
function onUploadEnd(resp) {
	$('#setting_upload').hide() ;
	$('#btnCompanyLogoUpload').prop('disabled','');
	var s = resp.split("|") ;
	if (s[0]==C_OK) {
		$('#imgLogo').prop('src',s[1]) ;
	} else {
		swal(s[1]) ;
	}
}
function uploadCompanyLogo() {
	var fn = $('#fileLogo').val() ;
	if (fn == "") {
		swal('System Message','You must select a logo image file for upload.') ;
		return ;
	}
    if ($('#txtCoyId').val() == 'Auto'){
		swal('System Message','Please create the company first or edit the existing company.') ;
		return ;
    }
	if (validImageExt(fn)) {
		$('#btnCompanyLogoUpload').prop('disabled','disabled') ;
		var url = "upload.pzx?t=l&n=fileLogo&id=" + $('#txtCoyId').val() + "&d=" + new Date().getTime();
		$('#setting_upload').show() ;
		uploaded = false ;
		ajaxUpload(this.form,url,onUploadEnd);
	}
}

function clearCompany() {
	//general
	$('#txtCoyId').val("Auto") ;
	$('#txtCoyCode').val("") ;
	$('#txtCoyName').val("") ;
	$('#txtCoyRef').val("") ;
	$('#cobCoyBank').val("") ;
	$('#txtCoyAcctNo').val("") ;
	$('#txtCoyRegNo').val("") ;
	$('#cobCoyRegType').val("") ;

	//address
	$('#txtCoyAddr1').val("") ;
	$('#txtCoyAddr2').val("") ;
	$('#txtCoyAddr3').val("") ;
	$('#txtCoyAddr4').val("") ;
	$('#txtCoyAddr5').val("") ;
	$('#txtCoyTel').val("") ;
	$('#txtCoyFax').val("") ;
	
	$('#txtCoyCpfNo').val("") ;
	$('#txtCoyCpfRef').val("") ;
	$('#txtCoyAuthName').val("") ;
	$('#txtCoyAuthTitle').val("") ;
	$('#txtCoyEgm').val("") ;
	$('#txtCoyBonus').val("") ;
	$('#txtCoyAuthTel').val("") ;
	$('#tblWorkFlow').empty() ;
	$('#cmbProration').val('0');
	$('#cmbProrationMonth').val('0');
	$('#txtCoyClearingAccount').val('');
	$('#cobCoyBaseCurrency').val('');

	//workflow
	$('#txtCoyActivityCodePrefix').val('');
	$('#txtCoyActivityCodeLength').val('10');
	$('#txtCoyActivityCodeRN').val('1');
	$('#txtCoyGRCodePrefix').val('');
	$('#txtCoyGRCodeLength').val('10');
	$('#txtCoyGRCodeRN').val('1');
	$('#txtCoyQuotationCodePrefix').val('');
	$('#txtCoyQuotationCodeLength').val('10');
	$('#txtCoyQuotationCodeRN').val('1');
	$('#txtCoySalesQuotationCodePrefix').val('');
	$('#txtCoySalesQuotationCodeLength').val('2');
	$('#txtCoySalesQuotationCodeRN').val('10');
	$('#txtCoySalesQuotationInternalPrefix').val('');
	$('#txtCoyProformaInvoiceCodePrefix').val('');
	$('#txtCoyProformaInvoiceCodeLength').val('2');
	$('#txtCoyProformaInvoiceCodeRN').val('10');

	$('#cmbClaimRejectReason').val('0');
        
    $('#txtFinancialMonth').val('1');
    $('#txtFinancialYear').val('0');
    
	//email setting
	$('#txtCoyEmailSettingServer').val('');
	$('#txtCoyEmailSettingPort').val('25');
	$('#txtCoyEmailSettingSender').val('');
	$('#txtCoyEmailSettingPassword').val('');
	$('#txtCoyEmailSettingAuth').prop('checked', false);
	$('#txtCoyEmailSettingSSL').prop('checked', false);

	//bank detail        
	$('#txtCoyBankName').val('');
	$('#txtCoyBankCode').val('');
	$('#txtCoyBankAccountName').val('');
	$('#txtCoyBankAccountNumber').val('');
	$('#txtCoyBankBranchCode').val('');
	$('#txtCoyBankSwiftCode').val('');
	$("#imgPaynowQRCode").attr("src", "");
    
    $('#tblCompanyLocationBody').html('');
	//$('#btnCompanyLogoUpload').prop('disabled','');
	//$('#btnCompanyLogoRemove').prop('disabled','disabled') ;
	$("#imgLogo").attr("src", "");
        
	$('#cmbProrationMonth').attr("disabled", true); 
	// $('#company-tabs').tabs("option", "active", 0) ;
	$('#txtCoyName').focus() ;
	$('#btnCoyUpdate').prop('disabled','disabled') ;
	
	$('#coy_err_name').hide() ;
	$('#coy_err_cpfno').hide() ;
	$('#coy_err_regtype').hide() ;
	$('#coy_err_regno').hide() ;
	$('#coy_err_cpfref').hide() ;
	$('#coy_err_authname').hide() ;
	$('#coy_err_mesg').text('') ;
	if (coy_obj != null && coy_obj != undefined)
	{
		$($(coy_obj).closest("tr")).removeClass("sbg-row-selected") ;
	}
	coy_obj = null ;
}
function updateCompany() {
	saveCompany(C_UPDATE) ;
}
function addCompany() {
	saveCompany(C_ADD) ;
}
function saveCompany(type) {
	if (validateCompany()) {
		var data = { "type": type, "id": $('#txtCoyId').val(), "name": $('#txtCoyName').val(), "name2": "",
			"regno": $('#txtCoyRegNo').val(), "cpfno": $('#txtCoyCpfNo').val(), "cpfref": $('#txtCoyCpfRef').val(),
			"bank": $('#cobCoyBank').val(), "acctno": $('#txtCoyAcctNo').val(), "regtype": $('#cobCoyRegType').val(),
			"refno": $('#txtCoyRef').val(),"authname": $('#txtCoyAuthName').val(), "authtitle": $('#txtCoyAuthTitle').val(),
			"authtelno": $('#txtCoyAuthTel').val(), "egmdate": $('#txtCoyEgm').val(), "bonusdate": $('#txtCoyBonus').val(),
			"tel": $('#txtCoyTel').val(), "fax": $('#txtCoyFax').val(), "addr1": $('#txtCoyAddr1').val(), "addr2": $('#txtCoyAddr2').val(), 
			"addr3": $('#txtCoyAddr3').val(), "addr4": $('#txtCoyAddr4').val(), "addr5": $('#txtCoyAddr5').val(),
			"claim_reject_reason" : $('#cmbClaimRejectReason').val(),
			"proration_claim" : $('#cmbProration').val(), "proration_month" : $('#cmbProrationMonth').val(), 
            "code": $('#txtCoyCode').val(),
			"clearingaccount" : $('#txtCoyClearingAccount').val(),
			"basecurrency" : $('#cobCoyBaseCurrency').val(),

			//workflow
			"activitycodeprefix" : $('#txtCoyActivityCodePrefix').val(),
			"activitycodelength" : $('#txtCoyActivityCodeLength').val(),
			"activitycodern" 	 : $('#txtCoyActivityCodeRN').val(),
			"grcodeprefix" 	: $('#txtCoyGRCodePrefix').val(),
			"grcodelength" 	: $('#txtCoyGRCodeLength').val(),
			"grcodern" 		: $('#txtCoyGRCodeRN').val(),
			"quotationcodeprefix" 	: $('#txtCoyQuotationCodePrefix').val(),
			"quotationcodelength" 	: $('#txtCoyQuotationCodeLength').val(),
			"quotationcodern" 		: $('#txtCoyQuotationCodeRN').val(),
			"salesquotationcodeprefix" 	: $('#txtCoySalesQuotationCodePrefix').val(),
			"salesquotationcodelength" 	: $('#txtCoySalesQuotationCodeLength').val(),
			"salesquotationcodern" 		: $('#txtCoySalesQuotationCodeRN').val(),
			"salesquotationinternalprefix" 	: $('#txtCoySalesQuotationInternalPrefix').val(),
			"proformainvoicecodeprefix" 	: $('#txtCoyProformaInvoiceCodePrefix').val(),
			"proformainvoicecodelength" 	: $('#txtCoyProformaInvoiceCodeLength').val(),
			"proformainvoicecodern" 		: $('#txtCoyProformaInvoiceCodeRN').val(),

			//email setting
			"emailsettingserver" : $('#txtCoyEmailSettingServer').val(),
			"emailsettingport" : $('#txtCoyEmailSettingPort').val(),
			"emailsettingsender" : $('#txtCoyEmailSettingSender').val(),
			"emailsettingpassword" : $('#txtCoyEmailSettingPassword').val(),
			"emailsettingauth" : ($('#txtCoyEmailSettingAuth').is(':checked') ? '1' : '0'),
			"emailsettingssl" : ($('#txtCoyEmailSettingSSL').is(':checked') ? '1' : '0'),

			//bank detail
			"bankdetailcode" 			: $('#txtCoyBankCode').val(),
			"bankdetailname" 			: $('#txtCoyBankName').val(),
			"bankdetailaccountname" 	: $('#txtCoyBankAccountName').val(),
			"bankdetailaccountnumber" 	: $('#txtCoyBankAccountNumber').val(),
			"bankdetailbranchcode" 		: $('#txtCoyBankBranchCode').val(),
			"bankdetailswiftcode" 		: $('#txtCoyBankSwiftCode').val(),

			//invoice setting
			"invoice_title" 			: getInvoiceTitle(),

			"financialmonth" : $('#txtFinancialMonth').val(), "financialyear" : $('#txtFinancialYear').val(),
			"comapany_location": getCompanyLocation(),
			"workFlowSteps" : getWorkFlowSteps(),
		} ;
		var url = "request.pzx?c=" + coy_url + "&d=" + new Date().getTime() ;
		
		callServer(url,"json",data,onCompanyResponse,coy_obj) ;
	}
}

function merge_options(obj1,obj2) {
    var obj3 = {};
    for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
    for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
    return obj3;
}
function printCompany() {
	var url = "report.pzx?c=" + coy_url + "&d=" + new Date().getTime() ;
	showReport(url) ;
}
function editCompany(id,obj) {
	var data = { "type": C_GET,"id": id} ;
	var url = "request.pzx?c=" + coy_url + "&d=" + new Date().getTime() ;
	clearCompany() ;
	showFormCompany();
	coy_obj = obj ;
	$($(obj).closest("tr")).addClass("sbg-row-selected");
	callServer(url,"json",data,showCompany,obj) ;
}

function deleteCompany(id,obj) {
	// if (confirm("Confirm you want to delete company id : " + id + "?")) {
	// 	var data = {"type": C_DELETE,"id": id} ;
	// 	var url = "request.pzx?c=" + coy_url + "&d=" + new Date().getTime() ;
	// 	callServer(url,"json",data,onCompanyResponse,obj) ;
	// }

	//=================================================

	swal("Confirm you want to delete company id : " + id + "?", {
		buttons: {
			ok: true,
		  cancel: "Cancel",
		},
	  })
	  .then((value) => {
		switch (value) {
		  case "ok":
			  var data = {"type": C_DELETE,"id": id} ;
			  var url = "request.pzx?c=" + coy_url + "&d=" + new Date().getTime() ;
			  callServer(url,"json",data,onCompanyResponse,obj) ;
		  break;
		}
	});	
}
function showCompany(obj,resp) {
	if (resp.status == C_OK) {
		
		showWorkFlowStep(resp.data.step);

		//general
		$('#txtCoyId').val(resp.data.id) ;
		$('#txtCoyAcctNo').val(resp.data.acctno) ;
		$('#cobCoyBank').val(resp.data.bank) ;
		$('#txtCoyName').val(resp.data.name) ;
		$('#txtCoyCode').val(resp.data.code) ;
		$('#txtCoyRef').val(resp.data.refno) ;
		$('#txtCoyRegNo').val(resp.data.regno) ;
		$('#cobCoyRegType').val(resp.data.regtype) ;

		//address
		$('#txtCoyTel').val(resp.data.tel) ;
		$('#txtCoyFax').val(resp.data.fax) ;
		$('#txtCoyAddr1').val(resp.data.addr1) ;
		$('#txtCoyAddr2').val(resp.data.addr2) ;
		$('#txtCoyAddr3').val(resp.data.addr3) ;
		$('#txtCoyAddr4').val(resp.data.addr4) ;
		$('#txtCoyAddr5').val(resp.data.addr5) ;
		
		$('#txtCoyCpfNo').val(resp.data.cpfno) ;
		$('#txtCoyCpfRef').val(resp.data.cpfref) ;
		$('#txtCoyAuthName').val(resp.data.authname) ;
		$('#txtCoyAuthTitle').val(resp.data.authtitle) ;
		$('#txtCoyAuthTel').val(resp.data.authtelno) ;
		$('#txtCoyEgm').val(resp.data.egmdate) ;
		$('#txtCoyBonus').val(resp.data.bonusdate) ;
		$('#cmbClaimRejectReason').val(resp.data.claimrejectreason);
		$('#cmbProration').val(resp.data.prorationclaim);
		$('#txtCoyClearingAccount').val(resp.data.clearingaccount);

		//workflow
		$('#txtCoyActivityCodePrefix').val(resp.data.activitycodeprefix);
		$('#txtCoyActivityCodeLength').val(resp.data.activitycodelength);
		$('#txtCoyActivityCodeRN').val(resp.data.activitycodern);
		$('#txtCoyGRCodePrefix').val(resp.data.grcodeprefix);
		$('#txtCoyGRCodeLength').val(resp.data.grcodelength);
		$('#txtCoyGRCodeRN').val(resp.data.grcodern);
		$('#txtCoyQuotationCodePrefix').val(resp.data.quotationcodeprefix);
		$('#txtCoyQuotationCodeLength').val(resp.data.quotationcodelength);
		$('#txtCoyQuotationCodeRN').val(resp.data.quotationcodern);
		$('#txtCoySalesQuotationCodePrefix').val(resp.data.salesquotationcodeprefix);
		$('#txtCoySalesQuotationCodeLength').val(resp.data.salesquotationcodelength);
		$('#txtCoySalesQuotationCodeRN').val(resp.data.salesquotationcodern);
		$('#txtCoySalesQuotationInternalPrefix').val(resp.data.salesquotationinternalprefix);
		$('#txtCoyProformaInvoiceCodePrefix').val(resp.data.proformainvoicecodeprefix);
		$('#txtCoyProformaInvoiceCodeLength').val(resp.data.proformainvoicecodelength);
		$('#txtCoyProformaInvoiceCodeRN').val(resp.data.proformainvoicecodern);

		$('#cmbProrationMonth').attr("disabled", resp.data.prorationclaim != '1'); 
		$('#cmbProrationMonth').val(resp.data.prorationmonth);
                
		$('#cobCoyBaseCurrency').val(resp.data.basecurrency);
                
		$('#txtFinancialMonth').val(resp.data.financialmonth);
		$('#txtFinancialYear').val(resp.data.financialyear);

        //email setting
		$('#txtCoyEmailSettingServer').val(resp.data.emailsettingserver);
		$('#txtCoyEmailSettingPort').val(resp.data.emailsettingport);
		$('#txtCoyEmailSettingSender').val(resp.data.emailsettingsender);
		$('#txtCoyEmailSettingPassword').val(resp.data.emailsettingpassword);
        $('#txtCoyEmailSettingAuth').prop('checked', (resp.data.emailsettingauth == '1' ? true : false));
		$('#txtCoyEmailSettingSSL').prop('checked', (resp.data.emailsettingssl == '1' ? true : false));

        //bank detail
		$('#txtCoyBankCode').val(resp.data.bankdetailcode);
		$('#txtCoyBankName').val(resp.data.bankdetailname);
		$('#txtCoyBankAccountName').val(resp.data.bankdetailaccountname);
		$('#txtCoyBankAccountNumber').val(resp.data.bankdetailaccountnumber);
        $('#txtCoyBankBranchCode').val(resp.data.bankdetailbranchcode);
		$('#txtCoyBankSwiftCode').val(resp.data.bankdetailswiftcode);
		if(resp.data.paynowqrpath != ''){
            $("#imgPaynowQRCode").attr("src", resp.data.paynowqrpath);
        }

		//invoice setting
		setInvoiceTitle(resp.data.invoice_title);
		
		setCompanyLocation(resp.data.location);
        if(resp.data.logopath != ''){
            $("#imgLogo").attr("src", resp.data.logopath);
        }
        
		$('#btnCoyUpdate').prop('disabled','') ;
		$('#txtCoyCode').focus() ;
	}
	else {
		swal("System Message",resp.mesg) ;
	}
}
function onCompanyResponse(obj,resp) {
	if (resp.status == C_OK) {
		no_Wf = 0;
		if (resp.type == C_ADD) {
			swal("Successfull!", resp.mesg, "success");
			clearCompany() ;
			filterCompany();
			closeFormCompany();
		} else if (resp.type == C_DELETE) {
			swal("Successfull!", resp.mesg, "success");
			clearCompany() ;
			filterCompany();
			closeFormCompany();
		} else if (resp.type == C_UPDATE) {
			swal("Successfull!", resp.mesg, "success");
			clearCompany() ;
			filterCompany();
			closeFormCompany();
		} else if (resp.type == C_DELETE_LOGO){
            $("#imgLogo").attr("src", "");
        } else if (resp.type == "DELETE_PAYNOW_QR_CODE"){
            $("#imgPaynowQRCode").attr("src", "");
        }
		$('#sbg-popup-box').html(resp.mesg) ;
		$('#sbg-popup-box').show() ;
		$('#sbg-popup-box').fadeOut(5000) ;
	}
	else 
		swal("Error",resp.mesg) ;
}

function validateCompany() {
	
	$('#coy_err_mesg').text('') ;
	if ($('#txtCoyName').val()=="")
	{
		$('#coy_err_name').show() ;
		$('#txtCoyName').focus() ;
		swal("company name can not be blank.") ;
		return false ;
	}
	else 
		$('#coy_err_name').hide() ;
	
	$('#coy_err_mesg').text('') ;
	if ($('#txtCoyCode').val()=="")
	{
		$('#coy_err_code').show() ;
		$('#txtCoyCode').focus() ;
		swal("company code can not be blank.") ;
		return false ;
	}
	else 
		$('#coy_err_name').hide() ;
	
    /*
	if ($('#txtCoyCpfNo').val()=="")
	{
		$('#coy_err_cpfno').show() ;
		$('#txtCoyCpfNo').focus() ;
		$('#coy_err_mesg').text("CPF CSN number can not be blank.") ;
		return false ;
	}
	else 
		$('#coy_err_cpfno').hide() ;
	if ($('#txtCoyCpfRef').val()=="")
	{
		$('#coy_err_cpfref').show() ;
		$('#txtCoyCpfRef').focus() ;
		$('#coy_err_mesg').text("CPF Ref code can not be blank.") ;
		return false ;
	}
	else 
		$('#coy_err_cpfref').hide() ;
		
	*/
	if ($('#txtCoyRegNo').val()=="")
	{
		$('#coy_err_regno').show() ;
		$('#txtCoyRegNo').focus() ;
		$('#coy_err_mesg').text("Registration no can not be blank.") ;
		return false ;
	}
	else 
		$('#coy_err_regno').hide() ;
	
	/*
	if ($('#cobCoyRegType').val()=="")
	{
		$('#coy_err_regtype').show() ;
		$('#cobCoyRegType').focus() ;
		$('#coy_err_mesg').text("You must select a Registeration no type.") ;
		return false ;
	}
	else 
		$('#coy_err_regtype').hide() ;
	
	if ($('#txtCoyAuthName').val()=="")
	{
		$('#coy_err_authname').show() ;
		$('#txtCoyAuthName').focus() ;
		$('#coy_err_mesg').text("Authorised person name can not be blank.") ;
		return false ;
	}
	else 
		$('#coy_err_authname').hide() ;
	*/
	/*
	if(no_Wf <= 0) {
		$('#coy_err_mesg').html("Please input workflow for the company. <br> If can not find workflow, please create it in Workflow tab first.") ;
		return false;
	}*/
	
	return true ;
}


function checkExist(valueCheck, arrayValue) {
	if(arrayValue.length == 0)
		return true;
	
	for(var i = 0; i < arrayValue.length; i++) {
		if(valueCheck == arrayValue[i])
			return false;
	}
	return true;
}

function addWorkFlow() {
	if ($('#cobWorkFlow').val() == "") {
		swal("You must select a approver.") ;
		return ;
	}
	no_Wf = no_Wf + 1;
	m_workflow_idx++;
	$('#tblWorkFlow').append("<tr id='trWorkFlow" + m_workflow_idx + "'><td style='width:30px;'>" +m_workflow_idx+ "</td>" +
		"<td style='width:200px;'><select style='width:200px' id='cobWorkFlow"+m_workflow_idx+ "'></select></td>" +
		"<td style='width:40px;text-align:center;'><a href='javascript:' onclick='removeWorkFlowStep(" + m_workflow_idx + ")'><i class='flaticon-delete'></i></a></td>" +
		"<td style='width:50px;display:none'><input style='width:50px' id='txtWorkFlowStep"+m_workflow_idx+ "' value='"+ $('#cobWorkFlow' + m_workflow_idx).val() +"'></input></td>" +		
		"</tr>"); 
	
	$('#cobWorkFlow'+m_workflow_idx).append($('#cobWorkFlow').html()) ;
}

function removeWorkFlowStep(idx) {
	if(no_Wf > 0)
		no_Wf = no_Wf - 1;
	$('#trWorkFlow'+idx).remove() ;
}

function removeWorkFlowStepBK(idx) {
	$('#trWorkFlow'+idx).remove() ;
	for(var i = idx+1; i <= m_workflow_idx ; i++) {
		$($("#trWorkFlow" + i).closest('tr')).children('td:eq(0)').html(i-1) ;
		$($("#trWorkFlow" + i).closest('tr')).children('td:eq(2)').html("<a href='javascript:' onclick='removeWorkFlowStep(" + (i-1) + ")'><i class='flaticon-delete'></i></a>") ;
		
		/*$("#trWorkFlow" + i).val() 	= "trWorkFlow" + (i-1);
		$("#txtWorkFlowStep" + i).val()  = "txtWorkFlowStep" + (i-1);*/
	}
	m_workflow_idx --;
	return;
}

function getWorkFlowSteps() {
	var lines 	= "";
	var sep 	= "" ;
	var wf_id 	= "";
	var step 	= 1 ;
	
	
	$('#tblWorkFlow tr').each(function() { 
		id 		= $(this).find("td").eq(0).html() ;
		wf_id 	= $('#cobWorkFlow'+ id).val() ;
		
		lines 	= lines + sep + step + "-" + wf_id;
		sep 	= "|" ;
		step++;
	}); 
	return lines;
}

function showWorkFlowStep(lines) {
	$('#tblWorkFlow').empty() ;
	if (lines == undefined || lines == null || lines == "") return ;
	var line = lines.split(',') ;
	m_workflow_idx = line.length;
	var fld = "" ;
	for (var i = 0 ; i < line.length ; i++) {
		if (line[i] != "") {
			no_Wf = no_Wf + 1;
			fld = line[i];
			$('#tblWorkFlow').append("<tr id='trWorkFlow" + (i+1) + "'><td style='width:30px;'>" +(i+1)+ "</td>" +
			"<td style='width:200px;'><select style='width:200px' id='cobWorkFlow"+(i+1)+ "'></select></td>" +
			"<td style='width:40px;text-align:center;'><a href='javascript:' onclick='removeWorkFlowStep(" + (i+1) + ")'><i class='flaticon-delete'></i></a></td>" +
			"<td style='width:50px;display:none'><input style='width:50px' id='txtWorkFlowStep"+(i+1)+ "' value='"+ fld +"'></input></td></tr>"); 
			$('#cobWorkFlow'+(i+1)).append($('#cobWorkFlow').html()) ;
			$('#cobWorkFlow'+(i+1)).val(fld) ;
		}
	}
}
function validImageExt(file) 
{
	var extArray = new Array(".png", ".jpg", ".jpeg"); 
	var validext = false;
	if (!file) 
		return;
   
	while (file.indexOf("\\") != -1)
		file = file.slice(file.indexOf("\\") + 1);
            
	var ext = file.slice(file.indexOf(".")).toLowerCase();
	for (var n = 0; n < extArray.length; n++) 
	{
		if (extArray[n] == ext) { validext = true; break; }
	}
	if (validext) {
		return true ;
	} else {
		swal("You can only upload files in .png, .jpg, .jpeg format") ;
		return false ;
	}
}

function addCompanyLocation(){
    
    m_interidx++;
    $('#tblCompanyLocationBody').append("<tr id='trCompanyLocation" + m_interidx + "'><td style='width:30px;display:none'>" +m_interidx+ "</td>" +
            "<td>"+m_interidx+"</td>"+
			"<td >" + "<input style=width='20%' class='form-control name' id='orderId"+m_interidx+"' placeholder='Name..'>" + "</td>" +
			"<td >" + "<textarea style=width='70%' class='form-control address' id='desc"+m_interidx+"' placeholder='Location Address..'></textarea>"  + "</td>" +
            "<td style='width:10%;text-align:center;padding-top: 25px;padding-bottom: 0px;'><a href='javascript:' onclick='removeCompanyLocation(" + m_interidx + ")'><i class='flaticon-delete'></i></a></td></tr>"); 
}

function removeCompanyLocation(idx) {
    $('#trCompanyLocation'+idx).remove() ;
}

function getCompanyLocation() {
	var lines = "" ;
    var sep = "" ;
    $('#tblCompanyLocationBody tr').each(function() { 
		var name 	= $('.name',this).val();
		var address = $('.address' ,this).val() ;
        lines 	= lines + sep + name +"~"+address ;
        sep 	= "|" ;
	}); 
	
	console.log(lines);
    return lines ;
}

function setCompanyLocation(lines) {
    if (lines == undefined || lines == null || lines == "") return ;
	
    var line = lines.split('|') ;
	var fld = "" ;
		
    m_interidx = 0 ;
    for (var i = 0 ; i < line.length ; i++) {
        if (line[i] != "") {
			fld = line[i].split('~') ;
			
            m_interidx++;
			$('#tblCompanyLocationBody').append("<tr id='trCompanyLocation" + m_interidx + "'>"+
			"<td>"+m_interidx+"</td>"+
			"<td >" + "<input style='' class='form-control name' id='orderId"+m_interidx+"' value='"+fld[0] +"'>" + "</td>" +
			"<td >" + "<textarea style='' class='form-control address' id='desc"+m_interidx +"' >"+fld[1]+"</textarea>"  + "</td>" +
            "<td style='text-align:center;padding-top: 25px;padding-bottom: 0px;'><a href='javascript:' onclick='removeCompanyLocation(" + m_interidx + ")'><i class='flaticon-delete'></i></a></td></tr>"); 
        }
    }
}
//paynow qr code
function removeBankPayNowQRCode(){
    if($('#txtCoyId').val() == "Auto"){
		swal('System Message','Unable to remove the PayNow QR code.') ;
        return;
    }
    if($('#imgPaynowQRCode').attr('src') == ""){
		swal('System Message','No image to remove.') ;
        return;
    }
	swal("Confirm you want to remove the PayNow QR code?", {
		buttons: {
			ok: true,
		  cancel: "Cancel",
		},
	  })
	  .then((value) => {
		switch (value) {
		  case "ok":
			  var data = {"type": "DELETE_PAYNOW_QR_CODE", "id": $('#txtCoyId').val()} ;
			  var url = "request.pzx?c=" + coy_url + "&d=" + new Date().getTime() ;
			  callServer(url,"json",data,onCompanyResponse,coy_obj) ;
		  break;
		}
	});
}
function onUploadEndBankPayNowQRCode(resp) {
	$('#setting_upload_paynowqr').hide() ;
	$('#btnBankPayNowQRUpload').prop('disabled','');
	var s = resp.split("|") ;
	if (s[0]==C_OK) {
		$('#imgPaynowQRCode').prop('src',s[1]) ;
	} else {
		swal(s[1]) ;
	}
}
function uploadBankPayNowQRCode() {
    if ($('#txtCoyId').val() == 'Auto'){
		swal('System Message','Please create the company first or edit the existing company.') ;
		return ;
    }
	var fn = $('#filePaynowQRCode').val() ;
	if (fn == "") {
		swal('System Message','You must select a PayNow QR Code file for upload.') ;
		return ;
	}
	if (validImageExt(fn)) {
		$('#btnBankPayNowQRUpload').prop('disabled','disabled') ;
		var url = "upload.pzx?t=l&n=filePaynowQRCode&f=PAYNOW&id=" + $('#txtCoyId').val() + "&d=" + new Date().getTime();
		$('#setting_upload_paynowqr').show() ;
		uploaded = false ;
		ajaxUpload(this.form,url,onUploadEndBankPayNowQRCode);
	}
}
//invoice setting
function addInvoiceTitle() {
	if ($('#txtInvoiceTitle').val() == '') {
		swal("System Warning", "Invoice Title cannot be blank.", "warning");
		return;
	}

	invoice_title_idx++;
	$('#invoice-title-list').append("<tr id='trinvoice" + invoice_title_idx + "' class='table table-bordered m-table m-table--border-brand m-table--head-bg-brand '>"+
		"<td style='text-align:center;vertical-align: middle;font-size:14px;display:none'>" +invoice_title_idx+ "</td>" +
		"<td><input type='text' class='form-control m-input' id='txtTitle"+invoice_title_idx+ "' value='"+ $('#txtInvoiceTitle').val() +"'></input></td>" +
		"<td style='text-align:center;vertical-align: middle;'><input type='checkbox' id='chkDefault"+invoice_title_idx+ "' onchange='changeInvoiceDefault(this);' /></td>" +
		"<td style='text-align:center;vertical-align: middle;'><a href='javascript:' onclick='removeInvoiceTitle(" + invoice_title_idx + ")'><i class='flaticon-delete' title='Delete'></i></a></td></tr>");
	$('#txtInvoiceTitle').val('');
}
function removeInvoiceTitle(idx) {
	$('#trinvoice'+idx).remove() ;
	invoice_title_idx--;
}
function changeInvoiceDefault(obj) {
	$('#invoice-title-list tr').each(function() {
		if($(this).find("td:eq(2) input[type='checkbox']").attr('id') != $(obj).attr('id')) {
			$(this).find("td:eq(2) input[type='checkbox']").prop("checked", false);
		}
	});
}
function getInvoiceTitle() {
	var titles = [];
    var title = {};
    $('#invoice-title-list tr').each(function() {
		title = {
			"id": $(this).find("td:eq(0)").html(),
			"title": $(this).find("td:eq(1) input[type='text']").val(),
			"default": $(this).find("td:eq(2) input[type='checkbox']").is(':checked') ? 1 : 0,
		};
		titles.push(title);
	});
	return JSON.stringify(titles) ;
}
function setInvoiceTitle(lines) {
	console.log(lines);
	$('#invoice-title-list').html('');
	if(lines.length > 0) {
		invoice_title_idx = lines.length;
		for(var i=0; i<lines.length; i++) {
			$('#invoice-title-list').append("<tr id='trinvoice" + lines[i].id + "' class='table table-bordered m-table m-table--border-brand m-table--head-bg-brand '>"+
				"<td style='text-align:center;vertical-align: middle;font-size:14px;display:none'>" + lines[i].id + "</td>" +
				"<td><input type='text' class='form-control m-input' id='txtTitle"+i+ "' value='"+ lines[i].title +"'></input></td>" +
				"<td style='text-align:center;vertical-align: middle;'><input type='checkbox' id='chkDefault"+lines[i].id+ "' onchange='changeInvoiceDefault(this);' /></td>" +
				"<td style='text-align:center;vertical-align: middle;'><a href='javascript:' onclick='removeInvoiceTitle(" + lines[i].id + ")'><i class='flaticon-delete' title='Delete'></i></a></td></tr>");
				$('#chkDefault'+lines[i].id).attr("checked", lines[i].default);
		}
	}
}