// globals
$.myglobals = { result: "unset" } 

// defaults
var speed = 'download';
var type = 'home'
var url = channel_url+'/_js/broadband/graph_' + type + '_' + speed  + '.json';
var old_url = false;
var graph_container = $("#graph");
var choice_container = $("#choices");
var to_date = new Date(); to_date = new Date(to_date.getFullYear(), to_date.getMonth(), 1);
var months_back = 12;
//var from_date = new Date(to_date.getFullYear(), to_date.getMonth() - 2, 1).getTime(); //This will default to 3 months
var from_date = new Date(to_date.getFullYear(), to_date.getMonth() - 11, 1).getTime(); //Defaults to 1 year
var loaded = false;
var hash = false;
var provider_list = false;
var reset_providers = false;

// url params
var url_type = false;
var url_date = false;
var url_speed = false;
var url_providers = false;

// load graph function
function load_graph(url,refresh) {

	// if new data is coming in, reset globals back to unset
	if(old_url != url) {
		$.myglobals.result = 'unset';
	
	// return false if just a view change, otherwise we go in a massive loop
	} else {
	
		plot_graph(refresh);
	
		return false;
	
	}

	// if globals unset, fetch data
	if($.myglobals.result == 'unset') {
		$.getJSON(url, function(data){
			$.myglobals.result = data;
			
		});
	
	}

	// see if the data has been loaded & if it has, plot the graph
	data_check = setInterval("plot_graph(" + refresh + ")",10);
	
	// set old url so we can see if we need to fetch data when user changes settings
	old_url = url;
	
}

// handle clicks on the legends
choice_container.find("input").live("click", function(){

	// stop user from removing the last line
	if(choice_container.find("input:checked").length == 0) {
	
		$(this).attr('checked','checked');
		
	} else {
	
		url_providers = '';
		choice_container.find('input:checked').each(function(){
			url_providers += $(this).parent().parent().attr('id') + ',';
		});
	
		// update url
		update_url(true);
	
		load_graph(url,false);
	}

});

// Data type switcher
$("ul.dataType li a").click(function(){

	type = $(this).attr("href");
	type = type.replace('#','');

	// reset providers
	reset_providers = true;

	// update url
	url_type = type.toLowerCase();
	update_url();

	// get data url
	url = channel_url+'/_js/broadband/graph_' + url_type + '_' + url_speed + '.json';

	// plot the graph
	load_graph(url,true);
	
	// reset nav
	$('ul#results_nav li').removeClass('selected');
	$(this).parent().addClass('selected');
	
	return false;

});

// Speed switcher
$("fieldset#graph_speed input").click(function(){

	speed = $(this).val();
	
	// update url
	url_speed = speed.replace(/_.*$/, '').toLowerCase();
	update_url();
	
	// get data url
	url = channel_url+'/_js/broadband/graph_' + url_type + '_' + url_speed + '.json';
	
	// plot the graph
	load_graph(url,false);

});

// Time switcher
$("fieldset#graph_time select").change(function(){

	months_back = $(this).val() - 1;
	from_date = new Date(to_date.getFullYear(), to_date.getMonth() - months_back, 1).getTime();
	
	// update url
	url_date = $(this).val();
	update_url();
	
	// get data url
	url = channel_url+'/_js/broadband/graph_' + url_type + '_' + url_speed + '.json';

	$('#speedgraphs_home').attr('class','month_' + months_back);

	// plot the graph
	load_graph(url,false);

});

// IE doesn't treat images inside labels properly
$("#choices label img").live('click', function(){

	if ($.browser.msie) {
		$(this).parent().parent().find('input').click().blur();
	}

});

// round number to even
function roundToEven(n) { n = Math.round(n); return n + n%2; }

// plot the graph
function plot_graph(refresh) {

	// don't plot graph until data is loaded in globals
	if ($.myglobals.result != 'unset') {

		// setup colours we want to use for the lines
		var colors = [];
	
		// clear loaders
		$('form#graph_controls fieldset').find('input,select').removeAttr("disabled");
	
		// clear interval
		clearInterval(data_check);
		
		// set data
		data = $.myglobals.result;
		
		var graph_data = [];
		
		// don't do this if already loaded
		if(refresh) {
			loaded = false;
			choice_container.empty();
		}
		
		// set default speed
		var fastest_speed = 0;
		
		// load providers
		$.each(data.providers, function(i,item){

			// only show first 10		
			if(i <= 10) {
				
				// find fastest_speed
				if(item.data.length >= 2) {
				
					$.each(item.data, function(i,item){
					
						if(item[1] > fastest_speed) {
							fastest_speed = roundToEven(item[1]);
						}
					
					});
				
				}
		
				// push provider colour
				colors.push(item.colour);
				
				// hard code a colour (flot needs this to remember graph)
				item.color = i;
			
				// don't do this if already loaded
				if(refresh && !loaded) {
					
					// only add providers who have data
					if(item.data.length >= 2) {
					
						// insert checkboxes
						choice_container.append('<li id="' + item.provider_id + '"><label for="'+ i +'"><img src='+ $.image({src: item.image, width: 50, height: 31, alt: item.label, mode: 'fill',depth:32,notag:true}) +' height="31" width="50" alt='+ item.label +' /></label><span style="background:' + colors[i] + '"><input type="checkbox" id="' + i + '" name="' + i + '" /></span></li>');
					}
				
				}
		
			}
		
		});

		// only do this on initial load
		if(!loaded) {
		
			if(hash && !reset_providers) {
		
				// select providers in URL
				$.each(provider_list, function(i,item){
				
					choice_container.find('li#' + item + ' input').attr('checked','checked');
				
				});
			
			} else {
			
				url_providers = '';	
			
				// check first three inputs
				choice_container.find("input").each(function (i) {
				
					// make sure first 4 checked
					if(i<4) {
					
						$(this).attr("checked","checked");
						url_providers += $(this).parent().parent().attr('id') + ',';
					}
					
				});
				
				update_url();
			
			}
		
		}

		// figure out which providers to show
		choice_container.find("input:checked").each(function () {
			var key = $(this).attr("name");
			if (key && data.providers[key])
				graph_data.push(data.providers[key]);
		});

		// load graph
		var plot = $.plot($("#graph"), graph_data, {
			yaxis: {
				min: 0,
				max: fastest_speed,
				labelWidth: 50,
				ticks: 5,
				tickFormatter: function (val, axis) {
					return Math.round(val*10)/10 + 'Mb';
				}
			},
			xaxis: {
				mode: 'time',
				timeformat: "%b",
				minTickSize: [1, "month"],
	            min: from_date,
	            max: (new Date(to_date.getFullYear(), to_date.getMonth(), 1).getTime())
			},
			legend: { show: false },
			series: {
				shadowSize: 0,
				lines: {
			  		lineWidth: 4
				}
			},
			colors: colors,
			grid: {
				aboveData: true,
				borderWidth: 1,
				borderColor: '#CCCCCC',
				autoHighlight: true
			}
		});
		
		// actually puts the data onto the graph
		if(graph_data) {
			plot.setData(graph_data);
		}
		
		// redraws & applies new axis
		plot.setupGrid();

		// say we've loaded it
		loaded = true;
		
	} else {
	
		// disable inputs
		$('form#graph_controls fieldset').find('input,select').attr("disabled","disabled");
		
		// remove loader if already there
		$('.loading_overlay').remove();
		
		// add loader
		graph_container.append('<div class="loading_overlay"><span class="loading_large"><span class="sifr">'+$.asset({src: '/_img/broadband/speedtest_new/spinner_big.gif',width: 32,height: 32,alt: 'Loading'})+' Loading data...</span></span></div>');
	
	}

}

// get url
function get_url() {

	hash = window.location.hash.replace('#','')
	var updated_url = hash.split("_");
	
	// custom hash, update map accordingly
	if(hash) {

		// create url params
		url_type = updated_url[0];
		url_date = updated_url[1];
		url_speed = updated_url[2];
		url_providers = updated_url[3];

		// update axis CSS
		$('#speedgraphs_home').attr('class', 'month_' + url_date);

		// check url is ok
		switch(url_type){
			case "home":
				break
			case "mobile":
				break
			default:
				window.location = window.location.pathname
				break
		}
		switch(url_speed){
			case "download":
				break
			case "upload":
				break
			default:
				window.location = window.location.pathname
				break
		}

		// split providers
		provider_list = url_providers.split(",");

		// update type
		$('#results_nav li').removeClass('selected');
		$('#results_nav li.speedgraphs_' + url_type).addClass('selected');

		// update date
		$('#time_length option[value=' + url_date + ']').attr('selected', 'selected');
		from_date = new Date(to_date.getFullYear(), to_date.getMonth() - (url_date - 1), 1).getTime();
	
		// update speed
		$('#graph_speed input:radio').removeAttr('checked');
		$('#graph_speed input#' + url_speed + '_speeds:radio').attr('checked','checked');
		
		// update URL for data
		url = channel_url+'/_js/broadband/graph_' + url_type + '_' + url_speed + '.json';
		
		// load graph
		load_graph(url,true);
		
		return false;
	
	} else {
	
		// create url params
		url_type = 'home';
		url_date = '12';
		url_speed = 'download';
		
		// call again so we can update map
		load_graph(url,true);
		
		return false;
	
	}

}

// update url
function update_url() {

	// strip last , from string
	url_providers = url_providers.replace(/,$/,"");
	
	// update url
	window.location.href = window.location.href.replace(/#.*$/, '') + '#' + url_type + '_' + url_date + '_'  + url_speed + '_'  + url_providers;

	// track in analytics - WE NEED TO SWITCH TO ASYNC (NEW GOOGLE ANALYTICS)
	//pageTracker._trackPageview("/speedtest/trends/#" + url_type + '_' + url_date + '_'  + url_speed + '_'  + url_providers);

}

// have to wait till page loaded
$(document).ready(function() {

	// check url for params
	get_url();
	
	// click box magic
	if (!$.browser.msie || $.browser.msie && $.browser.version > 6) {
		//clickBox();
	}

});
