function handleReportResponse(responseText) {
  var report = responseText.evalJSON();
  if(report.type) {
    switch(report.type) {
      case "SpamReport":
        r = $('new_spam_report');
        break;    
      case "AbuseReport":
        r = $('new_abuse_report');
        break;
      case "RickrollReport": 
        r = $('new_rickroll_report');
        break;
      default:
        alert("?");
    }
    var s = new Element('span',{ "class" : "thanks" }).update("Thanks, we've received your report and will be looking into things.");
    s.attr("id", "report_text");
    r.down().next().down().next().remove();
    r.down().next().insert(s);
  } else {
    alert("there was an error processing your request");
  }
}

function focusOnLinkInput() {
  if($('link_destination')) {
    $('link_destination').focus();
  }
}



function autolink(text) {
  array_of_text = text.split(/\s/);
  for(var i=0;i<array_of_text.length;i++) {
    word = array_of_text[i];
    if(word.match(/^(http|https)\:\/\//)) {
      if(word.length > 50) {
        word = '<a class="in_tweet_link" href="' + word + '" title="' + word + '">' + word.substring(0,25) + '...</a>';
      } else {
        word = '<a class="in_tweet_link" href="' + word + '">' + word + '</a>';
      }
      array_of_text[i] = word;
    } else if(word.match(/^\@/)) {
      word = '<a class="reply_tweet" href="http://twitter.com/' + word.replace(/\@/,'') + '">' + word + '</a>';
      array_of_text[i] = word;
    }
  }
  return array_of_text.join(" ");
}


function display_tweet(result, prepend, quickly) {
  var tweet_id_no_hash = "tweet_"+result.id;
  var tweet_id = "#" + tweet_id_no_hash;
  if(prepend) {
    $('<div></div>').html("").attr('id',tweet_id_no_hash).addClass("tweet").prependTo("#topical_tweets").hide();
  } else {
    $('<div></div>').html("").attr('id',tweet_id_no_hash).addClass("tweet").appendTo("#topical_tweets").hide();
  }
  $('<div></div>').html("").attr('id',tweet_id_no_hash+"_img").addClass('grid_1 alpha').appendTo(tweet_id);
  $('<div></div>').html("<span class=\"tweet_user\"><a href=\"http://twitter.com/"+result.from_user+"\">"+result.from_user+"</a></span>&nbsp;&mdash;&nbsp;"+autolink(result.text)+"<br /><span class=\"tweet_date\">"+display_date_and_time(result.created_at)+"</span>").addClass('grid_4 omega').appendTo(tweet_id);
  $('<a></a>').html("").attr('id',tweet_id_no_hash+"_img_a").attr('href',"http://twitter.com/"+result.from_user).attr('title',result.from_user).appendTo("#"+tweet_id_no_hash+"_img");
  $("<img/>").attr("src", result.profile_image_url).attr("height", "48").attr("width", "48").attr("alt", "").appendTo("#"+tweet_id_no_hash+"_img_a");
  $('<div></div>').html("").addClass("clear").appendTo(tweet_id);
  if(prepend) {
    $('<div></div>').html("").addClass("clear").prependTo("#topical_tweets");
  } else {
    $('<div></div>').html("").addClass("clear").appendTo("#topical_tweets");
  }
  if(quickly) {
    $(tweet_id).show();
  } else {
    $(tweet_id).slideDown(200, "easeOutQuint");
  }
}

function display_date_and_time(date_for_display) {
  return prettyDate(date_for_display);
}

function sort_tweets(tweets) {
  tweets.sort(sort_tweets_by_created_at);
}
function sort_tweets_by_created_at(a, b) {
  var x = a.created_at;
  var y = b.created_at;
  return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

function show_tweets(word_array) {
  tweets = [];
  max_id = 0;
  error_message_has_been_shown = false;
  twitter_domain = "http://search.twitter.com/search.json";
  callback_parameters = "&callback=?";
  english_only = "&lang=en";
  twitter_url = twitter_domain + "?show_user=false&q=" + word_array.join('+') + callback_parameters;  
  $.getJSON(twitter_url, function(data) {
    if(data.results.length > 0) {
      // $.jGrowl("Found " + data.results.length + " new Tweets. Automatically added them to the list.", { header: "New Tweets Found" }); 
      tweets = tweets.concat(data.results);
    } 
    twitter_url = twitter_domain + data.refresh_url + callback_parameters + english_only; // call this url next time for only new tweets
    max_id = data.max_id;
    sort_tweets(tweets);
  });
  var still_need_error_message = true;
  $.timer(5000, function(timer) {
    if(still_need_error_message) {
      $("#topical_tweets").html("<p></p>").html("Sorry, there are either no Tweets matching <strong>" + word_array.join(' ').replace(/pnt.me\//,'') + "</strong> (or Twitter is experiencing problems). We'll keep checking to see if anything new gets posted. In the meantime why not get the conversation started by <a href=\"http://twitter.com/home?status=http://" + word_array.join(' ') + "\">posting this link on Twitter</a> yourself?");
      error_message_has_been_shown = true;
    }
    timer.stop();
  });
  $.timer(20000, function (timer) {  
    $.getJSON(twitter_url, function(data) {
      twitter_url = twitter_domain + data.refresh_url + callback_parameters + english_only; // call this url next time for only new tweets
      if(data.max_id > max_id) {
        max_id = data.max_id;
        if(data.results.length > 0) {
          $.jGrowl("Found " + data.results.length + " new Tweets. Automatically added them to the list.", { header: "New Tweets Found" }); 
          tweets = tweets.concat(data.results);
        } 
      }
    });
    sort_tweets(tweets);
  });
  var first_time = true;
  $.timer(500, function(timer) {
    if(tweets.length > 0) {
      still_need_error_message = false;
      if(error_message_has_been_shown == true) {
        $("#topical_tweets").html("<p></p>");
        error_message_has_been_shown = false;
      }
      $('#loading_tweets').hide();  
      tweet_to_show = tweets.shift();
      display_tweet(tweet_to_show, true, false);
    }
    pruneOldTweets();
  });
}

function pruneOldTweets() {
  $(".tweet").each(
    function (i) {
      if(i > 50) {
        $(this).fadeOut(300, "easeOutQuint");
      }
    }
  ); 
}
 
/*
 * JavaScript Pretty Date
 * Copyright (c) 2008 John Resig (jquery.com)
 * Licensed under the MIT license.
 */

// Takes an ISO time and returns a string representing how
// long ago the date represents.
function prettyDate(time){
	var date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ")),
		diff = (((new Date()).getTime() - date.getTime()) / 1000),
		day_diff = Math.floor(diff / 86400);
			
	if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
		return;
			
	return day_diff == 0 && (
			diff < 60 && "just now" ||
			diff < 120 && "1 minute ago" ||
			diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
			diff < 7200 && "1 hour ago" ||
			diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
		day_diff == 1 && "Yesterday" ||
		day_diff < 7 && day_diff + " days ago" ||
		day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
}

// If jQuery is included in the page, adds a jQuery plugin to handle it as well
if ( typeof jQuery != "undefined" )
	jQuery.fn.prettyDate = function(){
		return this.each(function(){
			var date = prettyDate(this.title);
			if ( date )
				jQuery(this).text( date );
		});
	};

function showRequest(formData, jqForm, options) { 
  var queryString = $.param(formData); 
  var cur = $('#create_url_response');
  $('#create_url_response_container').css("marginTop", "11px");
  cur.html("");
  cur.removeClass("success");
  cur.removeClass("error");
  var i = document.createElement('img');
  i.src = "/images/ajax-loader.gif";
  i.alt = "please wait...";
  i.style.verticalAlign = "middle";
  var p = document.createElement('span');
  p.style.verticalAlign = "middle";
  p.style.marginLeft = "5px";
  p.style.color = "#ccc";
  p.innerHTML = "short'ng url...";
  cur.append(i).append(p);
  cur.slideDown("fast");
  return true; 
} 
 
function showResponse(responseText, statusText) {
  var link = responseText;
  var cur = $('#create_url_response');
  if(link.token) {
    $.timer(1000, function(timer) {
      timer.stop();
      cur.html("");
      var h = document.createElement('p');
      $(h).html("Your shortn'd link is ready");
      $(h).css("color","#777");
      var l = document.createElement('a');
      l.id = "new_shortnd_link";
      l.href = link.token;
      $(l).html(link.token);
      var p1 = document.createElement('p');
      p1.id = "new_url";
      $(p1).css("padding","0.5em 0");
      var a1 = document.createElement('a');
      a1.href = link.details;
      a1.id = "details_link";
      $(a1).addClass('small');
      $(a1).html("link details");
      var s = document.createElement('span');
      $(s).html("&middot;");
      var p2 = document.createElement('p');
      p2.id = "new_url_actions";
      var s = document.createElement('span');
      $(s).css("color", "#fff");
      $(s).css("display", "inline");
      $(s).css("marginLeft", "0.5em");
      $(s).css("verticalAlign", "middle");
      $(s).html(" &larr; copy this");
      $(p2).append(a1).append(s);
      cur.addClass('success');
      cur.removeClass('error');
      $(p1).append(l).append(s);
      cur.append(h);
      cur.append(p1);
      cur.append(p2);
      $('#create_url_response_container').css("marginTop", "-0.6em");
      $('#create_url_response_container').css("border", "2px solid #777");
    });
  } else {  
    cur.html("");
    cur.addClass('error');
    cur.removeClass('success');
    var h = document.createElement('p');
    if(link.errors.join(",").match(/Token has already/)) {
      $(h).html("<strong>Shoot!</strong> That token has already been taken, you'll have to pick another one.");
    } else if(link.errors.join(",").match(/too short/)) {
      $(h).html("<strong>Shoot!</strong> That token is too short, you'll have to pick another one. It has to be longer than 3 and shorter than 10 characters.");
    } else if(link.errors.join(",").match(/too long/)) {
      $(h).html("<strong>Shoot!</strong> That token is too long, you'll have to pick another one. It has to be longer than 3 and shorter than 10 characters.");
    } else {
      $(h).html("<strong>Gah!</strong> There was a problem. Though we tried, we couldn't short'n your link. Perhaps it's not a valid URL?");
    }
    cur.append(h);
    $('#create_url_response_container').css("marginTop", "11px");
    $('#create_url_response_container').css("border", "2px solid #ff0000");
  }
}

function toggleWithSlideDown(element_id) {
  if($(element_id).css('display') == "none") {
    $(element_id).slideDown();
    $(element_id + " input").focus();
  } else {
    $(element_id).slideUp();
    $(element_id + " input").attr("value","")
    $(element_id + " input").blur();
  }
  return false;
}



  
function newApikeyRequest(formData, jqForm, options) {
  var i = document.createElement('img');
  i.src = "/images/sm-ajax-loader.gif";
  i.alt = "please wait...";
  i.style.marginLeft = "10px";
  var current_apikey = $('#current_apikey');
  current_apikey.append(i);
}
function newApikeyResponse(responseText, statusText) {
  var current_apikey = $('#current_apikey');
  if(responseText.apikey) {
    current_apikey.html(responseText.apikey);
  } else {
    // error
  }
}
function newEmailRequest(formData, jqForm, options) {
  var i = document.createElement('img');
  i.src = "/images/sm-ajax-loader.gif";
  i.alt = "please wait...";
  i.style.marginLeft = "10px";
  var current_apikey = $('#current_api_email');
  current_apikey.append(i);
}
function newEmailResponse(responseText, statusText) {
  var current_apikey = $('#current_api_email');
  if(responseText.apikey) {
    current_apikey.html(responseText.api_email_address);
  } else {
    // error
  }
}

function deleteResponse(responseText, statusText) {
  if((responseText.success == true)||(responseText.success == "true")) {
    var i = new Image();
    i.src = "/images/action_delete.png";
    i.alt = "Your link has been deleted";
    $(i).css("verticalAlign", "middle");
    $('#hideme_' + responseText.id).parent().parent().addClass("done");
    $('#hideme_' + responseText.id).css("visibility", "visible");
    $('#hideme_' + responseText.id).html(i);
    $.jGrowl("Your link has been successfully deleted."); 
  } else {
    $.jGrowl("There was an error deleting your link."); 
  }
}






jQuery.fn.fadeToggle = function(speed, easing, callback) {
   return this.animate({opacity: 'toggle'}, speed, easing, callback);
}; 