var emp_obj = null ;
var item_sort = new Array();
var m_emp_claim_group_idx = 0;
$(document).ready(function() 
{ 
	$('input').css('marginTop', 0); 
	$('input').css('marginBottom',0);
	$('select').css('marginTop',0) ;
	$('select').css('marginBottom',0) ;	
	
	var dteopt = {
		dateFormat: "dd/mm/yy",
		appendText: "  dd/mm/yyyy",
		showOn: "button",
		buttonImage: "image/calendar.gif",
		buttonImageOnly: true
	};
	var dteopt2 = {
		dateFormat: "dd/mm/yy",
		showOn: "button",
		buttonImage: "image/calendar.gif",
		buttonImageOnly: true
	};
	var i;
	for(i = 0; i < document.getElementById('sbg-emp-table').rows[0].cells.length; i++){
		item_sort[i] = 1;
	}
	$('#txtEmpDob').datepicker(dteopt) ;
	$('#txtEmpJoin').datepicker(dteopt) ;
	$('#txtEmpResign').datepicker(dteopt);
	$('#txtEmpClaimGroupStartDate').datepicker(dteopt2);
	$('#txtEmpClaimGroupEndDate').datepicker(dteopt2);
	$('#txtEmpPostal').keypress(function() { numericInput(0,'',0,0) ; }) ;
	$('#btnEmpClear').button().bind('click',clearEmp) ;
	$('#btnEmpAdd').button().bind('click',addEmp) ;
	$('#btnEmpUpdate').button().bind('click',updateEmp) ;
	$('#btnEmpPrint').button().bind('click',printEmp) ;
	$('#btnEmpNew').button().bind('click',showInput) ;
	$('#btnEmpList').button().bind('click',filterEmp) ;
	$('#txtEmpDob').keypress(function() { dateInput('/') ; }) ;
	$('#txtEmpJoin').keypress(function() { dateInput('/') ; }) ;
	$('#txtEmpResign').keypress(function() { dateInput('/') ; }) ;
	$('#emp-tabs').tabs() ;
	$('#txtEmpName').focus() ;
	$(window).resize(resizeEmpGrid) ;
	$('#sbg-emp-entry').hide();
	resizeEmpGrid(false) ;
	clearEmp();
}) ;

function addClaimGroupHistory(){
	if($("#cobEmpClaimGroup").val() == ""){
		showDialog("Error","Please select the claim group!") ;
		return;
	}
	if($("#cobEmpExpenseItem").val() == ""){
		showDialog("Error","Please select the expense item!") ;
		return;
	}
	if($("#txtEmpClaimGroupStartDate").val() == ""){
		showDialog("Error","Please input the start date!") ;
		return;
	}
	if($("#txtEmpClaimGroupEndDate").val() == ""){
		showDialog("Error","Please input the end date!") ;
		return;
	}
	if($("#txtEmpClaimGroupValue").val() == ""){
		showDialog("Error","Please input the override value!") ;
		return;
	}
	m_emp_claim_group_idx++;
	
	var strHtml = "";
	strHtml += "<tr id='trempclaimgroup" + m_emp_claim_group_idx + "'><td style='display:none'>" + m_emp_claim_group_idx + "</td>";
	strHtml += "<td style='display:none'>" + $("#cobEmpClaimGroup").val() + "</td>";
	strHtml += "<td style='display:none'>" + $("#cobEmpClaimGroupOverrideType").val() + "</td>";
	strHtml += "<td style='display:none'>" + $("#cobEmpExpenseItem").val() + "</td>";
	strHtml += "<td style='width:140px;'>" + $('#cobEmpClaimGroup :selected').text() + "</td>";
	strHtml += "<td style='width:100px;'>" + $('#cobEmpExpenseItem :selected').text() + "</td>";
	strHtml += "<td style='width:90px;'>" + $('#txtEmpClaimGroupStartDate').val() + "</td>";
	strHtml += "<td style='width:90px;'>" + $('#txtEmpClaimGroupEndDate').val() + "</td>";
	strHtml += "<td style='width:60px;'>" + $('#cobEmpClaimGroupOverrideType :selected' ).text() + "</td>";
	strHtml += "<td style='width:85px;'>" + $('#txtEmpClaimGroupValueItem').val() + "</td>";
	strHtml += "<td style='width:85px;'>" + $('#txtEmpClaimGroupValueGroup').val() + "</td>";
	strHtml += "<td style='width:50px;text-align:center;'><a href='javascript:' onclick='removeEmpClaimGroup(" + m_emp_claim_group_idx + ")'><img src='image/remove_16.png' title='Remove'></img></a></td>";
	strHtml += "</tr>";
	$("#tblEmpClaimGroupHistory").append(strHtml);
}

function removeEmpClaimGroup(idx){
	$("#trempclaimgroup" + idx).remove();
}

function getEmpClaimGroupHistory(){
	
	var lines = "";
	var sep = "" ;
	var claim_group_id = "";
	var id = "" ;
	
	$('#tblEmpClaimGroupHistory tr').each(function() { 
		lines = lines + sep + $(this).find("td").eq(1).html() + 
                                    '~' + $(this).find("td").eq(2).html() + 
                                    '~' + $(this).find("td").eq(6).html() + 
                                    '~' + $(this).find("td").eq(7).html() + 
                                    '~' + $(this).find("td").eq(9).html() + 
                                    '~' + $(this).find("td").eq(10).html() + 
                                    '~' + $(this).find("td").eq(3).html();
		sep = "|" ;
	}); 
	return lines;
}

function showEmpClaimGroupHistory(lines){
	
	$('#tblEmpClaimGroupHistory').empty() ;
	if (lines == undefined || lines == null || lines == "") return ;
	var line = lines.split('|') ;
	m_emp_claim_group_idx = 0;
	for (var i = 0 ; i < line.length ; i++) {
		if (line[i] != "") {
			items 	= line[i].split('~');
			m_emp_claim_group_idx++;
			
			var strHtml = "";
			strHtml += "<tr id='trempclaimgroup" + m_emp_claim_group_idx + "'><td style='display:none'>" + m_emp_claim_group_idx + "</td>";
			strHtml += "<td style='display:none'>" + items[0] + "</td>";
			strHtml += "<td style='display:none'>" + items[4] + "</td>";
			strHtml += "<td style='display:none'>" + items[8] + "</td>";
			strHtml += "<td style='width:140px;'>" + items[1] + "</td>";
			strHtml += "<td style='width:100px;'>" + items[9] + "</td>";
			strHtml += "<td style='width:90px;'>" + items[2] + "</td>";
			strHtml += "<td style='width:90px;'>" + items[3] + "</td>";
			strHtml += "<td style='width:60px;'>" + items[5] + "</td>";
			strHtml += "<td style='width:85px;'>" + items[6] + "</td>";
			strHtml += "<td style='width:85px;'>" + items[7] + "</td>";
			strHtml += "<td style='width:50px;text-align:center;'><a href='javascript:' onclick='removeEmpClaimGroup(" + m_emp_claim_group_idx + ")'><img src='image/remove_16.png' title='Remove'></img></a></td>";
			strHtml += "</tr>";
			$("#tblEmpClaimGroupHistory").append(strHtml);
		}
	}
}

function sortEmpTable(elmt){
	var col = 0;
	var theader = document.getElementById('sbg-emp-header').rows[0];
	for(i=0;i<theader.cells.length;i++){
		var strHTML = theader.cells[i].innerHTML;
		if(elmt.innerHTML == strHTML){
			col = i;
		}
	}
	
	var asc = item_sort[col];
	var tbody = document.getElementById('sbg-emp-table');
	
	for(i = 0; i < tbody.rows[0].cells.length; i++){
		item_sort[i] = (col == i ? item_sort[i] * -1 : 1);
	}
	
    var rows = tbody.rows, rlen = rows.length, arr = new Array(), i, j, cells, clen;
	
    for(i = 1; i < rlen; i++){
		cells = rows[i].cells;
		clen = cells.length;
		arr[i-1] = new Array();
        for(j = 0; j < clen; j++){
			arr[i-1][j] = cells[j].innerHTML;
			cells[j].innerHTML = '';
        }
    }
    arr.sort(function(a, b){
		if(a[col] == b[col])
			return 0;
		if(!isNaN(a[col]) && !isNaN(b[col])){
			return ((parseInt(a[col]) > parseInt(b[col])) ? asc : -1*asc);
		}
        return ((a[col] > b[col]) ? asc : -1*asc);
    });
	
    for(i = 1; i < rlen; i++){
		cells = rows[i].cells;
		clen = cells.length;
        for(j = 0; j < clen; j++){
			cells[j].innerHTML = arr[i-1][j];
        }
    }

}
function filterEmp() {
	var data = { "type": C_LIST,"company": $('#cobCompany').val(),"department": $('#cobDepartment').val()} ;
	var url = "request.pzx?c=" + emp_url + "&d=" + new Date().getTime() ;		
	callServer(url,"html",data,showEmpFilterList,emp_obj) ;
}

function showEmpFilterList(obj,resp) {
	var fr = '<tr>' +
				'<td style="width:50px;height:1px"></td>' +
				'<td style="width:100px"></td>' +
				'<td style="width:200px"></td>' +
				'<td style="width:200px"></td>' +
				'<td style="width:200px"></td>' +
				'<td style="width:25px"></td>' + 
				'<td style="width:25px"></td>' +
			'</tr>';
	$('#sbg-emp-table').html(fr + resp) ;
}

function resizeEmpGrid(vis) {
	var h = $("#sbg-center-panel").outerHeight() - $("#emp-filter").outerHeight() - 55;
	if (vis)
		h = h - $('#sbg-emp-entry').outerHeight();
	$("div#sbg-emp-data").css("height", h +'px') ;
}
function clearEmp() {
	$('#txtEmpId').val("Auto") ;
	$('#txtCode').val("");
	$('#txtEmpName').val("") ;
	$('#txtEmpNric').val("") ;
	$('#cobEmpIdType').val("1") ;
	$('#txtEmpEmail').val("") ;
	$('#txtEmpDob').val("");
	$('#txtEmpJoin').val("") ;
	$('#txtEmpResign').val("") ;
	$('#txtAddrLine1').val("");
	$('#txtAddrLine2').val("");
	$('#txtAddrLine3').val("");
	$('#txtAddrLine4').val("");
	$('#txtEmpPostal').val("") ;
	$('#txtEmpTel').val("");
	$('#txtEmpMobile').val("");
	$('#cobEmpDept').val("") ;
	$('#cobEmpType').val("") ;
	$('#cobEmpGender').val("M") ;
	$('#cobEmpMarital').val("0");
	$('#cobEmpNat').val("") ;
	$('#cobEmpJob').val("") ;
	$('#cobEmpCoy').val("");
	$('#cobEmpRace').val("");
	$('#cobEmpPermit').val("");
	$('#txtEmpRmks').val("");
	$('#cobEmpClaimGroup').val("");
	$('#cobEmpExpenseItem').val("");
	$('#txtEmpClaimGroupDate').val("");
        $('#txtEmpClaimGroupValueItem').val("");
        $('#txtEmpClaimGroupValueGroup').val("");
        $('#txtEmpClaimGroupStartDate').val("");
        $('#txtEmpClaimGroupEndDate').val("");
        $("#cobEmpClaimGroupOverrideType").val(0);
	$('#emp-tabs').tabs("option", "active", 0) ;
	$('#txtEmpName').focus() ;
	$('#btnEmpUpdate').prop('disabled','disabled') ;
	
	$('#emp_err_dept').hide() ;
	$('#emp_err_nric').hide() ;
	$('#emp_err_name').hide() ;
	$('#emp_err_code').hide() ;
	$('#emp_err_coy').hide() ;
	$('#emp_err_race').hide() ;
	$('#emp_err_dob').hide();
	$('#emp_err_nat').hide() ;
	$('#emp_err_job').hide() ;
	$('#emp_err_type').hide() ;
	$('#emp_err_join').hide() ;
	$('#emp_err_resign').hide() ;
	m_emp_claim_group_idx = 0;
	
	$('#emp_err_mesg').text("") ;
	if (emp_obj != null && emp_obj != undefined)
	{
		$($(emp_obj).closest("tr")).removeClass("sbg-row-selected") ;
	}
	emp_obj = null;
}
function showInput(){
	
	$('#btnEmpNew').hide() ;
	$('#sbg-emp-entry').show('slow', function() {
		resizeEmpGrid(true);
	});
}
function hideInput(){
	
	$('#btnEmpNew').show();
	$('#sbg-emp-entry').hide('slow', function() {
		resizeEmpGrid(false) ;	
	});
}

function updateEmp() {
	saveEmp(C_UPDATE) ;
}
function addEmp() {
	saveEmp(C_ADD) ;
}
function saveEmp(type) {
	if (validateEmp()) {
		var block = "0" ;
		var data = { "type": type, "id": $('#txtEmpId').val(), "name": $('#txtEmpName').val(), "code": $('#txtCode').val(),
			"coy": $('#cobEmpCoy').val(), "dept": $('#cobEmpDept').val(), "emptype": $('#cobEmpType').val(),
			"job": $('#cobEmpJob').val(), "join": $('#txtEmpJoin').val(), "resign": $('#txtEmpResign').val(),
			"nric": $('#txtEmpNric').val(), "gender": $('#cobEmpGender').val(), "marital": $('#cobEmpMarital').val(),
			"race": $('#cobEmpRace').val(), "nat": $('#cobEmpNat').val(), "dob": $('#txtEmpDob').val(),
			"addr_line_1": $('#txtAddrLine1').val(), 
			"addr_line_2": $('#txtAddrLine2').val(), 
			"addr_line_3": $('#txtAddrLine3').val(),
			"addr_line_4": $('#txtAddrLine4').val(),
			"postal": $('#txtEmpPostal').val(), "tel": $('#txtEmpTel').val(), 
			"mobile": $('#txtEmpMobile').val(),	"email": $('#txtEmpEmail').val(), "rmks": $('#txtEmpRmks').val(), 
			"permit": $('#cobEmpPermit').val(),	"idtype": $('#cobEmpIdType').val(), "refno": "", "block": block,
			"emp_claim_group_history": getEmpClaimGroupHistory() };
		var url = "request.pzx?c=" + emp_url + "&d=" + new Date().getTime() ;
		callServer(url,"json",data,onEmpResponse,emp_obj) ;
	}
}
function printEmp() {
	var url = "report.pzx?c=" + emp_url + "&d=" + new Date().getTime();
	showReport(url) ;
}
function editEmp(id,obj) {
	var data = { "type": C_GET,"id": id} ;
	var url = "request.pzx?c=" + emp_url + "&d=" + new Date().getTime();		
	clearEmp() ;
	emp_obj = obj ;
	$($(obj).closest("tr")).addClass("sbg-row-selected");
	callServer(url,"json",data,showEmp,obj) ;
}

function deleteEmp(id,obj) {
	if (confirm("Confirm you want to delete employee id : " + id + "?")) {
		var data = {"type": C_DELETE,"id": id} ;
		var url = "request.pzx?c=" + emp_url + "&d=" + new Date().getTime() ;
		callServer(url,"json",data,onEmpResponse,obj) ;
	}
}
function showEmp(obj,resp) {
	if (resp.status == C_OK) {
		showInput();
		$('#txtEmpId').val(resp.data.id) ;
		$('#txtCode').val(resp.data.code);
		$('#txtEmpName').val(resp.data.name) ;
		$('#txtEmpNric').val(resp.data.nric) ;
		$('#cobEmpIdType').val(resp.data.idtype) ;
		$('#txtEmpEmail').val(resp.data.email) ;
		$('#txtEmpDob').val(resp.data.dob) ;
		$('#txtEmpJoin').val(resp.data.join) ;
		$('#txtEmpResign').val(resp.data.resign);
		$('#cobEmpDept').val(resp.data.dept) ;
		$('#cobEmpType').val(resp.data.emptype) ;
		$('#cobEmpCoy').val(resp.data.coy) ;
		$('#cobEmpRace').val(resp.data.race) ;
		$('#cobEmpNat').val(resp.data.nat) ;
		$('#cobEmpGender').val(resp.data.gender);
		$('#cobEmpMarital').val(resp.data.marital);
		$('#cobEmpJob').val(resp.data.job);
		$('#txtAddrLine1').val(resp.data.addr_line_1);
		$('#txtAddrLine2').val(resp.data.addr_line_2);
		$('#txtAddrLine3').val(resp.data.addr_line_3);
		$('#txtAddrLine4').val(resp.data.addr_line_4) ;
		$('#txtEmpPostal').val(resp.data.postal) ;
		$('#txtEmpTel').val(resp.data.tel);
		$('#txtEmpMobile').val(resp.data.mobile);
		$('#txtEmpRmks').val(resp.data.rmks);
		$('#cobEmpPermit').val(resp.data.permit) ;
		$('#btnEmpUpdate').prop('disabled','') ;
		$('#txtEmpName').focus() ;
		showEmpClaimGroupHistory(resp.data.emp_claim_group_history);
	}
	else {
		showDialog("System Message",resp.mesg) ;
	}
}
function onEmpResponse(obj,resp) {
	if (resp.status == C_OK) {
		if (resp.type == C_ADD) {
			$('#sbg-emp-table tr:first').after("<tr><td>" + resp.data + "</td>" + 
				"<td>" + $('#txtCode').val() + "</td>" + 
				"<td>" + $('#txtEmpName').val() + "</td>" + 
				"<td>" + $('#cobEmpCoy :selected').text() + "</td>" + 
				"<td>" + $('#cobEmpDept :selected').text() + "</td>" +
				"<td style='text-align:center'><a href='javascript:' onclick='editEmp(" + resp.data + ",this)'><img src='image/edit_16.png' title='Edit'></img></a></td>" +
				"<td style='text-align:center'><a href='javascript:' onclick='deleteEmp(" + resp.data + ",this)'><img src='image/delete_16.png' title='Delete'></img></a></td>" +
				"</tr>"); 
		} else if (resp.type == C_DELETE) { 
			$($(obj).closest("tr")).remove() ;
		} else if (resp.type == C_UPDATE) {
			$($(obj).closest('tr')).children('td:eq(1)').text($('#txtCode').val()) ;
			$($(obj).closest('tr')).children('td:eq(2)').text($('#txtEmpName').val()) ;
			$($(obj).closest('tr')).children('td:eq(3)').text($('#cobEmpCoy :selected').text()) ;
			$($(obj).closest('tr')).children('td:eq(4)').text($('#cobEmpDept :selected').text()) ;
		}
		$('#sbg-popup-box').html(resp.mesg) ;
		$('#sbg-popup-box').show() ;
		$('#sbg-popup-box').fadeOut(5000) ;
		clearEmp() ;
	}
	else 
		showDialog("Error",resp.mesg) ;
}
function validateEmp() {
	$('#emp_err_mesg').text('') ;
	if ($('#txtEmpName').blank()) {
		$('#emp_err_name').show() ;
		$('#txtEmpName').focus() ;
		$('#emp_err_mesg').text("Employee name can not be blank.") ;
		return false ;
	} else {
		$('#emp_err_name').hide() ;
	}
	if ($('#txtCode').blank()) {
		$('#emp_err_code').show() ;
		$('#txtCode').focus() ;
		$('#emp_err_mesg').text("Employee code can not be blank.") ;
		return false ;
	} else {
		$('#emp_err_code').hide() ;
	}
	if ($('#cobEmpCoy').val() == "") {
		$('#emp_err_coy').show() ;
		$('#cobEmpCoy').focus() ;
		$('#emp_err_mesg').text("You must assign a Company to this employee") ;
		return false ;
	} else {
		$('#emp_err_coy').hide() ;
	}
	if ($('#txtEmpNric').blank()) {
		$('#emp_err_nric').show() ;
		$('#txtEmpNric').focus() ;
		$('#emp_err_mesg').text("IC/FIN no can not be blank.") ;
		return false ;
	} else {
		$('#emp_err_nric').hide() ;
	}
	if ($('#cobEmpDept').val() == "") {
		$('#emp_err_dept').show() ;
		$('#cobEmpDept').focus() ;
		$('#emp_err_mesg').text("You must assign a Department to this employee") ;
		return false;
	} else {
		$('#emp_err_dept').hide() ;
	}
	if ($('#cobEmpRace').val() == "") {
		$('#emp_err_race').show() ;
		$('#cobEmpRace').focus() ;
		$('#emp_err_mesg').text("You must assign a Race to this employee") ;
		return false;
	} else {
		$('#emp_err_race').hide() ;
	}
	if ($('#cobEmpNat').val() == "") {
		$('#emp_err_nat').show() ;
		$('#cobEmpNat').focus() ;
		$('#emp_err_mesg').text("You must assign a Nationality to this employee") ;
		return false;
	} else {
		$('#emp_err_nat').hide() ;
	}
	if ($('#cobEmpJob').val() == "") {
		$('#emp_err_job').show() ;
		$('#cobEmpJob').focus() ;
		$('#emp_err_mesg').text("You must assign a Job Title to this employee") ;
		return false;
	} else {
		$('#emp_err_job').hide() ;
	}
	if ($('#cobEmpType').val() == "") {
		$('#emp_err_type').show() ;
		$('#cobEmpType').focus() ;
		$('#emp_err_mesg').text("You must assign a Employee Type to this employee") ;
		return false;
	} else {
		$('#emp_err_type').hide() ;
	}
	if ($('#txtEmpDob').blank()) {
		$('#emp_err_dob').show() ;
		$('#txtEmpDob').focus() ;
		$('#emp_err_mesg').text("Date of Birth can not be blank.") ;
		return false ;
	} else {
		$('#emp_err_dob').hide() ;
	}
	if ($('#txtEmpDob').validDate())
		$('#emp_err_dob').hide() ;
	else {
		$('#emp_err_dob').show() ;
		$('#txtEmpDob').focus() ;
		$('#emp_err_mesg').text("Invalid date entry for Date of Birth") ;
		return false ;
	}
	if ($('#txtEmpJoin').val() != ""){
		if ($('#txtEmpJoin').validDate())
			$('#emp_err_join').hide() ;
		else {
			$('#emp_err_join').show() ;
			$('#txtEmpJoin').focus() ;
			$('#emp_err_mesg').text("Invalid date entry for Join Date") ;
			return false ;
		}
	}
	
	if ($('#txtEmpResign').val() != "")	{
		if ($('#txtEmpResign').validDate())
			$('#emp_err_resign').hide() ;
		else {
			$('#emp_err_resign').show() ;
			$('#txtEmpResign').focus() ;
			$('#emp_err_mesg').text("Invalid date entry for Resign Date") ;
			return false ;
		}
	}
	return true ;
}

