// Constants
var RATE_LIMIT = 0;

;(function($) {
 
/* 

 tweet
 ---------
 Collects favorites for a twitter user and puts them into an element on your page, it checks the rate limit
 and will pull from a faves.json file as a cache if you're over your limit.
 
 Options:
 
 * user: twitter user you need to get favorites for (default: crashplan)
 * count: number of favorites to pull (default: 12)
 
 Example:
 
  $('#an-element').tweet();
 
*/

// Dependent on jquery.cookie.js
$.fn.tweet = function(options) {
	var opts = $.extend({}, $.fn.tweet.defaults, options);

	var LOCAL_CACHE = "shared/js/faves.json";
	var FAVE_URL = "https://api.twitter.com/1/favorites.json?callback=?&screen_name=" + opts.user + "&count=" + opts.count;
	var RATE_LIMIT_URL = "https://api.twitter.com/1/account/rate_limit_status.json?callback=?&screen_name=" + opts.user;

	return this.each(function() {
		var $this = $(this);
		$.getJSON(RATE_LIMIT_URL, function(json, textStatus) {
			RATE_LIMIT = json.remaining_hits;
			// will pull from a local json file if we get close to our rate limit
			var tweetUrl = RATE_LIMIT <= 120 ? LOCAL_CACHE : FAVE_URL;
			// Get the initial tweet from the cache as a random tweet, keeping it fresh
			$.getJSON(LOCAL_CACHE, function(json, textStatus) {
				var tweet = json[(json.length-1).randomize()];
				$this.hide();
				// debug("Load initial cache tweet")
				displayTweet($this, tweet);
			});
			$.getJSON(tweetUrl, function(json, textStatus) {
				var tweets = json;
				displayTweet($this, tweets[(tweets.length-1).randomize()]);
				setInterval(function() {
					var tweet = tweets[(tweets.length-1).randomize()];
					// debug("Loading real tweets")
					displayTweet($this, tweet);
				}, 10000);
			});
		});
	});
 
	function displayTweet (elem, tweet) {
		var tweetLink = '"'+'<a href="http://twitter.com/'+tweet.user.screen_name+'/statuses/'+tweet.id_str+'" target="_blank">'+tweet.text+'</a>'+'"';

		$(".tweet-text").html(tweetLink);
		$(".author").html("- "+tweet.user.screen_name+' via twitter');

		$(elem).fadeIn('fast');
	}
 
	// private function for debugging
	function debug($obj) {
		if (window.console && window.console.log) {
		  window.console.log($obj);
		}
	}
 
};

// default options
$.fn.tweet.defaults = {
	user: 'crashplan',
	count: 12
};

})(jQuery);

// Select a random number from a range
// Ex : (5).randomize() #
Number.prototype.randomize = function() {
	return Math.floor(Math.random()*this);
};


