/*
* tweetable 1.6 - jQuery twitter feed generator plugin
*
* Copyright (c) 2009 Philip Beel (http://www.theodin.co.uk/)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*
* With modifications from Philipp Robbel (http://www.robbel.com/) and Patrick DW (stackoverflow)
* for IE compatibility.
*
* And further modifications by engage interactive (with a little code borrowed from http://tweet.seaofclouds.com/ - Cheeers :D )
*
* Revision: $Id: jquery.tweetable.js 2011-01-06 $ 
*
*/

(function($){
	
	$.fn.twitterSelect = function() {
		
		//////////////////////////
		// GLOBAL VARIABLES

		var overlayHover = false;
		var linkHover = false;
		var visible = false;
		var timer;
		var locations = {};
		var userOffset = 0;
		
		//////////////////////////
		// GLOBAL OBJECTS

		var $html = $('html');
		var $twitterSelect;

		//////////////////////////
		// CREATE THE POPUP

		if(!$('#twitter_select').length && $('#twitter').length) {

			// Get locations
			$.getJSON('/locations/json', function(locations) {
				
				var html = '<ul>';
				
				for(var i in locations) {	
					if(locations[i].twitter != '') {
						html += '<li><a href="http://twitter.com/' + locations[i].twitter + '">' + locations[i].name + '</a></li>';
					}
				}
				
				html += '</ul>';
				
				// HTML
				$twitterSelect = $('<div/>', {
					'id':		'twitter_select',
					'html':		html
				});
				
				// Add to DOM
				$twitterSelect.appendTo('body').bind({
					'mouseenter':	function() {
						overlayHover = true;
					},
					'mouseleave':	function(){
						overlayHover = false;
						cleanUp();
					}
				});
				
			});
		
		}
		
		// Hide it
		var cleanUp = function() {
		
			timer = setTimeout(function() {
				
				if( !linkHover && !overlayHover ) {
				
					$twitterSelect.animate({
						'opacity': 0,
						'margin-top': userOffset
					}, 200, 'easeInOutExpo', function() {
						
						$twitterSelect.hide();
						visible = false;
						
					});
					
				}
				
			}, 300);
			
		}
		
		return this.each(function() {
			
			var $this = $(this);
			
			// Bind some events
			$this.bind({
				'mouseenter':	function(){
					
					// Set hover
					linkHover = true;
					
					// Clear any hide timers
					clearTimeout(timer);					
										
					//////////////////////////
					// POSITIONING
					
					var offset = $this.offset();
					var w = $this.width();
					var h = $this.outerHeight();
					
					// x & y
					var x = Math.round( offset.left + ( w / 2 ) ) - ( $twitterSelect.outerWidth(true) / 2 );
					var y = offset.top + h + userOffset;

					// Make sure we stay on the page
					if( x < userOffset ){
					
						x = userOffset;
					
					}else if( ( x + w + userOffset ) > $html.width() ){
						
						x = $html.width() - w - userOffset;
						
					}					
					
					// Are we visible? If not, we can set up for fresh animation
					if( !visible ){
					
						$twitterSelect.show().css({
							'opacity': 0,
							'margin-top': userOffset,
							'left': x,
							'top': y
						});
												
					}
					
					$twitterSelect.show().stop([]).animate({
						'opacity': 1,
						'left':	x,
						'top': y,
						'margin-top': 0
					}, 400, 'easeInOutExpo', function(){
						
						visible = true;
						
					});
				
				},
				'mouseleave':	function(){
					
					linkHover = false;
					
					cleanUp();
					
				},
				'click':		function(){
				
					return false;
					
				}
			});
						
		});
		
	}
	
	//define the tweetable plugin
	$.fn.tweet = function(options){

		//specify the plugins defauls
		var defaults = {
			limit:		10,					//number of tweets to show
			username:	'engagetweet',		//@username tweets to display
			type: 		'user',				//either user or list
			list: 		''					//name of the list if type == list
		};

		//overwrite the defaults
		var options = $.extend(defaults, options);
		
		//loop through each instance
		return this.each(function() {
		
			//assign our initial vars
			var $tweetList = $(this);
			var api = "http://api.twitter.com/1/";
			
			//if(options.type == 'list') api += "lists/statuses.json?slug=" + options.list + "&owner_screen_name=" + options.username;
			/*else*/ api += "statuses/user_timeline.json?screen_name=" + options.username;
			
			api += "&count=20&include_rts=1&callback=?";
			
			//do a JSON request to twitters API
			$.ajax({
				'url':			api,
				'dataType':		'json',
				'success':		function(data){
	
					var realLimit = 1;
					
					$tweetList.find('.loading').fadeOut(200,function(){
					
						$(this).remove();
					
						//loop through twitters response
						$.each(data,function(i, item){
							
		                    if( item.in_reply_to_status_id_str === null && realLimit <= options.limit ){
		                    
		                    	realLimit++;
		                    	
								$tweetList.append('<p title="' + relative_time(item.created_at) + '">' + item.text.replace(/#(.*?)(\s|$)/g, '<span class="hash">#$1 </span>').replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, '<a href="$&">$&</a> ').replace(/@(.*?)(\:|\s|\(|\)|$)/g, '<a href="http://twitter.com/$1">@$1</a>$2') + '</p>');
								
		                    }
		                    
						});
						
						$('#twitter div p:first').show().css({
							'top':		-38
						}).animate({
							'top':		0
						},400,'easeInOutExpo',function(){
							autoTweet();
						});
					
					});
				}

			});
			
			function autoTweet(){
				
				var t = $('#twitter p').size();
				var c = 1;
				var d = 4;
				var timer;
				var hover = false;
				
				$('#twitter').hover(function(){
					hover = true;
					clearTimeout(timer);
				},function(){
					hover = false;
					change();
				});
				
				function change(){
					
					c = c == t ? 1 : c + 1;
					
					timer = setTimeout(function(){
					
						clearTimeout(timer);
						
						if( !hover ){
						
							$('#twitter p:eq(' + ( c - 1 ) + ')').show().css({
								'top':	-38
							}).stop([]).animate({
								'top':	0
							},400,'easeInOutExpo').siblings('p').stop([]).animate({
								'top':	38
							},400,'easeInOutExpo',function(){
								$(this).hide();
							});
						
						}
						
						change();
						
					}, d * 1000);
					
				}
				
				change();
				
			}
			
		});
		
		function parse_date(date_str){
			// The non-search twitter APIs return inconsistently-formatted dates, which Date.parse
			// cannot handle in IE. We therefore perform the following transformation:
			// "Wed Apr 29 08:53:31 +0000 2009" => "Wed, Apr 29 2009 08:53:31 +0000"
			return Date.parse(date_str.replace(/^([a-z]{3})( [a-z]{3} \d\d?)(.*)( \d{4})$/i, '$1,$2$4$3'));
		}
		
		function relative_time(date){
		
			var date = parse_date(date);
		
			var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
			var delta = parseInt((relative_to.getTime() - date) / 1000, 10);
			var r = '';
			
			if (delta < 60) {
				r = delta + ' seconds ago';
			} else if(delta < 120) {
				r = 'a minute ago';
			} else if(delta < (45*60)) {
				r = (parseInt(delta / 60, 10)).toString() + ' minutes ago';
			} else if(delta < (2*60*60)) {
				r = 'an hour ago';
			} else if(delta < (24*60*60)) {
				r = '' + (parseInt(delta / 3600, 10)).toString() + ' hours ago';
			} else if(delta < (48*60*60)) {
				r = 'a day ago';
			} else {
				r = (parseInt(delta / 86400, 10)).toString() + ' days ago';
			}
			
			return 'about ' + r;
		}
		
	}

})(jQuery);
