$(document).ready(function() {
  worriedWords = [ 'worried', 'concerned', 'troubled', 'horrified', 'scared', 'panicked' ];
  
  $('#things-to-worry-about')
    .change(function() {
      if ($(this).val() !== 'Should I panic about ...') {
        $('#need-to-panic').fadeIn(300);
      } else {
        $('#need-to-panic').fadeOut(200);
      }
    });
  
  $('#need-to-panic')
    .click(function() {
      if (searchTerm !== 'Should I panic about ...') {
        $('#spinner').fadeIn(500);
        
        var searchTerm = $('#things-to-worry-about').val();
        var tpContainer = $('#these-people');
        var thesePeople = $('#messages');
        
        $('#status').fadeOut(200);
        tpContainer
          .fadeOut(200);

      
        var termForURL = ''
        $.each(searchTerm.split(','), function() {
          if (termForURL != '')
            termForURL += ' ';
            
          termForURL += '%22' + escape(this) + '%22';
        });
        
        var url = "http://search.twitter.com/search.json?q=%28panic+OR+worried+OR+concerned+OR+fear+OR+scare+OR+afraid+OR+worries+OR+scares+OR+%23isittimetopanic+%29+" + termForURL + "&rpp=10&callback=?";
        var firstTimeAgo = null;
        var lastTimeAgo = null;
        var results = 0;
        
        $.getJSON(url, function(json) {
          thesePeople.html('');
                  
          $.each(json.results, function(i, item) {
            results++;
            html = '<div class="tweet">' + '<img src="' + this.profile_image_url + '" />' + '<p><a href="http://twitter.com/' + this.from_user + '">' + this.from_user + '</a> <span class="worry">is ' + worriedWords[Math.floor(Math.random()*worriedWords.length)] + '!</span><br />' + this.text + '<span class="timeago">' + $.timeago(new Date(Date.parse(this.created_at))) + '</span></p></div>';
            
            if (firstTimeAgo == null) {
              firstTimeAgo = Date.parse(this.created_at);
            }
            
            lastTimeAgo = Date.parse(this.created_at);
            
            thesePeople
              .append(html);
          });
          
          $('#these-people span.timeago').timeago();
          
          $('#status').fadeIn(200);
          tpContainer.fadeIn(200);
          $('#spinner').fadeOut(200);
          
          var statusResult = '';
          if (results == 10 && (firstTimeAgo - lastTimeAgo <= 1800000)) {
            statusResult = 'YES!';
            $('#status-message').text('YES!');
          } else {
            statusResult = 'Meh';
            $('#status-message').text('Meh,');
          }
          
          $('#tweet-this').remove();
          $('#status')
            .append('<a id="tweet-this" href="http://twitter.com/home?status=' + escape('Panic about ' + searchTerm + '? Twitter says ' + statusResult + ' http://isittimetopanic.com') + '">Tweet This</a>');
        });
      }
    });
});
