Enjin_TwitterFeed = function(cfg) {
	Enjin_TwitterFeed.__instances[cfg.preset_id] = this;
	this.init(cfg);
}

Enjin_TwitterFeed.__preset_id = null;
Enjin_TwitterFeed.__instances = {};
Enjin_TwitterFeed.getInstance = function(preset_id) {	
	return Enjin_TwitterFeed.__instances[preset_id];
}

Enjin_TwitterFeed.TWITTER_FEED_URL = 'https://api.twitter.com/1/statuses/user_timeline.json?include_rts=1&callback=?';	
Enjin_TwitterFeed.TWITTER_USER_URL = 'https://api.twitter.com/1/users/show.json?callback=?';	


Enjin_TwitterFeed.prototype = {

	init: function(cfg) 
	{		
		$.extend(this, cfg);
		
		this.hide_paging  = (parseInt(this.hide_paging,10) == 1);
		this.page = 1;
		this.total = 0;
		this.total_pages = 1;
		
		this.el = $('.m_twitterfeed_' + this.preset_id);

		this.fetchUser();
	}	
	
	,prev: function()
	{
		this.page--;
		this.fetchFeed();
		return false;
	}
	
	,next: function()
	{
		this.page++;
		this.fetchFeed();
		return false;
	}

	,processUser: function(user)
	{
		var el = this.el.find('.header');
		
		el.find('.element_avatar img').attr('src', user.profile_image_url);	
		el.find('.user .screen_name a').text(user.screen_name);	
		el.find('.user .followers span').text(user.followers_count + '');
		
		//show header block, leave the loading animation so the items can load
		el.show();
			
		// now update counts and load the first feed	
		this.total = user.statuses_count; 
		this.total_pages = 	Math.ceil(this.total / this.tweets_per_page);
		this.fetchFeed();
	}
	
	,processFeed: function(feed)
	{
		var el = this.el;
		
		 // delete all exiting items , dont empty the container or you'll destory the template
		 el.find('.content .item').remove();
		
		// append the new tweets
		for ( var i = 0; i < feed.length; i++ )
		{
			var item = el.find('.item-template').clone();
			item.removeClass('item-template').addClass('item').attr('data-tweet', feed[i].id_str);
			item.find('.body').html( this.linkSearchRefs(this.linkScreenNames(this.linkURLs(feed[i].text))) );

			// reformat the time string into a format IE can understand, remove milliseconds,
			// and put the year before the time
			var dt = feed[i].created_at.split(' +0000 ');
			var time = new Date( dt[0].substr(0,dt[0].length-8) + dt[1] + ' ' + dt[0].substr(dt[0].length-8) );
			item.find('.detail .time').text( Date.getTimeDaysString(time.unixtime() - (time.getTimezoneOffset()*60)) );	
			
			el.find('.content').append(item);
		}
		
		// formatting for borders etc on final item
		el.find('.content .item:last').addClass('last');
		
		// update the paging
		if ( !this.hide_paging )
		{
			el.find('.footer .page').text('Page ' + this.page + ' of ' + this.total_pages);
			el.find('.footer .nav .prev').css({visibility: ( this.page > 1 ? 'visible' : 'hidden' )}); 
			el.find('.footer .nav .next').css({visibility: ( this.page < this.total_pages ? 'visible' : 'hidden' )}); 
			el.find('.footer').show();
		}	
		
		// hide the loading gif
		el.find('.content .loading').hide();
	}	
	
	/**
	 * Finds all twitter screen name references in the given text, identified as a @nnn teminated
	 * by a whitespace character, and alters then to be a hyperlink to the users page
	 */
	,linkScreenNames: function(text)
	{		
		return text.replace(/(@\w+)/g, '<a href="http://twitter.com/$1" target="_blank">$1</a>');
	}
	
	/**
	 * Attempt to make urls into hyperlinks in the text
	 */
	,linkURLs: function(text)
	{		
		return text.replace(/(http\:[^\s]*)/img, '<a href="$1" target="_blank">$1</a>');
	}	
	
	/**
	 * Attempt to link all #xxx reference in tweets to the search page in twitter
	 */
	,linkSearchRefs: function(text)
	{
		return text.replace(/(#\w+)/gm, '<a href="http://twitter.com/search?q=$1" target="_blank">$1</a>');
	}
	
	,fetchFeed: function()
	{
		// delete all exiting items , dont empty the container or you'll destory the template and loader
		this.el.find('.content .item').remove();	
		
		// show loading
		this.el.find('.content .loading').show();
		
		var self = this;
		$.getJSON( Enjin_TwitterFeed.TWITTER_FEED_URL, {screen_name:this.screen_name,page:this.page,count:this.tweets_per_page}, function(feed) { self.processFeed(feed); } );
	}
	
	,fetchUser: function()
	{
		var self = this;
		$.getJSON( Enjin_TwitterFeed.TWITTER_USER_URL, {screen_name:this.screen_name}, function(user) { self.processUser(user); } );
	}
	
	,follow: function()
	{
		this.openLink("https://twitter.com/intent/user?screen_name=" + this.screen_name);
		return false;
	}
	
	,viewProfile: function()
	{
		window.open("http://twitter.com/" + this.screen_name);
		return false;
	}
	
	,reply: function( tweet_id )
	{
		this.openLink("https://twitter.com/intent/tweet?in_reply_to=" + tweet_id);
		return false;
	}
	
	,retweet: function( tweet_id )
	{
		this.openLink("https://twitter.com/intent/retweet?tweet_id=" + tweet_id);
		return false;
	}
	
	,openLink: function( url )
	{	
		var width = 500;
		var height = 400;
		
	    var center_left = (screen.width / 2) - (width / 2);
	    var center_top = (screen.height / 2) - (height / 2);	
		var w = window.open(url,"module_twitterfeed","location=no,toolbar=no,width="+width+",height="+height+",left="+center_left+",top="+center_top);
		w.focus();
	}
}
