/*****************************/
/*     Created By Jithin     */
/*          19-11-2013       */
/*****************************/

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

/////////////////////////////////////////  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 = 5;

$(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: 1,
				onChangePage:window[hash],
			});
			$('.newpersonalLeaveApplicationForm').hide('blind',500,function(){$(this).remove();});
			
		}else{
			$('li[data-page="'+currentPage+'"]').addClass('menu-selected');
			if(hash){
				//window.location.hash =	currentPage;currentPage =hash; 
			}
			
			//currentPage =currentPage;
			
		}
	}else{
		window.location.hash = "pfRequests";
	}
}
$('#prdaddate').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();	
	});

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

jQuery('.registerwages').live('click',registerwages);
function registerwages(){
	window.location="register-wages.php#registerwages";
}

jQuery('.leave_Requests').live('click',leave_Requests);
function leave_Requests(){
	window.location="leave-request.php#leaveRequests";	
}

jQuery('.personal_leave').live('click',personal_leave);
function personal_leave(){
	window.location="leave-request.php#personalleave";	
}




jQuery('.searchPdt').live('click',function(){ leaveRequests('1','') });
jQuery('.searchpersonalPdt').live('click',function(){ personalleave('1','') });
jQuery('.searchPF').live('click',function(){ pf_request('1','') });

jQuery('.leaveList').live('change',function(){ balanceleave() });
jQuery('#day_from').live('change',function(){ checkbalanceleave() });
jQuery('#day_to').live('change',function(){ checkbalanceleave() });
function change(page){
location.href=page;
}
function removeCurrentPage(){

$('.paymentMethod').remove();
$('#tablelist table').hide('blind',500,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>');
							
		});	
	});
}




///////////////////////// 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 pf_request(e,pageno){
	alert(pageno);
	if(!pageno)
	pageno =1;
	
	
	var searchString = $('.pFSearchForm').serialize(); 
	
	//alert(searchString);
	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 userid=$('.userid').val();var user_name=$('.user_name').val();var depart_id=$('.depart_id').val();
	*/
	removeCurrentPage();
	var lastPage;

	$('#tablelist').append('<table width="100%" border="0" cellspacing="0" style="display:none" cellpadding="0" class="list-leaverequests">'+
										  '<tr>'+
											'<td width="15%"><translate>Sl No</translate></td>'+
											'<td width="15%"><translate>Employee</translate></td>'+
											'<td width="10%"><translate>Month</translate></td>'+
											'<td width="10%"><translate>Year</translate></td>'+
											'<td width="10%"><translate>Employee PF</translate></td>'+
											'<td width="12%"><translate>Company Contribution PF</translate></td>'+
													
										 '</tr>'+
										'</table>')	;
		//$.getJSON(hrURL + "manageLeaves.php?act=loadRequests&userid="+userid+"&page="+pageno+"&depart_id="+depart_id+"&"+searchString,function(data){

	$.getJSON(hrURL + "manageLeaves.php?act=PFRequests&page="+pageno+"&"+searchString,function(data){
		var pfdetails = data.get_pfdetails;
		
		$.each(pfdetails,function(index,pfdetails){
		
		var dates = pfdetails.pay_period;
		var mnt = new Date(dates).format("mmmm");
		var year = new Date(dates).format("yyyy");
		
		var pf_viewdetails='<tr>'+
						'<td width="15%">'+k+'</td>'+
						'<td width="15%">'+pfdetails.e_fname+'</td>'+
						'<td width="15%">'+mnt+'</td>'+
						'<td width="15%">'+year+'</td>'+
						'<td width="15%">'+pfdetails.cmp_pf+'</td>'+
						'<td width="28%">'+pfdetails.emp_pf+'</td>'+
						'</tr>';	

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








///////////////////////////////////////////////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('.Cancellleave').live('click',Cancellleave);
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()});
																																				  $(".cantcancel").each(function(){
		 $(this).attr('class', 'Cancellleave');
	});});
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 
}