/**
 * Report tool code.
 */

// Load XML metdat data for the given site using Ajax, and plot a graph of 
// the temperatures for each package on the tower.
function make_plot() {

  // Define default options for the flot library. Specify to 
  // use time on the x axis. These will be overridden by any options 
  // specified in the Ajax call.
  var flot_options = {
    xaxis: {
      mode: "time"//,      timeformat: "%m/%d/%y"
    },
    yaxis: {},
    y2axis: {},
    grid: {
      backgroundColor: "#fffaff",
      borderWidth: 1
    },
    legend: {
      container: $('#flot_legend')
    }
  };

  // Call the server, and draw the plot when server returns the data.
  $('#loading').show();
  $.getJSON('/cgi-pub/reports/report_ds.pl', 
    get_form_params(),
    function (json){
      if (json.errors) {
        $('#loading').hide();
        alert('Error: '+json.errors.join(', '));
        return;
      }

      // Enable plot report area.
      $('#report_area').removeClass('dimmed');

      // Build an array of datasets from the returned data.
      var array_of_datasets = [];
      for (var tower_id in json.datasets) {
        for (var i in json.datasets[tower_id]) {
          array_of_datasets.push(json.datasets[tower_id][i]);
        }
      }
      
      // Override default axis settings.
      jQuery.extend(flot_options.yaxis, json.yaxis);
      jQuery.extend(flot_options.y2axis, json.y2axis);
      
      // Draw the plot.
      $.plot($("#flot_graph"), array_of_datasets, flot_options);
      $('#loading').hide();
    }
  );
  
  return false;
}


// Get all relevent form control values to produce report.
function get_form_params() {
  var $selected_instruments = $("#timeline .instrument_selected");
  return {
    // Get the selected instruments as comma-sep string of instrument 
    // ids, e.g.: 23,288,4,98
    instrument_ids: $selected_instruments
      .map(function(){ return $(this).attr('id').substr(11); })
      .get()
      .join(","),

    // Make a string like: 288,98
    // Extracts instrument_id from ids like "units_23"
    alt_units: $selected_instruments.find(".units .selected[id]")
      .map(function(){return $(this).attr('id').substr(6);})
      .get()
      .join(","),
    
    min: $("form input[name='min']").is(':checked') ? 1 : 0,
    max: $("form input[name='max']").is(':checked') ? 1 : 0,
    avg: $("form input[name='avg']").is(':checked') ? 1 : 0,

    data_resolution: $("form input[name='data_resolution']:checked").val(),

    start_date: $("#start_date").val(),
    end_date: $("#end_date").val()
  }
}


// Initialize the page.
// This function is executed when the DOM is ready to be manipulated (but 
// images may not be done loading).
$(function () {
  
  // Updates all date-range controls with given start and/or
  // end dates, in milliseconds. Adjusts dates to prevent out of range 
  // and prevent end before start.
  function update_date_range(change) {
    var start_date = $start_date.datepicker('getDate');
    var end_date = $end_date.datepicker('getDate');
    
    if (!change.end && change.start && end_date && change.start > end_date.getTime()) {
      change.end = change.start;
    }
    if (!change.start && change.end && start_date && change.end < start_date.getTime()) {
      change.start = change.end;
    }
  
    var temp_date = new Date();
    if (change.start) {
      if (change.start < min_date.getTime()) {
        change.start = min_date.getTime();
      }
      temp_date.setTime(change.start);
      if (change.except != 'start_date') {
        $start_date.datepicker('setDate', temp_date);
      }
      if (change.except != 'date_slider') {
        $date_slider.slider('values', 0, change.start);
      }
    }
    if (change.end) {
      if (change.end > max_date.getTime()) {
        change.end = max_date.getTime();
      }
      temp_date.setTime(change.end);
      if (change.except != 'end_date') {
        $end_date.datepicker('setDate', temp_date);
      }
      if (change.except != 'date_slider') {
        $date_slider.slider('values', 1, change.end);
      }
    }

    update_date_range_bars(change);
  }

  function update_date_range_bars(change) {
    var min_time = min_date.getTime();
    if (change.start) {
      $date_range_start_bars.each(function() {
        var $this = $(this);
        $this
          .css('left', 
            ( (timeline_site_container_width - 5)
            * (change.start - min_date.getTime()) / (max_date.getTime() - min_date.getTime())
            ) + 'px')
          .height($this.parent().eq(0).height());
      });
    }
    if (change.end) {
      $date_range_end_bars.each(function() {
        var $this = $(this);
        $this
          .css('left', 
            ( (timeline_site_container_width - 5)
            * (change.end - min_date.getTime()) / (max_date.getTime() - min_date.getTime())
            ) + 'px')
          .height($this.parent().eq(0).height());
      });
    }
  }

  function fix_date_range_bars() {
    $date_range_start_bars.each(function() {
      var $this = $(this);
      $this.height($this.parent().eq(0).height());
    });
    $date_range_end_bars.each(function() {
      var $this = $(this);
      $this.height($this.parent().eq(0).height());
    });
  }

  // Initialize date choosing controls and their starting date values.
  var date_format = 'yyyy-MM-dd';
  var $start_date = $('#start_date');
  var $end_date = $('#end_date');
  var $date_slider = $('#date_slider');
  var $date_range_start_bars = $('.start_range_bar');
  var $date_range_end_bars = $('.end_range_bar');
  var timeline_site_container_width = $('.timeline_site_container').eq(0).width();

  var max_date = new Date();
  var start_date_default = new Date(max_date.getFullYear(), 1-1, 1);
  var end_date_default = new Date();

  $start_date.datepicker({
    minDate: min_date,
    maxDate: max_date,
    changeMonth: true,
    changeYear: true,
    dateFormat: 'yy-mm-dd',
    onClose: function() {
      update_date_range({
        start: Date.parse(this.value).getTime(),
        except: 'start_date'
      });
    }
  });

  $end_date.datepicker({
    minDate: min_date,
    maxDate: max_date,
    changeMonth: true,
    changeYear: true,
    dateFormat: 'yy-mm-dd',
    defaultDate: end_date_default,
    onClose: function() {
      update_date_range({
        end: Date.parse(this.value).getTime(),
        except: 'end_date'
      });
    }
  });
  
  {
    // "static local" variable
    var change = {except: 'date_slider'};
    
    $date_slider.slider({
      range: true,
      step: 1000*24*60*60, // one day
      min: min_date.getTime(),
      max: max_date.getTime(),
      values: [start_date_default.getTime(), end_date_default.getTime()],
      
      slide: function(event, ui) {
        change.start = ui.values[0] != change.start ? ui.values[0]: null;
        change.end = ui.values[1] != change.end ? ui.values[1]: null;
        update_date_range(change);
        change.start = ui.values[0];
        change.end = ui.values[1];
      }
    });
  }

  // If user types invalid date, reset using datepicker to bring it into range.
  // Push other date if changed date passes other date.
  $start_date.blur(function() {
    var start_date = Date.parseExact($start_date.val(), 'YYYY-M-d');
    if (start_date) {
      update_date_range({start: start_date.getTime()});
    }
  });
  $end_date.blur(function() {
    var end_date = Date.parseExact($end_date.val(), 'YYYY-M-d');
    if (end_date) {
      update_date_range({end: end_date.getTime()});
    }
  });


	// Add click-to-toggle selection to instrument buttons.
	$('#timeline .instrument')
		.click(function(){
			var $this = $(this);
			if ($this.hasClass('instrument_selected')) {
			  deselect_instrument($this);
			}
			else {
				select_instrument($this);
			}
		})
		.find('.units').click(function(e){
		  $(this).find('span').toggleClass('selected');
		  e.stopPropagation();
		})
  	.mousedown(function(){ return false; }); // Disable double-click selects text.

  // Provide buttons to quickly select a particular year. Build date range for each button.
  { var quick_picks = [];
    quick_picks.push([min_date.getFullYear(), [min_date, Date.parse(min_date.getFullYear() + '-12-31')]]);
    for (var y=1+min_date.getFullYear(); y<max_date.getFullYear(); y++) {
      quick_picks.push([y, [Date.parse(y + '-01-01'), Date.parse(y + '-12-31')]]);
    }
    quick_picks.push([max_date.getFullYear(), [Date.parse(max_date.getFullYear() + '-01-01'), max_date]]);
    
    var $quick_picks = $('#quick_picks');
    $.each(quick_picks, function(index, year) {
      $('<a href="#" class="btn ui-state-default ui-corner-all">'+ year[0] +'</a>').click(function(){
        update_date_range({
          start: year[1][0].getTime(), 
          end: year[1][1].getTime()
        });
        return false;
      }).appendTo($quick_picks);
    });
  }
  
  // Set initial start and end dates.
  update_date_range({
    start: start_date_default.getTime(),
    end: end_date_default.getTime()
  });

  // Initialize report area.
  $('#report_area').addClass('dimmed');

  // Initialize submit buttons -- don't submit form as normal; 
  // instead call ajax functions.
  $('#plot_btn').click(make_plot);
  

  // Build export URL, based on the current settings of all relevant controls.
  function get_export_url(report_type) {
    var params = $.param(get_form_params());
    return '/cgi-pub/reports/report_export.pl?format='+report_type+'&'+params;
  }

  // Show the current data as in HTML format in a popup window.
  $('#view_data_in_table_btn').click(function() {
    var w = UTIL.popup.open('');
    w.document.write('<img src="/images/indicators/indicator_arrows.gif">&nbsp;&nbsp;Loading...');
    w.location.href = get_export_url('html');
    return false;
  });
  $('#view_data_in_table_btn_url').bind("mouseenter mousedown keydown", function() {
    $('#view_data_in_table_btn_url').attr('href', get_export_url('html'));
    return true;
  });
  
  // Export the current data as TSV-formatted file.
  $('#export_tsv_btn').click(function() {
    window.location.href = get_export_url('tsv');
    return false;
  });
  $('#export_tsv_btn_url').bind("mouseenter mousedown keydown", function() {
    $('#export_tsv_btn_url').attr('href', get_export_url('tsv'));
    return true;
  });
  
  // Initialize instrument-area buttons.
  $('#btn_deselect_all').click(function() {
    $('#timeline .instrument').each(function() {
      deselect_instrument($(this));
    });
    return false;
  });

  // Dim/undim the min/max radio buttons if Full resolution is chosen/unchosen.
  $("input[name='data_resolution']").click(function () {
    if ($(this).val() == 'full') {
      $("input[name='min'], input[name='max']")
        .removeAttr("checked")
        .attr("disabled","disabled");
    }
    else {
      $("input[name='min'], input[name='max']")
        .removeAttr("disabled");
    }
  });
  
  
  // Show only the chosen site's instruments. Deselect any selected 
  // instruments at sites being hidden so they don't get plotted.
  
  $('#btn_show_200').click(function() {
    $('.timeline_site_container').hide();
    $('#site_200').show();
    fix_date_range_bars();
    return false;
  });

  $('#btn_show_301').click(function() {
    $('.timeline_site_container').hide();
    $('#site_301').show();
    fix_date_range_bars();
    return false;
  });

  $('#btn_show_1300').click(function() {
    $('.timeline_site_container').hide();
    $('#site_1300').show();
    fix_date_range_bars();
    return false;
  });

  $('#btn_show_all_sites').click(function() {
    $('.timeline_site_container').show();
    fix_date_range_bars();
    return false;
  });


  // The btn_abbreviated_instruments and btn_all_instruments code below
  // needs to be changed if we add more than two display levels.

  $('#btn_abbreviated_instruments').click(function() {
    $('#timeline .instrument:not(#timeline .display_0)')
      .css('visibility', 'hidden');
    $('#timeline .type_display_1').hide();
    fix_date_range_bars();
    return false;
  });

  $('#btn_all_instruments').click(function() {
    $('#timeline .instrument').css('visibility', 'visible');
    $('#timeline .type_display_1').show();
    fix_date_range_bars();
    return false;
  });

});


function select_instrument(instrument) {
  instrument
    .addClass('instrument_selected')
    .find('.plot').attr('src', '/images/plot.png');
}


function deselect_instrument(instrument) {
  instrument
    .removeClass('instrument_selected')
    .find('.plot').attr('src', '/images/plot_not.png');
}

/*
function debug(obj) {
  var s='';
  for (i in obj) {
    s += i+':'+obj[i]+"\n";
  }
  alert(s);
}
*/

