var hrURL =localStorage['serviceURLHR'];
var editIcon = "images/edit.png";
var editIconpen = "images/pen.png";
var removeIcon = "images/delete.png";

//jQuery('.searchPdt').live('click',function(){ paySalary('1','') });
jQuery('.paysalary').live('click',function(){ branchsalarypayment() });
jQuery('.editDeduction').live('click',editDeduction);
jQuery('.UpdateDeduction').live('click',UpdateDeduction);

jQuery('#empname').live('change',get_employee);
jQuery('#rdate').live('change',chkdat);
jQuery('#damount').live('keyup',deduct);
jQuery('#damount').live('blur',deduct_round);
jQuery('.addNewgratuity').live('click',addNewgratuity);
jQuery('.goBacktoList').live('click',locationHashChanged);
$('#saveNewContribution').live('click',saveNewContribution);



/*$('#rdate').on('click',function(){ alert();
		 $(this).datepicker({dateFormat:"dd-mm-yy"}).focus();	//
	});
*/
/////////////////////////////////////////  Page management and URL Tracking Functions  //////////////////////////////////////
$('.payroll-menu li').live('click',function(){
	$this = $(this);
	window.location.hash = $this.attr('data-page');
});


var itemCount=0;
var k=1;
var pageLimit = 25;

$(window).load(function(){
			   
});

$('.resi_dat').live('click',function(){ 
		 $(this).datepicker({dateFormat:"dd-mm-yy"}).focus();	//alert();
	});


$('.resi_dat_right').live('click',function(){ 
		alert("Sorry You Do Not Have Enough Permission To Edit  Gratuity");	//alert();
	});

/////////////////////////////////////////  URL TRACKING /////////////////////////////////////////////////////////////////////
locationHashChanged();					
													
window.onhashchange = locationHashChanged;			

function locationHashChanged() {	


	hash=window.location.href.split('#')[1]	
	
	if(hash){													
		$('.menu-selected').removeClass('menu-selected');			
		//var menuList = $('.payroll-menu');	
		
		if($('li[data-page="'+hash+'"]').length){
			$('li[data-page="'+hash+'"]').addClass('menu-selected');		
			 $('#light-pagination').pagination({
				itemsOnPage: pageLimit,
				cssStyle: 'light-theme',
				onPageClick : window[hash]
			});	
			
			setTimeout(window[hash],100); // call current function	
			currentPage =hash; 
			
			
		}else{
			$('li[data-page="'+currentPage+'"]').addClass('menu-selected');
			if(hash){
				//window.location.hash =	currentPage;currentPage =hash; 
			}
		}
	}else{
		window.location.hash = "paySalary";
	}									
}

loadBranch();

function loadBranch(){
	$.getJSON(serviceURLHR + 'branch.php?action=load',function(data){
		branch = data.branch;
		
		$.each(branch, function(index, branch) {
									 
							$('#branch').append('<option value="'+branch.branch_id+'">'+branch.branch_name	+'</option>');
							
		});	
	});
}

function registerwages(){
	window.location="register-wages.php#registerwages";
}

function change(page){
location.href=page;
}
function removeCurrentPage(){
$('.paymentMethod').remove();
$('#tablelist table').hide('blind',500,function(){ $(this).remove(); })	
}

function  download(pagenum)
{
	var searchString = $('.pdtSearchForm').serialize(); 
	//alert(searchString)
	window.location = serviceURLHR+"downloadsalarylist.php?pagenum="+pagenum+"&"+searchString;
}

loadimediatesupervisor();

function loadimediatesupervisor(){	
	
	$.getJSON(serviceURLHR + 'immediatesupervisor.php?action=load',function(data){
		imdsupervisor = data.imdsupervisor;
		$.each(imdsupervisor, function(index, imdsupervisor) {
									
				$('#imdatesupervisor').append('<option value="'+imdsupervisor.e_id+'">'+imdsupervisor.e_fname	+'</option>');
							
		});	
	});
}

loadholidaybranch();

function loadholidaybranch(){
	$.getJSON(serviceURLHR + 'branch.php?action=load',function(data){
		branch = data.branch;
		$('.holiday_branch').empty();
		$.each(branch, function(index, branch) {
									 
							$('.holiday_branch').append('<option value="'+branch.branch_id+'">'+branch.branch_name	+'</option>');
							
		});	
	});
}

loadimdsuper();

function loadimdsuper(){	
	
	$.getJSON(serviceURLHR + 'immediatesupervisor.php?action=load',function(data){
		imdsupervisor = data.imdsupervisor;
		$.each(imdsupervisor, function(index, imdsupervisor) {
		
				$('.imdatesuper').append('<option value="'+imdsupervisor.e_id+'">'+imdsupervisor.e_fname	+'</option>');
							
		});	
	});
}

////////////////////////////////Wages Start///////////////////////////////////////////////////
function registerwages11(){
	removeCurrentPage();
	$('.header').show('blind',500);
	$.getJSON(hrURL + "manageRegisterWages.php?act=list",function(data){
		var deduction = data.deductions;
			$('#tablelist').append('<table width="100%" border="0" cellspacing="0" style="display:none" cellpadding="0" class="list-deduction">'+
										  '<tr>'+
											'<td width="23%"><translate>Name</translate></td>'+
											'<td width="10%"><translate>Father name</translate></td>'+
											'<td width="12%"><translate>Designation</translate></td>'+
											'<td width="9%"><translate>Basic</translate></td>'+
											'<td width="6%"><translate>DA</translate></td>'+
											'<td width="5%"><img src="images/icon-add.png" class="addNewDeduction" width="20" height="20" /></td>'+
										 '</tr>'+
										'</table>')	

			$.each(deduction, function(index,deductions){
				var ded_unit='';
				var type='';
				
					$('.list-deduction').append( '<tr>'+
														'<td width="23%">'+deductions.name+'</td>'+
														'<td width="10%">'+deductions.description+'</td>'+
														'<td width="12%">'+type+'</td>'+
														'<td width="9%">'+deductions.amount+" ("+ded_unit+')</td>'+
														//'<td width="6%"><img data-id="'+deductions.id+'" src="'+editIcon+'" class="editDeduction"/></td>'+
														'<td width="5%"><img data-id="'+deductions.id+'" src="'+removeIcon+'" class="removeDeduction"/></td>'+
													 '</tr>');				
			});
			$('.list-deduction').show('blind',500);
		
	});
}

///////////////////////////////Wages End///////////////////////////////////////////////////


/////////////////////////////////////////////////////////////////////////////// Deduction management //////////////////////////////////////////////////////
function addnewDeduction(){
	if($('.newDeductionform').length){
	}else{
		$('.list-deduction').before('<form class="newDeductionform"><table width="50%" border="0" style="display:none" cellspacing="0" cellpadding="0" class="newDeduction">'+
								  '<tr>'+
									'<td width="47%">&nbsp;</td>'+
									'<td width="53%">&nbsp;</td>'+
								  '</tr>'+
								  '<tr>'+
									'<td><translate>Employee</translate></td>'+
									'<td width="6%">'+
									'<select name="member_id" class="imdatesuper" >'+
									'</select></td>'+
									'</tr>'+
								  '<tr>'+
									'<td><translate>Title</translate></td>'+
									'<td><input type="text" name="deductionTitle" id="deductionTitle" /></td>'+
								  '</tr>'+
								  '<tr>'+
									'<td><translate>Description</translate></td>'+
									'<td><textarea name="deductionDescription" id="deductionDescription" cols="45" rows="4"></textarea></td>'+
								  '</tr>'+
								  '<tr>'+
									'<td><translate>Type</translate></td>'+
									'<td><select name="type" id="type">'+
									  '<option value="1">Deduction</option>'+
									  '<option value="2">Earnings</option>'+
									  '<option value="3">Employer\'s Contribution</option>'+
									'</select>'+
									'</td>'+
								  '</tr>'+
								  '<tr>'+
									'<td><translate>Amount / Persentage</translate></td>'+
									'<td><input type="text" name="amount" id="amount" />'+
									 '<select name="unit" id="unit">'+
										'<option value="1">Rs</option>'+
										'<option value="2">%</option>'+
									  '</select>'+ 
									  '</td>'+
								  '</tr>'+
								  '<tr>'+
									'<td>&nbsp;</td>'+
									'<td><input type="button" name="button" class="color-button saveDeduction" id="button" value="Submit" />'+
									'<input type="button" name="button" class="color-button cancelDeduction" id="button" value="Cancel" /></td>'+
								  '</tr>'+
								  '<tr>'+
									'<td>&nbsp;</td>'+
									'<td>&nbsp;</td>'+
								  '</tr>'+
								'</table></form>');
	$('.newDeduction').show('blind',500);
	
	loadimdsuper();
	}
}

function editDeduction(){
	
//	$('#tablelist').html('');
	if($('.newDeductionform').length){
		
	}else{
	$this = $(this);
	var userid 	= $this.attr('data-id');
	var title_name 	  = $this.parent().parent().find('.deduct_name').text();
	var deduct_type   = $this.parent().parent().find('.deduct_type').text();
	var typeStr = '';
	if(deduct_type == "Deduction"){
		typeStr = 	'<tr><td><translate>Type</translate></td><td><select name="type" id="type"><option value="">Select type</option><option value="1">Earnings</option><option value="2" selected="selected">Deduction</option></select></td></tr>';
	}else{
		typeStr = 	'<tr><td><translate>Type</translate></td><td><select name="type" id="type"><option value="">Select type</option><option value="1" selected="selected">Earnings</option><option value="2">Deduction</option></select></td></tr>';	
	}
	$('.list-deduction').before('<div class="showeditform"><form class="newDeductionform"><table width="50%" border="0" style="display:none" cellspacing="0" cellpadding="0" class="newDeduction">'+
								  '<tr>'+
									'<td width="47%">&nbsp;</td>'+
									'<td width="53%">&nbsp;</td>'+
								  '</tr>'+
								  '<tr>'+
									'<td><translate>Title</translate></td>'+
									'<td>'+
									'<input type="hidden" name="deduct_ID" id="deduct_ID" value="'+userid+'" />'+
									'<input type="text"  name="deductionTitle" id="deductionTitle" value="'+title_name+'" /></td>'+
								  '</tr>'+
								  typeStr+
								  '<tr>'+
									'<td>&nbsp;</td>'+
									'<td><input type="button" name="button" class="color-button UpdateDeduction" id="button" value="Submit" />'+
									'<input type="button" name="button" class="color-button cancelDeduction" id="button" value="Cancel" /></td>'+
								  '</tr>'+
								  '<tr>'+
									'<td>&nbsp;</td>'+
									'<td>&nbsp;</td>'+
								  '</tr>'+
								'</table></form></div>');
	
	
	$('.newDeduction').show('blind',500);
	loadimdsuper();
	setTimeout(function(){ $('#type').val(deduct_type); },500);
	}
	
	//loadDepartment();
	//setTimeout(function(){ $('#department_name').val(departmenyid); },500);
}



function saveNewDeduction(){	
	dataString = $('.newDeductionform').serialize();
	$.post(hrURL + "manageDeduction.php?act=insert",dataString,function(data){
		var deductions = data.deduction
		switch(deductions.unit){
					case "1":ded_unit="Rs";break;
					case "2":ded_unit = "%";break;
				}
				switch (deductions.deduction_benefit){
					case "1":type = "Deduction";break;
					case "2":type = "Earnings";break;
					case "3":type = "Employer's Contribution";break;
				}
		$('.list-deduction').append( '<tr>'+
							'<td width="23%" class="deducte_fname">'+deductions.emp_name+'</td>'+
							'<td width="23%" class="deduct_name">'+deductions.name+'</td>'+
							'<td width="35%" class="deduct_desc">'+deductions.description+'</td>'+
							'<td width="12%" class="deduct_type">'+type+'</td>'+
							'<td width="19%" class="deduct_amount">'+deductions.amount+" ("+ded_unit+')</td>'+
							'<td width="6%"><img data-id="'+deductions.id+'" src="'+editIcon+'" class="editDeduction"/></td>'+
							'<td width="5%"><img data-id="'+deductions.id+'" src="'+removeIcon+'" class="removeDeduction"/></td>'+
							'</tr>');	
		
		$('.newDeductionform').hide('blind',500,function(){ $(this).remove(); });
		
	},'json');
}

function UpdateDeduction(){
	
	if ($.trim($("#deductionTitle").val()).length != 0 && $.trim($("#type").val()).length != 0) 
	{
		
	
	if ($.trim($("#deductionTitle").val()) != '') {
	var deductionDetails = $('.newDeductionform').serialize();
	
	//var departmentname 	= $('#department_name option:selected').text();
	
	var deduct_id	= $('#deduct_ID').val();
	
	
	$.post(serviceURLHR + "manageDeduction.php?act=update",deductionDetails,function(data){
																					 
		var deducts = data.deduction;
		var benfit = '';
		//alert(deducts.unit);
		console.log(data);
		if(deducts.deduction_benefit == 1)
		{
			benfit='Deduction';	   
		}
		else if(deducts.deduction_benefit == 2)
		{
			benfit='Deduction';
		}
		else if(deducts.deduction_benefit == 3)
		{
			benfit='Employers Contribution';
		}
		var currentUser = $('.deduct_'+deduct_id);
		currentUser.find('.deducte_fname').text(deducts.emp_name);
		currentUser.find('.deduct_name').text(deducts.name);
		currentUser.find('.deduct_desc').text(deducts.description);
		currentUser.find('.deduct_type').text(benfit);
		currentUser.find('.deduct_amount').text(deducts.amount);
		
	},"json");
		/*$('.newDeductionform').hide('blind',500,function(){ $(this).remove(); });*/
		window.location.reload();
	}
	else
	{
		alert('Please Select Depertment');	
		
	}
		
	}
	else
	{
		alert('All fields are required');	
	}
}


function removeDeduction(){
	var did = $(this).attr('data-id');
	$this = $(this);
	$.get(hrURL + "manageDeduction.php?act=remove&did="+did,function(){
		$this.parent().parent().remove();															 
	});
}




//////////////////////////////////////////////////////////////////////// Salary Management ////////////////////////////////////////////////////////////////

function paySalary(){
	go_to_empstruct();
    $('#light-pagination').show();
	$('.pdtSearchForm')[0].reset();
	$('#tablelist').html('');
	$('.employee-tab-dwn').css("display", "block");
	$(".memsrch").css("display", "none");
	$(".paysalsearch").css("display", "block");
	$(".calsrch").css("display", "none");
	$("#search_month").css("display", "block");
	$("#search_year").css("display", "block");
	$('.header').show('blind',500);
	removeCurrentPage();
	$('#payroll_search_btn').attr("onclick", 'search_emp_pay_salary()');	
	$('#tablelist').append('<table width="100%" border="0" cellspacing="0" style="display:none" cellpadding="0" class="list-employees">'+
		'<tr>'+
			'<td width="20%"><translate>Employee Name</translate></td>'+
			'<td width="12%"><translate>Branch</translate></td>'+
			'<td width="11%"><translate>Basic Pay</translate></td>'+
			'<td width="11%"><translate>Earnings</translate></td>'+
			'<td width="16%"><translate>Deductions</translate></td>'+
			'<td width="11%"><translate>Loss of Pay</translate></td>'+
			'<td width="11%"><translate>Net Pay</translate></td>'+
			'<td width="11%"><translate>Pay Slip</translate></td>'+
			'<td width="11%"><translate>Status</translate></td>'+
			'<td width="11%"><translate>Pay Type</translate></td>'+
		'</tr>'+
	'</table>');
	
	$.ajax({
		url:hrURL+"managePayrollSalary.php",
		type:"post",
		data:"act=EmployeePaySalary",
		success:function(result){
    		$('.list-employees').append(result);
			$('.expand_parent_row').click(function () {
				var currentDetails = $(this).next('.row_to_expand');
				$('.row_to_expand').not(currentDetails).hide();
				currentDetails.toggle();
			});
			$('.list-employees').show('blind',500);
			$('#light-pagination').pagination('updateItems',itemCount);
  		}
	});
}
/*function paySalary(pageno,e){/*
	$(".memsrch").css("display", "none");
	$(".paysalsearch").css("display", "block");
	$(".calsrch").css("display", "none");
	if(!pageno)
	pageno =1;
	var totbasicpay = 0;
	var totdeduction = 0;
	var totbenefit = 0;
	var totcontribution = 0;
	var totpayable = 0;

	var searchString = $('.pdtSearchForm').serialize(); 
	//alert(searchString);
	if(pageno == 1 ){
			k=1; 
		 }else{
			k= ((pageno-1) * pageLimit)+1;
		 }
		 var tot = 0;
	
	$('.header').show('blind',500);
	removeCurrentPage();
	
	
	
	
	$('#tablelist').append('<table width="100%" border="0" cellspacing="0" style="display:none" cellpadding="0" class="list-employees">'+
							 ' <tr>'+
								'<td width="20%" height="17"><translate>Name</translate></td>'+
								'<td width="10%"><translate>Branch</translate></td>'+
								'<td width="12%"><translate>Basic Pay</translate></td>'+
								'<td width="11%"><translate>Deductions</translate></td>'+
								'<td width="11%"><translate>Loss of Pay</translate></td>'+
								'<td width="11%"><translate>Earnings</translate></td>'+
								'<td width="16%"><translate>Employer Contributions</translate></td>'+
								'<td width="11%"><translate>Total Payable</translate></td>'+
								'<td width="9%"><translate>Pay Slip</translate></td>'+
								'<td width="9%"><translate>Payment Status</translate></td>'+
								'</tr>'+
								 
							'</table>');
	
	
	
	$.getJSON(hrURL+"manageSalary.php?act=lastms&page="+pageno+"&"+searchString,function(data){
		var salaryDetails = data.salaryDetails;
		
		$.each(salaryDetails,function(index,salaryDetails){
									  
		var status;
		if(salaryDetails.paymentStatus == 1){
			status ="Paid"; //'<img src="images/1388406658_ok-green.png" width="20"/> ';		
		}else{
			status ="Not Paid"; //'<img src="images/1388407735_delete_64.png" width="20"/> ';	
		}

			
			totbasicpay = parseInt(parseFloat(totbasicpay) + parseFloat(salaryDetails.basic_pay));
			totdeduction = parseInt(parseFloat(totdeduction) + parseFloat(salaryDetails.deduction));
			totbenefit = parseInt(parseFloat(totbenefit) + parseFloat(salaryDetails.benefit));
			totcontribution = parseInt(parseFloat(totcontribution) + parseFloat(salaryDetails.contribution));
			
		
			var total = (parseFloat(salaryDetails.basic_pay)+parseFloat(salaryDetails.benefit)-parseFloat(salaryDetails.deduction)).toFixed(2)	;		
			totpayable = parseFloat(totpayable) + parseFloat(total);
			$('.list-employees').append(' <tr>'+
											'<td width="20%" height="17">'+salaryDetails.name+'</td>'+
											'<td width="10%" height="17">'+salaryDetails.branch_name+'</td>'+
											'<td width="12%">'+parseFloat(salaryDetails.basic_pay).toFixed(2)+'</td>'+
											'<td width="11%">'+parseFloat(salaryDetails.deduction).toFixed(2)+'</td>'+
											'<td width="11%">'+parseFloat(salaryDetails.totalleavededuction).toFixed(2)+'</td>'+
											'<td width="11%">'+parseFloat(salaryDetails.benefit).toFixed(2)+'</td>'+
											'<td width="16%">'+parseFloat(salaryDetails.contribution).toFixed(2)+'</td>'+
											'<td width="11%">'+total+'</td>'+
											'<td width="9%"><a class="payslip showPaySlip" style="cursor:pointer" data-id="'+salaryDetails.employee_id+'">Pay Slip</a></td>'+
											'<td width="11%" align="center">'+status+'</td>'+
											'</tr>');
			
			itemCount = salaryDetails.totalrows;
			
				k++;
		});
		
		$('.list-employees').append(' <tr>'+
											'<td width="20%" height="17"></td>'+
											'<td width="10%" height="17" >Total</td>'+
											'<td width="12%">'+totbasicpay+'</td>'+
											'<td width="11%">'+totdeduction+'</td>'+
											'<td width="11%">'+totbenefit+'</td>'+
											'<td width="16%">'+totcontribution+'</td>'+
											'<td width="9%"></td>'+
											'<td width="11%">'+totpayable.toFixed(2)+'</td>'+
											'<td width="9%"></td>'+
											'<td width="11%" align="center"></td>'+
											'</tr>');
		
			
		$('.list-employees').show('blind',500);
		
		 $('#light-pagination').pagination('updateItems',itemCount);
			
	});
	//setTimeout(function(){ loadBranch(); } , 150);
	
	
}*/

function branchsalarypayment(){
var salmonth=$('#salmonth').val();
var salyear=$('#salyear').val();	
var branch=$('#branch').val();

		$('.header').show('blind',500);
	removeCurrentPage();

	$('#tablelist').append('<table width="100%" border="0" cellspacing="0" style="display:none" cellpadding="0" class="list-employees">'+
							 ' <tr>'+
								'<td width="20%" height="17"><translate>Name</translate></td>'+
								'<td width="10%"><translate>Branch</translate></td>'+
								'<td width="12%"><translate>Basic Pay</translate></td>'+
								'<td width="11%"><translate>Deductions</translate></td>'+
								'<td width="11%"><translate>Earnings</translate></td>'+
								'<td width="16%"><translate>Employer Contributions</translate></td>'+
								'<td width="11%"><translate>Total Payable</translate></td>'+
								'<td width="9%"><translate>Pay Slip</translate></td>'+
								'<td width="9%"><translate>Payment Status</translate></td>'+
								'</tr>'+
							'</table>');	
	
	$.getJSON(hrURL+"manageSalary.php?act=paysalary&branch="+branch+"&salmonth="+salmonth+"&salyear="+salyear,function(data){
																							  
	alert('Salary Payment Successful');
	var salaryDetails = data.salaryDetails;
		
		$.each(salaryDetails,function(index,salaryDetails){
									  
		var status;
		if(salaryDetails.paymentStatus == 1){
			status ="Paid"; //'<img src="images/1388406658_ok-green.png" width="20"/> ';		
		}else{
			status ="Not Paid"; //'<img src="images/1388407735_delete_64.png" width="20"/> ';	
		}
		
		
			var total = (parseFloat(salaryDetails.basic_pay)+parseFloat(salaryDetails.benefit)-parseFloat(salaryDetails.deduction)).toFixed(2)	;					  
			$('.list-employees').append(' <tr>'+
											'<td width="20%" height="17">'+salaryDetails.name+'</td>'+
											'<td width="10%" height="17">'+salaryDetails.branch_name+'</td>'+
											'<td width="12%">'+parseFloat(salaryDetails.basic_pay).toFixed(2)+'</td>'+
											'<td width="11%">'+parseFloat(salaryDetails.deduction).toFixed(2)+'</td>'+
											'<td width="11%">'+parseFloat(salaryDetails.benefit).toFixed(2)+'</td>'+
											'<td width="16%">'+parseFloat(salaryDetails.contribution).toFixed(2)+'</td>'+
											'<td width="11%">'+total+'</td>'+
											'<td width="9%"><a class="payslip showPaySlip" style="cursor:pointer" data-id="'+salaryDetails.employee_id+'">Pay Slip</a></td>'+
											'<td width="11%" align="center">'+status+'</td>'+
											'</tr>');
			
			itemCount = salaryDetails.totalrows;
			
				
	});
	
	$('.list-employees').show('blind',500);});
}
//$('.showPaySlip').live('click',function(){
	//window.location.hash = $(this).attr('data-id');	
//	History.pushState({state:1}, "State 1", "?state=1");
//});


function preloadPaySlip(){
//	removeCurrentPage();

	$this = $(this);	
	var  paymentmonth = $('.paymentmonth').val();
	var  paymentyear  = $('.paymentyear').val();
	var  branch  = $('#branch').val();
paySlip($this,paymentmonth,paymentyear,branch) ;
}

function paySlip($this,paymentmonth,paymentyear,branch){
	
	
var  paymentmonth = $('#salmonth').val();
	var  paymentyear  = $('#salyear').val();
removeCurrentPage();
$("#light-pagination").css("display", "none");
$("#tabletoatal").css("display", "none");
	var employeeid =$this.attr('data-id'); 
	$('.header').hide('blind',500);

	
	if(paymentmonth == null){
		
		var d = new Date();
		var paymentmonth =d.getMonth() +1; 

	}else{
		if(parseInt(paymentmonth) < 10){
		paymentmonth = 0+paymentmonth;	
		}
	}
	
	if(paymentyear==null){
			 var dt = new Date();
			dt.setDate(1);
			//dt.setMonth(dt.getMonth() - 1);
			var paymentyear =dt.getFullYear(); 
		//	alert(dt);
	}
	//$('#busy').show();
	//$('#tablelist form').hide('blind',200);

	firstdateofmth = "01/"+paymentmonth+"/"+paymentyear;

	var lastDay = new Date(paymentyear,paymentmonth, 0);
	var lastdateofmth = new Date(lastDay).format("mm-dd-yyyy");
	localStorage['lastdateofmth']=lastdateofmth;

	var month=new Array();
	month[1]="January";
	month[2]="February";
	month[3]="March";
	month[4]="April";
	month[5]="May";
	month[6]="June";
	month[7]="July";
	month[8]="August";
	month[9]="September";
	month[10]="October";
	month[11]="November";
	month[12]="December";
	
	var name_paymentmonth=paymentmonth;
	if(paymentmonth < 10 && paymentmonth.length > 1){
		
		name_paymentmonth = paymentmonth[2];
		paymentmonth = paymentmonth[1]+paymentmonth[2];	
		
		
	}
	
	var n = month[name_paymentmonth];
	var joindate;
	//alert(paymentmonth);
	
		//alert(paymentmonth.length);
		if(paymentmonth<10)
		{
			paymentmonth='0'+parseInt(paymentmonth);
		}
	

	$.getJSON(hrURL+"manageSalary.php?act=single&emp_id="+employeeid+"&month="+paymentmonth+"&year="+paymentyear+"&branch="+branch,function(data){
		var earnings = data.salaryDetails;
		//$('#busy').hide();
		//$('#tablelist').html('');
		
			var saldate=paymentyear+'-'+paymentmonth+'-01';
			
		$('#tablelist').append('<form class="paySlipForm">'+
							   
							   '<table width="100%" style="display:none" height="224" class="paySlip" border="0" cellpadding="0" cellspacing="0">'+
							  '<tr>'+
								'<td align="center">'+
								'<input type="hidden" name="year" class="paymentyear" data-id="'+employeeid+'" value="'+paymentyear+'" />'+
								'<input type="hidden" name="month" class="paymentmonth" data-id="'+employeeid+'" value="'+paymentmonth+'" />'+
								//'<div class="pay-slip-title-res-name" style="height:50px;"></div>'+
								'<div class="pay-slip-title" width="50%" style="font-size:14px;font-weight:bold;float:left;">Macollins</div>'+
								
								//'<div class="pay-slip-title-res-name" style="height:50px;"></div>'+
								'<div class="pay-slip-title" width="50%" style="font-size:14px;font-weight:bold;float:right;padding-right:30px;">Wages Slip</div></td>'+'</tr>'+
								'<tr>'+'<td align="center" style="padding-bottom:20px;padding-top:10px;">'+
								//'<div class="pay-slip-title-res-name" style="height:50px;"></div>'+
								'<div class="pay-slip-title" width="50%" style="float:left;">FORM XIII [See Rule 29 (2)]</div>'+
								
								//'<div class="pay-slip-title-res-name" style="height:50px;"></div>'+
								'</td>'+
								'</tr>'+
							 ' <tr>'+
								'<td height="122" valign="top"><table class="employee-details" width="100%" height="121" border="0" cellpadding="0" cellspacing="0">'+
								
								' <tr>'+
								 	'<td style="border-bottom:1px solid #aaa; font-size14px; font-weight:bold;"><translate>Branch</translate></td>'+
									'<td class="branch_name" style="border-bottom:1px solid #aaa; font-size14px; font-weight:bold;">&nbsp;</td>'+
									'<td style="border-bottom:1px solid #aaa; font-size14px; font-weight:bold;"><translate>Month & Year</translate></td>'+
									'<td class="monthyear" style="width:100px;border-bottom:1px solid #aaa; font-size14px; font-weight:bold;">'+ n +" "+ paymentyear +'</td>'+
									'<td style="border-bottom:1px solid #aaa; font-size14px; font-weight:bold;"><translate>Payment Date</translate></td>'+
									'<td class="paymentdate" style="width:250px;border-bottom:1px solid #aaa; font-size14px; font-weight:bold;">&nbsp;</td>'+
								  '</tr>'+
								 ' <tr>'+
									'<td width="13%"><translate>Employee ID and Name</translate></td>'+
									'<td width="20%" class="empid">&nbsp;</td>'+
									'<td width="13%"><translate>Fathers Name</translate></td>'+
									'<td width="20%" class="fatrname">&nbsp;</td>'+
								  '</tr>'+
								  '<tr>'+
									'<td><translate>Department Name</translate></td>'+
									'<td class="department">&nbsp;</td>'+
									'<td><translate>Designation</translate></td>'+
									'<td class="designation">&nbsp;</td>'+
								 ' </tr>'+
								 ' <tr>'+
								 	'<td><translate>Working Days</translate></td>'+
									'<td class="workingdays">&nbsp;</td>'+
									'<td><translate>Present Days</translate></td>'+
									'<td class="workeddays" style="width:100px;">&nbsp;</td>'+
									'<td><translate>Payment Mode</translate></td>'+
									'<td class="paymentMethods" style="width:250px;">&nbsp;</td>'+
								  '</tr>'+
								  
								'</table></td>'+
							  '</tr>'+
							  '<tr>'+
								'<td height="122" valign="top">'+
								
								'<table width="100%" class="earnings-deduction" border="0" cellpadding="0" cellspacing="0">'+
								  '<tr>'+
									'<td width="50%" height="30"><translate>Earning</translate></td>'+
									'<td width="50%"><translate>Deductions</translate></td>'+
								  '</tr>'+
								  '<tr><td valign="top" class="totalEarnings">'+
								 ' <span class="basicPay" style="width:80%; height:25px; float:left;"><translate>Basic Pay</translate></span>'+
									'<span class="basicPayAmt" style="float:right; width:20%; text-align:right;"></span>'+

								  
								  '</td><td valign="top" class="totalDeductions">'+
								  

								  
								  '</td></tr>'+
								  '<tr class="total-earnings">'+
									'<td  height="30"><span class="earnings" style="width:80%; height:25px; float:left;font-weight:bold;"><translate>Gross Pay</translate></span>'+
									'<span class="totalEarningsAmount" style="float:right; width:20%; text-align:right;"></span></td>'+
									'<td><span class="earnings" style="width:80%; height:25px; float:left;font-weight:bold;"><translate>Total Deductions</translate></span>'+
									'<span class="leaves" style="float:right; width:20%; text-align:right;"><input type="hidden" value="" name="earned_leaves" class="earned_leaves"></span>'+
         '<span class="lossofpayLeaves" style="float:right; width:20%; text-align:right;"><input type="hidden" value="" name="lossofpay_leaves" class="lossofpay_leaves" ></span>'+
									'<span class="totalDeductionAmount" style="float:right; width:20%; text-align:right;"></span></td>'+
								  '</tr>'+
								  '<tr class="total-earnings">'+
									'<td  height="30"><span class="earnings" style="width:80%; height:25px; float:left;"></span>'+
									'<span class="totalEarningsAmountaa" style="float:right; width:20%; text-align:right;"><translate>Net Pay</translate></span></td>'+
									'<td><span class="netPayable" style="width:80%; height:25px; float:left;"></span>'+
									'<span class="totalDeductionAmountaa" style="float:right; width:20%; text-align:right;"></span></td>'+
								  '</tr>'+
								   '<tr>'+
								'<td style="font-weight:bold;" colspan="2">Amount in Words :<span class="amountinwords" id="amountinwords"></span>'+
								
								
								
								'</td>'+
								
							 ' </tr>'+
							 '<table width="100%" height="100" class="paySlip" border="0" cellpadding="0" cellspacing="0"><td valign="top" class="">'+
								 ' <span class="" style="width:80%; height:25px; float:left;"></span>'+
									'<span class="" style="float:right; width:20%; text-align:right;"></span>'+

								  
								  '</td><td valign="top" class="">'+
								  

								  
								  '</td></tr>'+
								  '<tr class="">'+
									'<td  height="20">'+
									'</td>'+
									'<td>'+
									'</td>'+
								  '</tr>'+
								  '<tr class="">'+

									'<td  height="20" width="80%" style="font-weight:bold;">Supervisor Signature'+

									'</td>'+
									'<td  height="20" >'+
									'</td>'+
									'<td style="font-weight:bold;">Employee Signature'+
									'</td>'+
								  '</tr></table>'+
								  
								'</table></td>'+
								'</tr>'+
							 
							 '<tr>'+
							  '<tr>'+
								'<td>'+
								'<input type="button" class="color-button goBacktoList" style="float:left" value="Back">'+
								'<input type="button" class="color-button payCurrentSalary" style="float:left" value="Pay Salary">'+
								'<input type="button" class="color-button printPaySlip" style="display:none" value="Print PaySlip">'+
								'</td>'+
								'</tr>'+
							'</table></form>');
		var totalEarnings = 0;
		var totalDeduction = 0;
		var totalContribution = 0;
		
		$.each(earnings, function(index,earnings){
	
		
		$('.basicPayAmt').html(parseFloat(earnings.emp_basic_pay).toFixed(2));
		$('.empid').html(': '+earnings.e_id+'  '+earnings.e_fname);
		
		$('.branch_name').html(': '+earnings.branch_name);
		$('.workingdays').html(': '+earnings.workingDays);
		$('.workeddays').html(': '+earnings.lastMonthDays);
		$('.fatrname').html(': '+earnings.e_mname);
		$('.designation').html(': '+earnings.desig_name);
		$('.department').html(': '+earnings.depart_name);
		//$('.lossofpayLeaves').html(': '+earnings.lastMonthDays);
		//$('.leaves').html(': '+earnings.earnesLeaves);
		$('.lossofpay_leaves').val(earnings.lossofpay);
		$('.earned_leaves').val(earnings.earnesLeaves);
  		
		
		
		if(!(earnings.payment_date)){
		$('.paymentdate').html(': ');
		}else{$('.paymentdate').html(': '+new Date(earnings.payment_date).format("dd-mm-yyyy"));
		}
		
		var currentdate = new Date().format("yyyy-mm-dd");
		
	
		if(saldate>currentdate)
		{
			$(".payCurrentSalary").css("display", "none");
		}
		else
		{$(".payCurrentSalary").css("display", "block");
			}
		//$('.leaves').append('<input type="hidden" value='+earnings.earnesLeaves+' name="earned_leaves">');
		$('.basicPayAmt').append('<input type="hidden" value='+parseFloat(earnings.emp_basic_pay).toFixed(2)+' name="basicPayAmt"><input type="hidden" value='+earnings.DA+' name="emp_da"><input type="hidden" value='+earnings.grosssalary+' name="grosssalary"><input type="hidden" value='+earnings.PF+' name="emp_PF"><input type="hidden" value='+earnings.ESI+' name="emp_ESI"><input type="hidden" value='+earnings.lastMonthDays+' name="totworkeddays">');
		$('.empid').append('<input type="hidden" value='+earnings.e_id+' name="userid">');
		//$('.lossofpayLeaves').append('<input type="hidden" value='+earnings.lossofpay+' name="lossofpay_leaves">');
		
		
		
		if(earnings.paymentMethod){
			$('.paymentMethods').html(': '+earnings.paymentMethod + "("+ earnings.referances + ")");
		}else{
			$('.paymentMethods').html(': ');	
		}
		
		
		
		
		var paymentPerDay = parseFloat(earnings.emp_basic_pay)/parseFloat(earnings.totalDays);
		
		if(earnings.leave_tot_ded=='')
		var deductionLeaves = paymentPerDay*parseFloat(earnings.lossofpay);
		else
		var deductionLeaves = parseFloat(earnings.leave_tot_ded);
			
			/*joindate = new Date(earnings.e_dstart).format('dd-mm-yyyy');
			$('.joiningdate').html(': '+joindate);
			
			joindate = new Date(earnings.e_dstart).format('mm-dd-yyyy');*/
			
			
		
		
		if(earnings.deduction_benefit == "1"){
			$('.totalDeductions').append('<span class="earnings" style="width:80%; height:25px; float:left;">'+earnings.name+'</span>'+
									'<span class="deductionAmt" style="float:right; width:20%; text-align:right;">'+parseFloat(earnings.totalamount).toFixed(2)+'</span>');	
			
			$('.totalDeductions').append('<input type="hidden" value='+parseFloat(earnings.totalamount).toFixed(2)+' name="deductionAmt[]">');
			$('.totalDeductions').append('<input type="hidden" value='+parseFloat(earnings.totalamount).toFixed(2)+' name="deductionhiddenAmt[]">');
			$('.totalDeductions').append('<input type="hidden" value='+parseFloat(earnings.amount).toFixed(2)+' name="deductionPrice[]">');
			$('.totalDeductions').append('<input type="hidden" value='+earnings.unit+' name="deductionUnit[]">');
			$('.totalDeductions').append('<input type="hidden" value='+earnings.deduction_id+' name="deductionId[]">');
			
			totalDeduction +=parseFloat(earnings.totalamount);
		}else if(earnings.deduction_benefit == "2"){
			$('.totalEarnings').append('<span class="earnings" style="width:80%; height:25px; float:left;">'+earnings.name+'</span>'+
									'<span class="earningAmt" style="float:right; width:20%; text-align:right;">'+parseFloat(earnings.totalamount).toFixed(2)+'</span>');
			
			$('.totalEarnings').append('<input type="hidden" value='+parseFloat(earnings.totalamount).toFixed(2)+' name="deductionAmt[]">');
			$('.totalEarnings').append('<input type="hidden" value='+parseFloat(earnings.amount).toFixed(2)+' name="deductionPrice[]">');
			$('.totalEarnings').append('<input type="hidden" value='+earnings.unit+' name="deductionUnit[]">');
			$('.totalEarnings').append('<input type="hidden" value='+earnings.deduction_id+' name="deductionId[]">');
			
			
			totalEarnings +=parseFloat(earnings.totalamount);
			
		}else{
			
			if(earnings.totalamount !==null){
				totalContribution +=parseFloat(earnings.totalamount);
			}
			
			$('.totalEarnings').append('<input type="hidden" value='+parseFloat(earnings.totalamount).toFixed(2)+' name="deductionAmt[]">');
			$('.totalEarnings').append('<input type="hidden" value='+parseFloat(earnings.amount).toFixed(2)+' name="deductionPrice[]">');
			$('.totalEarnings').append('<input type="hidden" value='+earnings.unit+' name="deductionUnit[]">');
			$('.totalEarnings').append('<input type="hidden" value='+earnings.deduction_id+' name="deductionId[]">');
		}
		
		if(earnings.lossofpay > 0){
			$('.totalDeductions').append('<span class="earnings" style="width:80%; height:25px; float:left;"><translate>Leave</translate></span>'+
 									'<span class="deductionAmt" style="float:right; width:20%; text-align:right;"><input type="text" value='+parseFloat(deductionLeaves).toFixed(2)+' name="leave_deduction" style="width:40px;border:solid thin;"></span>');
			
		
			
			
		totalDeduction +=parseFloat(deductionLeaves);
		}
		
		if(earnings.overtime_status == 1 && earnings.over_time_sal > 0){
			
			$('.totalEarnings').append('<span class="earnings" style="width:80%; height:25px; float:left;"><translate>Over Time</translate></span>'+
 									'<span class="earningAmt" style="float:right; width:20%; text-align:right;">'+parseFloat(earnings.over_time_sal .toFixed(2))+'<input type="hidden" value='+parseFloat(earnings.over_time_sal.toFixed(2))+' name="over_time_pay" style="width:40px;border:solid thin;"></span>');
			
		
			
			
		totalEarnings +=parseFloat(earnings.over_time_sal.toFixed(2));
		}
		
			$('.totalEarningsAmount').html((parseFloat(totalEarnings)+parseFloat(earnings.emp_basic_pay)).toFixed(2));
			$('.totalDeductionAmount').html(totalDeduction.toFixed(2));
			$('.totalContribution').html(totalContribution.toFixed(2));
			
		$('.netPayable').html((parseFloat(totalEarnings)+parseFloat(earnings.emp_basic_pay)-totalDeduction).toFixed(2));
		$('.netPayable').append('<input type="hidden" value='+(parseFloat(totalEarnings)+parseFloat(earnings.emp_basic_pay)-totalDeduction).toFixed(2)+' name="total_payable" id="total_payable">');
		$('.netPayable').append('<input type="hidden" value='+(parseFloat(totalEarnings)+parseFloat(earnings.emp_basic_pay)).toFixed(2)+' name="total_earnings" id="total_earnings">');
		$('.netPayable').append('<input type="hidden" value='+totalDeduction.toFixed(2)+' name="total_deductions" id="total_deductions">');
		
		if(earnings.status == 'paid'){
			$('.payCurrentSalary').val('Salary Paid');
			$('.payCurrentSalary').removeClass('payCurrentSalary');	
			$('.printPaySlip').css({"display":"block","float":"left"});
		}
		var netpayable=(parseFloat(totalEarnings)+parseFloat(earnings.emp_basic_pay)-totalDeduction).toFixed(2)
		paisa_conver(netpayable);
		var sum_to_words=$('#amountinwords').html();
		$('.netPayable').append('<input type="hidden" value="'+sum_to_words+'" name="sum_to_words" id="sum_to_words">');
//	}
		});
		
		
		//alert("Slow ?");
		
		
		    // var joindate = new Date(joindate);
			 var lastdateofmth = new Date(lastDay);

		/*	if(joindate > lastdateofmth){
	
				$('.payCurrentSalary').val('Employee Joined Date is Grater');
				$('.payCurrentSalary').attr('class','color-button');
			}*/
		
		
		
		
		$('.paySlip').show('blind',500,function(){
			if($('.paySlipForm').length > 1){
				$('.paySlipForm:first').remove();
			}										
		});
		
		//alert(paymentmonth);
		$('.paymentmonth').getmonths(paymentmonth);
		$('.paymentyear').getYears(paymentyear);
	});
}

function oldpaySlip($this,paymentmonth,paymentyear){
	//alert(paymentmonth);
removeCurrentPage();
	var employeeid =$this.attr('data-id'); 
	$('.header').hide('blind',500);

	var  branch  = $('#branch').val();
	if(paymentmonth == null){
		var d = new Date();
		var paymentmonth =d.getMonth() +1; 

	}else{
		if(parseInt(paymentmonth) < 10){
		paymentmonth = 0+paymentmonth;	
		}
	}
	
	if(paymentyear==null){
			 var dt = new Date();
			dt.setDate(1);
			//dt.setMonth(dt.getMonth() - 1);
			var paymentyear =dt.getFullYear(); 
		//	alert(dt);
	}
	//$('#busy').show();
	//$('#tablelist form').hide('blind',200);

	firstdateofmth = "01/"+paymentmonth+"/"+paymentyear;

	var lastDay = new Date(paymentyear,paymentmonth, 0);
	var lastdateofmth = new Date(lastDay).format("mm-dd-yyyy");
	localStorage['lastdateofmth']=lastdateofmth;

	var month=new Array();
	month[1]="January";
	month[2]="February";
	month[3]="March";
	month[4]="April";
	month[5]="May";
	month[6]="June";
	month[7]="July";
	month[8]="August";
	month[9]="September";
	month[10]="October";
	month[11]="November";
	month[12]="December";
	
	
	if(paymentmonth < 10 && paymentmonth.length > 1){
		paymentmonth = paymentmonth[1];	
	}

	var n = month[paymentmonth];
	var joindate;
	
	
	$.getJSON(hrURL+"manageSalary.php?act=printsalary&emp_id="+employeeid+"&branch="+branch+"&month="+paymentmonth+"&year="+paymentyear,function(data){
		var earnings = data.salaryDetails;
		//$('#busy').hide();
		//$('#tablelist').html('');
		
		$('#tablelist').append('<form class="paySlipForm"><table width="100%" border="0" cellspacing="0" cellpadding="0">'+
								  '<tr>'+
									'<td width="38%">'+
									'<input type="button" class="color-button gobacktolist" value="Back To List"/>'+
									'Change Pay Period</td>'+
									'<td width="6%">'+
									
									
									'<select name="year" class="paymentyear" data-id="'+employeeid+'">'+
									'</select></td>'+
									'<td width="8%">'+
									
									'<select name="month"  class="paymentmonth" data-id="'+employeeid+'">'+
									'</select></td>'+
									
									'<td width="48%">&nbsp;</td>'+
								  '</tr>'+
								'</table>'+
							   
							   '<table width="100%" style="display:none" height="224" class="paySlip" border="0" cellpadding="0" cellspacing="0">'+
							  '<tr>'+
								'<td height="80" align="center">'+
								//'<div class="pay-slip-title-res-name" style="height:50px;"></div>'+
								'<div class="pay-slip-title">Pay Slip for the period of  '+ n +" "+ paymentyear +'</div></td>'+
								'</tr>'+
							 ' <tr>'+
								'<td height="122" valign="top"><table class="employee-details" width="100%" height="121" border="0" cellpadding="0" cellspacing="0">'+
								 ' <tr>'+
									'<td width="13%"><translate>Employee ID</translate></td>'+
									'<td width="37%" class="empid">&nbsp;</td>'+
									'<td width="14%"><translate>Employee Name</translate></td>'+
									'<td width="36%" class="empname">&nbsp;</td>'+
								  '</tr>'+
								  '<tr>'+
									'<td><translate>Joining Date</translate></td>'+
									'<td class="joiningdate">&nbsp;</td>'+
									'<td><translate>Designation</translate></td>'+
									'<td class="designation">&nbsp;</td>'+
								 ' </tr>'+
								 ' <tr>'+
									'<td><translate>Days Worked</translate></td>'+
									'<td class="workeddays">&nbsp;</td>'+
									'<td><translate>Payment Method</translate></td>'+
									'<td class="paymentMethods">&nbsp;</td>'+
								  '</tr>'+
								  '<tr>'+
									'<td><translate>Earned Leaves</translate></td>'+
									'<td class="leaves">&nbsp;</td>'+
									'<td><translate>Loss of pay</translate></td>'+
									'<td class="lossofpayLeaves">&nbsp;</td>'+
								  '</tr>'+
								'</table></td>'+
							  '</tr>'+
							  '<tr>'+
								'<td height="122" valign="top">'+
								
								'<table width="100%" class="earnings-deduction" border="0" cellpadding="0" cellspacing="0">'+
								  '<tr>'+
									'<td width="50%" height="30"><translate>Earning</translate></td>'+
									'<td width="50%"><translate>Deductions</translate></td>'+
								  '</tr>'+
								  '<tr><td valign="top" class="totalEarnings">'+
								 ' <span class="basicPay" style="width:80%; height:25px; float:left;"><translate>Basic Pay</translate></span>'+
									'<span class="basicPayAmt" style="float:right; width:20%; text-align:right;"></span>'+

								  
								  '</td><td valign="top" class="totalDeductions">'+
								  

								  
								  '</td></tr>'+
								  '<tr class="total-earnings">'+
									'<td  height="30"><span class="earnings" style="width:80%; height:25px; float:left;"><translate>Total Earnings</translate></span>'+
									'<span class="totalEarningsAmount" style="float:right; width:20%; text-align:right;"></span></td>'+
									'<td><span class="earnings" style="width:80%; height:25px; float:left;"><translate>Total Deduction</translate></span>'+
									'<span class="totalDeductionAmount" style="float:right; width:20%; text-align:right;"></span></td>'+
								  '</tr>'+
								'</table></td>'+
								'</tr>'+
							  '<tr>'+
								'<td>'+
								
								'<table width="100%" border="0" cellspacing="0" cellpadding="0" class="paymentSummery">'+
                                  '<tr>'+
                                    '<td width="50%"><span class="earnings" style="width:80%; height:25px; float:left;"><translate>Employer Contribution</translate></span>'+
									'<span class="totalContribution" style="float:right; width:20%; text-align:right;"></span></td>'+
									
                                    '<td><span class="earnings" style="width:80%; height:25px; float:left;"><translate>Net Payable</translate></span>'+
									'<span class="netPayable" style="float:right; width:20%; text-align:right;"></span></td>'+
                                  '</tr>'+

                                '</table>'+
								
								'</td>'+
							 ' </tr>'+
							  '<tr>'+
								'<td>'+
								'<input type="button" class="color-button payCurrentSalary" style="float:left" value="Pay Salary">'+
								'<input type="button" class="color-button printPaySlip" style="display:none" value="Print PaySlip">'+
								'</td>'+
								'</tr>'+
							'</table></form>');
		var totalEarnings = 0;
		var totalDeduction = 0;
		var totalContribution = 0;
		
		$.each(earnings, function(index,earnings){
		
		$('.basicPayAmt').html(parseFloat(earnings.emp_basic_pay).toFixed(2));
		$('.empid').html(': '+earnings.e_id);
		
		
		
		$('.empname').html(': '+earnings.e_fname);
		$('.designation').html(': '+earnings.e_post);
		$('.workeddays').html(': '+earnings.lastMonthDays);
		$('.leaves').html(': '+earnings.earnesLeaves);
		$('.lossofpayLeaves').html(': '+earnings.lossofpay);
		
		
		$('.leaves').append('<input type="hidden" value='+earnings.earnesLeaves+' name="earned_leaves">');
		$('.basicPayAmt').append('<input type="hidden" value='+parseFloat(earnings.emp_basic_pay).toFixed(2)+' name="basicPayAmt">');
		$('.empid').append('<input type="hidden" value='+earnings.e_id+' name="userid">');
		$('.lossofpayLeaves').append('<input type="hidden" value='+earnings.lossofpay+' name="lossofpay_leaves">');
		
		
		
		if(earnings.paymentMethod){
			$('.paymentMethods').html(': '+earnings.paymentMethod + "("+ earnings.referances + ")");
		}else{
			$('.paymentMethods').html(': ');	
		}
		
		
		
		
		var paymentPerDay = parseFloat(earnings.emp_basic_pay)/parseFloat(earnings.totalDays);
		var deductionLeaves = paymentPerDay*parseFloat(earnings.lossofpay);
		
			joindate = new Date(earnings.e_dstart).format('dd-mm-yyyy');
			$('.joiningdate').html(': '+joindate);
			
			joindate = new Date(earnings.e_dstart).format('mm-dd-yyyy');
			
			
		
		
		if(earnings.deduction_benefit == "1"){
			$('.totalDeductions').append('<span class="earnings" style="width:80%; height:25px; float:left;">'+earnings.name+'</span>'+
									'<span class="deductionAmt" style="float:right; width:20%; text-align:right;">'+parseFloat(earnings.totalamount).toFixed(2)+'</span>');	
			
			$('.totalDeductions').append('<input type="hidden" value='+parseFloat(earnings.totalamount).toFixed(2)+' name="deductionAmt[]">');
			$('.totalDeductions').append('<input type="hidden" value='+parseFloat(earnings.amount).toFixed(2)+' name="deductionPrice[]">');
			$('.totalDeductions').append('<input type="hidden" value='+earnings.unit+' name="deductionUnit[]">');
			$('.totalDeductions').append('<input type="hidden" value='+earnings.deduction_id+' name="deductionId[]">');
			
			totalDeduction +=parseFloat(earnings.totalamount);
		}else if(earnings.deduction_benefit == "2"){
			$('.totalEarnings').append('<span class="earnings" style="width:80%; height:25px; float:left;">'+earnings.name+'</span>'+
									'<span class="earningAmt" style="float:right; width:20%; text-align:right;">'+parseFloat(earnings.totalamount).toFixed(2)+'</span>');
			
			$('.totalEarnings').append('<input type="hidden" value='+parseFloat(earnings.totalamount).toFixed(2)+' name="deductionAmt[]">');
			$('.totalEarnings').append('<input type="hidden" value='+parseFloat(earnings.amount).toFixed(2)+' name="deductionPrice[]">');
			$('.totalEarnings').append('<input type="hidden" value='+earnings.unit+' name="deductionUnit[]">');
			$('.totalEarnings').append('<input type="hidden" value='+earnings.deduction_id+' name="deductionId[]">');
			
			
			totalEarnings +=parseFloat(earnings.totalamount);
			
		}else{
			
			if(earnings.totalamount !==null){
				totalContribution +=parseFloat(earnings.totalamount);
			}
			
			$('.totalEarnings').append('<input type="hidden" value='+parseFloat(earnings.totalamount).toFixed(2)+' name="deductionAmt[]">');
			$('.totalEarnings').append('<input type="hidden" value='+parseFloat(earnings.amount).toFixed(2)+' name="deductionPrice[]">');
			$('.totalEarnings').append('<input type="hidden" value='+earnings.unit+' name="deductionUnit[]">');
			$('.totalEarnings').append('<input type="hidden" value='+earnings.deduction_id+' name="deductionId[]">');
		}
		
		if(earnings.lossofpay > 0){
			$('.totalDeductions').append('<span class="earnings" style="width:80%; height:25px; float:left;">Leave</span>'+
									'<span class="deductionAmt" style="float:right; width:20%; text-align:right;">'+parseFloat(deductionLeaves).toFixed(2)+'</span>');
			
			$('.totalDeductions').append('<input type="hidden" value='+parseFloat(deductionLeaves).toFixed(2)+' name="leave_deduction">');
			
			
		totalDeduction +=parseFloat(deductionLeaves);
		}
		
		
			$('.totalEarningsAmount').html((parseFloat(totalEarnings)+parseFloat(earnings.emp_basic_pay)).toFixed(2));
			$('.totalDeductionAmount').html(totalDeduction.toFixed(2));
			$('.totalContribution').html(totalContribution.toFixed(2));
			
		$('.netPayable').html((parseFloat(totalEarnings)+parseFloat(earnings.emp_basic_pay)-totalDeduction).toFixed(2));
		$('.netPayable').append('<input type="hidden" value='+(parseFloat(totalEarnings)+parseFloat(earnings.emp_basic_pay)-totalDeduction).toFixed(2)+' name="total_payable">');
		
		
		if(earnings.status == 'paid'){
			$('.payCurrentSalary').val('Salary Paid');
			$('.payCurrentSalary').removeClass('payCurrentSalary');	
			$('.printPaySlip').css({"display":"block","float":"left"});
		}
		
//	}
		});
		//alert("Slow ?");
		
		
		     var joindate = new Date(joindate);
			 var lastdateofmth = new Date(lastDay);

			if(joindate > lastdateofmth){
	
				$('.payCurrentSalary').val('Employee Joined Date is Greater');
				$('.payCurrentSalary').attr('class','color-button');
			}
		
		
		
		
		$('.paySlip').show('blind',500,function(){
			if($('.paySlipForm').length > 1){
				$('.paySlipForm:first').remove();
			}										
		});
		
		$('.paymentmonth').getmonths(paymentmonth);
		$('.paymentyear').getYears(paymentyear);
	});
}
//////////////////////////////////////////////////////////// Leave Management /////////////////////////////////////////////////////////////////////

function leaveManagement(){
	$(".memsrch").css("display", "none");
	$(".paysalsearch").css("display", "none");
	$(".calsrch").css("display", "none");
	$('.header').show('blind',500);
	removeCurrentPage();
	$.getJSON(hrURL + "manageLeaves.php?act=list",function(data){
		var leaves = data.leaves;
			$('#tablelist').append('<table width="100%" border="0" cellspacing="0" style="display:none" cellpadding="0" class="list-leaves">'+
										  '<tr>'+
											'<td width="23%"><translate>Title</translate></td>'+
											'<td width="45%"><translate>Description</translate></td>'+
											'<td width="9%"><translate>Days</translate></td>'+
											'<td width="6%"><translate>Edit</translate></td>'+
											'<td width="5%"><img src="images/icon-add.png" class="addNewLeaves" width="20" height="20" /></td>'+
										 '</tr>'+
										'</table>')	

			$.each(leaves, function(index,leaves){
				
				var based_on='';
				switch(leaves.based_on){
					case "1":based_on="Month";break;
					case "2":based_on = "Year";break;
				}
				
					$('.list-leaves').append( '<tr>'+
														'<td width="23%">'+leaves.title+'</td>'+
														'<td width="45%">'+leaves.description+'</td>'+
														'<td width="9%">'+leaves.number_of_days+' Days / '+based_on+'</td>'+
														'<td width="6%"><img data-id="'+leaves.lid+'" src="'+editIcon+'" class="editLeave"/></td>'+
														'<td width="5%"><img data-id="'+leaves.lid+'" src="'+removeIcon+'" class="removeLeave"/></td>'+
													 '</tr>');				
			});
			$('.list-leaves').show('blind',500);
		
	});	
}

function addNewLeaves(){
	//alert('asd');
	 $('.newLeaveform').remove();
	$('.list-leaves').before('<form class="newLeaveform"><table width="50%" border="0" style="display:none" cellspacing="0" cellpadding="0" class="newLeave">'+
								  '<tr>'+
									'<td width="47%">&nbsp;</td>'+
									'<td width="53%">&nbsp;</td>'+
								  '</tr>'+
								  '<tr>'+
									'<td><translate>Title</translate></td>'+
									'<td><input type="text" name="leaveTitle" id="leaveTitle" /></td>'+
								  '</tr>'+
								  '<tr>'+
									'<td><translate>Description</translate></td>'+
									'<td><textarea name="leaveDescription" id="leaveDescription" cols="45" rows="4"></textarea></td>'+
								  '</tr>'+
								  '<tr>'+
									'<td><translate>Days</translate></td>'+
									'<td><input type="text" name="days" id="days" placeholder="Days" /> /'+
									  '<select name="based_on" id="based_on"> '+
										'<option value="1">Month</option>'+
										'<option value="2">Year</option>'+
									  '</select>'+
									  '</td>'+
								  '</tr>'+

								  '<tr>'+
									'<td>&nbsp;</td>'+
									'<td><input type="button" name="button" class="color-button saveLeave" id="button" value="Submit" />'+
									'<input type="button" name="button" class="color-button cancelNewLeave" id="button" value="Cancel" /></td>'+
								  '</tr>'+
								  '<tr>'+
									'<td>&nbsp;</td>'+
									'<td>&nbsp;</td>'+
								  '</tr>'+
								'</table></form>');
	$('.newLeave').show('blind',500);
}
function saveLeave(){	
	dataString = $('.newLeaveform').serialize();
	$.post( hrURL+ "manageLeaves.php?act=insert",dataString,function(data){
		var leaves = data.leaves
		var based_on='';
				switch(leaves.based_on){
					case "1":based_on="Month";break;
					case "2":based_on = "Year";break;
				}
				
			$('.list-leaves').append( '<tr>'+
									'<td width="23%">'+leaves.title+'</td>'+
									'<td width="45%">'+leaves.description+'</td>'+
									'<td width="9%">'+leaves.number_of_days+' Days / '+based_on+'</td>'+
									'<td width="6%"><img data-id="'+leaves.lid+'" src="'+editIcon+'" class="editLeave"/></td>'+
									'<td width="5%"><img data-id="'+leaves.id+'" src="'+removeIcon+'" class="removeLeave"/></td>'+
									'</tr>');	
			$('.newLeaveform').hide('blind',500,function(){ $(this).remove(); });
		
	},'json');
}


function removeLeaveType(){
	$this = $(this);
	var lid = $(this).attr('data-id');
	$.get(hrURL +"manageLeaves.php?act=remove&lid="+lid,function(){
		$this.parent().parent().remove();															 
	});
	
}

function editLeave(){
    $('.newLeaveform').remove();
	var lid = $(this).attr('data-id');
	//alert(lid);
	$.getJSON(hrURL + "manageLeaves.php?act=getleavebyId&lid="+lid,function(data){
		var leaves = data.editleaves;
		$.each(leaves, function(index,leaves){ 
								if(leaves.based_on=='1')
								var m_sel ="selected";
								else
								var m_sel ="";
								
								if(leaves.based_on=='2')
								var y_sel ="selected";
								else
								var y_sel ="";
			$('.list-leaves').before('<form class="newLeaveform"><table width="50%" border="0" style="display:none" cellspacing="0" cellpadding="0" class="newLeave">'+
							  '<tr>'+
								'<td width="47%">&nbsp;</td>'+
								'<td width="53%">&nbsp;</td>'+
							  '</tr>'+
							  '<tr>'+
								'<td><translate>Title</translate></td>'+
								'<td><input type="text" name="leaveTitle" id="leaveTitle" value="'+leaves.title+'" /></td>'+
							  '</tr>'+
							  '<tr>'+
								'<td><translate>Description</translate></td>'+
								'<td><textarea name="leaveDescription" id="leaveDescription" cols="45" rows="4">'+leaves.description+'</textarea></td>'+
							  '</tr>'+
							  '<tr>'+
								'<td><translate>Days</translate></td>'+
								'<td><input type="text" name="days" id="days" placeholder="Days" value="'+leaves.number_of_days+'" /> /'+
								  '<select name="based_on" id="based_on"> '+
									'<option value="1" '+m_sel+'>Month</option>'+
									'<option value="2" '+y_sel+'>Year</option>'+
								  '</select>'+
								  '</td>'+
							  '</tr>'+

							  '<tr>'+
								'<td>&nbsp;</td>'+
								'<td><input type="button" name="button" class="color-button updateLeave" id="button" value="Submit" />'+
								'<input type="hidden" name="lid" class="color-button updateLeave" id="lid" value="'+leaves.lid+'" />'+
								'<input type="button" name="button" class="color-button cancelNewLeave" id="button" value="Cancel" /></td>'+
							  '</tr>'+
							  '<tr>'+
								'<td>&nbsp;</td>'+
								'<td>&nbsp;</td>'+
							  '</tr>'+
							'</table></form>');
		});
		$('.newLeave').show('blind',500);
	});
	
}
function updateLeave(){	
	dataString = $('.newLeaveform').serialize();
	$.post( hrURL+ "manageLeaves.php?act=updateleave",dataString,function(data){
	
	},'json'); 
	$('#tablelist').html('');
	$.getJSON(hrURL + "manageLeaves.php?act=list",function(data){
		var leaves = data.leaves;
			$('#tablelist').append('<table width="100%" border="0" cellspacing="0" style="display:none" cellpadding="0" class="list-leaves">'+
										  '<tr>'+
											'<td width="23%"><translate>Title</translate></td>'+
											'<td width="45%"><translate>Description</translate></td>'+
											'<td width="9%"><translate>Days</translate></td>'+
											'<td width="6%"><translate>Edit</translate></td>'+
											'<td width="5%"><img src="images/icon-add.png" class="addNewLeaves" width="20" height="20" /></td>'+
										 '</tr>'+
										'</table>')	

			$.each(leaves, function(index,leaves){
				
				var based_on='';
				switch(leaves.based_on){
					case "1":based_on="Month";break;
					case "2":based_on = "Year";break;
				}
				
					$('.list-leaves').append( '<tr>'+
														'<td width="23%">'+leaves.title+'</td>'+
														'<td width="45%">'+leaves.description+'</td>'+
														'<td width="9%">'+leaves.number_of_days+' Days / '+based_on+'</td>'+
														'<td width="6%"><img data-id="'+leaves.lid+'" src="'+editIcon+'" class="editLeave"/></td>'+
														'<td width="5%"><img data-id="'+leaves.lid+'" src="'+removeIcon+'" class="removeLeave"/></td>'+
													 '</tr>');				
			});
			$('.list-leaves').show('blind',500);
		
	});	
}

Branchload();

function Branchload(){
	$.getJSON(serviceURLHR + 'branch.php?action=load',function(data){
		branch = data.branch;
		
		$.each(branch, function(index, branch) {
									 
							$('#branch2').append('<option value="'+branch.branch_id+'">'+branch.branch_name	+'</option>');
							
		});	
	});
}

function loademp_branch(branch_id)
{
	$.ajax({
		url:hrURL+"managePayrollSalary.php",
		type:"post",
		data:"act=LoadEmpBranch&branch_id="+branch_id,
		success:function(result){
			$('#imdatesupervisor2').html(result);
  		}
	});
}

function weeklyPayment()
{$('#light-pagination').hide();
	$('#tablelist').html('');
	$(".paysalsearch").css("display", "none");
	$(".calsrch").css("display", "none");
	removeCurrentPage();
	var lastPage;
	$('.header').show('blind',500);
	var designation_checklist = '';
	$('#tablelist').append('<div width="100%" align="right">'+
							   '<input type="button" name="list_weekly_salary" value="Show Weekly List" class="show_weekly_list_class btn-tab-01">'+
							   '</div>');
		
		$('#tablelist').append('<div id="masterlist">'+
							   '<form class="weekly_salary_form">'+
							   '<table width="25%" border="0" cellspacing="0" cellpadding="0">'+
							   '<tr>'+
							   '<td ><select name="mnth[]" id="parent_1" class="parent_combo" style="width:80%" >'+
									'<option value="0">Select Month</option>'+
									'<option value="1">January</option>'+
									'<option value="2">Febuary</option>'+
									'<option value="3">March</option>'+
									'<option value="4">April</option>'+
									'<option value="5">May</option>'+
									'<option value="6">June</option>'+
									'<option value="7">July</option>'+
									'<option value="8">August</option>'+
									'<option value="9">September</option>'+
									'<option value="10">October</option>'+
									'<option value="11">November</option>'+
									'<option value="12">December</option>'+
							'</select></td>'+
							'<td ><select name="years[]" id="parent_1" class="parent_combo" style="width:80%" >'+
									'<option value="2014">2014</option>'+
									'<option value="2015">2015</option>'+
									'<option value="2016">2016</option>'+
									'<option value="2017">2017</option>'+
									'<option value="2018">2018</option>'+
								'</select></td>'+
							   '</tr></table>'+
							   '<table width="100%" border="0" cellspacing="0" cellpadding="0" class="list-deduction earnings_row">'+
							   '<tr>'+
							   '<td width="20%"><translate>Earnings</translate></td>'+
							   '<td width="20%"><translate>Percentage</translate></td>'+
							   '<td width="20%"><translate>Amount</translate></td>'+
							   '<td width="20%"><input type="hidden" name="hidden_earning_row" id="hidden_earning_row" value="1">'+
							   '<input type="button" value="Add New Row" class="add_new_earning btn-tab-01"/></td>'+
							   '</tr></table></form></div>');
	$.getJSON(hrURL + "manage_earning_deduction.php?act=list_earning_type",function(data){
		var deductions = data.earningtype;
		
		/*var earning_combo = '<select name="parent[]" id="parent_1" class="parent_combo" style="width:100%" >'+
							'<option value="0">Select</option></select>';*/
		
		var earning_combo = '<select name="branch[]" id="branch2" class="weekly_branch_combo" style="width:200px;"  >'+
										'<option value="0">Branch</option></select>';
							
		/*if( deductions && deductions!==null){					
			$.each(deductions, function(index,deduction){
				earning_combo += '<option value="'+deduction.id+'">'+deduction.name+'</option>';						
			});
		}
		
		earning_combo += '<option value="newearning">Add New Earning</option>';
		earning_combo += '</select>';*/
		var parent_combo = '<select name="parent[]" id="parent_1" class="parent_combo" style="width:100%" >'+
							'<option value="0">Select</option></select>';
		$('.earnings_row').append('<tr id="earning_row_1" class="earnings_row_class">'+
							   '<td width="28%">'+earning_combo+'</td>'+
							   '<td width="10%"><select name="memberid[]" id="imdatesupervisor2" class="weekly_member_combo" style="width:100px;" >'+
    									'<option value="">Member</option></select></td>'+											
							   '<td width="10%" colspan="2"><input type="text" name="amount_value[]" class="max-amount" id="amount_1" style="width:100px;height:30px;" /><input type="hidden" name="mul_earn_parent_value[]" class="mul_earn_parent_class" id="mul_earn_parent_value" value="" style="width:100px;height:30px;" /></td>'+
							   '</tr>');
		
		$('.sal_structure_form').append('<div class="deduction_list_table"><table class="DeductionList" style="width:100%;"></table></div>');
		$('.weekly_branch_combo').on('change', function() {
			 var branch_id=$(this).val();
			 var x = $(this).closest('tr').find('.weekly_member_combo');
			  $.ajax({
			url:hrURL+"managePayrollSalary.php",
			type:"post",
			data:"act=LoadEmpBranch&branch_id="+branch_id,
			success:function(result){
				//alert(result);
				x.html(result);
			}
		});
		  
		});
		
		$('#tablelist').append('<input type="button" value="Weekly Confirm" class="weekly_salary_insert btn-tab-01" style="float:left; margin-top:30px; margin-left:20px;">'+
							   '<input type="button" value="Reset" class="weekly_salary_insert btn-tab-01" style="float:left; margin-top:30px; margin-left:20px;">');
		$('.list-deduction').show('blind',500);
	
	});
	
Branchload();
	
		

}


$('.weekly_salary_insert').live('click',function(){
	
	dataString = $('.weekly_salary_form').serialize();// alert(dataString);
	
	
	//console.log(dataString);
	
	
	$.post(hrURL + "manage_weekly_salary.php?act=insert_weekly_salary",dataString,function(data){
			alert('Salary Structure Successfully Saved');
			weeklyPayment();
		},'json');
	
	
	/*if(earnings=='' || percs=='')
	{
		alert('Please Enter Atleast One Row');
	}
	else if(desigs==0 )
	{
			alert('Please Select Atleast One Designation');
	}
	else
	{
		$.post(hrURL + "manage_earning_deduction.php?act=insert_salary_structure",dataString,function(data){
			alert('Salary Structure Successfully Saved');
			salaryStructure();
		},'json');
	
	}*/
});

$('.show_weekly_list_class').live('click',function(){
	$('#tablelist').html('');
	$('#tablelist').append('<div style="width:100%;" align="right"><input type="button" class="show_weekly_structure_list btn-tab-01" value="Back to Weekly Payment" name="list_salary"></div>');
	$('#tablelist').append('<table width="100%" border="0" cellspacing="0" cellpadding="0" class="list-employees">'+
	'<tr><td width="20%"><translate>Employee</translate></td>'+
	'<td width="20%"><translate>Branch</translate></td>'+
	'<td width="10%"><translate>Month</translate></td>'+
	'<td width="10%"><translate>Year</translate></td>'+	
	'<td width="10%"><translate>Amount</translate></td>'+
	'<td width="20%"><translate>Paid Date</translate></td>'+
	'</tr>');											
	$.getJSON(hrURL + "manage_weekly_salary.php?act=weekly_salary_list",function(data){
		var weekly = data.weeklysalary	
		var list_cntr = 1;
		$.each(weekly, function(i,weekly){
									
			$('.list-employees').append('<tr>'+
												'<td width="15%">'+weekly.e_fname+'</td>'+
												'<td width="10%">'+weekly.branch_name+'</td>'+
												'<td width="5%">'+weekly.MONTHNAME+'</td>'+
												'<td width="10%">'+weekly.paid_year+'</td>'+
												'<td width="5%">'+weekly.amount+'</td>'+
												'<td width="36%">'+weekly.add_date+'</td>'+
											 '</tr>');								
									
									});
		
	});
	$('.list-employees').append('</table>');
})


$('.show_weekly_structure_list').live('click',function(){
												
	weeklyPayment();
	//weeklyPayment();
});

/////subha gratuity management///////


function gratuity()
{ 
	$('#light-pagination').hide();
	$(".memsrch").css("display", "none");
	$(".paysalsearch").css("display", "none");
	$(".calsrch").css("display", "none");
	$('.header').show('blind',500);
	
		$('#tablelist').html('');


	//$(".calsrch").css("display", "none");
	$('#search_month,#search_year').css("display", "none");
	
	removeCurrentPage();
		var dt = new Date();//alert(dt);

var yrdd=dt.getFullYear();
var res_dat=yrdd+'-'+'12-31';
var minutes = 1000*60;
    		var hours = minutes*60;
    		var days = hours*24;

    	var oneDay = 24*60*60*1000;    // hours*minutes*seconds*milliseconds
   
    var R_secondDate = new Date(yrdd,12,31);
 



var amnt=0;
	k=1;
	$.getJSON(hrURL + "managegratutity.php?act=lists",function(data){
		var grats = data.grats;
			$('#tablelist').append('<table width="100%" border="0" cellspacing="0" style="display:none" cellpadding="0" class="list-leaves">'+
										  '<tr>'+
										  '<td width=""><translate>Sl No</translate></td>'+
											'<td width=""><translate>Name</translate></td>'+
											'<td width=""><translate>Date Of Join</translate></td>'+
											'<td width=""><translate>Resigned Date</translate></td>'+
											'<td width=""><translate>Days Wrkd</translate></td>'+
											'<td width=""><translate>LOP</translate></td>'+
											'<td width=""><translate>Total Day</translate></td>'+
											'<td width=""><translate>Total Year</translate></td>'+
											'<td width=""><translate>Basic/Year</translate></td>'+
											'<td width=""><translate>Basic/Day</translate></td>'+
											'<td width=""><translate>Gratuity Day</translate></td>'+
											'<td width=""><translate>Tot.Gratuity</translate></td>'+
											/*'<td width="15%"><img src="images/icon-add.png" class="addNewgratuityss" onclick="addNewgratuity();" width="20" height="20" /></td>'+*/
										 '</tr>'+
										'</table>')	;
var tot_amnt=0;
			$.each(grats, function(index,grats){
                    
					if(grats.user_id==1)
					{ 
					 var classes='resi_dat';
					}
					else
					{   if(grats.edit_riht==0)
					    {
						var classes='resi_dat_right';
						}
						else
						{
						var classes='resi_dat';
						}
					}
					
					var jdt=grats.date_join;
					var jdt = new Date(jdt);
					var jdts_Y=jdt.getFullYear(); 
					var jdts_M = jdt.getMonth();
					var jdts_D = jdt.getDate();
					var J_firstDate = new Date(jdts_Y,jdts_M,jdts_D);
				    var diffDays = Math.round(Math.abs((J_firstDate.getTime() - R_secondDate.getTime())/(oneDay)));
					if(diffDays > 0)
					{
						var diffDays=diffDays;
					}else{var diffDays=0;}
					
					$('.list-leaves').append( '<tr id="row_grat'+k+'">'+
											 '<td width="" >'+k+'</td>'+
														'<td width="">'+grats.e_fname+'</td>'+
														'<td width="">'+grats.date_join+'</td>'+
'<td width="" id="resi'+k+'"><input type="text" name="resi_dat'+k+'" id="resi_dat'+k+'" value="'+grats.resig_dat+'" style="border:0px;" readonly  class="'+classes+'" onchange="get_grta_date(this,'+grats.e_id+','+k+','+grats.tot_amnt_emp+')"/>'+'</td>'+
											'<td width="" id="dyas_wrkd'+k+'">'+grats.datjoin_resi_work+'</td>'+
											'<td width="" id="lop'+k+'">'+grats.lop_day+'</td>'+
											'<td width="" id="totalday'+k+'">'+grats.total_work_dys+'</td>'+
											'<td width="" id="totalyr'+k+'">'+parseFloat(grats.total_work_yr).toFixed(1)+'</td>'+
											'<td width="" id="basicyr'+k+'">'+parseFloat(grats.basic_per_yr).toFixed(2)+'</td>'+
											'<td width="" id="basicday'+k+'">'+parseFloat(grats.basic_per_day).toFixed(2)+'</td>'+
												'<td width="" id="gratMastday'+k+'">'+grats.num_days+'</td>'+
												'<td width="" id="totgrat'+k+'">'+parseFloat(grats.grat_amnt).toFixed(2)+'</td>'+
											
														//'<td width="6%"><img data-id="'+grats.id+'" src="'+editIcon+'" class="editgrats" onclick="editgrat();"/></td>'+
														//'<td width="15%"><img data-id="'+grats.e_id+'" src="'+removeIcon+'" class="removeLeave"/></td>'+
													 '</tr>');	
					var amnt=grats.tot_amnt_emp; 
					
				 tot_amnt=parseFloat(grats.grat_amnt)+parseFloat(tot_amnt);//alert(tot_amnt);
					           if(k==grats.num_row_emp)
							   {
								   	$('.list-leaves').append( '<tr>'+'<td width="" colspan="11" align="right" >Total</td>'+
											 '<td width=""  align="left" id="final_tot"><font color="red"><b>'+parseFloat(tot_amnt).toFixed(2)+'</b></font>&nbsp;</td>'+
													
													 '</tr>');	
							   }
			k++;});
			
				
			$('.list-leaves').show('blind',500);
		
	});	
}

function get_grta_date(obj,eid,k,amnt)
{
	var dats=obj.value;
	var tots=document.getElementById("totgrat"+k).innerHTML;
	
	
		$.post( hrURL+ 'grat_add.php?act=insert&dat='+dats+'&emp='+eid,'',function(data){
				var grats = data.grats;
					$.each(grats, function(index,grats){
					var grand_tots=Number(amnt)-Number(tots);
					var currentUser = $('#row_grat'+k);
					currentUser.find('#dyas_wrkd'+k).text(grats.datjoin_resi_work);
					currentUser.find('#lop'+k).text(grats.lop_day);
					currentUser.find('#totalday'+k).text(grats.datjoin_resi_work);
					currentUser.find('#totalyr'+k).text(parseFloat(grats.total_work_yr).toFixed(1));
					currentUser.find('#basicyr'+k).text(parseFloat(grats.basic_per_yr).toFixed(2));
					currentUser.find('#basicday'+k).text(parseFloat(grats.basic_per_day).toFixed(2));
					currentUser.find('#gratMastday'+k).text(grats.num_days);
					currentUser.find('#totgrat'+k).text(parseFloat(grats.grat_amnt).toFixed(2));
					var grand_tots=grand_tots+grats.grat_amnt;
				    document.getElementById("final_tot").style.color="red";
					document.getElementById("final_tot").style.fontWeight = 'bold';
					document.getElementById("final_tot").innerHTML=parseFloat(grand_tots).toFixed(2);
										   });
		/*	$('.list-leaves').append( '<tr class="reportime_'+timing.id+'">'+
															'<td width="15%">'+k+'</td>'+
															 '<td width="15%">'+timing.emply_stat+'</td>'+
						'<td width="5%"><img data-id="'+timing.id+'" src="'+editIconpen+'" class="editstatus"/></td>'+
					'<td width="5%"><img data-id="'+timing.id+'" src="'+removeIcon+'" class="removestatus"/></td>'+
														 '</tr>');*/
				
		},'json');
		
		
}

function loademployeelist(){ 
	
	$.getJSON(serviceURLHR + 'employeename_list.php?action=load_st',function(data){
		empnamelist = data.empnamelist;	
		$.each(empnamelist, function(index, empnamelist) {									 
							$('#empname').append('<option value="'+empnamelist.e_id+'">'+empnamelist.e_fname+'</option>');
							
		});	
	});
}

function addNewgratuity(){
	loademployeelist();
	//alert('asd');
	$('.newgratform').remove();
	$('.list-leaves').before('<form class="newgratform"><table width="100%" border="0" style="display:none" cellspacing="1" cellpadding="1" class="list-leavesg">'+
								  '<tr>'+
									'<td colspan="4" align="center" bgcolor="#003366" style="color:#FFFFFF">End Of Service Calculation</td>'+
								  '</tr>'+
								  '<tr>'+
									'<td width="25%"><translate>Employee Name</translate></td>'+
									'<td width="25%"><select name="empname" id="empname"><option selected="selected" value="">---select---</option></select></td>'+
								 
									'<td width="25%"><translate>Employee Id</translate></td>'+
									'<td width="25%"><input type="text" name="empid" id="empid" readonly/></td>'+
								  '</tr>'+
								  	  '<tr>'+
									'<td width="25%"><translate>Joining Date</translate></td>'+
									'<td width="25%"><input type="text" name="jdate" id="jdate" readonly /></td>'+
								 
									'<td width="25%"><translate>Resigning Date</translate></td>'+
									'<td width="25%"><input type="text" name="rdate" id="rdate" class="rdate" /></td>'+
								  '</tr>'+
								  		  	  '<tr>'+
									'<td width="25%"><translate>Department</translate></td>'+
									'<td width="25%"><input type="text" name="depart" id="depart" readonly/></td>'+
								 
									'<td width="25%"><translate>Designation</translate></td>'+
									'<td width="25%"><input type="text" name="desigs" id="desigs" readonly /></td>'+
								  '</tr>'+
								
 	  '<tr>'+
									'<td width="25%"><translate>Satus Of Employee</translate></td>'+
									'<td width="25%"><input type="text" name="estats" id="estats" readonly /><input type="hidden" name="timp" id="timp" value=""></td>'+
								 
									'<td width="25%"><translate>Basic Salary</translate></td>'+
									'<td width="25%"><input type="text" name="bsal" id="bsal" readonly/><input type="hidden" name="numdayss" id="numdayss" value=""></td>'+
								  '</tr>'+
								    '<tr>'+
									'<td width="25%"><translate>Amount</translate></td>'+
									'<td width="25%"><input type="text" name="amounts" id="amounts" readonly /></td>'+
								 
									'<td width="25%"><translate>Deduction Amount</translate></td>'+
									'<td width="25%"><input type="text" name="damount" id="damount" /></td>'+
								  '</tr>'+
								     '<tr>'+
									'<td width="25%"><translate>Net Amount</translate></td>'+
									'<td width="25%"><input type="text" name="netamnt" id="netamnt" readonly /></td>'+
								 
									'<td width="25%"><translate>Remark</translate></td>'+
									'<td width="25%"><textarea name="remarks" id="remarks" cols="45" rows="4"></textarea></td>'+
								  '</tr>'+
								  '<tr>'+
									'<td colspan="4" align="center"><input type="button" name="button" class="color-button savgrat" onclick="savgrat();" id="button" value="Submit" />'+
									'<input type="button" name="button" class="color-button cancelNewLeave" id="button" value="Cancel" /></td>'+
								  '</tr>'+
								  '<tr>'+
									'<td colspan="4" align="center">&nbsp;</td>'+
									
								  '</tr>'+
								'</table></form>');
	
	$('.list-leavesg').show('blind',500);
	$('.rdate').datepicker({dateFormat:"dd-mm-yy"});

}

function get_employee()
{
	var emp=$('#empname').val(); 
	if(emp==''){
				$('#jdate').val('');
				$('#empid').val('');
				$('#depart').val('');
				$('#desigs').val('');
				$('#bsal').val('');
				$('#estats').val('');
				$('#timp').val('');
				$('#numdayss').val('');
	}
	$.getJSON(serviceURLHR + "branch.php?act=emp&empid="+emp,function(data){
		var users = data.users; 
				 $.each(users, function(index, users) 
		   { 
			  	//alert(users.date_join+'dfd');
				$('#jdate').val(users.date_join);
				$('#empid').val(users.e_id);
				$('#depart').val(users.depart_name);
				$('#desigs').val(users.desig_name);
				$('#bsal').val(users.emp_basic_pay);
				$('#estats').val(users.emply_stat);
				$('#timp').val(users.time_period);
				$('#numdayss').val(users.num_days);
				
				
				//grat_calculate(users.emp_basic_pay);
				
				
		   });
		});
	
}
function chkdat()
{
	
	var emp=$('#empname').val(); 
	if(emp=='')
	{
		alert("Please Select Employee Name");
		$('#rdate').val('');
	}
	
		var rdates=$('#rdate').val();
	var jdat=$('#jdate').val();
	  var a = rdates;
      var b = jdat; 
	  
            var str2 = rdates;
            var str4 = jdat;
            var ONE_DAY = 1000 * 60 * 60 * 24; 
            var dt2 = parseInt(str2.substring(0, 2), 10);
            var mon2 = parseInt(str2.substring(3, 5), 10);
            var yr2 = parseInt(str2.substring(6, 10), 10);
            var dt4 = parseInt(str4.substring(0, 2), 10);
            var mon4 = parseInt(str4.substring(3, 5), 10);
            var yr4 = parseInt(str4.substring(6, 10), 10);
			var date2 = new Date(yr2, mon2 - 1, dt2);
            var date4 = new Date(yr4, mon4 - 1, dt4);
			var date2_ms = date2.getTime();
            var date4_ms = date4.getTime();
            var difference_ms = Math.abs(date2_ms - date4_ms);
            var y = Math.round(difference_ms / ONE_DAY);
			
			var totalYears = Math.floor(y / 365);
            var totalYearss = Math.abs(y / 365);
		   var totalMonths = Math.floor((y % 365) / 30);
		   
		 var totalYearss=totalYearss.toFixed(2);
			
           // var date2_ms = date2.getTime();

      if (parseFloat(a) < parseFloat(b))
	  {
        var dat=1;  // less than
		
	  }
      else if (parseFloat(a) == parseFloat(b))
	  {
        var dat=1;   // equal
		
	  }
      else if (parseFloat(a) > parseFloat(b))
	  {
        var dat=0;  // greater than
		
	  }
      else
	  {
         var dat=0;   // error
	  }
	
/*	if(dat==1)
	{
		alert("Resigning date should be Greater Than Joining Date");
		$('#rdate').val('');
	}
	*/
	var period=$('#timp').val();
	var numdys=$('#numdayss').val();
	var bsals=$('#bsal').val();
	var grats=0;//alert(totalYears);alert(period);
/*	if(Number(totalYears) >= Number(period) && Number(period)!=5)
	{
		var grats=(Number(bsals)*totalYearss*Number(numdys))/30;
	}
	else if(Number(totalYears) <= Number(period) && Number(period)!=5)
	{*/
		var grats=(Number(bsals)*totalYearss*Number(numdys))/30;
		var grats=grats.toFixed(2);
/*	}
	else
	{
	}*/
	
	$('#amounts').val(grats);
	$('#netamnt').val(grats);
	
}

function deduct()
{
	var dedct=$('#damount').val();
	//alert(dedct);
	if(isNaN(dedct))
	{
		$('#damount').val('');
	}
	else
	{
	var amnt=$('#amounts').val();
	var ntamnt=Number(amnt)-Number(dedct);//alert(ntamnt);
		var ntamnt=ntamnt.toFixed(2);
	$('#netamnt').val(ntamnt);

	}
	
	
}
function deduct_round()
{
		var dedct=$('#damount').val();
		$('#damount').val(dedct+'.00');
}

function savgrat()
{
		//var employeeid =$('#employeesList').val();
	var dataString = $('.newgratform').serialize();alert(dataString);
	
	$.post(serviceURLHR + "managegratutity.php?act=newgrat",dataString,function(){
		$('.newgratform').hide('blind',300,function(){ $(this).remove()});
		
	});
}
///////////////////////////////////////////// Leave request management //////////////////////////////////////////////

function leaveRequests(){
	$('.header').show('blind',500);
	removeCurrentPage();
	$('#tablelist').append('<table width="100%" border="0" cellspacing="0" style="display:none" cellpadding="0" class="list-leaverequests">'+
										  '<tr>'+
											'<td width="15%"><translate>Employee</translate></td>'+
											'<td width="15%"><translate>Designation</translate></td>'+
											'<td width="10%"><translate>Leave From</translate></td>'+
											'<td width="10%"><translate>Leave To</translate></td>'+
											'<td width="12%"><translate>Leave Type</translate></td>'+
											'<td width="36%"><translate>Reason</translate></td>'+
											'<td width="6%"><translate>Status</translate></td>'+
											'<td width="6%"><img src="images/icon-add.png" class="addNewLeaveRequest" width="20" height="20" /></td>'+
										 '</tr>'+
										'</table>')	;
	$.getJSON(hrURL + "manageLeaves.php?act=loadRequests",function(data){
		var leaves = data.leaves;
		
		
		
			$.each(leaves,function(index,leaves){
								   
		var status;
		if(leaves.status == 1){
			status ='<img src="images/1388407735_delete_64.png" style="cursor:pointer" data-status="0" requestid="'+leaves.id+'" class="approveLeave" width="20" height="20" />';
		}else{
			status ='<img src="images/1388406658_ok-green.png" style="cursor:pointer" data-status="1" requestid="'+leaves.id+'" class="approveLeave" width="20" height="20" />';
		}				   
								   
				
				$('.list-leaverequests').append('<tr>'+
												'<td width="15%">'+leaves.e_fname+'</td>'+
												'<td width="15%">'+leaves.e_post+'</td>'+
												'<td width="10%">'+leaves.day_from+'</td>'+
												'<td width="10%">'+leaves.day_to+'</td>'+
												'<td width="12%">'+leaves.title+'</td>'+
												'<td width="36%">'+leaves.reason+'</td>'+
												'<td width="6%">'+status+'</td>'+
												'<td width="6%"><img src="images/icon-add.png" class="addNewDeduction" width="20" height="20" /></td>'+
											 '</tr>');									   
			});
			$('.list-leaverequests').show('blind',500);
	});
	
	
	
}

function newLeaveRequest(){

$('.list-leaverequests').before('<div class="newLeaveApplicationWindow" style="display:none">'+
					 '<form class="newLeaveApplicationForm"><table width="500" height="200" border="0" cellpadding="0" cellspacing="0">'+
					  '<tr>'+
						'<td width="217">&nbsp;</td>'+
						'<td width="304"></td>'+
					  '</tr>'+
					  '<tr>'+
						'<td class="categories"><translate>Employee</translate></td>'+
						'<td><select name="employees" id="employeesList">'+
						'</select> </td>'+
					  '</tr>'+
					  '<tr>'+
						'<td class="categories"><translate>Leave From</translate></td>'+
						'<td><input type="text" name="day_from" id="day_from" class="my_date" /></td>'+
					  '</tr>'+
					  '<tr>'+
						'<td class="categories"><translate>Leave To</translate></td>'+
						'<td><input type="text" name="day_to" id="day_to" class="my_date" /></td>'+
					  '</tr>'+
					  '<tr>'+
						'<td class="categories"><translate>Leave Type</translate></td>'+
						'<td><select name="leave_id" id="leaveList">'+
						'</select>    </td>'+
					  '</tr>'+
					  '<tr>'+
						'<td class="categories"><translate>Reason</translate></td>'+
						'<td><textarea name="reason" id="reason" cols="45" rows="5"></textarea></td>'+
					  '</tr>'+
					  '<tr>'+
						'<td class="categories">&nbsp;</td>'+
						'<td><input type="button" name="button" id="applyLeave" class="color-button2 applyLeave" value="Submit" />'+
						'<input type="button" name="button" id="cencelApplication" class="color-button2 cencelApplication" value="Cancel" /></td>'+
					  '</tr>'+
					'</table></form></div>');
			$('#employeesList').getEmployees();
			
			setTimeout(function(){ $('#leaveList').loadLeaves(); } , 150);
			
$('.newLeaveApplicationWindow').show('blind',500);
}

function saveLeaveRequest(){
	var $this = $(this);
	var employeeid =$('#employeesList').val();
	var dataString = $('.newLeaveApplicationForm').serialize();
	
	$.post(serviceURLHR + "manageLeaves.php?act=newRequest&emp_id="+employeeid,dataString,function(){
		$('.newLeaveApplicationWindow').hide('blind',300,function(){ $(this).remove()});
		
	});
	
}


function changeRequestStatus(){
		var $this = $(this);
		var newStatus	 = $this.attr('data-status');
		var requestid	= $this.attr('requestid');
		$.get(hrURL + "manageLeaves.php?act=changeStatus&reqid="+requestid+"&set="+newStatus,function(){
				
				if(newStatus == 1){
					$this.attr({'src':'images/1388407735_delete_64.png','data-status':'0'});
				}else{
					$this.attr({'src':'images/1388406658_ok-green.png','data-status':'1'});
				}
				
				
				
		});
		
	
}



////////////////////////////////////////////////  PAY SALARY ////////////////////////////////////////////

function salaryPayment(){

if($('.paymentMethod').length){
	
}else{
	$(".paySlipForm").append('<div class="paymentMethod" style="display:none">'+
					 '<table width="500" height="200" border="0" cellpadding="0" cellspacing="0">'+
					  '<tr>'+
						'<td width="217">&nbsp;</td>'+
						'<td width="304">&nbsp;</td>'+
					  '</tr>'+
					  '<tr>'+
						'<td>&nbsp;</td>'+
						'<td>&nbsp;</td>'+
					  '</tr>'+
					  '<tr>'+
						'<td class="paymentmethod"><translate>Payment Method</translate></td>'+
						'<td>'+
						'<select name="paymentThrough" class="paymentThrough">'+
						'</select'+
						'</td>'+
					  '</tr>'+
					  '<tr>'+
						'<td class="referance_label"><translate>Referance</translate></td>'+
						'<td><input type="text" name="referance" id="referance" class="referance" /></td>'+
					  '</tr>'+

					  '<tr>'+
						'<td class="categories">&nbsp;</td>'+
						'<td><input type="button" name="button" id="submitSalary" class="color-button2" value="Submit" />'+
						'<input type="button" name="button" id="cancelPayment" class="color-button2" value="Cancel" /></td>'+
					  '</tr>'+
					'</table></div>');
	$('.paymentMethod').center();
	$('.paymentThrough').paymentMethods();
	
	$('.paymentMethod').show('fade',300);
}
	
}

function submitSalary(){
	var $this = $(this);
	var dataString = $('.paySlipForm').serialize();
	$.post(serviceURLHR + "manageSalary.php?act=paySal",dataString,function(){
																			
		$('.payCurrentSalary').val('Salary Paid');
		$('.payCurrentSalary').removeClass('payCurrentSalary');
		$('.printPaySlip').css({"display":"block","float":"left"});
		
		$('.paymentMethod').hide('fade',300,function(){ $(this).remove(); })
	});
}


function printPaySlip(){
	
	$('.paymentSummery').append(  '<tr class="setHt">'+
                                    '<td width="50%" height="250"></td>'+
                                    '<td></td>'+
                                  '</tr>'+
								  
								  '<tr class="signature">'+
                                    '<td width="50%" height="150"><translate>Employer\'s Signature</translate></td>'+
                                    '<td align="right"><translate>Employee\'s Signature</translate></td>'+
                                  '</tr>');
	
	$('.color-button').css('display','none');

	$('.paySlip').print();
	$('.color-button').css('display','block');
	$('.signature').remove();
	$('.setHt').remove();
	
};




$('.my_date').live('click',function(){
		 $(this).datepicker({dateFormat:"dd-mm-yy"}).focus();	
	});

///////////////////////// getLeaveList to ListBox ///////////////////////////////////////////////////

jQuery.fn.loadLeaves = function getLeaveList(){
	$this =this;
	$('#leaveList').html('');
	var employeeid = $('#employeesList').val();
	$.getJSON(	serviceURLHR +"manageLeaves.php?act=getLeaves&emp_id="+employeeid,function(data){
		var leaves = data.leaves;
		$.each(leaves,function(index,leaves){
			$this.append('<option value='+leaves.lid+'>'+leaves.title+'</option>');
		});
	});
}


/////////////////////// getEmployeeList ListBox//////////////////////////////////////////////////////
jQuery.fn.getEmployees = function getEmployeesList(){
	$this = this;
	$.getJSON(	serviceURLHR +"manageEmployees.php?action=employeeslist",function(data){
		var employees = data.employees;
		$.each(employees,function(index,employees){
			$this.append('<option value='+employees.e_id+'>'+employees.e_fname+'</option>');
		});
	});
}



/////////////////////// Load PaymentMethods list to select box //////////////////////////////////////
jQuery.fn.paymentMethods = function getPaymentMethodList(){
	$this = this;
	$.getJSON(	serviceURLHR +"paymentMethods.php?act=list",function(data){
		var methods = data.methods;
		$.each(methods,function(index,methods){
			$this.append('<option value='+methods.id+'>'+methods.title+'</option>');
		});
	});
}


////////////////////////////// Months list //////////////////////////////
jQuery.fn.getmonths = function setAllMunths(paymentmonth){
	$this = this;

	
	var currentMonth =paymentmonth;
	$this.html('');

var months = ["January", "February", "March", "April", "May", "June",
                  "July", "August", "September", "October", "November", "December"];

	$.each(months,function(index,months){
						   if(index<9)
						   {
		if( (parseInt(index)+1) == currentMonth){
			$this.append('<option selected="selected" value="0'+ (parseInt(index)+1) +'">'+months+'</option>');	
		}else{
			$this.append('<option value="0'+ (parseInt(index)+1) +'">'+months+'</option>');	
		}
						   }
						   else{
							   
				if( (parseInt(index)+1) == currentMonth){
			$this.append('<option selected="selected" value="'+ (parseInt(index)+1) +'">'+months+'</option>');	
		}else{
			$this.append('<option value="'+ (parseInt(index)+1) +'">'+months+'</option>');	
		}			   
							   
		}
		
	});


}

////////////////////////////// Year list //////////////////////////////
jQuery.fn.getYears = function setAllYears(paymentyear){
	$this = this;
	var currentYear =paymentyear; 
	$this.html('');


    var dt = new Date();
	var thisyear =dt.getFullYear(); 
	
	
	
	for ( i = 2013; i < (parseInt(thisyear)+1); i += 1 ) {  
		if( i == currentYear){
			$this.append('<option selected="selected" value="'+ i +'">'+i+'</option>');	
		}else{
			$this.append('<option value="'+ i +'">'+i+'</option>');	
		}
	}



}

function searchcalendar()
{
var holdybranch = $('#holidaybranch').val();

//removeCurrentPage();	
holidayCalendar(holdybranch);	

}
/////////////////////////////////////////// Holiday Calendar ////////////////////////////////////////
function holidayCalendar(holdybranch){
	
	if(holdybranch=='' || holdybranch=='undefined' || !holdybranch)
	{
		
	var holdybranch=$('.sessionbranch_id').val();
	}
	
	
	var user_type=$('#hiddenuser_type').val();	
	$(".memsrch").css("display", "none");
	$(".paysalsearch").css("display", "none");
	$(".calsrch").css("display", "block");
	removeCurrentPage();
	$("#tablelist").append('<table class="calendarHolder" style="display:none;" ><tr></td><div id="calendar"></div></td></tr></table>');
	loadholidaybranch();
	setTimeout(function(){ $('.holiday_branch').val(holdybranch); },500);
	
	
		var calendar = $('#calendar').fullCalendar({
			eventSources: [ {url:hrURL + "holidatManagement.php?act=list&branchid="+holdybranch}],
			eventDrop: function(event, delta) {
				date = new Date(event.start).format("yyyy-mm-dd");
				$.get(hrURL + "holidatManagement.php?act=update&title"+event.title+"&start="+date+"&id="+event.id+"&branchid="+holdybranch);
			},
			selectable: true,
			selectHelper: true,
			select: function(start, end, allDay) {
				if(user_type == 'Superadmin')
				{
				var title = prompt('Event Title:');
				if (title) {
					date = new Date(start).format("yyyy-mm-dd");
					$.get(hrURL + "holidatManagement.php?act=addNew&title="+title+"&start="+date+"&branchid="+holdybranch,function(){
					
					calendar.fullCalendar('renderEvent',{
							title: title,
							start: start,
							end: end,
							allDay: allDay
						},true );
					 });
				}
				calendar.fullCalendar('unselect');
				}
			},
			eventClick: function (calEvent, jsEvent, view) {       
				 if(confirm('Are you sure from removing the event?')){
					 $.get(hrURL + "holidatManagement.php?act=remove&id="+calEvent._id+"&branchid="+holdybranch)
						$('#calendar').fullCalendar('removeEvents', calEvent._id);
				 }
			},
			
			loading: function(bool) {
				if (bool) $('#loading').show();
				else $('#loading').hide();
			}
			
		});
	$('.calendarHolder').show('blind',500);
	//calendar.fullCalendar()
	
}

////////////////////////////////////////////////////////////////////  REPORTS  //////////////////////////////////////////////////////
function paymentHistory(){
	
	var selectedMth = $('.paymentHistorypaymentmonth').val();
	var selectedYear = $('.paymentHistorypaymentyear').val();
	
	if(!selectedMth){
		selectedMth = 1;
		selectedYear =2014;
	}
	
	removeCurrentPage();
	$('.header').show('blind',500);

	$("#tablelist").append('<table class="report-holder" style="display:none;">'+
						   '<tr><td>'+
						   '<select name="year" class="paymentHistorypaymentyear" data-id="">'+
									'</select>'+
									
									'<select name="month"  class="paymentHistorypaymentmonth" data-id="">'+
									'</select>'+
						   
						   '</td></tr>'+
						   '<tr><td><ul class="grandTotals">'+
							'<li class="salaryTotal"></li>'+
							'<li class="deductionTotal"></li>'+
							'<li class="earningsTotal"></li>'+
							'</ul>'+
							'<ul class="earnings">'+
							'<li class="earningsList"></li>'+
							'<li class="earningsList"></li>'+
							'<li class="earningsList"></li>'+
							'</ul>'+
'</td></tr></table>');
	
	$.getJSON(hrURL + "paymentReports.php?act=dashboard&month="+selectedMth+"&year="+selectedYear,function(data){
		
		
	if(data.dashboard.earningsList !== true)	{

	$('.salaryTotal').html('Paid Salary : '+data.dashboard.totalPaidAmt); 
	
	
	var totalDeductions=0;
	var totalEarnings=0;
	
	var deductionAndEarningsList=data.dashboard.earningsList;
	$('.earnings').html('');
		$.each(deductionAndEarningsList,function(index,deductionAndEarningsList){
				if(deductionAndEarningsList.deduction_benefit =="1"){
					if(deductionAndEarningsList.name=='PF')
					{
					$('.grandTotals').append('<li class="earningsList" ><a href="pf_listing.php" target="_blank" >'+deductionAndEarningsList.name+' : '+deductionAndEarningsList.totalDeduction+'</a></li>');	
					}
					else
					{$('.grandTotals').append('<li class="earningsList">'+deductionAndEarningsList.name+' : '+deductionAndEarningsList.totalDeduction+'</li>');	}
					
					totalDeductions += parseFloat(deductionAndEarningsList.totalDeduction);
					
				}else if(deductionAndEarningsList.deduction_benefit =="2"){
					$('.grandTotals').append('<li class="earningsList">'+deductionAndEarningsList.name+' : '+deductionAndEarningsList.totalDeduction+'</li>');	
					totalEarnings += parseFloat(deductionAndEarningsList.totalDeduction);
					
				}else{
					$('.grandTotals').append('<li class="earningsList">'+deductionAndEarningsList.name+' : '+deductionAndEarningsList.totalDeduction+'</li>');	
				}
				
				
	
				
				
		});
		$('.report-holder').show('blind',500);
		$('.deductionTotal').html('Total Deduction : '+parseFloat(totalDeductions).toFixed(2)); 	
		$('.earningsTotal').html('Total Earnings : '+parseFloat(totalEarnings).toFixed(2)); 
	
	
	}else{
		$("#tablelist").html('<table class="report-holder" style="display:none;">'+
						   '<tr><td>'+
						   '<select name="year" class="paymentHistorypaymentyear" data-id="">'+
									'</select>'+
									
									'<select name="month"  class="paymentHistorypaymentmonth" data-id="">'+
									'</select>'+
						   
						   '</td></tr>'+
						   '<tr><td>No Data found ! '+
						'</td></tr></table>');
		
		$('.report-holder').show('blind',500);
		$('.paymentHistorypaymentmonth').getmonths(selectedMth);
		$('.paymentHistorypaymentyear').getYears(selectedYear);
		
	}
	
	

		
	
		
		
	})
	
		$('.paymentHistorypaymentmonth').getmonths(selectedMth);
	$('.paymentHistorypaymentyear').getYears(selectedYear);
	
}

function test_skill(junkVal) {
   // var junkVal=document.getElementById('rupees').value;
    //junkVal=Math.floor(junkVal);
    var obStr=new String(junkVal);
    numReversed=obStr.split("");
    actnumber=numReversed.reverse();

    if(Number(junkVal) >=0){
        //do nothing
    }
    else{
        alert('wrong Number cannot be converted');
        return false;
    }
    if(Number(junkVal)==0){
		$('.amountinwords').html(obStr+''+'Rupees Zero Only'); 
       // document.getElementById('amountinwords').innerHTML=obStr+''+'Rupees Zero Only';
        return false;
    }
    if(actnumber.length>9){
        alert('Oops!!!! the Number is too big to covertes');
        return false;
    }

    var iWords=["Zero", " One", " Two", " Three", " Four", " Five", " Six", " Seven", " Eight", " Nine"];
    var ePlace=['Ten', ' Eleven', ' Twelve', ' Thirteen', ' Fourteen', ' Fifteen', ' Sixteen', ' Seventeen', ' Eighteen', ' Nineteen'];
    var tensPlace=['dummy', ' Ten', ' Twenty', ' Thirty', ' Forty', ' Fifty', ' Sixty', ' Seventy', ' Eighty', ' Ninety' ];

    var iWordsLength=numReversed.length;
    var totalWords="";
    var inWords=new Array();
    var finalWord="";
    j=0;
    for(i=0; i<iWordsLength; i++){
        switch(i)
        {
        case 0:
            if(actnumber[i]==0 || actnumber[i+1]==1 ) {
                inWords[j]='';
            }
            else {
                inWords[j]=iWords[actnumber[i]];
            }
            inWords[j]=inWords[j];
            break;
        case 1:
            tens_complication();
            break;
        case 2:
            if(actnumber[i]==0) {
                inWords[j]='';
            }
            else if(actnumber[i-1]!=0 && actnumber[i-2]!=0) {
                inWords[j]=iWords[actnumber[i]]+' Hundred and';
            }
            else {
                inWords[j]=iWords[actnumber[i]]+' Hundred';
            }
            break;
        case 3:
            if(actnumber[i]==0 || actnumber[i+1]==1) {
                inWords[j]='';
            }
            else {
                inWords[j]=iWords[actnumber[i]];
            }
            if(actnumber[i+1] != 0 || actnumber[i] > 0){
                inWords[j]=inWords[j]+" Thousand";
            }
            break;
        case 4:
            tens_complication();
            break;
        case 5:
            if(actnumber[i]==0 || actnumber[i+1]==1 ) {
                inWords[j]='';
            }
            else {
                inWords[j]=iWords[actnumber[i]];
            }
            inWords[j]=inWords[j]+" Lakh";
            break;
        case 6:
            tens_complication();
            break;
        case 7:
            if(actnumber[i]==0 || actnumber[i+1]==1 ){
                inWords[j]='';
            }
            else {
                inWords[j]=iWords[actnumber[i]];
            }
            inWords[j]=inWords[j]+" Crore";
            break;
        case 8:
            tens_complication();
            break;
        default:
            break;
        }
        j++;
    }

    function tens_complication() {
        if(actnumber[i]==0) {
            inWords[j]='';
        }
        else if(actnumber[i]==1) {
            inWords[j]=ePlace[actnumber[i-1]];
        }
        else {
            inWords[j]=tensPlace[actnumber[i]];
        }
    }
    inWords.reverse();
    for(i=0; i<inWords.length; i++) {
        finalWord+=inWords[i];
    }
        return finalWord;
    //document.getElementById('container').innerHTML=obStr+'  '+;
       
}
 
    //document.getElementById('container').innerHTML=finalWord;
 function paisa_conver(junkVal){

   junkVal = junkVal.split('.')[0];
 
        var finalWord1 = test_skill(junkVal);
    console.log(finalWord1);
    
            var finalWord2;
			
		 var val = 	$('#total_payable').val();
		 var enteredvalue = 	$('#total_payable').val();
    //var val = document.getElementById('total_payable').value;
 //var enteredvalue = document.getElementById('total_payable').value;
 
        if(val.indexOf('.')!=-1)
    {
          val = val.substring(val.indexOf('.')+1,val.length);
            if(val.length==0){
              finalWord2 = "Rupees Only.";
           }else{
            //   document.getElementById('rupees').value = val;
   paisa = enteredvalue.split('.')[1];
   //console.log(paisa);
   
   
   if(paisa){
   
             if(paisa>0){
				 finalWord2 = "Rupees and"+test_skill(paisa) + " paisa only";}
				 else{finalWord2 = "Rupees Only.";
				 }
      }else{
    finalWord2 = "Rupees Only.";
   }
    // 
           }
     
    } else{
          finalWord2 = "Rupees Only.";
    }
    //document.getElementById('amountinwords').innerHTML=finalWord1 +" "+finalWord2;
 
 $('.amountinwords').html(finalWord1 +" "+finalWord2);
 
 
}

function paidSalaryReport(){
	
	
}

function deductionAndEarningsReport(){
	
	
}

function pfRequests()
{
	window.location="pf_listing.php#pfRequests";
}
function esiRequests()
{
	window.location="pf_listing.php#esiRequests";
}

///////////////////////////////////////////////EVENT MANAGEMENT//////////////////////////////////////////
jQuery('.payCurrentSalary').live('click',salaryPayment);
jQuery('.addNewLeaves').live('click',addNewLeaves);
jQuery('.saveLeave').live('click',saveLeave);

jQuery('.weeklyPayment').live('click',weeklyPayment);

/*jQuery('.addNewDeduction').live('click',addnewDeduction);*/
jQuery('.addNewEarningDeduction').live('click',addNewEarningDeduction);

jQuery('.saveDeduction').live('click',saveNewDeduction);
jQuery('.payslip').live('click',preloadPaySlip);
jQuery('#cancelPayment').live('click',function(){ $('.paymentMethod').hide('fade',300,function(){ $(this).remove(); }) });
jQuery('#submitSalary').live('click',submitSalary);
jQuery('.paymentmonth').live('change',preloadPaySlip);
jQuery('.paymentyear').live('change',preloadPaySlip);
jQuery('.removeDeduction').live('click',removeDeduction);
jQuery('.removeLeave').live('click',removeLeaveType);
jQuery('.printPaySlip').live('click',printPaySlip);
jQuery('.gobacktolist').live('click',paySalary);
jQuery('.approveLeave').live('click',changeRequestStatus);

jQuery('.cancelDeduction').live('click',function(){ $('.newDeductionform').hide('blind',500,function(){ $(this).remove(); }) });
jQuery('.cancelNewLeave').live('click',function(){ $('.newLeaveform').hide('blind',500,function(){ $(this).remove(); }); });
jQuery('.addNewLeaveRequest').live('click',newLeaveRequest);
jQuery('#employeesList').live('change',function(){ $('#leaveList').loadLeaves(); });
jQuery('.applyLeave').live('click',saveLeaveRequest);
jQuery('.cencelApplication').live('click',function(){ $('.newLeaveApplicationWindow').hide('blind',300,function(){ $(this).remove()}); });

jQuery('.paymentHistorypaymentmonth').live('change',paymentHistory);
jQuery('.paymentHistorypaymentyear').live('change',paymentHistory);

$("#printdiv").print();

//////////////////////////////////////////////  Common popup function //////////////////////////////////


/* Salary Structure */
function addDiductions(){
	
	$(this).attr("disabled","disabled");									  
	var earning_selected_val  = '';
	$('.earning_combo').each(function(){ 
		if($(this).val()!=''){
			earning_selected_val = earning_selected_val+'<option value="'+$(this).val()+'">'+$(this).find("option:selected").text()+'</option>';
		}
	});
	
	$.getJSON(hrURL + "manage_earning_deduction.php?act=list_deduction_type",function(data){
		var deductions = data.deductionstype
		$('.DeductionList').append('<p><strong>Deduction</strong></p><table width="100%" border="0" cellspacing="0" style="display:none" cellpadding="0" class="list-deduction1  deduction_row">'+
							   '<tr>'+
							   '<td width="20%"><translate>Deduction</translate></td>'+
							   '<td width="20%"><translate>Percentage</translate></td>'+											
							   '<td width="20%"><translate>of</translate></td>'+
							   '<td width="20%"><translate>Max Amount</translate></td>'+
							   '<td width="20%"><input type="hidden" name="hidden_deduction_row" id="hidden_deduction_row" value="1"><input type="button" value="New Deduction Row" class="add_new_deduction btn-tab-01"/></td>'+
							   '</tr>'+
							   '</table>')	
		var earning_combo = '<select name="deduction[]" style="width:100%" class="deduction_combo_class" onchange="javascript:check_deduction_combo_val(this.value);"><option value="">Select Type</option>';
		
		if( deductions && deductions!==null){		
			$.each(deductions, function(index,deduction){
				earning_combo += '<option value="'+deduction.id+'">'+deduction.name+'</option>';						
			});
		}
		
		
		earning_combo += '<option value="newdeduction">Add New Deduction</option>';		
		earning_combo += '</select>';
		var parent_combo = '<select name="deduction_parent[]" style="width:100%" class="deduction_parent_combo_class" multiple="multiple">';
		parent_combo = parent_combo+'<option value="0">Select</option>';
		parent_combo = parent_combo+'<option value="2">Gross Pay</option>';
		
		if(earning_selected_val != ''){
			parent_combo = parent_combo+earning_selected_val;	
		}
		
		parent_combo = parent_combo+'</select>';
		$('.list-deduction1').append('<tr id="deduction_row_1" class="deduction_row_class">'+
							   '<td width="28%">'+earning_combo+'</td>'+
							  '<td width="10%"><input type="text" name="deduction_percenatge_value[]" class="deduction_percenatge_class"  style="width:100px;height:30px;"/></td>'+											
							   '<td width="28%">'+parent_combo+'</td>'+
							  '<td width="10%" colspan="2"><input type="text" name="deduction_amount_value[]" class="deduction_amount_class"  style="width:100px;height:30px;"/><input type="hidden" name="mul_dedc_parent_value[]" class="mul_dedc_parent_class" id="mul_dedc_parent_value" value="" style="width:100px;height:30px;" /></td>'+
							   '</tr>')
		$('.list-deduction1').show('blind',500);
	});
addEmployeecontribution();
}


/*$('.earning_combo').live('change',function(){
	$this = $(this);
	
	if($this.val() != ""){
	//console.log($this);
		newOption = $this.find('option:selected').text();
		newValue = $this.find('option:selected').val();
		var exists = 0 != $('.deduction_parent_combo_class[value='+newValue+']').length;
		
		if(exists==0){
			$('.deduction_parent_combo_class').append('<option value="'+newValue+'">'+newOption+'</option>');
		}
		
		selectedEarnings = [];
		$('.deduction_parent_combo_class').each(function(i){
			selectedEarnings[i]	= $(this).val();											 
		});
		
		
	}
});*/



/*$('.add_new_deduction').live('click',function(){
	var hidden_deduction_row = $('#hidden_deduction_row').val();
	hidden_deduction_row = parseInt(hidden_deduction_row)+1;
	$('#hidden_deduction_row').val(hidden_deduction_row);
	$.getJSON(hrURL + "manage_earning_deduction.php?act=list_earning_type",function(data){
		var deductions = data.earningtype
		var earning_combo = '<select name="deduction[]" style="width:80%" class="deduction_combo_bx"><option value="">Select Type</option>';
		$.each(deductions, function(index,deduction){
			earning_combo += '<option value="'+deduction.id+'">'+deduction.name+'</option>';						
		});
		earning_combo += '</select>';
		var parent_combo = '<select name="parent[]" class="parent_combo_bx" style="width:80%"><option value="">Select</option><option value="1">Basic Pay</option></select>';
		$('#tablelist').append('<tr id=deduction_row_'+hidden_earning_row+'>'+
							   '<td width="20%">'+earning_combo+'</td>'+
							   '<td width="20%"><input type="text" name="percenatge_value[]" style="200px;height:30px;" /></td>'+											
							   '<td width="20%">'+parent_combo+'</td>'+
							   '<td width="20%" colspan="2"><input type="text" name="amount_value[]"  style="200px;height:30px;"/></td>'+
							   '</tr>')
		$('.list-deduction1').show('blind',500);
	});
});*/


$('.deduction_combo_class:first').live('change',function(){
		$('.earning_combo').each(function(){
			var $this = $(this);
			selectedValue = $this.val();
			selectedOption = $this.find('option:selected').text();
			if($(".deduction_parent_combo_class option[value='"+selectedValue+"']").length == 0){
				$('.deduction_parent_combo_class').append('<option value="'+selectedValue+'">'+selectedOption+'</option>');
			}
			
		});
});

$('.employeecontribution_combo_class:first').live('change',function(){
		$('.earning_combo').each(function(){
			var $this = $(this);
			selectedValue = $this.val();
			selectedOption = $this.find('option:selected').text();
			if($(".employeecontribution_parent_combo_class option[value='"+selectedValue+"']").length == 0){
				$('.employeecontribution_parent_combo_class').append('<option value="'+selectedValue+'">'+selectedOption+'</option>');
			}
			
		});
});

$('.last_deduction').live('click',function(e){
	e.preventDefault();										  
	$('.deduction_row tr:last').remove();
	var rowCount = $('.deduction_row tr').length;
	if(rowCount > 2){
		$('.deduction_row tr:last').find('td:last-child').append('<span class="remo_span_ded"><a href="#" class="last_deduction">Remove</a></span>');
	}
});

$('.add_new_deduction').live('click',function(){
	var rowCount = $('.deduction_row tr').length;
	var newRow = $('.deduction_row_class:last').clone();
	var lastRow = $('.deduction_row_class:last');
	newRow.find('input').val('');
	if( lastRow.find('.deduction_combo_class').val()!='' && lastRow.find('.deduction_parent_combo_class').val()!='' && (lastRow.find('.deduction_percenatge_class').val()!='' ||  lastRow.find('.deduction_amount_class').val()!='') ){
		
		var last_row_parent_val = $('.deduction_row tr:last .deduction_parent_combo_class').val();
		if(last_row_parent_val == ''){
			last_row_parent_val = 0;
		}
		$('.deduction_row tr:last .mul_dedc_parent_class').val(last_row_parent_val);
		
		if(rowCount > 2){
			lastRow.find('td:last-child .remo_span_ded').text('');
		}
		newRow.find('input').val('');
		if(rowCount == 2){
			newRow.find('td:last-child').append('<span class="remo_span_ded"><a href="#" class="last_deduction">Remove</a></span>');
		}
		$('.deduction_row_class:last').after(newRow);			
	}else{
		alert('Please fill Deduction, Parent, and either Percenatage or Amount');
	}
});

$('.last_earninig').live('click',function(e){
	e.preventDefault();										  
	$('.earnings_row tr:last').remove();
	var rowCount = $('.earnings_row tr').length;
	if(rowCount > 2){
		$('.earnings_row tr:last').find('td:last-child').append('<span class="remo_span"><a href="#" class="last_earninig">Remove</a></span>');
	}
});
$('.add_new_earning').live('click',function(){
		var rowCount = $('.earnings_row tr').length;
		var newRow = $('.earnings_row_class:last').clone();
		var lastRow = $('.earnings_row_class:last');
		newRow.find('input').val('');
		if(lastRow.find('.earning_combo').val()!='' ){
				var last_row_parent_val = $('.earnings_row tr:last .parent_combo').val();
				if(last_row_parent_val == ''){
					last_row_parent_val = 0;
				}
				$('.earnings_row tr:last .mul_earn_parent_class').val(last_row_parent_val);
				if(rowCount > 2){
					lastRow.find('td:last-child .remo_span').text('');
				}
				newEarningText =  lastRow.find('.earning_combo option:selected').text();//parent_combo
				newEarningValue = lastRow.find('.earning_combo option:selected').val();
				newRow.find('.parent_combo').append('<option value="'+newEarningValue+'">'+newEarningText+'</option>');
				newRow.find('input').val('');
				if(rowCount == 2){
					newRow.find('td:last-child').append('<span class="remo_span"><a href="#" class="last_earninig">Remove</a></span>');
				}
				
					  
				$('.earnings_row_class:last').after(newRow);
				$('.weekly_branch_combo').on('change', function() {
					var branch_id=$(this).val();
					var x = $(this).closest('tr').find('.weekly_member_combo');
					$.ajax({
						url:hrURL+"managePayrollSalary.php",
						type:"post",
						data:"act=LoadEmpBranch&branch_id="+branch_id,
						success:function(result){
							//alert(result);
							x.html(result);
						}
					});
				});
		}
		else{
			alert('Please fill Earnings');
		}	
});

/*$('.confirm_earning_deduction').live('click',function(){
	var hidden_earning_count = $('#hidden_earning_row').val();
	for(var earning_cntr=1;earning_cntr<=hidden_earning_count;earning_cntr++){
		var earning_type = $('#earning_'+earning_cntr).val();
		var percenatge = $('#percenatge_'+earning_cntr).val();
		var parent = $('#parent_'+earning_cntr).val();
		var earning_type = $('#amount_'+earning_cntr).val();
		
	}
});*/

$('.confirm_earning_deduction').live('click',function(){
	var last_row_parent_val = $('.earnings_row tr:last .parent_combo').val();
	if(last_row_parent_val == ''){
		last_row_parent_val = 0;
	}
	$('.earnings_row tr:last .mul_earn_parent_class').val(last_row_parent_val);	
	
	var last_row_parent_val1 = $('.deduction_row tr:last .deduction_parent_combo_class').val();
	if(last_row_parent_val1 == ''){
		last_row_parent_val1 = 0;
	}
	$('.deduction_row tr:last .mul_dedc_parent_class').val(last_row_parent_val1);
													  
													  
	var desigs=$('input:checked.des_clss').length ;									  
	var earnings=$('#earning_1').val();	
	var percs=$('#amount_1').val();	
	dataString = $('.sal_structure_form').serialize();// alert(dataString);
	
	
	console.log(dataString);
	
	
	if(earnings=='' || percs=='')
	{
		alert('Please Enter Atleast One Row');
	}
	else if(desigs==0 )
	{
			alert('Please Select Atleast One Designation');
	}
	else
	{
		$.post(hrURL + "manage_earning_deduction.php?act=insert_salary_structure",dataString,function(data){
			alert('Salary Structure Successfully Saved');
			salaryStructure();
		},'json');
	
	}
});

$('.remove_sal_structure').live('click',function(){
	var did = $(this).attr('data-id');
	$this = $(this);
	$.get(hrURL + "manage_earning_deduction.php?act=remove_structure&did="+did,function(){
		$this.parent().parent().remove();															 
	});										 
});
$('.show_structure_list').live('click',function(){
												
	salaryStructure();
	//weeklyPayment();
});

$('.show_list_class').live('click',function(){
	$('#tablelist').html('');
	$('#tablelist').append('<div style="width:100%;" align="right"><input type="button" class="show_structure_list btn-tab-01" value="Back to Salary Structure" name="list_salary"></div>');
	$('#tablelist').append('<table width="100%" border="0" cellspacing="0" cellpadding="0" class="list-employees">'+
	'<tr><td width="20%"><translate>No.</translate></td>'+
	'<td width="20%"><translate>Designation</translate></td>'+
	'<td width="20%">Remove</td>'+
	'</tr>');											
	$.getJSON(hrURL + "manage_earning_deduction.php?act=list_salary_structure",function(data){
		var deductions = data.designationlist	
		var list_cntr = 1;
		$.each(deductions, function(i,deduction){
									
			
					
									
			$('.list-employees').append('<tr class="expand_parent_row" style="cursor:pointer">'+
											'<td>'+list_cntr+'</td>'+
											'<td>'+deduction.desig_name+'</td>'+
											'<td><img class="remove_sal_structure" data-id="'+deduction.id+'"  src="images/delete.png" /></td>'+
										'</tr>'+
										'<tr class="row_to_expand" style="display:none;">'+
											'<td colspan="3">'+
												'<table width="100%" height="67" border="0" cellpadding="0" cellspacing="0" class="table-bordered'+i+'" >'+
												'<tr style="display:none;"><td></td></tr>'+
												 ' <tr>'+
													'<td valign="top" width="50%">'+
													
													'<table width="100%" border="0" cellspacing="0" cellpadding="0" class="earning-list">'+
													 ' <tr style="background:#666">'+
														'<td>Earning  </td>'+
														'<td>Percentage</td>'+
														'<td>Of</td>'+
														'<td>Max-amount</td>'+
													  '</tr>'+
								
													'</table></td>'+
													'<td valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="0" class="deduction-list">'+
													 ' <tr style="background:#666">'+
														'<td>Deduction</td>'+
														'<td>Percentage</td>'+
														'<td>Of</td>'+
														'<td>Max-amount</td>'+
													  '</tr>'+
												
													'</table></td>'+
												  '</tr>'+
												'</table>');
										
										$.getJSON(hrURL + "manage_earning_deduction.php?act=designation_structure&designation_id="+deduction.designation_id,function(data){
											var designationstructure = data.designationstructure			
											$('.table-bordered tbody').html('');
											
											newArray = [];
											
											$.each(designationstructure, function(index,designationstructures){
											//	console.log(designationstructures.parent_id);	
												
												
												
												
												var parentsData = designationstructures.parent_id;												
												var parentDetails =parentsData.split(",");
												var parentName;
												//console.log(parentDetails);
												
												$.each(parentDetails,function(index,parentDetail){
														  
													$index = jQuery.inArray( parentDetail, newArray);
													
													newArray[index] = 	designationstructures.id1;
													var parentName=''; 
													
													if($index!='-1'){
														$itemname = designationstructure[$index].name;
														parentName = $itemname;
														
													}
													alert(designationstructures.parent_id);
													if(designationstructures.parent_id == 1){
														parentName = "Basic Pay";
													}
													if(designationstructures.parent_id == 2){
														parentName = "Grosspay";
													}
													console.log(parentName);
													console.log(newArray);
												})
												
												
	
												designationAmt =designationstructures.amount; 
												designationPer= designationstructures.percentage;
												if(designationstructures.percentage==0.00){
													designationPer = "-"
												}
												if(designationstructures.amount==0.00){
													designationAmt = "-"
												}
												
	
	
												if(designationstructures.type == '1'){
												
												$('.table-bordered'+i).find('.earning-list').append('<tr style="background:none;color:#686868;">'+
																			'<td>'+designationstructures.name+'</td>'+
																			'<td>'+designationPer+'</td>'+
																			'<td>'+parentName+'</td>'+
																			'<td>'+designationAmt+'</td>'+
																			'</tr>');
												}else{
													$('.table-bordered'+i).find('.deduction-list').append('<tr style="background:none;color:#686868;">'+
																			'<td>'+designationstructures.name+'</td>'+
																			'<td>'+designationPer+'</td>'+
																			'<td>'+parentName+'</td>'+
																			'<td>'+designationAmt+'</td>'+
																			'</tr>');
												}
											});
										});
										
										$('.list-employees').append('</table>'+
																	'</td>'+
																	'</tr>');	
			list_cntr = parseInt(list_cntr)+1;
		});
		$('.expand_parent_row').click(function () {
			
			//$( this ).toggleClass( "highlight" );
			
			var currentDetails = $(this).next('.row_to_expand');
			$('.row_to_expand').not(currentDetails).hide();
			currentDetails.toggle('fade');
		});
	});
	$('.list-employees').append('</table>');
});

$('#saveNewEarning').live('click',function(){
	var attr_name=$('#attribute').val();
	if(attr_name == ''){
		alert('Attribute Name is required')	;
	}else{
		$.ajax({
			type: "GET",
			url: hrURL + "manage_earning_deduction.php",
			data: "act=add_new_earning_name&attribute="+attr_name,
			success: function(result){
				$('.earning_combo:last').find('option:last').before('<option value="'+result+'" selected="selected">'+attr_name+'</option');	
				$('.newEmployeeDetails').hide('clip',300,function(){ $(this).remove(); });
			}
		});
	}
});


$('#saveNewDeduction').live('click',function(){
	var attr_name=$('#attribute').val();
	if(attr_name == ''){
		alert('Attribute Name is required')	;
	}else{
		$.ajax({
			type: "GET",
			url: hrURL + "manage_earning_deduction.php",
			data: "act=add_new_deduction_name&attribute="+attr_name,
			success: function(result){
				$('.deduction_combo_class:last').find('option:last').before('<option value="'+result+'" selected="selected">'+attr_name+'</option');	
				$('.newEmployeeDetails').hide('clip',300,function(){ $(this).remove(); });
			}
		});
	}
});


jQuery('.cancelNewDeduction').live('click',function(){  $('.newEmployeeDetails').hide('clip',300,function(){ $(this).remove(); })  });


function check_deduction_combo_val(ded_comb_val){
	if(ded_comb_val == 'newdeduction'){
		$("body").append('<div class="newEmployeeDetails" style="display:none; padding:25px; ">'+
					 '<form class="newSingleAttributeForm"><table  height="200" border="0" cellpadding="0" cellspacing="0">'+
					  '<tr>'+
						'<td width="200"><translate>Deduction</translate></td>'+
						'<td width="400"><input type="text" name="attribute" value="" id="attribute" /></td>'+
						'<td width="200">&nbsp;</td>'+
						'<td width="200">&nbsp;</td>'+
					  '</tr>'+
					  '<tr>'+
					    '<td>&nbsp;</td>'+
						'<td>&nbsp;</td>'+
						'<td></td>'+
						'<td><input type="button" name="button" id="saveNewDeduction"  class="color-button saveSingleAttrDetails" value="Submit" style="float:left; margine-left:5px" />'+
						'<input type="button" name="button" class="color-button2 cancelNewDeduction" style="float:left;" value="Cancel" /></td>'+
					  '</tr>'+
					'</table></form></div>');
	$('.newEmployeeDetails').show('fade',300);
	$('.newEmployeeDetails').center();		
	}		
}











jQuery('.cancelNewEarning').live('click',function(){  $('.newEmployeeDetails').hide('clip',300,function(){ $(this).remove(); })  });
function check_earning_combo_val(earn_combo_val){
	if(earn_combo_val == 'newearning'){
		$("body").append('<div class="newEmployeeDetails" style="display:none; padding:25px;">'+
					 '<form class="newSingleAttributeForm"><table width="800" height="200" border="0" cellpadding="0" cellspacing="0">'+
					  '<tr>'+
						'<td width="200"><translate>Earning</translate></td>'+
						'<td width="400"><input type="text" name="attribute" value="" id="attribute" /></td>'+
						'<td width="200">&nbsp;</td>'+
						'<td width="200">&nbsp;</td>'+
					  '</tr>'+
					  '<tr>'+
					    '<td>&nbsp;</td>'+
						'<td>&nbsp;</td>'+
						'<td></td>'+
						'<td><input type="button" name="button" id="saveNewEarning"  class="color-button saveSingleAttrDetails" value="Submit" style="float:left; margine-left:5px" />'+
						'<input type="button" name="button" class="color-button2 cancelNewEarning" style="float:left;" value="Cancel" /></td>'+
					  '</tr>'+
					'</table></form></div>');
	$('.newEmployeeDetails').show('fade',300);
	$('.newEmployeeDetails').center();		
	}
}


function salaryStructure(){
	$('#light-pagination').hide();
	$('#tablelist').html('');
	$(".paysalsearch").css("display", "none");
	$(".calsrch").css("display", "none");
	removeCurrentPage();
	var lastPage;
	$('.header').show('blind',500);
	var designation_checklist = '';
	$('#tablelist').append('<div width="100%" align="right">'+
							   '<input type="button" name="list_salary" value="Show List" class="show_list_class btn-tab-01">'+
							   '</div>');
		
		$('#tablelist').append('<div id="masterlist">'+
							   '<form class="sal_structure_form">'+
							   '<p>'+
							   '<div align="left" style="width:48%;"><strong>Earnings</strong></div>'+
							   '</p>'+
								'<table width="100%" border="0" cellspacing="0" style="display:none" cellpadding="0" class="list-deduction earnings_row">'+
							   '<tr>'+
							   '<td width="20%"><translate>Earnings</translate></td>'+
							   '<td width="20%"><translate>Percentage</translate></td>'+
							   '<td width="20%"><translate>of</translate></td>'+
							   '<td width="20%"><translate>Max Amount</translate></td>'+
							   '<td width="20%"><input type="hidden" name="hidden_earning_row" id="hidden_earning_row" value="1">'+
							   '<input type="button" value="New Earning Row" class="add_new_earning btn-tab-01"/></td>'+
							   '</tr></table></form></div>');
	$.getJSON(hrURL + "manage_earning_deduction.php?act=list_earning_type",function(data){
		var deductions = data.earningtype;
		
		
		
		var earning_combo = '<select name="earning[]" id="earning_1" class="earning_combo" style="width:100%" onchange="javascript:check_earning_combo_val(this.value);">'+
							'<option value="">Select Type</option>';
							
		if( deductions && deductions!==null){					
			$.each(deductions, function(index,deduction){
				earning_combo += '<option value="'+deduction.id+'">'+deduction.name+'</option>';						
			});
		}
		
		earning_combo += '<option value="newearning">Add New Earning</option>';
		earning_combo += '</select>';
		var parent_combo = '<select name="parent[]" id="parent_1" class="parent_combo" style="width:100%" multiple="multiple">'+
							'<option value="0">Select</option></select>';
		$('.earnings_row').append('<tr id="earning_row_1" class="earnings_row_class">'+
							   '<td width="28%">'+earning_combo+'</td>'+
							   '<td width="10%"><input type="text" name="percenatge_value[]" class="percent" id="percenatge_1"  style="width:100px;height:30px;"/></td>'+											
							   '<td width="28%">'+parent_combo+'</td>'+
							   '<td width="10%" colspan="2"><input type="text" name="amount_value[]" class="max-amount" id="amount_1" style="width:100px;height:30px;" /><input type="hidden" name="mul_earn_parent_value[]" class="mul_earn_parent_class" id="mul_earn_parent_value" value="" style="width:100px;height:30px;" /></td>'+
							   '</tr>');
		
		$('.sal_structure_form').append('<div class="deduction_list_table"><table class="DeductionList" style="width:100%;"></table></div>');
		$('.list-deduction').show('blind',500);
	
	});
	

	setTimeout(function(){
	$.getJSON(hrURL + "manage_earning_deduction.php?act=list_designation_type",function(data){
		$('.sal_structure_form').append('<h3 style="margin-top:10px;">Assign Salary Structure to</h3>'+
										'<div class="desclist  designation-list" style="height:200px; width:300px; float:left; overflow-y:scroll;">'+
										'<table class="DesignationList"></table></div>');																				
		var deductions = data.designations;
		var designation_cntr = 0;
		var kk=0;
		if( deductions && deductions!==null){		
			$.each(deductions, function(index,deduction){
					kk = kk+1; 					
										
				$('.DesignationList').append('<tr><td><input type="checkbox" name="designation[]" class="des_clss" value="'+deduction.desig_id+'" id="designation'+kk+'">'+deduction.desig_name+'</td></tr>');	
				designation_cntr = designation_cntr+1;
			});
		}
		
		
		$('#tablelist').append('<input type="button" value="Confirm" class="confirm_earning_deduction btn-tab-01" style="float:left; margin-top:180px; margin-left:20px;">'+
							   '<input type="button" value="Reset" class="reset_earning_deduction btn-tab-01" style="float:left; margin-top:180px; margin-left:20px;">');
		/*$('.confirmbutton').append('<div class="confirm_table"><table class="ConfirmButton" style="width:100%;"><tr><td><input type="button" value="Confirm" class="confirm_earning_deduction btn-tab-01"></td></tr></table></div>');*/	
	});
	addDiductions();
	},100);
		
}
/* Salary Structure */


$('.reset_earning_deduction').live('click',function(){
		salaryStructure();												
});







/* Earning Deduction Master Form */
function deductionManagement(e,pageno){
	if(!pageno)
	pageno =1;
	if(pageno == 1 ){
			k=1; 
		 }else{
			k= ((pageno-1) * pageLimit)+1;
		 }
		 var tot = 0;
	/*$(".memsrch").css("display", "block");*/
	$(".paysalsearch").css("display", "none");
	$(".calsrch").css("display", "none");
	removeCurrentPage();
	var lastPage;
	$('.header').show('blind',500);
	$('#tablelist').html('');
	/*$.getJSON(hrURL + "manageDeduction.php?act=list",function(data){
		var deduction = data.deductions;
			$('#tablelist').append('<table width="100%" border="0" cellspacing="0" style="display:none" cellpadding="0" class="list-deduction">'+
										  '<tr>'+
										    '<td width="23%"><translate>Employee Name</translate></td>'+
											'<td width="23%"><translate>Title</translate></td>'+											
											'<td width="35%"><translate>Description</translate></td>'+
											'<td width="12%"><translate>Type</translate></td>'+
											'<td width="19%"><translate>Value</translate></td>'+
											'<td width="5%"><translate>Edit</translate></td>'+
											'<td width="5%"><img src="images/icon-add.png" class="addNewDeduction" width="20" height="20" /></td>'+
										 '</tr>'+
										'</table>')	
			$('.list-deduction').show('blind',500);
			$.each(deduction, function(index,deductions){
				
				var ded_unit='';
				var type='';
				switch(deductions.unit){
					case "1":ded_unit="Rs";break;
					case "2":ded_unit = "%";break;
				}
				switch (deductions.deduction_benefit){
					case "1":type = "Deduction";break;
					case "2":type = "Earnings";break;
					case "3":type = "Employer's Contribution";break;
				}
					
					$('.list-deduction').append( '<tr class="deduct_'+deductions.id+'">'+
														'<td width="23%" class="deducte_fname" data-id="'+deductions.e_id+'">'+deductions.e_fname+'</td>'+
														'<td width="23%" class="deduct_name" >'+deductions.name+'</td>'+
														'<td width="35%" class="deduct_desc">'+deductions.description+'</td>'+
														'<td width="12%" class="deduct_type" data-id="'+deductions.deduction_benefit+'">'+type+'</td>'+
														'<td width="19%" class="deduct_amount"  data-id="'+deductions.unit+'">'+deductions.amount+" ("+ded_unit+')</td>'+
														'<td width="6%"><img data-id="'+deductions.id+'" src="'+editIcon+'" class="editDeduction"/></td>'+
														'<td width="5%"><img data-id="'+deductions.id+'" src="'+removeIcon+'" class="removeDeduction"/></td>'+
													 '</tr>');				
			});
			
		
	});*/
	
	$.getJSON(hrURL + "manage_earning_deduction.php?act=list",function(data){
		var deduction = data.earningdeductions;
		$('#tablelist').append('<table width="100%" border="0" cellspacing="0" style="display:none" cellpadding="0" class="list-deduction">'+
							   '<tr>'+
							   '<td width="8%"><translate>No.</translate></td>'+
							   '<td width="23%"><translate>Title</translate></td>'+											
							   '<td width="35%"><translate>Type</translate></td>'+
							   '<td width="5%"><translate>Edit</translate></td>'+
							   '<td width="5%"><img src="images/icon-add.png" class="addNewEarningDeduction" width="20" height="20" /></td>'+
							   '</tr>'+
							   '</table>')	
			$('.list-deduction').show('blind',500);
			var i = 1;
			$.each(deduction, function(index,deductions){
				$('.list-deduction').append( '<tr class="deduct_'+deductions.id+'">'+
					'<td width="23%" class="deducte_fname">'+i+'</td>'+
					'<td width="23%" class="deduct_name" >'+deductions.name+'</td>'+
					'<td width="23%" class="deduct_type" >'+deductions.type_text+'</td>'+
					'<td width="6%"><img data-id="'+deductions.id+'" src="'+editIcon+'" class="editDeduction"/></td>'+
					'<td width="5%"><img data-id="'+deductions.id+'" src="'+removeIcon+'" class="removeEarningDeduction"/></td>'+
			 	'</tr>');	
				i++;
			});
	});
	
}
jQuery('.removeEarningDeduction').live('click',removeEarningDeduction);
function removeEarningDeduction(){
	var did = $(this).attr('data-id');
	$this = $(this);
	
	r= confirm("Do you want to delete this item?.");
	if(r==true){
		$.get(hrURL + "manage_earning_deduction.php?act=remove&did="+did,function(){
			$this.parent().parent().remove();															 
		});
	}
}
jQuery('.cancelEarningDeduction').live('click',function(){ $('.newDeductionform').hide('blind',500,function(){ $(this).remove(); }) });
jQuery('.saveEarningDeduction').live('click',function(){
	var deductionTitle = $('#deductionTitle').val();
	var type = $('#type').val();
	if(deductionTitle == ''){
		alert('Title is required');
	}
	else if(type == ''){
		alert('Type is required');
	}
	else{
		dataString = $('.newDeductionform').serialize();
		var count = $('.list-deduction tr').length;
		$.post(hrURL + "manage_earning_deduction.php?act=insert",dataString,function(data){
			var deductions = data.earningdeductions
			$.each(deductions, function(index,deduction){
				$('.list-deduction').append( '<tr class="deduct_'+deduction.id+'">'+
					'<td width="23%" class="deduct_name" >'+count+'</td>'+
					'<td width="23%" class="deduct_name" >'+deduction.name+'</td>'+
					'<td width="23%" class="deduct_name" >'+deduction.type_text+'</td>'+
					'<td width="6%"><img data-id="'+deduction.id+'" src="'+editIcon+'" class="editDeduction"/></td>'+
					'<td width="5%"><img data-id="'+deduction.id+'" src="'+removeIcon+'" class="removeEarningDeduction"/></td>'+
				 '</tr>');	
			});
			$('.newDeductionform').hide('blind',500,function(){ $(this).remove(); });
		},'json');
	}
});
function addNewEarningDeduction(){
	$('.list-deduction').before('<form class="newDeductionform"><table width="50%" border="0" style="display:none" cellspacing="0" cellpadding="0" class="newDeduction">'+
								'<tr>'+
									'<td width="47%">&nbsp;</td>'+
									'<td width="53%">&nbsp;</td>'+
								'</tr>'+
								'<tr>'+
									'<td height="30"><translate>Title</translate></td>'+
									'<td><input type="text" style="200px;height:30px;" name="deductionTitle" id="deductionTitle" /></td>'+
								'</tr>'+
								'<tr>'+
									'<td height="30"><translate>Type</translate></td>'+
									'<td><select name="type" id="type">'+
									  '<option value="">Select type</option>'+
									  '<option value="1">Earnings</option>'+
									  '<option value="2">Deduction</option>'+
									'</select>'+
									'</td>'+
								  '</tr>'+
								  '<tr>'+
									'<td height="30">&nbsp;</td>'+
									'<td><input type="button" name="button" class="color-button saveEarningDeduction" id="button" value="Submit" />'+
									'<input type="button" name="button" class="color-button cancelEarningDeduction" id="button" value="Cancel" /></td>'+
								  '</tr>'+
								  '<tr>'+
									'<td>&nbsp;</td>'+
									'<td>&nbsp;</td>'+
								  '</tr>'+
								'</table></form>');
	$('.newDeduction').show('blind',500);
	/*loadimdsuper();*/
}
/* Earning Deduction Master Form */

function pay_slip_view(employee_id) {
	//alert("act=payslipview&employee_id="+employee_id+"&year="+$('#salyear').val()+"&month="+$('#salmonth').val());
	$.ajax({
		type: "POST",
		url: hrURL + "managePayrollSalary.php",
		data: "act=payslipview&employee_id="+employee_id+"&year="+$('#salyear').val()+"&month="+$('#salmonth').val(),
		success: function(result){
			$('#PaySlipModal').html(result);
			$('#PaySlipModal').modal('show');
		}
	});
}

function submitSalary() {
	//alert($('#PaySalaryForm').serialize());
	$.ajax({
		type: "POST",
		url: hrURL + "managePayrollSalary.php",
		data: $('#PaySalaryForm').serialize(),
		success: function(result){
			var row_id=$('#userid').val();
			$('.pay_status'+row_id).html('Paid');
			$('#PaySlipModal').modal('hide');
		}
	});	
}

function print_pay_slip() {	
//$('.hide').hide();

payslipprint = $('#PaySlipModal .modal-body').clone();
paymentThrough = payslipprint.find('.paymentThrough option:selected').text();
payslipprint.find('.paymentThrough').parent().html( "Payment Mode : "+paymentThrough );
paymentReferance = payslipprint.find('.referance').val();
payslipprint.find('.referance').parent().html( "Reference : "+paymentReferance );
payslipprint.find('#PaySalaryForm').css({'margin':'30px'});
payslipprint.find('.btn-primary').remove();
payslipprint.find('.btn-default').remove();

payslipprint.print();

//$('#PaySlipModal .modal-body').print();
return false;
}

function download_pay_salary() {
	var pagenum=1;
	var searchString = $('.pdtSearchForm').serialize(); 
	//alert(searchString)
	window.location = serviceURLHR+"downloadsalarylist.php?pagenum="+pagenum+"&"+searchString;
}

function download_pay_salary_cumulative() {
	var pagenum=1;
	var searchString = $('.pdtSearchForm').serialize(); 
	//alert(searchString)
	window.location = serviceURLHR+"downloadsalarylist_cumulative.php?pagenum="+pagenum+"&"+searchString;
}


function addEmployeecontribution(){
	$(this).attr("disabled","disabled");	
	var employeecontribution_selected_val  = '';
	$('.earning_combo').each(function(){ 
		if($(this).val()!=''){
			earning_combo_selected_val = earning_combo_selected_val+'<option value="'+$(this).val()+'">'+$(this).find("option:selected").text()+'</option>';
		}
	});
	

	$.getJSON(hrURL + "manage_earning_deduction.php?act=list_employercontribution",function(data){
																								
		var employeecontributions = data.contribution

		 
		$('.deduction_list_table').after('<div>'+
											 '<table class="employer_contribution list-employees">'+
												 '<tr>'+
													 '<td>Contribution</td>'+
													 '<td>Percentage</td>'+
													 '<td>Of</td>'+
													 '<td>Max Amount</td>'+
													 '<td><input type="button" value="New Employer Contribution" class="add_new_employerContribution btn-tab-01"></td>'+
												 '</tr>'+
											 '</table>'+
										 '</div>');
		 
		
		
		var employeecontribution_combo = '<select name="deduction[]" style="width:100%" class="employeecontribution_combo_class" onchange="javascript:check_employeecontribution_combo_val(this.value);"><option value="">Select Type</option>';
		if( employeecontributions && employeecontributions!==null){		
			$.each(employeecontributions, function(index,employeecontribution){
				employeecontribution_combo += '<option value="'+employeecontribution.id+'">'+employeecontribution.name+'</option>';						
			});
		}
		employeecontribution_combo += '<option value="newcontribution">Add New employeecontribution</option>';		
		employeecontribution_combo += '</select>';	/**/
		
		
		
		
		var parent_combo = '<select name="deduction_parent[]" style="width:100%" class="employeecontribution_parent_combo_class" multiple="multiple">';
		parent_combo = parent_combo+'<option value="0">Select</option>';
		parent_combo = parent_combo+'<option value="2">Gross Pay</option>';/**/
		
		/*if(earning_selected_val != ''){
			parent_combo = parent_combo+earning_selected_val;	
		}*/
		parent_combo = parent_combo+'</select>';
		$('.employer_contribution').append('<tr id="employeecontribution_row_1" class="employeecontribution_row_class">'+
							'<td width="28%">'+employeecontribution_combo+'</td>'+
							'<td width="10%">'+
							'<input type="text" name="deduction_percenatge_value[]" class="employeecontribution_percenatge_class" '+
																															'style="width:100px;height:30px;"/>'+
							'</td>'+											
							'<td width="28%">'+parent_combo+'</td>'+
							'<td width="10%">'+
							'<input type="text" name="deduction_amount_value[]" class="employeecontribution_amount_class" style="width:100px;height:30px;"/>'+
							'<input type="hidden" name="mul_dedc_parent_value[]" class="mul_dedc_parent_class" id="mul_dedc_parent_value" '+
																													'value="" style="width:100px;height:30px;" />'+
							'</td>'+
							'<td></td>'+
							'</tr>');
		
	});
}



jQuery('.cancelNewContribution').live('click',function(){  $('.newEmployeeDetails').hide('clip',300,function(){ $(this).remove(); })  });

function check_employeecontribution_combo_val(ded_comb_val){
	if(ded_comb_val == 'newcontribution'){
		$("body").append('<div class="newEmployeeDetails" style="display:none; padding:25px; ">'+
					 '<form class="newSingleAttributeForm"><table  height="200" border="0" cellpadding="0" cellspacing="0">'+
					  '<tr>'+
						'<td width="200"><translate>Employer Contribution</translate></td>'+
						'<td width="400"><input type="text" name="attribute" value="" id="attribute" /></td>'+
						'<td width="200">&nbsp;</td>'+
						'<td width="200">&nbsp;</td>'+
					  '</tr>'+
					  '<tr>'+
					    '<td>&nbsp;</td>'+
						'<td>&nbsp;</td>'+
						'<td></td>'+
						'<td>'+
		'<input type="button" name="button" id="saveNewContribution"  class="color-button saveSingleAttrDetails" value="Submit" style="float:left; margine-left:5px" />'+
						'<input type="button" name="button" class="color-button2 cancelNewContribution" style="float:left;" value="Cancel" /></td>'+
					  '</tr>'+
					'</table></form></div>');
	$('.newEmployeeDetails').show('fade',300);
	$('.newEmployeeDetails').center();		
	}		
}


function saveNewContribution(){	
	dataString = $('.newSingleAttributeForm').serialize();
	var newContribution = $('#attribute').val();
	$.get(hrURL + "manage_earning_deduction.php?act=insertContribution",dataString,function(data){
		$('.employeecontribution_combo_class:last').find('option:last').before('<option value="'+data+'">'+newContribution+'</option>');
		$('.employeecontribution_combo_class:last').val(data);
		$('.newEmployeeDetails').hide('fade',300,function(){ $(this).remove(); });		
	},'json');
}


$('.add_new_employerContribution').live('click',function(){
	var rowCount = $('.employeecontribution_row_class tr').length;
	var newRow = $('.employeecontribution_row_class:last').clone();
	var lastRow = $('.employeecontribution_row_class:last');
	newRow.find('input').val('');
	if( lastRow.find('.employeecontribution_combo_class').val()!='' && lastRow.find('.employeecontribution_parent_combo_class').val()!='' && (lastRow.find('.employeecontribution_percenatge_class').val()!='' ||  lastRow.find('.employeecontribution_amount_class').val()!='') ){
		
		var last_row_parent_val = $('.employeecontribution_row_class tr:last .employeecontribution_parent_combo_class').val();
		if(last_row_parent_val == ''){
			last_row_parent_val = 0;
		}
		$('.employeecontribution_row_class tr:last .employeecontribution_parent_combo_class').val(last_row_parent_val);
		
		if(rowCount > 2){
			lastRow.find('td:last-child .remo_span_ded').text('');
		}
		newRow.find('input').val('');
		if(rowCount == 2){
			newRow.find('td:last-child').append('<span class="remo_span_ded"><a href="#" class="last_deduction">Remove</a></span>');
		}
		$('.employeecontribution_row_class:last').after(newRow);			
	}else{
		alert('Please fill Employer Contribution, Parent, and either Percenatage or Amount');
	}
});

















jQuery.fn.center = function(parent) {
    if (parent) {
        parent = this.parent();
    } else {
        parent = window;
    }
    this.css({
        "position": "absolute",
        "top": ((($(parent).height() - this.outerHeight()) / 2) + $(parent).scrollTop() + "px"),
        "left": ((($(parent).width() - this.outerWidth()) / 2) + $(parent).scrollLeft() + "px")
    });
return 
}