var curveSelections ={};

var curvePlot = function(id, curveData,curveColors) {
	console.log("I am starting");
	var i;
	var data = [];
	for(i in curveData){
		var datum = {
			label: "",
			data: curveData[i],
			lines: { show: true, fill: false },
			points: { show: true, radius: 1 }
		};
		data.push(datum);
	}
	console.log("Data created");
	var options = {
        legend: { show: false },
        xaxis: {mode: "time", timeformat: "%d/%m" },
        yaxis: { min: 0 },
        selection: { mode: "x" },
        colors: []
    };
	for(i in curveColors){
		options.colors.push(curveColors[i]);
	}
    
	var placeholder = $("#popCurve"+id);
	var plot = $.plot(placeholder, data, options);

    console.log("I am here as well");
    
    var overData = {
	        lines: { show: true, lineWidth: 1 },
	        shadowSize: 0,
	        xaxis: { ticks: [], mode: "time" },
	        yaxis: { ticks: [] },
	        selection: { mode: "x" },
	        legend: { show: false },
	        colors: []
	};

	for(i in curveColors){
		overData.colors.push(curveColors[i]);
	}
	
    var overview = $.plot($("#overview"+id), data, overData);

    var internalSelection = false;
    var sr = function (start, end) {
		// add 0.99 to start day so that the next day is selected
		var startDay = parseInt(((start / 86400000) + 0.99));
		var endDay = parseInt(end / 86400000)+1;
		if(endDay - startDay >= 4){
			console.log("Changing zoom in button to " + startDay +" to "+ endDay);
			curveSelections[id] ={'periodStart': startDay, 'periodEnd': endDay}; 
			return true;
		} else {
			console.log("NOT Zooming to " + startDay +" to "+ endDay + " (too small interval)");
			return false;
		}
	};
    placeholder.bind("selected", function (event, area) {
        if(sr(area.x1.toFixed(1), area.x2.toFixed(1))){
	        //zoom
	        plot = $.plot(placeholder, data,
	                      $.extend(true, {}, options, {
	                          xaxis: { min: area.x1, max: area.x2 }
	                      }));
			if (internalSelection){
	            return; // prevent eternal loop
			}
	        internalSelection = true;
	        overview.setSelection(area);
	        internalSelection = false;
        }
    });
    
    $("#overview"+id).bind("selected", function (event, area) {
        if (internalSelection){
            return;
        }
        internalSelection = true;
        plot.setSelection(area);
        internalSelection = false;
    });

	console.log("I am finishing");
};