$(function(){
  var trends = $('#trends');
  var query = null;
  var options = {
  
    series: {
      lines: { show: true },
      points: { show: true }
    },
    
    legend: {
      position: 'nw',
      labelFormatter: function(label, series) {
        
        var tmpQuery = label;
        $.each(query, function(l, q){
          if (typeof q[label] != "undefined"){
            tmpQuery = q[label];
          }
        });
        
        return '<a target="_blank" href="http://search.twitter.com/search?q=' + tmpQuery + '">' + label + '</a>';
        
      },
      backgroundOpacity: 0.7
    },
    
    xaxis: {
      mode: "time",
      timeformat: "%H:%M",
      minTickSize: [5, "minute"]
    },
    
    yaxis: {
      min: 0,
      minTickSize: 10
    },
    
    grid: {
      hoverable: true,
      clickable: true
    }
    
  };
  
  function showTooltip(x, y, contents) {
    $('<div id="tooltip">' + contents + ' </div>').css( {
      position: 'absolute',
      display: 'none',
      top: y + 10,
      left: x + 10,
      border: '1px solid #fdd',
      padding: '4px',
      'background-color': '#fee'
    }).appendTo("body").fadeIn(200);
  }
  
  var previousPoint = null;
  $('#trends').bind('plothover', function(event, pos, item){
    
    if (item){
      if ((previousPoint == null) || (previousPoint[0] != item.datapoint[0] || previousPoint[1] != item.datapoint[1])) {
      
        previousPoint = item.datapoint;
        $("#tooltip").remove();

        showTooltip(item.pageX, item.pageY, item.series.label);
      
      }
    }else{
      $("#tooltip").remove();
      previousPoint = null; 
    }
    
  });
  
  $('#trends').bind('plotclick', function(event, pos, item){
    if (item){
      var tmpQuery = item.series.label;
        $.each(query, function(l, q){
          if (typeof q[item.series.label] != "undefined"){
            tmpQuery = q[item.series.label];
          }
        });
      
      window.open('http://search.twitter.com/search?q=' + tmpQuery)
    }
  });

  function updateTrends(){
    $('span#ajax').html('<img src="img/ajax.gif" />');
    $.ajax({
      type: "GET",
      url: "json.php",
      cache: false,
      dataType: "json",
      
      success: function(data, status){
      
        options.xaxis.max = data.xaxis_max;
        options.xaxis.min = data.xaxis_min;
        query = data.query;
        $.plot(trends, data.data, options);
        
        if (data.no_trends_now){
          $('#no-trends').html('Pēdējās divās stundās visi "maļ" savu, tāpēc nav tendenču, ko uzrādīt.').fadeIn();
        }else if ($('#no-trends').is(':visible')){
          $('#no-trends').fadeOut().html('');
        }
        
        $('span#ajax').html('');
        
      },
      
      error: function(data, status, error){
        $('span#ajax').html('');
        $('#no-trends').html('Neizdevās ielādēt tendences!').fadeIn();
      }
    });
  }
  
  updateTrends();
  
  setInterval(function(){
    updateTrends();
  },60000);
  
  if($.browser.mozilla || $.browser.safari){
    $("div.trend-list ul li.when").each(function(){
      $(this).css({'display': 'block', 'float': 'left', 'min-width': '70px'});
    });
  }
  
  $('#footer-clouds').css('height', ($('#footer').height() ? ($('#footer').height() + 10) + 'px' : ''));

});