function update_graph(min_date, max_date){
	var first_reading = parseInt(min_date);
	var last_reading = parseInt(max_date);
	var serialnumber = $F('graph_configuration_serialnumber');

	var chart_type = get_radio_value('graph_configuration_form', 'graph_configuration[type]');
	var flash_file = (chart_type == "Power" ? "Line" : "Column2D");

	var start_at = $F('graph_configuration_start_at_1i') + pad_date($F('graph_configuration_start_at_2i')) + pad_date($F('graph_configuration_start_at_3i')) + pad_date($F('graph_configuration_start_at_4i')) + pad_date($F('graph_configuration_start_at_5i'));
	var end_at = $F('graph_configuration_end_at_1i') + pad_date($F('graph_configuration_end_at_2i')) + pad_date($F('graph_configuration_end_at_3i')) + pad_date($F('graph_configuration_end_at_4i')) + pad_date($F('graph_configuration_end_at_5i'));
	var time = calculate_time_from_range(start_at, end_at);
	
	var chartTitle = create_chart_title(chart_type, time, currency);

	if(!detect_error(first_reading, last_reading, start_at, end_at)) {
		var jsURL="/device/"+serialnumber+"/"+chart_type.toLowerCase()+"/"+start_at+"/"+end_at+"/"+time+".xml";
		var chart = new FusionCharts('/flash/'+flash_file+'.swf', 'ChId1', '520', '442', '0', '0');
		chart.setDataURL(jsURL);
		chart.render('chartdiv');
		$('graph_title').update(chartTitle);
	}
}

function create_chart_title(chart_type, time, currency) {
	if("Power" == chart_type) {
		return "Power Usage - Watts (avg per " + create_time_for_title(time) + ")";
	} else if("Energy" == chart_type){
		return "Electricity Usage - KWH (sum per " + create_time_for_title(time) + ")";
	} else if("Cost" == chart_type) {
		return "Electricity Costs - " + currency + " (sum per " + create_time_for_title(time) + ")";
	} else {
		return "Carbon Costs - KG (sum per " + create_time_for_title(time) + ")";
	}
}

function create_time_for_title(time) {
	if("minutes" == time) {
		return "5 minutes";
	} else if("hours" == time) {
		return "hour";
	} else if("days" == time) {
		return "day";
	} else {
		return "month";
	}
}

function detect_error(first_reading, last_reading, start_at, end_at) {
	var start = parseInt(start_at);
	var end = parseInt(end_at);
	var diff = end - start;
	if(start_at < first_reading) {
		display_error_message("You've chosen a start date before your first reading.");
		return true;
	}
	else if(end_at > last_reading) {
		display_error_message("You've chosen an end date after your last reading.");
		return true;
	}
	else if(diff <= 0) {
		display_error_message("The end date you've chosen is before the start date.");
		return true;
	} else {
		clear_error_message();
		return false;
	}
}

function clear_error_message() {
	$('error_message').innerHTML = " ";
}
function display_error_message(message) {
	$('error_message').innerHTML = "<p class='error_message'>Oops! <br />" + message + "</p>";
}

function calculate_time_from_range(start_at, end_at) {
	// 2008 08 19 00 00
	// 0000 00 00 00 00
	var hours = 100;
	var days = 10000;
	var months = 1000000;
	var start = parseInt(start_at);
	var end = parseInt(end_at);
	var diff = end - start;
	if(diff < (12 * hours)) {
		return "minutes";
	} else if(diff < (4 * days)) {
		return "hours";
	} else if(diff < (3 * months)) {
		return "days";
	} else {
		return "months"
	}
}

function get_radio_value(form_id, field_name) {
	var fields = $(form_id)[field_name];
	for(var i = 0; i < fields.length; i++) {
		if(fields[i].checked) {
			return fields[i].value;
		}
	}
}

function pad_date(string) {
	if(string.length == 1) {
		return "0" + string;
	} else {
		return string;
	}
}

function init(device){
  Event.observe($('type'), 'change', function(){
    $('start').update('<option> Choose type and interval</option>');
    $('chartdiv').update('This text is replaced by the chart.');
  });
  Event.observe($('time'), 'change', function(){
    $('chartdiv').update('This text is replaced by the chart.');
  });
  Event.observe($('time'), 'change', buildTimeSelect);

  Event.observe($('start'), 'change', function(){
    params=renderChart();
    //fusion_path(serialnumber, type, start_date.to_formatted_s(:number), end_date.to_formatted_s(:number), time)
    var jsURL="/device/"+device+"/"+$F($('type'))+"/"+params[1]+"/"+params[2]+"/"+$F($('time'))+".xml";
    var chart = new FusionCharts('/flash/'+params[0]+'.swf', 'ChId1', '550', '442', '0', '0');
    chart.setDataURL(jsURL);
    chart.render('chartdiv');
  });
}

buildIntervalSelect = function(event){
  for (i=0; i<valuesArray.length; i++){
    var option = new Element('option', { 'value': i }).update(valuesArray[i]);
    $('time').insert(option);
  }
}

buildTimeSelect = function(event){
  switch (event.element().getValue()){
    case 'months':
      valuesArray = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
      break;
    case 'days':
      valuesArray = ['Sun', 'Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat']
      break;
    case 'hours':
      valuesArray = ['12am-6am', '6am-12pm', '12pm-6pm', '6pm-12am']
      break;
  }
  $('start').update();
  for (i=0; i<valuesArray.length; i++){
    var option = new Element('option', { 'value': i }).update(valuesArray[i]);
    $('start').insert(option);
  }
}

formatDate = function(date){
  var YYYY = date.getFullYear();
  var MM = ((date.getMonth()+1).toString().length===1)?('0'+(date.getMonth()+1)):(date.getMonth()+1);
  var dd = (date.getDate().toString().length===1)?('0'+date.getDate()):date.getDate();
  var hh = (date.getHours().toString().length===1)?('0'+date.getHours()):date.getHours();
  var mm = (date.getMinutes().toString().length===1)?('0'+date.getMinutes()):date.getMinutes();
  return YYYY+''+MM+''+dd+''+hh+''+mm;
}

function renderChart(){
  var charttype=($F($('type')) == 'power') ? "Line" : "Column2D";
  today = new Date();
  switch ($F($('time'))){
    case 'months':
      var theMonth = new Date(today.setMonth($F($('start'))));
      theMonth.setMonth(theMonth.getMonth()-3)
      if ($F($('start'))>(today.getMonth())){
        //startdate is last year
        theMonth.setFullYear(theMonth.getFullYear()-1);
      }
      theMonth.setDate(1);
      theMonth.setHours(0,0);
      starttime=formatDate(theMonth);
      theMonth.setMonth(theMonth.getMonth()+8);
      theMonth.setMinutes(theMonth.getMinutes()-1);
      endtime=formatDate(theMonth);
      break;
    case 'days':
      var dayDifference=7+(today.getDay())-$F($('start'));
      var theDay=new Date(today.setDate(today.getDate()-dayDifference));
      theDay.setDate(theDay.getDate()-3);
      theDay.setHours(0,0);
      starttime=formatDate(theDay);
      theDay.setDate(theDay.getDate()+6);
      theDay.setHours(23,59);
      endtime=formatDate(theDay);
      break;
    case 'hours':
      var yesterday = new Date(today.setDate(today.getDate()-1));
      switch ($F($('start'))){
        case '0':
          yesterday.setHours(0,0);
          yesterday.setHours(yesterday.getHours()-6);
          starttime=formatDate(yesterday);
          yesterday.setHours(11,59);
          endtime=formatDate(yesterday);
          break;
        case '1':
          yesterday.setHours(0,0);
          starttime=formatDate(yesterday);
          yesterday.setHours(17,59);
          endtime=formatDate(yesterday);
          break;
        case '2':
          yesterday.setHours(6,0);
          starttime=formatDate(yesterday);
          yesterday.setHours(23,59);
          endtime=formatDate(yesterday);
          break;
        case '3':
          yesterday.setHours(12,0);
          starttime=formatDate(yesterday);
          yesterday.setHours(yesterday.getHours()+18);
          yesterday.setMinutes(yesterday.getMinutes()-1);
          endtime=formatDate(yesterday);
          break;
      }
      break;
  }
  return [charttype,starttime,endtime];
}