//Global variables of the system
var dn = "WVNRN2FCOW92cE9JdDZWTGpuZnpZMmlvMEJiU2g5SFdMcmw1QmF0ZTJFdz06OoLXGEhQbqjMc4lylnwwl9Q="

//Get Current Date
var today_full_date = new Date()
var day = ("0" + today_full_date.getDate()).slice(-2)
var month = ("0" + (today_full_date.getMonth() + 1)).slice(-2)
var current_date = today_full_date.getFullYear()+"-"+(month)+"-"+(day)

$(document).ready(function () {
    
	//================================ Start of Automatically Logout  ==============================================
	//Current Allowed Adle Minutes to Expire Session is 5 minutes
    let idle_seconds_counter = 0, allowed_idle_seconds = 300
	$(document).on("keyup keypress mousemove", function () {
        idle_seconds_counter = 0
    })
	let idle_seconds_interval = setInterval(function () {
        // console.log("You did not make event for about " + idle_seconds_counter)
        if (idle_seconds_counter >= allowed_idle_seconds) {
            location = 'logout'
            clearInterval(idle_seconds_interval)
    	}
        idle_seconds_counter += 1
    }, 1000)

	//================================ End of Automatically Logout  ================================================

		
	//Global events of the system
	$("#telNo").bind("keypress", function (e) {
        var keyCode = e.which ? e.which : e.keyCode;            
        if (!(keyCode >= 48 && keyCode <= 57)) {
            return false;
        }
    })

	//Allow only numbers and dot, float numbers
	$("#txtSalaryPaymentPaidAmount, #txtBankAccountNumberOpenningBalance, #txtExpenseAmount, #txtAccountTransactionsTransactedAmount").keypress(function(event) {
		if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
			event.preventDefault()
		}
	})
	
	//Global functions of the system
	fillIdentificationDocumentTypes()
	fillEmployeeDepartments()
	fillEmployeePositions()
	fillWorkingAreas()
	fillActiveEmployees()
	fillActiveEmployeesReport()
	
	fillActiveUsers()
	fillActiveUsersReports()
	fillUsersForPrivileges()

	fillExpenseTypes()
	fillAdminAccounts()
	fillDepositAccounts()
	fillDepositAccountsReport()
	fillWithdrawalAccounts()
	fillWithdrawalAccountsReport()

	//================================ Start of System Configuraions ===============================================
	
	// ----------------------- Update Sysem FavIcon ---------------------
	$("#updateSystemFaviconForm").on('submit', function (e) {
		e.preventDefault()
		var formData = new FormData(this)
		var vl =  $("#txtSystemIdd").val()
		var cm = "Nno1am42V0x5dVRIQzUzcHRoZlU1aE52QTBhZzhDQ0FLWVdIL05PczRaUT06Opq5l4P5AAKdub/NZ0odFd8="
		var photoNames = $("#photoUpdateFavicon").val()
		var docNames = ""				// Means no documents in this update
		var hasFile = "Yes"
		var files = "photoUpdateFavicon"
		var tn = "S2hBWUZZUWFpNXFKUWpuZVgzeFg0dWs2QkMveWdDajRuSDVGVW5DUVRZaz06OvI5LZd/lMpddE5xJHGfNqI="
		var commandType = "update_command"
		var objName = "Favicon"
		formData.append("action", "ins_upd_del_everything")
		formData.append("vl", vl)
		formData.append("cm", cm)
		formData.append("hasFile", hasFile)
		formData.append("files", files)
		formData.append("photoUpdateFavicon", $("#systemFavIconPhoto")[0].files[0])
		formData.append("photoNames", photoNames)
		formData.append("docNames", docNames)
		formData.append("commandType", commandType)
		formData.append("tn", tn)
		formData.append("objName", objName)

		$.ajax({
			url: "api/main.php", type: "POST", data:  formData, contentType: false, cache: false, processData:false,
			beforeSend:function(){
				$("#btnUpdateSystemFavIcon").prop('disabled', true)
				$("#btnUpdateSystemFavIcon").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
			},
			success: function(data) {
				$("#btnUpdateSystemFavIcon").prop('disabled', false)
				$("#btnUpdateSystemFavIcon").html("<i class='fa fa-lg fa-pencil'></i> Update System Favicon")
				var Message = data.Message;
				var status = data.Status;
				if (status == true) {		
					swal ({
						title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
					}, function(isConfirm) {
						if (isConfirm) { location.reload() }
					})
				} else {
					Message.forEach(function (error) {
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
					})
				}	
		 	}, error: function(e) {
				bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
			}          
	   })

	})
	
	//------------------------ Update System Name ----------------------------------------------
	$("#updateSystemNameForm").on('submit', function (e) {

		e.preventDefault()

		var vl = $("#txtSystemNameSystemIddd").val() + "###" + $("#txtUpdateSystemName").val()
		var cm = "ZFZ2eGdheDczcDA3WjFoc005Q3pST0hIVFptMkpMZUg4VmdDaUdQNTNhTT06OozxMDhyuAmfiIA21QRiCLw="
		var tn = "eEhxQ1dvZ3htWFp4WXlLSEJqZG1OVlhvWG9LSG05V0VxdDJXL2dSMTNBVT06OsHloSaFIWAEYhPT44ag91Q="
		var commandType = "update_command"
		var hasFile = "No"
		var objName = "System name"

		var post = {
			"action" : "ins_upd_del_everything", "vl" : vl, "cm" : cm, "hasFile" : hasFile,
			"commandType" : commandType, "tn" : tn, "objName" : objName,
		};

		$.ajax({
			url: "api/main.php", type: "POST", data:  post, dataType: "JSON",
			beforeSend:function(){
				$("#btnUpdateSystemName").prop('disabled', true)
				$("#btnUpdateSystemName").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
			},
			success: function(data) {
				$("#btnUpdateSystemName").prop('disabled', false)
				$("#btnUpdateSystemName").html("<i class='fa fa-lg fa-pencil'></i> Update System Name")
				var Message = data.Message;
				var status = data.Status;
				if (status === true) {		
					swal ({
						title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
					}, function(isConfirm) {
						if (isConfirm) { location.reload() }
					})
				} else {
					Message.forEach(function (error) {
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
					})
				}	
			}, error: function(e) {
				bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
			}          
		})

	})
	
	// ----------------------- Update Sysem FavIcon ---------------------
	$("#updateLoginPageImageForm").on('submit', function (e) {
		e.preventDefault()
		var formData = new FormData(this)
		var vl =  $("#txtLoginPageImageSystemIdd").val()
		var cm = "SjBGOHRubE5Gei9ucG13QVVtQ3ZUWGthSGdvdldKdHVYWWFnajJ6Mitsdz06OqZH1wRhHWzC9X+1+9qzjSg="
		var photoNames = $("#photoUpdateLoginPageImage").val()
		var docNames = ""				// Means no documents in this update
		var hasFile = "Yes"
		var files = "photoUpdateLoginPageImage"
		var tn = "eEhxQ1dvZ3htWFp4WXlLSEJqZG1OVlhvWG9LSG05V0VxdDJXL2dSMTNBVT06OsHloSaFIWAEYhPT44ag91Q="
		var commandType = "update_command"
		var objName = "Login page image"
		formData.append("action", "ins_upd_del_everything")
		formData.append("vl", vl)
		formData.append("cm", cm)
		formData.append("hasFile", hasFile)
		formData.append("files", files)
		formData.append("photoUpdateLoginPageImage", $("#systemLoginPagePhoto")[0].files[0])
		formData.append("photoNames", photoNames)
		formData.append("docNames", docNames)
		formData.append("commandType", commandType)
		formData.append("tn", tn)
		formData.append("objName", objName)

		$.ajax({
			url: "api/main.php", type: "POST", data:  formData, contentType: false, cache: false, processData:false,
			beforeSend:function(){
				$("#btnUpdateLoginPageImage").prop('disabled', true)
				$("#btnUpdateLoginPageImage").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
			},
			success: function(data) {
				$("#btnUpdateLoginPageImage").prop('disabled', false)
				$("#btnUpdateLoginPageImage").html("<i class='fa fa-lg fa-pencil'></i> Update Image")
				var Message = data.Message;
				var status = data.Status;
				if (status == true) {		
					swal ({
						title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
					}, function(isConfirm) {
						if (isConfirm) { location.reload() }
					})
				} else {
					Message.forEach(function (error) {
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
					})
				}	
		 	}, error: function(e) {
				bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
			}          
	   })

	})
	
	
	//================================ End of System Configuraions =================================================
	
    // ============================ START OF EXTREA INFORMATION MODULE SCRIPTS ===================================
    
    // ============================ START OF ADMINISTRATION MENU MODULE SCRIPTS ==================================
    
    // ============================ Start of Payment Gateways Management Section =================================
	
	// Change gateway name label description
	$(document).on("change", "#cmbGatewayType", function () {
		var selectedGatewayType = $(this).val()
		if (selectedGatewayType === "") {
			$("#gatewayNameLabel").html("<span>Gateway Name</span>")
			$("#txtGatewaysGatewayName").attr("placeholder", "Enter gateway name")
		} else if (selectedGatewayType === "1") {
			$("#gatewayNameLabel").html("<span>Bank Name</span>")
			$("#txtGatewaysGatewayName").attr("placeholder", "Enter bank name")
		} else if (selectedGatewayType === "2") {
		    $("#gatewayNameLabel").html("<span>Company Name</span>")
		    $("#txtGatewaysGatewayName").attr("placeholder", "Enter company name")
		} else if (selectedGatewayType === "3") {
		    $("#gatewayNameLabel").html("<span>Description Name</span>")
		    $("#txtGatewaysGatewayName").attr("placeholder", "Enter description name")
		}
    })

	// Register Gateway Modal
	$("#registerPaymentGatewayForm").on('submit', function (e) {
		e.preventDefault()
		var formData = new FormData(this)
		var vl = $("#cmbGatewayType").val() + "###" + $("#txtGatewaysGatewayName").val() + "###" + $("#txtUserrIddd").val() + "###" + $("#txtGatewayRegisterDate").val() + "###" + "-" + "###" + "-"
		var hasFile = "Yes"
		var files = "photoGateway"
		var tn = "NC9UOU0xS1NHS3dGRnJuVzNYZ0ZBNHZKRlQzZHFGLzBNYWh6Q09SLzZoaz06OgqBHhs6/wOOl2QB7FubsRg="
		var commandType = "insert_command"
		var objName = "Payment gateway"
		var objPre = "GTW"
		formData.append("action", "ins_upd_del_everything")
		formData.append("vl", vl)
		formData.append("hasFile", hasFile)
		formData.append("files", files)
		formData.append("photoGateway", $("#gatewayPhoto")[0].files[0])
		formData.append("commandType", commandType)
		formData.append("tn", tn)
		formData.append("objName", objName)
		formData.append("objPre", objPre)
		swal ({
			title: "Are you sure?", text: "You want to register this gateway?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
		}, function(isConfirm) {
			if (isConfirm) {
			    $(".confirm").attr("disabled", "disabled") 
			    $(".confirm").attr("style", "color: #FFF") 
			    $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
				$.ajax({
                    url: "api/main.php", type: "POST", data:  formData, contentType: false, cache: false, processData:false,
					beforeSend:function(){
						$("#btnRegisterGateway").prop('disabled', true)
						$("#btnRegisterGateway").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
					}, success: function(data) {
						$("#btnRegisterGateway").prop('disabled', false)
						$("#btnRegisterGateway").html("<i class='fa fa-lg fa-save'></i> Register Gateway")
						var Message = data.Message
						var status = data.Status
						if (status == true) {		
							swal ({
								title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
							}, function(isConfirm) {
								if (isConfirm) { location.reload() }
							})
						} else {
							Message.forEach(function (error) {
								bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
							})
						}	
					 }, error: function(e) {
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
					}          
			   })
			}
		})
	})

	// Filling Data into Update Gatway Modal
	$(document).on("click", ".btnUpdateGateway", function (e) {
		e.preventDefault()
		var objectID = $(this).attr("data-id")
		var tn = "NC9UOU0xS1NHS3dGRnJuVzNYZ0ZBNHZKRlQzZHFGLzBNYWh6Q09SLzZoaz06OgqBHhs6/wOOl2QB7FubsRg="
		var cm = "Q1VUc245YnBGNi90OGQ3bmVvR3UwUT09OjpcT1AjCFW7uITb/RY1qJOI"
		var post = { "action": "fetch_parameterized_everything", "dn": dn, "tn" : tn, "cm" : cm, "objectID": objectID }
		$(".modal-body").load(objectID)
		$.ajax({
			method: "POST", url: "api/main.php", data:  post, dataType: "JSON",
			success: function(data) {
				var Message = data.Message
				var status = data.Status
				if (status == true) {
					var returned_info = Message.split("###")
					$("#txtGatewayIdd").val(returned_info[1])
					$("#cmbGatewayTypeUp").select2().val(returned_info[2]).trigger('change')
					if (returned_info[2] === '1') {
            			$("#gatewayNameLabelUp").html("<span>Bank Name</span>")
            			$("#txtGatewaysGatewayNameUp").attr("placeholder", "Enter bank name")
            		} else if (returned_info[2] === "2") {
            		    $("#gatewayNameLabelUp").html("<span>Company Name</span>")
            		    $("#txtGatewaysGatewayNameUp").attr("placeholder", "Enter company name")
            		} else if (returned_info[2] === "3") {
            		    $("#gatewayNameLabelUp").html("<span>Description Name</span>")
            		    $("#txtGatewaysGatewayNameUp").attr("placeholder", "Enter description name")
            		}
					$("#txtGatewaysGatewayNameUp").val(returned_info[3])
					$("#gatewayTargetUp").attr("src", returned_info[8])
					$("#photoGatewayUpdate").val(returned_info[8])
				}	
		 	}, error: function(e) {
				bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
			}          
	   })
	})
	
	// Change gateway name label description in the update modal
	$(document).on("change", "#cmbGatewayTypeUp", function () {
		var selectedGatewayType = $(this).val()
		if (selectedGatewayType === "") {
			$("#gatewayNameLabelUp").html("<span>Gateway Name</span>")
			$("#txtGatewaysGatewayNameUp").attr("placeholder", "Enter gateway name")
		} else if (selectedGatewayType === "1") {
			$("#gatewayNameLabelUp").html("<span>Bank Name</span>")
			$("#txtGatewaysGatewayNameUp").attr("placeholder", "Enter bank name")
		} else if (selectedGatewayType === "2") {
		    $("#gatewayNameLabelUp").html("<span>Company Name</span>")
		    $("#txtGatewaysGatewayNameUp").attr("placeholder", "Enter company name")
		} else if (selectedGatewayType === "3") {
		    $("#gatewayNameLabelUp").html("<span>Description Name</span>")
		    $("#txtGatewaysGatewayNameUp").attr("placeholder", "Enter description name")
		}
    })

	// Update Payment Gateway Modal
	$("#updatePaymentGatewayForm").on('submit', function (e) {
		e.preventDefault()
		var formData = new FormData(this)
		var vl =  $("#txtGatewayIdd").val() + "###" + $("#cmbGatewayTypeUp").val() + "###" + $("#txtGatewaysGatewayNameUp").val() + "###" + $("#txtUserrIddd").val() + "###" + $("#txtGatewayUpdateDate").val()
		var cm = "d0MzUnJiV1hIQWwzbnBXRHhucUxiNWpod0ROazlRN0RENXM0NXFudEdQM3pxaFprNkUwSnVTSDljTksya05pSTMrY1NyRWs2RFVBOEVoU0tySXZTNEVnWWppN0dNc08vd1FSRGJTOUVtSmM9OjrCbSWwOInsNFgJjRwX3+99"
		var photoNames = $("#photoGatewayUpdate").val()
		var docNames = ""				// Means no documents in this update
		var hasFile = "Yes"
		var files = "photoGatewayUpdate"
		var tn = "NC9UOU0xS1NHS3dGRnJuVzNYZ0ZBNHZKRlQzZHFGLzBNYWh6Q09SLzZoaz06OgqBHhs6/wOOl2QB7FubsRg="
		var commandType = "update_command"
		var objName = "Payment gateway"
		formData.append("action", "ins_upd_del_everything")
		formData.append("vl", vl)
		formData.append("cm", cm)
		formData.append("hasFile", hasFile)
		formData.append("files", files)
		formData.append("photoGatewayUpdate", $("#gatewayPhotoUp")[0].files[0])
		formData.append("photoNames", photoNames)
		formData.append("docNames", docNames)
		formData.append("commandType", commandType)
		formData.append("tn", tn)
		formData.append("objName", objName)
		swal ({
			title: "Are you sure?", text: "You want to update this gateway?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
		}, function(isConfirm) {
			if (isConfirm) {
			    $(".confirm").attr("disabled", "disabled") 
			    $(".confirm").attr("style", "color: #FFF") 
			    $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
				$.ajax({
                    url: "api/main.php", type: "POST", data:  formData, contentType: false, cache: false, processData:false,
					beforeSend:function(){
						$("#btnUpdateGateway").prop('disabled', true)
						$("#btnUpdateGateway").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
					}, success: function(data) {
						$("#btnUpdateGateway").prop('disabled', false)
						$("#btnUpdateGateway").html("<i class='fa fa-lg fa-pencil'></i> Update Gateway")
						var Message = data.Message
						var status = data.Status
						if (status == true) {		
							swal ({
								title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
							}, function(isConfirm) {
								if (isConfirm) { location.reload() }
							})
						} else {
							Message.forEach(function (error) {
								bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
							})
						}	
					 }, error: function(e) {
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
					}          
			   })
			}
		})

	})

	// Deleting Payment Gateway Data
	$(document).on('click', '.btnDeleteGateway', function(e){
		e.preventDefault()
		const deleteBtnID = $(this).attr("id")
		var vl = $(this).attr("data-id")
		var tn = "NC9UOU0xS1NHS3dGRnJuVzNYZ0ZBNHZKRlQzZHFGLzBNYWh6Q09SLzZoaz06OgqBHhs6/wOOl2QB7FubsRg="
		var cm = "Q1VUc245YnBGNi90OGQ3bmVvR3UwUT09OjpcT1AjCFW7uITb/RY1qJOI"
		var commandType = "delete_command"
		var objName = "Payment gateway"
		var post = {
			"action" : "ins_upd_del_everything", "vl" : vl, "tn" : tn, "cm" : cm, "commandType" : commandType, "objName" : objName,
		}
		swal({
            title: "Are your sure?", text: "You want to delete this permenantly?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
        }, function (isConfirm) {
            if (isConfirm) {
                $.ajax({
                    method: "POST", url: "api/main.php", data: post, dataType: "JSON",
                    success: function (data) {
                        var Message = data.Message
                        var status = data.Status
                        if (status == true) {
                            swal("success", Message, "success")
                            $("#" + deleteBtnID).parents("tr").remove()
                        } else {
                            swal("", Message, "error")
                        }
                    }, error: function (data) { }
                })
            }
        })
	})
	
	// ============================ End of Payment Gateways Management Section ===================================
	
    // ============================ END OF ADMINISTRATION MENU MODULE SCRIPTS ====================================

	// ============================ Start of Identification Document Type Information Section ====================

    // Register New Identification Document Type Page
    $("#addNewIdentificationDocumentTypePageForm").on("submit", function (e) {
        e.preventDefault()
        var vl = $("#txtDocumentNameAddNewIdentificationDocumentTypePage").val() + "###" + $("#txtRegisteredByAddNewIdentificationDocumentTypePage").val() + "###" + $("#txtRegisterDateAddNewIdentificationDocumentTypePage").val() + "###" + "-" + "###" + "-"
        var hasFile = "No"
        var tn = "MkFia2VsaGNsYytPTHMwZC9DU1RyRUprUGNJRHhFbTdaaER4bEowdjFVND06OhRX/pvQhQB0t0/lqQmx1Ho="
        var commandType = "insert_command"
        var objName = "Document type"
        var objPre = "IDT"
        var post = {
            action: "ins_upd_del_everything", vl: vl, hasFile: hasFile, commandType: commandType, tn: tn, objName: objName, objPre: objPre
        }
        
        swal ({
			title: "Are you sure?", text: "You want to register this document type?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
		}, function(isConfirm) {
		    if (isConfirm) {
                $(".confirm").attr("disabled", "disabled")
			    $(".confirm").attr("style", "color: #FFF") 
			    $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
				$.ajax({
					url: "api/main.php", type: "POST", data: post, dataType: "JSON",
					beforeSend:function(){
						$("#btnAddNewIdentificationDocumentTypePage").prop('disabled', true)
						$("#btnAddNewIdentificationDocumentTypePage").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
					}, success: function(data) {
						$("#btnAddNewIdentificationDocumentTypePage").prop('disabled', false)
						$("#btnAddNewIdentificationDocumentTypePage").html("<i class='fa fa-lg fa-save'></i> Register Type")
						var Message = data.Message
						var status = data.Status
						if (status == true) {		
							swal ({
								title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
							}, function(isConfirm) {
								if (isConfirm) { location.reload() }
							})
						} else {
							Message.forEach(function (error) {
								bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
							})
						}	
					 }, error: function(e) {
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
					}          
			   })
			}
		})

    })
    
    // Filling Data into Update Identification Document Type Modal
    $(document).on("click", ".btnUpdateIdentifictionDocumentType", function (e) {
        e.preventDefault()
        var objectID = $(this).attr("data-id")
        var tn = "MkFia2VsaGNsYytPTHMwZC9DU1RyRUprUGNJRHhFbTdaaER4bEowdjFVND06OhRX/pvQhQB0t0/lqQmx1Ho="
        var cm = "bEhhc3pkRjcyRUVPbmZEK3NydkRFdz09OjoTYjfbpmdx4sWPo5E4pxOx"
        var post = { "action": "fetch_parameterized_everything", "dn": dn, "tn": tn, "cm": cm, "objectID": objectID }
        $(".modal-body").load(objectID)
        $.ajax({
            method: "POST", url: "api/main.php", data: post, dataType: "JSON",
            success: function (data) {
                var Message = data.Message
                var status = data.Status
                if (status == true) {
                    var returned_info = Message.split("###")
                    $("#txtDocumentTypeIddUpdateIdentificationDocumentType").val(returned_info[1])
                    $("#txtDocumentTypeNameUpdateIdentificationDocumentType").val(returned_info[2])
                }
            }, error: function (e) {
                bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, { type: "danger", position: "topright", appendType: "append"})
            }
        })
    })

    // Update Identification Document Type Modal
    $("#updateIdentificationDocumentTypeForm").on("submit", function (e) {
        e.preventDefault()
        var vl = $("#txtDocumentTypeIddUpdateIdentificationDocumentType").val() + "###" + $("#txtDocumentTypeNameUpdateIdentificationDocumentType").val() + "###" + $("#txtUpdatedByUpdateIdentificationDocumentType").val() + "###" + $("#txtUpdateDateUpdateIdentificationDocumentType").val()
        var tn = "MkFia2VsaGNsYytPTHMwZC9DU1RyRUprUGNJRHhFbTdaaER4bEowdjFVND06OhRX/pvQhQB0t0/lqQmx1Ho="
        var cm = "RzlYZzhkdVRLaWlNTmFZLzBESGhCa3BjR0J5QUtoVXh3eDcxQXhSL1BmUkpGZE1iWFphU0dUZjVHamJkNU8zTXMxcUZHbEIwSFNzV0c4bGFEZ0hEYUE9PTo61VCvBGI2pbS7eQrqWxKWng=="
        var commandType = "update_command"
        var hasFile = "No"
        var objName = "Document type"
        var post = {
            action: "ins_upd_del_everything", vl: vl, cm: cm, hasFile: hasFile, commandType: commandType, tn: tn, objName: objName
        }
        swal({
            title: "Are your sure?", text: "You want to update this document type?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
        }, function (isConfirm) {
            if (isConfirm) {
                $(".confirm").attr("disabled", "disabled")
			    $(".confirm").attr("style", "color: #FFF") 
			    $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
                $.ajax({
                    url: "api/main.php", type: "POST", data: post, dataType: "JSON",
                    beforeSend: function () {
                        $("#txtUpdateDateUpdateIdentificationDocumentType").prop("disabled", true)
                        $("#txtUpdateDateUpdateIdentificationDocumentType").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
                    }, success: function (data) {
                        $("#txtUpdateDateUpdateIdentificationDocumentType").prop("disabled", false)
                        $("#txtUpdateDateUpdateIdentificationDocumentType").html("<i class='fa fa-pencil'></i> Update Type")
                        var Message = data.Message;
                        var status = data.Status;
                        if (status === true) {
                            swal({
                                title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
                            }, function (isConfirm) {
                                if (isConfirm) { location.reload() }
                            })
                        } else {
                            Message.forEach(function (error) {
                                bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, { type: "danger", position: "topright", appendType: "append"})
                            })
                        }
                    }, error: function (e) {
                        bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, { type: "danger", position: "topright", appendType: "append"})
                    },
                })
            }
        })
    })

    // Delete Identification Document Type Data
    $(document).on('click', '.btnDeleteIdentifictionDocumentType', function (e) {
        e.preventDefault()
        const deleteBtnID = $(this).attr("id")
        var vl = $(this).attr("data-id")
        var tn = "MkFia2VsaGNsYytPTHMwZC9DU1RyRUprUGNJRHhFbTdaaER4bEowdjFVND06OhRX/pvQhQB0t0/lqQmx1Ho="
        var cm = "bEhhc3pkRjcyRUVPbmZEK3NydkRFdz09OjoTYjfbpmdx4sWPo5E4pxOx"
        var commandType = "delete_command"
        var objName = "Document type"
        var post = {
            "action": "ins_upd_del_everything", "vl": vl, "tn": tn, "cm": cm, "commandType": commandType, "objName": objName
        }
        swal({
            title: "Are your sure?", text: "You want to delete this permenantly?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
        }, function (isConfirm) {
            if (isConfirm) {
                $(".confirm").attr("disabled", "disabled")
			    $(".confirm").attr("style", "color: #FFF") 
			    $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
                $.ajax({
                    method: "POST", url: "api/main.php", data: post, dataType: "JSON",
                    success: function (data) {
                        var Message = data.Message
                        var status = data.Status
                        if (status == true) {
                            swal("success", Message, "success")
                            $("#" + deleteBtnID).parents("tr").remove()
                        } else {
                            swal("", Message, "error")
                        }
                    }, error: function (data) { }
                })
            }
        })
    })

    // ============================ End of Identification Document Type Information Section ======================

	// ============================ Start of Department Information Section ======================================

    // Register New Department Page
    $("#addNewDepartmentPageForm").on("submit", function (e) {
        e.preventDefault()
        var vl = $("#txtPositionNameAddNewDepartmentPage").val() + "###" + $("#txtRegisteredByAddNewDepartmentPage").val() + "###" + $("#txtRegisterDateAddNewDepartmentPage").val() + "###" + "-" + "###" + "-"
        var hasFile = "No"
        var tn = "UGRudStLZmtPUTJjVC9sWkoyWVY3Zz09OjoFnwf6Lc/AmXEpjVZk1ega"
        var commandType = "insert_command"
        var objName = "Department"
        var objPre = "DPT"
        var post = {
            action: "ins_upd_del_everything", vl: vl, hasFile: hasFile, commandType: commandType, tn: tn, objName: objName, objPre: objPre
        }
        
        swal ({
			title: "Are you sure?", text: "You want to register this department?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
		}, function(isConfirm) {
		    if (isConfirm) {
			    $(".confirm").attr("disabled", "disabled") 
			    $(".confirm").attr("style", "color: #FFF") 
			    $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
				$.ajax({
					url: "api/main.php", type: "POST", data: post, dataType: "JSON",
					beforeSend:function(){
						$("#btnAddNewDepartmentPage").prop('disabled', true)
						$("#btnAddNewDepartmentPage").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
					}, success: function(data) {
						$("#btnAddNewDepartmentPage").prop('disabled', false)
						$("#btnAddNewDepartmentPage").html("<i class='fa fa-lg fa-save'></i> Register Position")
						var Message = data.Message
						var status = data.Status
						if (status == true) {		
							swal ({
								title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
							}, function(isConfirm) {
								if (isConfirm) { location.reload() }
							})
						} else {
							Message.forEach(function (error) {
								bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
							})
						}	
					 }, error: function(e) {
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
					}          
			   })
			}
		})

    })

    // Filling Data into Update Department Modal
    $(document).on("click", ".btnUpdateDepartment", function (e) {
        e.preventDefault()
        var objectID = $(this).attr("data-id")
        var tn = "UGRudStLZmtPUTJjVC9sWkoyWVY3Zz09OjoFnwf6Lc/AmXEpjVZk1ega"
        var cm = "V0NvclFML3ZNR3VEN0pTNkM2NVpTQT09OjpcNMTI1YgQG7AqLyQE0Qk2"
        var post = { "action": "fetch_parameterized_everything", "dn": dn, "tn": tn, "cm": cm, "objectID": objectID }
        $(".modal-body").load(objectID)
        $.ajax({
            method: "POST", url: "api/main.php", data: post, dataType: "JSON",
            success: function (data) {
                var Message = data.Message
                var status = data.Status
                if (status == true) {
                    var returned_info = Message.split("###")
                    $("#txtDepartmentIddUpdateDepartment").val(returned_info[1])
                    $("#txtDepartmentNameUpdateDepartment").val(returned_info[2])
                }
            }, error: function (e) {
                bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, { type: "danger", position: "topright", appendType: "append"})
            }
        })
    })

    // Update Department Modal
    $("#updateDepartmentForm").on("submit", function (e) {
        e.preventDefault()
        var vl = $("#txtDepartmentIddUpdateDepartment").val() + "###" + $("#txtDepartmentNameUpdateDepartment").val() + "###" + $("#txtUpdatedByUpdateDepartment").val() + "###" + $("#txtUpdateDateUpdateDepartment").val()
        var tn = "UGRudStLZmtPUTJjVC9sWkoyWVY3Zz09OjoFnwf6Lc/AmXEpjVZk1ega"
        var cm = "cHZvRDFiM1hlYmNpdlRuRXp4blBhVFBtOXFWK0dKZ04yWENCVWJSMThSTm1KN09BM29raytTeTkvK2lxQlV0S01LRWdtSnlFL0FCbERCVTNFdXZqSkE9PTo6XZUIJKp70Dy7SDQvuWKPeg=="
        var commandType = "update_command"
        var hasFile = "No"
        var objName = "Department"
        var post = {
            action: "ins_upd_del_everything", vl: vl, cm: cm, hasFile: hasFile, commandType: commandType, tn: tn, objName: objName
        }
        swal({
            title: "Are your sure?", text: "You want to update this department?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
        }, function (isConfirm) {
            if (isConfirm) {
			    $(".confirm").attr("disabled", "disabled") 
			    $(".confirm").attr("style", "color: #FFF") 
			    $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
                $.ajax({
                    url: "api/main.php", type: "POST", data: post, dataType: "JSON",
                    beforeSend: function () {
                        $("#btnUpdateDepartment").prop("disabled", true)
                        $("#btnUpdateDepartment").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
                    }, success: function (data) {
                        $("#btnUpdateDepartment").prop("disabled", false)
                        $("#btnUpdateDepartment").html("<i class='fa fa-pencil'></i> Update Type")
                        var Message = data.Message;
                        var status = data.Status;
                        if (status === true) {
                            swal({
                                title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
                            }, function (isConfirm) {
                                if (isConfirm) { location.reload() }
                            })
                        } else {
                            Message.forEach(function (error) {
                                bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, { type: "danger", position: "topright", appendType: "append"})
                            })
                        }
                    }, error: function (e) {
                        bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, { type: "danger", position: "topright", appendType: "append"})
                    },
                })
            }
        })
    })

    // Delete Department Data
    $(document).on('click', '.btnDeleteDepartment', function (e) {
        e.preventDefault()
        const deleteBtnID = $(this).attr("id")
        var vl = $(this).attr("data-id")
        var tn = "UGRudStLZmtPUTJjVC9sWkoyWVY3Zz09OjoFnwf6Lc/AmXEpjVZk1ega"
        var cm = "V0NvclFML3ZNR3VEN0pTNkM2NVpTQT09OjpcNMTI1YgQG7AqLyQE0Qk2"
        var commandType = "delete_command"
        var objName = "Department"
        var post = {
            "action": "ins_upd_del_everything", "vl": vl, "tn": tn, "cm": cm, "commandType": commandType, "objName": objName
        }
        swal({
            title: "Are your sure?", text: "You want to delete this permenantly?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
        }, function (isConfirm) {
            if (isConfirm) {
			    $(".confirm").attr("disabled", "disabled")
			    $(".confirm").attr("style", "color: #FFF") 
			    $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
                $.ajax({
                    method: "POST", url: "api/main.php", data: post, dataType: "JSON",
                    success: function (data) {
                        var Message = data.Message
                        var status = data.Status
                        if (status == true) {
                            swal("success", Message, "success")
                            $("#" + deleteBtnID).parents("tr").remove()
                        } else {
                            swal("", Message, "error")
                        }
                    }, error: function (data) { }
                })
            }
        })
    })

    // ============================ End of Department Information Section ========================================

    // ============================ Start of Employee Positions Information Section ==============================
  
    // Register New Employee Position Page
    $("#addNewEmployeePositionPageForm").on("submit", function (e) {
        e.preventDefault()
        var vl = $("#txtPositionNameAddNewEmployeePositionPage").val() + "###" + $("#txtRegisteredByAddNewEmployeePositionPage").val() + "###" + $("#txtRegisterDateAddNewEmployeePositionPage").val() + "###" + "-" + "###" + "-"
        var hasFile = "No"
        var tn = "VFJEblJkdHdBbmhhc1VETDRRRUh3NVVsSXk0MnhOY0gvVEo5aW02TkxRST06OoxTo2mka+G+fd6a50P57lM="
        var commandType = "insert_command"
        var objName = "Position"
        var objPre = "PS"
        var post = {
            action: "ins_upd_del_everything", vl: vl, hasFile: hasFile, commandType: commandType, tn: tn, objName: objName, objPre: objPre
        }
        
        swal ({
			title: "Are you sure?", text: "You want to register this position?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
		}, function(isConfirm) {
		    if (isConfirm) {
			    $(".confirm").attr("disabled", "disabled") 
			    $(".confirm").attr("style", "color: #FFF") 
			    $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
				$.ajax({
					url: "api/main.php", type: "POST", data: post, dataType: "JSON",
					beforeSend:function(){
						$("#btnAddNewEmployeePositionPage").prop('disabled', true)
						$("#btnAddNewEmployeePositionPage").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
					}, success: function(data) {
						$("#btnAddNewEmployeePositionPage").prop('disabled', false)
						$("#btnAddNewEmployeePositionPage").html("<i class='fa fa-lg fa-save'></i> Register Position")
						var Message = data.Message
						var status = data.Status
						if (status == true) {		
							swal ({
								title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
							}, function(isConfirm) {
								if (isConfirm) { location.reload() }
							})
						} else {
							Message.forEach(function (error) {
								bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
							})
						}	
					 }, error: function(e) {
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
					}          
			   })
			}
		})

    })

    // Filling Data into Update Employee Position Modal
    $(document).on("click", ".btnUpdateEmployeePosition", function (e) {
        e.preventDefault()
        var objectID = $(this).attr("data-id")
        var tn = "VFJEblJkdHdBbmhhc1VETDRRRUh3NVVsSXk0MnhOY0gvVEo5aW02TkxRST06OoxTo2mka+G+fd6a50P57lM="
        var cm = "KzR6bzNGQUNjYjkzQVR3diswcE10QT09Ojqfm62+RqJtKzSZkEXikM83"
        var post = { "action": "fetch_parameterized_everything", "dn": dn, "tn": tn, "cm": cm, "objectID": objectID }
        $(".modal-body").load(objectID)
        $.ajax({
            method: "POST", url: "api/main.php", data: post, dataType: "JSON",
            success: function (data) {
                var Message = data.Message
                var status = data.Status
                if (status == true) {
                    var returned_info = Message.split("###")
                    $("#txtPositionIddUpdateEmployeePosition").val(returned_info[1])
                    $("#txtPositionNameUpdateEmployeePosition").val(returned_info[2])
                }
            }, error: function (e) {
                bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, { type: "danger", position: "topright", appendType: "append"})
            }
        })
    })

    // Update Employee Position Modal
    $("#updateEmployeePositionForm").on("submit", function (e) {
        e.preventDefault()
        var vl = $("#txtPositionIddUpdateEmployeePosition").val() + "###" + $("#txtPositionNameUpdateEmployeePosition").val() + "###" + $("#txtUpdatedByUpdateEmployeePosition").val() + "###" + $("#txtUpdateDateUpdateEmployeePosition").val()
        var tn = "VFJEblJkdHdBbmhhc1VETDRRRUh3NVVsSXk0MnhOY0gvVEo5aW02TkxRST06OoxTo2mka+G+fd6a50P57lM="
        var cm = "OEdaaXVEcjFkLzJjd1dtdEdrSitnelBtMDYvTHYzUWZBeVhKK0t4ZThYc0xraUhmNGlxaFpZWkJtK2FHbGlaRWJqQWYxZStwaVBiOWljdVJ1SXZCUGc9PTo6skt34F3X2t+agT0BlYV+2Q=="
        var commandType = "update_command"
        var hasFile = "No"
        var objName = "Position"
        var post = {
            action: "ins_upd_del_everything", vl: vl, cm: cm, hasFile: hasFile, commandType: commandType, tn: tn, objName: objName
        }
        swal({
            title: "Are your sure?", text: "You want to update this position?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
        }, function (isConfirm) {
            if (isConfirm) {
			    $(".confirm").attr("disabled", "disabled") 
			    $(".confirm").attr("style", "color: #FFF") 
			    $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
                $.ajax({
                    url: "api/main.php", type: "POST", data: post, dataType: "JSON",
                    beforeSend: function () {
                        $("#btnUpdateEmployeePosition").prop("disabled", true)
                        $("#btnUpdateEmployeePosition").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
                    }, success: function (data) {
                        $("#btnUpdateEmployeePosition").prop("disabled", false)
                        $("#btnUpdateEmployeePosition").html("<i class='fa fa-pencil'></i> Update Type")
                        var Message = data.Message;
                        var status = data.Status;
                        if (status === true) {
                            swal({
                                title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
                            }, function (isConfirm) {
                                if (isConfirm) { location.reload() }
                            })
                        } else {
                            Message.forEach(function (error) {
                                bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, { type: "danger", position: "topright", appendType: "append"})
                            })
                        }
                    }, error: function (e) {
                        bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, { type: "danger", position: "topright", appendType: "append"})
                    },
                })
            }
        })
    })

    // Delete Employee Position Data
    $(document).on('click', '.btnDeleteEmployeePosition', function (e) {
        e.preventDefault()
        const deleteBtnID = $(this).attr("id")
        var vl = $(this).attr("data-id")
        var tn = "VFJEblJkdHdBbmhhc1VETDRRRUh3NVVsSXk0MnhOY0gvVEo5aW02TkxRST06OoxTo2mka+G+fd6a50P57lM="
        var cm = "OEd6ekFVSHpmVXhucE1SblRwVm0xUT09OjqO/fhh57AR01DJnqWqgtLQ"
        var commandType = "delete_command"
        var objName = "Position"
        var post = {"action": "ins_upd_del_everything", "vl": vl, "tn": tn, "cm": cm, "commandType": commandType, "objName": objName}
        swal({
            title: "Are your sure?", text: "You want to delete this permenantly?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
        }, function (isConfirm) {
            if (isConfirm) {
			    $(".confirm").attr("disabled", "disabled") 
			    $(".confirm").attr("style", "color: #FFF") 
			    $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
                $.ajax({
                    method: "POST", url: "api/main.php", data: post, dataType: "JSON",
                    success: function (data) {
                        var Message = data.Message
                        var status = data.Status
                        if (status == true) {
                            swal("success", Message, "success")
                            $("#" + deleteBtnID).parents("tr").remove()
                        } else {
                            swal("", Message, "error")
                        }
                    }, error: function (data) { }
                })
            }
        })
    })

    // ============================ End of Employee Positions Information Section ================================

	// ============================ Start of Working Area Information Section ====================================

	// Register New Working Area Page
	$("#registerNewWorkingAreaForm").on("submit", function (e) {
		e.preventDefault()
		var vl = $("#txtWorkingAreaNameRegisterNewWorkingArea").val() + "###" + $("#txtWorkingAreaDescriptionRegisterNewWorkingArea").val() + "###" + $("#txtRegisteredByRegisterNewWorkingArea").val() + "###" + $("#txtRegisterDateRegisterNewWorkingArea").val() + "###" + "-" + "###" + "-"
		var hasFile = "No"
		var tn = "MGtITEF4Vkg5RXNWY0YvTHJvRkFCZz09OjqjVjV/t8R0+T5J+BenYuzE"
		var commandType = "insert_command"
		var objName = "Working area"
		var objPre = "WAR"
		var post = {action: "ins_upd_del_everything", vl: vl, hasFile: hasFile, commandType: commandType, tn: tn, objName: objName, objPre: objPre}
		swal ({
			title: "Are you sure?", text: "You want to register this area?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
		}, function(isConfirm) {
			if (isConfirm) {
				$(".confirm").attr("disabled", "disabled") 
				$(".confirm").attr("style", "color: #FFF") 
				$(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
				$.ajax({
					url: "api/main.php", type: "POST", data: post, dataType: "JSON",
					beforeSend:function(){
						$("#btnRegisterNewWorkingArea").prop('disabled', true)
						$("#btnRegisterNewWorkingArea").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
					}, success: function(data) {
						$("#btnRegisterNewWorkingArea").prop('disabled', false)
						$("#btnRegisterNewWorkingArea").html("<i class='fa fa-lg fa-save'></i> Register Area")
						var Message = data.Message
						var status = data.Status
						if (status == true) {		
							swal ({
								title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
							}, function(isConfirm) {
								if (isConfirm) location.reload()
							})
						} else {
							Message.forEach(function (error) {
								bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
							})
						}	
					}, error: function(e) {
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
					}          
				})
			}
		})
	})
  
	// Filling Data into Working Area Table Modal
	$(document).on("click", ".btnUpdateWorkingArea", function (e) {
		e.preventDefault()
		var objectID = $(this).attr("data-id")
		var tn = "MGtITEF4Vkg5RXNWY0YvTHJvRkFCZz09OjqjVjV/t8R0+T5J+BenYuzE"
		var cm = "dXZOeUpHclVqbUQzM1FHa25Rck80QT09Ojor2Wr71+sOu5e0oL/zANeY"
		var post = { "action": "fetch_parameterized_everything", "dn": dn, "tn": tn, "cm": cm, "objectID": objectID }
		$(".modal-body").load(objectID)
		$.ajax({
			method: "POST", url: "api/main.php", data: post, dataType: "JSON",
			success: function (data) {
				var Message = data.Message
				var status = data.Status
				if (status == true) {
					var returned_info = Message.split("###")
					$("#txtWorkingAreaIdUpdateWorkingArea").val(returned_info[1])
					$("#txtWorkingAreaNameUpdateWorkingArea").val(returned_info[2])
					$("#txtWorkingAreaDescriptionUpdateWorkingArea").val(returned_info[3])
				}
			}, error: function (e) {
				bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, { type: "danger", position: "topright", appendType: "append"})
			}
		})
	})

	// Update Working Area Modal
	$("#updateWorkingAreaModal").on("submit", function (e) {
		e.preventDefault()
		var vl = $("#txtWorkingAreaIdUpdateWorkingArea").val() + "###" + $("#txtWorkingAreaNameUpdateWorkingArea").val() + "###" + $("#txtWorkingAreaDescriptionUpdateWorkingArea").val() + "###" + $("#txtUpdatedByUpdateWorkingArea").val() + "###" + $("#txtUpdatDateUpdateWorkingArea").val()
		var tn = "MGtITEF4Vkg5RXNWY0YvTHJvRkFCZz09OjqjVjV/t8R0+T5J+BenYuzE"
		var cm = "SGVUdHZmMzllMEZmUytzeWIxbGxMOFRIYVY4YWFkQ3h6YzBib2h0U3lwKzM4dnU1RjJ1RXdKVXZZeGU1M3psTWMwSXppcGgxSDZuWHQ3UW5vbFlxdGg4V1VYSTlHNSs2WUd0cTIweG1pVHA5QWVYRUJwZWN3dFFnUXBYQStxMFo6Oveqr/Q/8/tuuBxhqsm1jUA="
		var commandType = "update_command"
		var hasFile = "No"
		var objName = "Working area"
		var post = {
			action: "ins_upd_del_everything", vl: vl, cm: cm, hasFile: hasFile, commandType: commandType, tn: tn, objName: objName
		}
		swal({
			title: "Are your sure?", text: "You want to update this area?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
		}, function (isConfirm) {
			if (isConfirm) {
				$(".confirm").attr("disabled", "disabled") 
				$(".confirm").attr("style", "color: #FFF") 
				$(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
				$.ajax({
					url: "api/main.php", type: "POST", data: post, dataType: "JSON",
					beforeSend: function () {
						$("#btnUpdateWorkingArea").prop("disabled", true)
						$("#btnUpdateWorkingArea").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
					}, success: function (data) {
						$("#btnUpdateWorkingArea").prop("disabled", false)
						$("#btnUpdateWorkingArea").html("<i class='fa fa-pencil'></i> Update Area")
						var Message = data.Message;
						var status = data.Status;
						if (status === true) {
							swal({
								title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
							}, function (isConfirm) {
								if (isConfirm) { location.reload() }
							})
						} else {
							Message.forEach(function (error) {
								bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, { type: "danger", position: "topright", appendType: "append"})
							})
						}
					}, error: function (e) {
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, { type: "danger", position: "topright", appendType: "append"})
					}
				})
			}
		})
	})

	// Delete Working Area Data
	$(document).on('click', '.btnDeleteWorkingArea', function (e) {
		e.preventDefault()
		const deleteBtnID = $(this).attr("id")
		var vl = $(this).attr("data-id")
		var tn = "MGtITEF4Vkg5RXNWY0YvTHJvRkFCZz09OjqjVjV/t8R0+T5J+BenYuzE"
		var cm = "dXZOeUpHclVqbUQzM1FHa25Rck80QT09Ojor2Wr71+sOu5e0oL/zANeY"
		var commandType = "delete_command"
		var objName = "Working area"
		var post = {"action": "ins_upd_del_everything", "vl": vl, "tn": tn, "cm": cm, "commandType": commandType, "objName": objName}
		swal({
			title: "Are your sure?", text: "You want to delete this permenantly?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
		}, function (isConfirm) {
			if (isConfirm) {
				$(".confirm").attr("disabled", "disabled")
				$(".confirm").attr("style", "color: #FFF") 
				$(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
				$.ajax({
					method: "POST", url: "api/main.php", data: post, dataType: "JSON",
					success: function (data) {
						var Message = data.Message
						var status = data.Status
						if (status == true) {
							swal("success", Message, "success")
							$("#" + deleteBtnID).parents("tr").remove()
						} else {
							swal("", Message, "error")
						}
					}, error: function (data) { }
				})
			}
		})
	})

  	// ============================ End of Working Area Information Section ====================================== 
	
	// ============================ Start of Expense Types Information Section ===================================

	// Register New Expense Type Page
	$("#registerNewExpenseTypeForm").on("submit", function (e) {
		e.preventDefault()
		var vl = $("#txtExpenseTypeNameRegisterNewExpenseType").val() + "###" + $("#txtExpenseTypeDescriptionRegisterNewExpenseType").val() + "###" + $("#txtRegisteredByRegisterNewExpenseType").val() + "###" + $("#txtRegisterDateRegisterNewExpenseType").val() + "###" + "-" + "###" + "-"
		var hasFile = "No"
		var tn = "NlFkNzdnZ0RUQnFWc0Z6RVIwMzY4UT09OjqY9M1TCBlywPuhdVwgqqyn"
		var commandType = "insert_command"
		var objName = "Expense type"
		var objPre = "EXT"
		var post = {action: "ins_upd_del_everything", vl: vl, hasFile: hasFile, commandType: commandType, tn: tn, objName: objName, objPre: objPre}
		swal ({
			title: "Are you sure?", text: "You want to register this expense type?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
		}, function(isConfirm) {
			if (isConfirm) {
				$(".confirm").attr("disabled", "disabled") 
				$(".confirm").attr("style", "color: #FFF") 
				$(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
				$.ajax({
					url: "api/main.php", type: "POST", data: post, dataType: "JSON",
					beforeSend:function(){
						$("#btnRegisterNewExpenseType").prop('disabled', true)
						$("#btnRegisterNewExpenseType").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
					}, success: function(data) {
						$("#btnRegisterNewExpenseType").prop('disabled', false)
						$("#btnRegisterNewExpenseType").html("<i class='fa fa-lg fa-save'></i> Register Type")
						var Message = data.Message
						var status = data.Status
						if (status == true) {		
							swal ({
								title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
							}, function(isConfirm) {
								if (isConfirm) location.reload()
							})
						} else {
							Message.forEach(function (error) {
								bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
							})
						}	
					}, error: function(e) {
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
					}          
				})
			}
		})
	})
  
	// Filling Data into Expense Type Modal
	$(document).on("click", ".btnUpdateExpenseType", function (e) {
		e.preventDefault()
		var objectID = $(this).attr("data-id")
		var tn = "NlFkNzdnZ0RUQnFWc0Z6RVIwMzY4UT09OjqY9M1TCBlywPuhdVwgqqyn"
		var cm = "eEtTakEvZVZ4c2thb3hSaHhWMlVqQT09OjonZTTqmVXqNPVSZWynwh6+"
		var post = { "action": "fetch_parameterized_everything", "dn": dn, "tn": tn, "cm": cm, "objectID": objectID }
		$(".modal-body").load(objectID)
		$.ajax({
			method: "POST", url: "api/main.php", data: post, dataType: "JSON",
			success: function (data) {
				var Message = data.Message
				var status = data.Status
				if (status == true) {
					var returned_info = Message.split("###")
					$("#txtExpenseTypeIdUpdateExpenseType").val(returned_info[1])
					$("#txtExpenseTypeNameUpdateExpenseType").val(returned_info[2])
					$("#txtExpenseTypeDescriptionUpdateExpenseType").val(returned_info[3])
				}
			}, error: function (e) {
				bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, { type: "danger", position: "topright", appendType: "append"})
			}
		})
	})

	// Update Expense Type Modal
	$("#updateExpenseTypeForm").on("submit", function (e) {
		e.preventDefault()
		var vl = $("#txtExpenseTypeIdUpdateExpenseType").val() + "###" + $("#txtExpenseTypeNameUpdateExpenseType").val() + "###" + $("#txtExpenseTypeDescriptionUpdateExpenseType").val() + "###" + $("#txtUpdatedByUpdateExpenseType").val() + "###" + $("#txtUpdateDateUpdateExpenseType").val()
		var tn = "NlFkNzdnZ0RUQnFWc0Z6RVIwMzY4UT09OjqY9M1TCBlywPuhdVwgqqyn"
		var cm = "a0JzU2FSdC9OV2hXVDVKSExNeW1hejZxZURieDhQVVdZUy9POUgwZWdpR2xDWDJVTEpFVm9URDh6STZ6RnltRGpmMWpCK3kwT2ZqQlNoazBxa0lvL0hkNURjVFh3Qk9aeHpiMTB5WUQ4VlVYVWY2QnpEcHpCRzYxa3B3VEhmcUc6Opx6PGX4EmvrTLfgcONKSIw="
		var commandType = "update_command"
		var hasFile = "No"
		var objName = "Expense type"
		var post = {
			action: "ins_upd_del_everything", vl: vl, cm: cm, hasFile: hasFile, commandType: commandType, tn: tn, objName: objName
		}
		swal({
			title: "Are your sure?", text: "You want to update this expense type?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
		}, function (isConfirm) {
			if (isConfirm) {
				$(".confirm").attr("disabled", "disabled") 
				$(".confirm").attr("style", "color: #FFF") 
				$(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
				$.ajax({
					url: "api/main.php", type: "POST", data: post, dataType: "JSON",
					beforeSend: function () {
						$("#btnUpdateExpenseType").prop("disabled", true)
						$("#btnUpdateExpenseType").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
					}, success: function (data) {
						$("#btnUpdateExpenseType").prop("disabled", false)
						$("#btnUpdateExpenseType").html("<i class='fa fa-pencil'></i> Update Type")
						var Message = data.Message;
						var status = data.Status;
						if (status === true) {
							swal({
								title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
							}, function (isConfirm) {
								if (isConfirm) { location.reload() }
							})
						} else {
							Message.forEach(function (error) {
								bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, { type: "danger", position: "topright", appendType: "append"})
							})
						}
					}, error: function (e) {
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, { type: "danger", position: "topright", appendType: "append"})
					}
				})
			}
		})
	})

	// Delete Expense Type Data
	$(document).on('click', '.btnDeleteExpenseType', function (e) {
		e.preventDefault()
		const deleteBtnID = $(this).attr("id")
		var vl = $(this).attr("data-id")
		var tn = "NlFkNzdnZ0RUQnFWc0Z6RVIwMzY4UT09OjqY9M1TCBlywPuhdVwgqqyn"
		var cm = "eEtTakEvZVZ4c2thb3hSaHhWMlVqQT09OjonZTTqmVXqNPVSZWynwh6+"
		var commandType = "delete_command"
		var objName = "Expense type"
		var post = {"action": "ins_upd_del_everything", "vl": vl, "tn": tn, "cm": cm, "commandType": commandType, "objName": objName}
		swal({
			title: "Are your sure?", text: "You want to delete this permenantly?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
		}, function (isConfirm) {
			if (isConfirm) {
				$(".confirm").attr("disabled", "disabled")
				$(".confirm").attr("style", "color: #FFF") 
				$(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
				$.ajax({
					method: "POST", url: "api/main.php", data: post, dataType: "JSON",
					success: function (data) {
						var Message = data.Message
						var status = data.Status
						if (status == true) {
							swal("success", Message, "success")
							$("#" + deleteBtnID).parents("tr").remove()
						} else {
							swal("", Message, "error")
						}
					}, error: function (data) { }
				})
			}
		})
	})

	// ============================ End of Expense Types Information Section =====================================
    
    // ============================ END OF EXTREA INFORMATION MODULE SCRIPTS =====================================

	//================================ Start of Manage Menus =====================================================

	// Save First Generated Menu
	$(document).on("click", ".btnSaveFirstGeneratedMenu", function (e) {
		e.preventDefault()
	    var first_system_menu_name = $(this).parent().parent().parent().find('input:text[id=txtFirstMenuNamesList]').val()
	    var first_system_menu_icon = $(this).parent().parent().parent().find('input:text[id=txtFirstMenuIconsList]').val()
	    var first_system_menu_link = $(this).parent().parent().parent().find('input:text[id=txtFirstMenuLinksList]').val()
		if (first_system_menu_name == "" || first_system_menu_icon == "" || first_system_menu_link == "") {
		    bs4pop.notice("<i class='fa fa-exclamation-triangle'></i> &nbsp; Please fill the empty fields", {type: "warning", position: "topright", appendType: "append"})
		} else {
            var post = {"action" : "register_first_system_menu", "first_system_menu_name" : first_system_menu_name, "first_system_menu_icon": first_system_menu_icon, "first_system_menu_link": first_system_menu_link}
 	        $.ajax({
 				method: "POST", url : "api/main.php", data: post, dataType: "JSON",
 				beforeSend:function(){
    				$(".btnSaveFirstGeneratedMenu").prop('disabled', true)
    				$(".btnSaveFirstGeneratedMenu").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Wait")
    			},
 				success: function(data) {
 					var Message = data.Message
 					var status = data.Status
 					if (data.Status == true) {		
                        $.ajax({
                    		type: "POST", url : "api/main.php", data: {"action" : "display_system_menus"}, dataType: "text",
                    		success : function(response){
                    			$("#displaySystemMenusArea").html(response)
                    			$(".menu_ranking").sortable({
                                    delay: 100, stop: function() {
                                        var allMenuIds = new Array()
                                        $(".menu_ranking > tr").each(function() { allMenuIds.push($(this).attr("menu-id")) })
                                        changeMenuRank(allMenuIds)
                                    }
                                })
                                $(".submenu_ranking").sortable({
                                    delay: 100, stop: function() {
                                        var allSubmenuIds = new Array()
                                        $(".submenu_ranking > tr").each(function() { allSubmenuIds.push($(this).attr("submenu-id")) })
                                        changeSubmenuRank(allSubmenuIds)
                                    }
                                })
                    		},
                    		error : function(response){ }
                    	})
                    	$(".btnSaveFirstGeneratedMenu").prop('disabled', false)
 					    $(".btnSaveFirstGeneratedMenu").html("<i class='fa fa-save'></i> Save Menu")
 					} else {
 						Message.forEach(function (error) {
 							bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
 						})
		 		    }	
		 	    },
 				error : function(data){ }
 			})
		}
	})
	
	// Generate New Menu
	$(document).on("click", "#generateNewMenu", function (e) {
		e.preventDefault()
		$(this).closest('tr').after("<tr>\
                            			<td class='align-middle text-center'></td>\
                            			<td class='align-middle' colspan='3'>\
                            			    <div class='row no-gutters'>\
                                			    <div class='col-md-3 pr-1'><input type='text' class='form-control' name='txtMenuNamesList[]' id='txtMenuNamesList' placeholder='Enter menu name' required /></div>\
                                			    <div class='col-md-4 pr-1'><input type='text' class='form-control' name='txtMenuIconsList[]' id='txtMenuIconsList' placeholder='Enter font awesome icon' required /></div>\
                                			    <div class='col-md-3 pr-1'><input type='text' class='form-control' name='txtMenuLinksList[]' id='txtMenuLinksList' placeholder='Enter menu link (URL)' required /></div>\
                            			        <div class='col-md-2 text-center pr-1'>\
                            			            <span class='btn btn-primary btnSaveGeneratedMenu'><i class='fa fa-save'></i> Save</span>\
                            			            <span class='btn btn-danger btnDeleteGeneratedMenu'><i class='fa fa-trash pl-1'></i></span>\
                            			        </div>\
                            			    </div>\
                                        </td>\
                            		</tr>")
        // Focus the current last generated menu name textbox
        $("input:text[id=txtMenuNamesList]:last").focus()
        $(this).prop("disabled", true)
	})
		
	// Delete Generated Menu
	$(document).on("click", ".btnDeleteGeneratedMenu", function (e) {
		e.preventDefault()
	    $(this).parent().parent().parent().parent().prev('tr').find('span[id=generateNewMenu]').prop("disabled", false)
		$(this).parent().parent().parent().parent().remove()
	})
	
	// Save Generated Menu
	$(document).on("click", ".btnSaveGeneratedMenu", function (e) {
		e.preventDefault()
		// Get the ID of the Previous System Menu
		var prev_menu_id = $(this).closest('tr').prev().attr('menu-id')
	    var system_menu_name = $(this).parent().parent().parent().find('input:text[id=txtMenuNamesList]').val()
	    var system_menu_icon = $(this).parent().parent().parent().find('input:text[id=txtMenuIconsList]').val()
	    var system_menu_link = $(this).parent().parent().parent().find('input:text[id=txtMenuLinksList]').val()
		if (system_menu_name == "" || system_menu_icon == "" || system_menu_link == "") {
		    bs4pop.notice("<i class='fa fa-exclamation-triangle'></i> &nbsp; Please fill the empty fields", {type: "warning", position: "topright", appendType: "append"})
		} else {
            var post = {"action" : "register_new_system_menu", "prev_menu_id": prev_menu_id, "system_menu_name" : system_menu_name, "system_menu_icon": system_menu_icon, "system_menu_link": system_menu_link}
			$.ajax({
				method: "POST", url : "api/main.php", data: post, dataType: "JSON",
			    beforeSend:function(){
    				$(".btnSaveGeneratedMenu").prop("disabled", true)
    				$(".btnSaveGeneratedMenu").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Wait")
    			},
				success: function(data) {
					var Message = data.Message
					var status = data.Status
					if (status == true) {		
						$.ajax({
                    		type: "POST", url : "api/main.php", data: {"action" : "display_system_menus"}, dataType: "text",
                    		success : function(response){
                    			$("#displaySystemMenusArea").html(response)
                    			$(".menu_ranking").sortable({
                                    delay: 100, stop: function() {
                                        var allMenuIds = new Array()
                                        $(".menu_ranking > tr").each(function() { allMenuIds.push($(this).attr("menu-id")) })
                                        changeMenuRank(allMenuIds)
                                    }
                                })
                                $(".submenu_ranking").sortable({
                                    delay: 100, stop: function() {
                                        var allSubmenuIds = new Array()
                                        $(".submenu_ranking > tr").each(function() { allSubmenuIds.push($(this).attr("submenu-id")) })
                                        changeSubmenuRank(allSubmenuIds)
                                    }
                                })
                    		},
                    		error : function(response){ }
                    	})
                    	$(".btnSaveGeneratedMenu").prop('disabled', false)
 			            $(".btnSaveGeneratedMenu").html("<i class='fa fa-save'></i> Save")
					} else {
						Message.forEach(function (error) {
							bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
						})
				    }	
			    },
				error : function(data){ }
			})
		}
	})
	
	// Filling Data into Update Menu Modal
	$(document).on("click", ".btnUpdateMenu", function (e) {
		e.preventDefault()
		var selected_menu_id = $(this).attr("data-id")
		$(".modal-body").load(selected_menu_id)
		$.ajax({
			method: "POST", url: "api/main.php", data:  {"action": "fetch_menu_details", "selected_menu_id": selected_menu_id}, dataType: "JSON",
			success: function(data) {
				var Message = data.Message
				var status = data.Status
				if (status === true) {
				    Message.forEach(function (returned_data, i) {
                        $("#txtMenuIddUpdateMenu").val(returned_data[0])
    					$("#txtMenuNameUpdateMenu").val(returned_data[1])
    					$("#txtMenuIconUpdateMenu").val(returned_data[2])
    					$("#txtMenuLinkUpdateMenu").val(returned_data[3])
					})	
				}	
		 	}, error: function(e) {
				bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
			}          
	   })
	})

	// Update Menu
	$("#updateMenuForm").on('submit', function (e) {
		e.preventDefault()
        var selected_menu_id = $("#txtMenuIddUpdateMenu").val()
		var selected_menu_name = $("#txtMenuNameUpdateMenu").val()
		var selected_menu_icon = $("#txtMenuIconUpdateMenu").val()
		var selected_menu_link = $("#txtMenuLinkUpdateMenu").val()
		var post = {
			"action" : "update_menu_details", "selected_menu_id" : selected_menu_id, "selected_menu_name" : selected_menu_name,
			"selected_menu_icon" : selected_menu_icon, "selected_menu_link": selected_menu_link
		}
		swal ({
			title: "Are you sure?", text: "You want to update this menu ?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No",
			closeOnConfirm: false, closeOnCancel: false
		}, function(isConfirm) {
			if (isConfirm) {
                $(".confirm").attr("disabled", "disabled")
			    $(".confirm").attr("style", "color: #FFF") 
			    $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
			    $.ajax({
				    method: "POST", url : "api/main.php", data: post, dataType: "JSON",
    				beforeSend:function(){
    					$("#btnUpdateMenu").prop('disabled', true)
    					$("#btnUpdateMenu").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
    				},
    				success : function(data) {
    					var Message = data.Message
    					var status = data.Status
    					if (status == true) {
    						swal ({
    							title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: true
    						}, function(isConfirm) {
    							if (isConfirm) { location.reload() }
    						})
    					} else {
    						swal("", Message, "error")
    					}				
    				},
    				error : function(data){ }
    			})
			}
		})
	})
	
	// Delete Menu
    $(document).on('click', '.btnDeleteMenu', function (e) {
        e.preventDefault()
        const deleteBtnID = $(this).attr("id")
        var vl = $(this).attr("data-id")
        var tn = "NlFoRTdjUlRzK2RnNlRoRlZ3ME5uZz09Ojokc8DjuGy1CwKschCkwsw4"
        var cm = "d3UwZ2gvTEVFbjN2bUlFRG90ZzVFQT09Ojr/zyCxBtupfSyvRKnH2fhp"
        var commandType = "delete_command"
        var objName = "Menu"
        var post = {
            "action": "ins_upd_del_everything", "vl": vl, "tn": tn, "cm": cm, "commandType": commandType, "objName": objName
        }
        swal({
            title: "Are your sure?", text: "You want to delete this permenantly?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
        }, function (isConfirm) {
            if (isConfirm) {
                $(".confirm").attr("disabled", "disabled")
			    $(".confirm").attr("style", "color: #FFF") 
			    $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
                $.ajax({
                    method: "POST", url: "api/main.php", data: post, dataType: "JSON",
                    success: function (data) {
                        var Message = data.Message
                        var status = data.Status
                        if (status == true) {
                            swal ({
    							title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: true
    						}, function(isConfirm) {
    							if (isConfirm) { location.reload() }
    						})
                        } else {
                            swal("", Message, "error")
                        }
                    }, error: function (data) { }
                })
            }
        })
    })

	// Save First Generated Submenu For Menus With No Submenu
	$(document).on("click", ".btnSaveFirstGeneratedSubmenu", function (e) {
		e.preventDefault()
	    var parent_menu_id = $(this).parent().parent().parent().parent().parent().parent().parent().parent().attr('menu-id')
	    var first_submenu_menu_name = $(this).parent().parent().parent().find('input:text[id=txtFirstSubmenuNamesList]').val()
	    var first_submenu_menu_icon = $(this).parent().parent().parent().find('input:text[id=txtFirstSubmenuIconsList]').val()
	    var first_submenu_menu_link = $(this).parent().parent().parent().find('input:text[id=txtFirstSubmenuLinksList]').val()
		if (first_submenu_menu_name == "" || first_submenu_menu_icon == "" || first_submenu_menu_link == "") {
		    bs4pop.notice("<i class='fa fa-exclamation-triangle'></i> &nbsp; Please fill the empty fields", {type: "warning", position: "topright", appendType: "append"})
		} else {

            var post = {"action" : "register_first_submenu", "first_submenu_menu_name" : first_submenu_menu_name, "first_submenu_menu_icon": first_submenu_menu_icon, "first_submenu_menu_link": first_submenu_menu_link, "parent_menu_id": parent_menu_id}
			$.ajax({
				method: "POST", url : "api/main.php", data: post, dataType: "JSON",
				beforeSend:function(){
    				$(".btnSaveFirstGeneratedSubmenu").prop('disabled', true)
    				$(".btnSaveFirstGeneratedSubmenu").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Wait")
    			},
				success: function(data) {
					var Message = data.Message
					var status = data.Status
					if (status == true) {		
					    $.ajax({
                    		type: "POST", url : "api/main.php", data: {"action" : "display_system_menus"}, dataType: "text",
                    		success : function(response){
                    			$("#displaySystemMenusArea").html(response)
                    			$(".menu_ranking").sortable({
                                    delay: 100, stop: function() {
                                        var allMenuIds = new Array()
                                        $(".menu_ranking > tr").each(function() { allMenuIds.push($(this).attr("menu-id")) })
                                        changeMenuRank(allMenuIds)
                                    }
                                })
                                $(".submenu_ranking").sortable({
                                    delay: 100, stop: function() {
                                        var allSubmenuIds = new Array()
                                        $(".submenu_ranking > tr").each(function() { allSubmenuIds.push($(this).attr("submenu-id")) })
                                        changeSubmenuRank(allSubmenuIds)
                                    }
                                })
                    		},
                    		error : function(response){ }
                    	})
                    	$(".btnSaveFirstGeneratedSubmenu").prop('disabled', false)
 			            $(".btnSaveFirstGeneratedSubmenu").html("<i class='fa fa-save'></i> Save")
					} else {
						Message.forEach(function (error) {
							bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
						})
				    }	
			    },
				error : function(data){ }
			})
		}
	})
	
	// Generate New Submenu
	$(document).on("click", "#generateNewSubmenu", function (e) {
		e.preventDefault()
		$(this).closest('tr').after("<tr>\
                            			<td class='align-middle' colspan='3'>\
                            			    <div class='row no-gutters'>\
                                			    <div class='col-md-4 pl-5 pr-1'><input type='text' class='form-control' name='txtSubmenuNamesList[]' id='txtSubmenuNamesList' placeholder='Enter submenu name' required /></div>\
                                			    <div class='col-md-3 pr-1'><input type='text' class='form-control' name='txtSubmenuIconsList[]' id='txtSubmenuIconsList' placeholder='Enter fa icon' required /></div>\
                                			    <div class='col-md-3 pr-1'><input type='text' class='form-control' name='txtSubmenuLinksList[]' id='txtSubmenuLinksList' placeholder='Enter submenu link' required /></div>\
                                			    <div class='col-md-2 text-right pr-1'>\
                            			            <span class='btn btn-primary btnSaveGeneratedSubmenu'><i class='fa fa-save pl-1'></i></span>\
                            			            <span class='btn btn-danger btnDeleteGeneratedSubmenu'><i class='fa fa-trash pl-1'></i></span>\
                            			        </div>\
                                		    </div>\
                            		    </td>\
                            		</tr>")
        // Focus the current last generated menu name textbox
        $("input:text[id=txtSubmenuNamesList]:last").focus()        
        $(this).prop("disabled", true)
	})
	
	// Delete Generated Submenu
	$(document).on("click", ".btnDeleteGeneratedSubmenu", function (e) {
		e.preventDefault()
	    $(this).parent().parent().parent().parent().prev('tr').find('span[id=generateNewSubmenu]').prop("disabled", false)
		$(this).parent().parent().parent().parent().remove()
	})
	
	// Save Generated Submenu
	$(document).on("click", ".btnSaveGeneratedSubmenu", function (e) {
		e.preventDefault()
	    var parent_menu_id = $(this).parent().parent().parent().parent().parent().parent().parent().parent().parent().parent().parent().attr('menu-id')
	    var prev_submenu_id = $(this).closest('tr').prev().attr('submenu-id')
	    var submenu_menu_name = $(this).parent().parent().parent().find('input:text[id=txtSubmenuNamesList]').val()
	    var submenu_menu_icon = $(this).parent().parent().parent().find('input:text[id=txtSubmenuIconsList]').val()
	    var submenu_menu_link = $(this).parent().parent().parent().find('input:text[id=txtSubmenuLinksList]').val()
		if (submenu_menu_name == "" || submenu_menu_icon == "" || submenu_menu_link == "") {
		    bs4pop.notice("<i class='fa fa-exclamation-triangle'></i> &nbsp; Please fill the empty fields", {type: "warning", position: "topright", appendType: "append"})
		} else {
            var post = {"action" : "register_new_submenu", "submenu_menu_name" : submenu_menu_name, "submenu_menu_icon": submenu_menu_icon, "submenu_menu_link": submenu_menu_link, "parent_menu_id": parent_menu_id, "prev_submenu_id": prev_submenu_id}
			$.ajax({
				method: "POST", url : "api/main.php", data: post, dataType: "JSON",
				beforeSend:function(){
    				$(".btnSaveGeneratedSubmenu").prop('disabled', true)
    				$(".btnSaveGeneratedSubmenu").html("<i class='fa fa-lg fa-spinner fa-pulse pl-1'></i>")
    			},
				success: function(data) {
					var Message = data.Message
					var status = data.Status
					if (status == true) {		
    					$.ajax({
    					    type: "POST", url : "api/main.php", data: {"action" : "display_system_menus"}, dataType: "text",
                    		success : function(response){
                    			$("#displaySystemMenusArea").html(response)
                    			$(".menu_ranking").sortable({
                                    delay: 100, stop: function() {
                                        var allMenuIds = new Array()
                                        $(".menu_ranking > tr").each(function() { allMenuIds.push($(this).attr("menu-id")) })
                                        changeMenuRank(allMenuIds)
                                    }
                                })
                                $(".submenu_ranking").sortable({
                                    delay: 100, stop: function() {
                                        var allSubmenuIds = new Array()
                                        $(".submenu_ranking > tr").each(function() { allSubmenuIds.push($(this).attr("submenu-id")) })
                                        changeSubmenuRank(allSubmenuIds)
                                    }
                                })
                    		},
                    		error : function(response){ }
                    	})
                    	$(".btnSaveGeneratedSubmenu").prop('disabled', false)
 			            $(".btnSaveGeneratedSubmenu").html("<i class='fa fa-save pl-1'></i>")
					} else {
						Message.forEach(function (error) {
							bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
						})
				    }	
			    },
				error : function(data){ }
			})
		}
	})

	// Filling Data into Update Submenu Modal
	$(document).on("click", ".btnUpdateSubmenu", function (e) {
		e.preventDefault()
		var selected_submenu_id = $(this).attr("data-id")
		$(".modal-body").load(selected_submenu_id)
		$.ajax({
			method: "POST", url: "api/main.php", data:  {"action": "fetch_submenu_details", "selected_submenu_id": selected_submenu_id}, dataType: "JSON",
			success: function(data) {
				var Message = data.Message
				var status = data.Status
				if (status === true) {
				    Message.forEach(function (returned_data, i) {
                        $("#txtSubmenuIddUpdateSubmenu").val(returned_data[0])
    					$("#txtSubmenuNameUpdateSubmenu").val(returned_data[1])
    					$("#txtSubmenuIconUpdateSubmenu").val(returned_data[2])
    					$("#txtSubmenuLinkUpdateSubmenu").val(returned_data[3])
					})	
				}	
		 	}, error: function(e) {
				bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
			}          
	   })
	})

	// Update Submenu
	$("#updateSubmenuForm").on('submit', function (e) {
		e.preventDefault()
        var selected_submenu_id = $("#txtSubmenuIddUpdateSubmenu").val()
		var selected_submenu_name = $("#txtSubmenuNameUpdateSubmenu").val()
		var selected_submenu_icon = $("#txtSubmenuIconUpdateSubmenu").val()
		var selected_submenu_link = $("#txtSubmenuLinkUpdateSubmenu").val()
		var post = {
			"action" : "update_submenu_details", "selected_submenu_id" : selected_submenu_id, "selected_submenu_name" : selected_submenu_name,
			"selected_submenu_icon" : selected_submenu_icon, "selected_submenu_link": selected_submenu_link
		}
		swal ({
			title: "Are you sure?", text: "You want to update this submenu ?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No",
			closeOnConfirm: false, closeOnCancel: false
		}, function(isConfirm) {
			if (isConfirm) {
                $(".confirm").attr("disabled", "disabled")
			    $(".confirm").attr("style", "color: #FFF") 
			    $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
			    $.ajax({
				    method: "POST", url : "api/main.php", data: post, dataType: "JSON",
    				beforeSend:function(){
    					$("#btnUpdateSubmenu").prop('disabled', true)
    					$("#btnUpdateSubmenu").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
    				},
    				success : function(data) {
    					var Message = data.Message
    					var status = data.Status
    					if (status == true) {
    						swal ({
    							title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: true
    						}, function(isConfirm) {
    							if (isConfirm) { location.reload() }
    						})
    					} else {
    						swal("", Message, "error")
    					}				
    				},
    				error : function(data){ }
    			})
			}
		})
	})
	
	// Delete Submenu
    $(document).on('click', '.btnDeleteSubmenu', function (e) {
        e.preventDefault()
        const deleteBtnID = $(this).attr("id")
        var vl = $(this).attr("data-id")
        var tn = "MGhYSk9weFgySDNxSGkzNVB3ZTM5UT09OjoeUHxYJOyoO26CupIchHQk"
        var cm = "dE5NQkVML3N3RlhscGFROXZZTVVpQT09Ojp2QjgPkzdlsFDVJItPmS7Y"
        var commandType = "delete_command"
        var objName = "Submenu"
        var post = {
            "action": "ins_upd_del_everything", "vl": vl, "tn": tn, "cm": cm, "commandType": commandType, "objName": objName
        }
        swal({
            title: "Are your sure?", text: "You want to delete this permenantly?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
        }, function (isConfirm) {
            if (isConfirm) {
                $(".confirm").attr("disabled", "disabled")
			    $(".confirm").attr("style", "color: #FFF") 
			    $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
                $.ajax({
                    method: "POST", url: "api/main.php", data: post, dataType: "JSON",
                    success: function (data) {
                        var Message = data.Message
                        var status = data.Status
                        if (status == true) {
                            swal ({
    							title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: true
    						}, function(isConfirm) {
    							if (isConfirm) { location.reload() }
    						})
                        } else {
                            swal("", Message, "error")
                        }
                    }, error: function (data) { }
                })
            }
        })
    })
    
    // Search Menu or Submenu Live
    // $(document).on("keyup keypress blur change focusout", "#txtSearchMenuOrSubmenu", function (e) {
    $(document).on("keyup", "#txtSearchMenuOrSubmenu", function () {
		var menu_submenu_name = $(this).val()
		if (menu_submenu_name === "") {
		    location.reload()
		} else {
		    var post = { "action": "search_menu_submenu_live", "menu_submenu_name": menu_submenu_name }
    		$.ajax({
    			type: "POST", url: "api/main.php", data: post, dataType: "text",
    			success: function (response) {
    				$(".app-menu").html(response)
    			}
    		})
		}
	})

	//================================ End of Manage Menus =======================================================

	//================================ Start of User Privileges ==================================================
	
	$("#searchUserPrivilegesForm").on('submit', function (e) {
		e.preventDefault()
		var selected_user_id = $("#cmbUserIddSearchUserPrivileges").val()
		var post = {
			"action": "fetch_full_user_privileges", "selected_user_id" : selected_user_id, "dn": dn
		}
		$.ajax({
			type: "POST", url: "api/main.php", data: post, dataType: "text",
			beforeSend:function(){
				$("#btnSearchUserPrivileges").prop('disabled', true)
				$("#btnSearchUserPrivileges").html("<i class='fa fa-spinner fa-pulse' style='font-size: 18px; margin-left: 5px; margin-bottom: 3px;'></i> Please wait")
			},
			success: function (response) {
				$("#btnSearchUserPrivileges").prop('disabled', false)
				$("#btnSearchUserPrivileges").html("<i class='fa fa-search' style='font-size: 18px; margin-left: 5px; margin-bottom: 3px;'></i> Search")
				$("#userPrivilegesSection").html(response)
			}
		})
	})
	
	// Enable/Disable User System Menu
	$(document).on("change", "#cbxEnableDisableUserSystemMenuPrivilege", function() {
		var selected_user_id = $(this).attr('data-src')
		var selected_menu_id = $(this).attr('data-id')
		var user_submenus_list = []
		if ($(this).is(':checked')) {
		    $(this).closest('tr').next('tr').find('input:checkbox[id=cbxEnableDisableUserSubmenuenuPrivilege]').each(function() {
		        if (!$(this).is(':checked')) {
		            user_submenus_list.push($(this).attr("data-id"))
        			$(this).prop("checked", true)
		        }

    		})
			var post = {"action" : "enable_user_system_menu_privilege", "selected_user_id" : selected_user_id, "selected_menu_id": selected_menu_id, "user_submenus_list": user_submenus_list}
			$.ajax({
				method: "POST", url : "api/main.php", data: post, dataType: "JSON",
				success : function(data){
					var Message = data.Message
					var status = data.Status
					if (status == true) {
						bs4pop.notice("<i class='fa fa-check-circle'></i> &nbsp;" + Message, {type: "success", position: "bottomright", appendType: "append"})
					} else { swal("", Message, "error") } 
				},
				error : function(data){ }
			})
		} else {
            $(this).closest('tr').next('tr').find('input:checkbox[id=cbxEnableDisableUserSubmenuenuPrivilege]').each(function(){
    			user_submenus_list.push($(this).attr("data-id"))
    			$(this).prop("checked", false)
    		})			
    		var post = {"action" : "disable_user_system_menu_privilege", "selected_user_id" : selected_user_id, "selected_menu_id": selected_menu_id, "user_submenus_list": user_submenus_list}
			$.ajax({
				method: "POST", url : "api/main.php", data: post, dataType: "JSON",
				success : function(data){
					var Message = data.Message
					var status = data.Status
					if (status == true) {
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + Message, {type: "danger", position: "bottomright", appendType: "append"})
					} else { swal("", Message, "error") } 
				},
				error : function(data){ }
			})
		}
	})
	
	// Enable/Disable User Submenu
	$(document).on("change", "#cbxEnableDisableUserSubmenuenuPrivilege", function() {
		var selected_user_id = $(this).attr('data-src')
		var selected_menu_id = $(this).closest('tr').prev('tr').find('input:checkbox[id=cbxEnableDisableUserSystemMenuPrivilege]').attr('data-id')
		var selected_submenu_id = $(this).attr('data-id')
		if ($(this).is(':checked')) {
		    if ($(this).closest('tr').prev('tr').find('input:checkbox[id=cbxEnableDisableUserSystemMenuPrivilege]').is(':checked')) {
		        var post = {"action" : "enable_user_submenu_privilege", "selected_user_id" : selected_user_id, "selected_menu_id": 0, "selected_submenu_id": selected_submenu_id}
		        $.ajax({
    				method: "POST", url : "api/main.php", data: post, dataType: "JSON",
    				success : function(data){
    					var Message = data.Message
    					var status = data.Status
    					if (status == true) {
    						bs4pop.notice("<i class='fa fa-check-circle'></i> &nbsp;" + Message, {type: "success", position: "bottomright", appendType: "append"})
    					} else { swal("", Message, "error") } 
    				},
    				error : function(data){ }
    			})
		    } else {
		        $(this).closest('tr').prev('tr').find('input:checkbox[id=cbxEnableDisableUserSystemMenuPrivilege]').prop("checked", true)
		        var post = {"action" : "enable_user_submenu_privilege", "selected_user_id" : selected_user_id, "selected_menu_id": selected_menu_id, "selected_submenu_id": selected_submenu_id}
    			$.ajax({
    				method: "POST", url : "api/main.php", data: post, dataType: "JSON",
    				success : function(data){
    					var Message = data.Message
    					var status = data.Status
    					if (status == true) {
    						bs4pop.notice("<i class='fa fa-check-circle'></i> &nbsp;" + Message, {type: "success", position: "bottomright", appendType: "append"})
    					} else { swal("", Message, "error") } 
    				},
    				error : function(data){ }
    			})
		    }
		} else {
			var post = {"action" : "disable_user_submenu_privilege", "selected_user_id" : selected_user_id, "selected_submenu_id": selected_submenu_id}
			$.ajax({
				method: "POST", url : "api/main.php", data: post, dataType: "JSON",
				success : function(data){
					var Message = data.Message
					var status = data.Status
					if (status == true) {
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + Message, {type: "danger", position: "bottomright", appendType: "append"})
					} else { swal("", Message, "error") } 
				},
				error : function(data){ }
			})
		}
	})
	
	// Enable/Disable Full Roles at One Time
	$(document).on("change", "#cbxEnableDisableFullRolesOnce", function () {
		var selected_user_id = $(this).attr('role-userid')
	    var selected_user_roles_list = []
		if ($(this).is(":checked")) {
		    $(".insertUpdateDeleteRoles input:checkbox[id=cbxEnableDisableInsertRole]").prop("checked", true)
		    $(".insertUpdateDeleteRoles input:checkbox[id=cbxEnableDisableUpdateRole]").prop("checked", true)
		    $(".insertUpdateDeleteRoles input:checkbox[id=cbxEnableDisableDeleteRole]").prop("checked", true)
		    $(".insertUpdateDeleteRoles input:checkbox[id=cbxEnableDisableSingleRoleFully]").each(function() {
		        if (!$(this).is(':checked')) {
		            selected_user_roles_list.push($(this).attr("role-name"))
        			$(this).prop("checked", true)
		        }
    		})
            var post = {"action" : "enable_user_role_privileges_once", "selected_user_id" : selected_user_id, "selected_user_roles_list": selected_user_roles_list}
			$.ajax({
				method: "POST", url : "api/main.php", data: post, dataType: "JSON",
				success : function(data){
					var Message = data.Message
					var status = data.Status
					if (status == true) {
						bs4pop.notice("<i class='fa fa-check-circle'></i> &nbsp;" + Message, {type: "success", position: "bottomright", appendType: "append"})
					} else { swal("", Message, "error") } 
				},
				error : function(data){ }
			})
		} else {
		    $(".insertUpdateDeleteRoles input:checkbox[id=cbxEnableDisableInsertRole]").prop("checked", false)
		    $(".insertUpdateDeleteRoles input:checkbox[id=cbxEnableDisableUpdateRole]").prop("checked", false)
		    $(".insertUpdateDeleteRoles input:checkbox[id=cbxEnableDisableDeleteRole]").prop("checked", false)
		    $(".insertUpdateDeleteRoles input:checkbox[id=cbxEnableDisableSingleRoleFully]").each(function() {
		        if ($(this).is(':checked')) {
		            selected_user_roles_list.push($(this).attr("role-name"))
        			$(this).prop("checked", false)
		        }
    		})
            var post = {"action" : "disable_user_role_privileges_once", "selected_user_id" : selected_user_id, "selected_user_roles_list": selected_user_roles_list}
			$.ajax({
				method: "POST", url : "api/main.php", data: post, dataType: "JSON",
				success : function(data){
					var Message = data.Message
					var status = data.Status
					if (status == true) {
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + Message, {type: "danger", position: "bottomright", appendType: "append"})
					} else { swal("", Message, "error") } 
				},
				error : function(data){ }
			})
		}
	})
	
	// Enable/Disable Single Role Fully
	$(document).on("change", "#cbxEnableDisableSingleRoleFully", function () {
		var selected_user_id = $(this).attr('role-userid')
		var selected_user_role_name = $(this).attr('role-name')
		if ($(this).is(":checked")) {
		    $(this).parent('td').next('td').next('td').find('input:checkbox[id=cbxEnableDisableInsertRole]').prop("checked", true)
		    $(this).parent('td').next('td').next('td').next('td').find('input:checkbox[id=cbxEnableDisableUpdateRole]').prop("checked", true)
		    $(this).parent('td').next('td').next('td').next('td').next('td').find('input:checkbox[id=cbxEnableDisableDeleteRole]').prop("checked", true)
            var post = {"action" : "enable_single_user_role_fully", "selected_user_id" : selected_user_id, "selected_user_role_name": selected_user_role_name}
			$.ajax({
				method: "POST", url : "api/main.php", data: post, dataType: "JSON",
				success : function(data){
					var Message = data.Message
					var status = data.Status
					if (status == true) {
						bs4pop.notice("<i class='fa fa-check-circle'></i> &nbsp;" + Message, {type: "success", position: "bottomright", appendType: "append"})
					} else { swal("", Message, "error") } 
				},
				error : function(data){ }
			})
		} else {
            $(this).parent('td').next('td').next('td').find('input:checkbox[id=cbxEnableDisableInsertRole]').prop("checked", false)
		    $(this).parent('td').next('td').next('td').next('td').find('input:checkbox[id=cbxEnableDisableUpdateRole]').prop("checked", false)
		    $(this).parent('td').next('td').next('td').next('td').next('td').find('input:checkbox[id=cbxEnableDisableDeleteRole]').prop("checked", false)
            var post = {"action" : "disable_single_user_role_fully", "selected_user_id" : selected_user_id, "selected_user_role_name": selected_user_role_name}
			$.ajax({
				method: "POST", url : "api/main.php", data: post, dataType: "JSON",
				success : function(data){
					var Message = data.Message
					var status = data.Status
					if (status == true) {
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + Message, {type: "danger", position: "bottomright", appendType: "append"})
					} else { swal("", Message, "error") } 
				},
				error : function(data){ }
			})
		}
	})
	
	// Enable/Disable Single Insert Role
	$(document).on("change", "#cbxEnableDisableInsertRole", function () {
		var selected_user_id = $(this).attr('role-userid')
		var selected_user_role_name = $(this).attr('role-name')
		if ($(this).is(":checked")) {
		    if (!$(this).parent('td').prev('td').prev('td').find('input:checkbox[id=cbxEnableDisableSingleRoleFully]').is(":checked")) {
		        $(this).parent('td').prev('td').prev('td').find('input:checkbox[id=cbxEnableDisableSingleRoleFully]').prop("checked", true)
		        var post = {"action" : "enable_single_insert_role", "selected_user_id" : selected_user_id, "selected_user_role_name": selected_user_role_name}
    			$.ajax({
    				method: "POST", url : "api/main.php", data: post, dataType: "JSON",
    				success : function(data){
    					var Message = data.Message
    					var status = data.Status
    					if (status == true) {
    						bs4pop.notice("<i class='fa fa-check-circle'></i> &nbsp;" + Message, {type: "success", position: "bottomright", appendType: "append"})
    					} else { swal("", Message, "error") } 
    				},
    				error : function(data){ }
    			})
		    } else {
		        var post = {"action" : "enable_single_insert_role", "selected_user_id" : selected_user_id, "selected_user_role_name": selected_user_role_name}
    			$.ajax({
    				method: "POST", url : "api/main.php", data: post, dataType: "JSON",
    				success : function(data){
    					var Message = data.Message
    					var status = data.Status
    					if (status == true) {
    						bs4pop.notice("<i class='fa fa-check-circle'></i> &nbsp;" + Message, {type: "success", position: "bottomright", appendType: "append"})
    					} else { swal("", Message, "error") } 
    				},
    				error : function(data){ }
    			})
		    }
		   
		} else {
		    
	        var post = {"action" : "disable_single_insert_role", "selected_user_id" : selected_user_id, "selected_user_role_name": selected_user_role_name}
			$.ajax({
				method: "POST", url : "api/main.php", data: post, dataType: "JSON",
				success : function(data){
					var Message = data.Message
					var status = data.Status
					if (status == true) {
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + Message, {type: "danger", position: "bottomright", appendType: "append"})
					} else { swal("", Message, "error") } 
				},
				error : function(data){ }
			})

		}
	})
	
	// Enable/Disable Single Update Role
	$(document).on("change", "#cbxEnableDisableUpdateRole", function () {
		var selected_user_id = $(this).attr('role-userid')
		var selected_user_role_name = $(this).attr('role-name')
		if ($(this).is(":checked")) {
		    if (!$(this).parent('td').prev('td').prev('td').prev('td').find('input:checkbox[id=cbxEnableDisableSingleRoleFully]').is(":checked")) {
		        $(this).parent('td').prev('td').prev('td').prev('td').find('input:checkbox[id=cbxEnableDisableSingleRoleFully]').prop("checked", true)
		        var post = {"action" : "enable_single_update_role", "selected_user_id" : selected_user_id, "selected_user_role_name": selected_user_role_name}
    			$.ajax({
    				method: "POST", url : "api/main.php", data: post, dataType: "JSON",
    				success : function(data){
    					var Message = data.Message
    					var status = data.Status
    					if (status == true) {
    						bs4pop.notice("<i class='fa fa-check-circle'></i> &nbsp;" + Message, {type: "success", position: "bottomright", appendType: "append"})
    					} else { swal("", Message, "error") } 
    				},
    				error : function(data){ }
    			})
		    } else {
		        var post = {"action" : "enable_single_update_role", "selected_user_id" : selected_user_id, "selected_user_role_name": selected_user_role_name}
    			$.ajax({
    				method: "POST", url : "api/main.php", data: post, dataType: "JSON",
    				success : function(data){
    					var Message = data.Message
    					var status = data.Status
    					if (status == true) {
    						bs4pop.notice("<i class='fa fa-check-circle'></i> &nbsp;" + Message, {type: "success", position: "bottomright", appendType: "append"})
    					} else { swal("", Message, "error") } 
    				},
    				error : function(data){ }
    			})
		    }
		   
		} else {
		    
	        var post = {"action" : "disable_single_update_role", "selected_user_id" : selected_user_id, "selected_user_role_name": selected_user_role_name}
			$.ajax({
				method: "POST", url : "api/main.php", data: post, dataType: "JSON",
				success : function(data){
					var Message = data.Message
					var status = data.Status
					if (status == true) {
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + Message, {type: "danger", position: "bottomright", appendType: "append"})
					} else { swal("", Message, "error") } 
				},
				error : function(data){ }
			})

		}
	})
	
	// Enable/Disable Single Delete Role
	$(document).on("change", "#cbxEnableDisableDeleteRole", function () {
		var selected_user_id = $(this).attr('role-userid')
		var selected_user_role_name = $(this).attr('role-name')
		if ($(this).is(":checked")) {
		    if (!$(this).parent('td').prev('td').prev('td').prev('td').prev('td').find('input:checkbox[id=cbxEnableDisableSingleRoleFully]').is(":checked")) {
		        $(this).parent('td').prev('td').prev('td').prev('td').prev('td').find('input:checkbox[id=cbxEnableDisableSingleRoleFully]').prop("checked", true)
		        var post = {"action" : "enable_single_delete_role", "selected_user_id" : selected_user_id, "selected_user_role_name": selected_user_role_name}
    			$.ajax({
    				method: "POST", url : "api/main.php", data: post, dataType: "JSON",
    				success : function(data){
    					var Message = data.Message
    					var status = data.Status
    					if (status == true) {
    						bs4pop.notice("<i class='fa fa-check-circle'></i> &nbsp;" + Message, {type: "success", position: "bottomright", appendType: "append"})
    					} else { swal("", Message, "error") } 
    				},
    				error : function(data){ }
    			})
		    } else {
		        var post = {"action" : "enable_single_delete_role", "selected_user_id" : selected_user_id, "selected_user_role_name": selected_user_role_name}
    			$.ajax({
    				method: "POST", url : "api/main.php", data: post, dataType: "JSON",
    				success : function(data){
    					var Message = data.Message
    					var status = data.Status
    					if (status == true) {
    						bs4pop.notice("<i class='fa fa-check-circle'></i> &nbsp;" + Message, {type: "success", position: "bottomright", appendType: "append"})
    					} else { swal("", Message, "error") } 
    				},
    				error : function(data){ }
    			})
		    }
		   
		} else {
		    
	        var post = {"action" : "disable_single_delete_role", "selected_user_id" : selected_user_id, "selected_user_role_name": selected_user_role_name}
			$.ajax({
				method: "POST", url : "api/main.php", data: post, dataType: "JSON",
				success : function(data){
					var Message = data.Message
					var status = data.Status
					if (status == true) {
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + Message, {type: "danger", position: "bottomright", appendType: "append"})
					} else { swal("", Message, "error") } 
				},
				error : function(data){ }
			})

		}
	})
	
	
	// =============================== End of User Privileges ====================================================

	// =============================== Start of Login Process ====================================================
    
    //Direct Login
	$("#loginForm").submit(function (e) {
		e.preventDefault()
		var user_name = $("#user_Name").val()
		var pass_word = $("#pass_Word").val()
		var post = {"action" : "system_login_process" , "user_name" : user_name, "pass_word" : pass_word}
		$.ajax({
			method: "POST", url : "api/main.php", data: post, dataType: "JSON",
			beforeSend:function(){
				$("#loginNow").prop('disabled', true)
				$("#loginNow").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
			},
			success : function(data) {
				$("#loginNow").prop('disabled', false)
				$("#loginNow").html("<i class='fa fa-sign-in fa-lg fa-fw'></i>SIGN IN")
				var Message = data.Message
				var status = data.Status
				if (status == true) {
				    if (Message === "enabled2StepVerifying") {
				        location = "verification"
				    } else {
					    location = Message
				    }
				} else {
					Message.forEach(function (error) {
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
					})
				}	
		 	}, error: function(e) {
				bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
			}      
		})
	})
	
	//Login with Verification
	$("#verificationCodeForm").submit(function (e) {
		e.preventDefault()
		var verify_code = $("#txtVerificationCode").val()
		var post = {"action" : "login_with_2step_verification" , "verify_code" : verify_code}
		$.ajax({
			method: "POST", url : "api/main.php", data: post, dataType: "JSON",
			beforeSend:function(){
				$("#btnVerifyNow").prop('disabled', true)
				$("#btnVerifyNow").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
			},
			success : function(data) {
				$("#btnVerifyNow").prop('disabled', false)
				$("#btnVerifyNow").html("<i class='fa fa-check-circle fa-lg fa-fw'></i>Verify")
				var Message = data.Message
				var status = data.Status
				if (status == true) {
				    location = Message
				} else {
					Message.forEach(function (error) {
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
					})
				}	
		 	}, error: function(e) {
				bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
			}      
		})
	})

    //Resend Verification Code
    $(document).on("click", "#btnResendVerificationCode", function (e) {
		e.preventDefault()
		var post = {"action" : "resend_verification_code"}
		$.ajax({
			method: "POST", url : "api/main.php", data: post, dataType: "JSON",
			beforeSend:function(){
				$("#btnResendVerificationCode").prop('disabled', true)
				$("#btnResendVerificationCode").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
			},
			success : function(data) {
				$("#btnResendVerificationCode").prop('disabled', false)
				$("#btnResendVerificationCode").html("<i class='fa fa-send fa-lg fa-fw'></i>Re-send Code")
				var Message = data.Message
				var status = data.Status
				if (status == true) {
				    //Make the verification code textbox focus
				    $("#txtVerificationCode").val("M-")
					var input = $("#txtVerificationCode")
                    var len = input.val().length
                    input[0].focus()
                    input[0].setSelectionRange(len, len)
					bs4pop.notice("<i class='fa fa-check-circle'></i> &nbsp;" + Message, {type: "success", position: "topright", appendType: "append"})
				} else {
					Message.forEach(function (error) {
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
					})
				}	
		 	}, error: function(e) {
				bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
			}      
		})
	})

	// ============================ End of Login Process ============================================================

	// ============================ Start of Employees Information Section ==========================================
	
	// Register New Employee Modal
    $("#registerNewEmployeeForm").on('submit', function (e) {
	    e.preventDefault()
        var formData = new FormData(this)
		var vl = $("#txtEmployeeNameNewEmployee").val() + "###" + $("#txtBirthPlaceNewEmployee").val() + "###" + $("#txtBirthDateNewEmployee").val() + "###" + $("#cmbEmployeeSexNewEmployee").val() + "###" + $("#cmbMaritalStatusNewEmployee").val() + "###" + $("#cmbIdentificationDocumentTypeNewEmployee").val() + "###" + $("#txtHireDateNewEmployee").val() + "###" + $("#cmbEmployeeDepartmentNameNewEmployee").val() + "###" + $("#cmbEmployeePositionNameNewEmployee").val() + "###" + $("#cmbWorkingAreaNameNewEmployee").val() + "###" + $("#txtEmployeeSalaryNewEmployee").val() + "###" + $("#txtEmployeeHomeAddressNewEmployee").val() + "###" + $("#txtEmployeeMobilePhoneNewEmployee").val() + "###" + $("#txtEmployeeEmailAddressNewEmployee").val() + "###" + $("#txtEmployeeContactPersonNewEmployee").val() + "###" + $("#cmbEmployeeContactPersonRelationshipNewEmployee").val() + "###" + $("#txtEmployeeContactPersonMobilePhoneNewEmployee").val() + "###" + 1 + "###" + $("#txtRegisteredByNewEmployee").val() + "###" + $("#txtRegisterDateNewEmployee").val() + "###" + "-" + "###" + "-"
		var photoNames = $("#photoNewEmployee1").val()
		var docNames = $("#docNewEmployee1").val()
		var hasFile = "Yes"
		var files = "photoNewEmployee1###docNewEmployee1"
		var tn = "S2tLajZpRzNneVFwMVg2M0ladkxWUT09OjqvGV6loHhOl7kpdvi9HGFc"
		var commandType = "insert_command"
		var objName = "Employee"
		var objPre = "EM"
		formData.append("action", "ins_upd_del_everything")
		formData.append("vl", vl)
		formData.append("hasFile", hasFile)
		formData.append("files", files)
		formData.append("photoNewEmployee1", $("#newEmployeePhoto")[0].files[0])
		formData.append("docNewEmployee1", $("#cmbEmployeeIdentificationDocumentNewEmployee")[0].files[0])
		formData.append("photoNames", photoNames)
		formData.append("docNames", docNames)
		formData.append("commandType", commandType)
		formData.append("tn", tn)
		formData.append("objName", objName)
		formData.append("objPre", objPre)
        swal ({
			title: "Are you sure?", text: "You want to register this employee?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
		}, function(isConfirm) {
			if (isConfirm) {
                $(".confirm").attr("disabled", "disabled")
			    $(".confirm").attr("style", "color: #FFF") 
			    $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
			    $.ajax({
                    url: "api/main.php", type: "POST", data:  formData, contentType: false, cache: false, processData:false,
    				beforeSend:function(){
    					$("#btnRegisterNewEmployee").prop('disabled', true)
    					$("#btnRegisterNewEmployee").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
    				}, success: function(data) {
    					$("#btnRegisterNewEmployee").prop('disabled', false)
    					$("#btnRegisterNewEmployee").html("<i class='fa fa-lg fa-save'></i> Register Employee")
    					var Message = data.Message
    					var status = data.Status
    					if (status == true) {		
    						swal ({
    							title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
    						}, function(isConfirm) {
    							if (isConfirm) { location.reload() }
    						})
    					} else {
    						Message.forEach(function (error) {
    							bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
    						})
    					}	
    				 }, error: function(e) {
    					bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
    				}          
    		    })
			}
		})
	})


	// ----------------------- Filling Data into Employee Modal ---------------------
	$(document).on("click", ".btnUpdateEmployee", function (e) {
		e.preventDefault()
		var objectID = $(this).attr("data-id")
		var tn = "S2tLajZpRzNneVFwMVg2M0ladkxWUT09OjqvGV6loHhOl7kpdvi9HGFc"
		var cm = "ZlFzOHVmQ0wrSHlwUmdTRm1OMS96UT09Ojrw4xWCtWhehRjJCIAkN+KQ"
		var post = { "action": "fetch_parameterized_everything", "dn": dn, "tn" : tn, "cm" : cm, "objectID": objectID }
		$(".modal-body").load(objectID)
		$.ajax({
			method: "POST", url: "api/main.php", data:  post, dataType: "JSON",
			success: function(data) {
				var Message = data.Message
				var status = data.Status
				if (status == true) {
					var returned_info = Message.split("###")
					$("#txtEmployeeIddUpdateEmployee").val(returned_info[1])
					$("#txtEmployeeNameUpdateEmployee").val(returned_info[2])
					$("#txtBirthPlaceUpdateEmployee").val(returned_info[3])
					$("#txtBirthDateUpdateEmployee").val(returned_info[4])
					$("#cmbEmployeeSexUpdateEmployee").select2().val(returned_info[5]).trigger('change')
					$("#cmbMaritalStatusUpdateEmployee").select2().val(returned_info[6]).trigger('change')
					$("#cmbIdentificationDocumentTypeUpdateEmployee").select2().val(returned_info[7]).trigger('change')
					$("#txtHireDateUpdateEmployee").val(returned_info[8])
					$("#cmbEmployeeDepartmentNameUpdateEmployee").select2().val(returned_info[9]).trigger('change')
					$("#cmbEmployeePositionNameUpdateEmployee").select2().val(returned_info[10]).trigger('change')
					$("#cmbWorkingAreaNameUpdateEmployee").select2().val(returned_info[11]).trigger('change')
					$("#txtEmployeeSalaryUpdateEmployee").val(returned_info[12])
					$("#txtEmployeeHomeAddressUpdateEmployee").val(returned_info[13])
					$("#txtEmployeeMobilePhoneUpdateEmployee").val(returned_info[14])
					$("#txtEmployeeEmailAddressUpdateEmployee").val(returned_info[15])
					$("#txtEmployeeContactPersonUpdateEmployee").val(returned_info[16])
					$("#cmbEmployeeContactPersonRelationshipUpdateEmployee").select2().val(returned_info[17]).trigger('change')
					$("#txtEmployeeContactPersonMobilePhoneUpdateEmployee").val(returned_info[18])
					$("#updateEmployeePhotoTarget").attr("src", returned_info[24])
					$("#photoUpdateEmployee1").val(returned_info[24])
					$("#docUpdateEmployee1").val(returned_info[25])
				}	
		 	}, error: function(e) {
				bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
			}          
	   })
	})
	
	// ----------------------- Update Employee Modal ---------------------

	$("#updateEmployeeForm").on('submit', function (e) {
		e.preventDefault()
		var formData = new FormData(this)
		var vl = $("#txtEmployeeIddUpdateEmployee").val() + "###" + $("#txtEmployeeNameUpdateEmployee").val() + "###" + $("#txtBirthPlaceUpdateEmployee").val() + "###" + $("#txtBirthDateUpdateEmployee").val() + "###" + $("#cmbEmployeeSexUpdateEmployee").val() + "###" + $("#cmbMaritalStatusUpdateEmployee").val() + "###" + $("#cmbIdentificationDocumentTypeUpdateEmployee").val() + "###" + $("#txtHireDateUpdateEmployee").val() + "###" + $("#cmbEmployeeDepartmentNameUpdateEmployee").val() + "###" + $("#cmbEmployeePositionNameUpdateEmployee").val() + "###" + $("#cmbWorkingAreaNameUpdateEmployee").val() + "###" + $("#txtEmployeeSalaryUpdateEmployee").val() + "###" + $("#txtEmployeeHomeAddressUpdateEmployee").val() + "###" + $("#txtEmployeeMobilePhoneUpdateEmployee").val() + "###" + $("#txtEmployeeEmailAddressUpdateEmployee").val() + "###" + $("#txtEmployeeContactPersonUpdateEmployee").val() + "###" + $("#cmbEmployeeContactPersonRelationshipUpdateEmployee").val() + "###" + $("#txtEmployeeContactPersonMobilePhoneUpdateEmployee").val() + "###" + $("#txtUpdatedByUpdateEmployee").val() + "###" + $("#txtUpdateDateUpdateEmployee").val()
		var tn = "S2tLajZpRzNneVFwMVg2M0ladkxWUT09OjqvGV6loHhOl7kpdvi9HGFc"
        var cm = "VHJSREZnTm9IbUZtanc0NEQ0WWZoNXZBNmthRlhBVUM2WFF6aWcxNVpRNURmQy9tMkVNby9sZnViVG5TWVFCN01hZHVGcUdBbzlEV3g0dm9RczRvZjNjbURTUm5nQVpDaVZZa1Jqd29XWVFsMlVjeVI2cG1LYjVjNE0wdGdqVDQ2WlNSZmROQzRleGMzKysyV2pNMVJoU1ZyYlUzdExMRHZ6YUxGdllSWTNRRkp0QStjSWo2S1Fma013TWxRT3U1U3VQYnlUNFFXMGt4TWRuOUtsM1U2SmRnT2FZM2ZmK0xwYkhTYzNjNTg4OGJGSGJ0a2dUOTY2MEVDWnVmTXJwRnBkKzJRUjFmZkpBYkRwdkRlU1BJNHFKOC90QjYzQ0d5WnpsNHVxVzhJNmxSbFhxRWFySStobFBQTXdHZUZ4eTQ3SGs1MDNhbElHMkloWVM0TlJyeG90VGxPNndrSVUreGFWSStrUXR2WTNrdXJ1b1I3M2NoTkxrRjF6VXE5ZGtyYkREbU5MSTRmalc1ZkZFaFQ0Nzd2NHhPUTBtZkNiMisrSUFid3BLaGdwK3dCRisrN1J5cHNkN25CZlZsQlFVQ1MrK21FK1Nvc096MjY4Qkhaa3o2L0gva3gvUHJQbjhuS2QrUm4vemNlZDFVaENqYm1zdXVpRkg5QlQzWkpXTFdLVFAvck9kM3hJMVlpc05pendNZVNuNmw3azZnWVBWMDVwNXo5OGVhZGFJPTo6NW6PVhYRqax2lyZKZ/Hw5g=="
		var photoNames = $("#photoUpdateEmployee1").val()
		var docNames = $("#docUpdateEmployee1").val()
		var hasFile = "Yes"
		var files = "photoUpdateEmployee1###docUpdateEmployee1"
		var commandType = "update_command"
		var objName = "Employee"
		formData.append("action", "ins_upd_del_everything")
		formData.append("vl", vl)
		formData.append("cm", cm)
		formData.append("hasFile", hasFile)
		formData.append("files", files)
		formData.append("photoUpdateEmployee1", $("#updateEmployeePhoto")[0].files[0])
		formData.append("docUpdateEmployee1", $("#txtEmployeeIdentificationDocumentUpdateEmployee")[0].files[0])
		formData.append("photoNames", photoNames)
		formData.append("docNames", docNames)
		formData.append("commandType", commandType)
		formData.append("tn", tn)
		formData.append("objName", objName)
		swal ({
			title: "Are you sure?", text: "You want to update this employee?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
		}, function(isConfirm) {
			if (isConfirm) {
                $(".confirm").attr("disabled", "disabled")
			    $(".confirm").attr("style", "color: #FFF") 
			    $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
				$.ajax({
                    url: "api/main.php", type: "POST", data:  formData, contentType: false, cache: false, processData:false,
					beforeSend:function(){
						$("#btnUpdateEmployee").prop('disabled', true)
						$("#btnUpdateEmployee").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
					}, success: function(data) {
						$("#btnUpdateEmployee").prop('disabled', false)
						$("#btnUpdateEmployee").html("<i class='fa fa-lg fa-pencil'></i> Update Employee")
						var Message = data.Message
						var status = data.Status
						if (status == true) {		
							swal ({
								title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
							}, function(isConfirm) {
								if (isConfirm) { location.reload() }
							})
						} else {
							Message.forEach(function (error) {
								bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
							})
						}	
					 }, error: function(e) {
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
					}          
			    })
			}
		})
	
	})
	
	// Deleting User Data
	$(document).on('click', '.btnDeleteEmployee', function(e){
		e.preventDefault()
		const deleteBtnID = $(this).attr("id")
		var vl = $(this).attr("data-id")
		var tn = "S2tLajZpRzNneVFwMVg2M0ladkxWUT09OjqvGV6loHhOl7kpdvi9HGFc"
		var cm = "ZlFzOHVmQ0wrSHlwUmdTRm1OMS96UT09Ojrw4xWCtWhehRjJCIAkN+KQ"
		var commandType = "delete_command"
		var objName = "Employee"
		var post = { "action" : "ins_upd_del_everything", "vl" : vl, "cm" : cm, "tn" : tn, "commandType" : commandType, "objName" : objName }
		swal ({
			title: "Are you sure?", text: "You want to delete this permenantly?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
		}, function(isConfirm) {
			if (isConfirm) {
                $(".confirm").attr("disabled", "disabled")
			    $(".confirm").attr("style", "color: #FFF") 
			    $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
			    $.ajax({    
					method: "POST", url : "api/main.php", data: post, dataType: "JSON",
					success : function(data){
						var Message = data.Message
						var status = data.Status
						if (status == true) {
							swal("", Message, "success")
							$("#" + deleteBtnID).parents("tr").remove()
                        } else { swal("", Message, "error") }
					},
					error : function(data){ }
				})
			}
		})
	})


	// ============================ End of Employees Information Section ========================================

	// ============================ Start of Users Information Section ==========================================

	$("#registerUserForm").on('submit', function (e) {
		e.preventDefault()
		var vl = $("#cmbFullNameRegisterUser").val() + "###" + $("#txtUsernameRegisterUser").val() + "###" + $("#txtPasscodeRegisterUser").val() + "###" + $("#cmbEnableDisable2StepVerificationRegisterUser").val() + "###" + "M-000000" + "###" + "0" + "###" + $("#txtRegisteredByRegisterUser").val() + "###" + $("#txtRegisterDateRegisterUser").val() + "###" + "-" + "###" + "-"
		var hasFile = "No"
		var tn = "d0p4eGp2N0hBR3BNRC9iTlVqWWlNdz09OjpAe/3KisGcxd2YUmX8Zu4n"
		var commandType = "insert_command"
		var objName = "System user"
		var objPre = "US"
		var post = {
			"action" : "ins_upd_del_everything", "vl" : vl, "hasFile" : hasFile, "commandType" : commandType, "dn": dn, "tn" : tn, "objName" : objName, "objPre" : objPre
		}
		swal ({
			title: "Are you sure?", text: "You want to register this system user?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
		}, function(isConfirm) {
			if (isConfirm) {
                $(".confirm").attr("disabled", "disabled")
			    $(".confirm").attr("style", "color: #FFF") 
			    $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
				$.ajax({
			        url: "api/main.php", type: "POST", data:  post, dataType: "JSON",
					beforeSend:function(){
						$("#btnRegisterUser").prop('disabled', true)
						$("#btnRegisterUser").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
					}, success: function(data) {
						$("#btnRegisterUser").prop('disabled', false)
						$("#btnRegisterUser").html("<i class='fa fa-lg fa-save'></i> Register User")
						var Message = data.Message
						var status = data.Status
						if (status == true) {		
							swal ({
								title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
							}, function(isConfirm) {
								if (isConfirm) { location.reload() }
							})
						} else {
							Message.forEach(function (error) {
								bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
							})
						}	
					 }, error: function(e) {
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
					}          
			   })
			}
		})
	})

	// ------------------- Filling Data into Users Modal -------------------------
	$(document).on("click", ".btnUpdateUser", function (e) {
		e.preventDefault()
		var objectID = $(this).attr("data-id")

		var tn = "ajJwTTRjOWUvRHdEYzlDcXRKOWprdz09OjpmCAxHyW4T/Pg/e+Nh3vJd"
		var cm = "U1NjMVFwVVBuYjV0aU84TDhTbTVKZz09OjrOSxTCFzhU2hQWFoUwVft+"
		var post = { "action": "fetch_parameterized_everything", "dn": dn, "tn" : tn, "cm" : cm, "objectID": objectID }
		$(".modal-body").load(objectID)
		$.ajax({
			method: "POST", url: "api/main.php", data:  post, dataType: "JSON",
			success: function(data) {
				var Message = data.Message
				var status = data.Status
				if (status == true) {
					var returned_info = Message.split("###")
				// 	document.getElementById("selectempup").style.display="block"
				// 	document.getElementById("selectstudentup").style.display="none"
				// 	document.getElementById("selectparup").style.display="none"
					$("#empUserIDUp").val(returned_info[1])
					$("#userEmpIDUp").select2().val(returned_info[2]).trigger('change')
					$("#userNameUp").val(returned_info[4])
					$("#passWordUp").val(returned_info[5])
					$("#cmb2StepVerificationUp").select2().val(returned_info[6]).trigger('change')
				}	
		 	}, error: function(e) {
				bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
			}          
	   })
	})



	// ----------------------- Update User Modal ---------------------

	$("#updateUserFormsadmin").on('submit', function (e) {
		e.preventDefault()
	var vl = $("#empUserIDUp").val() + "###"
		 + $("#userEmpIDUp").val() + "###"
		  + $("#userNameUp").val() + "###" +
		 $("#passWordUp").val() + "###" 
		 + $("#cmb2StepVerificationUp").val()+ "###"
		  + $("#txtUserrIddd").val() + "###" + 
		  $("#registerDate").val()
		var cm = "NHFWSENZN1RFengxMkhmU3hJZVNjcEwzM0d6K0p1UndHMTRIYUdGdnNDNVdOak84a1ZqWmJOVTN0dW9qa1pmdXpScWx0TTFTcVAySmltaUgwRUVPSFZVeURpUWNKRDlWR09JN0hoaDVpMUZ0T3ErbzNYaVJDY3Nkd3N1NHhGTnY6OrvxAAFcvCFWbzttC/NxqzE="
		var hasFile = "No"
		var tn = "WkpyWFh0eVdDUXIrc0Q5VGo5dEpCdz09OjoFI4/87JExUB7/yGHukP2H"
		var commandType = "update_command"
		var objName = "User"
		var post = {
			"action" : "ins_upd_del_everything", "vl" : vl, "cm" : cm, "hasFile" : hasFile,
			"commandType" : commandType, "tn" : tn, "objName" : objName,
		}
		$.ajax({
			url: "api/main.php", type: "POST", data:  post, dataType: "JSON",
			beforeSend:function(){
				$("#updateUser").prop('disabled', true)
				$("#updateUser").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
			},
			success: function(data) {
				$("#updateUser").prop('disabled', false)
				$("#updateUser").html("<i class='fa fa-lg fa-pencil'></i> Update User")
				var Message = data.Message
				var status = data.Status
				if (status == true) {		
					swal ({
						title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
					}, function(isConfirm) {
						if (isConfirm) { location.reload() }
					})
				} else {
					Message.forEach(function (error) {
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
					})
				}	
		 	}, error: function(e) {
				bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
			}          
	    })


	
	
	})

	// Deleting User Data
	$(document).on('click', '.btnDeleteUser', function(e){
		e.preventDefault()
		const deleteBtnID = $(this).attr("id")
		var vl = $(this).attr("data-id")
		var cm = "MU1jblB5aWpHbVZ1K21tdlQ2UitDZz09OjogoLpCwOglDjCVExm55koz"
		var tn = "d0p4eGp2N0hBR3BNRC9iTlVqWWlNdz09OjpAe/3KisGcxd2YUmX8Zu4n"
		var commandType = "delete_command"
		var objName = "User"
		var post = { "action" : "ins_upd_del_everything", "vl" : vl, "cm" : cm, "tn" : tn, "commandType" : commandType, "objName" : objName }
		swal ({
			title: "Are you sure?", text: "You want to delete this permenantly?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
		}, function(isConfirm) {
			if (isConfirm) {
			    $(".confirm").attr("disabled", "disabled")
			    $(".confirm").attr("style", "color: #FFF") 
			    $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
			    $.ajax({    
					method: "POST", url : "api/main.php", data: post, dataType: "JSON",
					success : function(data){
						var Message = data.Message
						var status = data.Status
						if (status == true) {
							swal("", Message, "success")
							$("#" + deleteBtnID).parents("tr").remove()
                        } else { swal("", Message, "error") }
					},
					error : function(data){ }
				})
			}
		})
	})

	// ============================ End of Users Information Section ============================================

	// ============================ Start of Bank Accounts Management Section ===================================
	
	// Account type change 
    $("#cmbAccountNumbersAccountType").change(function () {
        var selectedAccountType = $(this).val()
		if (selectedAccountType == "") {
			$("#cmbAccountNumbersGatewayName").select2().val("").trigger('change')
			$("#bankAccountNameLabel").html("")
			$("#txtAccountNumbersAccountName").attr("placeholder", "Enter account name")
		} else {

			var post = {"action" : "fetch_gateway_name_data" , "selectedAccountType" : selectedAccountType }
			//Fetch the data of the selected employee using the above thisEmp variable
			$.ajax({
				method: "POST", url : "api/main.php", data: post, dataType: "JSON",
				success : function(data){
					var Message = data.Message
					var status = data.Status
					var html = '';
					if(status == true) {
					    if (selectedAccountType == "1") {
                			$("#accountGatewayNameLabel").html("<span>Bank Name</span>")
                			$("#bankAccountNameLabel").html("<span>Bank Account Name</span>")
                			$("#txtAccountNumbersAccountName").attr("placeholder", "Enter bank account name")
                			 $("#bankAccountNumberLabel").html("<span>Bank Account Number</span>")
                			$("#txtAccountNumbersAccountNumber").attr("placeholder", "Enter bank account number")
                			
                			html += `<option value="">Select Bank Name</option>`
            				Message.forEach(function(fetched_gateway_result, i){
            					html += `<option value="${fetched_gateway_result['gatewayID']}">${fetched_gateway_result['gatewayName']}</option>`
            				})
            				
                		} else if (selectedAccountType == "2") {
                		    $("#accountGatewayNameLabel").html("<span>Company Name</span>")
                			$("#bankAccountNameLabel").html("<span>Payment Type</span>")
                			$("#txtAccountNumbersAccountName").attr("placeholder", "Example: evc plus, e-dahab, merchant")
                			$("#bankAccountNumberLabel").html("<span>Payment Number</span>")
                		    $("#txtAccountNumbersAccountNumber").attr("placeholder", "Enter mobile or merchant number")
                		    
                		    html += `<option value="">Select Company Name</option>`
            				Message.forEach(function(fetched_gateway_result, i){
            					html += `<option value="${fetched_gateway_result['gatewayID']}">${fetched_gateway_result['gatewayName']}</option>`
            				})
            				
                		} else if (selectedAccountType == "3") {
                		    $("#accountGatewayNameLabel").html("<span>Payment Type</span>")
                		    $("#txtAccountNumbersAccountName").val("Cash Account")
                			$("#bankAccountNameLabel").html("<span>Cash Account Name</span>")
                			$("#txtAccountNumbersAccountName").attr("placeholder", "Ex: evc, e-bahab, merchant")
                			$("#bankAccountNumberLabel").html("<span>Cash Account Number</span>")
                			$("#txtAccountNumbersAccountNumber").val("10000001")

                            Message.forEach(function(fetched_gateway_result, i){
            					html += `<option value="${fetched_gateway_result['gatewayID']}">${fetched_gateway_result['gatewayName']}</option>`
            				})            				
                		} 
					    
        				$("#cmbAccountNumbersGatewayName").html(html) 
					}
				},
				error : function(data){ }
			})
		}
    })

	// Register New Account Number
	$("#addNewkAccountNumberForm").on("submit", function (e) {
		e.preventDefault()
		var vl = $("#cmbAccountNumbersGatewayName").val() + "###" + $("#txtAccountNumbersAccountName").val() + "###" + $("#txtAccountNumbersAccountNumber").val() + "###" + $("#txtBankAccountNumberOpenningBalance").val() + "###" + $("#txtUserrIddd").val() + "###" + $("#txtBankAccountRegisterDate").val() + " 00:00:00" + "###" + "-" + "###" + "-"
		var hasFile = "No"
		var tn = "N1d0VzE5Z0h5RlBFWGQvREIreVJmQT09Ojq7/V46Voj6xnLwkjydURKc"
		var commandType = "insert_command"
		var objName = "Account number"
		var objPre = "ACC"
		var post = {"action": "ins_upd_del_everything", "vl": vl, "hasFile": hasFile, "commandType": commandType, "tn": tn, "objName": objName, "objPre": objPre}
		swal ({
			title: "Are you sure?", text: "You want to register this account number?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
		}, function(isConfirm) {
		if (isConfirm) {
			$(".confirm").attr("disabled", "disabled") 
			$(".confirm").attr("style", "color: #FFF") 
			$(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
			$.ajax({
			url: "api/main.php", type: "POST", data: post, dataType: "JSON",
			beforeSend:function(){
				$("#btnRegisterAccountNumber").prop('disabled', true)
				$("#btnRegisterAccountNumber").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
			}, success: function(data) {
				$("#btnRegisterAccountNumber").prop('disabled', false)
				$("#btnRegisterAccountNumber").html("<i class='fa fa-lg fa-save'></i> Register Account Number")
				var Message = data.Message
				var status = data.Status
				if (status == true) {		
				swal ({
					title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
				}, function(isConfirm) {
					if (isConfirm) location.reload()
				})
				} else {
				Message.forEach(function (error) {
					bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
				})
				}	
			}, error: function(e) {
				bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
			}          
			})
		}
		})
	
	})

	// Delete Account Number Data
	$(document).on('click', '.btnDeleteAccountNumber', function (e) {
		e.preventDefault()
		const deleteBtnID = $(this).attr("id")
		var vl = $(this).attr("data-id")
		var tn = "N1d0VzE5Z0h5RlBFWGQvREIreVJmQT09Ojq7/V46Voj6xnLwkjydURKc"
		var cm = "dm5DQVlhK3hIZlR3QkhwRHdUNXZHUT09OjqsBH51E9zHsgRfEfMR1qk2"
		var commandType = "delete_command"
		var objName = "Account number"
		var post = {"action": "ins_upd_del_everything", "vl": vl, "tn": tn, "cm": cm, "commandType": commandType, "objName": objName}
		swal({
		title: "Are your sure?", text: "You want to delete this permenantly?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
		}, function (isConfirm) {
		if (isConfirm) {
			$(".confirm").attr("disabled", "disabled")
			$(".confirm").attr("style", "color: #FFF") 
			$(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
			$.ajax({
			method: "POST", url: "api/main.php", data: post, dataType: "JSON",
			success: function (data) {
				var Message = data.Message
				var status = data.Status
				if (status == true) {
					swal("success", Message, "success")
					$("#" + deleteBtnID).parents("tr").remove()
				} else {
					swal("", Message, "error")
				}
			}, error: function (data) { }
			})
		}
		})
	})


	// ============================ End of Bank Account Number Management Section ===============================

	// ============================ Start of Account Association Management Section =============================
	
	// Search User Associated Accounts
	$("#searchUsersForAccountAssociationForm").on('submit', function (e) {
		e.preventDefault()
		var selected_user_id = $("#cmbUserIddSearchUsersForAccountAssociation").val()
		var post = {"action": "fetch_user_associated_account_numbers", "selected_user_id" : selected_user_id, "dn": dn}
		$.ajax({
			type: "POST", url: "api/main.php", data: post, dataType: "text",
			beforeSend:function(){
				$("#btnSearchUsersForAccountAssociation").prop('disabled', true)
				$("#btnSearchUsersForAccountAssociation").html("<i class='fa fa-spinner fa-pulse'></i> Please wait")
			},
			success: function (response) {
				$("#btnSearchUsersForAccountAssociation").prop('disabled', false)
				$("#btnSearchUsersForAccountAssociation").html("<i class='fa fa-search'></i> Search")
				$("#userAssociatedAccountNumbersSection").html(response)
			}
		})
	})

	// Associate/Dissociate User Full Account NUmber
	$(document).on("change", ".cbxAssociateDissociateFullAcountNumber", function() {
		var selected_user_id = $(this).attr('data-src')
		var selected_account_id = $(this).attr('data-id')
		// alert("User ID: " + selected_user_id + " ---- Account Number: " + selected_account_id)
		// Get this accounts deposit and withdrawal account checkbox id
		var account_deposit_checkbox_id = $(this).parent().parent().parent().parent().find(".accountDepositTransaction").attr("id")
		var account_withdrawal_checkbox_id = $(this).parent().parent().parent().parent().find(".accountWithdrawalTransaction").attr("id")
		if ($(this).is(':checked')) {
			var post = {"action" : "associate_user_with_account_number_fully", "selected_user_id" : selected_user_id, "selected_account_id": selected_account_id}
			$.ajax({
				method: "POST", url : "api/main.php", data: post, dataType: "JSON",
				success : function(data){
					var Message = data.Message
					var status = data.Status
					if (status == true) {
						$("#" + account_deposit_checkbox_id).attr("checked", true)
						$("#" + account_withdrawal_checkbox_id).attr("checked", true)
						bs4pop.notice("<i class='fa fa-check-circle'></i> &nbsp;" + Message, {type: "success", position: "bottomright", appendType: "append"})
					} else { swal("", Message, "error") } 
				},
				error : function(data){ }
			})
		} else {
			var post = {"action" : "disssociate_user_with_account_number_fully", "selected_user_id" : selected_user_id, "selected_account_id": selected_account_id}
			$.ajax({
				method: "POST", url : "api/main.php", data: post, dataType: "JSON",
				success : function(data){
					var Message = data.Message
					var status = data.Status
					if (status == true) {
						$("#" + account_deposit_checkbox_id).attr("checked", false)
						$("#" + account_withdrawal_checkbox_id).attr("checked", false)
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + Message, {type: "danger", position: "bottomright", appendType: "append"})
					} else { swal("", Message, "error") } 
				},
				error : function(data){ }
			})
		}
	})

	// Associate/Dissociate User to Deposit Account Number
	$(document).on("change", ".accountDepositTransaction", function() {
		var selected_user_id = $(this).attr('data-src')
		var selected_account_id = $(this).attr('data-id')
		// Get parent account number
		var account_withdrawal_checkbox_id = $(this).parent().parent().parent().parent().find(".accountWithdrawalTransaction").attr("id")
		var parent_account_checkbox_id = $(this).parent().parent().parent().parent().parent().find(".cbxAssociateDissociateFullAcountNumber").attr("id")

		// Get this accounts deposit account checkbox id
		var account_deposit_checkbox_id = $(this).attr("id")
		if ($(this).is(':checked')) {
			var post = {"action" : "associate_user_with_deposit_account_number_only", "selected_user_id" : selected_user_id, "selected_account_id": selected_account_id}
			$.ajax({
				method: "POST", url : "api/main.php", data: post, dataType: "JSON",
				success : function(data){
					var Message = data.Message
					var status = data.Status
					if (status == true) {
						$("#" + account_deposit_checkbox_id).attr("checked", true)
						$("#" + parent_account_checkbox_id).attr("checked", true)
						bs4pop.notice("<i class='fa fa-check-circle'></i> &nbsp;" + Message, {type: "success", position: "bottomright", appendType: "append"})
					} else { swal("", Message, "error") } 
				},
				error : function(data){ }
			})
		} else {
			var post = {"action" : "dissociate_user_with_deposit_account_number_only", "selected_user_id" : selected_user_id, "selected_account_id": selected_account_id}
			$.ajax({
				method: "POST", url : "api/main.php", data: post, dataType: "JSON",
				success : function(data){
					var Message = data.Message
					var status = data.Status
					if (status == true) {
						if (!$("#" + account_withdrawal_checkbox_id).is(':checked')) {
							$("#" + account_deposit_checkbox_id).attr("checked", false)
							$("#" + parent_account_checkbox_id).attr("checked", false)
						}
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + Message, {type: "danger", position: "bottomright", appendType: "append"})
					} else { swal("", Message, "error") } 
				},
				error : function(data){ }
			})
		}
	})

	// Associate/Dissociate User to Withdrawal Account Number
	$(document).on("change", ".accountWithdrawalTransaction", function() {
		var selected_user_id = $(this).attr('data-src')
		var selected_account_id = $(this).attr('data-id')
		// Get parent account number
		var account_deposit_checkbox_id = $(this).parent().parent().parent().parent().find(".accountDepositTransaction").attr("id")
		var parent_account_checkbox_id = $(this).parent().parent().parent().parent().parent().find(".cbxAssociateDissociateFullAcountNumber").attr("id")

		// Get this accounts withdrawal account checkbox id
		var account_withdrawal_checkbox_id = $(this).attr("id")
		if ($(this).is(':checked')) {
			var post = {"action" : "associate_user_with_withdrawal_account_number_only", "selected_user_id" : selected_user_id, "selected_account_id": selected_account_id}
			$.ajax({
				method: "POST", url : "api/main.php", data: post, dataType: "JSON",
				success : function(data){
					var Message = data.Message
					var status = data.Status
					if (status == true) {
						$("#" + account_withdrawal_checkbox_id).attr("checked", true)
						$("#" + parent_account_checkbox_id).attr("checked", true)
						bs4pop.notice("<i class='fa fa-check-circle'></i> &nbsp;" + Message, {type: "success", position: "bottomright", appendType: "append"})
					} else { swal("", Message, "error") } 
				},
				error : function(data){ }
			})
		} else {
			var post = {"action" : "dissociate_user_with_withdrawal_account_number_only", "selected_user_id" : selected_user_id, "selected_account_id": selected_account_id}
			$.ajax({
				method: "POST", url : "api/main.php", data: post, dataType: "JSON",
				success : function(data){
					var Message = data.Message
					var status = data.Status
					if (status == true) {
						if (!$("#" + account_deposit_checkbox_id).is(':checked')) {
							$("#" + account_withdrawal_checkbox_id).attr("checked", false)
							$("#" + parent_account_checkbox_id).attr("checked", false)
						}
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + Message, {type: "danger", position: "bottomright", appendType: "append"})
					} else { swal("", Message, "error") } 
				},
				error : function(data){ }
			})
		}
	})

	// ============================ End of Account Association Management Section ===============================

	
	// ============================ Start of Account Transactions Section =======================================
    
    $(document).on("keyup", "#txtAmountNewAccountTransaction", function(){
		if ($(this).val() === "")
			$("#txtAmountInWordsNewAccountTransaction").val("")
		else {
			$("#txtAmountInWordsNewAccountTransaction").val(moneyValueToWords($(this).val()))
		}
	})
	
	// ------------------- Registering account transaction -------------------------

	$("#registerAccountTransactionForm").submit(function (e) {
		e.preventDefault()
		var withdrawal_amount = 0, deposit_amount = 0
		var transactionType = $("#cmbTransactionTypeNewAccountTransaction").val()
		if (transactionType === "1") deposit_amount = $("#txtAmountNewAccountTransaction").val()
		else if (transactionType === "2") withdrawal_amount = $("#txtAmountNewAccountTransaction").val()
		var vl = $("#cmbAccountNameNewAccountTransaction").val() + "###" + withdrawal_amount + "###" + deposit_amount + "###" + '0' + "###" + $("#txtTransactionDescriptionNewAccountTransaction").val() + "###" + "1" + "###" + $("#txtRegisteredByNewAccountTransaction").val() + "###" + $("#txtRegisterDateNewAccountTransaction").val() + " " + $("#txtRegisterTimeNewAccountTransaction").val() + "###" + "-" + "###" + "-"
		var hasFile = "No"
		var tn = "WnJFeVRwTkI4dVlUWVV0YVIyVTJoak9veUhSVFdiQWF0TVVKci9jMjlGMD06OpQJm7T8HV9EKo51U8Pa+KU="
		var commandType = "insert_command"
		var objName = "Transaction"
		var objPre = "TR"
		var post = {"action": "ins_upd_del_everything", "vl": vl, "hasFile": hasFile, "commandType": commandType, "tn": tn, "objName": objName, "objPre": objPre}
		if (transactionType === "1") {
		    $.ajax({
				url: "api/main.php", type: "POST", data:  post, dataType: "JSON",
				beforeSend:function(){
					$("#btnRegisterAccountTransaction").prop('disabled', true)
					$("#btnRegisterAccountTransaction").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
				},
				success: function(data) {
					$("#btnRegisterAccountTransaction").prop('disabled', false)
					$("#btnRegisterAccountTransaction").html("<i class='fa fa-lg fa-save'></i> Register Transaction")
					var Message = data.Message;
					var status = data.Status;
					if (status == true) {		
						swal ({
							title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
						}, function(isConfirm) {
							if (isConfirm) {location.reload()}
						})
					} else {
						Message.forEach(function (error) {
							bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
						})
					}	
				}, error: function(e) {bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})}          
		   	})
		} else if (transactionType === "2") {
		    //Check the account balance first
    		var withdrawalAccount = $("#cmbAccountNameNewAccountTransaction").val()
    		var currentWithdwaralAmount = Number($("#txtAmountNewAccountTransaction").val())
    		var check_acc_balance_post = {"action": "check_account_balance", "selectedAccountNo": withdrawalAccount}
    		$.ajax({
    			url: "api/main.php", type: "POST", data:  check_acc_balance_post, dataType: "JSON",
    			beforeSend:function(){
    				$("#btnRegisterAccountTransaction").prop('disabled', true)
    				$("#btnRegisterAccountTransaction").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
    			},
    			success: function(rs) {
    				var Account_Balance = rs.Message, Acc_Bala_Status = rs.Status
    				if (Acc_Bala_Status == true) {
    					if (Number(Account_Balance) >= currentWithdwaralAmount) {
    						$.ajax({
    							url: "api/main.php", type: "POST", data:  post, dataType: "JSON",
    							beforeSend:function(){
    								$("#btnRegisterAccountTransaction").prop('disabled', true)
    								$("#btnRegisterAccountTransaction").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
    							},
    							success: function(data) {
    								$("#btnRegisterAccountTransaction").prop('disabled', false)
    								$("#btnRegisterAccountTransaction").html("<i class='fa fa-lg fa-save'></i> Register Transaction")
    								var Message = data.Message;
    								var status = data.Status;
    								if (status == true) {		
    									swal ({
    										title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
    									}, function(isConfirm) {
    										if (isConfirm) {location.reload()}
    									})
    								} else {
    									Message.forEach(function (error) {
    										bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
    									})
    								}	
    							}, error: function(e) {bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})}          
    					   })
    					} else {
    						$("#btnRegisterAccountTransaction").prop('disabled', false)
    						$("#btnRegisterAccountTransaction").html("<i class='fa fa-lg fa-save'></i> Register Transaction")
    						swal("", "Your account balance is not sufficient", "error")
    					}
    				}
    			}, error: function(e) {
    				bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
    			}
    		})
		    
		}

	})
	
    // Delete Account Transaction Data
    $(document).on('click', '.btnDeleteAccountTransaction', function (e) {
        e.preventDefault()
        const deleteBtnID = $(this).attr("id")
        var vl = $(this).attr("data-id")
        var tn = "V3RBRTQ2Q2FadmtiNk0rQW5LVFBQUnEyWU04UExOTS84MHpJdEZKcXJMVT06Ok50Z/ck3aIzu/cEqwEqq74="
        var cm = "U0lHWGttQUN4VnlaVk9YNzZrTzdPQT09OjounAl5J8UwlEOXylPqc8sa"
        var commandType = "delete_command"
        var objName = "Transaction"
        var post = {
            "action": "ins_upd_del_everything", "vl": vl, "tn": tn, "cm": cm, "commandType": commandType, "objName": objName
        }
        swal({
            title: "Are your sure?", text: "You want to delete this permenantly?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
        }, function (isConfirm) {
            if (isConfirm) {
                $(".confirm").attr("disabled", "disabled")
			    $(".confirm").attr("style", "color: #FFF") 
			    $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
                $.ajax({
                    method: "POST", url: "api/main.php", data: post, dataType: "JSON",
                    success: function (data) {
                        var Message = data.Message
                        var status = data.Status
                        if (status == true) {
                            swal("success", Message, "success")
                            $("#" + deleteBtnID).parents("tr").remove()
                        } else {
                            swal("", Message, "error")
                        }
                    }, error: function (data) { }
                })
            }
        })
    })

	// ----------------------- Cancelling Account Transaction Data ---------------------
	$(document).on('click', '.btnCancelAccountTransaction', function(e){
	
		e.preventDefault()

		const deleteBtnID = $(this).attr("id")
		var vl = $(this).attr("data-id")
		var tn = "WnJFeVRwTkI4dVlUWVV0YVIyVTJoak9veUhSVFdiQWF0TVVKci9jMjlGMD06OpQJm7T8HV9EKo51U8Pa+KU="
		var cm = "U3c1SWo5ZHdmUlRoMDFaYkdrS1E1dkNhRmJqZFh2WWVWOG1GWmRNdEZEYjhUQ0NzSG5ZcEh1Y1hTeloxMlM4SXhobXloSmtpcEk4c1luVlV2THJzOVE9PTo6UPGcB/SA83Ltu8LqKXzs6Q=="
		var commandType = "update_command"
		var hasFile = "No"
		var objName = "Transaction"

		var post = {
			"action" : "ins_upd_del_everything", "vl" : vl, "cm" : cm, "hasFile" : hasFile,
			"commandType" : commandType, "tn" : tn, "objName" : objName,
		};

		swal ({
			title: "Are your sure?", text: "You want to cancel this transaction?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No",
			closeOnConfirm: false, closeOnCancel: false
		}, function(isConfirm) {
			if (isConfirm) {
				
				$.ajax({    
					method: "POST", url : "api/main.php", data: post, dataType: "JSON",
					success : function(data){
						var Message = data.Message;
						var status = data.Status;
						if (status == true) {
							swal("success", "Transaction has been cancelled successfully", "success")
							$("#" + deleteBtnID).parents("tr").remove()
						} else {
							swal("", Message, "error")
						}
					},
					error : function(data){ }
				})
			} else {
				swal("Cancelled", "Transaction cancelletion has been cancelled", "error")
			}
		})

	})
	
	// ------------------- Deleting Account Transaction ------------------------------
	$(document).on('click', '.btnDeleteTransaction', function(e){
		e.preventDefault()
		const deleteBtnID = $(this).attr("id")
		var vl = $(this).attr("data-id")
		var cm = "TXNoOUczbVN5UWFCSXdrKzlGeCtDQT09OjrPk++Lfh1c+8G68zgCLxbi"
		var tn = "WnJFeVRwTkI4dVlUWVV0YVIyVTJoak9veUhSVFdiQWF0TVVKci9jMjlGMD06OpQJm7T8HV9EKo51U8Pa+KU="
		var commandType = "delete_command"
		var objName = "Transaction"
		var post = {
			"action" : "ins_upd_del_everything", "vl" : vl, "cm" : cm, "tn" : tn, "commandType" : commandType, "objName" : objName,
		}
		swal ({
			title: "Are you sure?", text: "You want to delete this transaction permenently?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No",
			closeOnConfirm: false,
			closeOnCancel: false
		}, function(isConfirm) {
			if (isConfirm) {
			    $.ajax({    
					method: "POST", url : "api/main.php", data: post, dataType: "JSON",
					success : function(data){
						var Message = data.Message;
						var status = data.Status;
						if (status == true) {
							swal("", Message, "success")
							$("#" + deleteBtnID).parents("tr").remove()
                        } else {
                            swal("", Message, "error")
                        }
					},
					error : function(data){ }
				})
			} else {
				swal("Deletion Cancelled", "Transaction deletion has been cancelled", "error")
			}
		})

	})
	
	// ============================ End of Account Transactions Section =========================================
	
	// ============================ Start of Salaries Section ===================================================
	
    // ============================ Start of Advanced Salary Information Section ================================

    // Register New Advanced Salary Page
    $("#registerNewAdvancedSalaryForm").on("submit", function (e) {
        e.preventDefault()
        let obj = new Date(); 
        let month = obj.getUTCMonth(); 
        let year = obj.getUTCFullYear();
        const month_names = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
        let payment_month_year = `${month_names[month]}-${year}`
        var vl = $("#cmbEmployeeIddNewAdvancedSalary").val() + "###" + $("#cmbPaymentTypeNewAdvancedSalary").val() + "###" + payment_month_year + "###" + $("#txtPaidAmountNewAdvancedSalary").val() + "###" + $("#txtPaymentDescriptionNewAdvancedSalary").val() + "###" + $("#txtRegisteredByNewAdvancedSalary").val() + "###" + $("#txtRegisterDateNewAdvancedSalary").val() + "###" + "-" + "###" + "-"
        var hasFile = "No"
        var tn = "ekNCTVBGWjF4cVB4d2FyWGJjNE9LTWVjakwxUjhvTU0ybSs4NHdIMkR2RT06OhGoBFZKKX28n+pvBeQeCvQ="
        var commandType = "insert_command"
        var objName = "Advanced salary"
        var objPre = "ADS"
        var post = {action: "ins_upd_del_everything", vl: vl, hasFile: hasFile, commandType: commandType, tn: tn, objName: objName, objPre: objPre}
        swal ({
          title: "Are you sure?", text: "You want to register this advanced salary?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
        }, function(isConfirm) {
          if (isConfirm) {
            $(".confirm").attr("disabled", "disabled") 
            $(".confirm").attr("style", "color: #FFF") 
            $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
            $.ajax({
              url: "api/main.php", type: "POST", data: post, dataType: "JSON",
              beforeSend:function(){
                $("#btnRegisterNewAdvancedSalary").prop('disabled', true)
                $("#btnRegisterNewAdvancedSalary").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
              }, success: function(data) {
                $("#btnRegisterNewAdvancedSalary").prop('disabled', false)
                $("#btnRegisterNewAdvancedSalary").html("<i class='fa fa-lg fa-save'></i> Register Payment")
                var Message = data.Message
                var status = data.Status
                if (status == true) {		
                  swal ({
                    title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
                  }, function(isConfirm) {
                    if (isConfirm) location.reload()
                  })
                } else {
                  Message.forEach(function (error) {
                    bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
                  })
                }	
              }, error: function(e) {
                bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
              }          
            })
          }
        })
        
    })
      
    // Filling Data into Update Advanced Salary Modal
    $(document).on("click", ".btnUpdateAdvancedSalary", function (e) {
        e.preventDefault()
        var objectID = $(this).attr("data-id")
        var tn = "ekNCTVBGWjF4cVB4d2FyWGJjNE9LTWVjakwxUjhvTU0ybSs4NHdIMkR2RT06OhGoBFZKKX28n+pvBeQeCvQ="
        var cm = "bUExYnRlTUwyVi91VmdrQmxFbG9Jdz09OjrDppahOFjuaIGPxfl7fPJa"
        var post = { "action": "fetch_parameterized_everything", "dn": dn, "tn": tn, "cm": cm, "objectID": objectID }
        $(".modal-body").load(objectID)
        $.ajax({
          method: "POST", url: "api/main.php", data: post, dataType: "JSON",
          success: function (data) {
            var Message = data.Message
            var status = data.Status
            if (status == true) {
              var returned_info = Message.split("###")
              $("#txtPaymentIdUpdateAdvancedSalary").val(returned_info[1])
              $("#cmbEmployeeIddUpdateAdvancedSalary").select2().val(returned_info[2]).trigger('change')
              $("#cmbPaymentTypeUpdateAdvancedSalary").select2().val(returned_info[3]).trigger('change')
              $("#txtPaidAmountUpdateAdvancedSalary").val(returned_info[5])
              $("#txtPaymentDescriptionUpdateAdvancedSalary").val(returned_info[6])
            }
          }, error: function (e) {
            bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, { type: "danger", position: "topright", appendType: "append"})
          }
        })
    })

    // Update Advanced Salary Modal
    $("#updateAdvancedSalaryForm").on("submit", function (e) {
        e.preventDefault()
        var vl = $("#txtPaymentIdUpdateAdvancedSalary").val() + "###" + $("#cmbEmployeeIddUpdateAdvancedSalary").val() + "###" + $("#cmbPaymentTypeUpdateAdvancedSalary").val() + "###" + $("#txtPaidAmountUpdateAdvancedSalary").val() + "###" + $("#txtPaymentDescriptionUpdateAdvancedSalary").val() + "###" + $("#txtUpdatedByUpdateAdvancedSalary").val() + "###" + $("#txtUpdateDateUpdateAdvancedSalary").val()
        var tn = "ekNCTVBGWjF4cVB4d2FyWGJjNE9LTWVjakwxUjhvTU0ybSs4NHdIMkR2RT06OhGoBFZKKX28n+pvBeQeCvQ="
        var cm = "OXd4WnNSUGM1OC9ROHJBVStLSENPeHY2V016S0U3OEFHSlZPbGRDVFN3ekZUbkZPZlFVSm4yTWx0QXEzZmUyUXBML2YraUE3dW9DVTJaNDRmSVhhM1gwZ3M4ZjZXV3k2SjVMeGt2UHlZQVArdFV6K24xaG5mVmQ5b0lzMDZSclU6OmNplcc+nsBp5Gz4/IzwJg8="
        var commandType = "update_command"
        var hasFile = "No"
        var objName = "Advanced salary"
        var post = {
          action: "ins_upd_del_everything", vl: vl, cm: cm, hasFile: hasFile, commandType: commandType, tn: tn, objName: objName
        }
        swal({
          title: "Are your sure?", text: "You want to update this advanced salary?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
        }, function (isConfirm) {
          if (isConfirm) {
            $(".confirm").attr("disabled", "disabled") 
            $(".confirm").attr("style", "color: #FFF") 
            $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
            $.ajax({
              url: "api/main.php", type: "POST", data: post, dataType: "JSON",
              beforeSend: function () {
                  $("#btnUpdateAdvancedSalary").prop("disabled", true)
                  $("#btnUpdateAdvancedSalary").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
              }, success: function (data) {
                $("#btnUpdateAdvancedSalary").prop("disabled", false)
                $("#btnUpdateAdvancedSalary").html("<i class='fa fa-pencil'></i> Update Payment")
                var Message = data.Message;
                var status = data.Status;
                if (status === true) {
                  swal({
                      title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
                  }, function (isConfirm) {
                      if (isConfirm) { location.reload() }
                  })
                } else {
                  Message.forEach(function (error) {
                      bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, { type: "danger", position: "topright", appendType: "append"})
                  })
                }
              }, error: function (e) {
                  bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, { type: "danger", position: "topright", appendType: "append"})
              },
            })
          }
        })
    })

    // Delete Advanced Salary Data
    $(document).on('click', '.btnDeleteAdvancedSalary', function (e) {
        e.preventDefault()
        const deleteBtnID = $(this).attr("id")
        var vl = $(this).attr("data-id")
        var tn = "ekNCTVBGWjF4cVB4d2FyWGJjNE9LTWVjakwxUjhvTU0ybSs4NHdIMkR2RT06OhGoBFZKKX28n+pvBeQeCvQ="
        var cm = "bUExYnRlTUwyVi91VmdrQmxFbG9Jdz09OjrDppahOFjuaIGPxfl7fPJa"
        var commandType = "delete_command"
        var objName = "Advanced salary"
        var post = {"action": "ins_upd_del_everything", "vl": vl, "tn": tn, "cm": cm, "commandType": commandType, "objName": objName}
        swal({
          title: "Are your sure?", text: "You want to delete this permenantly?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
        }, function (isConfirm) {
          if (isConfirm) {
            $(".confirm").attr("disabled", "disabled")
            $(".confirm").attr("style", "color: #FFF") 
            $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
            $.ajax({
              method: "POST", url: "api/main.php", data: post, dataType: "JSON",
              success: function (data) {
                var Message = data.Message
                var status = data.Status
                if (status == true) {
                    swal("", Message, "success")
                    $("#" + deleteBtnID).parents("tr").remove()
                } else {
                    swal("", Message, "error")
                }
              }, error: function (data) { }
            })
          }
        })
    })
    
    // ============================ End of Advanced Salary Information Section ===========================================
    
    // ============================ Start of Advanced Salary Resport Information Section =================================
	
	$("#advancedSalariesReportForm").on('submit', function (e) {
		e.preventDefault()
		var selected_employee_id = $("#cmbEmployeeIdAdvancedSalariesReport").val()
		var selected_payment_month = $("#cmbPaymentMonthAdvancedSalariesReport").val()
		var post_data = {
			"action": "advanced_salaries_report", "selected_employee_id": selected_employee_id, "selected_payment_month": selected_payment_month
		}
		$.ajax({
			type: "POST", url: "api/main.php", data: post_data, dataType: "text",
			beforeSend:function(){
				$("#btnAdvancedSalariesReport").prop('disabled', true)
				$("#btnAdvancedSalariesReport").html("<i class='fa fa-spinner fa-pulse' style='font-size: 18px; margin-left: 5px; margin-bottom: 3px;'></i> Please wait")
			}, success: function (response) {
				$("#btnAdvancedSalariesReport").prop('disabled', false)
				$("#btnAdvancedSalariesReport").html("<i class='fa fa-search' style='font-size: 18px; margin-left: 5px; margin-bottom: 3px;'></i> Search")
				$("#advancedSalariesReportSection").html(response)
			}
		})
	})
	
	$(document).on('click', '#printAdvancedSalariesReport', function(){
		//Display and open the print dialog box to print the report
		var advancedSalReportRestorePage = document.body.innerHTML;
		var advancedSalReportPrintArea = document.getElementById("advancedSalariesPrintArea").innerHTML;
		document.body.innerHTML = advancedSalReportPrintArea;
		window.print()
		document.body.innerHTML = advancedSalReportRestorePage;	
	})
	
    // ============================ End of Advanced Salary Resport Information Section ===================================
    
    
    

	// ------------------- Charging employee salaries -----------------
	
	$("#salaryChargeForm").submit(function (e) {
		e.preventDefault()
		var empNameSalaryCharge = $("#empNameChargeSalaries").val()
		var salMonthSalaryCharge = $("#salaryMonthChargeSalaries").val()
		var post = {"action" : "fetch_employee_charge_salary", "salMonthSalChar" : salMonthSalaryCharge}
		$.ajax({
			type: "POST", url: "api/main.php", data: post, dataType: "text",
			beforeSend:function(){
				$("#btnChargeSalaries").prop('disabled', true)
				$("#btnChargeSalaries").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
			},
			success: function (response) {
				$("#btnChargeSalaries").prop('disabled', false)
				$("#btnChargeSalaries").html("<i class='fa fa-lg fa-search'></i> Search")
				$("#employeeChargeSalaries").html(response)
			}
		})
	})
	
	$(document).on("change", "#empChargeCheckAll", function () {
		if ($(this).is(":checked")) {
			var checkNoCheckBox = $("input:checkbox[id=empChargeCheck]").length
			if (checkNoCheckBox <= 0) {
				//Dont show the Charge All Button if there are no checkboxes
			} else {
				$(".showHideChargeBtn").show()
				$(".allEmpCharge :checkbox").prop("checked", true)
				$("#chargeAllEmpSal").html('<i class="fa fa-send"></i> Charge All')
			}
		} else {
			$(".showHideChargeBtn").hide()
			$(".allEmpCharge :checkbox").prop("checked", false)
			$("#chargeAllEmpSal").html('<i class="fa fa-send"></i> Charge All')
		}
	})
	
	$(document).on("change", "#empChargeCheck", function () {
		var allEmpCheckBox = $("input:checkbox[id=empChargeCheck]").length
		var checkAllEmpCheck = $("#empChargeCheck:checked").length
		if (checkAllEmpCheck  <= 0) {
			$("#empChargeCheckAll").prop("checked", false)
			$("#chargeAllEmpSal").html('<i class="fa fa-send"></i> Charge All')
			$(".showHideChargeBtn").hide()
		} else if (checkAllEmpCheck == allEmpCheckBox) {
			$(".showHideChargeBtn").show()
			$("#empChargeCheckAll").prop("checked", true)
			$("#chargeAllEmpSal").html('<i class="fa fa-send"></i> Charge All')
		} else {
			$(".showHideChargeBtn").show()
			$("#empChargeCheckAll").prop("checked", false)
			$("#chargeAllEmpSal").html('<i class="fa fa-send"></i> Charge Selected')
		}
	})
	
	$("#chargeAllEmpSal").on("click", function () {
		var selectedEmpToCharge = ""
		$("input[name='empChargeCheck']:checked").each(function() {
			selectedEmpToCharge += this.value + "###"
		})	
		var embToBeCharged = selectedEmpToCharge.slice(0, -3)
		var salChargeMonth = $("#salaryMonthChargeSalaries").val()
		var post = { "action" : "charge_employee_salaries", "embToBeCharged" : embToBeCharged, "salChargeMonth" : salChargeMonth};
		swal ({
			title: "Are you sure ?", text: "You want to charge the salaries of this month?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No",
			closeOnConfirm: false, closeOnCancel: false
		}, function(isConfirm) {
			if (isConfirm) {
				$.ajax({    
					method: "POST", url : "api/main.php", data: post, dataType: "JSON",
					success : function(data){
						var Message = data.Message
						var status = data.Status
						if (status == true) { swal ({ title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false }, function(isConfirm) { if (isConfirm) { location.reload() } }) } else { swal("", Message, "error") }
					},
					error : function(data){ }
				})
			} else { swal("Charge Cancelled", "Salary charge has been cancelled", "error") }
		})		
	})

	// ----------------------- Cancelling Employee Salary Charge ---------------------
	$(document).on('click', '.btnCancelSalaryCharge', function(e){
	
		e.preventDefault()

		const deleteBtnID = $(this).attr("id")
		var vl = $(this).attr("data-id")
		var tn = "VUhJZEJ6ZGM3dXl4dXFlVEVXd0NnaSswUjR3TDRuemtnaGNiZXFRQ0hkWT06OvISCq1Q7Jcb0HhL5iYYqkY="
		var cm = "WEtPWGVwZmZycHRQSHhBOG9IYXBpUkFOTWU4Sk9XWXhDbnU4YlNCcDQ3Y3M2Q1E5QkhpVnptWU1Xc2hDamV3TkV6WEVzT2lXM3RwRkdLS3k3UWFsRXc9PTo6VaJ1vwYdUq5UhGazKvpOFQ=="
		var commandType = "update_command"
		var hasFile = "No"
		var objName = "Salary charge"

		var post = {
			"action" : "ins_upd_del_everything", "vl" : vl, "cm" : cm, "hasFile" : hasFile,
			"commandType" : commandType, "tn" : tn, "objName" : objName,
		};

		swal ({
			title: "Are your sure?", text: "You want to cancel this salary charge?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No",
			closeOnConfirm: false, closeOnCancel: false
		}, function(isConfirm) {
			if (isConfirm) {
				
				$.ajax({    
					method: "POST", url : "api/main.php", data: post, dataType: "JSON",
					success : function(data){
						var Message = data.Message;
						var status = data.Status;
						if (status == true) {
							swal("success", "Salary charge has been cancelled successfully", "success")
							$("#" + deleteBtnID).parents("tr").remove()
						} else {
							swal("", Message, "error")
						}
					},
					error : function(data){ }
				})
			} else {
				swal("Cancelled", "Salary charge cancelletion has been cancelled", "error")
			}
		})

	})
	
	// ------------------- Deleting salary charge ---------------------
	$(document).on('click', '.chargeSalaryDeletion', function(e){
		e.preventDefault()
		const deleteBtnID = $(this).attr("id")
		var vl = $(this).attr("data-id")
		var cm = "ZTQyTVN3aWh0N0VVU24xclZZZWxudz09OjoIbVBNkAC4Mejemg7HW8ZF"
		var tn = "dFExaFhZZzU1VGNqd1VDT3RnV0dBakdOWDVFenFOVjBmRENyL0RBZlY2ST06OsZd7og4xKUjJF57ODTdTOM="
		var commandType = "delete_command"
		var objName = "Charge salary"
		var post = { "action" : "ins_upd_del_everything", "vl" : vl, "cm" : cm, "tn" : tn, "commandType" : commandType, "objName" : objName }
		swal ({
			title: "Are you sure?", text: "You want to delete this salary charge?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No",
			closeOnConfirm: false, closeOnCancel: false
		}, function(isConfirm) {
			if (isConfirm) {
			    $.ajax({    
					method: "POST", url : "api/main.php", data: post, dataType: "JSON",
					success : function(data){
						var Message = data.Message
						var status = data.Status
						if (status == true) {
							swal("", Message, "success")
							$("#" + deleteBtnID).parents("tr").remove()
                        } else { swal("", Message, "error") }
					},
					error : function(data){ }
				})
			} else { swal("Cancelled", "Salary charge deletion has been cancelled", "error") }
		})
	})

	// ========================== End of Charge Employee Salaries Section ========================

	// ========================== Start of Employee Salary Payments Section ======================

	// Employee name changed, if another employee is selected
    $("#cmbSalaryPaymentEmployeeName").change(function () {
        var selectedEmployeeID = $(this).val()
		if (selectedEmployeeID == "") {
			$("#txtSalaryPaymentEmployeeTitle").val("")
			$("#cmbSalaryPaymentSalaryMonth").select2().val("").trigger('change')
			$("#cmbEmployeeSalariesWithdrawalAccount").select2().val("").trigger('change')
			$("#txtEmployeeSalariesAccountNumber").val("")
			$("#txtSalaryPaymentPaidAmount").val("")
			$("#txtSalaryPaymentAmountInWords").val("")
			$("#txtSalaryPaymentSalaryDescription").val("")
		} else {
			$("#cmbSalaryPaymentSalaryMonth").select2().val("").trigger('change')
			$("#cmbEmployeeSalariesWithdrawalAccount").select2().val("").trigger('change')
			$("#txtEmployeeSalariesAccountNumber").val("")
			$("#txtSalaryPaymentPaidAmount").val("")
			$("#txtSalaryPaymentAmountInWords").val("")
			$("#txtSalaryPaymentSalaryDescription").val("")
			var post = {"action" : "fetch_employee_data" , "thisEmp" : selectedEmployeeID }
			//Fetch the data of the selected employee using the above thisEmp variable
			$.ajax({
				method: "POST", url : "api/main.php", data: post, dataType: "JSON",
				success : function(data){
					var Message = data.Message
					var status = data.Status
					if(status == true){
						var position_array = ["Super Admin", "Admin", "Finance", "Registrar"]
						Message.forEach(function(item) {
							$("#txtSalaryPaymentEmployeeTitle").val(position_array[item['titlePosition']])
						}) 
					}
				},
				error : function(data){ }
			})
		}
    })

	// Salary month is changed, if another month is selected
    $("#cmbSalaryPaymentSalaryMonth").change(function () {
        
        var employeeIdddd = $("#cmbSalaryPaymentEmployeeName").val()
		var selectedSalaryMonth = $(this).val()
		if (selectedSalaryMonth == "" && employeeIdddd === "") {
			$("#txtSalaryPaymentChargedAmount").val("")
			$("#txtSalaryPaymentRemainingBalance").val("")
			
		} else {
			var post = {"action" : "fetch_employee_charged_remain", "employeeIdddd" : employeeIdddd, "selectedSalaryMonth" : selectedSalaryMonth }
			//Fetch the data of the selected employee using the above thisEmp variable
			$.ajax({
				method: "POST", url : "api/main.php", data: post, dataType: "JSON",
				success : function(data){
					var Message = data.Message
					var status = data.Status
					if(status == true){
						var returned_info = Message.split("###")
						$("#txtSalaryPaymentChargedAmount").val(returned_info[0])
						$("#txtSalaryPaymentRemainingBalance").val(returned_info[1])
						$("#txtSalaryPaymentPaidAmount").prop('max', returned_info[1])
					}
				},
				error : function(data){ }
			})
		}
    })

	//Fill the account no, evc plus and so when withdarawn to is changed
	$(document).on("change", "#cmbEmployeeSalariesWithdrawalAccount", function () {

		var selectedAccountNo = $(this).val()
		
		if (selectedAccountNo === "") {
			$("#txtEmployeeSalariesAccountNumber").val("")
		} else {
			var post = {"action" : "fetch_account_number", "selectedAccountNo" : selectedAccountNo }
			//Fetch the data of the selected employee using the above thisEmp variable
			$.ajax({
				method: "POST", url : "api/main.php", data: post, dataType: "JSON",
				success : function(data){
					var Message = data.Message
					var status = data.Status
					if(status == true){
						$("#txtEmployeeSalariesAccountNumber").val(Message)
					}
				},
				error : function(data){ }
			})
		}
    })

	$(document).on("keyup keypress blur change focusout", "#txtSalaryPaymentPaidAmount", function(){
		if ($(this).val() == "")
			$("#txtSalaryPaymentAmountInWords").val("")
		else {
			$("#txtSalaryPaymentAmountInWords").val(moneyValueToWords($(this).val()))
		}
	})

	//Pay Salary button click on employee-salary page
    $("#employeeSalaryPaymentForm").submit(function (e) {

        e.preventDefault()

		var employeeIdd = $("#cmbSalaryPaymentEmployeeName").val()
		var salaryMonth = $("#cmbSalaryPaymentSalaryMonth").val()
		var salaryWithdrawalAccount = $("#cmbEmployeeSalariesWithdrawalAccount").val()
		var paidAmmount = $("#txtSalaryPaymentPaidAmount").val()
		var salDescription = $("#txtSalaryPaymentSalaryDescription").val()
		var salaryPaymentDate = $("#txtSalaryPaymentDate").val() + " 00:00:00"
		var post = {
			"action" : "pay_employee_salary", "employeeIdd" : employeeIdd, "salaryMonth" : salaryMonth,
			"salaryWithdrawalAccount" : salaryWithdrawalAccount, "paidAmmount" : paidAmmount, 
			"salDescription" : salDescription, "salaryPaymentDate" : salaryPaymentDate
		}

        swal ({
            title: "Are you sure", text: "You want to pay the salary of " + salaryMonth + " for this employee?", type: "", showCancelButton: true,
            confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: false
        }, function(isConfirm) {
            if (isConfirm) {

				//Check the bank account balance first
				var currentPaidAmount = Number($("#txtSalaryPaymentPaidAmount").val())
				var check_acc_balance_post = {
					"action" : "check_account_balance",
					"selectedAccountNo": salaryWithdrawalAccount
				}
		
				$.ajax({
					url: "api/main.php", type: "POST", data:  check_acc_balance_post, dataType: "JSON",
					beforeSend:function(){
						$("#btnPayEmployeeSalary").prop('disabled', true)
						$("#btnPayEmployeeSalary").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
					},
					success: function(rs) {
						var Account_Balance = rs.Message;
						var Acc_Bala_Status = rs.Status;
						
						if (Acc_Bala_Status == true) {
		
							if (Number(Account_Balance) >= currentPaidAmount) {

								$.ajax({
									method: "POST", url : "api/main.php", data: post, dataType: "JSON",
									success : function(data){
										var Message = data.Message
										var status = data.Status
										if (status == true) {
											swal ({
												title: "Success", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
											}, function(isConfirm) {
												if (isConfirm) { location.reload() }
											})
										} else { 
											//swal("", Message, "error")
											Message.forEach(function (error) {
												bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
											})
										}  
									},
									error : function(data){ }
								})

							} else {
								$("#btnPayEmployeeSalary").prop('disabled', false)
								$("#btnPayEmployeeSalary").html("<i class='fa fa-lg fa-save'></i> Register Salary Payment")
								swal ({
									title: "", text: "Your account balance is not sufficient, " + Account_Balance, type: "error", showCancelButton: false, closeOnConfirm: true, closeOnCancel: false
								}, function(isConfirm) {
									if (isConfirm) { /* location.reload() */ }
								})
							}
						}
					}, error: function(e) {
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
					}
				})	

            } else { swal("Cancelled", "Salary payment has been cancelled", "error") }
        })
    })

	// ----------------------- Cancelling Salary Payment ---------------------
	$(document).on('click', '.btnCancelSalaryPayment', function(e){

		e.preventDefault()

		const deleteBtnID = $(this).attr("id")
		var vl = $(this).attr("data-id")
		var tn = "dFExaFhZZzU1VGNqd1VDT3RnV0dBakdOWDVFenFOVjBmRENyL0RBZlY2ST06OsZd7og4xKUjJF57ODTdTOM="
		var cm = "b1pPUHQ3aG5LbjhoWUNQdjdPT0UrV1drU2JKZFdPaHZLYm8wcUNhTUtITUxONXdmNWJtdmh4cmVwSHJtOHM1cWxSaDVhQTJpc3JGN3V0TGxRZ1JsSVE9PTo6MGbm1C2SrXMsR4CbS/P4tw=="
		var commandType = "update_command"
		var hasFile = "No"
		var objName = "Salary payment"

		var post = {
			"action" : "ins_upd_del_everything", "vl" : vl, "cm" : cm, "hasFile" : hasFile,
			"commandType" : commandType, "tn" : tn, "objName" : objName,
		};

		swal ({
			title: "Are your sure?", text: "You want to cancel this salary payment?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No",
			closeOnConfirm: false, closeOnCancel: false
		}, function(isConfirm) {
			if (isConfirm) {
				
				$.ajax({    
					method: "POST", url : "api/main.php", data: post, dataType: "JSON",
					success : function(data){
						var Message = data.Message;
						var status = data.Status;
						if (status == true) {
							swal("success", "Salary payment has been cancelled successfully", "success")
							$("#" + deleteBtnID).parents("tr").remove()
						} else {
							swal("", Message, "error")
						}
					},
					error : function(data){ }
				})
			} else {
				swal("Cancelled", "Salary charge cancelletion has been cancelled", "error")
			}
		})

	})
	
	// ------------------- Deleting employee salary ---------------------
	$(document).on('click', '.salaryPaymentDeletion', function(e){
		e.preventDefault()
		const deleteBtnID = $(this).attr("id")
		var vl = $(this).attr("data-id")
		var cm = "WHYyaUk2TG5XK3ZzUG5BNktueW56dz09OjqV8D0DDH87u9003f7nZy6A"
		var tn = "b0lqOGk0akZud1ZORzhvdGhkcktSWlBlK0N4OUVmdktxNHVITHlqSFF0UT06OiGIx+6zq6oQD6mpLibND2w="
		var commandType = "delete_command"
		var objName = "Salary payment"
		var post = {
			"action" : "ins_upd_del_everything", "vl" : vl, "cm" : cm, "tn" : tn, "commandType" : commandType, "objName" : objName,
		}

		swal ({
			title: "Are you sure?", text: "You want to delete this salary payment?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No",
			closeOnConfirm: false, closeOnCancel: false
		}, function(isConfirm) {
			if (isConfirm) {
			    
			    $.ajax({    
					method: "POST", url : "api/main.php", data: post, dataType: "JSON",
					success : function(data){
						var Message = data.Message;
						var status = data.Status;
						if (status == true) {
							swal("", Message, "success")
							$("#" + deleteBtnID).parents("tr").remove()
                        } else {
                            swal("", Message, "error")
                        }
					},
					error : function(data){ }
				})
			} else {
				swal("Deletion Cancelled", "Salary payment deletion has been cancelled", "error")
			}
		})

	})
	
	// ========================== End of Employee Salary Payments Section ========================
	
	// ========================== Start of Expenses Section ======================================
	
	$(document).on("keyup", "#txtExpenseAmountRegisterNewExpense", function(){
		if ($(this).val() == "")
			$("#txtExpenseAmountWordsRegisterNewExpense").val("")
		else {
			$("#txtExpenseAmountWordsRegisterNewExpense").val(moneyValueToWords($(this).val()))
		}
	})

	// Register New Expense
	$("#registerNewExpenseForm").submit(function (e) {
		e.preventDefault()
		var expense_type_name = $("#cmbExpenseTypeRegisterNewExpense").val()
		var expense_amount = $("#txtExpenseAmountRegisterNewExpense").val()
		var selectedAccountNo = $("#cmbExpensesWithdrawalAccountRegisterNewExpense").val()
		var expense_remarks = $("#txtExpensePaymentRemarksRegisterNewExpense").val()
		var selectedPaymentDate = $("#txtExpenseDateRegisterNewExpense").val() + " " + $("#txtRegisterTimeNewExpense").val()
		var post = {
			"action": "register_new_expense",
			"expense_type_name": expense_type_name,
			"expense_amount": expense_amount,
			"selectedAccountNo": selectedAccountNo,
			"expense_remarks": expense_remarks,
			"selected_payment_date": selectedPaymentDate
		}
		swal ({
			title: "Are you sure?", text: "You want to register this expenses?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
		}, function(isConfirm) {
			if (isConfirm) {
                $(".confirm").attr("disabled", "disabled")
			    $(".confirm").attr("style", "color: #FFF") 
			    $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
			  	//Check the bank account balance first
				var expenseWithdrawalAccount = $("#cmbExpensesWithdrawalAccountRegisterNewExpense").val()
				var currentExpenseAmount = Number($("#txtExpenseAmountRegisterNewExpense").val())
				var check_acc_balance_post = { "action" : "check_account_balance", "selectedAccountNo": expenseWithdrawalAccount }
				$.ajax({
					url: "api/main.php", type: "POST", data:  check_acc_balance_post, dataType: "JSON",
					beforeSend:function(){
						$("#btnRegisterExpense").prop('disabled', true)
						$("#btnRegisterExpense").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
					},
					success: function(rs) {
						var Account_Balance = rs.Message
						var Acc_Bala_Status = rs.Status
						if (Acc_Bala_Status == true) {
							if (Number(Account_Balance) >= currentExpenseAmount) {
								$.ajax({
									url: "api/main.php", type: "POST", data:  post, dataType: "JSON",
									beforeSend:function(){
										$("#btnRegisterExpense").prop('disabled', true)
										$("#btnRegisterExpense").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
									},
									success: function(data) {
										$("#btnRegisterExpense").prop('disabled', false)
										$("#btnRegisterExpense").html("<i class='fa fa-lg fa-save'></i> Register Expense")
										var Message = data.Message
										var status = data.Status
										if (status == true) {		
											swal ({
												title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
											}, function(isConfirm) {
												if (isConfirm) { location.reload() }
											})
										} else {
											Message.forEach(function (error) {
												bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
											})
										}	
									}, error: function(e) {
										bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
									}          
								})
							} else {
								$("#btnRegisterExpense").prop('disabled', false)
								$("#btnRegisterExpense").html("<i class='fa fa-lg fa-save'></i> Register Expense")
								swal ({
									title: "", text: "Your account balance is not sufficient", type: "error", showCancelButton: false, closeOnConfirm: true, closeOnCancel: false
								}, function(isConfirm) {
									if (isConfirm) { /* location.reload() */ }
								})
							}
						}
					}, error: function(e) {
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
					}
				})
			}
		})
	})
	
	$(document).on("keyup", "#txtExpenseAmountUp", function(){
		if ($(this).val() == "")
			$("#txtExpenseAmountWordsUp").val("")
		else {
			$("#txtExpenseAmountWordsUp").val(moneyValueToWords($(this).val()))
		}
	})

	// Approve Expense
	$(document).on('click', '.btnApproveExpense', function(e){
		e.preventDefault()
		var expense_id_to_approve = $(this).attr("data-id")
		var post = { "action" : "approve_expense", "expense_id_to_approve" : expense_id_to_approve }
		swal ({
			title: "Are your sure?", text: "You want to approve this expense?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
		}, function(isConfirm) {
			if (isConfirm) {
                $(".confirm").attr("disabled", "disabled")
			    $(".confirm").attr("style", "color: #FFF") 
			    $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
				$.ajax({    
					method: "POST", url : "api/main.php", data: post, dataType: "JSON",
					success : function(data){
						var Message = data.Message
						var status = data.Status
						if (status == true) {
							swal ({
								title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: true, closeOnCancel: false
							}, function(isConfirm) {
								if (isConfirm) { location.reload() }
							})
						} else {
							swal("", Message, "error")
						}
					},
					error : function(data){ }
				})
			}
		})
	})

	// Cancel Expense
	$(document).on('click', '.btnCancelExpense', function(e){
		e.preventDefault()
		const deleteBtnID = $(this).attr("id")
		var vl = $(this).attr("data-id")
		var tn = "cGRVZzhXbjlKMCsrbnRMWHJwaDJyUT09OjqnVAfRTer/TWiak6mWwqP5"
		var cm = "RW8yOGx5L1lZS3c2enpLWGtOSEdIMVRSVVhTNHp1aDRocEhYc0dCSzdmdjlnU0NxVUt0bjdacVI3OWJXMTB6OElGVXdRcS9oTmp1dDZqdGdPYkpzZWc9PTo6DkGqfahHiBrPHRVtImyKaA=="
		var commandType = "update_command"
		var hasFile = "No"
		var objName = "Expense"
		var post = { "action" : "ins_upd_del_everything", "vl" : vl, "cm" : cm, "hasFile" : hasFile, "commandType" : commandType, "tn" : tn, "objName" : objName}
		swal ({
			title: "Are your sure?", text: "You want to cancel this expense?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
		}, function(isConfirm) {
			if (isConfirm) {
                $(".confirm").attr("disabled", "disabled")
			    $(".confirm").attr("style", "color: #FFF") 
			    $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
				$.ajax({    
					method: "POST", url : "api/main.php", data: post, dataType: "JSON",
					success : function(data){
						var Message = data.Message
						var status = data.Status
						if (status == true) {
							swal("success", "Expense has been cancelled successfully", "success")
							$("#" + deleteBtnID).parents("tr").remove()
						} else {
							swal("", Message, "error")
						}
					},
					error : function(data){ }
				})
			}
		})

	})

	// Delete Expense
	$(document).on('click', '.btnDeleteExpense', function(e){
		e.preventDefault()
		const deleteBtnID = $(this).attr("id")
		var vl = $(this).attr("data-id")
		var cm = "MXo0VE9zQ053VEttWWU0QnZBQ08yUT09Ojp2/6XWpnzKUQYVfd40FI0b"
		var tn = "b3dZaGVJbGs0Q3YyTWw5QlVYOFZyUT09OjoNdkMiRuKtwi3kHprhHEnR"
		var commandType = "delete_command"
		var objName = "Expense"
		var post = {
			"action" : "ins_upd_del_everything", "vl" : vl, "cm" : cm, "tn" : tn, "commandType" : commandType, "objName" : objName,
		}
		swal ({
			title: "Are you sure?", text: "You want to delete this expense permenently?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No",
			closeOnConfirm: false,
			closeOnCancel: false
		}, function(isConfirm) {
			if (isConfirm) {
                $(".confirm").attr("disabled", "disabled")
			    $(".confirm").attr("style", "color: #FFF") 
			    $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
			    $.ajax({    
					method: "POST", url : "api/main.php", data: post, dataType: "JSON",
					success : function(data){
						var Message = data.Message
						var status = data.Status
						if (status == true) {
							swal("", Message, "success")
							$("#" + deleteBtnID).parents("tr").remove()
                        } else {
                            swal("", Message, "error")
                        }
					},
					error : function(data){ }
				})
			}
		})
	})
	
	// ========================== End of Expenses Section ======================================
	
	// ========================== Start of Change Password =====================================
	
	// ========================== Start of Change User Passcode Admin Section ==================

  $(document).on("click", ".btnChangeUserPasscodeAdmin", function (e) {
    e.preventDefault()
    var selected_user_id = $(this).attr("data-id")
    var post_data = { "action": "fetch_user_information_to_change_passcode", "selected_user_id": selected_user_id}
    $(".modal-body").load(selected_user_id)
    $.ajax({
      method: "POST", url: "api/main.php", data: post_data, dataType: "JSON",
      success: function(data) {
        var Message = data.Message
        var status = data.Status
        if (status == true) {
            Message.forEach(function(returned_data, i){
                $("#txtUserIddChangeUserPasscodeAdmin").val(returned_data[0])
                $("#txtUserNameChangeUserPasscodeAdmin").val(returned_data[1])
                $("#txtUserInformationChangeUserPasscodeAdmin").val(returned_data[2] + "(" + returned_data[3] + ")")
			})
        }	
      }, error: function(e) {
        bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
      }          
    })
  })
	
	// ----------------------- Compare password mactch in confirm password ----------------
	$(document).on("focusout", "#confirmPassChange", function () {
		var pass = $("#pass1Change").val()
		if ($(this).val() != pass) {
			bs4pop.notice("<i class='fa fa-exclamation-triangle text-danger'></i> &nbsp; Password and confirm password must match each other, please check!", {type: "warning", position: "topright", appendType: "append"})
			$("#btnChangePassword").prop("disabled", true)
		} else {
			$("#btnChangePassword").prop("disabled", false)
		}
	})
	$(document).on("keyup", "#confirmPassChange", function () {
		var pass = $("#pass1Change").val()
		if ($(this).val() == pass) { $("#btnChangePassword").prop("disabled", false) } else { $("#btnChangePassword").prop("disabled", true) }
	})
	
	$("#changePasswordForm, #changeUserPasscodeAdminForm").submit(function (e) {
				
		e.preventDefault()
		var changing_user_type = $(this).attr("changing-user-type")
		var selected_user_id = $("#txtUserIddChangeUserPasscodeAdmin").val()
		var selected_user_name = $("#txtUserNameChangeUserPasscodeAdmin").val()
		var new_passcode_admin = $("#txtNewPasscodeChangeUserPasscodeAdmin").val()
		var old_passcode_user = $("#oldPasswordChange").val()
		var new_passcode_user = $("#pass1Change").val()
		var confirm_passcode_user = $("#confirmPassChange").val()
		var post_data = {
		    "action" : "change_password", "changing_user_type": changing_user_type, "selected_user_id": selected_user_id, "selected_user_name": selected_user_name, "new_passcode_admin": new_passcode_admin, "old_passcode_user" : old_passcode_user, "new_passcode_user" : new_passcode_user, "confirm_passcode_user" : confirm_passcode_user
		}
		swal ({
			title: "Are you sure?", text: "You want to change this passcode?", type: "", animation: "slide-from-top", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
		}, function(isConfirm) {
			if (isConfirm) {
			    $(".confirm").attr("disabled", "disabled") 
			    $(".confirm").attr("style", "color: #FFF") 
			    $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
		
        		$.ajax({    
        			method: "POST", url : "api/main.php", data: post_data, dataType: "JSON",
        			beforeSend:function(){
        				$("#btnChangePassword, #btnChangeUserPasscodeAdmin").prop('disabled', true)
        				$("#btnChangePassword, #btnChangeUserPasscodeAdmin").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
        			},
        			success : function(data){
        				$("#btnChangePassword, #btnChangeUserPasscodeAdmin").prop('disabled', false)
        				$("#btnChangePassword, #btnChangeUserPasscodeAdmin").html("<i class='fa fa-fw fa-lg fa-pencil'></i>Change Passcode")
        				var Message = data.Message;
        				var status = data.Status;
        				if (status == true) {
        					swal ({
        						title: "Success", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
        					}, function(isConfirm) {
        						if (isConfirm) { location = "manual-logout" }
        					})
        				} else {
        					swal("", Message, "error")
        				}
        			},
        			error : function(data){
        
        			}
        		})
			}
		})
	})
	
	// ========================== End of Change Password ================================================
	
	// ========================== Fetch 2-Step Verification Status ======================================

    $(document).on("click", "#securitySubMenu, #securityMenu", function (e) {

		e.preventDefault()
		
		var objectID = $(this).attr("data-id")
		var tn = "d0p4eGp2N0hBR3BNRC9iTlVqWWlNdz09OjpAe/3KisGcxd2YUmX8Zu4n"
		var cm = "YzhxdFhuWlJFQnJGQy9wU3FqSTR6UT09OjpDkHi5cvvKt7XcWWq7FYt/"

		var post = {
			"action": "fetch_parameterized_everything", "dn": dn, "tn" : tn, "cm" : cm, "objectID": objectID
		}

		$(".modal-body").load(objectID)

		$.ajax({
			method: "POST", url: "api/main.php", data:  post, dataType: "JSON",
			success: function(data) {
				var Message = data.Message;
				var status = data.Status;
				if (status == true) {
				
					var returned_info = Message.split("###")

					var verification_status = returned_info[5];
					if (verification_status == 1) {
					    $("#twoStepVerificationToggle").prop("checked", true)
					} else if (verification_status == 0) {
					    $("#twoStepVerificationToggle").prop("checked", false)
					}
					
				}	
		 	}, error: function(e) {
				bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
			}          
	   })

	})
	
	// ========================== End of Fetch 2-Step Verification Status ======================
	
	// ========================== Start of Enable 2-Step Verification ==========================

    $(document).on("change", "#twoStepVerificationToggle", function (e) {

		e.preventDefault()
		
		var post = {"action" : "enable_disable_2step_verification"};
		
		$.ajax({
			method: "POST", url : "api/main.php", data: post, dataType: "JSON",
			success : function(data) {
                var Message = data.Message;
				var status = data.Status;
				if (status == true) {
                
				} else {
					Message.forEach(function (error) {
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
					})
				}	
		 	}, error: function(e) {
				bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
			}      
		})
	})
	
	// ========================== End of Enable 2-Step Verification ============================

	// ========================== Start of Update Profile ======================================
	
	//Clicking of update user button in the update user model
	$("#updateUserProfileForm").on('submit', function (evt) {
		
		evt.preventDefault()
		
		var formData = new FormData(this)
		formData.append("action", "updateUserProfile")

		$.ajax({
			url: "api/main.php",
			type: "POST",
			data:  formData,
			contentType: false,
			cache: false,
			processData:false,
			beforeSend : function() {
				$("#updateProfileBtn").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
				$("#updateProfileBtn").attr("readonly", true)
	  		}, success: function(data) {
				$("#updateProfileBtn").html("<i class='fa fa-fw fa-lg fa-pencil'></i> Update Profile")
				$("#updateProfileBtn").attr("readonly", false)
				var sts = data.Status;
				var msg = data.Message;
				
				if (sts == true) {
					swal ({
						title: "", text: "User profile has been updated successfully", type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
					}, function(isConfirm) {
						if (isConfirm) { location.reload() }
					})
				} else {
					bs4pop.notice("<i class='fa fa-times-circle text-danger'></i> &nbsp; " + msg, {type: "warning", position: "topright", appendType: "append"})
				}		
		 	}, error: function(e) {
	   			alert(e)
			}          
	   })
	})

	// ========================== End of Update Profile ========================================



	// ========================== Start of System Reports ======================================
	
	// ------------------ Employees Report Section ---------------------------------
	
	$("#customEmployeesReportDate").prop("checked", true)
	$("#employeesReportStartFrom").prop("readonly", true)
	$("#employeesReportEndTo").prop("readonly", true)
	
	$("#customEmployeesReportDate").on('change', function () {
		if ($(this).is(':checked')) {
			$("#employeesReportStartFrom").prop("readonly", true)
			$("#employeesReportStartFrom").val("")
			$("#employeesReportEndTo").prop("readonly", true)
			$("#employeesReportEndTo").val("")
			$("#empNameEmployeesReport").prop("disabled", false)
		} else {
			$("#employeesReportStartFrom").prop("readonly", false)
			$("#employeesReportEndTo").prop("readonly", false)
			$("#empNameEmployeesReport").prop("disabled", true)
		}
	})
	
	$("#empNameEmployeesReport").on('change', function () {
		if ($(this).val() != "") {
			$("#employeesReportStartFrom").prop("readonly", true)
			$("#employeesReportStartFrom").val("")
			$("#employeesReportEndTo").prop("readonly", true)
			$("#employeesReportEndTo").val("")
		} else {
			// Do nothing
		}
	})
	
	$("#employeesReportForm").on('submit', function (e) {
		e.preventDefault()
		var emplInfoEmpReport = $("#empNameEmployeesReport").val()
		var strDateEmpReport = $("#employeesReportStartFrom").val()
		var endTooEmpReport = $("#employeesReportEndTo").val()
		
		$.ajax({
			type: "POST",
			url: "api/main.php",
			data: {
				"action": "employeesReport", 
				emplInfoEmpReport:emplInfoEmpReport, 
				strDateEmpReport:strDateEmpReport, 
				endTooEmpReport:endTooEmpReport
			},
			dataType: "text",
			beforeSend:function(){
				$("#btnEmployeesReport").prop('disabled', true)
				$("#btnEmployeesReport").html("<i class='fa fa-spinner fa-pulse' style='font-size: 18px; margin-left: 5px; margin-bottom: 3px;'></i>")
			},
			success: function (response) {
				$("#btnEmployeesReport").prop('disabled', false)
				$("#btnEmployeesReport").html("<i class='fa fa-search' style='font-size: 18px; margin-left: 5px; margin-bottom: 3px;'></i>")
				$("#empReportSection").html(response)
			}
		})
	})
	
	$(document).on('click', '#printEmployeesReport', function(){
		//Display and open the print dialog box to print the report
		var empReportRestorePage = document.body.innerHTML;
		var empReportPrintArea = document.getElementById("employeesReportPrintArea").innerHTML;
		document.body.innerHTML = empReportPrintArea;
		window.print()
		document.body.innerHTML = empReportRestorePage;	
	})

	// ------------- Print Bank Account Balances --------------------
	$(document).on('click', '#printBankAccountBalances', function(){
		//Display and open the print dialog box to print the report
		var bankAccountBalancesRestorePage = document.body.innerHTML;
		var bankAccountBalancesPrintArea = document.getElementById("bankAccountBalancesPrintArea").innerHTML;
		document.body.innerHTML = bankAccountBalancesPrintArea;
		window.print()
		document.body.innerHTML = bankAccountBalancesRestorePage;
		
	})

	// ============================ Start of Account Statement Section ===========================================

  	$("#txtFromDateSearchAccountStatement").prop("readonly", true)
	$("#txtToDateSearchAccountStatement").prop("readonly", true)
	  
	$("#cmbCustomDateSearchAccountStatement").on('change', function () {
		if ($(this).val() == 8) {
			$("#txtFromDateSearchAccountStatement").prop("readonly", false)
			$("#txtToDateSearchAccountStatement").prop("readonly", false)
			$('#txtFromDateSearchAccountStatement').val(current_date)
			$('#txtToDateSearchAccountStatement').val(current_date)
			$('#txtFromDateSearchAccountStatement').prop("max", current_date)
			$('#txtToDateSearchAccountStatement').prop("max", current_date)
		} else {
			$("#txtFromDateSearchAccountStatement").prop("readonly", true)
			$("#txtFromDateSearchAccountStatement").val("")
			$("#txtToDateSearchAccountStatement").prop("readonly", true)
			$("#txtToDateSearchAccountStatement").val("")			
		}
	})
	  
	$("#searchAccountStatementForm").on('submit', function (e) {
		e.preventDefault()
		var selected_account_id = $("#cmbAccountIddSearchAccountStatement").val()
		var selected_date_type = $("#cmbCustomDateSearchAccountStatement").val()
		var selected_start_date = $("#txtFromDateSearchAccountStatement").val()
		var selected_end_date = $("#txtToDateSearchAccountStatement").val()
		var post = {
			"action": "account_statement", 
			"selected_account_id" : selected_account_id, 
			"selected_date_type" : selected_date_type, 
			"selected_start_date" : selected_start_date, 
			"selected_end_date" : selected_end_date
		}
		$.ajax({
			type: "POST", url: "api/main.php", data: post, dataType: "text",
			beforeSend:function(){
				$("#btnSearchAccountStatement").prop('disabled', true)
				$("#btnSearchAccountStatement").html("<i class='fa fa-spinner fa-pulse' style='font-size: 18px; margin-left: 5px; margin-bottom: 3px;'></i> Please wait")
			},
			success: function (response) {
				$("#btnSearchAccountStatement").prop('disabled', false)
				$("#btnSearchAccountStatement").html("<i class='fa fa-search' style='font-size: 18px; margin-left: 5px; margin-bottom: 3px;'></i> Search")
				$("#accountStatementSection").html(response)
			}
		})
	})
		  
	$(document).on("click", "#printAccountStatement", function () {
		//Display and open the print dialog box to print the report
		var report_restore_page = document.body.innerHTML
		var report_print_area = document.getElementById("accountStatementPrintArea").innerHTML
		document.body.innerHTML = report_print_area
		window.print()
		document.body.innerHTML = report_restore_page
	})

	// ============================ End of Account Statement Section =============================================


	
	// ------------------ Charged Salaries Report Section ---------------------------------
	
	$("#customDateChargeSalariesReport").prop("checked", true)
	$("#startFromChargeSalariesReport").prop("readonly", true)
	$("#endToChargeSalariesReport").prop("readonly", true)
	
	$("#customDateChargeSalariesReport").on('change', function () {
		if ($(this).is(':checked')) {
			$("#startFromChargeSalariesReport").prop("readonly", true)
			$("#startFromChargeSalariesReport").val("")
			$("#endToChargeSalariesReport").prop("readonly", true)
			$("#endToChargeSalariesReport").val("")
		
		} else {
			$("#startFromChargeSalariesReport").prop("readonly", false)
			$("#endToChargeSalariesReport").prop("readonly", false)
		}
	})
	
	$("#chargedSalariesReportForm").on('submit', function (e) {
		e.preventDefault()
		var emplInfoChargeSalRep = $("#empNameChargeSalariesReport").val()
		var monthInfoChargeSalRep = $("#salaryMonthChargeSalariesReport").val()
		var strDateChargeSalRep = $("#startFromChargeSalariesReport").val()
		var endTooChargeSalRep = $("#endToChargeSalariesReport").val()
		
		//alert("Customer: " + emplInfo + " -- " + "Room: " + monthInfo + " -- " + "Start Date: " + strDate + " -- " + "End Date: " + endToo + " -- ")

		$.ajax({
			type: "POST",
			url: "api/main.php",
			data: {
				"action": "charged_salaries_report", 
				emplInfoChargeSalRep:emplInfoChargeSalRep, 
				monthInfoChargeSalRep:monthInfoChargeSalRep, 
				strDateChargeSalRep:strDateChargeSalRep, 
				endTooChargeSalRep:endTooChargeSalRep
			},
			dataType: "text",
			beforeSend:function(){
				$("#btnChargeSalariesReport").prop('disabled', true)
				$("#btnChargeSalariesReport").html("<i class='fa fa-spinner fa-pulse' style='font-size: 18px; margin-left: 5px; margin-bottom: 3px;'></i>")
			},
			success: function (response) {
				$("#btnChargeSalariesReport").prop('disabled', false)
				$("#btnChargeSalariesReport").html("<i class='fa fa-search' style='font-size: 18px; margin-left: 5px; margin-bottom: 3px;'></i>")
				$("#chargeSalariesReportSection").html(response)
			}
		})
	})
	
	$(document).on('click', '#printChargeSalariesReport', function(){
		//Display and open the print dialog box to print the report
		var chargeSalReportRestorePage = document.body.innerHTML;
		var chargeSalReportPrintArea = document.getElementById("chargeSalariesPrintArea").innerHTML;
		document.body.innerHTML = chargeSalReportPrintArea;
		window.print()
		document.body.innerHTML = chargeSalReportRestorePage;	
	})
	
	// ------------------ Salary Payments Report Section ---------------------------------
	
	$("#customDateSalaryPaymentsReport").prop("checked", true)
	$("#startFromSalaryPaymentsReport").prop("readonly", true)
	$("#endToSalaryPaymentsReport").prop("readonly", true)
	
	$("#customDateSalaryPaymentsReport").on('change', function () {
		if ($(this).is(':checked')) {
			$("#startFromSalaryPaymentsReport").prop("readonly", true)
			$("#startFromSalaryPaymentsReport").val("")
			$("#endToSalaryPaymentsReport").prop("readonly", true)
			$("#endToChargeSalariesReport").val("")
		
		} else {
			$("#startFromSalaryPaymentsReport").prop("readonly", false)
			$("#endToSalaryPaymentsReport").prop("readonly", false)
		}
	})
	
	$("#salaryPaymentsReportForm").on('submit', function (e) {
		e.preventDefault()
		var emplInfoSalaPaymRep = $("#empNameSalaryPaymentsReport").val()
		var monthInfoSalaPaymRep = $("#salaryMonthSalaryPaymentsReport").val()
		var strDateSalaPaymRep = $("#startFromSalaryPaymentsReport").val()
		var endTooSalaPaymRep = $("#endToSalaryPaymentsReport").val()
		
		//alert("Customer: " + emplInfo + " -- " + "Room: " + monthInfo + " -- " + "Start Date: " + strDate + " -- " + "End Date: " + endToo + " -- ")

		$.ajax({
			type: "POST",
			url: "api/main.php",
			data: {
				"action": "chargeSalaryPaymentReport", 
				emplInfoSalaPaymRep:emplInfoSalaPaymRep, 
				monthInfoSalaPaymRep:monthInfoSalaPaymRep, 
				strDateSalaPaymRep:strDateSalaPaymRep, 
				endTooSalaPaymRep:endTooSalaPaymRep
			},
			dataType: "text",
			beforeSend:function(){
				$("#btnSalaryPaymentsReport").prop('disabled', true)
				$("#btnSalaryPaymentsReport").html("<i class='fa fa-spinner fa-pulse' style='font-size: 18px; margin-left: 5px; margin-bottom: 3px;'></i>")
			},
			success: function (response) {
				$("#btnSalaryPaymentsReport").prop('disabled', false)
				$("#btnSalaryPaymentsReport").html("<i class='fa fa-search' style='font-size: 18px; margin-left: 5px; margin-bottom: 3px;'></i>")
				$("#salaryPaymentsReportSection").html(response)
			}
		})
	})
	
	$(document).on('click', '#printSalaryPaymentsReport', function(){
		//Display and open the print dialog box to print the report
		var salPaymReportRestorePage = document.body.innerHTML;
		var salPaymReReportPrintArea = document.getElementById("salaryPaymentsPrintArea").innerHTML;
		document.body.innerHTML = salPaymReReportPrintArea;
		window.print()
		document.body.innerHTML = salPaymReportRestorePage;
		location.reload(true)		
	})
	
	// ============================ Start of Expenses Report Section =============================================

	$("#txtFromDateSearchExpensesReport").prop("readonly", true)
	$("#txtToDateSearchExpensesReport").prop("readonly", true)
	  
	$("#cmbCustomDateSearchExpensesReport").on('change', function () {
		if ($(this).val() == 8) {
			$("#txtFromDateSearchExpensesReport").prop("readonly", false)
			$("#txtToDateSearchExpensesReport").prop("readonly", false)
			$('#txtFromDateSearchExpensesReport').val(current_date)
			$('#txtToDateSearchExpensesReport').val(current_date)
			$('#txtFromDateSearchExpensesReport').prop("max", current_date)
			$('#txtToDateSearchExpensesReport').prop("max", current_date)
		} else {
			$("#txtFromDateSearchExpensesReport").prop("readonly", true)
			$("#txtFromDateSearchExpensesReport").val("")
			$("#txtToDateSearchExpensesReport").prop("readonly", true)
			$("#txtToDateSearchExpensesReport").val("")			
		}
	})
	  
	$("#searchExpensesReportForm").on('submit', function (e) {
		e.preventDefault()
		var selected_expense_type = $("#cmbExpenseTypeSearchExpensesReport").val()
		var selected_date_type = $("#cmbCustomDateSearchExpensesReport").val()
		var selected_start_date = $("#txtFromDateSearchExpensesReport").val()
		var selected_end_date = $("#txtToDateSearchExpensesReport").val()
		var post = {
			"action": "expenses_report", 
			"selected_expense_type" : selected_expense_type, 
			"selected_date_type" : selected_date_type, 
			"selected_start_date" : selected_start_date, 
			"selected_end_date" : selected_end_date
		}
		$.ajax({
			type: "POST", url: "api/main.php", data: post, dataType: "text",
			beforeSend:function(){
				$("#btnSearchExpensesReport").prop('disabled', true)
				$("#btnSearchExpensesReport").html("<i class='fa fa-spinner fa-pulse' style='font-size: 18px; margin-left: 5px; margin-bottom: 3px;'></i>")
			},
			success: function (response) {
				$("#btnSearchExpensesReport").prop('disabled', false)
				$("#btnSearchExpensesReport").html("<i class='fa fa-search' style='font-size: 18px; margin-left: 5px; margin-bottom: 3px;'></i>")
				$("#expensesReportSection").html(response)
			}
		})
	})
		  
	$(document).on('click', '#printExpensesReport', function () {
		//Display and open the print dialog box to print the report
		var report_restore_page = document.body.innerHTML
		var report_print_area = document.getElementById("expensesReportPrintArea").innerHTML
		document.body.innerHTML = report_print_area
		window.print()
		document.body.innerHTML = report_restore_page
	})
  
	// ============================ End of Expenses Report Section ===============================================
	
	//========================== End of System Reports ================================================

	//========================== System Logout Process ================================================
	
	// Admins and Normal Users Logout.....
	$(document).on("click", "#logoutOutSide, #logoutMenu", function(e) {
		e.preventDefault()
		const href = $(this).attr('href')
		const getUserName = $(this).attr('data-id')
		swal ({
			title: "Are you sure?", text: "You want to logout " + getUserName, showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: true, closeOnCancel: true
		}, function(isConfirm) {
			if (isConfirm) {						
				swal("", "Logged out, Bye " + getUserName, "success")
				setTimeout(function () { document.location = href }, 500)
			}
		})
    })
    
    // Investors Logout.....
	$(document).on("click", "#investorLogoutOutSide, #investorLogoutMenu", function(e) {
		e.preventDefault()
		const href = $(this).attr('href')
		const getUserName = $(this).attr('data-id')
		swal ({
			title: "Are you sure ?",
			text: "You want to logout as " + getUserName +" ?",
			type: "success",
			showCancelButton: true,
			confirmButtonText: "Yes, logout!",
			cancelButtonText: "No, don't logout!",
			closeOnConfirm: false,
			closeOnCancel: false
		}, function(isConfirm) {
			if (isConfirm) {						
				swal("", "Logged out successfully, Good Bye " + getUserName, "success")
				setTimeout(function () {
				  document.location = href;
				}, 500)
			} else {
				swal("", "Logout process cancelled.", "error")
			}
		})
    })
	
})

// ================= Filling System Functions =======================

// Change the Rank of Menu
function changeMenuRank(all_menu_ids) {
	$.ajax({    
		method: "POST", url : "api/main.php", data: {"action" : "change_menu_rank", "all_menu_ids": all_menu_ids}, dataType: "JSON",
		success : function(data) {
		    console.log(data)
		}
	})
}

// Change the Rank of Submenu
function changeSubmenuRank(all_submenu_ids) {
	$.ajax({    
		method: "POST", url : "api/main.php", data: {"action" : "change_submenu_rank", "all_submenu_ids": all_submenu_ids}, dataType: "JSON",
		success : function(data) {
		    console.log(data)
		}
	})
}

// Fill Identification Document Type
function fillIdentificationDocumentTypes() {
	$.ajax({    
		method: "POST", url : "api/main.php", data: {"action" : "fill_identification_document_types"}, dataType: "JSON",
		success : function(data){
			var Message = data.Message
			var status = data.Status
			var html = '';
			if(status == true){
				html += `<option value="">Select Type</option>`
				Message.forEach(function(returned_data, i){
				    html += `<option value="${returned_data['documentTypeID']}">${returned_data['documentTypeName']}</option>`
				})
				$("#cmbIdentificationDocumentTypeNewEmployee, #cmbIdentificationDocumentTypeUpdateEmployee").html(html)  
			}
		},
		error : function(data){

		}
	})
}

// Fill Employee Departments
function fillEmployeeDepartments() {
	$.ajax({    
		method: "POST", url : "api/main.php", data: {"action" : "fill_employee_departments"}, dataType: "JSON",
		success : function(data){
			var Message = data.Message
			var status = data.Status
			var html = '';
			if(status == true){
				html += `<option value="">Select Department</option>`
				Message.forEach(function(returned_data, i){
				    html += `<option value="${returned_data['departmentID']}">${returned_data['departmentName']}</option>`
				})
				$("#cmbEmployeeDepartmentNameNewEmployee, #cmbEmployeeDepartmentNameUpdateEmployee").html(html)  
			}
		},
		error : function(data){

		}
	})
}

// Fill Employee Positions
function fillEmployeePositions() {
	$.ajax({    
		method: "POST", url : "api/main.php", data: {"action" : "fill_employee_positions"}, dataType: "JSON",
		success : function(data){
			var Message = data.Message
			var status = data.Status
			var html = '';
			if(status == true){
				html += `<option value="">Select Position</option>`
				Message.forEach(function(returned_data, i){
				    html += `<option value="${returned_data['positionID']}">${returned_data['positionName']}</option>`
				})
				$("#cmbEmployeePositionNameNewEmployee, #cmbEmployeePositionNameUpdateEmployee").html(html)  
			}
		},
		error : function(data){

		}
	})
}

// Fill Employee Working Areas
function fillWorkingAreas() {
	$.ajax({    
		method: "POST", url : "api/main.php", data: {"action" : "fill_working_areas"}, dataType: "JSON",
		success : function(data){
			var Message = data.Message
			var status = data.Status
			var html = '';
			if(status == true){
				html += `<option value="">Select Working Area</option>`
				Message.forEach(function(returned_data, i){
				    html += `<option value="${returned_data['workingAreaID']}">${returned_data['workingAreaName']}</option>`
				})
				$("#cmbWorkingAreaNameNewEmployee, #cmbWorkingAreaNameUpdateEmployee").html(html)  
			}
		},
		error : function(data){

		}
	})
}

// Fill Active Employees
function fillActiveEmployees() {
	$.ajax({    
		method: "POST", url : "api/main.php", data: {"action" : "fill_active_employees"}, dataType: "JSON",
		success : function(data){
			var Message = data.Message
			var status = data.Status
			var html = '';
			if(status == true){
				html += `<option value="">Select Employee</option>`
				Message.forEach(function(returned_data, i){
				    html += `<option value="${returned_data['employeeID']}">${returned_data['employeeID']} - ${returned_data['employeeName']} - ${returned_data['employeeMobileNo']}</option>`
				})
				$("#cmbFullNameRegisterUser, #cmbEmployeeIddNewAdvancedSalary, #cmbEmployeeIddUpdateAdvancedSalary, #cmbEmployeeIddSearchAdministrationStaffBulkMessagesAdmin").html(html)  
			}
		},
		error : function(data){

		}
	})
}

// Fill Active Employees Report
function fillActiveEmployeesReport() {
	$.ajax({    
		method: "POST", url : "api/main.php", data: {"action" : "fill_active_employees"}, dataType: "JSON",
		success : function(data){
			var Message = data.Message
			var status = data.Status
			var html = '';
			if(status == true){
				html += `<option value="All">General (All)</option>`
				Message.forEach(function(returned_data, i){
				    html += `<option value="${returned_data['employeeID']}">${returned_data['employeeID']} - ${returned_data['employeeName']} - ${returned_data['employeeMobileNo']}</option>`
				})
				$("#cmbEmployeeIddNameSendAdministrationStaffBulkShortMessage, #cmbEmployeeIdAdvancedSalariesReport").html(html)  
			}
		},
		error : function(data){

		}
	})
}

// Fill active usernames
function fillActiveUsers(){
	$.ajax({
		method: "POST", url : "api/main.php", data: {"action" : "fill_active_users"}, dataType: "JSON",
		success : function(data){
			var Message = data.Message;
			var status = data.Status;
			var html = '';
			if(status == true){
				html += `<option value="">Choose Username</option>`;
				Message.forEach(function(returned_data,i){
					html += `<option value="${returned_data['userID']}">${returned_data['userID']} - ${returned_data['employeeName']} (${returned_data['Username']})</option>`;
				})
				$("#cmbUsernameSearchGeneralReportttt").html(html)  
			}
		},
		error : function(data){

		}
	})
}

// Fill active usernames - reports
function fillActiveUsersReports(){
	$.ajax({
		method: "POST", url : "api/main.php", data: {"action" : "fill_active_users"}, dataType: "JSON",
		success : function(data){
			var Message = data.Message;
			var status = data.Status;
			var html = '';
			if(status == true){
				html += `<option value="">General (All)</option>`;
				Message.forEach(function(returned_data,i){
					html += `<option value="${returned_data['userID']}">${returned_data['userID']} - ${returned_data['employeeName']} (${returned_data['Username']})</option>`;
				})
				$("#cmbUsernameSearchGeneralReport").html(html)  
			}
		},
		error : function(data){

		}
	})
}

// Fill users for privileges
function fillUsersForPrivileges(){
	$.ajax({
		method: "POST", url : "api/main.php", data: {"action" : "fill_users_for_privileges"}, dataType: "JSON",
		success : function(data){
			var Message = data.Message;
			var status = data.Status;
			var html = '';
			if(status == true){
				html += `<option value="">Choose Username</option>`;
				Message.forEach(function(returned_data,i){
					html += `<option value="${returned_data['userID']}">${returned_data['userID']} - ${returned_data['employeeName']} (${returned_data['Username']})</option>`;
				})
				$("#cmbUserIddSearchUserPrivileges, #cmbUserIddSearchUsersForAccountAssociation").html(html)  
			}
		},
		error : function(data){

		}
	})
}

// Fill Expense Type Names
function fillExpenseTypes() {
	$.ajax({    
		method: "POST", url : "api/main.php", data: {"action" : "fill_expense_types"}, dataType: "JSON",
		success : function(data){
			var Message = data.Message
			var status = data.Status
			var html = '';
			if(status == true){
				html += `<option value="">Select Type</option>`
				Message.forEach(function(returned_data, i){
				    html += `<option value="${returned_data['expenseTypeID']}">${returned_data['expenseTypeName']}</option>`
				})
				$("#cmbExpenseTypeRegisterNewExpense").html(html)  
			}
		},
		error : function(data){

		}
	})
}

// Fill Accounts For Admins
function fillAdminAccounts() {
	$.ajax({    
		method: "POST", url : "api/main.php", data: {"action" : "fill_admin_accounts"}, dataType: "JSON",
		success : function(data){
			var Message = data.Message;
			var status = data.Status;
			var html = '';
			if(status == true){
				html += `<option value="">Select Account</option>`;
				Message.forEach(function(accounts_data, i){
				    if (accounts_data['gatewayType'] === "1") {
				        html += `<option value="${accounts_data['accountNoID']}">${accounts_data['gatewayName']} (${accounts_data['accountNumber']})</option>`;
				    } else if (accounts_data['gatewayType'] === "2") {
				        html += `<option value="${accounts_data['accountNoID']}">${accounts_data['gatewayName']} ${accounts_data['accountNoName']} (${accounts_data['accountNumber']})</option>`;
				    } else if (accounts_data['gatewayType'] === "3") {
				        html += `<option value="${accounts_data['accountNoID']}">${accounts_data['accountNoName']} (${accounts_data['accountNumber']})</option>`;
				    }
				})
				$("#cmbAccountNameNewAccountTransaction, #cmbAccountIddSearchAccountStatement").html(html)  
			}
		},
		error : function(data){

		}
	})
}

// Fill Deposit Accounts 
function fillDepositAccounts() {
	$.ajax({    
		method: "POST", url : "api/main.php", data: {"action" : "fill_deposit_accounts"}, dataType: "JSON",
		success : function(data){
			var Message = data.Message;
			var status = data.Status;
			var html = '';
			if(status == true){
				html += `<option value="">Select Account</option>`;
				Message.forEach(function(accounts_data, i){
				    if (accounts_data['gatewayType'] === "1") {
				        html += `<option value="${accounts_data['accountNoID']}">${accounts_data['gatewayName']} (${accounts_data['accountNumber']})</option>`;
				    } else if (accounts_data['gatewayType'] === "2") {
				        html += `<option value="${accounts_data['accountNoID']}">${accounts_data['gatewayName']} ${accounts_data['accountNoName']} (${accounts_data['accountNumber']})</option>`;
				    } else if (accounts_data['gatewayType'] === "3") {
				        html += `<option value="${accounts_data['accountNoID']}">${accounts_data['accountNoName']} (${accounts_data['accountNumber']})</option>`;
				    }
				})
				$("#cmbDepositAccountRegisterCustomerPayment0").html(html)  
			}
		},
		error : function(data){

		}
	})
}

// Fill Deposit Accounts for Reports
function fillDepositAccountsReport() {
	$.ajax({    
		method: "POST", url : "api/main.php", data: {"action" : "fill_deposit_accounts"}, dataType: "JSON",
		success : function(data){
			var Message = data.Message;
			var status = data.Status;
			var html = '';
			if(status == true){
				html += `<option value="">General (All)</option>`;
				Message.forEach(function(accounts_data, i){
				    if (accounts_data['gatewayType'] === "1") {
				        html += `<option value="${accounts_data['accountNoID']}">${accounts_data['gatewayName']} (${accounts_data['accountNumber']})</option>`;
				    } else if (accounts_data['gatewayType'] === "2") {
				        html += `<option value="${accounts_data['accountNoID']}">${accounts_data['gatewayName']} ${accounts_data['accountNoName']} (${accounts_data['accountNumber']})</option>`;
				    } else if (accounts_data['gatewayType'] === "3") {
				        html += `<option value="${accounts_data['accountNoID']}">${accounts_data['accountNoName']} (${accounts_data['accountNumber']})</option>`;
				    }
				})
				$("#cmbAccountIddSearchAccountStatement").html(html)  
			}
		},
		error : function(data){

		}
	})
}

// Fill Withdrawal Accounts 
function fillWithdrawalAccounts() {
	$.ajax({    
		method: "POST", url : "api/main.php", data: {"action" : "fill_withdrawal_accounts"}, dataType: "JSON",
		success : function(data){
			var Message = data.Message;
			var status = data.Status;
			var html = '';
			if(status == true){
				html += `<option value="">Select Account</option>`;
				Message.forEach(function(accounts_data, i){
				    if (accounts_data['gatewayType'] === "1") {
				        html += `<option value="${accounts_data['accountNoID']}">${accounts_data['gatewayName']} (${accounts_data['accountNumber']})</option>`;
				    } else if (accounts_data['gatewayType'] === "2") {
				        html += `<option value="${accounts_data['accountNoID']}">${accounts_data['gatewayName']} ${accounts_data['accountNoName']} (${accounts_data['accountNumber']})</option>`;
				    } else if (accounts_data['gatewayType'] === "3") {
				        html += `<option value="${accounts_data['accountNoID']}">${accounts_data['accountNoName']} (${accounts_data['accountNumber']})</option>`;
				    }
				})
				$("#cmbExpensesWithdrawalAccountRegisterNewExpense").html(html)  
			}
		},
		error : function(data){

		}
	})
}

// Fill Withdrawal Accounts Reports
function fillWithdrawalAccountsReport() {
	$.ajax({    
		method: "POST", url : "api/main.php", data: {"action" : "fill_withdrawal_accounts"}, dataType: "JSON",
		success : function(data){
			var Message = data.Message;
			var status = data.Status;
			var html = '';
			if(status == true){
				html += `<option value="">General (All)</option>`;
				Message.forEach(function(accounts_data, i){
				    if (accounts_data['gatewayType'] === "1") {
				        html += `<option value="${accounts_data['accountNoID']}">${accounts_data['gatewayName']} (${accounts_data['accountNumber']})</option>`;
				    } else if (accounts_data['gatewayType'] === "2") {
				        html += `<option value="${accounts_data['accountNoID']}">${accounts_data['gatewayName']} ${accounts_data['accountNoName']} (${accounts_data['accountNumber']})</option>`;
				    } else if (accounts_data['gatewayType'] === "3") {
				        html += `<option value="${accounts_data['accountNoID']}">${accounts_data['accountNoName']} (${accounts_data['accountNumber']})</option>`;
				    }
				})
				$("#cmbAccountIddSearchAccountStatementdd").html(html)  
			}
		},
		error : function(data){

		}
	})
}



// Convert number figures to words functions
function moneyValueToWords(number) {  
    var digit = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'];  
    var elevenSeries = ['Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'];  
    var countingByTens = ['Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'];  
    var shortScale = ['', 'Thousand', 'Million', 'Billion', 'Trillion'];  

    number = number.toString(); number = number.replace(/[\, ]/g, ''); if (number != parseFloat(number)) return 'Is not valid number'; var x = number.indexOf('.'); if (x == -1) x = number.length; if (x > 15) return 'Too big number'; var n = number.split(''); var str = ''; var sk = 0; for (var i = 0; i < x; i++) { if ((x - i) % 3 == 2) { if (n[i] == '1') { str += elevenSeries[Number(n[i + 1])] + ' '; i++; sk = 1; } else if (n[i] != 0) { str += countingByTens[n[i] - 2] + ' '; sk = 1; } } else if (n[i] != 0) { str += digit[n[i]] + ' '; if ((x - i) % 3 == 0) str += 'Hundred '; sk = 1; } if ((x - i) % 3 == 1) { if (sk) str += shortScale[(x - i - 1) / 3] + ' '; sk = 0; } } if (x != number.length) { var y = number.length; str += 'Point '; for (var i = x + 1; i < y; i++) str += digit[n[i]] + ' '; } str = str.replace(/\number+/g, ' '); return str.trim() + " Dollar";  

}

// ---------------------- Format Dollar ---------------------------------------
function formatDollar(num) {
	var p = num.toFixed(2).split(".")
	return "$" + p[0].split("").reverse().reduce(function(acc, num, i, orig) {
		return num + (num != "-" && i && !(i % 3) ? "," : "") + acc;
	}, "") + "." + p[1];
}



