var Graph = {};
Graph.tooltipHash = new Hash();
Graph.data = [];
Graph.localData = [];
Graph.options = {};
Graph.overview;
Graph.plot;

function showTooltip(x, y, refX, refY) {
  var tooltipIndex = refX + "+" + refY;
  var contents = Graph.tooltipHash.get(tooltipIndex);
  jQuery('<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);
}


function updateGraph() {
  var url = "/adjustments/show/" + $('username').value + ".json";
  $('instructions_div').hide();
  $('home_div').hide();
  
  new Ajax.Request(url, {
    method: 'get',
    onCreate: function() {
      $('ajax_loader').show();
    },
  	onSuccess: function(transport) {
	    var location = new String(window.location);
	    var domain = location.split('#')[0];
	    window.location.hash = $('username').value;
  	  
    	Graph.data = [];
	Graph.localData = [];
    	transport.responseJSON.each(function(adjustment, index) {
  	    var pointString;
  	    point = [adjustment['adjustment']['twitter_created_at_utc'], adjustment['adjustment']['new_utils']];
  	    Graph.data.push(point);
  	    pointString = adjustment['adjustment']['twitter_created_at_utc'] + "+" + adjustment['adjustment']['new_utils'];
  	    Graph.tooltipHash.set(pointString, "Current Utils: " + adjustment['adjustment']['new_utils'] + '<br>' + adjustment['adjustment']['text']);
  	  });
	
	var j = 0;
	var lastPoint;
	for( var p = Graph.data.length - 1; p >= 0; p--){
	  Graph.localData[j] = Graph.data[p];
	  var date = new Date(Graph.data[p][0]);
	  var oldDate = new Date();
	  oldDate.setDate(oldDate.getDate()-80);
	  if(date < oldDate && p < Graph.data.length - 35){
	    lastPoint = Graph.data[p][0];
	    break;
	  }
	j++;
	}

	Graph.options = { 
  	    xaxis: { mode: "time" },
  	    points: {show: "true"}, 
  	    colors: ["#e13333"],
  	    lines: {show: "true"}, 
  	    selection: {mode: "x"},
  	    grid: { hoverable: true, clickable: true } 
	};
  		      
	Graph.plot = jQuery.plot(jQuery("#myUtils"),[ Graph.localData ], Graph.options);
  
	Graph.overview = jQuery.plot(jQuery("#utilOverview"), [Graph.data], {
        lines: { show: true, lineWidth: 1 },
        shadowSize: 0,
    		xaxis: { ticks: [], mode: "time" },
    		colors: ["#e13333"],
    		yaxis: { ticks: [] },
    		selection: { mode: "x" }
      });
	var ranges = new Object();
	ranges.xaxis = new Object();
	if(lastPoint){
          ranges.xaxis.from = lastPoint;
        }else{
          ranges.xaxis.from = Graph.data[0][0];
        }
	ranges.xaxis.to = Graph.data[Graph.data.length - 1][0];
	Graph.overview.setSelection(ranges, false);

    },
	  onComplete: function(transport) {
      $('ajax_loader').hide();
      //alert(transport.responseText);
    }
  });
};

document.observe("dom:loaded", function() {
  $('username_submit').observe("click", function(event) {
    updateGraph();
  });
  $('username').observe('keypress', function(event) {
    if(event.keyCode == Event.KEY_RETURN) {
      updateGraph();
      this.blur();
    }
  });
  
  $('title').observe('click', function(event) {
    $('home_div').show();
    $('instructions_div').hide();
  });
  
  $('show_instructions').observe('click', function(event) {
    $('instructions_div').show();
    $('home_div').hide();
  });
  
  $('utilDescription').observe('click', function(event) {
    $('what_are_utils').toggle();
  });
  
  $$('#what_are_utils .close').first().observe('click', function(event) {
    $('what_are_utils').hide();
  });

  var previousPoint = null;
  jQuery("#myUtils").bind("plothover", function (event, pos, item) {
    jQuery("#x").text(pos.x.toFixed(2));
    jQuery("#y").text(pos.y.toFixed(2));

  	if (item) {
  	  if (previousPoint != item.datapoint) {
        previousPoint = item.datapoint;
            
        jQuery("#tooltip").remove();
        var x = item.datapoint[0].toFixed(0),
        y = item.datapoint[1].toFixed(0);
            
        showTooltip(item.pageX, item.pageY, x, y);
  	  }
  	}
  	else {
  	  jQuery("#tooltip").remove();
  	  previousPoint = null;            
  	}
  });

  jQuery("#myUtils").bind("plotselected", function (event, ranges) {
    // do the zooming
    Graph.plot = jQuery.plot(jQuery("#myUtils"), 
      [Graph.data],
      jQuery.extend(true, {}, Graph.options, {
        xaxis: { min: ranges.xaxis.from, max: ranges.xaxis.to }
      })
    );

    // don't fire event on the overview to prevent eternal loop
    Graph.overview.setSelection(ranges, true);
  });

   
  jQuery("#utilOverview").bind("plotselected", function (event, ranges) {
    Graph.plot.setSelection(ranges);
  });
  
  username = window.location.hash.gsub('#','')
  if(username) {
    $('username').value = username;
    updateGraph();
  }
});
