var themes = {};

themes.init = function(query, first_time){
  if(first_time){
    $.overalls($('div#welcome_message_container').html(), {blank:true});

    $('div.welcome_message button').button().click(function(){
      jQuery.get('/themes/welcome_message');
      $.overalls.close();
      return false;
    });
  }

  $('a.show_help').click(function(){
    $('div#help').toggle('blind');
    return false;
  });

  $('a.hide_help').click(function(){
    $('div#help').hide('blind');
    return false;
  });

  //setup search form
  //make a nice looking search button
  $('input#search').button({icons: {primary:'ui-icon-search'}});

  //put the focus on the query form input
  $('input#q').select().focus();

  //if query came in from the url, go make themes with it
  if(query){
    themes.get_themes({query: query});
  }

  $('.pagination a').live('click', function() {
    var data = $.deparam.querystring($(this).attr('href'));
    $.ajax({
      url: $(this).attr('href'),
      type: 'GET',
      dataType: 'html',
      beforeSend:function(){
       $('div#messages').fadeOut(600, function(){
          $(this).html('');
          $('div#message_loader').fadeIn();
        });
      },
      success: function(html){
        themes.show_messages(html);
      },
      error: function(){}
    });
    return false;
  });

};

themes.get_themes = function(data){

  if(themes.pending_request){
    themes.pending_request.abort();
    themes.pending_request = null;
  }

  if(themes.could_take_a_while){
    clearTimeout(themes.could_take_a_while);
    themes.could_take_a_while = null;
  }

  themes.pending_request = $.ajax({
    url: '/themes/themes',
    type: 'GET',
    data: data,
    dataType: 'json',

    beforeSend: function(){
      $('form#keyword_query').find('div.spinner').show();
      $('div#ajax_error').fadeOut();
      $('div#theme_graph:visible').hide('blind',600);
      $('input#search').button('disable');
      $('div#messages:visible').fadeOut(600);
      $('div#messages_found').hide('blind',600);
      themes.could_take_a_while = setTimeout(function(){
        $('div.could_take_a_while').fadeIn();
      }, 5000);
    },

    complete: function() {
      clearTimeout(themes.could_take_a_while);
      themes.could_take_a_while = null;
      $('div.could_take_a_while:visible').hide();

      $('input#search').button('enable');
      $('form#keyword_query').find('div.spinner').hide();
    },

    success: function(data){
      if(data){
        if(themes.paper && themes.paper.remove){
          themes.paper.remove();
        }
        themes.graph(data);
      }
    },

    error: function(){
      $('div#ajax_error').remove();
      $('form#keyword_query').append("<div id='ajax_error' style='display:none;'>we've encountered an error processing your request. please try again.</div>");
      $('div#ajax_error').fadeIn(600);
    }
   });
};

themes.graph = function (data, paper){
  themes.data = data.themes;
  if(data.themes.themes.length > 0){
    $('div#theme_graph').show('blind',600);
    themes.paper = Raphael('theme_graph', $('div#theme_graph').width(), $('div#theme_graph').height());
    data.paper_height = $('div#theme_graph').innerHeight();
    data.paper_width = $('div#theme_graph').innerWidth();
    themes.bubbles = themes.paper.bubbleGraph(data.themes.themes, {height: data.paper_height, width: data.paper_width, label_length: 20,
      hover: [themes.mouse_in(), themes.mouse_out() ],
      click: function(e, point){
        themes.current_point = point;
        if (themes.messages_loading_ajax){
          themes.messages_loading_ajax.abort();
        }
        $.each(themes.bubbles.series, function(index, p) {
          if(p.circle.attr('stroke-width')>3){
            p.circle.animate({'stroke-width': 3,'stroke': themes.bubbles.border_color},550, ">");
          }
        });
        point.circle.animate({'stroke-width': 5,'stroke': '#313131'},550, ">");

        themes.messages_loading_ajax = $.ajax({
          url: '/themes/' + point.theme_id,
          type: 'GET',
          data: {query: data.query},
          dataType: 'html',
          beforeSend:function(){
            $('div#messages').fadeOut(600, function(){
              $(this).html('');
              $('div#message_loader').fadeIn();
              $('div#message_load_error').fadeOut();
            });
          },
          success: function(html){
            themes.show_messages(html);
          },
          error: function(){
            $('div#message_loader').fadeOut();
            $('div#message_load_error').fadeIn();
          }
        });
      }
    });
    if(data.twitter_handle){
      $('div#messages_found').html('<h4>Clustered sample of ' + data.themes.messages_found + ' posts from ' + data.twitter_handle + ' for the last 6 months.</h4>').show();
    }
    else{
      $('div#messages_found').html('<h4>Clustered sample of ' + data.themes.messages_found + ' matching posts from the past 30 days.</h4>').show();
    }
  }
  else { // no themes returned
    var message = '';
    if(data.twitter_handle){
      message = "<h4> Hmmm, we don't seem to have enough data on " + data.twitter_handle + ' <p> Maybe try a different twitter name?</p></h4>';
    }
    else{
      message = '<h4 class="no_data">Well shoot, it looks like we don\'t have enough data to do our fancy clustering.<p> Maybe try a more general query?</p></h4>';
    }
    $('div#messages_found').html(message).show('blind',600);
  }
};

themes.show_messages = function(html){
  $('div#messages').stop(true, true).html(html);

  $('span.view_full_message').button({icons: {primary:'ui-icon-plus'}}).live('click', function(){
    var $msg = $(this).closest('div.message');
    $msg.find('div.truncated_body').hide();
    $msg.find('div.message_body').show();
    $msg.find('span.view_full_message, span.hide_full_message').toggle();
    return false;
  });

  $('span.hide_full_message').button({icons: {primary:'ui-icon-minus'}}).live('click', function(){
    var $msg = $(this).closest('div.message');
    $msg.find('div.truncated_body').show();
    $msg.find('div.message_body').hide();
    $msg.find('span.view_full_message, span.hide_full_message').toggle();
    $.scrollOut('#' + $msg.attr('id'));
    $msg.find('div.top_bar').delay(850).effect("highlight", {color: '#6CE0FA'}, 1000);
    return false;
  });

  $('div#messages_header').find('a.help').live('click', function(){
    $.overalls($('div#terms_not_in_posts').html(), {blank:true});
    return false;
  });

  $('div#message_loader').stop(true, true).fadeOut(600, function(){
    $('div#messages').fadeIn(600, function(){
      $.scrollOut('#messages');
      log('messages', themes)
      $('div.message').highlight(themes.current_point.terms, {className: 'highlight_term',wordsOnly: true, caseSensitive: false});
    });
  });

};

themes.show_tip = function ( e, theme, timeout ){
  themes.tip = $.tipTipLite(theme.size + ' posts<br>' + theme.terms.join("<br/>"), {mouse_event: e});
};

themes.hide_tip = function (theme){
  $.tipTipLite.hide();
};

themes.mouse_in = function (){
  return function(e, point, series, bubbles){
    if(point.circle.attr('r') < point.z+10){
      point.circle.animate({r: point.circle.attr('r')+10 }, 250, ">");
    }
    $.each(series, function(index, p) {
      if(p!=point){
        p.text_label.animate({opacity: 0.1},250, ">");
        p.label_line.animate({'stroke-width': 0},250, ">");
      }
    });
    setTimeout(function(){
      point.text_label.attr({'fill':bubbles.border_color});
      point.label_line.attr({opacity:1, stroke: bubbles.border_color}).toFront();
      point.text_label.toFront();
    },200);
    themes.show_tip(e, point, 200);
  };
};

themes.mouse_out = function (){
  return function(e, point, series, bubbles){
    point.circle.animate({r: point.z}, 250, "<");
    $.each(series, function(index, p) {
      if(p!=point){
        p.text_label.animate({opacity:1.0, fill: bubbles.font_color || p.color},250, "<");
        p.label_line.animate({'stroke-width': 1, stroke: bubbles.font_color || p.color},250, "<");
      }
    });
      point.text_label.attr({opacity:1.0, fill: bubbles.font_color || point.color});
      point.label_line.attr({opacity: 0.5, stroke: bubbles.font_color || point.color});
      themes.hide_tip(point);
  };
};

