$(function () {
    var d2, whichtxt;
	var which = $("#which").attr('class');
	var url = $("#which").attr('rel');
	$.getJSON(url, function (data) { 
		var datasets = data;
	    var choiceContainer = $("#choices");
	    $.each(datasets, function(key, val) {
		if(key == 'up'){
			choiceContainer.append('<input type="checkbox" name="' + key + '" checked="checked" >' + val.label + '</input>');
		} else {
			choiceContainer.append('<input type="checkbox" name="' + key + '" >' + val.label + '</input>');
		}
	        
	    });
	    choiceContainer.find("input").click(plotAccordingToChoices);
	    function plotAccordingToChoices() {
	        var data = [];
	        choiceContainer.find("input:checked").each(function () {
	            var key = $(this).attr("name");
	            if (key && datasets[key])
	                data.push(datasets[key]);
	        });
	        if (data.length > 0)
	            $.plot($("#placeholder"),
				data, {
					lines: { show: true, lineWidth: 2, fill: 0.3 },
					minTickSize: [10, "minutes"],
	                yaxis: { min: 0, max: 100 },
	                xaxis: { mode: "time" },
		            selection: { mode: "xy" },
		            grid: { hoverable: true },
				}
				
			);
	    }
	    plotAccordingToChoices();
	});
	
	function showTooltip(x, y, contents) {
        $('<div id="tooltip">' + contents + '</div>').css( {
            top: y + 5,
            left: x + 5
        }).appendTo("body").fadeIn(200);
    }

    var previousPoint = null;
    $("#placeholder").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 y = item.datapoint[1].toFixed(0);
                
                showTooltip(item.pageX, item.pageY, item.series.label + ": " + y + "%");
            }
        } else {
            $("#tooltip").remove();
            previousPoint = null;            
        }
    });
});
