var isSetUnprotectedMode = true;
var isDemoSetUnprotectedMode = true;
var showMsgBox = false;
let tempSliderObj = {};
let tempSliderObj1 = {};
let centralWavelengthSliderObj = {};
let centralWavelengthSliderObj1 = {};
let combFrequencySliderObj = {};
let combFrequencySliderObj1 = {};
let demoCentralWavelengthSliderObj = {};
let demoCombFrequencySliderObj = {};
let rfSynthFqSliderObj = {};
let rfSynthPwSliderObj = {};
let demuxCombo1Obj = {};
let demuxCombo2Obj = {};
let demuxCombo3Obj = {};
let demuxCombo4Obj = {};
let iDrive_Slider_Obj_0 = {};
let iDrive_Slider_Obj_1 = {};
let iDrive_Slider_Obj_2 = {};
let iDrive_Slider_Obj_3 = {};
let iDrive_Slider_Obj_4 = {};
let iDrive_Slider_Obj_5 = {};
let iDrive_Slider_Obj_6 = {};
let iDrive_Slider_Obj_7 = {};
let iDrive_Slider_Obj_8 = {};
let iDrive_Slider_Obj_9 = {};
let iDrive_Slider_Obj_10 = {};
let iDrive_Slider_Obj_11 = {};
let iDrive_Slider_Obj_12 = {};
let iDrive_Slider_Obj_13 = {};
let Demux_Slider_Obj_0 = {};
let Demux_Slider_Obj_1 = {};
let Demux_Slider_Obj_2 = {};
let Demux_Slider_Obj_3 = {};
let Demo_Demux_Slider_Obj_0 = {};
let Demo_Demux_Slider_Obj_1 = {};
let Demo_Demux_Slider_Obj_2 = {};
let Demo_Demux_Slider_Obj_3 = {};
let calibrationWaveSliderObj = {};
let calibrationFreqSliderObj = {};

let Debug_Slider_1 = {};
let Debug_Setvalue_1 = {};
let Debug_Slider_2 = {};
let Debug_Setvalue_2 = {};
let Debug_Slider_3 = {};
let Debug_Setvalue_3 = {};
let Debug_Slider_4 = {};
let Debug_Setvalue_4 = {};
let Debug_Slider_5 = {};
let Debug_Setvalue_5 = {};
let Debug_Slider_6 = {};
let Debug_Setvalue_6 = {};
let Debug_Slider_7 = {};
let Debug_Setvalue_7 = {};
let Debug_Slider_8 = {};
let Debug_Setvalue_8 = {};
let Debug_Slider_9 = {};
let Debug_Setvalue_9 = {};
let Debug_Slider_10 = {};
let Debug_Setvalue_10 = {};

var isIDriveValChange = false
isSetUnprotectedMode = true;




let idriveId = [];
let rfSynthId = [];

var mymodal = $('#myModal');
mymodal.find(".modal-body").addClass("scrollContainerModal");
var opticalCombSwitchId = "#wavelength-turn-on-off";
var demoOpticalCombSwitchId = "#demo-wavelength-turn-on-off";
var techData = null;
var opticalFrequencyCombData = null;
var rfSynthData = null;
var iDriveData = null;
var combToneData = null;
var demuxMapData = null;
var demoDemuxMapData = null;
var demoCombToneData = null;
var combtone1, combtone2, combtone3, combtone4 = -1;
var demo_combtone1, demo_combtone2, demo_combtone3, demo_combtone4 = -1;


var commonOpticalCombId = "";

// data for idac_vdac
var iDAC_VDAC_data = null

var isCllicked = false;
var parameters = {};
var url = String.empty;
var moduleControlData = [];
var demoModeData = [];
var connectionSettings = [];
var moduleControlParameters = [];


function outOffRange(minValue, maxValue, setValue){
	if (setValue > maxValue || setValue < minValue) {
        swal("Warning", "out of range", "warning");
    }
}


function loadSlider(sliderObj, sliderID, sliderSetupValueID, min, max, setValue, width, isIDrive, step, isOpticalComb, isDemoIDrive, id, isRfSynth, isDebug = false) {
	let values = {
		min: min,
		max: max
	}
	sliderObj.slider = new rSlider({
		target: sliderID,
		values: values,
		step: step,
		range: true,
		scale: true,
		labels: false,
		width: width,
		idriveId: id,
		isRfSynth: isRfSynth,
		isIDrive: isIDrive,
		isOpticalComb: isOpticalComb,
		onChange: function (vals) {
			min = vals.split(",")[0];
			if (isOpticalComb)
				min = parseInt(min);
			else
				min = parseFloat(min).toFixed(2);
			$(sliderSetupValueID).val(min);
		}
	});
	sliderObj.slider.setValues(setValue, max);

	$($('div[data-dir="right"]')).css("display", "none");
	// if (!isDebug) {
	// 	$(".rs-scale").children().css("display", "none");
	// }
	// $(".rs-scale").css("right", 0);
	// console.log($(".rs-scale").children(), $(".rs-scale").children().last(), "child");
	// $(".rs-scale").children().last().css("float", "right");
	if (isIDrive && step == 0.01 || isIDrive && step == 0.001) {
	// if (isIDrive) {
		var protectModeVar = false;
		if (isDemoIDrive)
			var switchID = demoOpticalCombSwitchId;
		else
			var switchID = opticalCombSwitchId;

		$(sliderObj.slider.conf.target).nextAll().find(".rs-pointer").mousedown(function (e) {
			commonOpticalCombId = switchID;
			if (switchID == "#demo-wavelength-turn-on-off")
				protectModeVar = isDemoSetUnprotectedMode;
			else
				protectModeVar = isSetUnprotectedMode;
			
			protectModeVar = true

			if (protectModeVar == false) {
				if ($(switchID).prop("checked") == true) {
					$(".state-box-layout").fadeIn();
					$("body").css("overflow", "hidden");
				} else {
					$(".warning-box-layout").fadeIn();
					$("#warning-password").focus();
					$("body").css("overflow", "hidden");
				}
			}
		});
	}
	// to add slider user validation on normal sliders
	// else if (isOpticalComb){
	// 	$(sliderObj.slider.conf.target).nextAll().find(".rs-pointer").mousedown(function (e) {
	// 		if (isSetUnprotectedMode == false) {
	// 				$(".warning-box-layout").fadeIn();
	// 				$("#warning-password").focus();
	// 				$("body").css("overflow", "hidden");
	// 		}
	// 	});
	// }
}

function readJsonData(connectionType, data) {
	switch (connectionType) {
		case "ethernet":
			data.forEach(function (d) {
				$("#IPaddress").val(d.ip_addr);
				$("#subNetMask").val(d.netmask);
				$("#defaultGetway").val(d.gateway);
				$("#DNSServer").val(d.dns);
				$("#ethernetCheckButton").prop("checked", d.enabled == 1 ? true : false);
			});
			break;
		case "serial":
			data.forEach(function (d) {
				$("#BAUDRate").val(d.baud_rate);
				$("#Parity").val(d.parity);
				$("#DataBits").val(d.data_bits);
				$("#flowControl").val(d.flow_control);
				$("#serialCheckButton").prop("checked", d.enabled == 1 ? true : false);
			});
			break;
		case "remote_storage":
			data.forEach(function (d) {
				$("#rs-share").val(d.share);
				$("#rs-user").val(d.user);
				$("#rs-password").val(d.password);
				$("#protocol").val(d.protocol);
				$("#remoteButton").prop("checked", d.enabled == 1 ? true : false);
			});
			break;
		case "remote":
			data.forEach(function (d) {
				$("#remoteControlID").val(d.id);
				$("#remoteControlEnable").prop("checked", d.enabled == 1 ? true : false);
			});
			break;
		case "email":
			emailResponse = data
			data.forEach(function (d) {
				$("#recipientEmail").val(d.out_server);
				$("#senderEmail").val(d.in_server);
				$("#smtpServer").val(d.smtp_server);
				$("#portNumber").val(d.port_number);
				$("#password").val(d.pw);
				if(d.authentication == "true")
					$("#authenticationCheck").prop('checked', true);
				else
					$("#authenticationCheck").prop('checked', false);


				if (d.alert_msg == "true") {
					$("#alertMessagesON").prop('checked', true);
					const parts = d.level.split(',');
					for (var i = 0; i < parts.length; i++) {
						if (parts[i] == "INFO")
							$("#InfoMessagesON").prop('checked', true);
						else if (parts[i] == "WARNING")
							$("#warningMessagesON").prop('checked', true);
						else if (parts[i] == "ALERT")
							$("#alertMessages").prop('checked', true);
					}
				} else {
					$("#alertMessagesON").prop('checked', false);
					$("#InfoMessagesON").prop('checked', false);
					$("#warningMessagesON").prop('checked', false);
					$("#alertMessages").prop('checked', false);
				}
			});
			break;
		case "temperature":
			$("#temp-id1").val(data[0].Id);
			$("#temp-id2").val(data[1].Id);
			if (data[0].state == 0)
				$(".temp-state").attr("src", "../images/redLed.png");
			else if (data[0].state == 1)
				$(".temp-state").attr("src", "../images/greenLed.png");
			else
				$(".temp-state").attr("src", "../images/warningLed.png");
			
				if (data[1].state == 0)
				$(".temp-state").attr("src", "../images/redLed.png");
			else if (data[1].state == 1)
				$(".temp-state").attr("src", "../images/greenLed.png");
			else
				$(".temp-state").attr("src", "../images/warningLed.png");

			$("#temp-name").text(data.name);
			$("#temp-current-reading").text(data.getCurrent);
			$("#temp-reading1").text(data[0].setTemp);
			$("#temp-reading2").text(data[1].setTemp);
			$("#general-setvalue1").val(data[0].setTemp);
			$("#general-setvalue2").val(data[1].setTemp);

			if (data[0].onOffState == 1)
				$("#temp-turn-on-off1").prop("checked", true);
			else
				$("#temp-turn-on-off1").prop("checked", false);
			if (data[1].onOffState == 1)
				$("#temp-turn-on-off2").prop("checked", true);
			else
				$("#temp-turn-on-off2").prop("checked", false);
			break;
		case "RFSynthesizer":
			if (data.state == 0)
				$("#rf-synthesizer-state").attr("src", "../images/redLed.png");
			else if (data.state == 1)
				$("#rf-synthesizer-state").attr("src", "../images/greenLed.png");
			else
				$("#rf-synthesizer-state").attr("src", "../images/warningLed.png");

			$("#rfSynth-power-current-reading").text(data.getPower);
			if (data.OnOffState == 1)
				$("#rfSynth-turn-on-off").prop("checked", true);
			else
				$("#rfSynth-turn-on-off").prop("checked", false);

			$("#rfSynth-turn-on-off").change(function () {
				rfSynthId.push(rfSynthData.id);
			});
			$("#rfSynth-fq-setvalue").change(function () {
				rfSynthId.push(rfSynthData.id);
			});
			$("#rfSynth-power-setvalue").change(function () {
				rfSynthId.push(rfSynthData.id);
			});
			break;
		case "Password_hidden":
			// console.log(data[0].type)
			let type = $("#rs-password");
        	let typeValue = data[0]?.type == "Yes" ? "password" : "text";
			type.attr("type",typeValue);
			if(data[0]?.type == 'Yes'){
				$("#togglePassword").show() 
            	$("#hidetogglePassword").hide()
			}
			else{
				$("#togglePassword").hide() 
            	$("#hidetogglePassword").show()
			}
			break;
		case "read_enable_ssh":
			$("input[name='rbEnSSH']").each(function () {		
				if($(this).attr('value') == data?.enable_ssh) {
					$(this).prop('checked',true);
				}
			});
			$("#sshButton").prop("checked", data.enabled == 1 ? true : false);

			$('#sshButton').change(function() {
				const isChecked = $(this).is(':checked');
				$('input[name="rbEnSSH"]').prop('disabled', !isChecked).css('cursor', isChecked ? 'pointer' : 'auto');
			}).trigger('change');

			break;
		case "read_reverse_ssh":
			reverseSShData = data;
			$("input[name='enReverseSSH']").each(function () {		
				if($(this).attr('value') == data?.enable_reverse) {
					$(this).prop('checked',true);
				}
			});
			if(data?.enable_reverse == "yes"){
				$("#reverseSshConfig").show();
			}
			else{
				$("#reverseSshConfig").hide();
				$("#connectReverseSSH").attr("disabled",true);
			}
			$("#rs_remote_ip").val(data?.remote_ip),
			$("#rs_remote_port").val(data?.remote_port),
			$("#rs_remote_user").val(data?.username),
			$("#rs_local_port").val(data?.local_port),
			$("#key_file_name").html(data?.key_path).css({"color":"green"})
			$("#rs_key_path").html(data?.file_content);
			readReverseSshStatus();
			// $("#reverseSsh").prop("checked", data.rev_enabled == 1 ? true : false);

			// if (!$('#reverseSsh').is(':checked')) {
			// 	$('input[name="enReverseSSH"]').prop('disabled', true);
			// }

			$('#reverseSsh').change(function() {
				const isChecked = $(this).is(':checked');
				$('input[name="enReverseSSH"]').prop('disabled', !isChecked).css('cursor', isChecked ? 'pointer' : 'auto');
			}).trigger('change');

			break;
	}
}


function showModal(title, desc) {
	if(title == "Error"){
		$(".modal-header").css({
			"color": "#fff",
			"background-color": "#db4141"
		});
		$(".close").css({
			"color": "#fff"
		});
	}
	mymodal.find('.modal-title').text(title);
	mymodal.find('.modal-body').text(desc).css({"text-align":"center"});
	mymodal.modal('show');
	setTimeout(()=> {
		mymodal.modal("hide")
		$(".modal-header").css({
			"color": "#000",
			"background-color": "#fff"
		});
		$(".close").css({
			"color": "#000"
		});
	},autoClose)
	
}

function BindDropdownCombToneData() {
	$("#dr_demultiplexer_0,#dr_demultiplexer_1,#dr_demultiplexer_2,#dr_demultiplexer_3").empty();
	$("#dr_demultiplexer_0,#dr_demultiplexer_1,#dr_demultiplexer_2,#dr_demultiplexer_3").append(new Option("Select", -1));
	combToneData.forEach(function (data) {
		$("#dr_demultiplexer_0,#dr_demultiplexer_1,#dr_demultiplexer_2,#dr_demultiplexer_3").append(new Option(data.tone + " , " + data.comb_central_wav, data.id));
	});
	combtone1 = demuxMapData[0].lut_id;
	combtone2 = demuxMapData[1].lut_id;
	combtone3 = demuxMapData[2].lut_id;
	combtone4 = demuxMapData[3].lut_id;

	if (combToneData.find(x => x.id === demuxMapData[0].lut_id)) {
		$("#dr_demultiplexer_0").val(demuxMapData[0].lut_id);
		$("#dr_demultiplexer_1 option[value='" + demuxMapData[0].lut_id + "'").remove();
		$("#dr_demultiplexer_2 option[value='" + demuxMapData[0].lut_id + "'").remove();
		$("#dr_demultiplexer_3 option[value='" + demuxMapData[0].lut_id + "'").remove();
	} else {
		$("#dr_demultiplexer_0").val(-1);
	}

	if (combToneData.find(x => x.id === demuxMapData[1].lut_id)) {
		$("#dr_demultiplexer_1").val(demuxMapData[1].lut_id);
		$("#dr_demultiplexer_0 option[value='" + demuxMapData[1].lut_id + "'").remove();
		$("#dr_demultiplexer_2 option[value='" + demuxMapData[1].lut_id + "'").remove();
		$("#dr_demultiplexer_3 option[value='" + demuxMapData[1].lut_id + "'").remove();
	} else {
		$("#dr_demultiplexer_1").val(-1);
	}

	if (combToneData.find(x => x.id === demuxMapData[2].lut_id)) {
		$("#dr_demultiplexer_2").val(demuxMapData[2].lut_id);
		$("#dr_demultiplexer_0 option[value='" + demuxMapData[2].lut_id + "'").remove();
		$("#dr_demultiplexer_1 option[value='" + demuxMapData[2].lut_id + "'").remove();
		$("#dr_demultiplexer_3 option[value='" + demuxMapData[2].lut_id + "'").remove();
	} else {
		$("#dr_demultiplexer_2").val(-1);
	}

	if (combToneData.find(x => x.id === demuxMapData[3].lut_id)) {
		$("#dr_demultiplexer_3").val(demuxMapData[3].lut_id);
		$("#dr_demultiplexer_0 option[value='" + demuxMapData[3].lut_id + "'").remove();
		$("#dr_demultiplexer_1 option[value='" + demuxMapData[3].lut_id + "'").remove();
		$("#dr_demultiplexer_2 option[value='" + demuxMapData[3].lut_id + "'").remove();
	} else {
		$("#dr_demultiplexer_3").val(-1);
	}
}

function saveOpticalCombData(isShowMsg) {
	$.ajax({
		type: "Get",
		url: "../cgi/cgi_ModeMapManager.py",
		contentType: 'application/json',
		dataType: 'json',
		headers: {
			'Access-Control-Allow-Origin': '*'
		},
		data: {
			requestType: "update_mode_map",
			id: opticalFrequencyCombData[0].id,
			set_wavelength: $("#wavelength-setvalue1").val(),
			set_min_smsr: $("#frequency-setvalue1").val()
		},
		success: function (response) {
			if (isShowMsg) {
				if(response.status == "fail")
				{
					showModal('Error', response.description);
					$('.loaderDiv').css('display', 'none');
				}
				else{

					showModal('Success', response.description);
					$.ajax({
						type: "Get",
						url: "../cgi/cgi_DemuxMap.py",
						contentType: 'application/json',
						dataType: 'json',
						headers: {
							'Access-Control-Allow-Origin': '*'
						},
						data: {
							requestType: "read_CombTone"
						},
						success: function (response) {
							combToneData = response;
							loadModuleControlData();
							// BindDropdownCombToneData();
							isSetUnprotectedMode = true; //Demo-mode.js (if you set false then channel demultiplexer slider will stuck)
						},
						error: function (ex) {
							$("#test").html(ex.responseText)
						}
					});
				}
			}
		},
		error: function (ex) {
			$("#test").html(ex.responseText)
		}
	});
}
function saveOpticalCombData2(isShowMsg) {
	$.ajax({
		type: "Get",
		url: "../cgi/cgi_ModeMapManager.py",
		contentType: 'application/json',
		dataType: 'json',
		headers: {
			'Access-Control-Allow-Origin': '*'
		},
		data: {
			requestType: "update_mode_map",
			id: opticalFrequencyCombData[1].id,
			set_wavelength: $("#wavelength-setvalue2").val(),
			set_min_smsr: $("#frequency-setvalue2").val()
		},
		success: function (response) {
			if (isShowMsg) {
				if(response.status == "fail")
				{
					showModal('Error', response.description);
					$('.loaderDiv').css('display', 'none');
				}
				else{

					showModal('Success', response.description);
					$.ajax({
						type: "Get",
						url: "../cgi/cgi_DemuxMap.py",
						contentType: 'application/json',
						dataType: 'json',
						headers: {
							'Access-Control-Allow-Origin': '*'
						},
						data: {
							requestType: "read_CombTone"
						},
						success: function (response) {
							combToneData = response;
							loadModuleControlData();
							// BindDropdownCombToneData();
							isSetUnprotectedMode = true; //Demo-mode.js (if you set false then channel demultiplexer slider will stuck)
						},
						error: function (ex) {
							$("#test").html(ex.responseText)
						}
					});
				}
			}
		},
		error: function (ex) {
			$("#test").html(ex.responseText)
		}
	});
}

// for email form of connection page
function enableFormField(){
	$('#recipientEmail').prop("disabled", false);
}

$(document).ready(function () {



	/*-------------------------------Connection-------------------------------*/
	$('#myModal').on('hidden.bs.modal', function () {
		if (mymodal.find('.modal-title').text() == "Email Error") {
			$(".modal-header").css({
				"color": "#000",
				"background-color": "#fff"
			});
			$(".close").css({
				"color": "#000"
			});
			var setUpEmailModel = $("#setUpEmailModel");
			setUpEmailModel.modal('show');
		} 
		// else if (showMsgBox == true) {
		// 	$(".msg-box").fadeIn();
		// 	setTimeout(function () {
		// 		$(".msg-box").fadeOut();
		// 	}, 2000);
		// 	showMsgBox = false;
		// }
	});
	/*-----------------------------Module Control-----------------------------*/

	function saveStateOpticalCombData() {
		var set_frequency_state = $("#frequency-turn-on-off1").prop("checked") == true ? 1 : 0;
		var set_on_off_state = $("#wavelength-turn-on-off1").prop("checked") == true ? 1 : 0;
		$.ajax({
			type: "Get",
			url: "../cgi/cgi_ModeMapManager.py",
			contentType: 'application/json',
			dataType: 'json',
			headers: {
				'Access-Control-Allow-Origin': '*'
			},
			data: {
				requestType: "update_state_mode_map",
				id: opticalFrequencyCombData[0].id,
				set_on_off_state: set_on_off_state,
				set_power_state: set_frequency_state
			},
			success: function (response) {
				// console.log(opticalFrequencyCombData.set_on_off_state, set_on_off_state)
				if(opticalFrequencyCombData[0].state != set_on_off_state){
					if(set_on_off_state == 1)
						ShowNotif("Central Wevelength On",'success');
					else 
						ShowNotif("Central Wevelength Off",'success');
						
					loadModuleControlData();
				}
				if(opticalFrequencyCombData[0].setPowerState != set_frequency_state){
					if(set_frequency_state == 1)
						ShowNotif("Power (dbm) On",'success');
					else 
						ShowNotif("Power (dbm) Off",'success');
						
					loadModuleControlData();
				}
			},
			error: function (ex) {
				$("#test").html(ex.responseText);
			}
		});
	}
	function saveStateOpticalCombData2() {
		var set_frequency_state = $("#frequency-turn-on-off2").prop("checked") == true ? 1 : 0;
		var set_on_off_state = $("#wavelength-turn-on-off2").prop("checked") == true ? 1 : 0;
		$.ajax({
			type: "Get",
			url: "../cgi/cgi_ModeMapManager.py",
			contentType: 'application/json',
			dataType: 'json',
			headers: {
				'Access-Control-Allow-Origin': '*'
			},
			data: {
				requestType: "update_state_mode_map",
				id: opticalFrequencyCombData[1].id,
				set_on_off_state: set_on_off_state,
				set_power_state: set_frequency_state
			},
			success: function (response) {
				// console.log(opticalFrequencyCombData.set_on_off_state, set_on_off_state)
				if(opticalFrequencyCombData[1].state != set_on_off_state){
					if(set_on_off_state == 1)
						ShowNotif("Central Wevelength On",'success');
					else 
						ShowNotif("Central Wevelength Off",'success');
						
					loadModuleControlData();
				}
				if(opticalFrequencyCombData[1].setPowerState != set_frequency_state){
					if(set_frequency_state == 1)
						ShowNotif("Power (dbm) On",'success');
					else 
						ShowNotif("Power (dbm) Off",'success');
						
					loadModuleControlData();
				}
			},
			error: function (ex) {
				$("#test").html(ex.responseText);
			}
		});
	}
	function saveDemoStateOpticalCombData() {
		var demo_state = $("#demo-wavelength-turn-on-off").prop("checked") == true ? 1 : 0;
		// var set_on_off_state = $("#wavelength-turn-on-off").prop("checked") == true ? 1 : 0;
		$.ajax({
			type: "Get",
			url: "../cgi/cgi_CombMapManager.py",
			contentType: 'application/json',
			dataType: 'json',
			headers: {
				'Access-Control-Allow-Origin': '*'
			},
			data: {
				requestType: "update_demo_state_comb_map",
				id: opticalFrequencyCombData[0].id,
				// set_on_off_state: set_on_off_state,
				demo_state: demo_state
			},
			success: function (response) {
				if(opticalFrequencyCombData[0].demoState != demo_state){
					if(demo_state == 1)
						ShowNotif("Central Wevelength On",'success');
					else 
						ShowNotif("Central Wevelength Off",'success');
					loadDemoData();
				}
				
				//showModal('Success',response.description);
			},
			error: function (ex) {
				$("#test").html(ex.responseText);
			}
		});
	}


	//tooltip
	$(".tooltipBtn").mouseover(function () {
		var tooltiptext = $(this).children()[3];
		if ($($(this).children()[0]).prop("checked"))
			$(tooltiptext).text('Turn Off').fadeIn();
		else
			$(tooltiptext).text('Turn On').fadeIn();

	});
	$('.tooltipBtn').mouseleave(function () {
		var tooltiptext = $(this).children()[3];
		$(tooltiptext).fadeOut();
	});

	//warning box 
	$(".btn-cancel").click(function () {
		$(".error-msg").css("display", "none");
		$("#warning-password").val('');
		$(".warning-box-layout").fadeOut();
		$("body").css("overflow", "auto");
		$(".setvalue").prop("disabled", false);
		$(".setvalueidac").prop("disabled", false);
		$(".connectionSetValue").prop("disabled", false);
	});

	$("#warning-password").focus(function () {
		$(".error-msg").css("display", "none");
	});

	$(".btn-submit").click(function () {
		$.ajax({
			type: "Get",
			url: "../cgi/cgi_ValidateUser.py",
			contentType: 'application/json',
			dataType: 'json',
			headers: {
				'Access-Control-Allow-Origin': '*'
			},
			data: {
				requestType: "validate_password",
				password: $("#warning-password").val()
			},
			success: function (response) {
				if (parseInt(response.isvalidPassword) == 1) {
					if (commonOpticalCombId == "#demo-wavelength-turn-on-off") {
						isDemoSetUnprotectedMode = true;
						if(isIDriveValChange == true){
							$("#demo-wavelength-switch-off").css("pointerEvents", "none");
						}
						else{
							$("#demo-wavelength-switch-off").css("pointerEvents", "auto");
						}
						$(".demo-setvalue").prop("disabled", false);
					} else {
						if(isIDriveValChange == true){
							$("#wavelength-switch-off").css("pointerEvents", "none");
						}else{
							$("#wavelength-switch-off").css("pointerEvents", "auto");
						}
						isSetUnprotectedMode = true;
						$(".setvalue").prop("disabled", false);
						$(".setvalueidac").prop("disabled", false);
					}

					$(".warning-box-layout").fadeOut();
					$("body").css("overflow", "auto");
					$("#warning-password").val('');
					isSetUnprotectedMode = true;
					$(".connectionSetValue").prop("disabled", false);
				} else {
					$(".error-msg").css("display", "block");
				}
			},
			error: function (ex) {
				console.log(ex);
			}
		});
	});

	$(".setvalue").focus(function () {
		if (isSetUnprotectedMode == false) {
			commonOpticalCombId = "#wavelength-turn-on-off";
			if ($("#wavelength-turn-on-off").prop("checked") == true) {
				$(".state-box-layout").fadeIn();
			} else {
				$(this).prop("disabled", true);
				$(".warning-box-layout").fadeIn();
				$("#warning-password").focus();
			}
		}
	});

	$(".idriveBtn").click(function (e) {
		if (isSetUnprotectedMode == false) {
			commonOpticalCombId = "#wavelength-turn-on-off";
			e.preventDefault();
			if ($("#wavelength-turn-on-off").prop("checked") == true) {
				$(".state-box-layout").fadeIn();
			} else {
				$(".warning-box-layout").fadeIn();
				$("#warning-password").focus();
			}
		}
	});

	$(".close-icon").click(function () {
		$(".btn-cancel").trigger("click");
		$(".state-box-layout").fadeOut();
	});

	$(".set-on-yes").click(function () {
		$(commonOpticalCombId).prop("checked", false);
		isIDriveValChange = true
		saveStateOpticalCombData();
		$(".state-box-layout").hide();
		$(".warning-box-layout").fadeIn();
		$("#warning-password").focus();
	});

	$(".set-off-no").click(function () {
		$(".state-box-layout").fadeOut();
	});

	$("#wavelength-turn-on-off1,#frequency-turn-on-off1").change(function () {
		saveStateOpticalCombData();
	});
	$("#wavelength-turn-on-off2,#frequency-turn-on-off2").change(function () {
		saveStateOpticalCombData2();
	});
	$("#demo-wavelength-turn-on-off").change(function () {
		saveDemoStateOpticalCombData();
	});

	$(document).keypress(function (event) {
		var keycode = (event.keyCode ? event.keyCode : event.which);
		if (keycode == '13') {
			if ($(".state-box-layout").css('display') == 'block') {
				$(".set-on-yes").trigger('click');
			} else if ($(".warning-box-layout").css('display') == 'block') {
				$(".btn-submit").trigger('click');
			}
		} else if (keycode == '27') {
			if ($(".state-box-layout").css('display') == 'block') {
				$(".set-off-no").trigger('click');
			} else if ($(".warning-box-layout").css('display') == 'block') {
				$(".btn-submit").trigger('click');
			}
		}
	});

	// for validation of input boxes and sliders of connection, calibration, demo
	$(".connectionSetValue").focus(function (event) {
		if (isSetUnprotectedMode == false) {
			$(this).prop("disabled", true);
			$(".warning-box-layout").fadeIn();
			$("#warning-password").focus();
		}
	});

	/*------------------------------Demo Mode Page---------------------------------------------*/


	/*--------------------------- Calibration ----------------------------*/





	// $("#debug_tab").click(function () {
	// 	if ($("#cal-wavelength-slider-debug").next().length == 0) {
	// 		loadSlider(calibrationWaveSliderObj, "#cal-wavelength-slider-debug", "#cal-wavelength-slider-debug", 0, 100, 25, caliSliders, true, 1, false, 0, false);
	// 		//	loadSlider(calibrationFreqSliderObj,"#cal-wavelength-slider-debug","#cal-frequency-slider-debug",0,100,25,caliSliders,true,1,false,0,false);
	// 		$("#cal-wavelength-slider-debug").prop("disabled", true);
	// 		//$("#cal-frequency-slider-debug").prop("disabled",true);
	// 	}
	// });




	//$("#cal-frequency-setvalue-debug").change(function(){
	//      var value=parseFloat(parseFloat($(this).val()).toFixed(2));
	//    calibrationFreqSliderObj.slider.setValues(value,100)
	//});


	// $("#operationDropdown").change(function () {
	// 	if ($(this).val() == "OPS") {
	// 		$("#demultiplexer1Value-debug").text('Scope detected');
	// 	} else {
	// 		//	$("#demultiplexer1Value-debug").text('OSA detected');
	// 	}

	// 	if (parseInt($(this).val()) == -1) {
	// 		$("#cal-wavelength-setvalue-debug").prop("disabled", true);
	// 		//	$("#cal-frequency-setvalue-debug").prop("disabled",true);
	// 		//	calibrationWaveSliderObj.slider.conf.isIDrive=true;
	// 		calibrationFreqSliderObj.slider.conf.isIDrive = true;
	// 	} else {
	// 		$("#cal-wavelength-setvalue-debug").prop("disabled", false);
	// 		//	$("#cal-frequency-setvalue-debug").prop("disabled",false);
	// 		//	calibrationWaveSliderObj.slider.conf.isIDrive=false;
	// 		calibrationFreqSliderObj.slider.conf.isIDrive = false;
	// 	}
	// });

	setInterval(readReverseSshStatus, 10000);


});

$("input[name='enReverseSSH']").on('change', function () {
    const selectedValue = $(this).val(); // use .val() instead of .attr('value')

    if (selectedValue === "no" && isReverseSSHConnected) {
        alert("Reverse SSH is already connected. Disconnect first before disabling.");
        
        // Re-select "yes"
        $("input[name='enReverseSSH'][value='yes']").prop("checked", true);
        return;
    }

    if (selectedValue === "yes") {
        $("#reverseSshConfig").show();
        $("#connectReverseSSH").attr("disabled", false).css("cursor", "pointer");
    } else {
        $("#reverseSshConfig").hide();
        $("#connectReverseSSH").attr("disabled", true).css("cursor", "not-allowed");
    }
});


$("#rs_key_path").on("change", function () {
  const file = this.files[0];
  if (file) {
    $("#key_file_name").text(file.name);
  } else {
    $("#key_file_name").text("None");
  }
});
function connectReverse(){
	$('.loaderDiv').css('display', 'block');
	$.ajax({
		type: "Get",
		url: "../cgi/cgi_EnableSsh.py",
		contentType: 'application/json',
		dataType: 'json',
		headers: {
			'Access-Control-Allow-Origin': '*'
		},
		data: {
			requestType: "connectReverseSSH",
		},
		success: function (response) {
			$('.loaderDiv').css('display', 'none');
			if(response?.status == "error"){
				$(".modal-header").css({
					"color": "#fff",
					"background-color": "#db4141"
				});
				$(".close").css({
					"color": "#fff"
				});
			}
			readReverseSshStatus();
			mymodal.find('.modal-title').text('Reverse SSH');
            mymodal.find('.modal-body').text(response.description).css({"text-align":"center"});
            mymodal.modal('show');

			// mymodal.one('hidden.bs.modal', function () {
			// 	let port = $("#rs_remote_port").val();
			// 	window.open(`http://34.253.161.228:${port}`, '_blank', 'width=800,height=600');
			// });

            setTimeout(()=> {
                mymodal.modal("hide")
                $(".modal-header").css({
                    "color": "#000",
                    "background-color": "#fff"
                });
                $(".close").css({
                    "color": "#000"
                });
            },autoClose)

			// window.open('http://34.253.161.228:7681', '_blank', 'width=800,height=600');
			
		},
		error: function (ex) {
			$('.loaderDiv').css('display', 'none');
			console.log(ex);
		}
	});
}

function disconnectReverse(){
	$('.loaderDiv').css('display', 'block');
	$.ajax({
		type: "Get",
		url: "../cgi/cgi_EnableSsh.py",
		contentType: 'application/json',
		dataType: 'json',
		headers: {
			'Access-Control-Allow-Origin': '*'
		},
		data: {
			requestType: "disconnectReverseSSH",
		},
		success: function (response) {
			$('.loaderDiv').css('display', 'none');
			if(response?.status == "error"){
				$(".modal-header").css({
					"color": "#fff",
					"background-color": "#db4141"
				});
				$(".close").css({
					"color": "#fff"
				});
			}
			readReverseSshStatus();
			mymodal.find('.modal-title').text('Reverse SSH');
            mymodal.find('.modal-body').text(response.description).css({"text-align":"center"});
            mymodal.modal('show');

            setTimeout(()=> {
                mymodal.modal("hide")
                $(".modal-header").css({
                    "color": "#000",
                    "background-color": "#fff"
                });
                $(".close").css({
                    "color": "#000"
                });
            },autoClose)
			
		},
		error: function (ex) {
			$('.loaderDiv').css('display', 'none');
			console.log(ex);
		}
	});
}

function readReverseSshStatus(){
	let enable_reverse =  $("input[name='enReverseSSH']:checked").val();
	if(enable_reverse == "no"){
		$("#connectReverseSSH").attr({"disabled": true}).css("cursor", "not-allowed");
		$("#disconnectReverseSSH").attr("disabled", true).css("cursor", "not-allowed");
		$("#reverseSshStatus").text("");
		return
	}
	// else{
	// 	$("#connectReverseSSH").attr({"disabled": false}).css("cursor", "pointer");
	// 	$("#disconnectReverseSSH").attr({"disabled": false}).css("cursor", "pointer");
	// }
	$.ajax({
		type: "Get",
		url: "../cgi/cgi_EnableSsh.py",
		contentType: 'application/json',
		dataType: 'json',
		headers: {
			'Access-Control-Allow-Origin': '*'
		},
		data: {
			requestType: "reverseSSHStatus",
		},
		success: function (response) {
			isReverseSSHConnected = response?.connected;
			
			if(response?.connected){
				$("#connectReverseSSH").attr({"disabled": true}).css("cursor", "not-allowed");
				$("#disconnectReverseSSH").attr({"disabled": false}).css("cursor", "pointer");
				$("#reverseSshStatus").text(response.description).css({"color":"green"});
			}
			else{
				$("#connectReverseSSH").attr("disabled",false).css("cursor", "pointer");
				$("#disconnectReverseSSH").attr("disabled", true).css("cursor", "not-allowed");
				$("#reverseSshStatus").text(response.description).css({"color":"red"});

			}
			
		},
		error: function (ex) {
			console.log(ex);
		}
	});
}


const cancelReverse = () => {
	$("#rs_remote_ip").val(reverseSShData?.remote_ip),
	$("#rs_remote_port").val(reverseSShData?.remote_port),
	$("#rs_remote_user").val(reverseSShData?.username),
	$("#rs_local_port").val(reverseSShData?.local_port),
	$("#key_file_name").html(reverseSShData?.key_path).css({"color":"green"})
	$("#rs_key_path").html(reverseSShData?.file_content);
	validateReverseSSHForm();
}