var dept_obj = null ;
var m_interidx = 0;
$(document).ready(function() 
{ 
	$('#formDept').hide() ;
	$('#btnDeptClear').button().bind('click',clearDept) ;
	$('#btnDeptUpdate').button().bind('click',updateDept) ;
	$('#btnDeptAdd').button().bind('click',addDept) ;
	$('#btnDeptPrint').button().bind('click',printDept) ;
	// $('#dept-tabs').tabs() ;
	$('#txtDeptDesc').focus() ;
	$(window).resize(resizeDeptGrid) ;
	resizeDeptGrid() ;
	clearDept() ;
	filterDept();
}) ;

function showFormDept(){
	clearDept() ;
	$('#formDept').show('slow') ;
}

function closeFormDept(){
	clearDept() ;
	$('#formDept').hide('slow') ;
}

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

function clearDept() {
	$('#txtDeptId').val("Auto") ;
	$('#txtDeptDesc').val("") ;
	$('#txtDeptRef').val("") ;
	// $('#dept-tabs').tabs("option", "active", 0) ;
	$('#txtDeptDesc').focus() ;
	$('#btnDeptUpdate').prop('disabled','disabled') ;
	
	$('#tblDeptInterPermission').empty() ;
	$('#dept_err_mesg').text('') ;
	$('#dept_err_desc').hide() ;
	if (dept_obj != null && dept_obj != undefined)
	{
		$($(dept_obj).closest("tr")).removeClass("sbg-row-selected") ;
	}
	dept_obj = null;
}

function filterDept() {
	var data = { "type": C_LIST} ;
	var url = "request.pzx?c=" + dept_url + "&d=" + new Date().getTime() ;		
	callServer(url,"json",data,showDeptFilterList,dept_obj) ;
}

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

function init_dt() {
	var datatable = $('.sbg-dept-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:150,
			}, {
				field: "ref",
				title: "Reference",
				width: 100,
			}, {
				field: 'actions',
				title: 'Actions',
				sortable: true,
				width: 510,
				overflow: 'visible',
		}],
	});
}

function addDeptInterPermission(){
    
    if ($('#cobDeptInterPermission').val() == '0'){
		swal("Error","Please select the item, default UOM and default taxes type .") ;
		return;
    }
    m_interidx++;
    $('#tblDeptInterPermission').append("<tr id='trDeptInterPermission" + m_interidx + "'><td style='width:30px;display:none'>" +m_interidx+ "</td>" +
            "<td style='display:none'>" + $('#cobDeptInterPermission').val() + "</td>" +
            "<td style='width:300px;'>" + $("#cobDeptInterPermission option:selected").text() + "</td>" +
            "<td style='text-align:center;'><a href='javascript:' onclick='removeDeptInterPermission(" + m_interidx + ")'><i class='flaticon-delete'></i></a></td></tr>"); 
}
function removeDeptInterPermission(idx) {
    $('#trDeptInterPermission'+idx).remove() ;
}
function getDeptInterPermission(){
    var lines = "" ;
    var sep = "" ;
    $('#tblDeptInterPermission tr').each(function() { 
        inter = $(this).find("td").eq(1).html()  ;
        lines = lines + sep + inter;
        sep = "|" ;
    }); 
    return lines ;
}
function showDeptInterPermission(lines) {
    if (lines == undefined || lines == null || lines == "") return ;

    var line = lines.split('|') ;
    var fld = "" ;
    m_interidx = 0 ;
    for (var i = 0 ; i < line.length ; i++) {
        if (line[i] != "") {
            fld = line[i].split('~') ;
            m_interidx++;
            $('#tblDeptInterPermission').append("<tr id='trDeptInterPermission" + m_interidx + "'><td style='width:30px;display:none'>" +m_interidx+ "</td>" +
                        "<td style='display:none'>" + fld[0] + "</td>" +
                        "<td style='width:300px;'>" + fld[1] + "</td>" +
                        "<td style='width:40px;text-align:center;'><a href='javascript:' onclick='removeDeptInterPermission(" + m_interidx + ")'><i class='flaticon-delete'></i></a></td>" + 
                        "</tr>"); 
        }
    }
}
function updateDept() {
	saveDept(C_UPDATE) ;
}
function addDept() {
	saveDept(C_ADD) ;
}
function saveDept(type) {
	if (validateDept()) {
		var data = { "type": type, 
                                "id": $('#txtDeptId').val(), 
                                "desc": $('#txtDeptDesc').val(),
                                "refno": $('#txtDeptRef').val(),
                                "inter_permission": getDeptInterPermission() };
		var url = "request.pzx?c=" + dept_url + "&d=" + new Date().getTime() ;
		callServer(url,"json",data,onDeptResponse,dept_obj) ;
	}
}
function printDept() {
	var url = "report.pzx?c=" + dept_url + "&d=" + new Date().getTime();
	showReport(url) ;
}
function editDept(id,obj) {
	var data = { "type": C_GET,"id": id} ;
	var url = "request.pzx?c=" + dept_url + "&d=" + new Date().getTime() ;		
	clearDept() ;
	showFormDept();
	dept_obj = obj ;
	$($(obj).closest("tr")).addClass("sbg-row-selected");
	callServer(url,"json",data,showDept,obj) ;
}

function deleteDept(id,obj) {
	// if (confirm("Confirm you want to delete department id : " + id + "?")) {
	// 	//$($(obj).closest("tr")).remove() ;
	// 	var data = {"type": C_DELETE,"id": id} ;
	// 	var url = "request.pzx?c=" + dept_url + "&d=" + new Date().getTime() ;
	// 	callServer(url,"json",data,onDeptResponse,obj) ;
	// }

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

	swal("Confirm you want to delete Department 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=" + dept_url + "&d=" + new Date().getTime() ;
			  callServer(url,"json",data,onDeptResponse,obj) ;
		  break;
		}
	});
}
function showDept(obj,resp) {
    if (resp.status == C_OK) {
        $('#txtDeptId').val(resp.data.id) ;
        $('#txtDeptDesc').val(resp.data.desc) ;
        $('#txtDeptRef').val(resp.data.refno) ;
        
        showDeptInterPermission(resp.data.inter_permission);
        
        $('#btnDeptUpdate').prop('disabled','') ;
        $('#txtDeptDesc').focus() ;
    }
    else {
        swal("System Message",resp.mesg) ;
    }
}
function onDeptResponse(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(10000) ;
		clearDept() ;
		filterDept();
		closeFormDept();
	}
	else 
		swal("Error",resp.mesg) ;
}
function validateDept() {
	$('#dept_err_mesg').text('') ;
	if ($('#txtDeptDesc').val()=="")
	{
		$('#dept_err_desc').show() ;
		$('#txtDeptDesc').focus() ;
		swal("department description can not be blank.") ;
		return false ;
	}
	else 
		$('#dept_err_desc').hide() ;
			
	return true ;
}