var currency_obj = null ;
var m_currencyidxrate = 0;

$(document).ready(function() 
{ 
	$('#formCurrency').hide() ;
	$('#btnCurrencyClear').button().bind('click',clearCurrency) ;
	$('#btnCurrencyAdd').button().bind('click',addCurrency) ;
	$('#btnCurrencyUpdate').button().bind('click',updateCurrency) ;
	$('#btnCurrencyPrint').button().bind('click',printCurrency) ;
	// $('#currency-tabs').tabs() ;
	$('#txtCurrencyDesc').focus() ;
	$(window).resize(resizeCurrencyGrid) ;
	resizeCurrencyGrid() ;
	clearCurrency() ;
	filterCurrency();
}) ;

function showFormCurrency(){
	clearCurrency() ;
	$('#formCurrency').show('slow') ;
}

function closeFormCurrency(){
	clearCurrency() ;
	$('#formCurrency').hide('slow') ;
}	

function addCurrencyRate(){
    
    if (isNaN($('#txtCurrencyRateFrom').val()) || $('#txtCurrencyRateFrom').val()==""){
        $('#txtCurrencyRateFrom').val('1.000000');
    } 
	m_currencyidxrate++;
	$('#tblCurrencyRate').append("<tr id='trCurrencyRate" + m_currencyidxrate + "'><td style='width:30px;display:none'>" +m_currencyidxrate+ "</td>" +
		"<td style='display:none'>" + $('#cobCurrencyFrom').val() + "</td>" +
		"<td style='width: 50%;'>" + $("#cobCurrencyFrom option:selected").text() + "</td>" +
		"<td style='width: 40%;text-align:right'>" + $("#txtCurrencyRateFrom").val() + "</td>" +
		"<td style='width:10%;text-align:center;'><a href='javascript:' onclick='removeCurrencyRate(" + m_currencyidxrate + ")'><i class='flaticon-delete'></i></a></td></tr>"); 
}

function removeCurrencyRate(idx) {
	$('#trCurrencyRate'+idx).remove() ;
}

function getCurrencyRate(){
	var lines = "" ;
	var sep = "" ;
	$('#tblCurrencyRate tr').each(function() { 
		from = $(this).find("td").eq(1).html()  ;
		rate = $(this).find("td").eq(3).html() ;
        
        lines = lines + sep + from  + "~" + rate;
        sep = "|" ;
	}); 
	return lines ;
}

function showCurrencyRate(lines) {
	if (lines == undefined || lines == null || lines == "") return ;
	
	var line = lines.split('|') ;
	var fld = "" ;
	m_currencyidxrate = 0 ;
	for (var i = 0 ; i < line.length ; i++) {
		if (line[i] != "") {
			fld = line[i].split('~') ;
			m_currencyidxrate++;
			$('#tblCurrencyRate').append("<tr id='trCurrencyRate" + m_currencyidxrate + "'><td style='width:30px;display:none'>" +m_currencyidxrate+ "</td>" +
                                    "<td style='display:none'>" + fld[0] + "</td>" +
                                    "<td style='width: 50%;'>" + fld[1] + "</td>" +
                                    "<td style='width: 40%;text-align:right'>" + fld[2] + "</td>" +
                                    "<td style='width: 10%;text-align:center;'><a href='javascript:' onclick='removeCurrencyRate(" + m_currencyidxrate + ")'><i class='flaticon-delete'></i></a></td></tr>"); 
			
		}
	}
}

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

function clearCurrency() {
	$('#txtCurrencyId').val("Auto") ;
	$('#txtCurrencyDesc').val("") ;
	$('#txtCurrencyRef').val("") ;
	$('#txtCurrencyRate').val("1.000000") ;
	// $('#currency-tabs').tabs("option", "active", 0) ;
	$('#txtCurrencyDesc').focus() ;
	$('#btnCurrencyUpdate').prop('disabled','disabled') ;
	$('#currency_err_mesg').text('') ;
	$('#currency_err_desc').hide() ;
	$('#currency_err_ref').hide() ;
	$('#tblCurrencyRate').empty() ;
    
	m_currencyidxrate = 0 ;
	if (currency_obj != null && currency_obj != undefined)
	{
		$($(currency_obj).closest("tr")).removeClass("sbg-row-selected") ;
	}
	currency_obj = null;
}

function filterCurrency() {
	var data = { "type": C_LIST} ;
	var url = "request.pzx?c=" + currency_url + "&d=" + new Date().getTime() ;		
	callServer(url,"json",data,showCurrencyFilterList,currency_obj) ;
}

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

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

function updateCurrency() {
	saveCurrency(C_UPDATE) ;
}
function addCurrency() {
	saveCurrency(C_ADD) ;
}
function saveCurrency(type) {
	if (validateCurrency()) {
		var data = { "type": type, "id": $('#txtCurrencyId').val(), 
					"desc": $('#txtCurrencyDesc').val(),
                    "ref": $('#txtCurrencyRef').val(),
					"def_rate": $('#txtCurrencyRate').val(),
					"rate": getCurrencyRate()};
		var url = "request.pzx?c=" + currency_url + "&d=" + new Date().getTime() ;
		callServer(url,"json",data,onCurrencyResponse,currency_obj) ;
	}
}
function printCurrency() {
	var url = "report.pzx?c=" + currency_url + "&d=" + new Date().getTime();
	showReport(url) ;
}
function editCurrency(id,obj) {
	var data = { "type": C_GET,"id": id} ;
	var url = "request.pzx?c=" + currency_url + "&d=" + new Date().getTime();
	clearCurrency() ;
	showFormCurrency();
	currency_obj = obj ;
	$($(obj).closest("tr")).addClass("sbg-row-selected");
	callServer(url,"json",data,showCurrency,obj) ;
}

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

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

	swal("Confirm you want to delete Currency 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=" + currency_url + "&d=" + new Date().getTime() ;
			  callServer(url,"json",data,onCurrencyResponse,obj) ;
		  break;
		}
	  });
}
function showCurrency(obj,resp) {
	if (resp.status == C_OK) {
		$('#txtCurrencyId').val(resp.data.id) ;
		$('#txtCurrencyDesc').val(resp.data.desc) ;
		$('#txtCurrencyRate').val(resp.data.def_rate) ;
		$('#txtCurrencyRef').val(resp.data.ref) ;
        showCurrencyRate(resp.data.rate);
		$('#btnCurrencyUpdate').prop('disabled','') ;
		$('#txtCurrencyDesc').focus() ;
	}
	else {
		swal("System Message",resp.mesg) ;
	}
}
function onCurrencyResponse(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) ;
		clearCurrency() ;
		filterCurrency();
		closeFormCurrency();
	}
	else 
		swal("Error",resp.mesg) ;
}
function validateCurrency() {
	$('#currency_err_mesg').text('') ;
	if ($('#txtCurrencyDesc').val()=="") {
		$('#currency_err_desc').show() ;
		$('#txtCurrencyDesc').focus() ;
		swal("Currency description can not be blank." + "<br>") ;
		return false ;
	} else 
		$('#currency_err_desc').hide() ;
		
	if ($('#txtCurrencyRef').val()=="") {
		$('#currency_err_ref').show() ;
		$('#txtCurrencyRef').focus() ;
		swal("Currency ref can not be blank. This ref is needed for e-submission of employee income." + "<br>") ;
		// $('#currency_err_mesg').html($('#currency_err_mesg').html() + "currency ref can not be blank. This ref is needed for e-submission of employee income."  + "<br>") ;
		return false ;
	} else 
		$('#currency_err_ref').hide() ;		
	
	if ($('#txtCurrencyRate').val()=="") {
		$('#currency_err_rate').show() ;
		$('#txtCurrencyRate').focus() ;
		swal("Currency rate can not be blank." + "<br>") ;
		// $('#currency_err_mesg').html($('#currency_err_mesg').html() + "currency rate can not be blank.") ;
		return false ;
	} else {
		$('#currency_err_rate').hide() ;
		if(isNumeric($('#txtCurrencyRate').val()) == false) {
			swal("Currency rate must be a number." + "<br>") ;
			// $('#currency_err_mesg').html($('#currency_err_mesg').html() + "currency rate must be a number.") ;
			return false ;
		}
	}
	
	return true ;
}

function isNumeric( obj ) {
    return !jQuery.isArray( obj ) && (obj - parseFloat( obj ) + 1) >= 0;
}