// Page Description
// loadSlider() call from setup.js and take parameter sliderobj,sliderId,slidersetupValueId,min value,max value, width of slider
// loadSlider() width of slider from constant.js file

moduleControlParameters = [{
	moduleType: "temperature",
	url: "../cgi/cgi_TECManager.py",
	data: {
		requestType: "read_TEC"
	}
},
{
	moduleType: "centralWavelength",
	url: "../cgi/cgi_ModeMapManager.py",
	data: {
		requestType: "read_mode_map",
		id: 1
	}
},
{
	moduleType: "sweep",
	url: "../cgi/cgi_Sweep.py",
	data: {
		requestType: "read_sweep",
	}
},
	// {
	// 	moduleType: "RFSynthesizer",
	// 	url: "../cgi/cgi_RFAmp.py",
	// 	data: {
	// 		requestType: "read_RFAmp",
	// 		name: "Amp-Section2-SlaveGain1-RF-Synthesizer"
	// 	}
	// },
	// {
	// 	moduleType: "iDrive",
	// 	url: "../cgi/cgi_IDriveManager.py",
	// 	data: {
	// 		requestType: "read_i_drive"
	// 	}
	// },
	// {
	// 	moduleType: "comboTone",
	// 	url: "../cgi/cgi_DemuxMap.py",
	// 	data: {
	// 		requestType: "read_CombTone"
	// 	}
	// },
	// {
	// 	moduleType: "demuxMap",
	// 	url: "../cgi/cgi_DemuxMap.py",
	// 	data: {
	// 		requestType: "read_DemuxMap"
	// 	}
	// },
	// {
	// 	moduleType: "demoDemuxMap",
	// 	url: "../cgi/cgi_DemuxMap.py",
	// 	data: {
	// 		requestType: "read_DemoDemuxMap"
	// 	}
	// },
	// {
	// 	moduleType: "demoComboTone",
	// 	url: "../cgi/cgi_DemuxMap.py",
	// 	data: {
	// 		requestType: "read_DemoCombTone"
	// 	}
	// },
];

function BindIdriveData() {
	iDriveData.forEach(function (data, index) {
		if (data.set_current == null)
			iDriveData[index].set_current = 0;

		if (data.state == 0)
			$("#iDrive_State_" + index).attr("src", "../images/redLed.png");
		else if (data.state == 1)
			$("#iDrive_State_" + index).attr("src", "../images/greenLed.png");
		else
			$("#iDrive_State_" + index).attr("src", "../images/warningLed.png");

		$("#iDrive_CrReading_" + index).text(data.get_current);
		if (data.set_on_off_state == 1)
			$("#iDrive_Switch_" + index).prop("checked", true);
		else
			$("#iDrive_Switch_" + index).prop("checked", false);

		$("#iDrive_Setvalue_" + index).val(data.set_current);

		$("#iDrive_Setvalue_" + index).change(function () {
			var value = parseFloat(parseFloat($(this).val()).toFixed(2));
			eval("iDrive_Slider_Obj_" + index).slider.setValues(value, data.set_current_limit);
			outOffRange(data.set_min_current, data.set_current_limit, value)
			idriveId.push(data.id);
		});

		$("#iDrive_Switch_" + data.id).change(function () {
			idriveId.push(data.id);
		});

		if (eval("iDrive_Slider_Obj_" + index).slider != undefined)
			eval("iDrive_Slider_Obj_" + index).slider.setValues(data.set_current, data.set_current_limit);
	});
}

function BindDemuxMapData(set) {
	demuxMapData.forEach(function (d, index) {
		if (set == 0 || set == 1) {
			$("#Demux_Setvalue_" + index).val(d.set_demux_power);
			$("#Demux_Switch_" + index).prop("checked", d.set_on_off_state == 1 ? true : false);
			$("#Demux_Setvalue_" + index).change(function () {
				var value = parseFloat(parseFloat($(this).val()).toFixed(2));
				eval("Demux_Slider_Obj_" + index).slider.setValues(value, d.get_max_Demux_power);
				outOffRange(d.get_demux_power, d.get_max_Demux_power, value)
			});
		}
	});
}

function BindCombData(set) {
	if (set == 0 || set == 1) {
		if (opticalFrequencyCombData[0].state == true)
			$("#wavelength-turn-on-off1").prop("checked", true);
		else
			$("#wavelength-turn-on-off1").prop("checked", false);
		if (opticalFrequencyCombData[1].state == true)
			$("#wavelength-turn-on-off2").prop("checked", true);
		else
			$("#wavelength-turn-on-off2").prop("checked", false);
		if (opticalFrequencyCombData[0].setPowerState == 1)
			$("#frequency-turn-on-off1").prop("checked", true);
		else
			$("#frequency-turn-on-off1").prop("checked", false);
		if (opticalFrequencyCombData[1].setPowerState == 1)
			$("#frequency-turn-on-off2").prop("checked", true);
		else
			$("#frequency-turn-on-off2").prop("checked", false);
		$("#wavelength-setvalue1").val(opticalFrequencyCombData[0].setWaveLength);
		$("#wavelength-setvalue2").val(opticalFrequencyCombData[1].setWaveLength);
		$("#frequency-setvalue1").val(opticalFrequencyCombData[0].setPower ?? 0);
		$("#frequency-setvalue2").val(opticalFrequencyCombData[1].setPower ?? 0);
	}
	if (set == 0 || set == 2) {
		if (opticalFrequencyCombData[0].demoState == 1)
			$("#demo-wavelength-turn-on-off").prop("checked", true);
		else
			$("#demo-wavelength-turn-on-off").prop("checked", false);
		$("#demo-wavelength-setvalue").val(opticalFrequencyCombData[0].demoWavelength);
		$("#demo-frequency-setvalue").val(opticalFrequencyCombData[0].demoFSR);
	}
}

function saveRFSynthData(url, requestType, id, frequency, power, onoffState, showMsg) {
	$.ajax({
		type: "Get",
		url: url,
		contentType: 'application/json',
		dataType: 'json',
		headers: {
			'Access-Control-Allow-Origin': '*'
		},
		data: {
			requestType: requestType,
			id: id,
			set_Frequency: frequency,
			set_Power: power,
			OnOffState: onoffState
		},
		success: function (response) {
			$('.loaderDiv').css('display', 'none');
			if (showMsg)
				showModal('Success', response.description);
		},
		error: function (ex) {
			$("#test").html(ex.responseText)
		}
	});
}

function saveData(url, requestType, id, name, setValue, turnOnOffState, showMsg) {
	if (setValue == "")
		setValue = 0;

	$.ajax({
		type: "Get",
		url: url,
		contentType: 'application/json',
		dataType: 'json',
		headers: {
			'Access-Control-Allow-Origin': '*'
		},
		data: {
			requestType: requestType,
			id: id,
			name: name,
			set_on_off_state: turnOnOffState,
			set_current: setValue
		},
		success: function (response) {
			if (showMsg) {
				if (response?.status == 'fail') {
					showModal('Error', response.description);
					$('.loaderDiv').css('display', 'none');
				}
				else {
					showModal('Success', response.description);
					setTimeout(() => {
						$("#myModal").modal("hide");

					}, autoClose)
					loadModuleControlData();
				}
			}
			else {
				if (response?.status == 'fail') {
					showModal('Error', response.description);
					$('.loaderDiv').css('display', 'none');
				}
				else {
					$('.loaderDiv').css('display', 'none');
					showModal('Success', "Updated successfully ");
				}
			}
		},
		error: function (ex) {
			$("#test").html(ex.responseText)
		}
	});
}

function saveDemultiplexData(url, requestType, id, name, setvalue, turnOffState, demux_id, set_tone, showMsg) {
	if (setvalue == "")
		setvalue = 0;

	$.ajax({
		type: "Get",
		url: url,
		contentType: 'application/json',
		dataType: 'json',
		headers: {
			'Access-Control-Allow-Origin': '*'
		},
		data: {
			requestType: requestType,
			id: id,
			name: name,
			set_on_off_state: turnOffState,
			set_power: setvalue,
			lut_id: demux_id,
			set_tone: set_tone
		},
		success: function (response) {
			console.log(response.status + "," + response.description);
			if (showMsg)
				showModal(response.status, response.description);
		},
		error: function (ex) {
			$("#test").html(ex.responseText)
		}
	});
}


function loadModuleControlData() {
	return new Promise(function (resolve, reject) {
		let i = 1;
		moduleControlParameters.forEach(function (parameter) {
			$.ajax({
				type: "Get",
				url: parameter.url,
				async: false,
				contentType: 'application/json',
				dataType: 'json',
				headers: {
					'Access-Control-Allow-Origin': '*'
				},
				data: parameter.data,
				success: function (response) {
					switch (parameter.moduleType) {
						case "temperature":
							techData = response;
							break;
						case "centralWavelength":
							opticalFrequencyCombData = response;
							BindCombData(0);
							break;
						case "iDrive":
							iDriveData = response;
							BindIdriveData();
							break;
						case "RFSynthesizer":
							rfSynthData = response[0];
							break;
						case "comboTone":
							combToneData = response;
							break;
						case "demuxMap":
							demuxMapData = response;
							BindDemuxMapData(0);
							break;
						case "sweep":
							sweepdata = response;
							$("#start_wavelegth").val(sweepdata[0].start_wave);
							$("#stop_wavelegth").val(sweepdata[0].stop_wave);
							$("#increment_wavelegth").val(((sweepdata[0].increment_wave).toFixed(1)));
							$("#repetation_rate").val(sweepdata[0].repetition_rate);
							$("#chirp_bandwith").val(sweepdata[0].chirp_bandwidth);
							$("#chirp_frequency").val(sweepdata[0].chirp_frequency);
							$("#start_wavelegth1").val(sweepdata[1].start_wave);
							$("#stop_wavelegth1").val(sweepdata[1].stop_wave);
							$("#increment_wavelegth1").val(((sweepdata[1].increment_wave).toFixed(1)));
							$("#repetation_rate1").val(sweepdata[1].repetition_rate);
							$("#chirp_bandwith1").val(sweepdata[1].chirp_bandwidth);
							$("#chirp_frequency1").val(sweepdata[1].chirp_frequency);
							// BindDemuxMapData(0);
							break;
						// case "demoDemuxMap":
						// 	demoDemuxMapData = response;
						// 	BindDemoDemuxMapData(0);
						// 	break;
						// case "demoComboTone":
						// 	demoCombToneData = response;
						// 	BindDemoDropdownCombToneData();
						// 	break;
					}
					$("#graph-water-mark").addClass("d-none");
					$(".main-tab-content").removeClass("d-none");
					$('.loaderDiv').css('display', 'none');
					if (moduleControlParameters.length == i) {
						resolve()
					}
					else {
						++i;
					}
				},
				error: function (ex) {
					// $("#test").html(ex.responseText)
					if (moduleControlParameters.length == i) {
						reject(ex)
					}
					else {
						++i;
					}
				}
			});
		});
	})
	// if ($("#demo_dr_demultiplexer_0").val() == -1 || $("#demo_dr_demultiplexer_1").val() == -1 || $("#demo_dr_demultiplexer_2").val() == -1 || $("#demo_dr_demultiplexer_3").val() == -1) {
	// 	$("#updateView").prop("disabled", true);
	// }
}
$(document).ready(function () {

	loadModuleControlData().then(function () {
		//general temperature
		$("#general-tab1").click(function () {
			if ($("#general-slider1").next().length == 0) {
				setTimeout(function () {
					loadSlider(tempSliderObj, "#general-slider1", "#general-setvalue1", techData[0].setMinTemp, techData[0].setMaxTemp, techData[0].setTemp, generalSliderWidthLVL1, false, 0.01, false);
					readJsonData(moduleControlParameters[0].moduleType, techData);
				}, 1);
			}
		});
		$("#general-tab2").click(function () {
			if ($("#general-slider2").next().length == 0) {
				setTimeout(function () {
					loadSlider(tempSliderObj1, "#general-slider2", "#general-setvalue2", techData[1].setMinTemp, techData[1].setMaxTemp, techData[1].setTemp, generalSliderWidthLVL1, false, 0.01, false);
					readJsonData(moduleControlParameters[0].moduleType, techData);
				}, 1);
			}
		});

		//Optical comb
		$("#laser-tab1").click(function () {
			if ($("#central-wavelength-slider1").next().length == 0) {
				setTimeout(function () {
					loadSlider(centralWavelengthSliderObj, "#central-wavelength-slider1", "#wavelength-setvalue1", opticalFrequencyCombData[0].minWavelength, opticalFrequencyCombData[0].maxWaveLength, opticalFrequencyCombData[0].setWaveLength, generalSliderWidthLVL1, false, 1, true);
					// loadSlider(combFrequencySliderObj, "#repetation-rate-slider", "#repetation-setvalue", opticalFrequencyCombData[0].get_min_FSR, opticalFrequencyCombData[0].get_max_FSR, opticalFrequencyCombData[0].set_comb_FSR, generalSliderWidthLVL1, false, 1, true);
					loadSlider(combFrequencySliderObj, "#central-frequency-slider1", "#frequency-setvalue1", opticalFrequencyCombData[0].minPower, opticalFrequencyCombData[0].maxPower, opticalFrequencyCombData[0].setPower, generalSliderWidthLVL1, false, 0.01, false);
				}, 1);
			}
			$("#optical-comb-tab").animate({
				scrollTop: 10 // Scroll up by 10 pixels
			}, 1500);

		});
		$("#laser-tab2").click(function () {
			if ($("#central-wavelength-slider2").next().length == 0) {
				setTimeout(function () {
					loadSlider(centralWavelengthSliderObj1, "#central-wavelength-slider2", "#wavelength-setvalue2", opticalFrequencyCombData[1].minWavelength, opticalFrequencyCombData[1].maxWaveLength, opticalFrequencyCombData[1].setWaveLength, generalSliderWidthLVL1, false, 1, true);
					// loadSlider(combFrequencySliderObj, "#repetation-rate-slider", "#repetation-setvalue", opticalFrequencyCombData[1].get_min_FSR, opticalFrequencyCombData[1].get_max_FSR, opticalFrequencyCombData[1].set_comb_FSR, generalSliderWidthLVL1, false, 1, true);
					loadSlider(combFrequencySliderObj1, "#central-frequency-slider2", "#frequency-setvalue2", opticalFrequencyCombData[1].minPower, opticalFrequencyCombData[1].maxPower, opticalFrequencyCombData[1].setPower, generalSliderWidthLVL1, false, 0.01, false);
				}, 1);
			}
		});

		$("#slave-laser-tab").click(function () {
			if ($("#iDrive_Slider_0").next().length == 0) {
				setTimeout(function () {
					loadSlider(iDrive_Slider_Obj_0, "#iDrive_Slider_0", "#iDrive_Setvalue_0", iDriveData[0].set_min_current, iDriveData[0].set_current_limit, iDriveData[0].set_current, slaveLaserWidth, true, 0.01, false, false, iDriveData[0].id, false);
				}, 1);
			}
			if ($("#iDrive_Slider_1").next().length == 0) {
				setTimeout(function () {
					loadSlider(iDrive_Slider_Obj_1, "#iDrive_Slider_1", "#iDrive_Setvalue_1", iDriveData[1].set_min_current, iDriveData[1].set_current_limit, iDriveData[1].set_current, slaveLaserWidth, true, 0.01, false, false, iDriveData[1].id, false);
					loadSlider(rfSynthFqSliderObj, "#rfSynth-fq-slider", "#rfSynth-fq-setvalue", rfSynthData.min_Frequency, rfSynthData.max_Freqency, rfSynthData.set_Frequency, slaveLaserWidth, true, 0.01, false, false, rfSynthData.id, true);
					loadSlider(rfSynthPwSliderObj, "#rfSynth-power-slider", "#rfSynth-power-setvalue", rfSynthData.min_Power, rfSynthData.max_Power, rfSynthData.set_Power, slaveLaserWidth, true, 0.01, false, false, rfSynthData.id, true);
					readJsonData(moduleControlParameters[2].moduleType, rfSynthData);
				}, 1);
			}
		});

		//VOA current control
		$("#voa-tab").click(function () {
			if ($("#iDrive_Slider_2").next().length == 0) {
				setTimeout(function () {
					loadSlider(iDrive_Slider_Obj_2, "#iDrive_Slider_2", "#iDrive_Setvalue_2", iDriveData[2].set_min_current, iDriveData[2].set_current_limit, iDriveData[2].set_current, slaveLaserWidth, true, 0.01, false, false, iDriveData[2].id, false);
				}, 1);
			}
		});

		$("#master-laser-tab").click(function () {
			if ($("#iDrive_Slider_3").next().length == 0) {
				setTimeout(function () {
					loadSlider(iDrive_Slider_Obj_3, "#iDrive_Slider_3", "#iDrive_Setvalue_3", iDriveData[3].set_min_current, iDriveData[3].set_current_limit, iDriveData[3].set_current, slaveLaserWidth, true, 0.01, false, false, iDriveData[3].id, false);
				}, 1);
			}
			if ($("#iDrive_Slider_4").next().length == 0) {
				setTimeout(function () {
					loadSlider(iDrive_Slider_Obj_4, "#iDrive_Slider_4", "#iDrive_Setvalue_4", iDriveData[4].set_min_current, iDriveData[4].set_current_limit, iDriveData[4].set_current, slaveLaserWidth, true, 0.01, false, false, iDriveData[4].id, false);
				}, 1);
			}
		});

		//Coupler
		$("#coupler-tab").click(function () {
			if ($("#iDrive_Slider_5").next().length == 0) {
				setTimeout(function () {
					loadSlider(iDrive_Slider_Obj_5, "#iDrive_Slider_5", "#iDrive_Setvalue_5", iDriveData[5].set_min_current, iDriveData[5].set_current_limit, iDriveData[5].set_current, slaveLaserWidth, true, 0.01, false, false, iDriveData[5].id, false);
				}, 1);
			}
		});

		$("#demux1-tab").click(function () {
			if ($("#iDrive_Slider_6").next().length == 0) {
				setTimeout(function () {
					loadSlider(iDrive_Slider_Obj_6, "#iDrive_Slider_6", "#iDrive_Setvalue_6", iDriveData[6].set_min_current, iDriveData[6].set_current_limit, iDriveData[6].set_current, slaveLaserWidth, true, 0.01, false, false, iDriveData[6].id, false);
				}, 1);
			}
			if ($("#iDrive_Slider_7").next().length == 0) {
				setTimeout(function () {
					loadSlider(iDrive_Slider_Obj_7, "#iDrive_Slider_7", "#iDrive_Setvalue_7", iDriveData[7].set_min_current, iDriveData[7].set_current_limit, iDriveData[7].set_current, slaveLaserWidth, true, 0.01, false, false, iDriveData[7].id, false);
				}, 1);
			}
		});

		$("#demux2-tab").click(function () {
			if ($("#iDrive_Slider_8").next().length == 0) {
				setTimeout(function () {
					loadSlider(iDrive_Slider_Obj_8, "#iDrive_Slider_8", "#iDrive_Setvalue_8", iDriveData[8].set_min_current, iDriveData[8].set_current_limit, iDriveData[8].set_current, slaveLaserWidth, true, 0.01, false, false, iDriveData[8].id, false);
				}, 1);
			}
			if ($("#iDrive_Slider_9").next().length == 0) {
				setTimeout(function () {
					loadSlider(iDrive_Slider_Obj_9, "#iDrive_Slider_9", "#iDrive_Setvalue_9", iDriveData[9].set_min_current, iDriveData[9].set_current_limit, iDriveData[9].set_current, slaveLaserWidth, true, 0.01, false, false, iDriveData[9].id, false);
				}, 1);
			}
		});

		$("#demux3-tab").click(function () {
			if ($("#iDrive_Slider_10").next().length == 0) {
				setTimeout(function () {
					loadSlider(iDrive_Slider_Obj_10, "#iDrive_Slider_10", "#iDrive_Setvalue_10", iDriveData[10].set_min_current, iDriveData[10].set_current_limit, iDriveData[10].set_current, slaveLaserWidth, true, 0.01, false, false, iDriveData[10].id, false);
				}, 1);
			}
			if ($("#iDrive_Slider_11").next().length == 0) {
				setTimeout(function () {
					loadSlider(iDrive_Slider_Obj_11, "#iDrive_Slider_11", "#iDrive_Setvalue_11", iDriveData[11].set_min_current, iDriveData[11].set_current_limit, iDriveData[11].set_current, slaveLaserWidth, true, 0.01, false, false, iDriveData[11].id, false);
				}, 1);
			}
		});

		$("#demux4-tab").click(function () {
			if ($("#iDrive_Slider_12").next().length == 0) {
				setTimeout(function () {
					loadSlider(iDrive_Slider_Obj_12, "#iDrive_Slider_12", "#iDrive_Setvalue_12", iDriveData[12].set_min_current, iDriveData[12].set_current_limit, iDriveData[12].set_current, slaveLaserWidth, true, 0.01, false, false, iDriveData[12].id, false);
				}, 1);
			}
			if ($("#iDrive_Slider_13").next().length == 0) {
				setTimeout(function () {
					loadSlider(iDrive_Slider_Obj_13, "#iDrive_Slider_13", "#iDrive_Setvalue_13", iDriveData[13].set_min_current, iDriveData[13].set_current_limit, iDriveData[13].set_current, slaveLaserWidth, true, 0.01, false, false, iDriveData[13].id, false);
				}, 1);
			}
		});

		$("#demux-tab").click(function () {
			if ($("#Demux_Slider_0").next().length == 0) {
				BindDropdownCombToneData();
				setTimeout(function () {
					loadSlider(Demux_Slider_Obj_0, "#Demux_Slider_0", "#Demux_Setvalue_0", demuxMapData[0].get_demux_power, demuxMapData[0].get_max_Demux_power, demuxMapData[0].set_demux_power, demuxSliderWidth, true, 0.01, false);
					loadSlider(Demux_Slider_Obj_1, "#Demux_Slider_1", "#Demux_Setvalue_1", demuxMapData[1].get_demux_power, demuxMapData[1].get_max_Demux_power, demuxMapData[1].set_demux_power, demuxSliderWidth, true, 0.01, false);
					loadSlider(Demux_Slider_Obj_2, "#Demux_Slider_2", "#Demux_Setvalue_2", demuxMapData[2].get_demux_power, demuxMapData[2].get_max_Demux_power, demuxMapData[2].set_demux_power, demuxSliderWidth, true, 0.01, false);
					loadSlider(Demux_Slider_Obj_3, "#Demux_Slider_3", "#Demux_Setvalue_3", demuxMapData[3].get_demux_power, demuxMapData[3].get_max_Demux_power, demuxMapData[3].set_demux_power, demuxSliderWidth, true, 0.01, false);
				}, 1);
			}
		});

		$("#general-setvalue1").change(function () {
			var value = parseFloat(parseFloat($(this).val()).toFixed(2));
			tempSliderObj.slider.setValues(value, techData[0].setMaxTemp);
			outOffRange(techData[0].setMinTemp, techData[0].setMaxTemp, value);
		});
		$("#general-setvalue2").change(function () {
			var value = parseFloat(parseFloat($(this).val()).toFixed(2));
			tempSliderObj1.slider.setValues(value, techData[1].setMaxTemp);
			outOffRange(techData[1].setMinTemp, techData[1].setMaxTemp, value);
		});

		$("#wavelength-setvalue1").change(function () {
			var value = parseFloat(parseFloat($(this).val()).toFixed(2));
			centralWavelengthSliderObj.slider.setValues(value, opticalFrequencyCombData[0].get_max_central_wavelength)
			outOffRange(opticalFrequencyCombData[0].get_min_central_wavelength, opticalFrequencyCombData[0].get_max_central_wavelength, value)
		});
		$("#wavelength-setvalue2").change(function () {
			var value = parseFloat(parseFloat($(this).val()).toFixed(2));
			centralWavelengthSliderObj1.slider.setValues(value, opticalFrequencyCombData[1].get_max_central_wavelength)
			outOffRange(opticalFrequencyCombData[1].get_min_central_wavelength, opticalFrequencyCombData[1].get_max_central_wavelength, value)
		});

		$("#frequency-setvalue1").change(function () {
			var value = parseFloat(parseFloat($(this).val()).toFixed(2));
			combFrequencySliderObj.slider.setValues(value, opticalFrequencyCombData[0].get_max_FSR)
			outOffRange(opticalFrequencyCombData[0].get_min_FSR, opticalFrequencyCombData[0].get_max_FSR, value)
		});
		$("#frequency-setvalue2").change(function () {
			var value = parseFloat(parseFloat($(this).val()).toFixed(2));
			combFrequencySliderObj1.slider.setValues(value, opticalFrequencyCombData[1].get_max_FSR)
			outOffRange(opticalFrequencyCombData[1].get_min_FSR, opticalFrequencyCombData[1].get_max_FSR, value)
		});

		$("#rfSynth-fq-setvalue").change(function () {
			var value = parseFloat(parseFloat($(this).val()).toFixed(2));
			rfSynthFqSliderObj.slider.setValues(value, rfSynthData.max_Freqency);
			outOffRange(rfSynthData.min_Frequency, rfSynthData.max_Freqency, value)
		});

		$("#rfSynth-power-setvalue").change(function () {
			var value = parseFloat(parseFloat($(this).val()).toFixed(2));
			rfSynthPwSliderObj.slider.setValues(value, rfSynthData.max_Power);
			outOffRange(rfSynthData.min_Power, rfSynthData.max_Power, value)
		});

		$("#dr_demultiplexer_0").change(function () {

			var prevTone = combToneData.filter(function (item) {
				return item.id == combtone1;
			});

			if (prevTone.length > 0)
				$("#dr_demultiplexer_1,#dr_demultiplexer_2,#dr_demultiplexer_3").append(new Option(prevTone[0].tone + " , " + prevTone[0].comb_central_wav, prevTone[0].id));

			if (parseInt($(this).val()) > 0) {
				$("#dr_demultiplexer_1 option[value='" + $(this).val() + "'").remove();
				$("#dr_demultiplexer_2 option[value='" + $(this).val() + "'").remove();
				$("#dr_demultiplexer_3 option[value='" + $(this).val() + "'").remove();
				combtone1 = $(this).val();
			}

		});

		$("#dr_demultiplexer_1").change(function () {

			var prevTone = combToneData.filter(function (item) {
				return item.id == combtone2;
			});

			if (prevTone.length > 0)
				$("#dr_demultiplexer_0,#dr_demultiplexer_2,#dr_demultiplexer_3").append(new Option(prevTone[0].tone + " , " + prevTone[0].comb_central_wav, prevTone[0].id));

			if (parseInt($(this).val()) > 0) {
				$("#dr_demultiplexer_0 option[value='" + $(this).val() + "'").remove();
				$("#dr_demultiplexer_2 option[value='" + $(this).val() + "'").remove();
				$("#dr_demultiplexer_3 option[value='" + $(this).val() + "'").remove();
				combtone2 = $(this).val();
			}

		});

		$("#dr_demultiplexer_2").change(function () {
			var prevTone = combToneData.filter(function (item) {
				return item.id == combtone3;
			});

			if (prevTone.length > 0)
				$("#dr_demultiplexer_1,#dr_demultiplexer_0,#dr_demultiplexer_3").append(new Option(prevTone[0].tone + " , " + prevTone[0].comb_central_wav, prevTone[0].id));

			if (parseInt($(this).val()) > 0) {
				$("#dr_demultiplexer_0 option[value='" + $(this).val() + "'").remove();
				$("#dr_demultiplexer_1 option[value='" + $(this).val() + "'").remove();
				$("#dr_demultiplexer_3 option[value='" + $(this).val() + "'").remove();
				combtone3 = $(this).val();
			}

		});

		$("#dr_demultiplexer_3").change(function () {
			var prevTone = combToneData.filter(function (item) {
				return item.id == combtone4;
			});

			if (prevTone.length > 0)
				$("#dr_demultiplexer_1,#dr_demultiplexer_2,#dr_demultiplexer_0").append(new Option(prevTone[0].tone + " , " + prevTone[0].comb_central_wav, prevTone[0].id));

			if (parseInt($(this).val()) > 0) {
				$("#dr_demultiplexer_1 option[value='" + $(this).val() + "'").remove();	
				$("#dr_demultiplexer_2 option[value='" + $(this).val() + "'").remove();
				$("#dr_demultiplexer_0 option[value='" + $(this).val() + "'").remove();
				combtone4 = $(this).val();
			}

		});

		$(".save-btn").click(function () {
			$('.loaderDiv').css('display', 'block');
			switch ($(this).val()) {
				case "temperature1":
					saveData("../cgi/cgi_TECManager.py", "update_TEC", $("#temp-id1").val(), "Temperature Control", $("#general-setvalue1").val(), $("#temp-turn-on-off1").prop("checked") == true ? 1 : 0, true);
					// isSetUnprotectedMode = false;
					$("#temp-reading1").html($("#general-setvalue1").val())
					break;
				case "temperature2":
					saveData("../cgi/cgi_TECManager.py", "update_TEC", $("#temp-id2").val(), "Temperature Control", $("#general-setvalue2").val(), $("#temp-turn-on-off2").prop("checked") == true ? 1 : 0, true);
					// isSetUnprotectedMode = false;
					$("#temp-reading2").html($("#general-setvalue2").val())
					break;
				case "opticalComb1":
					saveOpticalCombData(true); // Function write in setup.js
					// isSetUnprotectedMode = false;
					// $("#wavelength-switch-off").css("pointerEvents", "auto");
					break;
				case "opticalComb2":
					saveOpticalCombData2(true); // Function write in setup.js
					// isSetUnprotectedMode = false;
					// $("#wavelength-switch-off").css("pointerEvents", "auto");
					break;
				case "opticalIdrive":
					idriveId = idriveId.filter((value, index) => idriveId.indexOf(value) === index);
					rfSynthId = rfSynthId.filter((value, index) => rfSynthId.indexOf(value) === index);

					tempDriveData = iDriveData.filter(function (item) {
						return idriveId.includes(item.id);
					});

					if (rfSynthId.length == 0 && tempDriveData.length == 0) {
						// $("#wavelength-switch-off").css("pointerEvents", "auto");
						// isSetUnprotectedMode = false;
						showModal('Success', 'No changes are made');
						return;
					}

					if (rfSynthId.length > 0) {
						//RFSynthesizer
						saveRFSynthData("../cgi/cgi_RFAmp.py", "update_RFAmp", rfSynthData.id, $("#rfSynth-fq-setvalue").val(), $("#rfSynth-power-setvalue").val(), $("#rfSynth-turn-on-off").prop("checked") == true ? 1 : 0, (rfSynthId.length > 0 && tempDriveData.length == 0));
					}

					idriveId = [];
					rfSynthId = [];

					if (tempDriveData.length == 0)
						return;

					tempDriveData.forEach(function (data, index) {
						var setValue = $("#iDrive_Setvalue_" + (data.id - 1)).val();
						var turnOffState = $("#iDrive_Switch_" + (data.id - 1)).prop("checked") == true ? 1 : 0;

						saveData("../cgi/cgi_IDriveManager.py", "update_i_drive", data.id, data.name, setValue, turnOffState, false);
						//isSetUnprotectedMode = false;
						// $("#wavelength-switch-off").css("pointerEvents", "auto");
						// showMsgBox = true;
					});
					showModal('Success', 'updated successfully');
					// isIDriveValChange = false
					break;
				case "demux":
					$('.loaderDiv').css('display', 'block');
					demuxMapData.forEach(function (data, index) {
						var setvalue = $("#Demux_Setvalue_" + (data.id - 1)).val();
						var turnOffState = $("#Demux_Switch_" + (data.id - 1)).prop("checked") == true ? 1 : 0;
						var demux_id = $("#dr_demultiplexer_" + (data.id - 1)).val();
						var set_tone = $("#dr_demultiplexer_" + (data.id - 1) + " option:selected").html().split(",")[0].slice(-2).trim();
						saveDemultiplexData("../cgi/cgi_DemuxMap.py", "update_DemuxMap", data.id, data.name, setvalue, turnOffState, demux_id, set_tone, false);
					});

					showModal('Success', 'updated successfully');
					// if (commonOpticalCombId == "#demo-wavelength-turn-on-off") {
					// 	isDemoSetUnprotectedMode = false;
					// 	$("#demo-wavelength-switch-off").css("pointerEvents", "auto");
					// 	showMsgBox = true;
					// } else {
					// 	isSetUnprotectedMode = false;
					// 	$("#wavelength-switch-off").css("pointerEvents", "auto");
					// 	showMsgBox = true;
					// }
					// isIDriveValChange = false
					break;
				case "demuxIdrive":
					idriveId = idriveId.filter((value, index) => idriveId.indexOf(value) === index);
					temp1DriveData = iDriveData.filter(function (item) {
						return idriveId.includes(item.id);
					});

					if (temp1DriveData.length == 0) {
						showModal('Success', 'No changes are made');
						return;
					}

					temp1DriveData.forEach(function (data, index) {
						var setValue = $("#iDrive_Setvalue_" + (data.id - 1)).val();
						var turnOffState = $("#iDrive_Switch_" + (data.id - 1)).prop("checked") == true ? 1 : 0;

						saveData("../cgi/cgi_IDriveManager.py", "update_i_drive", data.id, data.name, setValue, turnOffState, false);
						// isSetUnprotectedMode = true;
						// $("#wavelength-switch-off").css("pointerEvents", "auto");
						// showMsgBox = true;
					});
					showModal('Success', 'Updated Successfully');
					idriveId = [];
					// isIDriveValChange = true
					break;
			}
			// loadModuleControlData();
		});

		//cancel
		$("#cancel-btn").click(function () {
			let i = 0
			if ($("#general-slider1").next().length > 0) {
				if ($("#general-setvalue1").val() != techData[0].setTemp) {
					i++;
				}
				let tempTrack = $("#temp-turn-on-off1").prop("checked") == true ? 1 : 0;
				if (tempTrack != techData[0].onOffState) {
					i++;
				}
			}
			if ($("#general-slider2").next().length > 0) {
				if ($("#general-setvalue2").val() != techData[1].setTemp) {
					i++;
				}
				let tempTrack = $("#temp-turn-on-off2").prop("checked") == true ? 1 : 0;
				if (tempTrack != techData[1].onOffState) {
					i++;
				}
			}
			if ($("#central-wavelength-slider1").next().length > 0) {

				if ($("#wavelength-setvalue1").val() != opticalFrequencyCombData[0].setWaveLength) {
					i++;
				}
				if ($("#frequency-setvalue1").val() != opticalFrequencyCombData[0].setPower) {
					i++;
				}
			}
			if ($("#central-wavelength-slider2").next().length > 0) {

				if ($("#wavelength-setvalue2").val() != opticalFrequencyCombData[1].setWaveLength) {
					i++;
				}
				if ($("#frequency-setvalue2").val() != opticalFrequencyCombData[1].setPower) {
					i++;
				}
			}

			if ($("#general-slider1").next().length > 0) {
				//temperature
				readJsonData(moduleControlParameters[0].moduleType, techData);
				tempSliderObj.slider.setValues(techData[0].setTemp, techData[0].setMaxTemp);
			}
			if ($("#general-slider2").next().length > 0) {
				//temperature
				readJsonData(moduleControlParameters[0].moduleType, techData);
				tempSliderObj1.slider.setValues(techData[1].setTemp, techData[1].setMaxTemp);
			}

			if ($("#central-wavelength-slider1").next().length > 0) {
				BindCombData(1);
				centralWavelengthSliderObj.slider.setValues(opticalFrequencyCombData[0].setWaveLength, opticalFrequencyCombData[0].maxWaveLength)
				combFrequencySliderObj.slider.setValues(opticalFrequencyCombData[0].setPower, opticalFrequencyCombData[0].maxPower)
			}
			if ($("#central-wavelength-slider2").next().length > 0) {
				BindCombData(1);
				centralWavelengthSliderObj1.slider.setValues(opticalFrequencyCombData[1].setWaveLength, opticalFrequencyCombData[1].maxWaveLength)
				combFrequencySliderObj1.slider.setValues(opticalFrequencyCombData[1].setPower, opticalFrequencyCombData[1].maxPower)
			}

			//rf synthesizer
			// if ($("#rfSynth-fq-slider").next().length > 0) {
			// 	readJsonData(moduleControlParameters[2].moduleType, rfSynthData);
			// 	rfSynthFqSliderObj.slider.setValues(rfSynthData.set_Frequency, rfSynthData.max_Freqency);
			// 	rfSynthPwSliderObj.slider.setValues(rfSynthData.set_Power, rfSynthData.max_Power);
			// }

			// if ($("#Demux_Slider_0").next().length > 0) {
			// 	Demux_Slider_Obj_0.slider.setValues(demuxMapData[0].set_demux_power, demuxMapData[0].get_max_Demux_power);
			// 	Demux_Slider_Obj_1.slider.setValues(demuxMapData[1].set_demux_power, demuxMapData[1].get_max_Demux_power);
			// 	Demux_Slider_Obj_2.slider.setValues(demuxMapData[2].set_demux_power, demuxMapData[2].get_max_Demux_power);
			// 	Demux_Slider_Obj_3.slider.setValues(demuxMapData[3].set_demux_power, demuxMapData[3].get_max_Demux_power);
			// 	BindDemuxMapData(1);
			// }
			// BindIdriveData();	
			// console.log(i)
			if (i > 0) {
				showMsg = true
				showModal("Alert!", "Changes Reversed")
			}
			else {
				showMsg = true
				showModal("Alert!", "No Changes Detected")
			}
		});

		$("#restore-module-btn").click(() => {
			let parameter = { url: "../cgi/cgi_RestoreDefaultSettings.py", data: { requestType: "restore_module" } };
			$.ajax({
				url: parameter.url,
				type: "get",
				data: parameter.data,
				contentType: 'application/json',
				dataType: 'json',
				headers: {
					'Access-Control-Allow-Origin': '*'
				},
				success: function (response) {
					showModal('Success', response.response);
					loadModuleControlData()
				}
			})
		})
		$("#sweep-check").click((e) => {
			if (e.target.value == 'Disable') {
				$("#sweep-check").removeClass("btn-danger").addClass("btn-normal").val("Enable");
				$("#repetation-setvalue").attr("disabled", true);
				$("#repetation-rate").css("display", "none");
				$("#repetation-turn-on-off").attr("disabled", true)
			}
			else {
				$("#sweep-check").removeClass("btn-normal").addClass("btn-danger").val("Disable");
				$("#repetation-setvalue").attr("disabled", false)
				$("#repetation-rate").css("display", "block")
				$("#repetation-turn-on-off").attr("disabled", false)
			}
		})
		$("#start-sweep").click(() => {
			$("#start-sweep").attr("disabled", 'disabled').html("In Progress...");
			let start_wavelegth = parseFloat($("#start_wavelegth").val());
			let stop_wavelegth = parseFloat($("#stop_wavelegth").val());
			let increment_wavelegth = parseFloat($("#increment_wavelegth").val());
			let repetation_rate = parseFloat($("#repetation_rate").val());
			let chirp_bandwith = $("#chirp_bandwith").val();
			let chirp_frequency = $("#chirp_frequency").val();
			// let current_value = 0;
			if (stop_wavelegth && increment_wavelegth && repetation_rate) {

				interval = setTimeout(() => {

					$.ajax({
						type: "get",
						url: "../cgi/cgi_Sweep.py",
						contentType: 'application/json',
						headers: {
							'Access-Control-Allow-Origin': '*'
						},
						contentType: 'application/json',
						dataType: 'json',
						data: {
							requestType: "save_sweep",
							start_wavelegth: start_wavelegth,
							stop_wavelegth: stop_wavelegth,
							increment_wavelegth: increment_wavelegth,
							repetation_rate: repetation_rate,
							chirp_bandwith: chirp_bandwith,
							chirp_frequency: chirp_frequency
						},
						async: false,
						success: function (response) {
							if (response.status == 'success') {

								swal({ title: "Sweep Initiated", text: "", type: "success" }, function () {
									$("#start-sweep").attr("disabled", false).html("Start");

								});
							}
							else {
								swal({ title: "Sweep Initiated Fail", text: "", type: "error" }, function () {
									$("#start-sweep").attr("disabled", false).html("Start");

								});
							}


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

			}
			else {
				ShowNotif("Above value should not be empty or 0", 'fail')
				$("#start-sweep").attr("disabled", false).html("Start");
			}


		})
		$("#stop-sweep").click(() => {
			$(".icon-container").css("display", "none")
			let instantaneous_value = $("#instantaneous_value").val(0);
			$("#start-sweep").attr("disabled", false).html("Start");
			$("#stop-sweep").attr("disabled", 'disabled');

			$.ajax({
				type: "get",
				url: "../cgi/cgi_Sweep.py",
				contentType: 'application/json',
				headers: {
					'Access-Control-Allow-Origin': '*'
				},
				contentType: 'application/json',
				dataType: 'json',
				data: {
					requestType: "stop_sweep",
				},
				async: false,
				success: function (response) {
					$("#stop-sweep").attr("disabled", false);

				}
			})
			swal({ title: "Sweep Stopped", text: "", type: "warning" }, function () {

			})
			return;
		})

		$("#start-sweep1").click(() => {
			$("#start-sweep1").attr("disabled", 'disabled').html("In Progress...");
			let start_wavelegth = parseFloat($("#start_wavelegth1").val());
			let stop_wavelegth = parseFloat($("#stop_wavelegth1").val());
			let increment_wavelegth = parseFloat($("#increment_wavelegth1").val());
			let repetation_rate = parseFloat($("#repetation_rate1").val());
			let chirp_bandwith = $("#chirp_bandwith1").val();
			let chirp_frequency = $("#chirp_frequency1").val();
			// let current_value = 0;
			if (stop_wavelegth && increment_wavelegth && repetation_rate) {

				interval = setTimeout(() => {

					$.ajax({
						type: "get",
						url: "../cgi/cgi_Sweep.py",
						contentType: 'application/json',
						headers: {
							'Access-Control-Allow-Origin': '*'
						},
						contentType: 'application/json',
						dataType: 'json',
						data: {
							requestType: "save_sweep1",
							start_wavelegth: start_wavelegth,
							stop_wavelegth: stop_wavelegth,
							increment_wavelegth: increment_wavelegth,
							repetation_rate: repetation_rate,
							chirp_bandwith: chirp_bandwith,
							chirp_frequency: chirp_frequency
						},
						async: false,
						success: function (response) {
							if (response.status == 'success') {

								swal({ title: "Sweep Initiated", text: "", type: "success" }, function () {
									$("#start-sweep1").attr("disabled", false).html("Start");

								});
							}
							else {
								swal({ title: "Sweep Initiated Fail", text: "", type: "error" }, function () {
									$("#start-sweep1").attr("disabled", false).html("Start");

								});
							}


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

			}
			else {
				ShowNotif("Above value should not be empty or 0", 'fail')
				$("#start-sweep1").attr("disabled", false).html("Start");
			}


		})

		$("#stop-sweep1").click(() => {
			$(".icon-container").css("display", "none")
			let instantaneous_value = $("#instantaneous_value").val(0);
			$("#start-sweep1").attr("disabled", false).html("Start");
			$("#stop-sweep1").attr("disabled", 'disabled');

			$.ajax({
				type: "get",
				url: "../cgi/cgi_Sweep.py",
				contentType: 'application/json',
				headers: {
					'Access-Control-Allow-Origin': '*'
				},
				contentType: 'application/json',
				dataType: 'json',
				data: {
					requestType: "stop_sweep1",
				},
				async: false,
				success: function (response) {
					$("#stop-sweep1").attr("disabled", false);

				}
			})
			swal({ title: "Sweep Stopped", text: "", type: "warning" }, function () {

			})
			return;
		})

		$(".accordion-head").click(function (e) {
			e.preventDefault();
			var $this = $(this);
			if ($this.hasClass('icon') == true) {
				$(".customClass").animate({
					scrollTop: ($this.offset().top) - $(".customClass").offset().top + $(".customClass").scrollTop()
				}, 1000);
			}
		})
	})
})
