var usrgrp_obj = null ;

$(document).ready(function() 
{ 
	$('#formUserGroup').hide() ;
	$('#btnUsrGrpClear').button().bind('click',clearUserGroup) ;
	$('#btnUsrGrpUpdate').button().bind('click',updateUserGroup) ;
	$('#btnUsrGrpAdd').button().bind('click',addUserGroup) ;
	$('#btnUsrGrpPrint').button().bind('click',printUserGroup) ;
	// $('#usrgrp-tabs').tabs() ;
	$('#txtUsrGrpDesc').focus() ;
	$(window).resize(resizeUsrGrpGrid) ;
	resizeUsrGrpGrid() ;
	clearUserGroup();
	filterUserGroup();
}) ;

function showFormUserGroup(){
	clearUserGroup() ;
	$('#formUserGroup').show('slow') ;
}

function closeFormUserGroup(){
	clearUserGroup() ;
	$('#formUserGroup').hide('slow') ;
}

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

function clearUserGroup() {
	$('#txtUsrGrpId').val("Auto") ;
	$('#txtUsrGrpDesc').val("") ;
	$('#usrgrp-admin').find(':checkbox').each(function() {
		$(this).prop('checked',false) ;
	});
	$('#usrgrp-hr').find(':checkbox').each(function() {
		$(this).prop('checked',false) ;
	});
	$('#usrgrp-activity').find(':checkbox').each(function() {
		$(this).prop('checked',false) ;
	});
	// $('#usrgrp-tabs').tabs("option", "active", 0) ;
	$('#txtUsrGrpDesc').focus() ;
	$('#btnUsrGrpUpdate').prop('disabled','disabled');
	$('#usrgrp_err_desc').hide() ;
	$('#usrgrp_err_mesg').text('') ;
	if (usrgrp_obj != null && usrgrp_obj != undefined)
	{
		$($(usrgrp_obj).closest("tr")).removeClass("sbg-row-selected") ;
	}
	usrgrp_obj = null;
}

function filterUserGroup() {
	var data = { "type": C_LIST} ;
	var url = "request.pzx?c=" + usrgrp_url + "&d=" + new Date().getTime() ;		
	callServer(url,"json",data,showUserGroupFilterList,usrgrp_obj) ;
}

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

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

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

		// column sorting
		sortable: true,

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

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

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

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

function updateUserGroup() {
	saveUserGroup(C_UPDATE) ;
}
function addUserGroup() {
	saveUserGroup(C_ADD) ;
}
function saveUserGroup(type) {
	if (validateUserGroup()) {
		var data = { 
			"type": type, 
			"id": $('#txtUsrGrpId').val(), 
			"desc": $('#txtUsrGrpDesc').val(),
			"admin": getAdmin(),
			"hr": getHr(),
			"activity": getActivity(),
			"portal": getPortal(),
		};
		var url = "request.pzx?c=" + usrgrp_url + "&d=" + new Date().getTime() ;
		callServer(url,"json",data,onUserGroupResponse,usrgrp_obj) ;
	}
}
function printUserGroup() {
	var url = "report.pzx?c=" + usrgrp_url + "&d=" + new Date().getTime();
	showReport(url) ;
}
function editUserGroup(id,obj) {
	var data = { "type": C_GET,"id": id} ;
	var url = "request.pzx?c=" + usrgrp_url + "&d=" + new Date().getTime();		
	clearUserGroup() ;
	showFormUserGroup();
	usrgrp_obj = obj ;
	$($(obj).closest("tr")).addClass("sbg-row-selected");
	callServer(url,"json",data,showUserGroup,obj) ;
}

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

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

	swal("Confirm you want to delete User Group 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=" + usrgrp_url + "&d=" + new Date().getTime() ;
			  callServer(url,"json",data,onUserGroupResponse,obj) ;
		  break;
		}
	  });
}
function showUserGroup(obj,resp) {
	if (resp.status == C_OK) {
		$('#txtUsrGrpId').val(resp.data.id) ;
		$('#txtUsrGrpDesc').val(resp.data.desc) ;
		$('#btnUsrGrpUpdate').prop('disabled','') ;
		$('#chkAdmSet').prop('checked',resp.data.admin.setting) ;
		$('#chkAdmCoy').prop('checked',resp.data.admin.company) ;
		$('#chkAdmUser').prop('checked',resp.data.admin.user) ;
		$('#chkAdmGroup').prop('checked',resp.data.admin.group);
		$('#chkAdmReset').prop('checked',resp.data.admin.reset) ;
		$('#chkAdmResetHistory').prop('checked',resp.data.admin.reset_history) ;
		$('#chkAdmContentCategory').prop('checked',resp.data.admin.content_category) ;
		$('#chkAdmContentFiles').prop('checked',resp.data.admin.content_files) ;
		$('#chkAdmContentNews').prop('checked',resp.data.admin.content_news) ;
        
		$('#chkHrEmp').prop('checked',resp.data.hr.employee) ;
		$('#chkHrDept').prop('checked',resp.data.hr.dept) ;
		$('#chkHrType').prop('checked',resp.data.hr.type) ;
		$('#chkHrJob').prop('checked',resp.data.hr.job) ;
		$('#chkHrNat').prop('checked',resp.data.hr.nat) ;
		$('#chkHrRace').prop('checked',resp.data.hr.race) ;
		$('#chkHrPermit').prop('checked',resp.data.hr.permit) ;
		$('#chkHrEmpPassword').prop('checked',resp.data.hr.empPassword) ;
		$('#chkHrEmpPurge').prop('checked',resp.data.hr.empPurge) ;
		$('#chkHrTransPurge').prop('checked',resp.data.hr.transPurge) ;

		//service
		$('#chkActivityTaxes').prop('checked',resp.data.activity.activityTaxes) ;
		$('#chkActivityCustomer').prop('checked',resp.data.activity.activityCustomer) ;
		$('#chkActivityBrand').prop('checked',resp.data.activity.activityBrand) ;
		$('#chkActivityModel').prop('checked',resp.data.activity.activityModel) ;
		$('#chkActivityProject').prop('checked',resp.data.activity.activityProject) ;
		$('#chkActivityPhase').prop('checked',resp.data.activity.activityPhase) ;
		$('#chkActivityExpense').prop('checked',resp.data.activity.activityExpense) ;
		$('#chkActivityProduct').prop('checked',resp.data.activity.activityProduct) ;
		$('#chkActivityCurrency').prop('checked',resp.data.activity.activityCurrency) ;
		$('#chkActivityConsultant').prop('checked',resp.data.activity.activityConsultant) ;

		//portal
		$('#chkPortalCustomerMaster').prop('checked',resp.data.portal.customerMaster) ;
		$('#chkPortalSalesQuotation').prop('checked',resp.data.portal.salesQuotation) ;
		$('#chkPortalJobQuotation').prop('checked',resp.data.portal.jobQuotation) ;
		$('#chkPortalJobPlan').prop('checked',resp.data.portal.jobPlan) ;
		$('#chkPortalService').prop('checked',resp.data.portal.service) ;
		$('#chkPortalReports').prop('checked',resp.data.portal.reports) ;

		$('#txtUsrGrpDesc').focus() ;
	}
	else {
		swal("System Message",resp.mesg) ;
	}
}
function onUserGroupResponse(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");
		}
		$('#sbg-popup-box').html(resp.mesg) ;
		$('#sbg-popup-box').show() ;
		$('#sbg-popup-box').fadeOut(5000) ;
		clearUserGroup() ;
		filterUserGroup();
		closeFormUserGroup();
	}
	else 
		swal("Error",resp.mesg) ;
}
function validateUserGroup() {
	$('#usrgrp_err_mesg').text('') ;
	
	if ($('#txtUsrGrpDesc').val()=="")
	{
		$('#usrgrp_err_desc').show() ;
		$('#txtUsrGrpDesc').focus() ;
		swal("User Group description can not be blank.") ;
		return false ;
	}
	else 
		$('#usrgrp_err_desc').hide() ;
			
	return true ;
}
function getAdmin() {
	return { "setting"	: getAccess('chkAdmSet'),
		"company"		: getAccess('chkAdmCoy'),
		"user"			: getAccess('chkAdmUser'),
		"group"			: getAccess('chkAdmGroup'),
		"reset"			: getAccess('chkAdmReset'),
		"reset_history" : getAccess('chkAdmResetHistory'),
		"content_category" : getAccess('chkAdmContentCategory'),
		"content_files" : getAccess('chkAdmContentFiles'),
		"content_news" : getAccess('chkAdmContentNews') 
	} ;
}
function getHr() {
	return { "employee"	: getAccess('chkHrEmp'),
		"type"			: getAccess('chkHrType'),
		"dept"			: getAccess('chkHrDept'),
		"job"			: getAccess('chkHrJob'),
		"nat"			: getAccess('chkHrNat'),
		"race"			: getAccess('chkHrRace'),
		"permit"		: getAccess('chkHrPermit'),
		"empPassword"	: getAccess('chkHrEmpPassword'),
		"empPurge"		: getAccess('chkHrEmpPurge'),
		"transPurge"	: getAccess('chkHrTransPurge') 
	} ;
}

function getActivity() {
	return { "activity_taxes"         : getAccess('chkActivityTaxes'),
		"activity_customer"           : getAccess('chkActivityCustomer'),
		"activity_brand"           	  : getAccess('chkActivityBrand'),
		"activity_model"           	  : getAccess('chkActivityModel'),
		"activity_project"            : getAccess('chkActivityProject'),
		"activity_phase"              : getAccess('chkActivityPhase'),
		"activity_expense"            : getAccess('chkActivityExpense'),
		"activity_product"            : getAccess('chkActivityProduct'),
		"activity_currency"           : getAccess('chkActivityCurrency') ,
		"activity_consultant"         : getAccess('chkActivityConsultant') 
	};
}
function getPortal() {
	return { 
		"portal_customer_master" 	: getAccess('chkPortalCustomerMaster'),
		"portal_sales_quotation"	: getAccess('chkPortalSalesQuotation'),
		"portal_job_quotation"		: getAccess('chkPortalJobQuotation'),
		"portal_job_plan"			: getAccess('chkPortalJobPlan'),
		"portal_service"			: getAccess('chkPortalService'),
		"portal_reports"			: getAccess('chkPortalReports'),
	};
}
function getAccess(id) {
	if ($('#' + id).is(':checked'))
		return "1";
	else 
		return "0";
}