/*****************************/
/*     Created By Jithin     */
/*          19-11-2013       */
/*****************************/
var hrURL =localStorage['serviceURLHR'];
var serviceURLHR =localStorage['serviceURLHR'];
var editIcon = "images/edit.png";
var removeIcon = "images/delete.png";
var currentPage;
var usertype;

/////////////////////////////////////////  Page management and URL Tracking Functions  //////////////////////////////////////
$('.payroll-menu li').live('click',function(){
	$this = $(this);
	window.location.hash = $this.attr('data-page');
});
/////////////////////////////////////////  URL TRACKING /////////////////////////////////////////////////////////////////////

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

$(window).load(function(){
   	locationHashChanged();					   
});
			
//jQuery(window).hashchange( 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){
			
			//$('#light-pagination').pagination('updateItems',15);
			$('li[data-page="'+hash+'"]').addClass('menu-selected');		
			
			
			
			setTimeout(window[hash],100); // call current function	
			currentPage =hash; 
			
			
			
			$("#light-pagination").jui_pagination({
				currentPage: 1,
				visiblePageLinks: 5,
				totalPages: 103,
				onChangePage:window[hash],
			});
			
			
		}else{
			$('li[data-page="'+currentPage+'"]').addClass('menu-selected');
			if(hash){
				//window.location.hash =	currentPage;currentPage =hash; 
			}
			
			//currentPage =currentPage;
			
		}
	}else{
		window.location.hash = "viewcirculars";
	}
}
$('#circulardate').live('click',function(){
		 $(this).datepicker({dateFormat:"dd-mm-yy"}).focus();	
	});

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

$('#toaddate').live('click',function(){
		 $(this).datepicker({dateFormat:"dd-mm-yy"}).focus();	
	});
jQuery('.removeCircular').live('click',removeCircular);
jQuery('.removeTiming').live('click',removeTiming);
jQuery('.editTiming').live('click',editTiming);
jQuery('.searchPdt').live('click',function(){ leaveRequests('1','') });
jQuery('.searchcircularPdt').live('click',function(){ viewcirculars('','1') });
jQuery('.circularsubmit').live('click',function(){ circularsubmit() });
jQuery('.reportimesubmit').live('click',function(){ reportimesubmit() });
jQuery('.searchpersonalPdt').live('click',function(){ personalleave('1','') });
jQuery('.leaveList').live('change',function(){ balanceleave() });
jQuery('#day_from').live('change',function(){ checkbalanceleave() });
jQuery('#day_to').live('change',function(){ checkbalanceleave() });

jQuery('.policysubmit').live('click',function(){ policysubmit() });
jQuery('.formsubmit').live('click',function(){ formsubmit() });

function change(page){
location.href=page;
}
function removeCurrentPage(){

$('.paymentMethod').remove();
$('#tablelist table').hide('blind',500,function(){ $(this).remove(); })	
}


function checkbalanceleave()
{
	var leavetype=$('.leaveList').val();
	if(leavetype!='')
	{
		balanceleave();
	}
	
}
function balanceleave()
{
	
	
	var userid=$('#employeesList').val();
	var leavetype=$('.leaveList').val();
	var day_from=$('#day_from').val();
	var day_to=$('#day_to').val();
		
		

	$.getJSON(hrURL + "balanceLeave.php?userid="+userid+"&leavetype="+leavetype+"&day_from="+day_from+"&day_to="+day_to,function(data){
																						
						
						var leaves = data.leaves;	
						
						if(leaves!='general')
						{
							if(leaves >0)
							var leavebalance=leaves+' leave is available';
							else
							var leavebalance='Leave Not Available';
						$('.leavebalance').html(leavebalance);
							if(parseInt(leaves)<=0)
							{
							
							$(".applypersonalLeave").css("display", "none");
							
							}
							else
							{
							
							$(".applypersonalLeave").css("display", "block");
							}
						}
						else
						{
							var leavebalance='';
							$('.leavebalance').html(leavebalance);
							$(".applypersonalLeave").css("display", "block");
						}
						//$('.categories').append(data.leaves);
						
	});
}

/////////////////////////////////////////////////////////////////////////////// Deduction management //////////////////////////////////////////////////////
function deductionManagement(){
	removeCurrentPage();
	$('.header').show('blind',500);
	$.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%">Title</td>'+
											'<td width="45%">Description</td>'+
											'<td width="12%">Type</td>'+
											'<td width="9%">Value</td>'+
											//'<td width="6%">&nbsp;</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='';
				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%">'+deductions.name+'</td>'+
														'<td width="45%">'+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);
		
	});
}

function addnewDeduction(){
	//alert('asd');
	//alert($('.newDeductionform').length);
	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>Title</td>'+
									'<td><input type="text" name="deductionTitle" id="deductionTitle" /></td>'+
								  '</tr>'+
								  '<tr>'+
									'<td>Description</td>'+
									'<td><textarea name="deductionDescription" id="deductionDescription" cols="45" rows="4"></textarea></td>'+
								  '</tr>'+
								  '<tr>'+
									'<td>Type</td>'+
									'<td><select name="type" id="type">'+
									  '<option value="1">Deduction</option>'+
									  '<option value="2">Benefit</option>'+
									  '<option value="3">Employer\'s Contribution</option>'+
									'</select>'+
									'</td>'+
								  '</tr>'+
								  '<tr>'+
									'<td>Amount / Persentage</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);
	}
}

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%">'+deductions.name+'</td>'+
							'<td width="45%">'+deductions.description+'</td>'+
							'<td width="12%">'+type+'</td>'+
							'<td width="9%">'+deductions.amount+" ("+ded_unit+')</td>'+
							'<td width="5%"><img data-id="'+deductions.id+'" src="'+removeIcon+'" class="removeDeduction"/></td>'+
							'</tr>');	
		
		$('.newDeductionform').hide('blind',500,function(){ $(this).remove(); });
		
	},'json');
}


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(){
	$('.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="30%" height="17">Name</td>'+
								'<td width="12%">Basic Pay</td>'+
								'<td width="11%">Deductions</td>'+
								'<td width="11%">Earnings</td>'+
								'<td width="16%">Employer Contributions</td>'+
								'<td width="11%">Total Payable</td>'+
								'<td width="9%">Pay Slip</td>'+
								'<td width="9%">Payment Status</td>'+
								'</tr>'+
							'</table>');	
	
	$.getJSON(hrURL+"manageSalary.php?act=lastms",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"/> ';	
		}
		
		
			var total = (parseFloat(salaryDetails.basic_pay)+parseFloat(salaryDetails.benefit)-parseFloat(salaryDetails.deduction)).toFixed(2)	;					  
			$('.list-employees').append(' <tr>'+
											'<td width="30%" height="17">'+salaryDetails.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>');											  
		});
		
		$('.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();
paySlip($this,paymentmonth,paymentyear) ;
}

function paySlip($this,paymentmonth,paymentyear){
	//alert(paymentmonth);
removeCurrentPage();
	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";
	
	
	if(paymentmonth < 10 && paymentmonth.length > 1){
		paymentmonth = paymentmonth[1];	
	}

	var n = month[paymentmonth];
	var joindate;
	
	
	$.getJSON(hrURL+"manageSalary.php?act=single&emp_id="+employeeid+"&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%">Employee ID</td>'+
									'<td width="37%" class="empid">&nbsp;</td>'+
									'<td width="14%">Employee Name</td>'+
									'<td width="36%" class="empname">&nbsp;</td>'+
								  '</tr>'+
								  '<tr>'+
									'<td>Joining Date</td>'+
									'<td class="joiningdate">&nbsp;</td>'+
									'<td>Designation</td>'+
									'<td class="designation">&nbsp;</td>'+
								 ' </tr>'+
								 ' <tr>'+
									'<td>Days Worked</td>'+
									'<td class="workeddays">&nbsp;</td>'+
									'<td>Payment Method</td>'+
									'<td class="paymentMethods">&nbsp;</td>'+
								  '</tr>'+
								  '<tr>'+
									'<td>Earned Leaves</td>'+
									'<td class="leaves">&nbsp;</td>'+
									'<td>Loss of pay</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">Earning</td>'+
									'<td width="50%">Deductions</td>'+
								  '</tr>'+
								  '<tr><td valign="top" class="totalEarnings">'+
								 ' <span class="basicPay" style="width:80%; height:25px; float:left;">Basic Pay</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;">Total Earnings</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;">Total Deduction</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;">Employer Contribution</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;">Net Payable</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 Grater');
				$('.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(){
	$('.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%">Title</td>'+
											'<td width="45%">Description</td>'+
											'<td width="9%">Days</td>'+
											//'<td width="6%">&nbsp;</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');
	$('.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>Title</td>'+
									'<td><input type="text" name="leaveTitle" id="leaveTitle" /></td>'+
								  '</tr>'+
								  '<tr>'+
									'<td>Description</td>'+
									'<td><textarea name="leaveDescription" id="leaveDescription" cols="45" rows="4"></textarea></td>'+
								  '</tr>'+
								  '<tr>'+
									'<td>Days</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="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 reportimesubmit(){
	var formData = new FormData($('#reportimeform')[0]);
	//alert(hrURL);
	//alert(serviceURLHR);
    $.ajax({
        url: hrURL + 'manageReportime.php?action=insert',  //Server script to process data
        type: 'POST',
        data: formData,
		processData: false,  // tell jQuery not to process the data
  		contentType: false ,  // tell jQuery not to set contentType
		success: function(data){
				//if(data=='success'){
				alert("Item successfully Updated.");
				//window.location="list.html";
			//}
		}
	});	
}


function circularsubmit(){
	//alert('gfghfggj');
	removeCurrentPage();
	var formData = new FormData($('#circularform')[0]);
	
    $.ajax({
        url: hrURL + 'manageCircular.php?action=insert',  //Server script to process data
        type: 'POST',
        data: formData,
		processData: false,  // tell jQuery not to process the data
  		contentType: false ,  // tell jQuery not to set contentType
		success: function(data){
				
				alert("Item successfully inserted.");
				window.location="circular-polcies.php#viewcirculars";
			
		}
	});	
}
function addcirculars(){
	$(".addpolicy").css("display", "none");	
	$("#policydiv").css("display", "none");
	$(".addcircular").css("display", "block");	
	$("#circulardiv").css("display", "none");
	$(".addform").css("display", "none");	
	$(".musteroll").css("display", "none")
	
	removeCurrentPage();
}
function viewcirculars(e,pageno){
	$(".addpolicy").css("display", "none");	
	$("#policydiv").css("display", "none");
	$("#circulardiv").css("display", "block");
	$(".addcircular").css("display", "none");
	$(".addform").css("display", "none");	
	$(".musteroll").css("display", "none")
	if(!pageno)
	pageno =1;
	
	var searchString = $('.pdtcircularSearchForm').serialize(); 
	
	
	if(pageno == 1 ){
			k=1; 
		 }else{
			k= ((pageno-1) * pageLimit)+1;
		 }
		 var tot = 0;

	var userid=$('.userid').val();
	var depart_id=$('.depart_id').val();
	$('.header').show('blind',500);
	removeCurrentPage();
	var lastPage;
	
	var circular_option='';
	if(usertype != 'Subadmin'){
	 	circular_option ='<td width="10%">Options</td>';
	}

	$('#tablelist').append('<table width="100%" border="0" cellspacing="0" style="display:none;" cellpadding="0" class="list-circulardetails">'+
										  '<tr>'+
											'<td width="15%">Sl No</td>'+
											'<td width="15%">Title</td>'+
											'<td width="15%">Date</td>'+
											'<td width="10%">Download</td>'+
											circular_option+
											
										 '</tr>'+
										'</table>')	;

$.getJSON(hrURL + "manageCircular.php?action=viewcircular&page="+pageno+"&"+searchString,function(data){
		
		var circulars = data.circulars;
		
		var circular_remove='';
			if(usertype != 'Subadmin'){
	 	circular_remove ='<td width="5%"><img data-id="'+circulars.id+'" src="'+removeIcon+'" class="removeCircular"/></td>';
		}
		
		
		$.each(circulars,function(index,circulars){
			
		var circulardetails='<tr>'+
						'<td width="15%">'+k+'</td>'+
						'<td width="15%">'+circulars.circulartitle+'</td>'+
						'<td width="10%">'+ new Date(circulars.circulardate).format("dd-mm-yyyy")+'</td>'+
						'<td width="15%"><a  href="'+hrURL+'download_circular.php?filename='+circulars.fileupload+'" title="'+circulars.fileupload+'" style="height:5px,width:5px" class="pro-icon-02">Download</a></td>'+
						circular_remove+
						
							 '</tr>';
	

				$('.list-circulardetails').append(circulardetails);	
				itemCount = circulars.totalrows;
				lastPage  = circulars.lastPage;
				
				k++;
				
			});
			
			$('.list-circulardetails').show('blind');
			$("#light-pagination").jui_pagination({
				totalPages: lastPage,
			});
		
		});
$(".list-circulardetails").css("display", "block");

}


function removeCircular(){
	

var checkstr =  confirm('are you sure you want to delete this?');
if(checkstr == true){
	
 var did = $(this).attr('data-id');
 
	$this = $(this);
	
	
	$.get(hrURL + "manageCircular.php?act=removeded&did="+did,function(){
		$this.parent().parent().remove();															 
	});
}else{
return false;
}

}

function policysubmit(){
	//var dataString = $('#frm1').serialize();

removeCurrentPage();
	var formData = new FormData($('#policyform')[0]);
	//alert(hrURL);
	//alert(serviceURLHR);
    $.ajax({
        url: hrURL + 'managePolicies.php?action=insert',  //Server script to process data
        type: 'POST',
        data: formData,
		processData: false,  // tell jQuery not to process the data
  		contentType: false ,  // tell jQuery not to set contentType
		success: function(data){
				//if(data=='success'){
				alert("Item successfully inserted.");
				window.location="circular-polcies.php#viewpolices";
				//window.location="list.html";
			//}
		}
	});	
}
function addpolices(){
$(".addpolicy").css("display", "block");	
	$("#policydiv").css("display", "none");
	$(".addcircular").css("display", "none");	
	$("#circulardiv").css("display", "none");
	$(".addform").css("display", "none");
	$(".musteroll").css("display", "none")
	removeCurrentPage();
}
function viewpolices(e,pageno){
	 	$("#policydiv").css("display", "block");
		$(".addpolicy").css("display", "none");
		$("#circulardiv").css("display", "none");
		$(".addcircular").css("display", "none");
		$(".addform").css("display", "none");
		$(".musteroll").css("display", "none")
	if(!pageno)
	pageno =1;
	
	var searchString = $('.pdtcircularSearchForm').serialize(); 
	
	
	if(pageno == 1 ){
			k=1; 
		 }else{
			k= ((pageno-1) * pageLimit)+1;
		 }
		 var tot = 0;

	var userid=$('.userid').val();
	//alert(userid);
	var depart_id=$('.depart_id').val();
	$('.header').show('blind',500);
	removeCurrentPage();
	var lastPage;
	var policy_option='';
	if(usertype != 'Subadmin'){
	 	policy_option ='<td width="10%">Options</td>';
	}

	$('#tablelist').append('<table width="100%" border="0" cellspacing="0" style="display:none;" cellpadding="0" class="list-circulardetails">'+
										  '<tr>'+
											'<td width="15%">Sl No</td>'+
											'<td width="15%">Title</td>'+
											'<td width="15%">Date</td>'+
											'<td width="10%">Download</td>'+
											policy_option+
										 '</tr>'+
										'</table>')	;

$.getJSON(hrURL + "managePolicies.php?action=viewpolicy&page="+pageno+"&"+searchString,function(data){
		
		var policy = data.policy;
		
		
		
		
		$.each(policy,function(index,policy){
		
		var policy_remove='';
			if(usertype != 'Subadmin'){
	 	policy_remove ='<td width="5%"><img data-id="'+policy.id+'" src="'+removeIcon+'" class="removeCircular"/></td>';
	}
		
		
		var circulardetails='<tr>'+
						'<td width="15%">'+k+'</td>'+
						'<td width="15%">'+policy.policie_title+'</td>'+
						'<td width="10%">'+ new Date(policy.policie_date).format("dd-mm-yyyy")+'</td>'+
						'<td width="15%"><a  href="'+hrURL+'download_circular.php?filename='+policy.policie_fileupload+'" title="'+policy.policie_fileupload+'" style="height:5px,width:5px" class="pro-icon-02">Download</a></td>'+
						policy_remove+
						
							 '</tr>';
	

				$('.list-circulardetails').append(circulardetails);	
				itemCount = policy.totalrows;
				lastPage  = policy.lastPage;
				
				k++;
				
			});
			
			$('.list-circulardetails').show('blind');
			$("#light-pagination").jui_pagination({
				totalPages: lastPage,
			});
		
		});
$(".list-circulardetails").css("display", "block");

}


function addforms(){
	$(".addpolicy").css("display", "none");	
	$("#policydiv").css("display", "none");
	$(".addcircular").css("display", "none");	
	$("#circulardiv").css("display", "none");
	$(".addform").css("display", "block");	
	$(".musteroll").css("display", "none")
	removeCurrentPage();
}
function viewform(e,pageno){
	
	 
		$("#policydiv").css("display", "none");
		$(".addpolicy").css("display", "none");
		$("#circulardiv").css("display", "none");
		$(".addcircular").css("display", "none");
		$(".addform").css("display", "none");
		$(".musteroll").css("display", "none");
	if(!pageno)
	pageno =1;
	
	var searchString = $('.pdtcircularSearchForm').serialize(); 
	
	
	if(pageno == 1 ){
			k=1; 
		 }else{
			k= ((pageno-1) * pageLimit)+1;
		 }
		 var tot = 0;

	var userid=$('.userid').val();
	var depart_id=$('.depart_id').val();
	$('.header').show('blind',500);
	removeCurrentPage();
	var lastPage;
	
	var form_option='';
	if(usertype != 'Subadmin'){
	 	form_option ='<td width="10%">Options</td>';
	}

	$('#tablelist').append('<table width="100%" border="0" cellspacing="0" style="display:none;" cellpadding="0" class="list-circulardetails">'+
										  '<tr>'+
											'<td width="15%">Sl No</td>'+
											'<td width="15%">Title</td>'+
											'<td width="15%">Date</td>'+
											'<td width="10%">Download</td>'+
											form_option+
											
										 '</tr>'+
										'</table>')	;

$.getJSON(hrURL + "manageForm.php?action=viewforms&page="+pageno+"&"+searchString,function(data){

		var forms = data.forms;
		
		var form_remove='';
			if(usertype != 'Subadmin'){
	 	form_remove ='<td width="5%"><img data-id="'+forms.id+'" src="'+removeIcon+'" class="removeCircular"/></td>';
		}
		
		$.each(forms,function(index,forms){
	
		var circulardetails='<tr>'+
						'<td width="15%">'+k+'</td>'+
						'<td width="15%">'+forms.form_title+'</td>'+
						'<td width="10%">'+ new Date(forms.form_date).format("dd-mm-yyyy")+'</td>'+
						'<td width="15%"><a  href="'+hrURL+'download_circular.php?filename='+forms.form_fileupload+'" title="'+forms.form_fileupload+'" style="height:5px,width:5px" class="pro-icon-02">Download</a></td>'+
						form_remove+
						
							 '</tr>';
	

				$('.list-circulardetails').append(circulardetails);	
				itemCount = forms.totalrows;
				lastPage  = forms.lastPage;
				
				k++;
				
			});
			
			$('.list-circulardetails').show('blind');
			$("#light-pagination").jui_pagination({
				totalPages: lastPage,
			});
		
		});
$(".list-circulardetails").css("display", "block");

}

function formsubmit(){
	
	//var dataString = $('#frm1').serialize();

removeCurrentPage();
	var formData = new FormData($('#add_form')[0]);
	//alert(hrURL);
	//alert(serviceURLHR);
    $.ajax({
        url: hrURL + 'manageForm.php?action=insert',  //Server script to process data
        type: 'POST',
        data: formData,
		processData: false,  // tell jQuery not to process the data
  		contentType: false ,  // tell jQuery not to set contentType
		success: function(data){
				//if(data=='success'){
				alert("Item successfully inserted.");
				window.location="circular-polcies.php#viewform";
				//window.location="list.html";
			//}
		}
	});	
}

function muster_roll(){
	$(".addpolicy").css("display", "none");	
	$("#policydiv").css("display", "none");
	$(".addcircular").css("display", "none");	
	$("#circulardiv").css("display", "none");
	$(".addform").css("display", "none");	
	$(".musteroll").css("display", "block");	
	
	removeCurrentPage();
}

function removeCircular(){
	

var checkstr =  confirm('are you sure you want to delete this?');
if(checkstr == true){
	
 var did = $(this).attr('data-id');
 
	$this = $(this);
	
	
	$.get(hrURL + "manageCircular.php?act=removeded&did="+did,function(){
		$this.parent().parent().remove();															 
	});
}else{
return false;
}

}

function removeTiming(){
	

var checkstr =  confirm('are you sure you want to delete this?');
if(checkstr == true){
	
 var did = $(this).attr('data-id');
 
 
	$this = $(this);
	
	$.get(hrURL + "manageReportime.php?act=removeded&did="+did,function(){
		$this.parent().parent().remove();															 
	});
}else{
return false;
}

}


function addtiming(){ 
	loadBranch();
	$(".addcircular").css("display", "block");	
	$(".list-circulardetails").css("display", "none");
	removeCurrentPage();
}
function viewtiming(e,pageno){
	
		$(".addcircular").css("display", "none");
		$(".list-circulardetails").css("display", "block");
	if(!pageno)
	pageno =1;
	
	var searchString = $('.pdtcircularSearchForm').serialize(); 
	
	
	if(pageno == 1 ){
			k=1; 
		 }else{
			k= ((pageno-1) * pageLimit)+1;
		 }
		 var tot = 0;

	var userid=$('.userid').val();
	var depart_id=$('.depart_id').val();
	$('.header').show('blind',500);
	removeCurrentPage();
	var lastPage;

	$('#tablelist').append('<table width="100%" border="0" cellspacing="0" style="display:none;" cellpadding="0" class="list-circulardetails">'+
										  '<tr>'+
											'<td width="15%">Sl No</td>'+
											'<td width="15%">Branch</td>'+
											'<td width="15%">Report Timing</td>'+
											'<td width="15%">Report Late Time</td>'+
											'<td width="10%">Half Day</td>'+
											'<td width="10%">Full Day</td>'+
											'<td width="10%">Edit</td>'+
											'<td width="10%">Delete</td>'+
											
										 '</tr>'+
										'</table>')	;

$.getJSON(hrURL + "manageReportime.php?action=viewtiming&page="+pageno+"&"+searchString,function(data){
		
		var timing = data.timing;
		
		console.log(timing);
		
		
		$.each(timing,function(index,timing){
			
		var circulardetails='<tr>'+
						'<td width="15%">'+k+'</td>'+
						'<td width="15%">'+timing.branch_name+'</td>'+
						'<td width="15%">'+timing.report_time+''+timing.time_in+'</td>'+
						'<td width="15%">'+timing.late_time+''+timing.time_in+'</td>'+
						'<td width="15%">'+timing.half_day+'</td>'+
						'<td width="15%">'+timing.full_day+'</td>'+
						'<td width="5%"><img data-id="'+timing.reptime_id+'" src="'+editIcon+'" class="editTiming"/></td>'+
						'<td width="5%"><img data-id="'+timing.reptime_id+'" src="'+removeIcon+'" class="removeTiming"/></td>'+
						
							 '</tr>';
	

				$('.list-circulardetails').append(circulardetails);	
				itemCount = timing.totalrows;
				lastPage  = timing.lastPage;
				
				k++;
				
			});
			
			$('.list-circulardetails').show('blind');
			$("#light-pagination").jui_pagination({
				totalPages: lastPage,
			});
		
		});
$(".list-circulardetails").css("display", "block");

}






///////////////////////////////////////////// Leave request management ////////////////////////////////
function leaveRequests(e,pageno){

	if(!pageno)
	pageno =1;
	
	
	var searchString = $('.pdtSearchForm').serialize(); 
	if(pageno == 1 ){
			k=1; 
		 }else{
			k= ((pageno-1) * pageLimit)+1;
		 }
		 var tot = 0;
	$(".searchpersonalPdt").css("display", "none");
	$(".searchPdt").css("display", "block");
	$(".designation").css("display", "block");
	$(".branch").css("display", "block");
	$(".imdatesupervisor").css("display", "block");
	var userid=$('.userid').val();
	var depart_id=$('.depart_id').val();
	$('.header').show('blind',500);
	removeCurrentPage();
	var lastPage;

	$('#tablelist').append('<table width="100%" border="0" cellspacing="0" style="display:none" cellpadding="0" class="list-leaverequests">'+
										  '<tr>'+
											'<td width="15%">Sl No</td>'+
											'<td width="15%">Employee</td>'+
											'<td width="15%">Designation</td>'+
											'<td width="10%">Leave From</td>'+
											'<td width="10%">Leave To</td>'+
											'<td width="12%">Leave Type</td>'+
											'<td width="28%">Reason</td>'+
											'<td width="14%">Imm.Supervisor</td>'+
											'<td width="6%">HR</td>'+
											
										 '</tr>'+
										'</table>')	;
	$.getJSON(hrURL + "manageLeaves.php?act=loadRequests&userid="+userid+"&page="+pageno+"&depart_id="+depart_id+"&"+searchString,function(data){
		var leaves = data.leaves;
		
		
		
		
		$.each(leaves,function(index,leaves){
			
			
		
		if(leaves.imd_status == 1)
		{
			viewstatus ='<img src="images/1388406658_ok-green.png" style="cursor:pointer" data-status="0" requestid="'+leaves.id+'"  title="Approved" class="approveLeave" width="20" height="20" />';
			
		}else{
			viewstatus ='<img src="images/1388407735_delete_64.png" style="cursor:pointer" data-status="1" requestid="'+leaves.id+'"  title="Pending" class="approveLeave" width="20" height="20" />';
			
		}	
		
		if(depart_id==3)
		{
		var HR_leav_class='HRapproveLeave';
			if(leaves.imd_status == 1)
			{
				viewstatus ='<img src="images/1388406658_ok-green.png" style="cursor:pointer" data-status="0"  title="Approved" requestid="'+leaves.id+'" class="noapproveLeave" width="20" height="20" />';
				
			}else{
				viewstatus ='<img src="images/1388407735_delete_64.png" style="cursor:pointer" data-status="1"  title="Pending" requestid="'+leaves.id+'" class="noapproveLeave" width="20" height="20" />';
				
			}
		}
		else
		{
		var HR_leav_class='HRLeave';
		}
		
		if(leaves.HRstatus == 1)
		{
			
			HRstatus ='<img src="images/1388406658_ok-green.png" style="cursor:pointer" data-status="0" requestid="'+leaves.id+'"  title="Approved" class="'+HR_leav_class+'" width="20" height="20" />';
		}else{
			
			HRstatus ='<img src="images/1388407735_delete_64.png" style="cursor:pointer" data-status="1" requestid="'+leaves.id+'"  title="Pending" class="'+HR_leav_class+'" width="20" height="20" />';
		}						   
	
		var leavedetails='<tr>'+
						'<td width="15%">'+k+'</td>'+
						'<td width="15%">'+leaves.e_fname+'</td>'+
						'<td width="15%">'+leaves.desig_name+'</td>'+
						'<td width="10%">'+ new Date(leaves.day_from).format("dd-mm-yyyy")+'</td>'+
						'<td width="10%">'+ new Date(leaves.day_to).format("dd-mm-yyyy")+'</td>'+
						'<td width="12%">'+leaves.title+'</td>'+
												'<td width="28%">'+leaves.reason+'</td>'+
												'<td width="14%">'+viewstatus+'</td>'+
												'<td width="6%">'+HRstatus+'</td>'+
												
											 '</tr>';
	

				$('.list-leaverequests').append(leavedetails);	
				itemCount = leaves.totalrows;
				lastPage  = leaves.lastPage;
				
				k++;
			});
			$('.list-leaverequests').show('blind');
			$("#light-pagination").jui_pagination({
				totalPages: lastPage,
			});
			
			
			
	});
	
	
	
}



function newLeaveRequest(){
if($('.newLeaveApplicationForm').length){
		
	}else{
$('.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">Employee</td>'+
						'<td><select name="employees" id="employeesList">'+
						'</select> </td>'+
					  '</tr>'+
					  '<tr>'+
						'<td class="categories">Leave From</td>'+
						'<td><input type="text" name="day_from" id="day_from" class="my_date" /></td>'+
					  '</tr>'+
					  '<tr>'+
						'<td class="categories">Leave To</td>'+
						'<td><input type="text" name="day_to" id="day_to" class="my_date" /></td>'+
					  '</tr>'+
					  '<tr>'+
						'<td class="categories">Leave Type</td>'+
						'<td><select name="leave_id" id="leaveList">'+
						'</select>    </td>'+
					  '</tr>'+
					  '<tr>'+
						'<td class="categories">Reason</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();
			
			
			
$('.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/1388406658_ok-green.png','title':'Approved','data-status':'0'});
				}else{
					$this.attr({'src':'images/1388407735_delete_64.png','title':'Pending','data-status':'1'});
				}
				
				
				
		});
		
	
}
function HRchangeRequestStatus(){
		var $this = $(this);
		var newStatus	 = $this.attr('data-status');
		var requestid	= $this.attr('requestid');
		
		
		$.get(hrURL + "manageLeaves.php?act=HRchangeStatus&reqid="+requestid+"&set="+newStatus,function(){
				
				if(newStatus == 1){
					$this.attr({'src':'images/1388406658_ok-green.png','title':'Approved','data-status':'0'});
				}else{
					$this.attr({'src':'images/1388407735_delete_64.png','title':'Pending','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">Payment Method</td>'+
						'<td>'+
						'<select name="paymentThrough" class="paymentThrough">'+
						'</select'+
						'</td>'+
					  '</tr>'+
					  '<tr>'+
						'<td class="referance_label">Referance</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(); })
	});
}


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>');
							
		});	
	});
}


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>');
							
		});	
	});
}

loadDesignation();

function loadDesignation(){
	
	$.getJSON(serviceURLHR + 'designations.php?action=load',function(data){
		designation = data.designation;
		
		$.each(designation, function(index, designation) {
									 
							$('#designation').append('<option value="'+designation.desig_id+'">'+designation.desig_name+'</option>');
							
		});	
	});
}


function printPaySlip(){
	
	$('.paymentSummery').append(  '<tr class="setHt">'+
                                    '<td width="50%" height="250"></td>'+
                                    '<td></td>'+
                                  '</tr>'+
								  
								  '<tr class="signature">'+
                                    '<td width="50%" height="150">Employer\'s Signature</td>'+
                                    '<td align="right">Employee\'s Signature</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(){
	selected =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){
			selected.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>');
		});
		$('#leaveList').loadLeaves();
	});
}



/////////////////////// 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( (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>');	
		}
	}



}
/////////////////////////////////////////// Holiday Calendar ////////////////////////////////////////
function holidayCalendar(){
	removeCurrentPage();
	$("#tablelist").append('<table class="calendarHolder" style="display:none"><tr></td><div id="calendar"></div></td></tr></table>');
		var calendar = $('#calendar').fullCalendar({
		
		//	editable: true,
			
			eventSources: [ {url:hrURL + "holidatManagement.php?act=list"}],
			
			eventDrop: function(event, delta) {
			//	alert(event.title + ' was moved ' + delta + ' days\n' +
					//'(should probably update your database)');
				date = new Date(event.start).format("yyyy-mm-dd");
				$.get(hrURL + "holidatManagement.php?act=update&title"+event.title+"&start="+date+"&id="+event.id);
				
			},
			selectable: true,
			selectHelper: true,
			select: function(start, end, allDay) {
				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,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)
						$('#calendar').fullCalendar('removeEvents', calEvent._id);
				 }
			},
			
			loading: function(bool) {
				if (bool) $('#loading').show();
				else $('#loading').hide();
			}
			
		});
	$('.calendarHolder').show('blind',500);
	//calendar.fullCalendar()
	
}

////////////////////////////////////////////////////////////////////  REPORTS  //////////////////////////////////////////////////////
function paymentHistory(){
	
	alert('das');
	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"){
					$('.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 paidSalaryReport(){
	
	
}

function deductionAndEarningsReport(){
	
	
}









///////////////////////////////////////////////EVENT MANAGEMENT//////////////////////////////////////////
jQuery('.payCurrentSalary').live('click',salaryPayment);
jQuery('.addNewLeaves').live('click',addNewLeaves);
jQuery('.saveLeave').live('click',saveLeave);
jQuery('.addNewDeduction').live('click',addnewDeduction);
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('.HRapproveLeave').live('click',HRchangeRequestStatus);
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('.addNewpersonalLeaveRequest').live('click',newpersonalLeaveRequest);
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('.applypersonalLeave').live('click',savepersonalLeaveRequest);
jQuery('.cancelpersonalApplication').live('click',function(){ $('.newpersonalLeaveApplicationWindow').hide('blind',300,function(){ $(this).remove()}); });
jQuery('.paymentHistorypaymentmonth').live('change',paymentHistory);
jQuery('.paymentHistorypaymentyear').live('change',paymentHistory);


$("#printdiv").print();
//////////////////////////////////////////////  Common popup function //////////////////////////////////

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 
}