var user_obj = null ;
var m_absent_index;

$(document).ready(function() 
{ 
	$('#formUser').hide() ;
	$('input').css('marginTop', 0); 
	$('input').css('marginBottom',0);
	$('select').css('marginTop',0) ;
	$('select').css('marginBottom',0) ;
	
	var dteopt = {
			todayHighlight: true,
		    orientation: "bottom left",
		    autoclose: true,
		    format: 'dd/mm/yyyy',
		    templates: {
		        leftArrow: '<i class="la la-angle-left"></i>',
		        rightArrow: '<i class="la la-angle-right"></i>'
		    }
		}

	$("#txtUserStart").datepicker(dteopt) ;
	$("#txtUserExpiry").datepicker(dteopt) ;
	$("#txtUserAbsentStart").datepicker(dteopt) ;
	$("#txtUserAbsentEnd").datepicker(dteopt) ;
	$('#btnUserClear').button().bind('click',clearUser) ;
	$('#btnUserUpdate').button().bind('click',updateUser) ;
	$('#btnUserAdd').button().bind('click',addUser) ;
	$('#btnUserPrint').button().bind('click',printUser) ;
	// $('#user-tabs').tabs() ;
	$('#txtUserName').focus() ;
	$(window).resize(resizeUserGrid) ;
	resizeUserGrid() ;
	clearUser() ;
	filterUser();
}) ;

function showFormUser(){
	$('#formUser').show('slow') ;
	populateLocation(0);
	
}

function closeFormUser(){
	clearUser() ;
	$('#formUser').hide('slow') ;
}	

function resizeUserGrid() {
	var h = $("#sbg-center-panel").outerHeight() - $("#sbg-user-entry").outerHeight() - 55;
	$("div#sbg-user-data").css("height", h +'px') ;		
}
function clearUser() {
    m_absent_index = 0;
	$('#txtUserId').val("Auto") ;
	$('#txtUserName').val("") ;
	$('#txtUserFull').val("") ;
	$('#txtUserEmail').val("") ;
	$('#txtUserStart').val("") ;
	$('#txtUserExpiry').val("") ;
    
    $('#txtUserExpiry').prop('readonly', false);
    var dteopt = {
			todayHighlight: true,
		    orientation: "bottom left",
		    autoclose: true,
		    format: 'dd/mm/yyyy',
		    templates: {
		        leftArrow: '<i class="la la-angle-left"></i>',
		        rightArrow: '<i class="la la-angle-right"></i>'
		    }
		}
	$("#txtUserExpiry").datepicker(dteopt) ;
	
	$('#cobUserDept').val("0") ;
	$('#cobUserDesignation').val("0") ;
	$('#cobUserSubstitute').val("") ;
	$('#cobUserGroup').val("") ;
	$('#cobUserCoy').val(1) ;
	// $('#user-tabs').tabs("option", "active", 0) ;
	$('#txtUserName').focus() ;
	$('#btnUserUpdate').prop('disabled','disabled') ;
	$('#cobDept').val('');
	$('#cobUserLocation').html('');
	
	$('#user_err_name').hide() ;
	$('#user_err_full').hide() ;
	$('#user_err_group').hide() ;
	$('#user_err_mesg').text('') ;
	if (user_obj != null && user_obj != undefined)
	{
		$($(user_obj).closest("tr")).removeClass("sbg-row-selected") ;
	}
    $('#tblUserAbsentHistory').empty();
	user_obj = null;
}

function filterUser() {
	var data = { "type": C_LIST} ;
	var url = "request.pzx?c=" + user_url + "&d=" + new Date().getTime() ;		
	callServer(url,"json",data,showUserFilterList,user_obj) ;
}

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

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

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

		// column sorting
		sortable: true,

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

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

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

		columns: [
			{
				field: "id",
				title: "ID",
				width:30,
			}, {
				field: "name",
				title: "Name",
				width:150,
			}, {
				field: "fullname",
				title: "Full Name",
				width:200,
			}, {
				field: "group",
				title: "Group",
				width:120,
			}, {
				field: 'actions',
				title: 'Actions',
				sortable: true,
				width: 480,
				overflow: 'visible',
		}],
	});
}

function addAbsentHistory(){
    
    if ($('#txtUserAbsentStart').val()=="" || $('#txtUserAbsentEnd').val()==""){
		swal("Error","Please put in the start date and the end date.") ;
		return;
    }
	m_absent_index++;
	$('#tblUserAbsentHistory').append("<tr id='trAbsentHistory" + m_absent_index + "'>" +
		"<td style='width:50%;text-align:center;'>" + $("#txtUserAbsentStart").val() + "</td>" +
		"<td style='width:40%;text-align:center;'>" + $("#txtUserAbsentEnd").val() + "</td>" +
		"<td style='width:10%px;text-align:center;'><a href='javascript:' onclick='removeAbsentHistory(" + m_absent_index + ")'><i class='flaticon-delete'></i></a></td></tr>"); 
}
function removeAbsentHistory(index){
	$('#trAbsentHistory'+index).remove() ;
}
function updateUser() {
	saveUser(C_UPDATE) ;
}
function addUser() {
	saveUser(C_ADD) ;
}
function generateAbsentHistoryLines(){
	var lines = "" ;
	var sep = "" ;
	$('#tblUserAbsentHistory tr').each(function() { 
		start = $(this).find("td").eq(0).html()  ;
		end = $(this).find("td").eq(1).html() ;
        
        lines = lines + sep + start  + "~" + end;
        sep = "|" ;
	}); 
	return lines ;
}
function showAbsentHistoryLines(lines){
    
	if (lines == undefined || lines == null || lines == "") return ;
	
	var line = lines.split('|') ;
	var fld = "" ;
	m_absent_index = 0 ;
	for (var i = 0 ; i < line.length ; i++) {
		if (line[i] != "") {
			fld = line[i].split('~') ;
			m_absent_index++;
			$('#tblUserAbsentHistory').append("<tr id='trAbsentHistory" + m_absent_index + "'>" +
                                                "<td style='width:50%;text-align:center;'>" + fld[0] + "</td>" +
                                                "<td style='width:40%;text-align:center;'>" + fld[1] + "</td>" +
                                                "<td style='width:10%px;text-align:center;'>" + 
                                                "<a href='javascript:' onclick='removeAbsentHistory(" + m_absent_index + ")'><i class='flaticon-delete'></i></a></td></tr>"); 
			
		}
	}
}
function saveUser(type) {
	if (validateUser()) {
		var block = "0" ;
        
		var data = { "type": type, 
                        "id": $('#txtUserId').val(), 
                        "name": $('#txtUserName').val(),
						"email": $('#txtUserEmail').val(),
						"phone": $('#txtUserPhone').val(), 
                        "start": $('#txtUserStart').val(), 
                        "expiry": $('#txtUserExpiry').val(),
                        "block": block,	
                        "fullname": $('#txtUserFull').val(), 
                        "designation_id": $('#cobUserDesignation').val(), 
                        "substitute_id": $('#cobUserSubstitute').val(), 
                        "dept_id": $('#cobUserDept').val(), 
                        "group": $('#cobUserGroup').val(),
						"coy": $('#cobUserCoy').val(),
						"user_location": $('#cobUserLocation').val(),
                        "absent_history" : generateAbsentHistoryLines()};
		var url = "request.pzx?c=" + user_url + "&d=" + new Date().getTime() ;
		callServer(url,"json",data,onUserResponse,user_obj) ;
	}
}
function printUser() {
	var url = "report.pzx?c=" + user_url + "&d=" + new Date().getTime();
	showReport(url) ;
}
function editUser(id,obj) {
	var data = { "type": C_GET,"id": id} ;
	var url = "request.pzx?c=" + user_url + "&d=" + new Date().getTime();		
	clearUser() ;
	showFormUser();
	user_obj = obj ;
	$($(obj).closest("tr")).addClass("sbg-row-selected");
	callServer(url,"json",data,showUser,obj) ;
}

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

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

	swal("Confirm you want to delete User id : " + id + "?", {
		buttons: {
			ok: true,
		  cancel: "Cancel",
		},
	  })
	  .then((value) => {
		switch (value) {
		  case "ok":
			  var data = {"type": C_DELETE,"id": id} ;
			  var url = "request.pzx?c=" + user_url + "&d=" + new Date().getTime() ;
			  callServer(url,"json",data,onUserResponse,obj) ;
		  break;
		}
	  });
}
function showUser(obj,resp) {
	if (resp.status == C_OK) {
		$('#txtUserId').val(resp.data.id) ;
		$('#txtUserName').val(resp.data.name) ;
		$('#txtUserFull').val(resp.data.fullname) ;
		$('#txtUserEmail').val(resp.data.email) ;
		$('#txtUserPhone').val(resp.data.phone) ;
		$('#txtUserStart').val(resp.data.start) ;
		$('#txtUserExpiry').val(resp.data.expiry) ;
        
		$('#cobUserDesignation').val(resp.data.designation_id) ;
		$('#cobUserSubstitute').val(resp.data.substitute_id) ;
		$('#cobUserDept').val(resp.data.dept_id) ;
		$('#cobUserGroup').val(resp.data.group) ;
		$('#cobUserCoy').val(resp.data.coy) ;
		populateLocation(resp.data.user_location);
		//$('#cobUserLocation').val(resp.data.user_location) ;
        showAbsentHistoryLines(resp.data.absent_history);
        
        $('#txtUserExpiry').prop('readonly', resp.data.cannot_edit_expire);
        if (resp.data.cannot_edit_expire){
            $("#txtUserExpiry").datepicker('destroy'); 
            $("#txtUserExpiry").removeClass("hasDatepicker").removeAttr('txtUserExpiry');
        } else {
            var dteopt = {
			todayHighlight: true,
		    orientation: "bottom left",
		    autoclose: true,
		    format: 'dd/mm/yyyy',
		    templates: {
		        leftArrow: '<i class="la la-angle-left"></i>',
		        rightArrow: '<i class="la la-angle-right"></i>'
		    }
		}
            $("#txtUserExpiry").datepicker(dteopt) ;
        }
		//if (resp.data.block == "1")
			//$('#chkBlock').prop("checked", true); 
		$('#btnUserUpdate').prop('disabled','') ;
		$('#txtUserName').focus() ;
		
	}
	else {
		swal("System Message",resp.mesg) ;
	}
}
function populateLocation(user_location) {
	var data = { "type": "POPULATE_LOCATION", "coy_id":$('#cobUserCoy').val(),"user_location":user_location} ;
	var url = "request.pzx?c=" + user_url + "&d=" + new Date().getTime() ;		
	callServer(url,"json",data,onUserPopulateResponse,user_obj) ;
}
function onUserPopulateResponse(obj,resp) {
	if (resp.status == C_OK) {
		 if(resp.type == "POPULATE_LOCATION"){
			$('#cobUserLocation').html();
			$('#cobUserLocation').html(resp.data.html);
			$('#cobUserLocation').val(resp.data.user_location);
		}		
	}
	else 
		swal("Error",resp.mesg) ;
}
function onUserResponse(obj,resp) {
	if (resp.status == C_OK) {
		if (resp.type == C_ADD) {
			swal("Successfull!", "Your Item Successfully add to the system", "success"); 
		} else if (resp.type == C_DELETE) {
			swal("Successfull!", "Your Item Successfully delete to the system", "success");
		} else if (resp.type == C_UPDATE) {
			swal("Successfull!", "Your Item Successfully update to the system", "success");
		} 
		
		if(resp.type == C_GET + '_EMP'){
		} else {
			$('#sbg-popup-box').html(resp.mesg) ;
			$('#sbg-popup-box').show() ;
			$('#sbg-popup-box').fadeOut(5000) ;
			clearUser() ;
			filterUser();
			closeFormUser();
		}
	}
	else 
		swal("Error",resp.mesg) ;
}
function validateUser() {
	$('#user_err_mesg').text('') ;
	if ($('#txtUserName').val()=="")
	{
		$('#user_err_name').show() ;
		$('#txtUserName').focus() ;
		swal("User signin name can not be blank.") ;
		return false ;
	}
	else 
		$('#user_err_name').hide() ;
		
	if ($('#txtUserFull').val()=="")
	{
		$('#user_err_full').show() ;
		$('#txtUserFull').focus() ;
		swal("You must enter the name of this user.") ;
		return false ;
	}
	else 
		$('#user_err_full').hide() ;
		
	if ($('#cobUserGroup').val() == "") {
		$('#user_err_group').show() ;
		$('#cobUserGroup').focus() ;
		swal("You must assign a User group to this user") ;
		return false 
	}
	else 
		$('#user_err_group').hide() ;
		
    if ($('#txtUserId').val() == $('#cobUserSubstitute').val()){
		swal("The substitute must be different from the user itself.") ;
		return false;
    }

    if ($('#cobUserDesignation').val() == 0){
		swal("You must choose the designation of this user.") ;
		return false;
    }
    
	return true ;
}