var C_ADD 		= "a" ;
var C_CHANGE 	= "c" ;
var C_DELETE 	= "d" ;
var C_EXPORT 	= "e" ;
var C_GET 		= "g";
var C_LIST 		= "l" ;
var C_NEW 		= "n";
var C_QUERY 	= "q" ;
var C_REPORT 	= "r" ;
var C_UPDATE 	= "u" ;
var C_VIEW 		= "v";
var C_LOGOUT 	= "504";
var C_PWD		= "4";
var C_SORT 		= "s";
var C_LOAD	 	= "ld";
var C_SHOW 		= "sh";
var C_SAVE	 	= "sv";

var	C_OK 		= "0";
var C_INFO 		= "6" ;
var C_INVALID 	= "7";
var C_CONFIRM 	= "8" ;
var C_ERROR 	= "9" ;

var baypass_page = false;
var task_list_idx = 1;
var countTotalColumnSpan = 0;

//Session Timeout
var IDLE_LOGOUT_AFTER_MS  = (typeof SERVER_SESSION_TIMEOUT_MS !== 'undefined')
                             ? SERVER_SESSION_TIMEOUT_MS
                             : 15 * 60 * 1000; // fallback if PHP didn't inject it
var IDLE_WARNING_AFTER_MS = IDLE_LOGOUT_AFTER_MS - (2 * 60 * 1000); // warn 2 min before logout
var IDLE_COUNTDOWN_SEC    = Math.round((IDLE_LOGOUT_AFTER_MS - IDLE_WARNING_AFTER_MS) / 1000);
var idleWarningTimer = null;
var idleLogoutTimer  = null;
var idleCountdownInterval = null;
var idleWarningShown = false;
var idleLogoutCalled = false;

function sortingColumn(obj, column, order) {
	$(obj).attr("onclick", sortableColumn(obj, column, order));
	record_obj = obj;

	var sort_name = $(obj).attr("name");
	switch (sort_name) {
		case "customer_sort_column":
			customerFilter();
			break;
		case "customer-contact_sort_column":
			filterCustomerContact();
			break;
		case "prospect_sort_column":
			prospectFilter();
			break;
		case "prospect-contact_sort_column":
			filterProspectContact();
			break;
		case "customer-delivery_sort_column":
			filterCustomerDelivery();
			break;
		case "prospect-delivery_sort_column":
			filterProspectDelivery();
			break;
		case "supplier-contact_sort_column":
			filterSupplierContact();
			break;
		case "fixedAssetRegister_sort_column":
			fixedAssetRegisterFilter();
			break;
		case "destination_sort_column":
			destinationFilter();
			break;
		case "user_sort_column":
			userFilter();
			break;
		case "export-customer-history_sort_column":
			exportCustomerHistoryFilter();
			break;
			
	}

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

	// $(obj).attr("onclick", sortable(column, order, tablename, alias));

	// var table_cols = $('#' + tablename + ' th');
	// var cols = [];
	// table_cols.each(function (i) {
	// 	if (i > 0) {
	// 		var id = $(this).attr('id');
	// 		if ($('input[name=showHideColumns][id=' + id + ']').is(':checked')) {
	// 			cols.push($(this).text().trim() + ":1");
	// 		} else {
	// 			cols.push($(this).text().trim() + ":0");
	// 		}
	// 	}
	// });

	// var data = {
	// 	"type": type,
	// 	"column_sequence": cols,
	// 	"column_sorting": sorts,
	// };
	// var url = "index.pzx?c=" + url + "&d=" + new Date().getTime();
	// callServer(url, "json", data, callback, null);
}

function showMessageHome(type, message, title){
	$("#modalMessageHomeViewContent").html(message);
	if(type == 'error')
		$("#modalMessageHomeHeaderContent").css({ "background-color": "#e20000" });
	else if(type == 'success')
		$("#modalMessageHomeHeaderContent").css({ "background-color": "#3A78AD" });
	else if(type == 'warning')
		$("#modalMessageHomeHeaderContent").css({ "background-color": "#FFD42A" });
	$("#modalMessageHomeViewTitle").html(title);
	$("#messageHomeView").modal("show");
}

function onMainResponse(data) {
	hideProgress() ;
	$("#sbg-center-panel").html(data) ;
}
function onLogout() {
	screen_index = 0 ;
	var data = { "type": C_LOGOUT, "index": screen_index } ;
	var url = "request.pzx?c=" + home_url  +"&d=" + new Date().getTime() ;
	callServer(url,"json",data,onLogoutResponse) ;
}
function onLogoutResponse(data) {
	openSite("index.pzx");
}

function showChangeBU(){
	$("#sbg-change-bu").modal("show");
}
function onChangeBUPrev() {
	
	$('#globalBuValue').val( $('#temGlobalBuValue').val() );
}
function onChangeBU() {
	$("#sbg-change-bu").modal("hide");
	LoadingScreen("show");
	screen_index = 0 ;
	var data = { "type": "C_CHANGE_BU" ,"bu":$('#globalBuValue').val(), "ledger":$("#globalLedgerValue").val(),"index": screen_index } ;
	var url = "request.pzx?c=" + home_url  +"&d=" + new Date().getTime() ;
	callServer(url,"json",data,changeBUResponse) ;
}

function changeBUResponse(obj,resp) {
	if(resp.status != C_OK){
		swal.fire("Error", resp.mesg, "error");
		return;
	}

	swal.fire("Success","Business Unit or Ledger has been changed.",'success');
	setTimeout(function (){
		current_url = window.location.href;
		pieces = current_url.split("?");

		new_url = pieces[0] + resp.data;
		window.location.href = new_url;
		// location.reload();
		// LoadingScreen("hide");
	}, 1500); // How long you want the delay to be, measured in milliseconds.
	
}
function showChangePassword(){
	$('#txtOldPwd').val("");
	$('#txtNewPwd1').val("");
	$('#txtNewPwd2').val("");
	$("#btnChangePwdCancel").show();
	$("#sbg-change-pwd").modal("show");
}
function onChangePassword() {
	if($('#txtOldPwd').val() == ""){
		swal.fire('Warning', "Please input your old password!", "warning");
		return;
	}
	if($('#txtNewPwd1').val() == ""){
		swal.fire('Warning', "Please input your new password!", "warning");
		return;
	}
	if($('#txtNewPwd1').val() != $('#txtNewPwd2').val()){
		swal.fire('Warning', "Confirm password is different!", "warning");
		return;
	}
	var data = { "type": C_PWD,
				 "oldPwd"	: $('#txtOldPwd').val(),
				 "newPwd"	: $('#txtNewPwd1').val()} ;
	var url = "request.pzx?c=" + home_url  +"&d=" + new Date().getTime() ;
	callServer(url,"json",data,onChangePasswordResponse) ;
	/**/
}
function onChangePasswordResponse(obj,resp) {
	if(resp.status != C_OK){
		swal.fire('Warning', resp.mesg, "warning");
		return;
	}

	$("#sbg-change-pwd").modal('hide');
	swal.fire('Success', resp.mesg, "success");
}

$(function() {
    $('.navbar-btn').click(function() {
    });
	/*
	if($("#txtNeedChangePassword").val() == "2"){
        $('#lblChangePwd').html('You need to change your password after self-resetting.');
		showChangePassword();
		$("#btnChangePwdCancel").hide();
	} else if ($("#txtNeedChangePassword").val() == "3"){
        $('#lblChangePwd').html('You need to change your password every '+$('#txtMaxPasswordAge').val()+' days.');
		showChangePassword();
		$("#btnChangePwdCancel").hide();
    }**/
});

function showPage(page,desc,type) {
	LoadingScreen("show");
	if(!baypass_page && $("#contentTitle").html()=="Journal Entry" && $('#ledger-entry-table-body'+ledger_entry_active_ref+" tr").length != 0){

		swal.fire("Journal has not been held or posted, are you sure you want to exit journal entry?", "warning", {
			buttons: {
				ok: true,
				cancel: "Cancel",
			},
		})
		.then(function(result) {	
		switch (result) {
			case "ok":
				baypass_page = true;
				showPage(page,desc,type);
				deleteCanceledJournalAttachment();
				hold_ref_number = 0;
				ledger_entry_active_ref = 1;
				ledger_entry_ref_idx = 1;
				array_doc_id = [];
				array_doc_name = [];
				break;
			default:
				LoadingScreen("hide");
				break;
		}
		});
	}else if(!baypass_page && $("#contentTitle").html()=="Interco Mapping" && $('#intercomapping-table-body tr').length != 0){
		swal.fire("System Confirmation", "Are you sure you want to exits Interco Mapping? Any unsaved changes will be lost.", "warning", {
			buttons: {
				ok: true,
				cancel: "Cancel",
			},
		})
		.then(function(result) {	
		switch (result) {
			case "ok":
				baypass_page = true;
				showPage(page,desc,type);
				break;
			default:
				LoadingScreen("hide");
				break;
			}
		});
	}else{
		baypass_page = false;
		screen_index = 0 ;
		showProgress("loading " + desc) ;
		var data = { "type": type , "index": screen_index} ;
		var url = "index.pzx?c=" + page + "&t=" + type  + "&d=" + new Date().getTime() ;

		callServer(url,"json",data,onHomeResponse,null) ;
	}

}

function onHomeResponse(obj, resp) {
	// if (resp.status != C_OK)
	// 	return false;

	// $(".content").html(resp.data.htmlContent);
	// $("#contentTitle").html(resp.data.headTitle);
	LoadingScreen("hide");
	showScreen(resp);
}

//function showMobilePage(page,type) {
//	showProgress("loading ") ;
//	var data = { "type": type} ;
//	var url = "mobile.pzx?c=" + page + "&t=" + type ;
//	$(".content").load(url,data,function() {hideProgress();}) ;
//}

/****
 * Add collapse and remove events to boxes
 */
$("[data-widget='collapse']").click(function() {
    var box = $(this).parents(".box").first();
    var bf = box.find(".box-body, .box-footer");
    if (!box.hasClass("collapsed-box")) {
        box.addClass("collapsed-box");
        bf.slideUp();
    } else {
        box.removeClass("collapsed-box");
        bf.slideDown();
    }
});

//$("[data-widget='remove']").click(function() {
//    var box = $(this).parents(".box").first();
//    box.slideUp();
//});

$('a').click(function() {
	var box = $(this).parents(".li").first();
	 if (!box.hasClass("active"))
		 box.addClass("active");
});

$(document).ready(function () {
	$('[data-toggle=offcanvas]').click(function () {
	    $('.row-offcanvas').toggleClass('active');
	  });
});

function openCompanyNewsMoad(id) {
	$("#companyNews").modal('show');

	$("#modalcompanyNewsContent").html($("#companyNewsText"+id).text());

}
function openDepartmentNewsMoad(id) {
	$("#DepartmentNews").modal('show');

	$("#modalDepartmentNewsContent").html($("#departmentNewsText"+id).text());
}
/****
 * Change BreadCrumb and header title when click to change page
 * @param arrNaviName 			All of navigation element name
 * @param arrNaviURL 			url corresponding with element name
 * @param navMenuActiveLArr 	menu name corresponding with the element name
 */
//function changeMainHeader(arrNaviName, arrNaviURL, navMenuActiveLArr) {
//	var lenArr = arrNaviName.length;
//	var breadcrumb = "";
//	var classHome  = "fa fa-home";
//	for(var i = 0; i < lenArr-1; i++) {
//		if(i != 0)
//			classHome = "fa";
//
//		breadcrumb = breadcrumb + "<li><a onclick=\"loadContentToMaster('"+arrNaviURL[i]+"', '"+ navMenuActiveLArr[i]+"')\" " +
//								        "href='#'><i class='"+classHome+"'></i> "+ arrNaviName[i] +"</a></li>";
//	}
//
//	breadcrumb = breadcrumb + "<li class='active'>"+arrNaviName[lenArr-1]+"</li>";
//
//}

/*****
 * Load Content to master view and activate corresponding menu
 * @param url
 * @param menuActive : active menu element when changing page
 * Remain one step: set active menu
 */
function loadContentToMaster(url, menuActive) {
	var data = {} ;
	$(".content").load(url,data,function() {hideProgress();}) ;
}


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

function nextscreen() {
  screen_index++;
}
function prevscreen(page_title) {
  $('#screen'+(screen_index-1)+'a').html("");
  $('#screen'+(screen_index-1)+'a').hide();
  $('#screen'+(screen_index-1)+'').show();
  screen_index--;

  $('#contentTitle').html(page_title);
}
function showScreen(resp) {
	if(resp.status != C_OK){
		swal.fire("Error", (resp.mesg == "" ? "Cannot show current screen":resp.mesg   ), "error");
		
		//match via the shared helper: this used to compare a literal that had a typo
		//("You session" vs the "Your session" the server sends) and so never fired
		if(typeof isSessionTimeoutResponse === 'function' && isSessionTimeoutResponse(resp)){
			setTimeout(function() {
				location.reload();
			  }, 2000);
		}

		return;
	}
	if(resp.data.action_menu == "" || resp.data.action_menu == undefined) {
		$("#actionsMenu").removeClass("content-header");
		$("#actionsMenu").html("");
	} else {
		$("#actionsMenu").addClass("content-header");
		$("#actionsMenu").html(resp.data.action_menu);
	}

	$("#contentTitle").html(resp.data.headTitle);

    /**fill the container at first index */
    if(screen_index == 0 ){
        $(".content").html('');
        $(".content").html(resp.data.htmlContent);
    }else{
        /**hide the previous index */
        $('#screen'+(screen_index-1)+'').hide();
        /**fill the index-1a or the next screen with HTML from controller */
        $('#screen'+(screen_index-1)+'a').html(resp.data.htmlContent);
        /**show the main power */
        $('#screen'+(screen_index-1)+'a').show();
    }
    window.scrollTo(0,0);
}



async function showContentIndex(html) {
    if(screen_index == 0 ){
        $("#screen_container").html(html);
    }else{
        /**hide the previous index */
        $('#screen'+(screen_index-1)+'').hide();
        /**fill the index-1a or the next screen with HTML from controller */
        $('#screen'+(screen_index-1)+'a').html(html);
        /**show the main power */
        $('#screen'+(screen_index-1)+'a').show();
    }
    return;
}

//filter
function filterRow(filterRow, objBtn, stat) {
    if (stat) {
        $('#'+filterRow).show();
        $(objBtn).attr("onclick","filterRow('"+filterRow+"',this,false);");
    } else {
        $('#'+filterRow).hide();
        $(objBtn).attr("onclick","filterRow('"+filterRow+"',this,true);");
    }
}

//=========================
//TASK LIST

function taskListFilter() {
    var data = { "type": "C_FILTER_TASK_LIST",
				 "index": screen_index,
				};
    var url  = "index.pzx?c=" + home_url + "&d=" + new Date().getTime() ;
	callServer(url,"json",data,onResponseTaskList,null) ;
}

function addNewTaskListLine() {
    $('#task-list-table-body').append(
        '<tr id="tr_task_list'+task_list_idx+'">'+
        '<td style="display:none" class="task_list_idx" id="task_list_idx'+task_list_idx+'">'+task_list_idx+'</td>'+
        '<td><input type="text" id="task_list_date'+task_list_idx+'" class="form-control task_list_date" value="<?php echo date("d/m/Y");?>"></td>'+
        '<td><input type="text" id="task_list_desc'+task_list_idx+'" class="form-control task_list_desc"></td>'+
        '<td style="text-align:center!important;"><input type="checkbox" id="task_list_check'+task_list_idx+'" class="task_list_check"></td>' +
        '<td><a style="float:right;margin-top:5px;background-color:grey;color:white;" href="#" onclick="deleteTaskListLine('+task_list_idx+');" class="btn btn-primary btn-sm">Delete</a></td>' +
        '</tr>'
	);

	$('.task_list_date').datepicker({
		format: "dd/mm/yyyy",
		useCurrent : true,
		todayHighlight: true
	});

    task_list_idx++;
}

function deleteTaskListLine(idx) {
	$('#tr_task_list'+idx).remove();
}

function saveTaskListLine() {
	if( validateTaskList() ){
        var data = { "type": "C_SAVE_TASK_LIST",
				 "index": screen_index,
                 "task_list_data": getTaskListTable()
				};

        var url  = "index.pzx?c=" + home_url + "&d=" + new Date().getTime() ;
		callServer(url,"json",data,onResponseTaskList,null) ;
		return false;
    }else{
        swal.fire('Warning',"Please fill all task description",'warning');
    }
}

function getTaskListTable() {
    var arrays = [];
    $('#task-list-table-body tr').each(function() {
        var data = {
			"date" : $(".task_list_date",this).val(),
			"desc" : $(".task_list_desc",this).val(),
			"status" : ($('.task_list_check',this).is(':checked') ? '1' : '0'),
        };

        arrays.push(data);
    });

    return JSON.stringify(arrays) ;
}


function onResponseTaskList(obj,resp) {
    if(resp.status!=C_OK){
		swal.fire('Warning',resp.mesg,'warning');
		return;
	}

    if(resp.type == "C_SAVE_TASK_LIST"){
        swal.fire('Success',resp.mesg,'success');
        taskListFilter();
    }else if(resp.type == "C_FILTER_TASK_LIST"){
        $('#task-list-table-body').html(resp.data.html);
		task_list_idx = resp.data.idx;
    }
}

function validateTaskList() {
    var allstatus = true;
    $('#task-list-table-body tr').each(function() {
		var desc = $(".task_list_desc",this).val();
        if(desc=="" || desc==undefined){
            allstatus = false;
        }

    });

    return allstatus;
}
function convertNumber(value) {
	return value
	  // Keep only digits and decimal points:
	  .replace(/(,|[^\d.-]+)+/g, '')
	  // Remove duplicated decimal point, if one exists:
	  .replace(/^(\d*\.)(.*)\.(.*)$/, '$1$2$3')
	  // Keep only two digits past the decimal point:
	  .replace(/\.(\d{2})\d+/, '.$1')
	  // Add thousands separators:
	  .replace(/\B(?=(\d{3})+(?!\d))/g, ",")
}
function convertTextToNumber(value) {
	return value
	  // Keep only digits and decimal points:
	  .replace(/(,|[^\d.-]+)+/g, '')
	  // Remove duplicated decimal point, if one exists:
	  .replace(/^(\d*\.)(.*)\.(.*)$/, '$1$2$3')
	  // Keep only two digits past the decimal point:
	  .replace(/\.(\d{2})\d+/, '.$1')
	  // Add thousands separators:
	  .replace(/\B(?=(\d{3})+(?!\d))/g, ",")
}

function removeCommas(value) {
	if(value != undefined) {
	  if(value.includes(',')) {
		return value
		  // Keep only digits and decimal points:
		//   .replace(/[^\d.]/g, "");
		  .replace(/(,|[^\d.-]+)+/g, '');
	  } else {
		return value;
	  }
	}
}

//Session Timeout
// The idle timers below are pure browser state. The server only extends the session when a
// request actually reaches it, so working locally (typing into a form, reading a list) keeps
// resetting the client timer while the server clock runs out unnoticed - and the next button
// press is rejected and logs the user out with no warning. This heartbeat keeps the server's
// Active_Time in step with real activity.
var KEEPALIVE_GAP_MS = Math.max(15000, Math.floor(IDLE_LOGOUT_AFTER_MS / 3));
var lastKeepAliveAt  = 0;
//latched once the session is over. deliberately NOT idleLogoutCalled, which resetIdleTimers
//clears on the next mouse move - the very events that fire while the goodbye dialog is up.
var sessionEnded     = false;

function keepServerSessionAlive() {
	// while the warning is up the user must answer it; pinging would defeat the prompt
	if (idleWarningShown || sessionEnded) return;

	var now = new Date().getTime();
	if (now - lastKeepAliveAt < KEEPALIVE_GAP_MS) return;
	lastKeepAliveAt = now;

	// deliberately not callServer(): this is a background ping and must not flash the
	// progress overlay over the screen the user is working on
	$.ajax({
		url      : "request.pzx?c=" + home_url + "&d=" + now,
		type     : "POST",
		data     : { "type": "C_KEEP_ALIVE" },
		dataType : "json",
		cache    : false,
		success  : function(resp) {
			// session already gone - say so now instead of letting them keep typing into
			// a dead session and lose the work on their next click
			if (typeof isSessionTimeoutResponse === 'function' &&
				typeof handleSessionTimeout === 'function' &&
				isSessionTimeoutResponse(resp)) {
				handleSessionTimeout(resp);
			}
		}
		// network blips are ignored on purpose - the next activity retries
	});
}

function resetIdleTimers() {
	// user must explicitly click "Stay Logged In" to dismiss it.
	if (idleWarningShown) return;

	clearTimeout(idleWarningTimer);
	clearTimeout(idleLogoutTimer);

	idleLogoutCalled = false;

	idleWarningTimer = setTimeout(showIdleWarning, IDLE_WARNING_AFTER_MS);
	idleLogoutTimer  = setTimeout(onIdleLogout, IDLE_LOGOUT_AFTER_MS);

	keepServerSessionAlive();   // throttled, so mousemove does not spam the server
}
 
function showIdleWarning() {
	idleWarningShown = true;
    var secondsLeft = IDLE_COUNTDOWN_SEC;

	function warningHtml(sec) {
        return 'You\'ve been inactive for a while. For your security, you will be logged out in <strong>' +
               sec +
               '</strong> seconds.<br><br>Click <strong>"Stay Logged In"</strong> to continue your session.';
    }

    Swal.fire({
        title: "Session Expiring Soon",
        html: warningHtml(secondsLeft),
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "Stay Logged In",
        cancelButtonText: "Logout Now",
        allowOutsideClick: false,
        allowEscapeKey: false,
		reverseButtons: true,
        didOpen: () => {
            idleCountdownInterval = setInterval(function () {
                secondsLeft--;
                Swal.update({
                    html: warningHtml(secondsLeft)
                });
                if (secondsLeft <= 0) {
                    clearInterval(idleCountdownInterval);
                    Swal.close();
                }
            }, 1000);
        }
    }).then((result) => {
        clearInterval(idleCountdownInterval);
        if (result.isConfirmed) {
            onStayLoggedIn();
        } else {
            onIdleLogout();
        }
    });
}
 
function onStayLoggedIn() {
	clearInterval(idleCountdownInterval);
	idleWarningShown = false;
 
	// Ping server to refresh Active_Time / extend session
	var data = { "type": "C_KEEP_ALIVE"};
	var url = "request.pzx?c=" + home_url + "&d=" + new Date().getTime();
	callServer(url, "json", data, function(obj, resp) {
		resetIdleTimers();
	});
}
 
function onIdleLogout() {
	if (idleLogoutCalled) return; // prevent double call, only in swal2
    idleLogoutCalled = true;
    sessionEnded     = true;   // stop the heartbeat renewing a session we are ending

	clearInterval(idleCountdownInterval);
    idleWarningShown = false;
    clearTimeout(idleWarningTimer);
    clearTimeout(idleLogoutTimer);

    Swal.fire({
		title: "Session Timeout",
		text: "You have been logged out due to inactivity.",
		icon: "warning",
		allowOutsideClick: false,
		allowEscapeKey: false,
		timer: 3000,
	}).then(() => {
		idleLogoutCalled = false;
        onLogout();
    });
}
 
function initIdleTimeoutWatcher() {
	// loading the page was itself a request, so the server clock is already fresh
	lastKeepAliveAt = new Date().getTime();

	var activityEvents = "mousemove mousedown keydown scroll touchstart";
	$(document).on(activityEvents, function() {
		resetIdleTimers();
	});
	resetIdleTimers();
}

$(document).ready(function() {
	initIdleTimeoutWatcher();
});

function isSessionTimeoutResponse(resp) {
    var result = resp.status == C_ERROR &&
           (resp.mesg && resp.mesg.toLowerCase().indexOf("session has timeout") !== -1);
    return result;
}

function handleSessionTimeout(resp) {
	LoadingScreen("hide");
    sessionEnded = true;   // session is gone; no point pinging it
    clearInterval(idleCountdownInterval);
    clearTimeout(idleWarningTimer);
    clearTimeout(idleLogoutTimer);

    Swal.fire({
		title: "Session Timeout",
		text: resp.mesg || "Your session has timed out, please login again.",
		icon: "warning",
		allowOutsideClick: false,
		allowEscapeKey: false,
		timer: 3000,
	}).then(() => {
		openSite("index.pzx");
	});
}