/* jQuery-graphs for plotting graphs from numeric forecast-data, WXSIM's latest.csv-version
*  Made by Henkka, nordicweather.net, March 2010
*  v.1.1
*/
$(function () {

// Datasets and specific settings for each value
//**********************************************
var tempdatasets = {
        "chill": {
            data: chill, 
            label: uahname4, 
            lines: { show: true, lineWidth: 1 },
            color: "blue"
        },
        "heat": {
            data: heat, 
            label: uahname4b, 
            lines: { show: true, lineWidth: 1 },
            color: "red"
        },
        "dew": {
            data: dew, 
            label: uahname3, 
            color: "lightgreen"
        },
        "temp": {
            data: temp, 
            label: uahname1, 
            color: "#FF6D6D",
            threshold: { below: colorchange, color: "#5CACEE" }
        }
        };
var userdatasets = {
        "wind": {   
            data: wsp, 
            label: uahname13, 
            yaxis: 1,
            color: "blue"
        },
        "baro": {   
            data: baro, 
            label: uahname2, 
            yaxis: 2,
            color: "green"
        },
        "hum": {   
            data: hum, 
            label: uahname6, 
            yaxis: 2,
            color: "brown"
        }
        };
var raindatasets = {
        "rain": {   
            data: rain, 
            label: uahname14, 
            color: "#5CACEE"
        },
        "frz": {   
            data: frz, 
            label: uahname9, 
            color: "red"
        },
        "sleet": {   
            data: sleet, 
            label: uahname8, 
            color: "orange"
        },
        "snow": {   
            data: snow, 
            label: uahname7, 
            color: "blue"
        }
        };
var solardatasets = { 
        "uv": {   
            data: uv, 
            label: uahname10, 
            color: "orange"
        },
        "solar": {   
            data: solar, 
            label: uahname15, 
            yaxis: 2,
            color: "yellow"
        }
        };
var clouddatasets = [ {   
            data: cloud, 
            label: uahname13, 
            color: "white"
        },{   
            data: cloudb,  
            color: "white"
        }];
var stormdatasets = {
        "seve": {   
            data: seve, 
            label: uahname11, 
            yaxis: 2,
            color: "green"
        },
        "conv": {   
            data: conv, 
            label: uahname12, 
            color: "red"
        }
        };
        
// CHECKBOXES
//***********************************************
// Here are set wich boxes are choosen as default

    // Temperature-graph
    var tempchoiceContainer = $("#tempchoices");
    $.each(tempdatasets, function(key, val) {
       if ((key == "temp")) {
       tempchoiceContainer.append('<input type="checkbox" name="' + key +
                               '" checked="checked" id="id' + key + '">' +
                               '<label for="id' + key + '">'
                                + val.label +'</label>&nbsp;&nbsp;');
       } else {
       tempchoiceContainer.append('<input type="checkbox" name="' + key +
                               '" id="id' + key + '">' +
                               '<label for="id' + key + '">'
                                + val.label +'</label>&nbsp;&nbsp;');
       }
    });
    tempchoiceContainer.find("input").click(plotAccordingToTempChoices);

    // Wind & baro-graph
    var userchoiceContainer = $("#userchoices");
    $.each(userdatasets, function(key, val) {
       if ((key == "wind")) {
       userchoiceContainer.append('<input type="checkbox" name="' + key +
                               '" checked="checked" id="id' + key + '">' +
                               '<label for="id' + key + '">'
                                + val.label +'</label>&nbsp;&nbsp;');
       } else {
       userchoiceContainer.append('<input type="checkbox" name="' + key +
                               '" id="id' + key + '">' +
                               '<label for="id' + key + '">'
                                + val.label +'</label>&nbsp;&nbsp;');
       }
    });
    userchoiceContainer.find("input").click(plotAccordingToUserChoices);
    
    // Solar-graph
    var solarchoiceContainer = $("#solarchoices");
    $.each(solardatasets, function(key, val) {
       if ((key == "uv")) {
       solarchoiceContainer.append('<input type="checkbox" name="' + key +
                               '" checked="checked" id="id' + key + '">' +
                               '<label for="id' + key + '">'
                                + val.label +'</label>&nbsp;&nbsp;');
       } else {
       solarchoiceContainer.append('<input type="checkbox" name="' + key +
                               '" id="id' + key + '">' +
                               '<label for="id' + key + '">'
                                + val.label +'</label>&nbsp;&nbsp;');
       }
    });
    solarchoiceContainer.find("input").click(plotAccordingToSolarChoices);
    
    // Precip-graph
    var rainchoiceContainer = $("#rainchoices");
    $.each(raindatasets, function(key, val) {
       if  ((key == "snow") && (showsnow == true)) {
       rainchoiceContainer.append('<input type="checkbox" name="' + key +
                               '" checked="checked" id="id' + key + '">' +
                               '<label for="id' + key + '">'
                                + val.label +'</label>&nbsp;&nbsp;');
       } else if  ((key == "sleet") && (showsleet == true)) {
       rainchoiceContainer.append('<input type="checkbox" name="' + key +
                               '" checked="checked" id="id' + key + '">' +
                               '<label for="id' + key + '">'
                                + val.label +'</label>&nbsp;&nbsp;');
       } else if  ((key == "frz") && (showfrz == true)) {
       rainchoiceContainer.append('<input type="checkbox" name="' + key +
                               '" checked="checked" id="id' + key + '">' +
                               '<label for="id' + key + '">'
                                + val.label +'</label>&nbsp;&nbsp;');
       } else if ((key == "rain") && (showrain == true)) {
       rainchoiceContainer.append('<input type="checkbox" name="' + key +
                               '" checked="checked" id="id' + key + '">' +
                               '<label for="id' + key + '">'
                                + val.label +'</label>&nbsp;&nbsp;');
       } else if (key == "totprec") {
       rainchoiceContainer.append('<input type="checkbox" name="' + key +
                               '" checked="checked" id="id' + key + '">' +
                               '<label for="id' + key + '">'
                                + val.label +'</label>&nbsp;&nbsp;');
       } else {
       rainchoiceContainer.append('<input type="checkbox" name="' + key +
                               '" id="id' + key + '">' +
                               '<label for="id' + key + '">'
                                + val.label +'</label>&nbsp;&nbsp;');
       }
    });
    rainchoiceContainer.find("input").click(plotAccordingToRainChoices);
    
   // Stormgraph
   var stormchoiceContainer = $("#stormchoices");
    $.each(stormdatasets, function(key, val) {
      stormchoiceContainer.append('<input type="checkbox" name="' + key +
                               '" checked="checked" id="id' + key + '">' +
                               '<label for="id' + key + '">'
                                + val.label +'</label>&nbsp;&nbsp;');
    });
   stormchoiceContainer.find("input").click(plotAccordingToStormChoices);
   
// GRAPHS
//**********************************
// Graphwide settings are found here

    // Temperature-graph
    function plotAccordingToTempChoices() {
        var tempdata = [];

        tempchoiceContainer.find("input:checked").each(function () {
            var key = $(this).attr("name");
            if (key && tempdatasets[key])
                tempdata.push(tempdatasets[key]);
        });


        if (tempdata.length > 0)
            var plot2 = $.plot($("#uah"), tempdata,      
            {
            series: {
            lines: { show: true, fill: false },
            shadowSize: 3
            },
            xaxis: {
            mode: "time",
            timeformat: '',
            tickSize: [1, "day"],
            //ticks: daylines,
            min: startdate,
            max: stopdate
            },
            yaxis: { labelWidth: 25},
            y2axis: { labelWidth: 25},
            grid: {
            borderColor: "#383875",
            borderWidth: 1,
            backgroundColor: { colors: ["#ddd", "#fafafa"] },
            hoverable: true,
            autoHighlight: true,
            mouseActiveRadius: 50
            },
            legend: {
            backgroundOpacity: 0.5,
            noColumns: 6,
            container: "#uahleg"
            }
          
            });
           
    }

   // Precipitation-graph
   function plotAccordingToRainChoices() {
        var raindata = [];

        rainchoiceContainer.find("input:checked").each(function () {
            var key = $(this).attr("name");
            if (key && raindatasets[key])
                raindata.push(raindatasets[key]);
        });
    
            if (raindata.length > 0)
            var plot4 = $.plot($("#uah3"), raindata,      
            {
            series: {
            bars: { show: true, fill: 0.9, barWidth: 7500000,align: "center" },
            shadowSize: 2
            },
            xaxis: {
            mode: "time",
            timeformat: '',
            tickSize: [1, "day"],
            min: startdate,
            max: stopdate
            },
            yaxis: { labelWidth: 25},
            y2axis: { labelWidth: 25},
            grid: {
            borderColor: "#383875",
            borderWidth: 1,
            backgroundColor: { colors: ["#ddd", "#fafafa"] },
            hoverable: true,
            autoHighlight: true,
            mouseActiveRadius: 50
            },
            legend: {
            backgroundOpacity: 0.5,
            noColumns: 6,
            container: "#uah3leg"
            }
          
            });
            
       }
       
   // UV&solar-graph
   function plotAccordingToSolarChoices() {
        var solardata = [];

        solarchoiceContainer.find("input:checked").each(function () {
            var key = $(this).attr("name");
            if (key && solardatasets[key])
                solardata.push(solardatasets[key]);
        });


        if (solardata.length > 0)
            var plot3 = $.plot($("#uah4"), solardata,      
            {
            series: {
            lines: { show: true, fill: true },
            shadowSize: 3
            },
            xaxis: {
            mode: "time",
            timeformat: '',
            tickSize: [1, "day"],
            min: startdate,
            max: stopdate
            },
            yaxis: { labelWidth: 25},
            y2axis: { labelWidth: 25},
            grid: {
            borderColor: "#383875",
            borderWidth: 1,
            backgroundColor: { colors: ["#ddd", "#fafafa"] },
            hoverable: true,
            autoHighlight: true,
            mouseActiveRadius: 50
            },
            legend: {
            backgroundOpacity: 0.5,
            noColumns: 6,
            container: "#uah4leg"
            }
          
            });
            
        }
           
    // Storm-graph
    function plotAccordingToStormChoices() {
        var stormdata = [];

        stormchoiceContainer.find("input:checked").each(function () {
            var key = $(this).attr("name");
            if (key && stormdatasets[key])
               stormdata.push(stormdatasets[key]);
        });

            var plot4 = $.plot($("#uah5"), stormdata,      
            {
            series: {
            lines: { show: true, fill: true },
            shadowSize: 3
            },
            xaxis: {
            mode: "time",
            timeformat: '',
            tickSize: [1, "day"],
            min: startdate,
            max: stopdate
            },
            yaxis : { labelWidth: 25, min: 0, max: 6},
            y2axis: { labelWidth: 25, min: 0, max: 6},
            grid: {
            borderColor: "#383875",
            borderWidth: 1,
            backgroundColor: { colors: ["#ddd", "#fafafa"] }
            },
            legend: {
            backgroundOpacity: 0.5,
            noColumns: 6,
            container: "#uah5leg"
            }
          
            });
           
    }
    
    // Wind & pressure-graph
    function plotAccordingToUserChoices() {
        var userdata = [];

        userchoiceContainer.find("input:checked").each(function () {
            var key = $(this).attr("name");
            if (key && userdatasets[key])
               userdata.push(userdatasets[key]);
        });

            var plot5 = $.plot($("#uah7"), userdata,      
            {
            series: {
            lines: { show: true, fill: false },
            shadowSize: 3
            },
            xaxis: {
            mode: "time",
            timeformat: '',
            tickSize: [1, "day"],
            min: startdate,
            max: stopdate
            },
            yaxis : { labelWidth: 25 },
            y2axis: { labelWidth: 25},
            grid: {
            borderColor: "#383875",
            borderWidth: 1,
            backgroundColor: { colors: ["#ddd", "#fafafa"] },
            hoverable: true,
            autoHighlight: true,
            mouseActiveRadius: 50
            },
            legend: {
            backgroundOpacity: 0.5,
            noColumns: 6,
            container: "#uah7leg"
            }
          
            });
           
    }
     
   // Cloudgraph
   var plot2 = $.plot($("#uah6"), clouddatasets,      
            {
            series: {
            lines: { show: true, lineWidth: 0, fill: true, fillColor: { colors:["#ccc", "#fafafa"]}},
            shadowSize: 0
            },
            xaxis: {
            mode: "time",
            timeformat: '',
            tickSize: [1, "day"],
            min: startdate,
            max: stopdate
            },
            yaxis: { ticks: [[-100, "100"], [0, "0"], [100, "100"]], max:100, min:-100, labelWidth: 25},
            y2axis: { labelWidth: 25},
            grid: {
            show: true,
            borderColor: "#383875",
            borderWidth: 0,
            tickColor: "lightblue",
            backgroundColor: "lightblue"
            },
            legend: {
            backgroundOpacity: 0.5,
            noColumns: 6,
            container: "#uah6leg"
            }
          
            });

    // Maybe we should plot the graphs too? ;)
    plotAccordingToTempChoices();
    plotAccordingToRainChoices();
    plotAccordingToUserChoices();
    plotAccordingToSolarChoices();
    plotAccordingToStormChoices();

// TOOLTIPS
//********************************************
// Each graph needs its own setting here, sigh
    
    function showTooltip(x, y, contents) {
        $('<div id="tooltip">' + contents + '</div>').css( {
            position: 'absolute',
            display: 'none',
            top: y + 2,
            left: x + 15,
            border: '1px solid #eee',
            padding: '2px',
            'background-color': '#fff',
            opacity: 0.90
        }).appendTo("body").fadeIn(200);
    }
    
    // Tooltip for tempgraph
    var previousPoint = null;
    $("#uah").bind("plothover", function (event, pos, item) {
        $("#x").text(pos.x.toFixed(2));
        $("#y").text(pos.y.toFixed(2));

            if (item) {
                if (previousPoint != item.datapoint) {
                    previousPoint = item.datapoint;
                    
                    $("#tooltip").remove();
                    var x = item.datapoint[0].toFixed(3),
                        y = item.datapoint[1].toFixed(1);
                    var x = tzdif+x*1;
                    var hy = new Date(x*1);
                    var day = hy.getDate();
                    var hour = hy.getHours();
                    var min = hy.getMinutes();
                    if ( min == '0' ) { min = '00'; }
                    var mo = hy.getMonth()+1;
                    var yr = hy.getFullYear();
                    showTooltip(item.pageX, item.pageY, hour+':'+min+' '+y);
                }
            }
            else {
                $("#tooltip").remove();
                previousPoint = null;            
            }
    });
    
   // Tooltip for precipitation-graph
   $("#uah3").bind("plothover", function (event, pos, item) {
        $("#x").text(pos.x.toFixed(2));
        $("#y").text(pos.y.toFixed(2));

            if (item) {
                if (previousPoint != item.datapoint) {
                    previousPoint = item.datapoint;
                    
                    $("#tooltip").remove();
                    var x = item.datapoint[0].toFixed(3),
                        y = item.datapoint[1].toFixed(1);
                    var x = tzdif+x*1;
                    var hy = new Date(x*1);
                    var day = hy.getDate();
                    var hour = hy.getHours();
                    var min = hy.getMinutes();
                    if ( min == '0' ) { min = '00'; }
                    var mo = hy.getMonth()+1;
                    var yr = hy.getFullYear();
                    showTooltip(item.pageX, item.pageY, hour+':'+min+' '+y);
                }
            }
            else {
                $("#tooltip").remove();
                previousPoint = null;            
            }
    });
    
    // Tooltip for UV/solar-graph
    $("#uah4").bind("plothover", function (event, pos, item) {
        $("#x").text(pos.x.toFixed(2));
        $("#y").text(pos.y.toFixed(2));

            if (item) {
                if (previousPoint != item.datapoint) {
                    previousPoint = item.datapoint;
                    
                    $("#tooltip").remove();
                    var x = item.datapoint[0].toFixed(3),
                        y = item.datapoint[1].toFixed(1);
                    var x = tzdif+x*1;
                    var hy = new Date(x*1);
                    var day = hy.getDate();
                    var hour = hy.getHours();
                    var min = hy.getMinutes();
                    if ( min == '0' ) { min = '00'; }
                    var mo = hy.getMonth()+1;
                    var yr = hy.getFullYear();
                    showTooltip(item.pageX, item.pageY, hour+':'+min+' '+y);
                }
            }
            else {
                $("#tooltip").remove();
                previousPoint = null;            
            }
    });
    
    // Tooltip for wind/pressure-graph
    $("#uah7").bind("plothover", function (event, pos, item) {
        $("#x").text(pos.x.toFixed(2));
        $("#y").text(pos.y.toFixed(2));

            if (item) {
                if (previousPoint != item.datapoint) {
                    previousPoint = item.datapoint;
                    
                    $("#tooltip").remove();
                    var x = item.datapoint[0].toFixed(3),
                        y = item.datapoint[1].toFixed(1);
                    var x = tzdif+x*1;
                    var hy = new Date(x*1);
                    var day = hy.getDate();
                    var hour = hy.getHours();
                    var min = hy.getMinutes();
                    if ( min == '0' ) { min = '00'; }
                    var mo = hy.getMonth()+1;
                    var yr = hy.getFullYear();
                    showTooltip(item.pageX, item.pageY, hour+':'+min+' '+y);
                }
            }
            else {
                $("#tooltip").remove();
                previousPoint = null;            
            }
    });
    
    
});
