var taxestype_obj = null ;
var m_percentageidx = 0 ;

$(document).ready(function() 
{ 
	$('#formTaxesType').hide() ;
	$('#btnTaxesTypeClear').button().bind('click',clearTaxesType) ;
	$('#btnTaxesTypeUpdate').button().bind('click',updateTaxesType) ;
	$('#btnTaxesTypeAdd').button().bind('click',addTaxesType) ;
	$('#btnTaxesTypePrint').button().bind('click',printTaxesType) ;
	// $('#taxes-type-tabs').tabs() ;
	$('#txtTaxesTypeDesc').focus() ;
        
	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>'
		    }
		}

	$('#txtTaxesTypeStartDate').datepicker(dteopt).datepicker("setDate", new Date()) ;

	// $('#txtTaxesTypeStartDate').datepicker(dteopt) ;
        
	$(window).resize(resizeTaxesTypeGrid) ;
	resizeTaxesTypeGrid() ;
	clearTaxesType();
	filterTaxesType();
}) ;

function showFormTaxesType(){
	$('#formTaxesType').show('slow') ;
}

function closeFormTaxesType(){
	clearTaxesType() ;
	$('#formTaxesType').hide('slow') ;
}

function addPercentages(){
        m_percentageidx++;
        $('#tblPercentages').append("<tr id='trpercentage" + m_percentageidx + "'>" + 
		"<td style='width:150px;display:none'>" + m_percentageidx + "</td>" +
		"<td style='width:150px;'>" + $('#txtTaxesTypeStartDate').val() + "</td>" +
		"<td style='width:150px;'>" + $('#txtTaxesTypePercentage').val() + "</td>" +
		"<td style='width:50px;text-align:center;'><a href='javascript:' onclick='removePercentages(" + m_percentageidx + ")'><i class='flaticon-delete'></i></a></td></tr>"); 
	
}

function removePercentages(idx){
	$('#trpercentage'+idx).remove() ;
}

function getPercentagesRow(){
	var lines = "";
	var sep = "" ;
	var start_date = "";
	var percentage = "";
	var id = "" ;
	
	$('#tblPercentages tr').each(function() { 
		id = $(this).find("td").eq(0).html() ;
		start_date = $(this).find("td").eq(1).html() ;
		percentage = $(this).find("td").eq(2).html() ;
		if(isNaN(percentage) || percentage.length == 0)
			percentage = '0';
		
		lines = lines + sep + start_date + '~' + percentage;
		sep = "|" ;
	}); 
	return lines;
}

function showPercentageRows(lines){
    
	$('#tblPercentages').empty() ;
	if (lines == undefined || lines == null || lines == "") return ;
	var line = lines.split('|') ;
	var fld = "" ;
	m_percentageidx = 0 ;
	for (var i = 0 ; i < line.length ; i++) {
		if (line[i] != "") {
			items 	= line[i].split('~');
			m_percentageidx++;
                        $('#tblPercentages').append("<tr id='trpercentage" + m_percentageidx + "'>" + 
                                "<td style='width:150px;display:none'>" + m_percentageidx + "</td>" +
                                "<td style='width:150px;'>" + items[1] + "</td>" +
                                "<td style='width:150px;'>" + items[0] + "</td>" +
                                "<td style='width:50px;text-align:center;'><a href='javascript:' onclick='removePercentages(" + m_percentageidx + ")'><i class='flaticon-delete'></i></a></td></tr>"); 

		}
	}
}
function resizeTaxesTypeGrid() {
	var h = $("#sbg-center-panel").outerHeight() - $("#sbg-taxestype-entry").outerHeight() - 55;
	$("div#sbg-taxestype-data").css("height", h +'px') ;		
}
function clearTaxesType() {
	$('#txtTaxesTypeId').val("Auto") ;
	$('#txtTaxesTypeDesc').val("") ;
	$('#txtTaxesTypeCode').val("") ;
	$('#txtTaxesTypeGLCode').val("") ;
	$('#txtTaxesTypeDefaultPercentage').val("0.00") ;
	// $('#taxestype-tabs').tabs("option", "active", 0) ;
	$('#txtTaxesTypeDesc').focus() ;
	$('#btnTaxesTypeUpdate').prop('disabled','disabled') ;
	$('#taxestype_err_mesg').text('') ;
        $('#txtTaxesTypeStartDate').val('');
	$('#taxestype_err_desc').hide() ;
	if (taxestype_obj != null && taxestype_obj != undefined)
	{
		$($(taxestype_obj).closest("tr")).removeClass("sbg-row-selected") ;
	}
	taxestype_obj = null;
}

function filterTaxesType() {
	var data = { "type": C_LIST} ;
	var url = "request.pzx?c=" + taxestype_url + "&d=" + new Date().getTime() ;		
	callServer(url,"json",data,showTaxesTypeFilterList,taxestype_obj) ;
}

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

function init_dt() {
	var datatable = $('.sbg-taxes-type-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: "default",
				title: "Default",
				width: 70,
			}, {
				field: 'actions',
				title: 'Actions',
				sortable: true,
				width: 420,
				overflow: 'visible',
		}],
	});
}

function updateTaxesType() {
	saveTaxesType(C_UPDATE) ;
}
function addTaxesType() {
	saveTaxesType(C_ADD) ;
}
function saveTaxesType(type) {
	if (!validateTaxesType()) {
		return false;
	}
	var data = { "type": type, 
                        "id": $('#txtTaxesTypeId').val(), 
                        "code": $('#txtTaxesTypeCode').val(),
                        "gl_code": $('#txtTaxesTypeGLCode').val(),
                        "desc": $('#txtTaxesTypeDesc').val(),
                        "default_percentage": $('#txtTaxesTypeDefaultPercentage').val(), 
                        "percentages": getPercentagesRow()};
	var url = "request.pzx?c=" + taxestype_url + "&d=" + new Date().getTime() ;
	callServer(url,"json",data,onTaxesTypeResponse,taxestype_obj) ;
}

function editTaxesType(id,obj) {
	var data = { "type": C_GET,"id": id} ;
	var url = "request.pzx?c=" + taxestype_url + "&d=" + new Date().getTime();		
	clearTaxesType();
	showFormTaxesType();
	taxestype_obj = obj ;
	$($(obj).closest("tr")).addClass("sbg-row-selected");
	callServer(url,"json",data,showTaxesType,obj) ;
}

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

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

	swal("Confirm you want to delete Taxes Type 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=" + taxestype_url + "&d=" + new Date().getTime() ;
			  callServer(url,"json",data,onTaxesTypeResponse,obj) ;
		  break;
		}
	  });
}
function showTaxesType(obj,resp) {
	if (resp.status != C_OK) {
		swal("System Message",resp.mesg) ;
		return false;
	}
	
	$('#txtTaxesTypeId').val(resp.data.id) ;
	$('#txtTaxesTypeCode').val(resp.data.code) ;
	$('#txtTaxesTypeGLCode').val(resp.data.gl_code) ;
	$('#txtTaxesTypeDesc').val(resp.data.desc) ;
	$('#txtTaxesTypeDefaultPercentage').val(resp.data.default_percentage) ;
        
    showPercentageRows(resp.data.percentages);
	$('#btnTaxesTypeUpdate').prop('disabled','') ;
	$('#txtTaxesTypeDesc').focus() ;
}
function printTaxesType() {
	var url = "report.pzx?c=" + taxestype_url + "&d=" + new Date().getTime();
	showReport(url) ;
}
function onTaxesTypeResponse(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) ;
	clearTaxesType() ;
	filterTaxesType();
	closeFormTaxesType();
}
function validateTaxesType() {
	$('#taxestype_err_mesg').text('') ;
	if ($('#txtTaxesTypeDesc').val()=="")
	{
		$('#taxestype_err_desc').show() ;
		$('#txtTaxesTypeDesc').focus() ;
		swal("Tax type description can not be blank.") ;
		return false ;
	}
	else 
		$('#taxestype_err_desc').hide() ;
        
	if ($('#txtTaxesTypeCode').val()=="")
	{
		$('#taxestype_err_desc').show() ;
		$('#txtTaxesTypeCode').focus() ;
		swal("Tax type code can not be blank.") ;
		return false ;
	}
	else 
		$('#taxestype_err_desc').hide() ;
        
	if ($('#txtTaxesTypeGLCode').val()=="")
	{
		$('#taxestype_err_desc').show() ;
		$('#txtTaxesTypeGLCode').focus() ;
		swal("Tax type GL code can not be blank.") ;
		return false ;
	}
	else 
		$('#taxestype_err_desc').hide() ;
			
	return true ;
}