$(document).ready( function() {

    // tabsFunctionality();
    nestedAccordionFunctionality();
    // opticalFrequencyComb();
    // demultiplexerOutputs();
    //OpticalfrequencycombSeries_100();

    // for page separation
    // OpticalfrequencycombSeries_1000();                     
    // DemuxSpectrumSeries();            
    
    //RenderIntensityChart();

    $(document).on("click","#btnNext",function() {
        // $("#setupTabs > .current").next('li').trigger('click');
        $("#setupTabs > .current").next('li').find('a:first')[0].click();
    });

    $(document).on("click","#btnPrevious",function() {
        // $("#setupTabs > .current").prev('li ').trigger('click');
        $("#setupTabs > .current").prev('li').find('a:first')[0].click();
    });

    $(document).on("change","#calibration #demultiplexer1",function() {
        var id =$(this).val();
        if (id === "PPS") {
            $("#demultiplexer1Value").html('');
            $("#calibrationCFSR").html('');
            $("#demultiplexer1Value").text("Scope Detected");
            $("#calibrationCFSR").text("Pulse Repetition Rate Range (GHz)");
        }
    });
    $(document).on('click', '#demoDemuxBtn', function (event) {
        console.log("hit scroll outside");
        event.preventDefault();
        $('html, body').animate({
            scrollTop: $("#plotly-graphs-div").offset().top
        }, 1500);
    });

});

function opticalFrequencyComb() {
    Highcharts.chart('opticalFrequencyCombo', {
        chart: {
            type: 'column'
        },
        credits: {
            enabled: false
        },
        title: {
            text: 'Optical Frequency Comb'
        },
        xAxis: {
            title: {
                text: 'Wavelength (nm)'
            },
            categories: [
                '1549.52',
                '1550',
                '1550.48'
            ],
            crosshair: true
        },
        yAxis: {
            min: 0,
            title: {
                text: 'Power (dBm)'
            }
        },
        tooltip: {
            headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
            pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
                '<td style="padding:0"><b>{point.y:.1f} mm</b></td></tr>',
            footerFormat: '</table>',
            shared: true,
            useHTML: true
        },
        plotOptions: {
            column: {
                pointPadding: 0.2,
                borderWidth: 0
            }
        },
        series: [{
            data: [400, 400, 400]
    
        }, {
            data: [400, 400, 400]
    
        }, {
            data: [400, 400, 400]
        },{
            data: [400, 400, 400]
        }]
    });
}

function demultiplexerOutputs() {
    Highcharts.chart('demultiplexerOutputs', {
        chart: {
            type: 'column'
        },
        credits: {
            enabled: false
        },
        title: {
            text: 'Demultiplexer outputs'
        },
        xAxis: {
            title: {
                text: 'Wavelength (nm)'
            },
            categories: [
                '1549.52 nm',
                '1550 nm',
                '1550.48'
            ],
            crosshair: true
        },
        yAxis: {
            min: 0,
            title: {
                text: 'Power (dBm)'
            }
        },
        tooltip: {
            headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
            pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
                '<td style="padding:0"><b>{point.y:.1f} mm</b></td></tr>',
            footerFormat: '</table>',
            shared: true,
            useHTML: true
        },
        plotOptions: {
            column: {
                pointPadding: 0.2,
                borderWidth: 0
            }
        },
        series: [{
            name: 'Demux 1',
            data: [200, 1000, 300]
    
        }, {
            name: 'Demux 2',
            data: [200, 1200, 250]
    
        }, {
            name: 'Demux 3',
            data: [200, 900, 250]
    
        }, {
            name: 'Demux 4',
            data: [1000, 300, 800]
    
        }]
    });
}

function OpticalfrequencycombSeries_100() {

    CallCSVData(csvPath_100).then(function (response) {
        var chart = new Highcharts.Chart({
            chart: {
                renderTo: 'divOpticalfrequencycomb_100',
                type: 'line',
                zoomType: 'xy'
            },
            title: {
                text: 'Optical frequency comb - 100 points'
            },
            xAxis: {
                title: {
                    text: 'Wavelength (nm)'
                }
            },
            yAxis: {
                title: {
                    text: 'Power (dBm)'
                }
            },
            series: [{
                name: 'Optical frequency comb',
                data: response,//[[1549.608888888889, -38.90705129753387]],
                dashStyle: 'dash',
            }]
        });
    });
}

function OpticalfrequencycombSeries_1000() {
    setTimeout(function(){ 
        CallCSVData(csvPath_1000+"?"+Math.random()).then(function (response) {
            var x=[];
            var y=[];
            for(var i=0;i<response.length;i++){
                x.push(response[i][0]);
                y.push(response[i][1]);
            }
            
            var min=parseInt(x[0]);
            var middle=parseInt(x[0])+1;
            var max=parseInt(x[0])+2;

            var opticalData = {
              x: x,
              y: y,
              type: 'scatter'
            };

            var data = [opticalData];

            var layout={
                autosize:false,
                width:600,
                height:500,
                title: 'Optical Frequency Comb 1000',
                xaxis: {
                    tickmode: "array", // If "array", the placement of the ticks is set via `tickvals` and the tick text is `ticktext`.
                    tickvals: [min+0.25,min+0.50,min+0.75,middle,middle+0.25,middle+0.50,middle+0.75,max]
                }
            };
            var config= {responsive: true}

            Plotly.newPlot('divOpticalfrequencycomb_1000', data,layout,config);
        });
    }, 1000);
}    

var chartDataDemux = [];

// function DemuxSpectrumSeries() {
//     CallCSVData(csvPath_demux1).then(function (response) {
//         chartDataDemux.push(response.slice(0,response.length-1));
//         CallCSVData(csvPath_demux2).then(function (response) {
//             chartDataDemux.push(response.slice(0,response.length-1));
//             CallCSVData(csvPath_demux3).then(function (response) {
//                 chartDataDemux.push(response.slice(0,response.length-1));
//                 CallCSVData(csvPath_demux4).then(function (response) {
//                     chartDataDemux.push(response.slice(0,response.length-1));
//                     RenderDemuxChart();
//                 });
//             });
//         });
//     });
// }

function DemuxSpectrumSeries() {
    CallCSVData(csvPath_demux1+"?"+Math.random()).then(function (response) {
        chartDataDemux.push(response.slice(0,response.length-1));
        CallCSVData(csvPath_demux2+"?"+Math.random()).then(function (response) {
            chartDataDemux.push(response.slice(0,response.length-1));
            CallCSVData(csvPath_demux3+"?"+Math.random()).then(function (response) {
                chartDataDemux.push(response.slice(0,response.length-1));
                CallCSVData(csvPath_demux4+"?"+Math.random()).then(function (response) {
                    chartDataDemux.push(response.slice(0,response.length-1));
                    RenderDemuxChart();
                });
            });
        });
    });
}

function RenderIntensityChart()
{
    Highcharts.chart('divIntensity', {
        chart: {
            type: 'heatmap',
            inverted: false,            
            zoomType: 'xy'
        },
    
        data: {
            csv: document.getElementById('csv').innerHTML
        },
    
        title: {
            text: 'Intensity Chart',
        },
    
       
    
        xAxis: {
            tickPixelInterval: 0.01,
            min: 0,
            max: 0.08
        },
    
        yAxis: {
            title: {
                text: null
            },
            labels: {
                format: '{value}'
            },
            minPadding: 0,
            maxPadding: 0,
            startOnTick: false,
            endOnTick: false,
            /* tickPositions: range(0.01,0.07,0.005), */
                     tickWidth: 0.001,
            min: 0.01,
            max: 0.09
        },
    
        colorAxis: {
            stops: [
                [0, '#0d0092'],
                [0.150, '#2432ff'], //1300
                [0.25, '#47aeff'],
                [0.375, '#62feb4'],
                [0.5, '#b2ff44'],
                [0.625, '#f9d200'],
                [0.75, '#f15204'],
                [0.8, '#b41600'],
            ],
            min: 1290,
            max: 1315
        },
        legend: {
            align: 'right',
            layout: 'vertical',
             margin: 0,
            verticalAlign: 'middle',
            y: 52,
            x:0,
            symbolHeight: 200
          },
        series: [{
                turboThreshold: 0,
            borderWidth: 0,
            rowsize: 0.002,
            colsize: 0.002, // one day
            tooltip: {
                headerFormat: 'Wavelength<br/>',
                pointFormat: '{point.x} {point.y} <br>{point.value} ℃</br>'
            }
        }]
    });
    
    function range(start, stop, step){
        if (typeof stop=='undefined'){
            // one param defined
            stop = start;
            start = 0;
        };
        if (typeof step=='undefined'){
            step = 1;
        };
        var result = [];
        for (var i=start; step>0 ? i<stop : i>stop; i+=step){
            result.push(i);
        };
        return result;
    };
    
}

function RenderDemuxChart(){
        var x1=[];
        var y1=[];
        var x2=[];
        var y2=[];
        var x3=[];
        var y3=[];
        var x4=[];
        var y4=[];

        for(var i=0;i<chartDataDemux[0].length;i++){
            x1.push(Number(chartDataDemux[0][i][0]).toFixed(2));
        }
        for(var i=0;i<chartDataDemux[0].length;i++){
            y1.push(chartDataDemux[0][i][1]);
        }

        for(var i=0;i<chartDataDemux[1].length;i++){
            x2.push(Number(chartDataDemux[1][i][0]).toFixed(2));
        }
        for(var i=0;i<chartDataDemux[1].length;i++){
            y2.push(chartDataDemux[1][i][1]);
        }

        for(var i=0;i<chartDataDemux[2].length;i++){
            x3.push(Number(chartDataDemux[2][i][0]).toFixed(2));
        }
        for(var i=0;i<chartDataDemux[2].length;i++){
            y3.push(chartDataDemux[2][i][1]);
        }

        for(var i=0;i<chartDataDemux[3].length;i++){
            x4.push(Number(chartDataDemux[3][i][0]).toFixed(2));
        }
        for(var i=0;i<chartDataDemux[3].length;i++){
            y4.push(chartDataDemux[3][i][1]);
        }

        chartDataDemux=[];

        var trace1 = {
              x: x1,
              y: y1,
              type: 'scatter',
              name:'Demux 1'
            };

            var trace2 = {
              x: x2,
              y: y2,
              type: 'scatter',
              name:'Demux 2'
            };

            var trace3 = {
              x: x3,
              y: y3,
              type: 'scatter',
              name:'Demux 3'
            };

            var trace4 = {
              x: x4,
              y: y4,
              type: 'scatter',
              name:'Demux 4'
            };

            var data = [trace1, trace2,trace3,trace4];

            var min=parseInt(x1[0]);
            var middle=parseInt(x1[0])+1;
            var max=parseInt(x1[0])+2;

            var layout={
                autosize:false,
                width:600,
                height:500,
                title: 'Demux Spectrum',
                xaxis: {
                    tickmode: "array", // If "array", the placement of the ticks is set via `tickvals` and the tick text is `ticktext`.
                    tickvals: [min+0.25,min+0.50,min+0.75,middle,middle+0.25,middle+0.50,middle+0.75,max]
                }
            };

            Plotly.newPlot('divDemuxSpectrum', data,layout);
}

