// JavaScript Document
// Make sure that datasets.js is imported BEFORE this file

// Global variables:
var marker_click = false;   // Flags if a marker has been clicked on or off
var last_clicked = 0;       // ID of the last marker to trigger a click event
init_dataset();             // Put all of the data into the appropriate arrays

// Set options for the graph
var options = 
{ 
    lines:      { show: true },
    points:     { show: true },
    selection:  { mode: "xy" },
    legend:     { noColumns: 2,
                  margin: 20 },
    grid:       { hoverable: true, clickable: true },
    yaxis:      { min: 0 },   //, max: 45
    xaxis:      { mode: 'time', timeformat: "%b - %y" }
};

var points = new Array();
var totalPoints;

function init()
{
    totalPoints = 4;
    points[0] = { title: 'Lucas Heights',lat: -34.047,lng: 150.988 };
    points[1] = { title: 'Warrawong',lat: -34.4842,lng: 150.8878 };
    points[2] = { title: 'Mayfield',lat: -32.8990,lng: 151.7389 };
    points[3] = { title: 'Mascot',lat: -33.9315,lng: 151.1944 };

}

function initialize_map() 
{
    init();
    if (GBrowserIsCompatible())
    {
        var map = new GMap2(document.getElementById("map_canvas"));
        map.setCenter(new GLatLng(-33.4632,151.1890), 7);
        
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        map.setMapType(G_HYBRID_MAP);
        
        // Add the points and put a controller on the map for zoom & scroll    
        var latlng;
        
        for (var i = 0; i < totalPoints; i++)
        {
        	latlng = new GLatLng(points[i].lat,points[i].lng);      // Lucas Heights
       		map.addOverlay(create_marker(latlng, (i+1), points[i].title));
        }
    }
}

function create_marker(latlng, id, marker_title)
{
    var marker = new GMarker(latlng, {title:marker_title});

    marker.value = id;
    GEvent.addListener(marker, "click", function() { click_marker(id) });
    
    return marker;
}

// This function handles the click event for the markers on the map
function click_marker(marker)
{
    $("#Areas option[value=" + marker +"]").attr("selected","selected") ;

    if (marker > 0)
    {
        $("#title_text").html("<strong>" + points[marker-1].title + "</strong>");

    	if(last_clicked == 0)    // First time click
     	   marker_click = !marker_click;
        
    	var choices = document.getElementById("choices");
    	var grapharea = document.getElementById("grapharea");
    	var graphlabel = document.getElementById("g_label");

    	// Check if we are clicking a new marker, or turning off the graph
	
	
    	//if(marker == last_clicked) { marker_click = !marker_click; } // JOSH: This breaks the app in firefox
    	if(marker_click)
    	{
    	    choices.style.visibility = "visible";
     	   grapharea.style.visibility = "visible";
     	   grapharea.style.height = "290px";
        
     	   graphlabel.style.visibility = "visible";
     	   graphlabel.style.height = "290px";
    	}
   	else
    	{
    	    choices.style.visibility = "hidden";
    	    grapharea.style.visibility = "hidden";
    	    grapharea.style.height = "0px";
    	    
    	    graphlabel.style.visibility = "hidden";
    	    graphlabel.style.height = "0px";
    	}
   	last_clicked = marker;
    
    	// Check which year is selected in the year drop down box
    	var yearIndex = document.getElementById("yearselect").selectedIndex;
    	var year = document.getElementById("yearselect").options[yearIndex].text;
    
    	datasets = select_dataset(marker, year);
    
    	// Hard-code color indices to prevent them from shifting as countries are turned on/off
    	var i = 0;
    	$.each(datasets, function(key, val)
    	{
    	    val.color = i;
    	    ++i;
    	});
    
    	plotAccordingToChoices("#item_choice","#grapharea");
    }
    else
    {


    }
}

function select_dataset(datasetnum, yr)
{
    if (datasetnum == 1)
    {
        if (yr == 2000)         datasets = dataset1;
        else if (yr == 2001)    datasets = dataset2;
        else if (yr == 2002)    datasets = dataset3;
        else if (yr == 2003)    datasets = dataset4;
        else if (yr == 2004)    datasets = dataset5;
        else if (yr == 2005)    datasets = dataset6;
        else if (yr == 2006)    datasets = dataset7;
        else if (yr == 2007)    datasets = dataset8;
        else if (yr == 2008)    datasets = dataset9;
        else if (yr == 2009)    datasets = dataset37;
        else if (yr == 2010)    datasets = dataset42;
    }
    else if (datasetnum == 2)
    {
        if (yr == 2000)         datasets = dataset10;
        else if (yr == 2001)    datasets = dataset11;
        else if (yr == 2002)    datasets = dataset12;
        else if (yr == 2003)    datasets = dataset13;
        else if (yr == 2004)    datasets = dataset14;
        else if (yr == 2005)    datasets = dataset15;
        else if (yr == 2006)    datasets = dataset16;
        else if (yr == 2007)    datasets = dataset17;
        else if (yr == 2008)    datasets = dataset18;
        else if (yr == 2009)    datasets = dataset38;
        else if (yr == 2010)    datasets = dataset43;
    }
    else if (datasetnum == 3)
    {
        if (yr == 2000)         datasets = dataset19;
        else if (yr == 2001)    datasets = dataset20;
        else if (yr == 2002)    datasets = dataset21;
        else if (yr == 2003)    datasets = dataset22;
        else if (yr == 2004)    datasets = dataset23;
        else if (yr == 2005)    datasets = dataset24;
        else if (yr == 2006)    datasets = dataset25;
        else if (yr == 2007)    datasets = dataset26;
        else if (yr == 2008)    datasets = dataset27;
        else if (yr == 2009)    datasets = dataset39;
        else if (yr == 2010)    datasets = dataset44;
    }
    else    // datasetnum == 4;
    {
        if (yr == 2000)         datasets = dataset28;
        else if (yr == 2001)    datasets = dataset29;
        else if (yr == 2002)    datasets = dataset30;
        else if (yr == 2003)    datasets = dataset31;
        else if (yr == 2004)    datasets = dataset32;
        else if (yr == 2005)    datasets = dataset33;
        else if (yr == 2006)    datasets = dataset34;
        else if (yr == 2007)    datasets = dataset35;
        else if (yr == 2008)    datasets = dataset36;
        else if (yr == 2009)    datasets = dataset40;
        else if (yr == 2010)    datasets = dataset41;
    }
    
    return datasets;
}

function change_graph_year(year)
{
    datasets = select_dataset(last_clicked, year);
    plotAccordingToChoices("#item_choice","#grapharea");
}

function update_graph() { plotAccordingToChoices("#item_choice","#grapharea"); }

function plotAccordingToChoices(str_item_choice,str_grapharea) 
{
	
    var data = [];
	var item_choice = $(str_item_choice);
	var grapharea = $(str_grapharea);

	
    item_choice.find("input:checked").each(function () 
    {
        var key = $(this).attr("name");
        if (key && datasets[key])
            data.push(datasets[key]);
	});
   
	if (data.length > 0)
		$.plot(grapharea, data, options);
		
	// Add tooltips to hover events over plot points
    var previousPoint = null;

    $(str_grapharea).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(2), y = item.datapoint[1].toFixed(2);
                showTooltip(item.pageX, item.pageY, item.series.label + " = " + y);
            }
        }
        else 
        {
            $("#tooltip").remove();
            previousPoint = null;
        }
    });
}

function showTooltip(x, y, contents) 
{
    $('<div id="tooltip">' + contents + '</div>').css( 
    {
        position: 'absolute',
        display: 'none',
        top: y + 5,
        left: x + 5,
        border: '1px solid #fdd',
        padding: '2px', 'background-color': '#fee',
        opacity: 0.80
    }).appendTo("body").fadeIn(200);
}

// Hard-code color indices to prevent them from shifting as countries are turned on/off
var i = 0;
$.each(datasets, function(key, val)
{
    val.color = i;
    ++i;
});




