let idac_slider_no = 1
let vdac_slider_no = 1
let vDac_Slider_Objs_list = []
var iDAC_VDAC_data;
var idacSwitchSafe = true

function updateSliderRange(element, sliderName, sliderId) {
    let dropDownId = $(element).parent().attr('aria-labelledby');
    if($(`#${dropDownId}`).attr("data-max") == element.getAttribute("data-max"))
    {
        return false
    }
    $(`#${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 - 1]['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'));
        });
    }
}

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 () {

    // to get idac and vdac data from db
    $.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);
        }
    })
    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');
    }
    loadIdacVdac();

    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="${data.control_sectionName}" 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-md-5 col-xl-4 col-xxl-4 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>
                </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-md-4 col-xl-5 col-lg-5 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()
                  }, 1500);
            });
        }
        addIdacSliderElement(data,i);
    }

    function addIdacSliderElement(data,sliderElementId) {
        // console.log(data);
        let new_id = sliderElementId;
        $(`#iDacDiv${new_id}`).click(function () {
        // $(`#${data.control_sectionName}`).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() {
        iDAC_VDAC_data.v_dac_data.forEach(function(data,i){
            window['vDac_Slider_Obj_'+vdac_slider_no] = {};
            window['is_vdac_loaded_'+vdac_slider_no] = false;
            // if (count > 1 && count < 6) {
            //     addVdacSliderElement(count);
            // }
            addVdac(true);

        })
    }

    function addVdac(addEvent = true) {

        
        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}</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-md-5 col-xl-4 col-lg-4 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=${iDAC_VDAC_data["v_dac_data"][vdac_slider_no - 1]['set_min_current']} data-max=${iDAC_VDAC_data["v_dac_data"][vdac_slider_no - 1]['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 = 0 onclick="updateSliderRange(this, 'vdac', ${vdac_slider_no})">-10V to 0V</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=${iDAC_VDAC_data["v_dac_data"][vdac_slider_no - 1]['set_min_current']} data-max=${iDAC_VDAC_data["v_dac_data"][vdac_slider_no - 1]['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;">
                        ${iDAC_VDAC_data["v_dac_data"][vdac_slider_no - 1]['set_min_current']}V to ${iDAC_VDAC_data["v_dac_data"][vdac_slider_no - 1]['set_current_limit']}V
                        </button>
                    </div>
                </div>
            </div>
            
            <div class="col-md-4 col-xl-5 col-lg-5 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 (addEvent) {
            $("#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(vdac_slider_no);
        vdac_slider_no++;
    }

    function addVdacSliderElement(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}`, iDAC_VDAC_data["v_dac_data"][new_id - 1]['set_min_current'], iDAC_VDAC_data["v_dac_data"][new_id - 1]['set_current_limit'], iDAC_VDAC_data["v_dac_data"][new_id - 1]['set_current'], generalSliderWidthLVL2, true, 0.001, false, false, iDAC_VDAC_data["v_dac_data"][new_id - 1]['id'], false, isDebug = true)
                    updateOnOffSwitch(`#vDac_Switch_${new_id}`, iDAC_VDAC_data["v_dac_data"][new_id - 1]["set_on_off_state"]);
                    updateUserName(`#vDacUser${new_id}`, `#vDacUserInput${new_id}`, iDAC_VDAC_data["v_dac_data"][new_id - 1]["name"]);
                    $(`#Debug_Setvalue_vDac_${new_id}`).change(function () {
                        updateSliderAccordingToSetValue(eval(`vDac_Slider_Obj_${new_id}`), this, iDAC_VDAC_data["v_dac_data"][new_id - 1]['set_current_limit'], iDAC_VDAC_data["v_dac_data"][new_id - 1]['set_min_current']);
                    });
                    eval(`is_vdac_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("");
                }
            })
        })
        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"] = `iDAC${i+1}`;
                        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"] = `iDAC${i+1}`;
                        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"] = `iDAC${i+1}`;
                            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"] = `iDAC${i+1}`;
                        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.")
        } 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">${data_obj["label_name"]} :</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);
                            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.forEach(function(data,i){
            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("");
                }
            })
        })
        if(result > 0)
            return false;
        else
            return true;
    }

    function saveVdac() {
        if(!validateVdacUser())
            return false;
        vDacData = []
        iDAC_VDAC_data.v_dac_data.forEach(function(data,i){
            i++
            if (eval(`is_vdac_loaded_${i}`)) {
                data_to_send = {
                    "id": i
                }
                // let vdac_name = null
                let vdac_id = i;
                // to add current value
                let vdac_current_value = $(`#Debug_Setvalue_vDac_${i}`).val();
                if (iDAC_VDAC_data["v_dac_data"][i - 1]["set_current"] != vdac_current_value) {
                    data_to_send["vdac_current_value"] = vdac_current_value;
                    iDAC_VDAC_data["v_dac_data"][i - 1]["set_current"] = vdac_current_value;
                }

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

                $(`#vDacUser${i}`).text(name);
                $(eval(`vDacUserInput${i}`)).val(name);
                console.log()
                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);
                            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);

    // $("#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 () {
        // comment code
        $(".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")
        }
        else {
            showMsg = true
            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) {
                let message = `${response.response} `
				showModal('Success', message);
			}
		})
	}) 
    $("#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) {
                let message = `${response.response}`
				showModal('Success', message);
			}
		})
	})

    $("#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(i<16){
                if (eval(`is_vdac_loaded_${i+1}`)) {

                    data_to_send = {}
                    // let vdac_name = null
                    // to add current value
                    let vdac_current_value = $(`#Debug_Setvalue_vDac_${i+1}`).val();
                    if (data.set_current != vdac_current_value) {
                        data_to_send["vdac_current_value"] = vdac_current_value;
                        $(`#Debug_Slider_vDac_${i+1}`).next().remove("div");
                        loadSlider(eval(`vDac_Slider_Obj_${i+1}`), `#Debug_Slider_vDac_${i+1}`, `#Debug_Setvalue_vDac_${i+1}`, 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+1}`).prop("checked") == true ? 1 : 0;
                    if (data.set_on_off_state != turnOnOffState) {
                        data_to_send["turnOnOffState"] = turnOnOffState;
                    }
                    // to add name
                    let name = $(`#vDacUserInput${i+1}`).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+1}`).attr("data-max");
                    if (data.set_current_limit != vdac_max) {
                       
                            data_to_send["vdac_max"] = vdac_max;
                    }
                    let vdac_min = $(`#vdac-range-${i+1}`).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+1}`).text(`${data.set_min_current} to ${data.set_current_limit}mA`);
                    $(`#vdac-range-${i+1}`).attr("data-max",data.set_current_limit)
                    $(`#vdac-range-${i+1}`).attr("data-min",data.set_min_current)
                    eval(`vDac_Slider_Obj_${i+1}`).slider.setValues(data.set_current,data.set_current_limit);
                    
                    // update range value
                    let changes = $(`#Debug_Setvalue_vDac_${i+1}`);
                    changes[0].value = data.set_current;
    
                    // update switch value
                    updateOnOffSwitch(`#vDac_Switch_${i+1}`, data.set_on_off_state);
    
                    // update user name value
                    updateUserName(`#vDacUser${i+1}`, `#vDacUserInput${i+1}`,data.name);
    
                   
                }
                
            }
        })
        console.log(vDacData)
        if(vDacData.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"); 
        $("#idac_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")
        }) 
        for (let i = 1; i < 11; i++) {
            $(`#vDacDiv${i}>a`).removeClass("icon")
            $(`#vDacDiv${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");
        $("#idac_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")
        })
        for (let i = 1; i < 11; i++) {
            $(`#vDacDiv${i}>a`).removeClass("icon")
            $(`#vDacDiv${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");
    })
})
