var model_obj = null ;

$(document).ready(function() 
{ 
	$('#formModel').hide() ;
	$('#btnModelClear').button().bind('click',clearModel) ;
	$('#btnModelUpdate').button().bind('click',updateModel) ;
	$('#btnModelAdd').button().bind('click',addModel) ;
	$('#btnModelPrint').button().bind('click',printModel) ;
	// $('#model-tabs').tabs() ;
	$('#txtModelDesc').focus() ;
	$(window).resize(resizeModelGrid) ;
	resizeModelGrid() ;
	clearModel();
	filterModel();
}) ;

function showFormModel(){
	clearModel();
	$('#formModel').show('slow') ;
}

function closeFormModel(){
	clearModel() ;
	$('#formModel').hide('slow') ;
}	

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

function clearModel() {
	$('#txtModelId').val("Auto") ;
	$('#txtModelDesc').val("") ;
	$('#txtModelCode').val("") ;
	$('#txtModelRef').val("") ;
	$('#txtModelBrand').val(0) ;
	// $('#model-tabs').tabs("option", "active", 0) ;
	$('#txtModelDesc').focus() ;
	$('#btnModelUpdate').prop('disabled','disabled') ;
	$('#model_err_mesg').text('') ;
	$('#model_err_desc').hide() ;
	$('#model_err_code').hide() ;
	if (model_obj != null && model_obj != undefined)
	{
		$($(model_obj).closest("tr")).removeClass("sbg-row-selected") ;
	}
	model_obj = null;
}

function filterModel() {
	var data = { "type": C_LIST} ;
	var url = "request.pzx?c=" + model_url + "&d=" + new Date().getTime() ;		
	callServer(url,"json",data,showModelFilterList,model_obj) ;
}

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

function init_dt() {
	var datatable = $('.sbg-model-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: "code",
				title: "Code",
				width:70,
			}, {
				field: "desc",
				title: "Description",
				width:200,
			}, {
				field: "brand",
				title: "Brand",
				width: 150,
			}, {
				field: 'actions',
				title: 'Actions',
				sortable: true,
				width: 470,
				overflow: 'visible',
		}],
	});
}

function updateModel() {
	saveModel(C_UPDATE) ;
}
function addModel() {
	saveModel(C_ADD) ;
}
function saveModel(type) {
	if (!validateModel()) {
		return false;
	}
	var data = { "type": type, 
                    "id": $('#txtModelId').val(), 
                    "code": $('#txtModelCode').val(),
                    "desc": $('#txtModelDesc').val(), 
                    "ref": $('#txtModelRef').val(),
                    "brand": $('#txtModelBrand').val()};
	var url = "request.pzx?c=" + model_url + "&d=" + new Date().getTime() ;
	callServer(url,"json",data,onModelResponse,model_obj) ;
}

function editModel(id,obj) {
	var data = { "type": C_GET,"id": id} ;
	var url = "request.pzx?c=" + model_url + "&d=" + new Date().getTime();		
	clearModel();
	showFormModel();
	model_obj = obj ;
	$($(obj).closest("tr")).addClass("sbg-row-selected");
	callServer(url,"json",data,showModel,obj) ;
}

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

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

	swal("Confirm you want to delete Model 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=" + model_url + "&d=" + new Date().getTime() ;
			  callServer(url,"json",data,onModelResponse,obj) ;
		  break;
		}
	  });
}
function showModel(obj,resp) {
	if (resp.status != C_OK) {
		swal("System Message",resp.mesg) ;
		return false;
	}
	
	$('#txtModelId').val(resp.data.id) ;
	$('#txtModelCode').val(resp.data.code) ;
	$('#txtModelDesc').val(resp.data.desc) ;
	$('#txtModelRef').val(resp.data.ref) ;
	$('#txtModelBrand').val(resp.data.brand) ;
	$('#btnModelUpdate').prop('disabled','') ;
	$('#txtModelDesc').focus() ;
}
function printModel() {
	var url = "report.pzx?c=" + model_url + "&d=" + new Date().getTime();
	showReport(url) ;
}
function onModelResponse(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) ;
	clearModel() ;
	filterModel();
	closeFormModel();
}
function validateModel() {
	$('#model_err_mesg').text('') ;
	if ($('#txtModelDesc').val()=="")
	{
		$('#model_err_desc').show() ;
		$('#txtModelDesc').focus() ;
		swal("Model description can not be blank.") ;
		return false ;
	}
	else 
		$('#model_err_desc').hide() ;
    
	if ($('#txtModelCode').val()=="")
	{
		$('#model_err_code').show() ;
		$('#txtModelCode').focus() ;
		swal("Model code can not be blank.") ;
		return false ;
	}
	else 
		$('#model_err_code').hide() ;
			
	return true ;
}