var checklist_obj 	= null ;
var m_interidx 		= 0;
$(document).ready(function() 
{ 
	$('#formCheckList').hide() ;
	$('#btnChecklistClear').button().bind('click',clearChecklist) ;
	$('#btnChecklistUpdate').button().bind('click',updateChecklist) ;
	$('#btnChecklistAdd').button().bind('click',addChecklist) ;
	$('#btnChecklistPrint').button().bind('click',printChecklist) ;
	// $('#checklist-tabs').tabs() ;
	$('#txtChecklistName').focus() ;
	$(window).resize(resizeChecklistGrid) ;
	resizeChecklistGrid() ;
	clearChecklist();
	filterChecklist();
}) ;

function showFormCheckList(){
	clearChecklist();
	$('#formCheckList').show('slow') ;
}

function closeFormCheckList(){
	clearChecklist() ;
	$('#formCheckList').hide('slow') ;
}	

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

function clearChecklist() {
	$('#txtChecklistId').val("Auto") ;
	$('#txtChecklistName').val("") ;
	$('#txtChecklistCode').val("") ;
	$('#tblChecklistDetailBody').html("") ;
	$('#txtChecklistRef').val("") ;
	// $('#checklist-tabs').tabs("option", "active", 0) ;
	$('#txtChecklistName').focus() ;
	$('#btnChecklistUpdate').prop('disabled','disabled') ;
	$('#checklist_err_mesg').text('') ;
	$('#checklist_err_name').hide() ;
	$('#checklist_err_code').hide() ;
	if (checklist_obj != null && checklist_obj != undefined)
	{
		$($(checklist_obj).closest("tr")).removeClass("sbg-row-selected") ;
	}
	checklist_obj = null;
}

function filterChecklist() {
	var data = { "type": C_LIST} ;
	var url = "request.pzx?c=" + checklist_url + "&d=" + new Date().getTime() ;		
	callServer(url,"json",data,showCheckListFilterList,checklist_obj) ;
}

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

function init_dt() {
	var datatable = $('.sbg-checklist-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,
		autoWidth: false,
		// 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: "code",
				title: "Code",
				width:70,
			}, {
				field: "name",
				title: "Name",
				width:200,
			}, {
				field: "ref",
				title: "Reference",
				width: 100,
			}, {
				field: 'actions',
				title: 'Actions',
				sortable: true,
				width: 420,
				overflow: 'visible',
		}],
	});
}

function updateChecklist() {
	saveChecklist(C_UPDATE) ;
}
function addChecklist() {
	saveChecklist(C_ADD) ;
}
function saveChecklist(type) {
	if (!validateChecklist()) {
		return false;
	}
	var data = { "type": type, 
                    "id": $('#txtChecklistId').val(), 
                    "code": $('#txtChecklistCode').val(),
                    "name": $('#txtChecklistName').val(), 
					"ref": $('#txtChecklistRef').val(),
					"checklist": getChecklistDetail(),};
	var url = "request.pzx?c=" + checklist_url + "&d=" + new Date().getTime() ;
	
	callServer(url,"json",data,onChecklistResponse,checklist_obj) ;
}

function editChecklist(id,obj) {
	var data = { "type": C_GET,"id": id} ;
	var url = "request.pzx?c=" + checklist_url + "&d=" + new Date().getTime();		
	clearChecklist();
	showFormCheckList();
	checklist_obj = obj ;
	$($(obj).closest("tr")).addClass("sbg-row-selected");
	callServer(url,"json",data,showChecklist,obj) ;
}

function deleteChecklist(id,obj) {
	// if (confirm("Confirm you want to delete Checklist id : " + id + "?") == false) {
	// 	return false;
	// }
	
	// var data = {"type": C_DELETE,"id": id} ;
	// var url = "request.pzx?c=" + checklist_url + "&d=" + new Date().getTime() ;
	// callServer(url,"json",data,onChecklistResponse,obj) ;

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

	swal("Confirm you want to delete Checklist 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=" + checklist_url + "&d=" + new Date().getTime() ;
			  callServer(url,"json",data,onChecklistResponse,obj) ;
		  break;
		}
	  });
}
function showChecklist(obj,resp) {
	if (resp.status != C_OK) {
		swal("System Message",resp.mesg) ;
		return false;
	}
	
	$('#txtChecklistId').val(resp.data.id) ;
	$('#txtChecklistName').val(resp.data.name) ;
	$('#txtChecklistCode').val(resp.data.code) ;
	$('#txtChecklistRef').val(resp.data.ref) ;
	
	setChecklistDetail(resp.data.checklist);
	$('#btnChecklistUpdate').prop('disabled','') ;
	$('#txtChecklistName').focus() ;
}
function printChecklist() {
	var url = "report.pzx?c=" + checklist_url + "&d=" + new Date().getTime();
	showReport(url) ;
}
function onChecklistResponse(obj,resp) {
	if (resp.status != C_OK) {
		swal("Error",resp.mesg) ;
		return;
	}
	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) ;
	clearChecklist() ;
	filterChecklist();
	closeFormCheckList();
}
function validateChecklist() {
	$('#checklist_err_mesg').text('') ;
	if ($('#txtChecklistName').val()=="")
	{
		$('#checklist_err_name').show() ;
		$('#txtChecklistName').focus() ;
		swal("Checklist nameription can not be blank.") ;
		return false ;
	}
	else 
		$('#checklist_err_name').hide() ;
    
	if ($('#txtChecklistCode').val()=="")
	{
		$('#checklist_err_code').show() ;
		$('#txtChecklistCode').focus() ;
		swal("Checklist code can not be blank.") ;
		return false ;
	}
	else 
		$('#checklist_err_code').hide() ;
			
	return true ;
}

function addChecklistDetail(){
    
    m_interidx++;
    $('#tblChecklistDetailBody').append("<tr id='trChecklistDetail" + m_interidx + "'><td style='width:30px;display:none'>" +m_interidx+ "</td>" +
            
			"<td >" + "<input style=width='10%' class='form-control order' id='orderId"+m_interidx+"' value='"+m_interidx+"'>" + "</td>" +
			"<td >" + "<input style=width='80%' class='form-control desc' id='desc"+m_interidx+"'>"  + "</td>" +
            "<td style='width:10%;text-align:center;padding-top: 25px;padding-bottom: 0px;'><a href='javascript:' onclick='removeChecklistDetail(" + m_interidx + ")'><i class='flaticon-delete'></i></a></td></tr>"); 
}

function removeChecklistDetail(idx) {
    $('#trChecklistDetail'+idx).remove() ;
}

function getChecklistDetail() {
	var lines = "" ;
    var sep = "" ;
    $('#tblChecklistDetailBody tr').each(function() { 
		order 	= $('.order',this).val();
		desc 	= $('.desc' ,this).val() ;
        lines 	= lines + sep + order +"~"+desc ;
        sep 	= "|" ;
    }); 
    return lines ;
}

function setChecklistDetail(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++;
            $('#tblChecklistDetailBody').append("<tr id='trChecklistDetail" + m_interidx + "'>"+
			"<td >" + "<input style='' class='form-control order' id='orderId"+m_interidx+"' value='"+fld[0] +"'>" + "</td>" +
			"<td >" + "<input style='' class='form-control desc' id='desc"+m_interidx +"' value='"+fld[1] +"'>"  + "</td>" +
            "<td style='text-align:center;padding-top: 25px;padding-bottom: 0px;'><a href='javascript:' onclick='removeChecklistDetail(" + m_interidx + ")'><i class='flaticon-delete'></i></a></td></tr>"); 
        }
    }
}