function load_station_by_river_id(sel_river_id) {
	var datastr = "sel_river_id=" + sel_river_id;
	//$("#wl_sva_btn").css({"display":"none"});
	$('#view_wli_data').html("");
	$('#graph_data').html("");
	// alert(datastr);
	$("#station_list_holder").load('module/ground_water_ex/station_list_by_river.php', datastr);
}

function load_station_by_river_id_excel(sel_river_id) {
	var datastr = "sel_river_id=" + sel_river_id;
	$("#wl_sva_btn").css({ "display": "none" });
	$('#view_wli_data').html("");
	$('#graph_data').html("");
	//alert(datastr);
	$("#station_list_holder_1").load('module/ground_water_ex/station_list_by_river_excel.php', datastr);
}

function load_wl_graph_holder() {
	var active_tab = $('.form_tab .tab-pane.active').attr('id');
	//alert(active_tab);
	if (active_tab == 'data_upload') {
		return false;
	}
	else {
		var station = $("#station").val();
		var station_arr = station.split("#");
		var station_id = station_arr[0];
		var tidal_status = station_arr[1];
		var year = $("#year").val();
		var month = $("#month").val();
		var datastr = "station_id=" + station_id + "&tidal_status=" + tidal_status + "&year=" + year + "&month=" + month;
		$('#graph_data').load('module/ground_water_ex/swl_graph_holder.php', datastr);
	}

}

function flushData() {
	//alert('flush');
	$("#wl_sva_btn").css({ "display": "none" });
	$('#view_wli_data').html("");
	$('#graph_data').html("");
	//alert($('#station_1').val());
}

$('#year').on("keypress", function () {
	$("#wl_sva_btn").css({ "display": "none" });
	$('#view_wli_data').html("");
	$('#graph_data').html("");
});


function loadDeForm() {
	//alert("loadDeForm");
	$('#view_wli_data').html("");
	$('#graph_data').html("");
	$('#river').val('');
	//$('#station').val('');
	$('#station_name_holder').val('');
	$('#act_tab_name').val('data_entry');
	$('.nav-tabs a[href="#data_list"]').tab('show');
	//alert($('#station_1').val());
}

function loadExcelData() {
	//alert('loadDeForm');
	$('#view_wli_data').html("");
	$('#graph_data').html("");
	$('#river_1').val('');
	//$('#station').val('');
	$('#station_name_holder_1').val('');
	$('#act_tab_name').val('data_upload');
	$('.nav-tabs a[href="#data_list"]').tab('show');
	//alert($('#station').val());

}

function load_data_on_act_tab() {
	var active_tab = $('.data_content .tab-pane.active').attr('id');
	//alert(active_tab);
	if (active_tab == 'data_list') {
		//alert('line 63');
		load_water_level_info();
	}
	else {
		//alert('line 67');
		load_wl_graph_holder();
	}
}

function load_water_level_info() {
	var active_tab = $('.form_tab .tab-pane.active').attr('id');
	//alert(active_tab);
	if (active_tab == 'data_upload') {
		return false;
	}
	else {
		var river = $('#river').val();
		var station = $('#station').val();
		var station_arr = station.split("#");
		var station_id = station_arr[0];
		var tidal_status = station_arr[1];
		var year = $('#year').val();
		var month = $('#month').val();
		if (river == "") {
			alert('Please select a River');
			('#river').focus();
			return false;
		}
		else if (station == "") {
			alert('Please select a Station');
			('#station').focus();
			return false;
		}
		else if (year == "") {
			alert('Please mention a Year');
			('#year').focus();
			return false;
		}
		else if (month == "") {
			alert('Please mention a Month');
			('#month').focus();
			return false;
		}
		else {
			var datastr = "river=" + river + "&station=" + station_id + "&year=" + year + "&month=" + month + "&tidal_status=" + tidal_status;
			//alert(datastr);
			$('.nav-tabs a[href="#data_list"]').tab('show');
			$('#cover-spin').show(0);
			$.ajax({
				url: 'module/ground_water_ex/water_level_information_datatable.php',
				type: 'get',
				data: datastr,
				cache: false,
				success: function (data) {
					$('#cover-spin').hide();
					$("#wl_sva_btn").css({ "display": "block" });
					$("#view_wli_data").html(data);
					$('#6hr_1').select();
				}
			});
			//$('#view_wli_data').load('module/ground_water_ex/water_level_information_datatable.php'); 
		}
	}
}


function save_water_level_info(curr_col_name, curr_col_val, next_col_name) {
	var operation = "single_col_save";
	var station = $("#station").val();
	var station_arr = station.split("#");
	var station_id = station_arr[0];
	var tidal_status = station_arr[1];
	//var station_id = 'SW26';
	var year = $("#year").val();
	var month = $("#month").val();
	var col_name_arr = curr_col_name.split("_");
	var col_name = col_name_arr[0];
	var sel_day = col_name_arr[1];
	var datastr = "station_id=" + station_id + "&year=" + year + "&month=" + month + "&sel_day=" + sel_day + "&col_name=" + col_name +
		"&col_val=" + curr_col_val + "&operation=" + operation;
	//alert(datastr);

	if (col_name == 'hwl') {
		var ht_val = $("#ht_" + sel_day).val();
		datastr = datastr + "&ht_val=" + ht_val;
	}
	else if (col_name == 'lwl') {
		var lt_val = $("#lt_" + sel_day).val();
		datastr = datastr + "&lt_val=" + lt_val;
	}
	else {
		datastr = datastr;
	}
	//alert(datastr);
	$.ajax({
		url: 'module/ground_water_ex/water_level_information_ajax.php',
		type: 'post',
		data: datastr,
		cache: false,
		success: function (result) {
			//	alert(result);
			/*if(result==1){
				alert('Data has been saved successfully');
			}
			else{
				alert(result);
			}*/
			$('#' + next_col_name).focus();
		}
	});

}

// function wl_multiple_save(){





function wl_multiple_save() {
	//alert('wl_multiple_save');
	var flag = 0;

	var act_tab_name = $("#act_tab_name").val();
	if (act_tab_name == 'data_entry') {
		var station = $("#station").val();
	}
	else {
		var station = $("#station_1").val();
	}
	//alert(station);
	var station_arr = station.split("#");
	var station_id = station_arr[0];
	var tidal_status = station_arr[1];

	var sel_mon_tot_day = $("#sel_mon_tot_day").val();

	if (sel_mon_tot_day == "") {
		alert('Please load the data first');
	} else {
		$('#cover-spin').hide();
		//var dataToSave = [];

		for (var sel_day = 1; sel_day <= sel_mon_tot_day; sel_day++) {
			//alert("Checking!");
			var date = $('#date_' + sel_day).val();
			var six_hr = $('#6hr_' + sel_day).val();
			var nine_hr = $('#9hr_' + sel_day).val();
			var twelve_hr = $('#12hr_' + sel_day).val();
			var fifteen_hr = $('#15hr_' + sel_day).val();
			var eighteen_hr = $('#18hr_' + sel_day).val();
			var high_time = $('#ht_' + sel_day).val();
			var low_time = $('#lt_' + sel_day).val();
			var highest_wl = $('#hwl_' + sel_day).val();
			var lowest_wl = $('#lwl_' + sel_day).val();
			var remarks = $('#remarks').val();
			var year = $('#year').val();
			var month = $('#month').val();
			var operation = "single_row_save";

			var datastr = "sel_date=" + date + "&station_id=" + station_id + "&operation=" + operation + "&tidal_status=" + tidal_status +
				"&six_hr=" + six_hr + "&nine_hr=" + nine_hr + "&twelve_hr=" + twelve_hr + "&fifteen_hr=" + fifteen_hr + "&eighteen_hr=" + eighteen_hr;

			if (tidal_status == "T") {
				datastr = datastr + "&high_time=" + high_time + "&low_time=" + low_time + "&highest_wl=" + highest_wl +
					"&lowest_wl=" + lowest_wl;
			}
			//alert(datastr);
			$.ajax({
				url: 'module/ground_water_ex/water_level_information_ajax.php',
				type: 'post',
				data: datastr,
				cache: false,
				success: function (result) {
					//	alert(result);
					if (result == 1) {
						if (flag == 0) {
							alert('Data has been saved successfully');
							flag = 1;
						}
					}
					else {
						//alert(result);
					}
				}
			});
		}
		alert('Data has been saved successfully');
	}
}


////--Multi-save for excel--////
function wl_multiple_save_excel() {
	//alert("wl_multiple_save_excel");;
	var act_tab_name = $("#act_tab_name").val();
	if (act_tab_name == 'data_entry') {
		var station = $("#station").val();
	}
	else {
		var station = $("#station_1").val();
	}
	//alert(station);
	var station_arr = station.split("#");
	var station_id = station_arr[0];
	var tidal_status = station_arr[1];
	var table = document.getElementById("wli_data_table");
	var tbodyRowCount = table.tBodies[0].rows.length;
	//alert(tbodyRowCount);

	$('#cover-spin').show(0);
	for (var sel_day = 1; sel_day <= tbodyRowCount; sel_day++) {
		var date = $('#date_' + sel_day).val();
		var six_hr = $('#6hr_' + sel_day).val();
		var nine_hr = $('#9hr_' + sel_day).val();
		var twelve_hr = $('#12hr_' + sel_day).val();
		var fifteen_hr = $('#15hr_' + sel_day).val();
		var eighteen_hr = $('#18hr_' + sel_day).val();
		var high_time = $('#ht_' + sel_day).val();
		var low_time = $('#lt_' + sel_day).val();
		var highest_wl = $('#hwl_' + sel_day).val();
		var lowest_wl = $('#lwl_' + sel_day).val();
		var operation = "single_row_save";

		var datastr = "sel_date=" + date + "&station_id=" + station_id + "&operation=" + operation + "&tidal_status=" + tidal_status +
			"&six_hr=" + six_hr + "&nine_hr=" + nine_hr + "&twelve_hr=" + twelve_hr + "&fifteen_hr=" + fifteen_hr + "&eighteen_hr=" + eighteen_hr;

		if (tidal_status == "T") {
			datastr = datastr + "&high_time=" + high_time + "&low_time=" + low_time + "&highest_wl=" + highest_wl +
				"&lowest_wl=" + lowest_wl;
		}
		//alert(datastr);
		$.ajax({
			url: 'module/ground_water_ex/water_level_information_ajax.php',
			type: 'post',
			data: datastr,
			cache: false,
			success: function (result) {
				//alert(result);
				if (result == 1) {
					//alert('Data has been saved successfully');
				}
				else {
					alert(result);
				}
			}
		});
	}
	if (sel_day >= tbodyRowCount) {
		//alert(sel_day);
		alert('Data has been saved successfully');
		$('#cover-spin').hide();
	}
}

////--Multi-save for excel--////
function save_single_water_level_info(sel_day, press_op) {
	//alert("save_single_water_level_info");
	var act_tab_name = $("#act_tab_name").val();
	if (act_tab_name == 'data_entry') {
		var station = $("#station").val();
	}
	else {
		var station = $("#station_1").val();
	}
	//alert(station);
	var station_arr = station.split("#");
	var station_id = station_arr[0];
	var tidal_status = station_arr[1];
	var date = $('#date_' + sel_day).val();
	var six_hr = $('#6hr_' + sel_day).val();
	var nine_hr = $('#9hr_' + sel_day).val();
	var twelve_hr = $('#12hr_' + sel_day).val();
	var fifteen_hr = $('#15hr_' + sel_day).val();
	var eighteen_hr = $('#18hr_' + sel_day).val();
	var high_time = $('#ht_' + sel_day).val();
	var low_time = $('#lt_' + sel_day).val();
	var highest_wl = $('#hwl_' + sel_day).val();
	var lowest_wl = $('#lwl_' + sel_day).val();
	var operation = "single_row_save";

	var datastr = "sel_date=" + date + "&station_id=" + station_id + "&operation=" + operation + "&tidal_status=" + tidal_status +
		"&six_hr=" + six_hr + "&nine_hr=" + nine_hr + "&twelve_hr=" + twelve_hr + "&fifteen_hr=" + fifteen_hr + "&eighteen_hr=" + eighteen_hr;

	if (tidal_status == "T") {
		datastr = datastr + "&high_time=" + high_time + "&low_time=" + low_time + "&highest_wl=" + highest_wl +
			"&lowest_wl=" + lowest_wl;
	}
	//alert(datastr);
	$.ajax({
		url: 'module/ground_water_ex/water_level_information_ajax.php',
		type: 'post',
		data: datastr,
		cache: false,
		success: function (result) {
			//	alert(result);
			if (result == 1) {
				if (press_op == "btn_click") {
					alert('Data has been saved successfully');
				}
			}
			else {
				alert(result);
			}
		}
	});
}

function load_wl_graph() {
	//alert('load_wl_graph');
	var station_id = $("#grph_sel_station_id").val();
	var tidal_status = $("#grph_sel_tidal_status").val();
	var year = $("#grph_sel_year").val();
	var month = $("#grph_sel_month").val();

	var graph_str = "station_id=" + station_id + "&tidal_status=" + tidal_status + "&year=" + year + "&month=" + month;
	//alert(graph_str);
	if (tidal_status == "T") {
		//ajax
		//alert('12345');
		//$('#cover-spin').show(0);
		$.ajax({
			type: "post",
			url: "module/ground_water_ex/water_level_graph.php",
			data: graph_str,
			success: function (str) {
				if ($.trim(str)) {
					$('#cover-spin').hide();
					//alert(str);
					var mwl_data = $.parseJSON(str);

					createChart(mwl_data, year, month);


					function createChart(data, year, month) {

						// JS - Destroy exiting Chart Instance to reuse <canvas> element
						let chartStatus = Chart.getChart("graph_canvas"); // <canvas> id
						if (chartStatus != undefined) {
							chartStatus.destroy();
						}
						//-- End of chart destroy  

						//alert(data);
						var regularLength = data.Regular.length;
						var labels = [];

						for (var i = 0; i < regularLength; i++) {
							var day = Math.floor(i / 5) + 1;
							var time = 6 + (i % 5) * 3; // Calculate the time in 24-hour format
							var date = `${day.toString().padStart(2, '0')}-${month}-${year}`;
							labels.push({ date: date, time: `${time}:00` });
							//alert("Checking!");
						}

						var chartData = {
							labels: labels.map(item => item.date),
							datasets: [
								{
									label: "Regular",
									data: data.Regular,
									fill: false,
									borderColor: 'rgba(0, 0, 255, 1)',
									spanGaps: true,
								},
								{
									label: "High",
									data: data.High,
									fill: false,
									borderColor: 'rgba(255, 0, 0, 1)',
									spanGaps: true,
								},
								{
									label: "Low",
									data: data.Low,
									fill: false,
									borderColor: 'rgba(0, 128, 0, 1)',
									spanGaps: true,
								},
							],
						};

						//var riverName = "Your River Name"; // Replace with the actual river name
						var ctx = document.getElementById("graph_canvas").getContext("2d");
						lineChart = new Chart(ctx, {
							type: "line",
							data: chartData,
							options: {
								scales: {
									x: {
										display: true,
										title: {
											display: true,
											text: 'Date'
										},
										ticks: {
											source: labels.map(item => item.date),
										},
									},
									y: {
										display: true,
										title: {
											display: true,
											text: 'Water Level (m)'
										},
									},
								},
								plugins: {
									title: {
										display: true,
										text: data.Title,
										font: {
											size: 16, // Adjust the font size as needed
										},
									},
									tooltip: {
										callbacks: {
											title: function (tooltipItems) {
												// Display both date and time when hovering over data points
												var dataIndex = tooltipItems[0].dataIndex;
												var labelItem = labels[dataIndex];
												return `${labelItem.date} ${labelItem.time}`;
											},
										},
									},
								},

							},
						});
					}
				}
			}
		});
	}
	else if (tidal_status != "T") {
		//ajax
		//alert('12345');
		//$('#cover-spin').show(0);
		$.ajax({
			type: "post",
			url: "module/ground_water_ex/water_level_graph_nonT.php",
			data: graph_str,
			success: function (str) {

				//$("#graph_data").html(str);
				if ($.trim(str)) {
					//alert(str);
					$('#cover-spin').hide();
					//alert(str);
					var mwl_data = $.parseJSON(str);
					//alert("Checking");
					// google.charts.load('current',{packages:['corechart']})
					// google.charts.setOnLoadCallback(drawChart);

					//alert("Checking");

					createChart(mwl_data, year, month);

					// if (lineChart) {
					// 	lineChart.destroy();
					// }

					//var lineChart = null;

					function createChart(data, year, month) {

						// JS - Destroy exiting Chart Instance to reuse <canvas> element
						let chartStatus = Chart.getChart("graph_canvas"); // <canvas> id
						if (chartStatus != undefined) {
							chartStatus.destroy();
						}
						//-- End of chart destroy  

						//alert(data);
						var regularLength = data.Regular.length;
						var labels = [];

						for (var i = 0; i < regularLength; i++) {
							var day = Math.floor(i / 5) + 1;
							var time = 6 + (i % 5) * 3; // Calculate the time in 24-hour format
							var date = `${day.toString().padStart(2, '0')}-${month}-${year}`;
							labels.push({ date: date, time: `${time}:00` });
							//alert("Checking!");
						}

						var chartData = {
							labels: labels.map(item => item.date),
							datasets: [
								{
									label: "Regular",
									data: data.Regular,
									fill: false,
									borderColor: 'rgba(0, 0, 255, 1)',
									spanGaps: true,
								},
							],
						};

						//var riverName = "Your River Name"; // Replace with the actual river name
						var ctx = document.getElementById("graph_canvas").getContext("2d");
						lineChart = new Chart(ctx, {
							type: "line",
							data: chartData,
							options: {
								scales: {
									x: {
										display: true,
										title: {
											display: true,
											text: 'Date'
										},
										ticks: {
											source: labels.map(item => item.date),
										},
									},
									y: {
										display: true,
										title: {
											display: true,
											text: 'Water Level (m)'
										},
									},
								},
								plugins: {
									title: {
										display: true,
										text: data.Title,
										font: {
											size: 16 // Adjust the font size as needed
										},
									},
									tooltip: {
										callbacks: {
											title: function (tooltipItems) {
												// Display both date and time when hovering over data points
												var dataIndex = tooltipItems[0].dataIndex;
												var labelItem = labels[dataIndex];
												return `${labelItem.date} ${labelItem.time}`;
											},
										},
									},
								},

							},
						});
					}
				}
			}
		});
	}
}
function dl_wl_graph() {
	//	alert('downloadChart');
	var chartContainer = document.getElementById('graph_canvas');
	var canvas = document.createElement('canvas');
	canvas.width = chartContainer.offsetWidth;
	canvas.height = chartContainer.offsetHeight;
	//alert(chartContainer.offsetWidth);
	var ctx = canvas.getContext('2d');
	ctx.fillStyle = 'white';
	ctx.fillRect(0, 0, canvas.width, canvas.height);
	//alert('line 695');
	html2canvas(chartContainer).then(function (chartCanvas) {
		ctx.drawImage(chartCanvas, 0, 0);
		//	alert('line 698');
		canvas.toBlob(function (blob) {
			var link = document.createElement('a');
			link.href = URL.createObjectURL(blob);
			link.download = 'swl_graph.png';
			link.click();
		});
	});
	//alert('line 705');
}
//////////--Delete--///////////
function delete_data(row_id) {
	//alert("delete_data");
	var row_id = row_id;
	var date = $("#date_" + row_id).val();
	var operation = 'delete';
	var station = $("#station").val();
	var station_arr = station.split("#");
	var station_id = station_arr[0];
	var tidal_status = station_arr[1];

	datastr = "in_date=" + date + "&station=" + station_id + "&operation=" + operation;
	//alert(datastr);
	if (confirm('Are you sure you want to delete the selected row?')) {
		$.ajax({
			url: 'module/ground_water_ex/water_level_information_ajax.php',
			type: 'post',
			data: datastr,
			success: function (str) {
				//alert(str);
				if (str == 1) {
					alert("Data has been deleted successfully");

				} else {
					alert('Fail to delete data');
				}
				load_water_level_info();
			}
		});
	}

}

// function wl_delete_all() {

// 	var station_arr = station.split("#");
// 	var station_id = station_arr[0];
// 	var table = document.getElementById("wli_data_table");
// 	var tbodyRowCount = table.tBodies[0].rows.length;
// 	var sel_day = 1;
// 	var successfulDeletions = 0;

// 	if (confirm('Are you sure you want to delete all rows?')) {
// 		function deleteRow(sel_day) {
// 			if (sel_day <= tbodyRowCount) {
// 				var date = $('#date_' + sel_day).val();
// 				var operation = "delete_all";
// 				var datastr = "sel_date=" + date + "&station=" + station_id + "&operation=" + operation;

// 				$('#cover-spin').show(0);
// 				$.ajax({
// 					url: 'module/ground_water_ex/water_level_information_ajax.php',
// 					type: 'post',
// 					data: datastr,
// 					cache: false,
// 					success: function (result) {
// 						if (result == 1) {
// 							successfulDeletions++;
// 							deleteRow(sel_day + 1); // Continue to delete the next row
// 						} else {
// 							// Handle the case when deletion fails
// 						}

// 						// Check if all rows have been successfully deleted
// 						if (successfulDeletions === tbodyRowCount) {
// 							// All rows have been deleted, trigger the alert and reload the page
// 							//load_water_level_info();
// 							$('#cover-spin').hide();
// 							alert('Data has been deleted successfully');

// 							load_water_level_info();

// 						}
// 					}
// 				});
// 			}
// 		}

// 		// Start deleting rows
// 		deleteRow(sel_day);
// 	}
// }

// function wl_delete_all() {
// 	var station = $("#station").val();
// 	var year = $("#year").val();
// 	var month = $("#month").val();

// 	// var station_arr = station.split("#");
// 	// var station_id = station_arr[0];
// 	// var table = document.getElementById("wli_data_table");
// 	// var tbodyRowCount = table.tBodies[0].rows.length;
// 	// var sel_day = 1;
// 	// var successfulDeletions = 0;

// 	if (confirm('Are you sure you want to delete all rows?')) {


// 		// var date = $('#date_' + sel_day).val();
// 		var station_arr = station.split("#");
// 		var station_id = station_arr[0];
// 		var operation = "delete_all";
// 		var datastr = "year=" + year + "&station=" + station_id + "&month=" + month + "&operation=" + operation;

// 		alert(datastr);

// 		//$('#cover-spin').show(0);
// 		$.ajax({
// 			url: 'module/ground_water_ex/water_level_information_ajax.php',
// 			type: 'post',
// 			data: datastr,
// 			cache: false,
// 			success: function (result) {
// 				console.log(result);
// 				if (result == 1) {
// 					//$('#cover-spin').hide();
// 					alert('Data has been deleted successfully');

// 					load_water_level_info();
// 				}
// 			}
// 		});

// 	}
// }

function wl_delete_all() {
    var station = $("#station").val();             
    var station_arr = station.split("#");
    var station_id = station_arr[0];
    var table = document.getElementById("wli_data_table");
    var tbodyRowCount = table.tBodies[0].rows.length;
    var sel_day = 1;
    var successfulDeletions = 0;

    if (confirm('Are you sure you want to delete all rows?')) {
        function deleteRow(sel_day) {
            if (sel_day <= tbodyRowCount) {
                var date = $('#date_' + sel_day).val();
                var operation = "delete_all";
                var datastr = "sel_date=" + date + "&station=" + station_id + "&operation=" + operation;
               
				//$('#cover-spin').show(0);
                $.ajax({
                    url: 'module/ground_water_ex/water_level_information_ajax.php',
                    type: 'post',
                    data: datastr,
                    cache: false,
                    success: function (result) {
                        if (result == 1) {
							//alert('hellow');
                            successfulDeletions++;
                            deleteRow(sel_day + 1); // Continue to delete the next row
                        } else {
                            // Handle the case when deletion fails
                        }

                        // Check if all rows have been successfully deleted
                        if (successfulDeletions === tbodyRowCount) {
                            // All rows have been deleted, trigger the alert and reload the page
							//load_water_level_info();
							//$('#cover-spin').hide();
                            //alert('Data has been deleted successfully');
							
                           // load_water_level_info();
							
                        }
                    }
                });
            }
        }

        // Start deleting rows
        deleteRow(sel_day);
		load_water_level_info();
		alert('Data has been deleted successfully');
	
		
	
    }
}