
var loadingOverlay = document.getElementById('loading-overlay');
//console.log("before win load", loadingOverlay);
window.addEventListener('load', function () {
	var loadingOverlay = document.getElementById('loading-overlay');
	var loadingIcon = document.getElementById('loading-icon');
	console.log("Loading windows");
	var spinner = new Image();
	spinner.src = 'Spinner.svg';
	// Set the background image of the loading icon once the spinner image has loaded
	spinner.addEventListener('load', function () {
		loadingIcon.style.backgroundImage = 'url(Spinner.svg)';
	});
});
window.addEventListener('load', function () {
	hideLoadingSpinner();
});
function showLoadingSpinner() {
	// Show the loading spinner
	//console.log("showing spinner", loadingOverlay);
	loadingOverlay.style.display = 'block';
}

function hideLoadingSpinner() {
	// Hide the loading spinner\
	//console.log("hiding spinner", loadingOverlay);
	loadingOverlay.style.display = 'none';
}
function workManager(url) {
	//loadingOverlay.style.display = 'block';
	showLoadingSpinner();
	document.getElementById("center1").style.display = "block";
	//console.log("URl=" + url)

	fetch(url)
		.then(response => {
			//console.log(response);
			if (!response.ok) {
				hideLoadingSpinner();
				throw new Error('Request failed with status: ' + response.status);
			}
			//loadingOverlay.style.display = 'none';
			hideLoadingSpinner();
			return response.json();
		})
		.then(data => {
			//console.log('Response:', data);

			// Loop through the data and populate select options
			var select = document.getElementById('empCode');
			data.forEach(employee => {
				//console.log('employee:', employee.name, employee.empcode);
				var option = document.createElement('option');
				option.value = employee.empcode;
				option.textContent = employee.name + " " + employee.empcode;
				select.appendChild(option);

			});
		})
		.catch(error => console.log(error));
}
function planView() {
	//loadingOverlay.style.display = 'block';
	//showLoadingSpinner();
	console.log("getting plan view");
	//window.location.href = "/ibase/planview";
	var xhr = new XMLHttpRequest();
	xhr.open('GET', '/ibase/planview', true);
	xhr.onreadystatechange = function () {
		if (xhr.readyState === 4 && xhr.status === 200) {
			console.log("getting plan view success....");
			// Redirect to the new page
			window.location.href = '/ibase/webitm/jsp/workManager/planview.jsp';
		}
		else {
			console.log("getting plan view failed");
		}
	};
	xhr.send();
}


var responseData = new Array();
var totalRowCount = 0;
var offset=0;
var limit=10;
var reportType="";
function viewFeedback(totalCount) {
	showLoadingSpinner();
	console.log("calling viewFeedback");
	//console.log("offset=",offset);
	//console.log("limit=",limit);
	
	const tableView = document.getElementById('tableView');
	const calendarView = document.getElementById('calendarView');
	tableView.style.display = "block";
	calendarView.style.display = "none";

	if (view() == 1) {
		var dateFrom = $('#datepicker').val();
		var dateTo = $('#datepickerTo').val();
		var requestid = $('#requestid').val();
		
		//dateFrom="01-Jan-2020";
		//dateTo="31-Jan-2020";
		console.log("date from=",dateFrom);
		console.log("date To=",dateTo);
		
		
		console.log("viewFeedback page==>",page);
		console.log("viewFeedback offset==>",offset);
		console.log("viewFeedback limit==>",limit);
		empCode = getSelectedEmployee();
		$.ajax({
			type: 'POST',
			data:
			{
				empCode: empCode,
				dateFrom: dateFrom,
				dateTo: dateTo,
				requestid: requestid,
				offset:offset,
				limit:limit,
				totalRecord:totalCount,
				action: "feedback"
			},
			//url:'/ibase/servlet/emp',
			url: '/ibase/emp',
			success: function (response) {
				//console.log("first response ",response)
				if (response == "No data to show") {
					responseData = response;
					DeleteRows();
					hideLoadingSpinner();
					alert(response);
				} else {
					//console.log(response);
					if(totalCount==='y'){
						reportType="feedback";
						offset=0;
						limit=10;
						totalRowCount = parseInt(response);	
						createPaginationDiv(totalRowCount);
					}else{
					writeTable(response);
					hideLoadingSpinner();
					}
				}
				hideLoadingSpinner();
			},
			error: function (data) {
				jQuery('.alert').show();
				jQuery('.alert').html(data.fail);
				hideLoadingSpinner();
			}
		});
	} else {
		DeleteRows();
		hideLoadingSpinner();
	}
	//loadingOverlay.style.display='none';
	//hideLoadingSpinner();


}
const element = document.querySelector(".pagination ul");
let totalPages = 20;


let page = 1;
function createPaginationDiv(totalRow){
	//viewFeedback('n');
	
	//calling function with passing parameters and adding inside element which is ul tag
	totalPages = Math.trunc(totalRow/10);
	offset=0;
	limit=10;
	page=1;
	console.log("totalPages in createPaginationDiv",totalPages);
	console.log("limit",limit);
	console.log("offset",offset);
	//console.log("page in createPaginationDiv",page);
	element.innerHTML = createPagination(totalPages, page);	
}

function createPagination(totalPages, page){
	console.log("totalPages=",totalPages);
	console.log("Page=",page);
	console.log("Total Record=",totalRowCount);
	offset=(page-1)*10;
	limit=10;
	
	if(reportType==="feedback"){
		viewFeedback('n');
	}
	else if(reportType==="plan"){
		console.log("limit ",limit);
		console.log("offset ",offset);
		console.log("page ",page);
		
		getPlanReport('n');
	}
  let liTag = '';
  let active;
  let beforePage = page - 1;
  let afterPage = page + 1;
  if(page > 1){ //show the next button if the page value is greater than 1
    liTag += `<li class="btn prev" onclick="createPagination(totalPages, ${page - 1})"><span><i class="fas fa-angle-left"></i> Prev</span></li>`;
  }

  if(page > 2){ //if page value is less than 2 then add 1 after the previous button
    liTag += `<li class="first numb" onclick="createPagination(totalPages, 1)"><span>1</span></li>`;
    if(page > 3){ //if page value is greater than 3 then add this (...) after the first li or page
      liTag += `<li class="dots"><span>...</span></li>`;
    }
  }

  // how many pages or li show before the current li
  if (page == totalPages) {
    beforePage = beforePage - 2;
  } else if (page == totalPages - 1) {
    beforePage = beforePage - 1;
  }
  // how many pages or li show after the current li
  if (page == 1) {
    afterPage = afterPage + 2;
  } else if (page == 2) {
    afterPage  = afterPage + 1;
  }

  for (var plength = beforePage; plength <= afterPage; plength++) {
    if (plength > totalPages) { //if plength is greater than totalPage length then continue
      continue;
    }
    if (plength == 0) { //if plength is 0 than add +1 in plength value
      plength = plength + 1;
    }
    if(page == plength){ //if page is equal to plength than assign active string in the active variable
      active = "active";
    }else{ //else leave empty to the active variable
      active = "";
    }
    liTag += `<li class="numb ${active}" onclick="createPagination(totalPages, ${plength})"><span>${plength}</span></li>`;
  }

  if(page < totalPages - 1){ //if page value is less than totalPage value by -1 then show the last li or page
    if(page < totalPages - 2){ //if page value is less than totalPage value by -2 then add this (...) before the last li or page
      liTag += `<li class="dots"><span>...</span></li>`;
    }
    liTag += `<li class="last numb" onclick="createPagination(totalPages, ${totalPages})"><span>${totalPages}</span></li>`;
  }

  if (page < totalPages) { //show the next button if the page value is less than totalPage(20)
    liTag += `<li class="btn next" onclick="createPagination(totalPages, ${page + 1})"><span>Next <i class="fas fa-angle-right"></i></span></li>`;
  }
  element.innerHTML = liTag; //add li tag inside ul tag
  return liTag; //reurn the li tag
}
function clearPagination(){
	console.log("clearing pagination");
	var pagination_div = document.getElementById("pagination");
	pagination_div.innerHTML="";
}

function getPlanReport(totalCount) {
	showLoadingSpinner();
	if (view() == 1) {
		createPlanTable();
		//clearPagination();
		const tableView = document.getElementById('tableView');
		tableView.style.display = "block";
		const calendarView = document.getElementById('calendarView');
		calendarView.style.display = "none";

		const chart = document.getElementById('gantt-chart');
		chart.style.display = "none";

		var dateFrom = $('#datepicker').val();
		var dateTo = $('#datepickerTo').val();
		var requestid = $('#requestid').val();
		dateFrom="01-Jan-2020";
		//dateTo="31-Jan-2020";
		empCode = getSelectedEmployee();
		var isTotal=totalCount;
		console.log("Offset==>",offset);
		console.log("Limit==>",limit);
		console.log("Page==>",page);
		$.ajax({

			type: 'POST',

			data: {
				empCode: empCode,
				dateFrom: dateFrom,
				dateTo: dateTo,
				requestid: requestid,
				totalRecord:isTotal,
				offset:offset,
				limit:limit,
				action: "plan"
			},
			url: '/ibase/emp',
			success: function (response) {
				if (response == "No data to show") {
					DeleteRows();
					hideLoadingSpinner();
					alert(response);
				} else {
					if(isTotal=="y"){
						totalRowCount = parseInt(response);	
						console.log("Total Plan records=",totalRowCount);
						reportType="plan";
						offset=0;
						limit=10;
						createPaginationDiv(totalRowCount);
						hideLoadingSpinner();	
					}else{
						writePlanTable(response);
						hideLoadingSpinner();
					}
				}
			},
			error: function (data) {
				jQuery('.alert').show();
				jQuery('.alert').html(data.fail);
				hideLoadingSpinner();
			}
		});
	}
	else {
		DeleteRows();
		hideLoadingSpinner();
	}
}

function writePlanTable(response) {
	showLoadingSpinner();
	var table = document.getElementById('table');
	DeleteRows();
	for (var i in response) {

		var report = response[i]
		//responseData.push(report);
		var row = table.insertRow(1);

		var cellPerson = row.insertCell(0);
		cellPerson.innerHTML = report.person;

		var cellDate = row.insertCell(1);
		cellDate.innerHTML = report.date;

		var cellRequestid = row.insertCell(2);
		cellRequestid.innerHTML = report.requestid;

		var cellDescription = row.insertCell(3);
		cellDescription.innerHTML = report.description;

		var cellTime = row.insertCell(4);
		cellTime.innerHTML = report.time;

		var cellActiondtl = row.insertCell(5);
		cellActiondtl.innerHTML = report.actiondtl;
		hideLoadingSpinner();
	}

}
function writeTable(response) {
	showLoadingSpinner();
	//console.log("response Type=" + typeof response)
	console.log("response data=",response)
	var table = document.getElementById('table');
	table.innerHTML = "";
	var row = table.insertRow(0);


	var cellPerson = row.insertCell(0);
	cellPerson.innerHTML = "Person";
	cellPerson.style.background = "#009879";
	cellPerson.style.color = "#ffffff";

	var cellDate = row.insertCell(1);
	cellDate.innerHTML = "Date";
	cellDate.style.background = "#009879";
	cellDate.style.color = "#ffffff";

	var cellRequestid = row.insertCell(2);
	cellRequestid.innerHTML = "Request ID";
	cellRequestid.style.background = "#009879";
	cellRequestid.style.color = "#ffffff";

	var cellDescr = row.insertCell(3);
	cellDescr.innerHTML = "Descr";
	cellDescr.style.background = "#009879";
	cellDescr.style.color = "#ffffff";

	var cellStatus = row.insertCell(4);
	cellStatus.innerHTML = "Status";
	cellStatus.style.background = "#009879";
	cellStatus.style.color = "#ffffff";

	var cellActiondtl = row.insertCell(5);
	cellActiondtl.innerHTML = "Action DTL";
	cellActiondtl.style.background = "#009879";
	cellActiondtl.style.color = "#ffffff";

	var cellStartdate = row.insertCell(6);
	cellStartdate.innerHTML = "Plan Start Date";
	cellStartdate.style.background = "#009879";
	cellStartdate.style.color = "#ffffff";

	var cellTime = row.insertCell(7);
	cellTime.innerHTML = "STD TIME";
	cellTime.style.background = "#009879";
	cellTime.style.color = "#ffffff";

	var cellTimespend = row.insertCell(8);
	cellTimespend.innerHTML = "TIME SPEND";
	cellTimespend.style.background = "#009879";
	cellTimespend.style.color = "#ffffff";

	var cellAction = row.insertCell(9);
	cellAction.innerHTML = "Action";
	cellAction.style.background = "#009879";
	cellAction.style.color = "#ffffff";



	DeleteRows();
	var index = 1;
	for (var i in response) {

		var report = response[i]
		responseData[i] = report;
		var row = table.insertRow(1);
		row.setAttribute("id", index);
		index = index + 1;
		// console.log(row)
		var cellPerson = row.insertCell(0);
		cellPerson.innerHTML = report.person;


		var cellDate = row.insertCell(1);
		cellDate.innerHTML = report.date;


		var cellRequestid = row.insertCell(2);
		cellRequestid.innerHTML = report.requestid;

		var cellDescription = row.insertCell(3);
		cellDescription.innerHTML = report.description;
		//  console.log(report.description);
		var cellStatus = row.insertCell(4);
		cellStatus.innerHTML = report.status;


		var cellActiondtl = row.insertCell(5);
		cellActiondtl.innerHTML = report.actiondtl;

		var cellStartDate = row.insertCell(6);
		cellStartDate.innerHTML = report.startdate;

		var cellStdtime = row.insertCell(7);
		cellStdtime.innerHTML = report.stdtime;

		var cellSpendtime = row.insertCell(8);
		cellSpendtime.innerHTML = report.timespend;

		//create send mail buttin
		var button = document.createElement('input');
		button.type = "button";
		button.className = "button";
		button.value = "Send Status";
		button.innerText = "Status Update"
		button.onclick = function (e) {
			var empcode;//,requestid,description,actiondtl,stdtime,startdate,timespend,status;
			var requestid;
			var description;
			var actiondtl;
			var stdtime;
			var startdate;
			var timespend;
			var status;

			var table = document.getElementById('table');
			var index = e.target.parentNode.id;


			for (i = 1; i < table.rows.length; i++) {

				if (table.rows.item(i).id == index - 1) {
					var objCells = table.rows.item(i).cells;
					empcode = objCells.item(0).innerHTML;
					requestid = objCells.item(2).innerHTML;
					description = objCells.item(3).innerHTML;
					status = objCells.item(4).innerHTML;
					actiondtl = objCells.item(5).innerHTML;
					startdate = objCells.item(6).innerHTML;
					stdtime = objCells.item(7).innerHTML;
					timespend = objCells.item(8).innerHTML;
				}
			}

			//Modal Logic
			var modal = document.getElementById("modal");
			modal.style.display = "block";
			var span = document.getElementsByClassName("close")[0];
			span.onclick = function () {
				modal.style.display = "none";
			}

			document.getElementById("requestidhead").innerHTML = requestid;
			document.getElementById("requestidheadtxt").value = requestid;

			var emp = empcode.substring(empcode.indexOf("(") + 1, empcode.indexOf(")"))
			document.getElementById("personhead").innerHTML = empcode;
			document.getElementById("personheadtxt").value = emp;

			document.getElementById("descriptionhead").innerHTML = description;
			document.getElementById("descriptionheadtxt").value = description;

			document.getElementById("actiondtltxt").value = actiondtl;
			document.getElementById("stdtimetxt").value = stdtime;
			document.getElementById("startdatetxt").value = startdate;
			document.getElementById("timespendtxt").value = timespend;
			
		}


		var buttonReq = document.createElement('input');
		buttonReq.type = "button";
		buttonReq.className = "button";
		buttonReq.value = "Request Status";
		buttonReq.innerText = "Request Status";
		buttonReq.style.marginTop = "10px";
		buttonReq.onclick = function (e) {
			var empcode;
			var requestid;
			var description;
			var actiondtl;
			var stdtime;
			var startdate;
			var timespend;
			var status;

			var table = document.getElementById('table');
			var index = e.target.parentNode.id;


			for (i = 1; i < table.rows.length; i++) {

				if (table.rows.item(i).id == index - 1) {
					var objCells = table.rows.item(i).cells;
					empcode = objCells.item(0).innerHTML;
					requestid = objCells.item(2).innerHTML;
					description = objCells.item(3).innerHTML;
					actiondtl = objCells.item(5).innerHTML;
					startdate = objCells.item(6).innerHTML;
					stdtime = objCells.item(7).innerHTML;
					timespend = objCells.item(8).innerHTML;
					status = objCells.item(4).innerHTML;
				}
			}
			//console.log(empcode, requestid, description, actiondtl, stdtime, startdate, timespend, status);
			var modal = document.getElementById("modalReq");
			modal.style.display = "block";
			var span = document.getElementById("closeReq");
			span.onclick = function () {
				modal.style.display = "none";
			}


			document.getElementById("requestidheadReq").innerHTML = requestid;
			document.getElementById("requestidheadtxtReq").value = requestid;

			var emp = empcode.substring(empcode.indexOf("(") + 1, empcode.indexOf(")"))
			document.getElementById("personheadReq").innerHTML = empcode;
			document.getElementById("personheadtxtReq").value = emp;

			document.getElementById("descriptionheadReq").innerHTML = description;
			document.getElementById("descriptionheadtxtReq").value = description;

			document.getElementById("actiondtltxtReq").value = actiondtl;
			document.getElementById("stdtimetxtReq").value = stdtime;
			document.getElementById("startdatetxtReq").value = startdate;
			document.getElementById("timespendtxtReq").value = timespend;

			getCurrentStatus(requestid, emp);
		}

		var cellButton = row.insertCell(9);
		cellButton.appendChild(button);

		cellButton.appendChild(buttonReq);
		cellButton.setAttribute("id", index);
	}
hideLoadingSpinner();
}
function getCurrentStatus(requestid, empcode) {
	//console.log("requestid to Ajax " + requestid);
	$.ajax({
		type: 'POST',
		data: {
			requestid: requestid,
			empcode: empcode,
			action: "currentStatus"
		},
		url: '/ibase/emp',
		success: function (response) {
			var res = response.split(" ");
			//document.getElementById('currentStatus').value=res[1];
			document.getElementById('currentStatus').innerHTML = res[1];

			document.getElementById('emailTo').value = res[0];
		},
		error: function (data) {
			jQuery('.alert').show();
			jQuery('.alert').html(data.fail);
		}
	});

}

function DeleteRows() {
	var table = document.getElementById("table");
	var rowCount = table.rows.length;
	for (var i = rowCount - 1; i > 0; i--) {
		table.deleteRow(i);
	}
}
function getSelectedEmployee() {
	var selected = [];
	for (var option of document.getElementById('empCode').options) {
		if (option.selected) {
			if (option.value == 1) {
				document.getElementById('selected').innerHTML = ("Selected Employee: All");
				selected.push(" All");
				return selected;
			}
			selected.push(option.value);
		}
	}
	return selected;
}
function getFirstDay() {
	var date = new Date();
	console.log("First Date=",new Date(date.getFullYear(), date.getMonth(), 1));
	return new Date(date.getFullYear(), date.getMonth(), 1);
}
function getLastDay() {
	var date = new Date();
	console.log("Last Date=",new Date(date.getFullYear(), date.getMonth() + 1, 0));
	return new Date(date.getFullYear(), date.getMonth() + 1, 0);
}

$(function () {
	$("#datepicker").datepicker({ dateFormat: 'dd-M-yy' }).datepicker("setDate", getFirstDay());

});
$(function () {

	$("#datepickerTo").datepicker({ dateFormat: 'dd-M-yy' }).datepicker("setDate", getLastDay());

});

function showPlanCalendarView() {
	if (view() == 1) {
		showLoadingSpinner();
		const tableView = document.getElementById('tableView');
		const calendarView = document.getElementById('calendarView');
		const chart = document.getElementById('gantt-chart');
		var dateFrom = $('#datepicker').val();
		var empcode = getSelectedEmployee();
		var date = new Date(dateFrom);
		tableView.style.display = "none";
		calendarView.style.display = "block";
		chart.style.display = "none";

		var firstDate = new Date(date.getFullYear(), date.getMonth(), 1);
		var lastDate = new Date(date.getFullYear(), date.getMonth() + 1, 0);
		//var resp = getPlanCalendarData(empcode, dateFrom);

		//const result = resp.responseJSON;
		
		$.ajax({
		type: 'POST',
		//async: false,
		data: {
			empcode: empcode,
			date: dateFrom,
			action: 'plancalendar'
		},
		url: '/ibase/emp',
		success: function (response) {
			if(Object.keys(response).length===0){
				
				alert("No Data To Show");
			}
			else
			{
				writePlanCalendarView(response);
			}
			hideLoadingSpinner();
		},
		error: function (data) {
			jQuery('.alert').show();
			jQuery('.alert').html(data.fail);
			hideLoadingSpinner();
		}
	});
		
		
		
		
		
		
		
		
		
		
		/*if (Object.keys(resp.responseJSON).length === 0) {
			calendarView.style.display = "none";
			tableView.style.display = "block";
			alert("No data");
			return;
		}*/

		
	}

}
function writePlanCalendarView(result)
{
	const tableView = document.getElementById('tableView');
		const calendarView = document.getElementById('calendarView');
		const chart = document.getElementById('gantt-chart');
		var dateFrom = $('#datepicker').val();
		var empcode = getSelectedEmployee();
		var date = new Date(dateFrom);
		tableView.style.display = "none";
		calendarView.style.display = "block";
		chart.style.display = "none";

		var firstDate = new Date(date.getFullYear(), date.getMonth(), 1);
		var lastDate = new Date(date.getFullYear(), date.getMonth() + 1, 0);

	
	
	
	
	
	var start = firstDate.getDay();//get week no of starting date

		if (start == 0)
		 {
			start = 6;
		}
		else start = start - 1;
		var d = firstDate;
		for (let i = 0; i < lastDate.getDate() + start; i++)
		{
			if (i >= start)
			{
				//console.log(d);
				var dayDiv = document.getElementById(i);
				dayDiv.innerHTML = "";
				var datestr = ("0" + (d.getDate())).slice(-2) + "-" + d.toLocaleString('default', { month: 'short' }).toUpperCase() + "-" + d.getFullYear();
				var dateLabel = document.createElement('label');
				dateLabel.setAttribute('class', 'dateLabel');

				dateLabel.innerHTML = datestr;
				var header = document.createElement('div');
				header.appendChild(dateLabel);
				dayDiv.appendChild(header);
				var linebreak = document.createElement("br");
				dayDiv.appendChild(linebreak);

				if (result[datestr] !== undefined) 
				{
					for (let j = 0; j < result[datestr].length; j++)
					{
						let plan = result[datestr][j];
						//console.log(plan.name)
						var requestLink = document.createElement('a');
						requestLink.setAttribute('class', i);
						requestLink.setAttribute('id', 'link');
						requestLink.setAttribute('href', '#');
						requestLink.addEventListener('click', function ()
						{
							document.getElementById('requestid').value = plan.requestid;
							offset=0;
							limit=10;
							getPlanReport('y');
							//this.preventDefault();
						});
						var linktext = plan.name + "\n" + plan.requestid + "\nEffort: " + plan.time;
						if (plan.name == "")
						{
							linktext = plan.requestid + "\nEffort: " + plan.time;
						}
						requestLink.innerText = linktext
						dayDiv.appendChild(requestLink);

						var linebreak = document.createElement("br");
						dayDiv.appendChild(linebreak);
					}
				}
				d.setDate(d.getDate() + 1);
			} else
				console.log(i);

		}
}

 function showCalendar() {

	showLoadingSpinner();
	
	if (view() == 1) {

		const tableView = document.getElementById('tableView');
		const calendarView = document.getElementById('calendarView');
		tableView.style.display = "none";
		calendarView.style.display = "block";
		var dateFrom = $('#datepicker').val();

		//var selected = document.getElementById('selected').innerHTML;
		//var selectedEmp = selected.split(":");
		var empcode = getSelectedEmployee();
		//console.log("empcode", empcode);
		
		//var resp = getCalendar(empcode, dateFrom);
		//console.log(resp);
		
		$.ajax({
		type: 'POST',
		//async: false,
		data: {
			empcode: empcode,
			date: dateFrom,
			action: "feedbackcalendar"
		},
		url: '/ibase/emp',
		success: function (response) {
			console.log("inline response=",response);
			console.log("inline response length=",response.length);
			if(Object.keys(response).length===0){
				alert("No Data To Show");
			}
			else if(response.length==0){
				alert("No Data To Show");
				
			}
			else{
			addEmptyMonth(response);
			
			}
			hideLoadingSpinner();
			
		},
		error: function (data) {
			jQuery('.alert').show();
			jQuery('.alert').html(data.fail);
			hideLoadingSpinner();
		}
	});
		
		
		
		
	
		
		
		
		
				
	/*	console.log("final response=",resp);
		//console.log(typeof resp.responseJSON)
		if (Object.keys(resp.responseJSON).length === 0) {
			//console.log("resp=",resp)
			calendarView.style.display = "none";
			tableView.style.display = "block";
			alert("No data");
		} else{
			addEmptyMonth(resp);
			}*/
	}
	else {
		//hideLoadingSpinner();
	}
	
	

}
function getPlanCalendarData(empcode, date) {
	console.log("calling getPlanCalendarData")
	showLoadingSpinner();
	return $.ajax({
		type: 'POST',
		async: false,
		data: {
			empcode: empcode,
			date: date,
			action: 'plancalendar'
		},
		url: '/ibase/emp',
		success: function (response) {
			hideLoadingSpinner();
		},
		error: function (data) {
			jQuery('.alert').show();
			jQuery('.alert').html(data.fail);
			hideLoadingSpinner();
		}
	});
}

function getCalendar(empcode, date) {
	showLoadingSpinner();

	return $.ajax({
		type: 'POST',
		async: false,
		data: {
			empcode: empcode,
			date: date,
			action: "feedbackcalendar"
		},
		url: '/ibase/emp',
		success: function () {
			// console.log(response)
			hideLoadingSpinner();
			// addEmptyMonth(response);
		},
		error: function (data) {
			jQuery('.alert').show();
			jQuery('.alert').html(data.fail);
			hideLoadingSpinner();
		}
	});}

















function addEmptyMonth(response) {
	showLoadingSpinner();
	//console.log(response);
	//const result = response.responseJSON;
	const result = response;
	console.log("result to adding months=",result);
	
	var selected = document.getElementById('selected').innerHTML;
	var selectedEmp = selected.split(":");
	var empcode = selectedEmp[1].split(" ")[0];
	var dateFrom = $('#datepicker').val();
	var date = new Date(dateFrom);
	var table = document.getElementById('calendarTable');

	var firstDate = new Date(date.getFullYear(), date.getMonth(), 1);
	var lastDate = new Date(date.getFullYear(), date.getMonth() + 1, 0);
	var start = firstDate.getDay();
	var d = firstDate;
	var lastDay = lastDate.getDate();
	if (start == 0) {

		start = 6;
	}
	else start = start - 1;
	for (let i = 0; i < lastDate.getDate() + start; i++) {
		if (i >= start) {
			var dayDiv = document.getElementById(i);
			dayDiv.innerHTML = "";
			var datestr = ("0" + (d.getDate())).slice(-2) + "-" + d.toLocaleString('default', { month: 'short' }).toUpperCase() + "-" + d.getFullYear();
			var dateLabel = document.createElement('label');
			dateLabel.setAttribute('class', 'dateLabel');
			dateLabel.innerHTML = datestr;
			var header = document.createElement('div');
			header.appendChild(dateLabel);
			dayDiv.appendChild(header);
			var linebreak = document.createElement("br");
			dayDiv.appendChild(linebreak);

			if (result[datestr] !== undefined) {

				for (let j = 0; j < result[datestr].length; j++) {
					let info = result[datestr][j];
					//console.log(info);

					var requestLink = document.createElement('a');
					requestLink.setAttribute('class', i);
					requestLink.setAttribute('id', 'link');
					requestLink.setAttribute('href', '#');
					requestLink.addEventListener('click', function () {
						//alert(info.requestid)
						document.getElementById('requestid').value = info.requestid;
						viewFeedback('y');
						//this.preventDefault();

					});

					var linktext = info.empname + "\n" + info.requestid + "\n Planned:" + info.time + " \nSpent:" + info.spenttime + " (" + info.totalspent + ")\n";

					if (info.empname == "") {
						linktext = info.requestid + "\n Planned:" + info.time + " \nSpent:" + info.spenttime + " (" + info.totalspent + ")\n";
					}
					requestLink.innerText = linktext;
					dayDiv.appendChild(requestLink);

					var linebreak = document.createElement("br");
					dayDiv.appendChild(linebreak);
				}
			}
			d.setDate(d.getDate() + 1);
		}
		else {

		}
	}
	hideLoadingSpinner();
}

function requestStatus() {
	
	var form = $("#formReq");
	if (document.getElementById("remarkReq").value == "") {
		alert("Enter Remark")
		return;
	}
	showLoadingSpinner();
	$.ajax({
		type: 'POST',
		data: form.serialize(),
		url: '/ibase/email',
		beforeSend: function () {
			document.getElementById("submit").value = "Sending...";
		},
		success: function (response) {
			alert(response);
			var modal = document.getElementById("modalReq");
			modal.style.display = "none";
			hideLoadingSpinner();
		},
		error: function (data) {
			jQuery('.alert').show();
			jQuery('.alert').html(data.fail);
			hideLoadingSpinner();
		}
	});

}


function statusUpdate() {
	console.log("sending Status....");
	showLoadingSpinner();
	//var form = $("#form");
	var form = $("#form").get(0);
	
	var formData = new FormData(form);
	var attachment1 = document.getElementById("attachment1");
	var attachment2 = document.getElementById("attachment1");
	var attachment3 = document.getElementById("attachment1");
	if (attachment1.files.length > 0) {
		// Loop through the selected files and append them to the FormData object
		for (var i = 0; i < attachment1.files.length; i++) {
			var file = attachment1.files[i];
			formData.append("attachment1", file);
		}
	}
	if (attachment2.files.length > 0) {
		// Loop through the selected files and append them to the FormData object
		for (var i = 0; i < attachment2.files.length; i++) {
			var file = attachment2.files[i];
			formData.append("attachment2", file);
		}
	}
	if (attachment3.files.length > 0) {
		// Loop through the selected files and append them to the FormData object
		for (var i = 0; i < attachment3.files.length; i++) {
			var file = attachment3.files[i];
			formData.append("attachment3", file);
		}
	}



	if (document.getElementById("remark").value == "") {
		alert("Enter Remark")
		return;
	}
	if (document.getElementById("hrsSpendToday").value == "") {
		alert("Enter Hours Todays Spend")
		return;
	}
	if (document.getElementById("hrsLeft").value == "") {
		alert("Enter Required Hours")
		return;
	}
	if (document.getElementById("datepickerEnd").value == "") {
		alert("Enter New End Date")
		return;
	}
	document.getElementById("submit").value = "Sending...";
	$.ajax({
		type: 'POST',
		processData: false, // Prevent automatic processing of data
		contentType: false, // Prevent automatic setting of content type
		//data: form.serialize(),
		data: formData,
		url: '/ibase/email',
		beforeSend: function () {
			document.getElementById("submit").value = "Sending...";
		},
		success: function (response) {
			alert(response);
			var modal = document.getElementById("modal");
			modal.style.display = "none";
			hideLoadingSpinner();
		},
		error: function (data) {
			jQuery('.alert').show();
			jQuery('.alert').html(data.fail);
			hideLoadingSpinner();
		}
	});


}


$(function () {

	$("#datepickerEnd").datepicker({ dateFormat: 'dd-M-yy' }).datepicker();

});


function enableMultiple(check) {
	// var check = document.getElementById("select");
	var dropdown = document.getElementById("empCode");
	if (check.checked) {
		dropdown.setAttribute('multiple', true);
	}
	else {
		dropdown.removeAttribute('multiple');
	}
	dropdown.setAttribute("name", "empCode")
}

function view() {
	var date1 = new Date(document.getElementById("datepicker").value);
	var date2 = new Date(document.getElementById("datepickerTo").value);

	if (date1 > date2) {

		alert("From date should be less than To date");
		return 0;
	}
	var selected = [];
	for (var option of document.getElementById('empCode').options) {
		if (option.selected) {
			if (option.value == 1) {
				document.getElementById('selected').innerHTML = ("Selected Employee: All");
				return 1;
			}
			selected.push(option.text);

		}
	}
	if (selected.length == 0) {
		alert("Select Employee");
		return 0;
	}
	document.getElementById('selected').innerHTML = "Selected Employee:" + selected;
	return 1;
}
function createPlanTable() {
	view();
	var table = document.getElementById('table');
	table.innerHTML = "";
	var row = table.insertRow(0);

	// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
	var cellPerson = row.insertCell(0);
	cellPerson.innerHTML = "Person";
	cellPerson.style.background = "#009879";
	cellPerson.style.color = "#ffffff";

	var cellDate = row.insertCell(1);
	cellDate.innerHTML = "Date";
	cellDate.style.background = "#009879";
	cellDate.style.color = "#ffffff";

	var cellRequestid = row.insertCell(2);
	cellRequestid.innerHTML = "Request ID";
	cellRequestid.style.background = "#009879";
	cellRequestid.style.color = "#ffffff";

	var cellDescr = row.insertCell(3);
	cellDescr.innerHTML = "Descr";
	cellDescr.style.background = "#009879";
	cellDescr.style.color = "#ffffff";

	var cellTime = row.insertCell(4);
	cellTime.innerHTML = "Time";
	cellTime.style.background = "#009879";
	cellTime.style.color = "#ffffff";

	var cellActiondtl = row.insertCell(5);
	cellActiondtl.innerHTML = "Action DTL";
	cellActiondtl.style.background = "#009879";
	cellActiondtl.style.color = "#ffffff";
}

