// for idac vDac slider
// let vDac_Slider_Obj_1 = {}
// let vDac_Slider_Obj_2 = {}
// let vDac_Slider_Obj_3 = {}
// let vDac_Slider_Obj_4 = {}
// let vDac_Slider_Obj_5 = {}
// let vDac_Slider_Obj_6 = {}
// let vDac_Slider_Obj_7 = {}
// let vDac_Slider_Obj_8 = {}
// let vDac_Slider_Obj_9 = {}
// let vDac_Slider_Obj_10 = {}
// let vDac_Slider_Obj_11 = {}
// let vDac_Slider_Obj_12 = {}
// let vDac_Slider_Obj_13 = {}
// let vDac_Slider_Obj_14 = {}
// let vDac_Slider_Obj_15 = {}
// let vDac_Slider_Obj_16 = {}

// let iDac_Slider_Obj_1 = {}
// let iDac_Slider_Obj_2 = {}
// let iDac_Slider_Obj_3 = {}
// let iDac_Slider_Obj_4 = {}
// let iDac_Slider_Obj_5 = {}
// let iDac_Slider_Obj_6 = {}
// let iDac_Slider_Obj_7 = {}
// let iDac_Slider_Obj_8 = {}
// let iDac_Slider_Obj_9 = {}
// let iDac_Slider_Obj_10 = {}
// let iDac_Slider_Obj_11 = {}
// let iDac_Slider_Obj_12 = {}
// let iDac_Slider_Obj_13 = {}
// let iDac_Slider_Obj_14 = {}
// let iDac_Slider_Obj_15 = {}
// let iDac_Slider_Obj_16 = {}
// let iDac_Slider_Obj_17 = {}
// let iDac_Slider_Obj_18 = {}
// let iDac_Slider_Obj_19 = {}
// let iDac_Slider_Obj_20 = {}

// let is_idac_loaded_1 = false
// let is_idac_loaded_2 = false
// let is_idac_loaded_3 = false
// let is_idac_loaded_4 = false
// let is_idac_loaded_5 = false
// let is_idac_loaded_6 = false
// let is_idac_loaded_7 = false
// let is_idac_loaded_8 = false
// let is_idac_loaded_9 = false
// let is_idac_loaded_10 = false
// let is_idac_loaded_11 = false
// let is_idac_loaded_12 = false
// let is_idac_loaded_13 = false
// let is_idac_loaded_14 = false
// let is_idac_loaded_15 = false
// let is_idac_loaded_16 = false
// let is_idac_loaded_17 = false
// let is_idac_loaded_18 = false
// let is_idac_loaded_19 = false
// let is_idac_loaded_20 = false


// let is_vdac_loaded_1 = false
// let is_vdac_loaded_2 = false
// let is_vdac_loaded_3 = false
// let is_vdac_loaded_4 = false
// let is_vdac_loaded_5 = false
// let is_vdac_loaded_6 = false
// let is_vdac_loaded_7 = false
// let is_vdac_loaded_8 = false
// let is_vdac_loaded_9 = false
// let is_vdac_loaded_10 = false
// let is_vdac_loaded_11 = false
// let is_vdac_loaded_12 = false
// let is_vdac_loaded_13 = false
// let is_vdac_loaded_14 = false
// let is_vdac_loaded_15 = false
// let is_vdac_loaded_16 = false



let idac_slider_no = 1
let vdac_slider_no = 0
let vDac_Slider_Objs_list = []
var iDAC_VDAC_data;
var idacSwitchSafe = true
var idacSweepList = [];
var vdacSweepList = [];
var start_current_error = false;
var stop_current_error = false;
var increment_step_error = false;
var interval_sec_error = false;
var selectedRfRegId = "";
var validation;
function updateSliderRange(element, sliderName, sliderId) {
    let dropDownId = $(element).parent().attr('aria-labelledby');
    $(`#${dropDownId}`).text(element.innerText);
    $(`#${dropDownId}`).attr("data-max", element.getAttribute("data-max"));
    $(`#${dropDownId}`).attr("data-min", element.getAttribute("data-min"));
    if (sliderName == "idac") {
        let new_id = sliderId;
        // eval(`iDac_Slider_Obj_${new_id}`).destroy();
        $(`#Debug_Slider_iDac_${new_id}`).next().remove("div");
        loadSlider(eval(`iDac_Slider_Obj_${new_id}`), `#Debug_Slider_iDac_${new_id}`, `#Debug_Setvalue_iDac_${new_id}`, parseFloat(element.getAttribute('data-min')), parseFloat(element.getAttribute('data-max')), 0, generalSliderWidthLVL2, true, 0.001, false, false, new_id, false, isDebug = true);
        $(`#Debug_Setvalue_iDac_${new_id}`).off('change');
        $(`#Debug_Setvalue_iDac_${new_id}`).change(function () {
            updateSliderAccordingToSetValue(eval(`iDac_Slider_Obj_${new_id}`), this, element.getAttribute('data-max'), element.getAttribute('data-min'));
        });
    } 
    else if (sliderName == "vdac") {
        let new_id = sliderId
        $(`#Debug_Slider_vDac_${new_id}`).next().remove("div");
        loadSlider(eval(`vDac_Slider_Obj_${new_id}`), `#Debug_Slider_vDac_${new_id}`, `#Debug_Setvalue_vDac_${new_id}`, parseFloat(element.getAttribute('data-min')), parseFloat(element.getAttribute('data-max')), 0, generalSliderWidthLVL2, true, 0.001, false, false, iDAC_VDAC_data["v_dac_data"][new_id]['id'], false, isDebug = true)
        $(`#Debug_Setvalue_vDac_${new_id}`).off('change');
        $(`#Debug_Setvalue_vDac_${new_id}`).change(function () {
            updateSliderAccordingToSetValue(eval(`vDac_Slider_Obj_${new_id}`), this, element.getAttribute('data-max'), element.getAttribute('data-min'));
        });
    }
    else if (sliderName == "tec") {
        let new_id = sliderId
        $(`#Debug_Slider_tecDac_${new_id}`).next().remove("div");
        loadSlider(eval(`vDac_Slider_Obj_${new_id}`), `#Debug_Slider_tecDac_${new_id}`, `#Debug_Setvalue_tecDac_${new_id}`, parseFloat(element.getAttribute('data-min')), parseFloat(element.getAttribute('data-max')), 0, generalSliderWidthLVL1, true, 0.001, false, false, iDAC_VDAC_data["tec_dac_data"][new_id]['id'], false, isDebug = true)
        $(`#Debug_Setvalue_tecDac_${new_id}`).off('change');
        $(`#Debug_Setvalue_tecDac_${new_id}`).change(function () {
            updateSliderAccordingToSetValue(eval(`tecDac_Slider_Obj_${new_id}`), this, element.getAttribute('data-max'), element.getAttribute('data-min'));
        });
    }
}
function updateSliderRangeForSweep(element, sliderName) {
    let dropDownId = $(element).parent().attr('aria-labelledby');
    $(`#${dropDownId}`).text(element.innerText);
    $(`#${dropDownId}`).attr("data-max", element.getAttribute("data-max"));
    $(`#${dropDownId}`).attr("data-min", element.getAttribute("data-min"));
}

function updateSliderAccordingToSetValue(object, this1, max_value, min_value) {
    // let value = parseFloat($(id).val()).toFixed(2);
    // console.log("setvalue", value, max);
    // object.slider.setValues(value, max);
    var max_value = parseFloat(parseFloat(max_value).toFixed(3))
    var min_value = parseFloat(parseFloat(min_value).toFixed(3))
    var value = parseFloat(parseFloat($(this1).val()).toFixed(3));
    if (value > max_value || value < min_value) {
        swal("Warning", "out of range", "warning");
    }
    object.slider.setValues(value, max_value);
}

function showRangeDropDown(e, id) {
    // e.stopPropagation();
    // $("#" + id).trigger('click');
}

$(document).ready(function () {
    // var answer = confirm ("reload ?")
    // if (answer) location.reload();
    // to get idac and vdac data from db
    $("#refAdd").hide();
    $("#refSearch").hide();
    // getRfRegData();
    $.ajax({
        type: "get",
        url: "../cgi/cgi_IdacVdac.py",
        contentType: 'application/json',
        headers: {
            'Access-Control-Allow-Origin': '*'
        },
        contentType: 'application/json',
        dataType: 'json',
        data: {
            requestType: "read_iDac_vDac"
        },
        async: false,
        success: function (response) {
            iDAC_VDAC_data = response;
            response?.i_dac_data.forEach((element,i) => {
                // console.log(i);
                // eval(`var iDac_Slider_Obj_${i}`)
                window['iDac_Slider_Obj_'+i] = {};
                window['is_idac_loaded_'+i] = false;
                addIdac(element,i)
            });
            response?.v_dac_data.forEach((element,i) => {
                window['vDac_Slider_Obj_'+i] = {};
                window['is_vdac_loaded_'+i] = false;
                addVdac(element,i)
            });
            
            response?.tec_dac_data.forEach((element,i) => {
                window['tecDac_Slider_Obj_'+i] = {};
                window['is_tecdac_loaded_'+i] = false;
                addTecdac(element,i)
            });
            // readJsonData(parameter.connectionType, response);
        },
        error: function (ex) {
            console.log(ex);
        }
    })
    const loadIdacVdac = () =>{ 
        $.ajax({
            type: "get",
            url: "../cgi/cgi_IdacVdac.py",
            contentType: 'application/json',
            headers: {
                'Access-Control-Allow-Origin': '*'
            },
            contentType: 'application/json',
            dataType: 'json',
            data: {
                requestType: "read_iDac_vDac"
            },
            async: false,
            success: function (response) {
                iDAC_VDAC_data = response;
                // response?.i_dac_data.forEach((element,i) => {
                //     // console.log(i);
                //     // eval(`var iDac_Slider_Obj_${i}`)
                //     window['iDac_Slider_Obj_'+i] = {};
                //     window['is_idac_loaded_'+i] = false;
                //     addIdac(element,i)
                // });

                // readJsonData(parameter.connectionType, response);
            },
            error: function (ex) {
                console.log(ex);
            }
        })
        $('.loaderDiv').css('display', 'none');
    }
    function loadIdacSystemName(){
        $.ajax({
            type: "get",
            url: "../cgi/cgi_setCurrentTest.py",
            contentType: 'application/json',
            headers: {
                'Access-Control-Allow-Origin': '*'
            },
            contentType: 'application/json',
            dataType: 'json',
            data: {
                requestType: "get_idacs"
            },
            async: false,
            success: function (response) {
                // let array = []
                // let data = '<option>Select</option>'
                idacSweepList.push('<option>Select</option>')
                response.map((item)=> {
                    let data = `<option value="${item.id}">${item.name}</option>`
                    idacSweepList.push(data)
                })
                // idacSweepList = array;
                $("#idac_vdac_list").append(idacSweepList);
            },
            error: function (ex) {
                console.log(ex);
            }
        })
    }
    function loadVdacSystemName(){
        $.ajax({
            type: "get",
            url: "../cgi/cgi_setCurrentTest.py",
            contentType: 'application/json',
            headers: {
                'Access-Control-Allow-Origin': '*'
            },
            contentType: 'application/json',
            dataType: 'json',
            data: {
                requestType: "get_vdacs"
            },
            async: false,
            success: function (response) {
                // $("#idac_vdac_list").html("")
                // let array = []
                vdacSweepList.push('<option>Select</option>')
                response.map((item)=> {
                    let data = `<option value="${item.id}">${item.name}</option>`
                    vdacSweepList.push(data)
                })
                // vdacSweepList = array;
                // $("#idac_vdac_list").append(vdacSweepList);
            },
            error: function (ex) {
                console.log(ex);
            }
        })
    }
    // validation  = new JustValidate('#regForm',{
    //     errorFieldCssClass: 'is-invalid',
    // });
    // validation
    // .addField('#reg_name', [
    //     {
    //         rule: 'required',
    //     },
    //     {
    //         rule: 'minLength',
    //         value: 1,
    //     },
    //     {
    //         rule: 'maxLength',
    //         value: 16,
    //     },
    // ])
    // .addField('#address', [
    //     {
    //         rule: 'required',
    //     },
    //     {
    //         rule: 'minLength',
    //         value: 1,
    //     },
    //     {
    //         rule: 'maxLength',
    //         value: 12,
    //     },
    // ])
    // .addField('#value', [
    //     {
    //         rule: 'required',
    //     },
    //     {
    //         rule: 'minLength',
    //         value: 1,
    //     },
    //     {
    //         rule: 'maxLength',
    //         value: 12,
    //     },
    // ])
    // .onSuccess((event)=>{
    //     saveRfReg()
    // })
    
    loadIdacVdac();
    // loadIdacSystemName()
    // loadVdacSystemName()
    $("#graph-water-mark").addClass("d-none");
	$("#iDacDivContainer").removeClass("d-none");
    function updateOnOffSwitch(id, value) {
        if (value == 1) {
            $(id).prop("checked", true)
        } else {
            $(id).prop("checked", false)
        }
    }

    function updateUserName(text_id, input_id, value) {
        if (value == null) {
            $(input_id).val("");
            $(text_id).text("");
        } else {
            $(input_id).val(value);
            $(text_id).text(value);
        }
    }




    function addIdacSlider() {
        // to add slider on click of add idac
        // $("#add_idac").click(addIdac);

        // for (let count = 0; count < 10; count++) {
        //     addIdac(true);
        // }
    }

    function addIdac(data,i) {
        let slider = `<li id="iDacDiv${i}"><a id="iDacA${i}" class="third-level-child i_dac_v_dac"
        href="javascript:void(0);" style="padding:0px !important">iDac ${i+1}</a>
        <div class="third-level-content variable-optical mb-0">
<div class="row colfixone mb-0">
<div class="col-lg-12 dactitle">
</div>
    <div class="col-xl-5 col-lg-5 d-flex">
        <div><img src="../images/Power-Supply.png" /></div>
        <div><img src="../images/greenLed.png"></div>
        <div class="d-flex">
            <div>
                <span class="light-color  text-bold">iDAC
                </span>
            </div>
            <div class="pl-0 ml-2">
                <input type="text" value="" class="setvalueidac form-control" id="iDacUserInput${i}" placeholder="UserName" style="width: 125px;">
                <span id="userInputError${i}" style="color:red"></span>
            </div>
        </div>
		<div class="ml-3 d-flex">
            <div>
                <div id = "slider-range-container" class="col-xl-1 d-flex">
                    <div class="dropdown">
                        <button class="setvalueidac light-color btn text-bold dropdown-toggle debugRangebtn" id="idac-range-drop-${i}" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" data-min=0 data-max=${data.set_current_limit} style="color:#0056b3; text-align:left; font-weight:inherit; padding:0; background:none;">
                        Range
                        </button>
                    
                        <div class="dropdown-menu" aria-labelledby="idac-range-${i}">
                            <button class="dropdown-item" id = "idac-range-drop-e-${i}" data-min = 0 data-max = 3.125 onclick="updateSliderRange(this, 'idac', ${i})">0 to 3.125mA</button>
                            <button class="dropdown-item" id = "idac-range-drop-e-${i}" data-min = 0 data-max = 6.25 onclick="updateSliderRange(this, 'idac', ${i})">0 to 6.25mA</button>
                            <button class="dropdown-item" id = "idac-range-drop-e-${i}" data-min = 0 data-max = 12.5 onclick="updateSliderRange(this, 'idac', ${i})">0 to 12.5mA</button>
                            <button class="dropdown-item" id = "idac-range-drop-e-${i}" data-min = 0 data-max = 25 onclick="updateSliderRange(this, 'idac', ${i})">0 to 25mA</button>
                            <button class="dropdown-item" id = "idac-range-drop-e-${i}" data-min = 0 data-max = 50 onclick="updateSliderRange(this, 'idac', ${i})">0 to 50mA</button>
                            <button class="dropdown-item" id = "idac-range-drop-e-${i}" data-min = 0 data-max = 100 onclick="updateSliderRange(this, 'idac', ${i})">0 to 100mA</button>
                            <button class="dropdown-item" id = "idac-range-drop-e-${i}" data-min = 0 data-max = 200 onclick="updateSliderRange(this, 'idac', ${i})">0 to 200mA</button>
                            <button class="dropdown-item" id = "idac-range-drop-e-${i}" data-min = 0 data-max = 300 onclick="updateSliderRange(this, 'idac', ${i})">0 to 300mA</button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="pl-0">
                <button class="btn secondry-btn form-control common-input-field" type="button" id="idac-range-${i}" aria-haspopup="true" aria-expanded="false" data-min=0 data-max=${data.set_current_limit} style="border:1px solid #0056b3; text-align:left; text-overflow:ellipsis; overflow:hidden; white-space:nowrap; margin:0 !important; cursor:default; font-size:14px;" onclick=showRangeDropDown(event,"idac-range-drop-${i}")>
          0 to ${data.set_current_limit}mA
          </button>
            </div>
        </div>
    </div>
    
    <div class="col-xl-4 col-lg-4 mtBEq d-flex justify-content-start">
        <div class="slider-container">
            <input type="text" id="Debug_Slider_iDac_${i}"
                class="slider" style="display:none" />
        </div>
    </div>
    <div class="col-xl-2 col-lg-2 col-sm-10 setIdacVdacValue ml-2 d-flex justify-content-start">
    <div class="set-value-debug mt-1">Set Value</div>
            <div class="form-group ml-1 mb-1">
                <input type="number"
                    id="Debug_Setvalue_iDac_${i}" value=""
                    class="setvalueidac form-control common-input-field">
                <span id="idacValueError${i}" style="color:red"></span>
            </div>
    </div>
    <div class="col-xl-1 col-lg-1 col-sm-2 ml-1">
        <label
            class="idacBtn tooltipBtn toggleSwitch large switchFix">
            <input type="checkbox" id="iDac_Switch_${i}" name="iDac_Switch_${i}">
            <span>
                <span>OFF</span>
                <span>ON</span>
            </span>
            <a></a>
            <p class="tooltiptext"></p>
        </label>
    </div>
</div>
</div>
</li>`





        $("#iDac_slider_container").append(slider);
        // vDac_Slider_Objs_list.push({})
        // console.log(vDac_Slider_Objs_list, "vDac_Slider_Objs_list", i)
        //  to add event listener to dropdown functionality of slider
        if (true) {
            $("#iDac_slider_container li:last-child a:first-child").on('click', function (e) {
                e.preventDefault();
                var $this = $(this);

                if ($this.hasClass('icon')) {
                    $this.removeClass('icon')
                } else {
                    $this.addClass('icon');
                }

                if ($this.next().hasClass('show-level')) {
                    $this.next().removeClass('show-level')
                } else {
                    $this.next().addClass('show-level');
                }
                $(".customClass").animate({
                    scrollTop: ($this.offset().top)-$(".customClass").offset().top + $(".customClass").scrollTop()
                  }, 1000);
            });
        }
        addIdacSliderElement(data,i);
    }

    function addIdacSliderElement(data,sliderElementId) {
        // console.log(data);
        let new_id = sliderElementId;
        // $(`#iDacDiv${new_id}`).click(function () {
        $(`#iDacA${new_id}`).click(function () {
            if ($(`#Debug_Slider_iDac_${new_id}`).next().length == 0) {
                setTimeout(function () {
                    loadSlider(eval(`iDac_Slider_Obj_${new_id}`), `#Debug_Slider_iDac_${new_id}`, `#Debug_Setvalue_iDac_${new_id}`, data.set_min_current, data.set_current_limit, data.set_current, generalSliderWidthLVL2, true, 0.001, false, false, data.id, false, isDebug = true);
                    updateOnOffSwitch(`#iDac_Switch_${new_id}`, data.set_on_off_state);
                    updateUserName(`#iDacUser${new_id}`, `#iDacUserInput${new_id}`,data.name);
                    $(`#Debug_Setvalue_iDac_${new_id}`).change(function () {
                        updateSliderAccordingToSetValue(eval(`iDac_Slider_Obj_${new_id}`), this, data.set_current_limit,data.set_min_current);
                    });
                    eval(`is_idac_loaded_${new_id}=true;`);
                }, 1);
            }

        });
    }

    function addVdacSlider() {
        // for (let count = 0; count < 40; count++) {
        //     // if (count > 1 && count < 6) {
        //     //     addVdacSliderElement(count);
        //     // }
        //     addVdac(true);

        // }
    }

    function addVdac(data,i) {

        
        let slider = `<li id="vDacDiv${vdac_slider_no}"><a id="vDacA${vdac_slider_no}" class="third-level-child i_dac_v_dac"
        href="javascript:void(0);">vDAC ${vdac_slider_no+1}</a>
        <div class="third-level-content variable-optical mb-0">
        <div class="row colfixone mb-0">
        <div class="col-lg-12 dactitle"></div>
            <div class="col-xl-5 col-lg-5 d-flex">
                <div><img src="../images/Power-Supply.png" /></div>
                <div><img src="../images/greenLed.png"></div>
                <div class="d-flex">
                    <div>
                        <span class="light-color  text-bold">vDAC 
                        </span>
                    </div>
                    <div class="pl-0  ml-2">
                        <input type="text" value="" class="setvalueidac form-control" id="vDacUserInput${vdac_slider_no}" placeholder="UserName" style="width: 125px;">
                        <span id="vdacInputError${vdac_slider_no}" style="color:red"></span>
                    </div>
                </div>
                <div class="ml-3 d-flex">
                    <div>
                        <div id = "vdac-slider-range-container" class="col-xl-1 d-flex">
                            <div class="dropdown">
                                <button class="setvalueidac light-color text-bold btn dropdown-toggle debugRangebtn" type="button" id="vdac-range-drop-${vdac_slider_no}" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" data-min=${data['set_min_current']} data-max=${data['set_current_limit']} style="color:#0056b3; text-align:left; font-weight:inherit; padding:0; background:none;">
                                Range
                                </button>
                    
                                <div class="dropdown-menu" aria-labelledby="vdac-range-${vdac_slider_no}">
                                    <button class="dropdown-item" id = "vdac-range-drop-e-${vdac_slider_no}" data-min = 0 data-max = 5 onclick="updateSliderRange(this, 'vdac', ${vdac_slider_no})">0V to 5V</button>
                                    <button class="dropdown-item" id = "vdac-range-drop-e-${vdac_slider_no}" data-min = 0 data-max = 10 onclick="updateSliderRange(this, 'vdac', ${vdac_slider_no})">0V to 10V</button>
                                    <button class="dropdown-item" id = "vdac-range-drop-e-${vdac_slider_no}" data-min = -2.5 data-max = 2.5 onclick="updateSliderRange(this, 'vdac', ${vdac_slider_no})">-2.5V to 2.5V</button>
                                    <button class="dropdown-item" id = "vdac-range-drop-e-${vdac_slider_no}" data-min = -5 data-max = 5 onclick="updateSliderRange(this, 'vdac', ${vdac_slider_no})">-5V to 5V</button>
                                    <button class="dropdown-item" id = "vdac-range-drop-e-${vdac_slider_no}" data-min = -10 data-max = 10 onclick="updateSliderRange(this, 'vdac', ${vdac_slider_no})">-10V to 10V</button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="pl-0">
                        <button class="btn secondry-btn form-control common-input-field" type="button" id="vdac-range-${vdac_slider_no}" aria-haspopup="true" aria-expanded="false" data-min=${data['set_min_current']} data-max=${data['set_current_limit']} style="border:1px solid #0056b3; text-align:left; text-overflow:ellipsis; overflow:hidden; white-space:nowrap; margin:0 !important; cursor:default; font-size:14px;">
                        ${data['set_min_current']}V to ${data['set_current_limit']}V
                        </button>
                    </div>
                </div>
            </div>
            
            <div class="col-xl-4 col-lg-4 mtBEq d-flex justify-content-start">
                <div class="slider-container">
                    <input type="text" id="Debug_Slider_vDac_${vdac_slider_no}"
                        class="slider" style="display:none" />
                </div>
            </div>
            <div class="col-xl-2 col-lg-2 col-sm-10 ml-2 d-flex justify-content-start">
                <div class="set-value-debug mt-1">Set Value</div>
                <div class="form-group ml-1 mb-1">
                    <input type="number"
                        id="Debug_Setvalue_vDac_${vdac_slider_no}" value=""
                        class="setvalueidac form-control common-input-field">
                        <span id="vdacValueError${vdac_slider_no}" style="color:red"></span>
                </div>
            </div>
            <div class="col-xl-1 col-lg-1 col-sm-2 ml-1">
                <label
                    class="idacBtn tooltipBtn toggleSwitch large switchFix">
                    <input type="checkbox" id="vDac_Switch_${vdac_slider_no}">
                    <span>
                        <span>OFF</span>
                        <span>ON</span>
                    </span>
                    <a></a>
                    <p class="tooltiptext"></p>
                </label>
            </div>
        </div>
        </div>
        </li>`





        $("#vDac_slider_container").append(slider);
        // vDac_Slider_Objs_list.push({})
        // console.log(vDac_Slider_Objs_list, "vDac_Slider_Objs_list", idac_slider_no)
        //  to add event listener for dropdown functionality of slider
        if (true) {
            $("#vDac_slider_container li:last-child a:first-child").on('click', function (e) {
                e.preventDefault();
                var $this = $(this);

                if ($this.hasClass('icon')) {
                    $this.removeClass('icon')
                } else {
                    $this.addClass('icon');
                }

                if ($this.next().hasClass('show-level')) {
                    $this.next().removeClass('show-level')
                } else {
                    $this.next().addClass('show-level');
                }
                if($this.hasClass('icon') == true)
                    $(".customClass").animate({
                        scrollTop: ($this.offset().top)-$(".customClass").offset().top + $(".customClass").scrollTop()
                    }, 1500);
            });
        }
        addVdacSliderElement(data,i);
        vdac_slider_no++;
    }

    function addVdacSliderElement(data,sliderElementId) {
        let new_id = sliderElementId;
        // $(`#vDacDiv${new_id}`).click(function () {
        $(`#vDacA${new_id}`).click(function () {
            if ($(`#Debug_Slider_vDac_${new_id}`).next().length == 0) {
                setTimeout(function () {
                    loadSlider(eval(`vDac_Slider_Obj_${new_id}`), `#Debug_Slider_vDac_${new_id}`, `#Debug_Setvalue_vDac_${new_id}`, data['set_min_current'], data['set_current_limit'], data['set_current'], generalSliderWidthLVL2, true, 0.001, false, false, data['id'], false, isDebug = true)
                    updateOnOffSwitch(`#vDac_Switch_${new_id}`, data["set_on_off_state"]);
                    updateUserName(`#vDacUser${new_id}`, `#vDacUserInput${new_id}`, data["name"]);
                    $(`#Debug_Setvalue_vDac_${new_id}`).change(function () {
                        updateSliderAccordingToSetValue(eval(`vDac_Slider_Obj_${new_id}`), this, data['set_current_limit'], data['set_min_current']);
                    });
                    eval(`is_vdac_loaded_${new_id}=true;`);
                }, 1);
            }
        });
    }
    
    function addTecdac(data,i) {

        
        let slider = `<li id="tecDacDiv${i}"><a id="tecDacA${i}" class="third-level-child i_dac_v_dac"
        href="javascript:void(0);">TEC ${i+1}</a>
        <div class="third-level-content variable-optical mb-0">
        <div class="row colfixone mb-0">
        <div class="col-lg-12 dactitle"></div>
            <div class="col-xl-3 col-lg-3 d-flex">
                <div><img src="../images/Power-Supply.png" /></div>
                <div><img src="../images/greenLed.png"></div>
                <div class="d-flex">
                    
                </div>
                <div class="ml-3 d-flex">
                    <div>
                        <div id = "vdac-slider-range-container" class="col-xl-1 d-flex">
                            <div class="dropdown">
                                <button class="setvalueidac light-color text-bold btn dropdown-toggle debugRangebtn" type="button" id="tecdac-range-drop-${i}" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" data-min=${data['set_min_current']} data-max=${data['set_current_limit']} style="color:#0056b3; text-align:left; font-weight:inherit; padding:0; background:none;">
                                Range
                                </button>
                    
                                <div class="dropdown-menu" aria-labelledby="tecdac-range-${i}">
                                    <button class="dropdown-item" id = "tecdac-range-drop-e-${i}" data-min = 0 data-max = 5 onclick="updateSliderRange(this, 'tec', ${i})">0V to 5V</button>
                                    <button class="dropdown-item" id = "tecdac-range-drop-e-${i}" data-min = 0 data-max = 10 onclick="updateSliderRange(this, 'tec', ${i})">0V to 10V</button>
                                    <button class="dropdown-item" id = "tecdac-range-drop-e-${i}" data-min = -2.5 data-max = 2.5 onclick="updateSliderRange(this, 'tec', ${i})">-2.5V to 2.5V</button>
                                    <button class="dropdown-item" id = "tecdac-range-drop-e-${i}" data-min = -3 data-max = 3 onclick="updateSliderRange(this, 'tec', ${i})">-3V to 3V</button>
                                    <button class="dropdown-item" id = "tecdac-range-drop-e-${i}" data-min = -5 data-max = 5 onclick="updateSliderRange(this, 'tec', ${i})">-5V to 5V</button>
                                    <button class="dropdown-item" id = "tecdac-range-drop-e-${i}" data-min = -10 data-max = 10 onclick="updateSliderRange(this, 'tec', ${i})">-10V to 10V</button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="pl-0">
                        <button class="btn secondry-btn form-control common-input-field" type="button" id="tecdac-range-${i}" aria-haspopup="true" aria-expanded="false" data-min=${data['set_min_current']} data-max=${data['set_current_limit']} style="border:1px solid #0056b3; text-align:left; text-overflow:ellipsis; overflow:hidden; white-space:nowrap; margin:0 !important; cursor:default; font-size:14px;">
                        ${data['set_min_current']}V to ${data['set_current_limit']}V
                        </button>
                    </div>
                </div>
            </div>
            
            <div class="col-xl-6 col-lg-6 mtBEq d-flex justify-content-start">
                <div class="slider-container">
                    <input type="text" id="Debug_Slider_tecDac_${i}"
                        class="slider" style="display:none" />
                </div>
            </div>
            <div class="col-xl-2 col-lg-2 col-sm-10 ml-2 d-flex justify-content-start">
                <div class="set-value-debug mt-1">Set Value</div>
                <div class="form-group ml-1 mb-1">
                    <input type="number"
                        id="Debug_Setvalue_tecDac_${i}" value=""
                        class="setvalueidac form-control common-input-field">
                        <span id="tecdacValueError${i}" style="color:red"></span>
                </div>
            </div>
            <div class="col-xl-1 col-lg-1 col-sm-2 ml-1">
                <label
                    class="idacBtn tooltipBtn toggleSwitch large switchFix">
                    <input type="checkbox" id="tecDac_Switch_${i}">
                    <span>
                        <span>OFF</span>
                        <span>ON</span>
                    </span>
                    <a></a>
                    <p class="tooltiptext"></p>
                </label>
            </div>
        </div>
        </div>
        </li>`





        $("#tec_slider_container").append(slider);
        // vDac_Slider_Objs_list.push({})
        // console.log(vDac_Slider_Objs_list, "vDac_Slider_Objs_list", idac_slider_no)
        //  to add event listener for dropdown functionality of slider
        if (true) {
            $("#tec_slider_container li:last-child a:first-child").on('click', function (e) {
                e.preventDefault();
                var $this = $(this);

                if ($this.hasClass('icon')) {
                    $this.removeClass('icon')
                } else {
                    $this.addClass('icon');
                }

                if ($this.next().hasClass('show-level')) {
                    $this.next().removeClass('show-level')
                } else {
                    $this.next().addClass('show-level');
                }
                if($this.hasClass('icon') == true)
                    $(".customClass").animate({
                        scrollTop: ($this.offset().top)-$(".customClass").offset().top + $(".customClass").scrollTop()
                    }, 1500);
            });
        }
        addTecdacSliderElement(data,i);
    }

    function addTecdacSliderElement(data,sliderElementId) {
        let new_id = sliderElementId;
        // $(`#vDacDiv${new_id}`).click(function () {
        $(`#tecDacA${new_id}`).click(function () {
            if ($(`#Debug_Slider_tecDac_${new_id}`).next().length == 0) {
                setTimeout(function () {
                    loadSlider(eval(`tecDac_Slider_Obj_${new_id}`), `#Debug_Slider_tecDac_${new_id}`, `#Debug_Setvalue_tecDac_${new_id}`, data['set_min_current'], data['set_current_limit'], data['set_current'], generalSliderWidthLVL1, true, 0.001, false, false, data['id'], false, isDebug = true)
                    updateOnOffSwitch(`#tecDac_Switch_${new_id}`, data["set_on_off_state"]);
                    // updateUserName(`#vDacUser${new_id}`, `#vDacUserInput${new_id}`, data["name"]);
                    $(`#Debug_Setvalue_tecDac_${new_id}`).change(function () {
                        updateSliderAccordingToSetValue(eval(`tecDac_Slider_Obj_${new_id}`), this, data['set_current_limit'], data['set_min_current']);
                    });
                    eval(`is_tecdac_loaded_${new_id}=true;`);
                }, 1);
            }
        });
    }

    addIdacSlider();
    addVdacSlider();
    validateIdacUser();
    function validateIdacUser(){
        let result = 0;
        iDAC_VDAC_data?.i_dac_data.forEach((data,i)=> {
            let name = $(`#iDacUserInput${i}`).val();
            if(name.length > 16){
                $(`#userInputError${i}`).html("Name must be less than 16 characters");
                result++;
            }
            else {
                $(`#userInputError${i}`).html("");
            }

            $(`#iDacUserInput${i}`).keyup((e)=> {
                if (e.target.value.length > 16) {
                    $(`#userInputError${i}`).html("Name must be less than 16 characters");
                }
                else {
                    $(`#userInputError${i}`).html("");
                }
            })
            // $(`#Debug_Setvalue_iDac_${i}`).keydown(function (e) {
            //     const regex = new RegExp("/^(0|[1-9]\d*)(\.\d+)?$/");
            //     console.log(e.target.value , !regex.test(e.target.value));
            //     if (e.target.value != null && !regex.test(e.target.value)) 
            //         e.preventDefault();
            // });
            // let idacValue = $(`#Debug_Setvalue_iDac_${i}`).val();
            // if(idacValue.match("^\\d+(\\.\\d+)?$")){
            //     $(`#idacValueError${i}`).html("")
            // }
            // else {
            //     if(idacValue){
            //         $(`#idacValueError${i}`).html("Value should be number");
            //         result++
            //     }
            // }
            // $(`#Debug_Setvalue_iDac_${i}`).keyup((e)=> {
            //     // if (/^\d+(\.\d{1,2})?$/.test(e.target.value)) {
            //     //     $(`#idacValueError${i}`).html("");
            //     //     return true
            //     // } else {
            //     //     $(`#idacValueError${i}`).html("Value should be number");
            //     //     result++;
            //     //     return false
            //     // }
            //     if (/^[0-9]+$/.test(e.target.value)) {
            //         // $(`#vdacValueError${i}`).html("");
            //         return true
            //     } else {
            //         // $(`#vdacValueError${i}`).html("Value should be number");
            //         // result++;
            //         e.preventDefault();
            //         return false
            //     }
            // })
        })
        if(result > 0)
            return false;
        else
            return true;
    }
    function saveIdac() {
        if(!validateIdacUser())
            return false;
        iDacData = []
        // updated_data = []
        // for (let i = 1; i < 17; i++) {
            iDAC_VDAC_data?.i_dac_data.forEach(function(data,i){
                // console.log(data);
                if (eval(`is_idac_loaded_${i}`)) {
                    data_to_send = {
                        id: data.id
                    }
                    // let idac_name = null
                    let idac_id = i;
                    // data_to_send["label_name"] = data.control_sectionName;
                    // to add current value
                    let idac_current_value = $(`#Debug_Setvalue_iDac_${i}`).val();
                    if (data.set_current != idac_current_value) {
                        data_to_send["label_name"] = data.control_sectionName;
                        data_to_send["idac_current_value"] = idac_current_value;
                        data.set_current = idac_current_value;
                        // if (idac_current_value == "") {
                        // 	data_to_send["idac_current_value"] = iDAC_VDAC_data["i_dac_data"][i - 1]["set_current"];
                        // }
                    }
    
                    // to add turn on off state
                    let turnOnOffState = $(`#iDac_Switch_${i}`).prop("checked") == true ? 1 : 0;
                    if (data.set_on_off_state != turnOnOffState) {
                        data_to_send["label_name"] = data.control_sectionName;
                        data_to_send["turnOnOffState"] = turnOnOffState;
                        data.set_on_off_state = turnOnOffState
                    }
                    // console.log(data_to_send);
                    // to add name
                    let name = $(`#iDacUserInput${i}`).val();
                    if (data.name != name) {
                        if (name == "") {
                            name = data.name;
                        } else {
                            data_to_send["label_name"] = data.control_sectionName;
                            data_to_send["name"] = name;
                        }
                        data.name = name;
                    }
                    // to add new min and max value to db
                    let idac_max = $(`#idac-range-${i}`).attr("data-max");
                    if (data.set_current_limit != idac_max) {
                        data_to_send["label_name"] = data.control_sectionName;
                        if (idac_max == "") {
                            idac_max = data.set_current_limit;
                        } else {
                            data_to_send["idac_max"] = idac_max;
                        }
                        data.set_current_limit = idac_max;
                    }
    
                    $(`#iDacUser${i}`).text(name);
                    $(eval(`iDacUserInput${i}`)).val(name);
                    // console.log(data_to_send);
                    if (Object.keys(data_to_send).length > 1) {
                        iDacData.push(data_to_send);
                    }
                    // console.log(iDacData);
                }
            })
        // }
        // console.log(iDacData);
        // return false;
        showMsg = true
        if (iDacData.length == 0) {
            showModal("Alert!", "No Changes Detected.")
            // ShowNotif("No Changes Detected.",'success');
        } else {
            $('.loaderDiv').css('display', 'block');
            $.ajax({
                type: "Get",
                url: "../cgi/cgi_IdacVdac.py",
                contentType: 'application/json',
                dataType: 'json',
                headers: {
                    'Access-Control-Allow-Origin': '*'
                },
                data: {
                    requestType: "updateIdac",
                    idac_data: JSON.stringify(iDacData)
                },
                success: function (response) {
                    if (showMsg) {
                        if(response.status == "fail"){
                            $(".modal-header").css({
                                "color": "#fff",
                                "background-color": "#db4141"
                            });
                            $(".close").css({
                                "color": "#fff"
                            });
                            mymodal.find('.modal-title').text('Error');
                            mymodal.find('.modal-body').html(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)
                            $('.loaderDiv').css('display', 'none');
                        }
                        else{

                            mymodal.find('.modal-title').text('Success');
                            let inner_text = "";
                            let updated_data = `<span class="modal-desc-head"> ${response.description} </span>
                                        <ul class="modal-ul-container">`;
                            for (let data_obj of iDacData) {
                                // console.log(data_obj);
                                updated_data += `<span style="font-weight:600">iDac ${data_obj["id"]}:</span>`
                                if ("name" in data_obj) {
                                    updated_data += `<li>name: ${data_obj["name"]}</li>`
                                }
                                if ("idac_current_value" in data_obj) {
                                    updated_data += `<li>current-value: ${data_obj["idac_current_value"]}</li>`
                                }
                                if ("turnOnOffState" in data_obj) {
                                    updated_data += `<li>on-off-switch: ${parseInt(data_obj["turnOnOffState"]) == 1 ? "On": "Off"}</li>`
                                }
                                if ("idac_max" in data_obj) {
                                    updated_data += `<li>range: 0 to ${data_obj["idac_max"]}</li>`
                                }
                                updated_data += "<span class = 'modal-desc-border'> </span>"
                            }
                            updated_data += '</ul>'
    
                            mymodal.find('.modal-body').html(updated_data).css({"text-align":"left"});
                            mymodal.modal('show');
                            setTimeout(()=> {
                                mymodal.modal("hide")
                            },autoClose)
                            loadIdacVdac();
                        }
                    }
                },
                error: function (ex) {
                    $("#test").html(ex.responseText)
                }
            });
            isSetUnprotectedMode = true;
        }
    }
    validateVdacUser();
    function validateVdacUser(){
        let result = 0;
        iDAC_VDAC_data?.v_dac_data.map((item,i) => {

                let name = $(`#vDacUserInput${i}`).val();
                if(name.length > 16){
                    $(`#vdacInputError${i}`).html("Name must be less than 16 characters");
                    result++;
                }
                else {
                    $(`#vdacInputError${i}`).html("");
                }
                $(`#vDacUserInput${i}`).keyup((e)=> {
                    if (e.target.value.length > 16) {
                        $(`#vdacInputError${i}`).html("Name must be less than 16 characters");
                    }
                    else {
                        $(`#vdacInputError${i}`).html("");
                    }
                })
                // let vdacValue = $(`#Debug_Setvalue_vDac_${i}`).val();
                // if(vdacValue.match("^\\d+(\\.\\d+)?$")){
                //     $(`#vdacValueError${i}`).html("")
                // }
                // else {
                //     if(vdacValue){
                //         $(`#vdacValueError${i}`).html("Value should be number");
                //         result++
                //     }
                // }
                // $(`#Debug_Setvalue_vDac_${i}`).keyup((e)=> {
                //     if (/^\d+(\.\d{1,2})?$/.test(e.target.value)) {
                //         $(`#vdacValueError${i}`).html("");
                //         return true
                //     } else {
                //         $(`#vdacValueError${i}`).html("Value should be number");
                //         result++;
                //         return false
                //     }
                // })
            
        })
        if(result > 0)
            return false;
        else
            return true;
    }
    function saveVdac() {
        if(!validateVdacUser())
            return false;
        vDacData = []
        iDAC_VDAC_data?.v_dac_data.forEach((item,i) => {
            if (eval(`is_vdac_loaded_${i}`)) {
                data_to_send = {
                    "id": item.id
                }
                // let vdac_name = null
                let vdac_id = i;
                // to add current value
                let vdac_current_value = $(`#Debug_Setvalue_vDac_${i}`).val();
                if (item["set_current"] != vdac_current_value) {
                    data_to_send["vdac_current_value"] = vdac_current_value;
                    item["set_current"] = vdac_current_value;
                }

                // to add turn on off state
                let turnOnOffState = $(`#vDac_Switch_${i}`).prop("checked") == true ? 1 : 0;
                if (item["set_on_off_state"] != turnOnOffState) {
                    data_to_send["turnOnOffState"] = turnOnOffState;
                    item["set_on_off_state"] = turnOnOffState
                }
                // to add name
                let name = $(`#vDacUserInput${i}`).val();
                if (item["name"] != name) {
                    if (name == "") {
                        name = item["name"];
                    } else {
                        data_to_send["name"] = name;
                    }
                    item["name"] = name;
                }
                // to add new min and max value to db
                let vdac_max = $(`#vdac-range-${i}`).attr("data-max");
                if (item["set_current_limit"] != vdac_max) {
                    if (vdac_max == "") {
                        vdac_max = item["set_current_limit"];
                    } else {
                        data_to_send["vdac_max"] = vdac_max;
                    }
                    item["set_current_limit"] = vdac_max;
                }
                let vdac_min = $(`#vdac-range-${i}`).attr("data-min");
                if (item["set_min_current"] != vdac_min) {
                    if (vdac_min == "") {
                        vdac_min = item["set_min_current"];
                    } else {
                        data_to_send["vdac_min"] = vdac_min;
                    }
                    item["set_min_current"] = vdac_min;
                }

                $(`#vDacUser${i}`).text(name);
                $(eval(`vDacUserInput${i}`)).val(name);
                if (Object.keys(data_to_send).length > 1) {
                    vDacData.push(data_to_send);
                }
            }
        })
        showMsg = true
        if (vDacData.length == 0) {
            showModal("Alert!", "No Changes Detected.")
        } else {
            $('.loaderDiv').css('display', 'block');
            $.ajax({
                url: "../cgi/cgi_IdacVdac.py",
                type: "get",
                data: {
                    requestType: "updateVdac",
                    vdac_data: JSON.stringify(vDacData)
                },
                success: function (response) {
                    if (showMsg) {
                        if(response.status == "fail"){
                            $(".modal-header").css({
                                "color": "#fff",
                                "background-color": "#db4141"
                            });
                            $(".close").css({
                                "color": "#fff"
                            });
                            mymodal.find('.modal-title').text('Error');
                            mymodal.find('.modal-body').html(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)
                            $('.loaderDiv').css('display', 'none');
                        }
                        else{
                            
                            mymodal.find('.modal-title').text('Success');
                            let inner_text = "";
                            let updated_data = `<span class="modal-desc-head"> ${response.description} </span>
                                    <ul class="modal-ul-container">`;
                            for (let data_obj of vDacData) {
                                updated_data += `<span style="font-weight:600">vDAC ${data_obj["id"]}:</span>`
                                if ("name" in data_obj) {
                                    updated_data += `<li>name: ${data_obj["name"]}</li>`
                                }
                                if ("vdac_current_value" in data_obj) {
                                    updated_data += `<li>current-value: ${data_obj["vdac_current_value"]}</li>`
                                }
                                if ("turnOnOffState" in data_obj) {
                                    updated_data += `<li>on-off-switch: ${parseInt(data_obj["turnOnOffState"]) == 1 ? "On": "Off"}</li>`
                                }
                                if ("vdac_max" in data_obj || "vdac_min" in data_obj) {
                                    updated_data += `<li>range: ${iDAC_VDAC_data["v_dac_data"][data_obj["id"]-1]["set_min_current"]} to ${iDAC_VDAC_data["v_dac_data"][data_obj["id"]-1]["set_current_limit"]}</li>`
                                }
                                updated_data += "<span class = 'modal-desc-border'> </span>"
                            }
                            updated_data += '</ul>'
    
                            mymodal.find('.modal-body').html(updated_data).css({"text-align":"left"});
                            mymodal.modal('show');
                            setTimeout(()=> {
                                mymodal.modal("hide")
                            },autoClose)
                            loadIdacVdac();
                        }
                    }
                },
                error: function (ex) {
                    $("#test").html(ex.responseText)
                }
            });
            isSetUnprotectedMode = true;

        }
    }
    function validateTecdacUser(){
        let result = 0;
        iDAC_VDAC_data?.tec_dac_data.map((item,i) => {

                // let name = $(`#vDacUserInput${i}`).val();
                // if(name.length > 16){
                //     $(`#vdacInputError${i}`).html("Name must be less than 16 characters");
                //     result++;
                // }
                // else {
                //     $(`#vdacInputError${i}`).html("");
                // }
                // $(`#vDacUserInput${i}`).keyup((e)=> {
                //     if (e.target.value.length > 16) {
                //         $(`#vdacInputError${i}`).html("Name must be less than 16 characters");
                //     }
                //     else {
                //         $(`#vdacInputError${i}`).html("");
                //     }
                // })
                // let vdacValue = $(`#Debug_Setvalue_vDac_${i}`).val();
                // if(vdacValue.match("^\\d+(\\.\\d+)?$")){
                //     $(`#vdacValueError${i}`).html("")
                // }
                // else {
                //     if(vdacValue){
                //         $(`#vdacValueError${i}`).html("Value should be number");
                //         result++
                //     }
                // }
                // $(`#Debug_Setvalue_vDac_${i}`).keyup((e)=> {
                //     if (/^\d+(\.\d{1,2})?$/.test(e.target.value)) {
                //         $(`#vdacValueError${i}`).html("");
                //         return true
                //     } else {
                //         $(`#vdacValueError${i}`).html("Value should be number");
                //         result++;
                //         return false
                //     }
                // })
            
        })
        if(result > 0)
            return false;
        else
            return true;
    }
    
    function saveTecdac() {
        if(!validateTecdacUser())
            return false;
        tecDacData = []
        iDAC_VDAC_data?.tec_dac_data.forEach((item,i) => {
            if (eval(`is_tecdac_loaded_${i}`)) {
                data_to_send = {
                    "id": item.id
                }
                // let vdac_name = null
                let tecdac_id = i;
                // to add current value
                let tecdac_current_value = $(`#Debug_Setvalue_tecDac_${i}`).val();
                if (item["set_current"] != tecdac_current_value) {
                    data_to_send["tecdac_current_value"] = tecdac_current_value;
                    item["set_current"] = tecdac_current_value;
                }

                // to add turn on off state
                let turnOnOffState = $(`#tecDac_Switch_${i}`).prop("checked") == true ? 1 : 0;
                if (item["set_on_off_state"] != turnOnOffState) {
                    data_to_send["turnOnOffState"] = turnOnOffState;
                    item["set_on_off_state"] = turnOnOffState
                }
                // to add name
                // let name = $(`#tecDacUserInput${i}`).val();
                // if (item["name"] != name) {
                //     if (name == "") {
                //         name = item["name"];
                //     } else {
                //         data_to_send["name"] = name;
                //     }
                //     item["name"] = name;
                // }
                // to add new min and max value to db
                let tecdac_max = $(`#tecdac-range-${i}`).attr("data-max");
                if (item["set_current_limit"] != tecdac_max) {
                    if (tecdac_max == "") {
                        tecdac_max = item["set_current_limit"];
                    } else {
                        data_to_send["tecdac_max"] = tecdac_max;
                    }
                    item["set_current_limit"] = tecdac_max;
                }
                let tecdac_min = $(`#tecdac-range-${i}`).attr("data-min");
                if (item["set_min_current"] != tecdac_min) {
                    if (tecdac_min == "") {
                        tecdac_min = item["set_min_current"];
                    } else {
                        data_to_send["tecdac_min"] = tecdac_min;
                    }
                    item["set_min_current"] = tecdac_min;
                }

                // $(`#vDacUser${i}`).text(name);
                // $(eval(`vDacUserInput${i}`)).val(name);
                if (Object.keys(data_to_send).length > 1) {
                    tecDacData.push(data_to_send);
                }
            }
        })
        showMsg = true
        if (tecDacData.length == 0) {
            showModal("Alert!", "No Changes Detected.")
        } else {
            $('.loaderDiv').css('display', 'block');
            $.ajax({
                url: "../cgi/cgi_IdacVdac.py",
                type: "get",
                data: {
                    requestType: "updateTecdac",
                    tecdac_data: JSON.stringify(tecDacData)
                },
                success: function (response) {
                    if (showMsg) {
                        if(response.status == "fail"){
                            $(".modal-header").css({
                                "color": "#fff",
                                "background-color": "#db4141"
                            });
                            $(".close").css({
                                "color": "#fff"
                            });
                            mymodal.find('.modal-title').text('Error');
                            mymodal.find('.modal-body').html(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)
                            $('.loaderDiv').css('display', 'none');
                        }
                        else{
                            
                            mymodal.find('.modal-title').text('Success');
                            let inner_text = "";
                            let updated_data = `<span class="modal-desc-head"> ${response.description} </span>
                                    <ul class="modal-ul-container">`;
                            for (let data_obj of tecDacData) {
                                updated_data += `<span style="font-weight:600">TEC ${data_obj["id"]}:</span>`
                                // if ("name" in data_obj) {
                                //     updated_data += `<li>name: ${data_obj["name"]}</li>`
                                // }
                                if ("tecdac_current_value" in data_obj) {
                                    updated_data += `<li>current-value: ${data_obj["tecdac_current_value"]}</li>`
                                }
                                if ("turnOnOffState" in data_obj) {
                                    updated_data += `<li>on-off-switch: ${parseInt(data_obj["turnOnOffState"]) == 1 ? "On": "Off"}</li>`
                                }
                                if ("tecdac_max" in data_obj || "tecdac_min" in data_obj) {
                                    updated_data += `<li>range: ${iDAC_VDAC_data["tec_dac_data"][data_obj["id"]-1]["set_min_current"]} to ${iDAC_VDAC_data["tec_dac_data"][data_obj["id"]-1]["set_current_limit"]}</li>`
                                }
                                updated_data += "<span class = 'modal-desc-border'> </span>"
                            }
                            updated_data += '</ul>'
    
                            mymodal.find('.modal-body').html(updated_data).css({"text-align":"left"});
                            mymodal.modal('show');
                            setTimeout(()=> {
                                mymodal.modal("hide")
                            },autoClose)
                            loadIdacVdac();
                        }
                    }
                },
                error: function (ex) {
                    $("#test").html(ex.responseText)
                }
            });
            isSetUnprotectedMode = true;

        }
    }

    $("#save-idac-data").click(saveIdac);
    $("#save-vdac-data").click(saveVdac);
    $("#save-tecdac-data").click(saveTecdac);

    // $("#iDac_slider_container li a:first-child").addClass("i_dac_v_dac");

    // $("#vDac_slider_container li a:first-child").addClass("i_dac_v_dac");


    $('.debudBtn').click(function () {
        var vr = $(this).attr('vr')
        $(".table_main").hide()
        $("#main_" + vr).show();
        $('.debudBtn').removeClass('cur');
        $(this).addClass('cur')
    });

    $("#iDac").click(function () {
        //$("#vDacDiv").css("display", "none");
        //$("#iDacDiv").css("display", "block");
        //console.log("added class to idac");
        $(".tab-content").removeClass('current');
        $("#iDacDivContainer").addClass("current");
        $("#idacVdacModalClose").click();
        // $("#").show();   
    });

    $("#vDac").click(function () {
        $(".tab-content").removeClass('current');
        $("#vDacDivContainer").addClass("current");
        $("#idacVdacModalClose").click();
        //$("#vDacDiv").css("display", "block")
        //$("#iDacDiv").css("display", "none")
        // $("#").show();   
    });

    // $("#iDacVdacSelectModal").modal('show');

    // $("#debug-tab").click(function () {
    //     $("#iDacVdacSelectModal").modal('show');
    // })

    $(".idacBtn").click(function (e) {
        if (isSetUnprotectedMode == false) {
            commonOpticalCombId = "#wavelength-turn-on-off";
            e.preventDefault();
            $(".warning-box-layout").fadeIn();
            $("#warning-password").focus();
        }
    });
    $(".setvalueidac").focus(function () {
        if (isSetUnprotectedMode == false) {
            commonOpticalCombId = "#wavelength-turn-on-off";
            $(this).prop("disabled", true);
            $(".warning-box-layout").fadeIn();
            $("#warning-password").focus();

        }
    });

    $("#demo-cancel-btn").click(function () {
        let iDacData = []
        iDAC_VDAC_data?.i_dac_data.forEach(function(data,i){
            if (eval(`is_idac_loaded_${i}`)) {
                data_to_send = {}
                let idac_current_value = $(`#Debug_Setvalue_iDac_${i}`).val();
                if (data.set_current != idac_current_value) {
                    data_to_send["idac_current_value"] = idac_current_value;
                    $(`#Debug_Slider_iDac_${i}`).next().remove("div");
                    loadSlider(eval(`iDac_Slider_Obj_${i}`), `#Debug_Slider_iDac_${i}`, `#Debug_Setvalue_iDac_${i}`, parseFloat(data.set_min_current), parseFloat(data.set_current_limit), 0, generalSliderWidthLVL2, true, 0.001, false, false, i, false, isDebug = true);
                }

                // to add turn on off state
                let turnOnOffState = $(`#iDac_Switch_${i}`).prop("checked") == true ? 1 : 0;
                if (data.set_on_off_state != turnOnOffState) {
                    data_to_send["turnOnOffState"] = turnOnOffState;
                }
                // to add name
                let name = $(`#iDacUserInput${i}`).val();
                if (data.name != name) {
                    data_to_send["name"] = name;
                }
                // to add new min and max value to db
                let idac_max = $(`#idac-range-${i}`).attr("data-max");
                if (data.set_current_limit != idac_max) {                   
                        data_to_send["idac_max"] = idac_max;
                }
                if (Object.keys(data_to_send).length > 0) {
                    iDacData.push(data_to_send);
                }

                // update loader value
                $(`#idac-range-${i}`).text(`${data.set_min_current} to ${data.set_current_limit}mA`);
                $(`#idac-range-${i}`).attr("data-max",data.set_current_limit)
                $(`#idac-range-${i}`).attr("data-min",data.set_min_current)
                
                // $(`#Debug_Setvalue_iDac_${i}`).off('change');
                eval(`iDac_Slider_Obj_${i}`).slider.setValues(data.set_current,data.set_current_limit);
                
                // update range value
                let setValue = $(`#Debug_Setvalue_iDac_${i}`);
                setValue[0].value = data.set_current;

                // update switch value
                updateOnOffSwitch(`#iDac_Switch_${i}`, data.set_on_off_state);

                // update user name value
                updateUserName(`#iDacUser${i}`, `#iDacUserInput${i}`,data.name);

               
               
            }
        })
        if(iDacData.length > 0){
            showMsg = true
            showModal("Alert!", "Changes Reversed");
            // ShowNotif("Changes Reversed",'success');
        }
        else {
            showMsg = true
            // ShowNotif("No Changes Detected",'success');
            showModal("Alert!", "No Changes Detected")
        }
    })
    $("#restore-idac-btn").click(()=>{
		let parameter = {url : "../cgi/cgi_RestoreDefaultSettings.py", data : {requestType : "restore_idac"}};
		$.ajax({
			url : parameter.url,
			type : "get",
			data : parameter.data,
			contentType: 'application/json',
			dataType: 'json',
			headers: {
				'Access-Control-Allow-Origin': '*'
			},
			success: function (response) {
                // ShowNotif(response.response,"success")
				showModal('Success', response.response);
			}
		})
	}) 
    $("#restore-vdac-btn").click(()=>{
		let parameter = {url : "../cgi/cgi_RestoreDefaultSettings.py", data : {requestType : "restore_vdac"}};
		$.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);
			}
		})
	})

    $("#demo-cancel-btn-vdac").click(function () {
        let vDacData = []
        iDAC_VDAC_data.v_dac_data.forEach(function(data,i){
            // if (count > 1 && count < 6) {
            //     addVdacSliderElement(count);
            // }
                if (eval(`is_vdac_loaded_${i}`)) {

                    data_to_send = {}
                    // let vdac_name = null
                    // to add current value
                    let vdac_current_value = $(`#Debug_Setvalue_vDac_${i}`).val();
                    if (data.set_current != vdac_current_value) {
                        data_to_send["vdac_current_value"] = vdac_current_value;
                        $(`#Debug_Slider_vDac_${i}`).next().remove("div");
                        loadSlider(eval(`vDac_Slider_Obj_${i}`), `#Debug_Slider_vDac_${i}`, `#Debug_Setvalue_vDac_${i}`, parseFloat(data.set_min_current), parseFloat(data.set_current_limit), 0, generalSliderWidthLVL2, true, 0.001, false, false, i, false, isDebug = true);
                    }
    
                    // to add turn on off state
                    let turnOnOffState = $(`#vDac_Switch_${i}`).prop("checked") == true ? 1 : 0;
                    if (data.set_on_off_state != turnOnOffState) {
                        data_to_send["turnOnOffState"] = turnOnOffState;
                    }
                    // to add name
                    let name = $(`#vDacUserInput${i}`).val();
                    if (data.name != name) {
                        data_to_send["name"] = name;
                    }
                    // to add new min and max value to db
                    let vdac_max = $(`#vdac-range-${i}`).attr("data-max");
                    if (data.set_current_limit != vdac_max) {
                       
                            data_to_send["vdac_max"] = vdac_max;
                    }
                    let vdac_min = $(`#vdac-range-${i}`).attr("data-min");
                    if (data.set_min_current != vdac_min) {
                        
                         data_to_send["vdac_min"] = vdac_min;
                    }
    
                    if (Object.keys(data_to_send).length > 0) {
                        vDacData.push(data_to_send);
                    }
                    $(`#vdac-range-${i}`).text(`${data.set_min_current}V to ${data.set_current_limit}V`);
                    $(`#vdac-range-${i}`).attr("data-max",data.set_current_limit)
                    $(`#vdac-range-${i}`).attr("data-min",data.set_min_current)
                    eval(`vDac_Slider_Obj_${i}`).slider.setValues(data.set_current,data.set_current_limit);
                    
                    // update range value
                    let changes = $(`#Debug_Setvalue_vDac_${i}`);
                    changes[0].value = data.set_current;
    
                    // update switch value
                    updateOnOffSwitch(`#vDac_Switch_${i}`, data.set_on_off_state);
    
                    // update user name value
                    updateUserName(`#vDacUser${i}`, `#vDacUserInput${i}`,data.name);
    
                   
                }
                
        })
        if(vDacData.length > 0){
            showMsg = true
            showModal("Alert!", "Changes Reversed.")
        }
        else {
            showMsg = true
            showModal("Alert!", "No Changes Detected.")
        }
    })
    
    $("#demo-cancel-btn-tec").click(function () {
        let tecDacData = []
        iDAC_VDAC_data.tec_dac_data.forEach(function(data,i){
            // if (count > 1 && count < 6) {
            //     addVdacSliderElement(count);
            // }
                if (eval(`is_tecdac_loaded_${i}`)) {

                    data_to_send = {}
                    // let vdac_name = null
                    // to add current value
                    let vdac_current_value = $(`#Debug_Setvalue_tecDac_${i}`).val();
                    console.log(data.set_current , vdac_current_value)
                    if (data.set_current != vdac_current_value) {
                        data_to_send["vdac_current_value"] = vdac_current_value;
                        $(`#Debug_Slider_tecDac_${i}`).next().remove("div");
                        loadSlider(eval(`tecDac_Slider_Obj_${i}`), `#Debug_Slider_tecDac_${i}`, `#Debug_Setvalue_tecDac_${i}`, parseFloat(data.set_min_current), parseFloat(data.set_current_limit), 0, generalSliderWidthLVL1, true, 0.001, false, false, i, false, isDebug = true);
                    }
    
                    // to add turn on off state
                    let turnOnOffState = $(`#tecDac_Switch_${i}`).prop("checked") == true ? 1 : 0;
                    if (data.set_on_off_state != turnOnOffState) {
                        data_to_send["turnOnOffState"] = turnOnOffState;
                    }
                    // to add name
                    // let name = $(`#tecDacUserInput${i}`).val();
                    // if (data.name != name) {
                    //     data_to_send["name"] = name;
                    // }
                    // to add new min and max value to db
                    let vdac_max = $(`#tecdac-range-${i}`).attr("data-max");
                    if (data.set_current_limit != vdac_max) {
                       
                            data_to_send["tecdac_max"] = vdac_max;
                    }
                    let vdac_min = $(`#tecdac-range-${i}`).attr("data-min");
                    if (data.set_min_current != vdac_min) {
                        
                         data_to_send["tecdac_min"] = vdac_min;
                    }
    
                    if (Object.keys(data_to_send).length > 0) {
                        tecDacData.push(data_to_send);
                    }
                    $(`#tecdac-range-${i}`).text(`${data.set_min_current}V to ${data.set_current_limit}V`);
                    $(`#tecdac-range-${i}`).attr("data-max",data.set_current_limit)
                    $(`#tecdac-range-${i}`).attr("data-min",data.set_min_current)
                    eval(`tecDac_Slider_Obj_${i}`).slider.setValues(data.set_current,data.set_current_limit);
                    
                    // update range value
                    let changes = $(`#Debug_Setvalue_tecDac_${i}`);
                    changes[0].value = data.set_current;
    
                    // update switch value
                    updateOnOffSwitch(`#tecDac_Switch_${i}`, data.set_on_off_state);
    
                    // update user name value
                    // updateUserName(`#tecDacUser${i}`, `#tecDacUserInput${i}`,data.name);
    
                   
                }
                
        })
        if(tecDacData.length > 0){
            showMsg = true
            showModal("Alert!", "Changes Reversed.")
        }
        else {
            showMsg = true
            showModal("Alert!", "No Changes Detected.")
        }
    })
    $("#idac").click(()=> {
        $("#vdac").removeClass("icon");
        $("#vDac_slider_container").parent().removeClass("show-level"); 
        $("#tec").removeClass("icon");
        $("#tec_slider_container").parent().removeClass("show-level");
        $("#regRef").removeClass("icon");
        $("#regRef-child").removeClass("show-level");
        $("#idac_buttons").css("display","block")
        $("#vdac_buttons").css("display","none")
        $("#tecdac_buttons").css("display","none")
        iDAC_VDAC_data?.i_dac_data.forEach(function(data,i){
            $(`#iDacDiv${i}>a`).removeClass("icon")
            $(`#iDacDiv${i}>div`).removeClass("show-level")
        }) 
        iDAC_VDAC_data?.i_dac_data.forEach(function(data,i){
            $(`#vDacDiv${i}>a`).removeClass("icon")
            $(`#vDacDiv${i}>div`).removeClass("show-level")
        })
        iDAC_VDAC_data?.tec_dac_data.forEach(function(data,i){
            $(`#tecDacDiv${i}>a`).removeClass("icon")
            $(`#tecDacDiv${i}>div`).removeClass("show-level")
        })
        // $(".universal-cancel").attr("id","demo-cancel-btn");
        // $(".universal-restore").attr("id","restore-idac-btn");
        // $(".universal-save").attr("id","save-idac-data");
    })
    $("#vdac").click(()=> {
        $("#idac").removeClass("icon");
        $("#iDac_slider_container").parent().removeClass("show-level");
        $("#tec").removeClass("icon");
        $("#tec_slider_container").parent().removeClass("show-level");
        $("#regRef").removeClass("icon");
        $("#regRef-child").removeClass("show-level");
        $("#idac_buttons").css("display","none")
        $("#tecdac_buttons").css("display","none")
        $("#vdac_buttons").css("display","block")
        iDAC_VDAC_data?.i_dac_data.forEach(function(data,i){
            $(`#iDacDiv${i}>a`).removeClass("icon")
            $(`#iDacDiv${i}>div`).removeClass("show-level")
        })
        iDAC_VDAC_data?.i_dac_data.forEach(function(data,i){
            $(`#vDacDiv${i}>a`).removeClass("icon")
            $(`#vDacDiv${i}>div`).removeClass("show-level")
        })
        iDAC_VDAC_data?.tec_dac_data.forEach(function(data,i){
            $(`#tecDacDiv${i}>a`).removeClass("icon")
            $(`#tecDacDiv${i}>div`).removeClass("show-level")
        })
        // $(".universal-cancel").attr("id","").attr("id","demo-cancel-btn-vdac");
        // $(".universal-restore").attr("id","restore-vdac-btn");
        // $(".universal-save").attr("id","save-vdac-data");
    })
    $("#tec").click(()=> {
        $("#idac").removeClass("icon");
        $("#iDac_slider_container").parent().removeClass("show-level");
        $("#vdac").removeClass("icon");
        $("#vDac_slider_container").parent().removeClass("show-level");
        $("#regRef").removeClass("icon");
        $("#regRef-child").removeClass("show-level");
        $("#idac_buttons").css("display","none")
        $("#tecdac_buttons").css("display","block")
        $("#vdac_buttons").css("display","none")
        iDAC_VDAC_data?.i_dac_data.forEach(function(data,i){
            $(`#iDacDiv${i}>a`).removeClass("icon")
            $(`#iDacDiv${i}>div`).removeClass("show-level")
        })
        iDAC_VDAC_data?.i_dac_data.forEach(function(data,i){
            $(`#vDacDiv${i}>a`).removeClass("icon")
            $(`#vDacDiv${i}>div`).removeClass("show-level")
        })
    })
    $("#regRef").click(()=> {
        $("#idac").removeClass("icon");
        $("#iDac_slider_container").parent().removeClass("show-level");
        $("#vdac").removeClass("icon");
        $("#vDac_slider_container").parent().removeClass("show-level");
        $("#sweep").removeClass("icon");
        $("#sweep-child").removeClass("show-level");
        iDAC_VDAC_data?.i_dac_data.forEach(function(data,i){
            $(`#iDacDiv${i}>a`).removeClass("icon")
            $(`#iDacDiv${i}>div`).removeClass("show-level")
        })
        for (let i = 1; i < 11; i++) {
            $(`#vDacDiv${i}>a`).removeClass("icon")
            $(`#vDacDiv${i}>div`).removeClass("show-level")
        } 
    })
    $("#regRef").click(function(){
        let $this = $(this)
        $(".customClass").animate({
            scrollTop: ($this.offset().top)-$(".customClass").offset().top + $(".customClass").scrollTop()
        }, 1000);
    })
    $("#idac_vdac_change").change((e)=> {
        $(`#sweep-range-idac`).text(`Select`);
        $(`#sweep-range-vdac`).text(`Select`);
        if(e.target.value == "iDAC"){
            $("#idac_vdac_list").attr("disabled",false)
            $("#idac-range-selector").css("display","block")
            $("#vdac-range-selector").css("display","none")
            $("#idac_vdac_list").empty().append(idacSweepList)
            // $("#idac_vdac_list").append(idacSweepList);
        }
        else  if(e.target.value == "vDAC") {
            $("#idac_vdac_list").attr("disabled",false)
            $("#vdac-range-selector").css("display","block")
            $("#idac-range-selector").css("display","none")
            $("#idac_vdac_list").empty().append(vdacSweepList)
            // $("#idac_vdac_list").append(vdacSweepList);
        }
        else {
            $("#idac_vdac_list").empty().append(["<option>Select</option>"])
        }
    })
    var interval;
    var serverResponse;
    $("#start-sweep").click(()=> {
        if(!start_current_error && !stop_current_error && !increment_step_error && !interval_sec_error){
            let idac_id = parseFloat($("#idac_vdac_list").val());
            let idac_vdac_change = $("#idac_vdac_change").val();
            let start_current = parseFloat($("#start_current").val());
            let stop_current = parseFloat($("#stop_current").val());
            let increment_step = parseFloat($("#increment_step").val());
            let interval_sec = parseFloat($("#interval_sec").val());
            let instantaneous_value = $("#instantaneous_value");
            let current_value = 0;
            if(increment_step && interval_sec  && stop_current ){
                if(start_current < stop_current  &&  increment_step != 0 && interval_sec !=0){
                    if(idac_id){
                        $("#stop-sweep").attr("disabled",false);
                        $("#start-sweep").attr("disabled",true).html("In Progress...");
                        $(".icon-container").css("display","block");
                        interval = setInterval(()=> {
                            if(current_value == 0)
                                current_value = (start_current) + (increment_step);
                            else 
                                current_value += (increment_step);
                            instantaneous_value.val(current_value);
                            if(current_value >= stop_current){
                                // $(this).html("Save")
                                // showModal("Success","Sweep Completed")
                                $(".icon-container").css("display","none")
                                // swal({title:serverResponse, text:"", type:"success"},function(){
                                //     // let start_current = $("#start_current").val(0);
                                //     // let stop_current = $("#stop_current").val(0);
                                //     // let increment_step = $("#increment_step").val(0);
                                //     // let interval_sec = $("#interval_sec").val(0);
                                //     let instantaneous_value = $("#instantaneous_value").val(0);
                                // });
                                // $("#stop-sweep").attr("disabled",true);
                                $.ajax({
                                    type: "get",
                                    url: "../cgi/cgi_setCurrentTest.py",
                                    contentType: 'application/json',
                                    headers: {
                                        'Access-Control-Allow-Origin': '*'
                                    },
                                    contentType: 'application/json',
                                    dataType: 'json',
                                    data: {
                                        requestType: "Set_InstantaneousCurrent",
                                        type : idac_vdac_change,
                                        start_current : start_current,
                                        stop_current : stop_current,
                                        increment_step : increment_step,
                                        interval_sec : interval_sec,
                                        id : idac_id
                                    },
                                    async: false,
                                    success: function (response) {
                                        serverResponse = response.description
                                        $("#stop-sweep").attr("disabled",true);
                                        if(response.status == "fail"){
                                            swal({title:serverResponse, text:"", type:"error"},function(){
                                                // let start_current = $("#start_current").val(0);
                                                // let stop_current = $("#stop_current").val(0);
                                                // let increment_step = $("#increment_step").val(0);
                                                // let interval_sec = $("#interval_sec").val(0);
                                                let instantaneous_value = $("#instantaneous_value").val(0);
                                            });
                                        }
                                        else{
                                            swal({title:serverResponse, text:"", type:"success"},function(){
                                                // let start_current = $("#start_current").val(0);
                                                // let stop_current = $("#stop_current").val(0);
                                                // let increment_step = $("#increment_step").val(0);
                                                // let interval_sec = $("#interval_sec").val(0);
                                                let instantaneous_value = $("#instantaneous_value").val(0);
                                            });
                                        }
                                        // ShowNotif(response.description,response.status)
                                        
                                    },
                                    error: function (ex) {
                                        console.log(ex);
                                    }
                                })
                                $("#start-sweep").attr("disabled",false).html("Start");
                                clearInterval(interval);
                                return;
                            }
                        },parseInt(interval_sec*1000));
        
                        // saving on DB
                    
                        
                    }
                    else {
                        ShowNotif("Please select at least one device","fail")
                    }
                }
                else {
                    ShowNotif("Stop current should not be less than start current and increment step or increment interval should not be 0",'fail')
                }
            }
            else {
                ShowNotif("Above value should not be empty or 0",'fail')
            }
        }
        else {
            ShowNotif("Above value should not be empty or 0",'fail')
        }

    })
    $("#stop-sweep").click(()=> {
        $('.loaderDiv').css({'display':'block'});
        // let start_current = $("#start_current").val(0);
        // let stop_current = $("#stop_current").val(0);
        // let increment_step = $("#increment_step").val(0);
        // let interval_sec = $("#interval_sec").val(0);
        $(".icon-container").css("display","none");
        let instantaneous_value = $("#instantaneous_value").val(0);
        $("#start-sweep").attr("disabled",false).html("Start");
        // $("#stop-sweep").attr("disabled",true);
        
        clearInterval(interval);
        $.ajax({
			type: "get",
			url: "../cgi/cgi_setCurrentTest.py",
			contentType: 'application/json',
			headers: {
				'Access-Control-Allow-Origin': '*'
			},
			contentType: 'application/json',
			dataType: 'json',
			data: {
				requestType: "stop_sweep",
			},
			async: false,
			success: function (response) {
                $('.loaderDiv').css('display', 'none');
				$("#stop-sweep").attr("disabled",true);
                if(response.status == "fail"){
                    swal({title:response.description, text:"", type:"error"},function(){})
                }
                else{
                    swal({title:"Sweep Stopped", text:"", type:"warning"},function(){})
                }

			}})
        return;
    })
    $("#idac_vdac_list").change((e)=> {
        let idac_vdac_change = $("#idac_vdac_change").val();
        $.ajax({
            type: "get",
            url: "../cgi/cgi_setCurrentTest.py",
            contentType: 'application/json',
            headers: {
                'Access-Control-Allow-Origin': '*'
            },
            contentType: 'application/json',
            dataType: 'json',
            data: {
                requestType: idac_vdac_change == 'iDAC' ? "read_iDac_id" : "read_vDac_id",
                id : e.target.value
            },
            async: false,
            success: function (response) {
                let idname = ''
                if(idac_vdac_change == 'iDAC'){
                    idname ="sweep-range-idac"
                }
                else {
                    idname ="sweep-range-vdac"

                }
                $(`#${idname}`).text(`${response[0].set_min_current} to ${response[0].set_current_limit} mA`);
                $(`#${idname}`).attr("data-max", response[0].set_current_limit);
                $(`#${idname}`).attr("data-min", response[0].set_min_current);
                
            },
            error: function (ex) {
                console.log(ex);
            }
        })
    })
    $("#start_current").keyup((e)=> {
        if(isNaN(e.target.value)) {
            start_current_error = true
           $("#start_current_error").html("Value should be numeric")
        }
        else {
            $("#start_current_error").html("")
        }
    }).change((e)=> {
        if(!e.target.value){
            e.target.value = 0
        }
    })
    
    $("#stop_current").keyup((e)=> {
        if(e.target.value != '' && isNaN(e.target.value)) {
            stop_current_error = true
           $("#stop_current_error").html("Value should be numeric")
        }
        else {
            $("#stop_current_error").html("")
        }
    }).change((e)=> {
        if(!e.target.value){
            e.target.value = 0
        }
    })
    $("#increment_step").keyup((e)=> {
        if(e.target.value != '' && isNaN(e.target.value)) {
            increment_step_error = true
           $("#increment_step_error").html("Value should be numeric")
        }
        else {
            $("#increment_step_error").html("")
        }
    }).change((e)=> {
        if(!e.target.value){
            e.target.value = 0
        }
    })
    $("#interval_sec").keyup((e)=> {
        if(e.target.value != '' && isNaN(e.target.value)) {
            interval_sec_error = true
           $("#interval_sec_error").html("Value should be numeric")
        }
        else {
            $("#interval_sec_error").html("")
        }
    }).change((e)=> {
        if(!e.target.value){
            e.target.value = 0
        }
    })

    

    
})
function getRfRegData() {
    $('.loaderDiv').show();
    $("#reg_name_search").val("");
    $("#value_search").val("");
    $.ajax({
        type: "get",
        url: "../cgi/cgi_RegSynth.py",
        contentType: 'application/json',
        headers: {
            'Access-Control-Allow-Origin': '*'
        },
        contentType: 'application/json',
        dataType: 'json',
        data: {
            requestType: "readAllReg",
        },
        success: function (response) {
            $('.loaderDiv').hide();
            $("#ref_reg").html("").append(`<table id="ref_reg_table" style="width:100%" class="table table-striped table-bordered display"></table>`)
            $("#ref_reg_table").append(`<thead>
                <tr class="tbheader">
                <th>#</th>
                ${
                    response.headers.map((item)=> (
                        `<th>${item}</th>`
                    )).join('')
                }
                </tr>
            </thead>`)

            $("#ref_reg_table").append(`<tbody>
                
                ${
                    response.data.map((item)=> (
                        `<tr>
                            <td><input type="radio" name="rfReg" id=""rfReg onclick="selectedRfRegId=${item.id}" value="${item.id}" /></td>
                            <td>${item.reg_name}</td>
                            <td>${item.address}</td>
                            <td>${item.value}</td>
                        </tr>`
                    )).join('')
                }
                
            </tbody>`)
            $("#ref_reg_table").DataTable({
                responsive: true,
                // searching: false
            })
        },
        error: function (ex) {
            console.log(ex);
        }
    })
}

function saveRfReg(){
    let reg_name = $("#reg_name").val();
    let address = $("#address").val();
    let value = $("#value").val();
    $(".loaderDiv").show()
    $.ajax({
        type: "get",
        url: "../cgi/cgi_RegSynth.py",
        contentType: 'application/json',
        headers: {
            'Access-Control-Allow-Origin': '*'
        },
        contentType: 'application/json',
        dataType: 'json',
        data: {
            requestType: selectedRfRegId ? "updateRfReg" : "saveRfReg",
            reg_name: reg_name,
            address: address,
            value: value,
            id : selectedRfRegId ?? ""
        },
        success: function (response) {
            $(".loaderDiv").hide()
            if(response.status == "success"){
                if(selectedRfRegId){
                    $("#editRgReg").removeClass("btn-info").addClass("btn-primary")
                    selectedRfRegId = "";
                    $("#refAdd").hide();
                }
                getRfRegData();
                $("#reg_name").val("").removeAttr("disabled");
                $("#address").val("");
                $("#value").val("");
                swal({title:response.description, text:"", type:"success"},function(){})
            }
            else{
                swal({title:response.description, text:"", type:"error"},function(){})
            }
        }
    })
}

function searchRfReg(){
    let reg_name = $("#reg_name_search").val();
    // let address = $("#address").val();
    let value = $("#value_search").val();
    $(".loaderDiv").show();
    $.ajax({
        type: "get",
        url: "../cgi/cgi_RegSynth.py",
        contentType: 'application/json',
        headers: {
            'Access-Control-Allow-Origin': '*'
        },
        contentType: 'application/json',
        dataType: 'json',
        data: {
            requestType: "readRF_reg",
            reg_name: reg_name,
            value: value
        },
        success: function (response) {
            $(".loaderDiv").hide();
            var table = $('#ref_reg_table').DataTable();
            table.destroy();
            if(response.reg_name){
                $("#ref_reg_table tbody").html("");
                $("#ref_reg_table tbody").append(`<tr>
                    <td>${response.reg_name}</td>
                    <td>${response.address}</td>
                    <td>${response.value}</td>
                </tr>`)
            }
            else{
                $("#ref_reg_table tbody").html(`<tr><td colspan="3" class="text-center">No Data Found</td></tr>`);
            }
            $("#ref_reg_table").DataTable({
                responsive: true,
                // searching: false
            })
            
        },
        error : function (response) {
            $(".loaderDiv").hide()
        }
    })
}

function openRfRegAdd(button){
    $("#refAdd").show();
    $("#refSearch").hide();
    validation.refresh();
    $("#reg_name").val("").removeAttr("disabled");
    $("#address").val("");
    $("#value").val("");
    $("#addRfReg").removeClass("btn-primary").addClass("btn-info")
    $("#editRgReg").removeClass("btn-info").addClass("btn-primary")
    $("#deleteRfReg").removeClass("btn-info").addClass("btn-primary")
}
function editRfRef(){
    validation.refresh()
    if(selectedRfRegId == ""){
        alert("Please select Rf_Reg")
        return
    }
    $("#editRgReg").removeClass("btn-primary").addClass("btn-info")
    $("#addRfReg").removeClass("btn-info").addClass("btn-primary")
    $("#deleteRfReg").removeClass("btn-info").addClass("btn-primary")
    $(".loaderDiv").show();
    $.ajax({
        type: "get",
        url: "../cgi/cgi_RegSynth.py",
        contentType: 'application/json',
        headers: {
            'Access-Control-Allow-Origin': '*'
        },
        contentType: 'application/json',
        dataType: 'json',
        data: {
            requestType: "readRFRegById",
            id : selectedRfRegId
        },
        success: function (response) {
            $(".loaderDiv").hide();
            $("#reg_name").val(response.reg_name).attr("disabled", "disabled");
            $("#address").val(response.address);
            $("#value").val(response.value);
        },
        error : function (response) {
            $(".loaderDiv").hide()
            // swal({title:response.description, text:"", type:"error"},function(){})
        }   
    })
    $("#refAdd").show();

}
function openSearch(){
    $("#refAdd").hide();
    $("#refSearch").toggle();
}

function deleteRfRef(){

    if(selectedRfRegId == ""){
        alert("Please select Rf_Reg")
        return
    }
    $("#refAdd").hide();
    $("#deleteRfReg").removeClass("btn-primary").addClass("btn-info")
    $("#editRgReg").removeClass("btn-info").addClass("btn-primary")
    $("#addRfReg").removeClass("btn-info").addClass("btn-primary")
    $(".loaderDiv").show();
    $.ajax({
        type: "get",
        url: "../cgi/cgi_RegSynth.py",
        contentType: 'application/json',
        headers: {
            'Access-Control-Allow-Origin': '*'
        },
        contentType: 'application/json',
        dataType: 'json',
        data: {
            requestType: "deleteRfReg",
            id : selectedRfRegId
        },
        success: function (response) {
            $(".loaderDiv").hide();
            swal({title:response.description, text:"", type:"success"},function(){})
            getRfRegData();
            selectedRfRegId = "";
        },
        error : function (response) {
            $(".loaderDiv").hide()
            swal({title:response.description, text:"", type:"error"},function(){})
        }
    })
}