/*
 * jTwitter 1.1.1 - Twitter API abstraction plugin for jQuery
 *
 * Copyright (c) 2009 jQuery Howto
 *
 * Licensed under the GPL license:
 *   http://www.gnu.org/licenses/gpl.html
 *
 * URL:
 *   http://jquery-howto.blogspot.com
 *
 * Author URL:
 *   http://jquery-howto.blogspot.com
 *
 */
(function( $ ){
	$.extend( {
		jTwitter: function( username, numPosts, fnk ) {
			var info = {};
			
			// If no arguments are sent or only username is set
			if( username == 'undefined' || numPosts == 'undefined' ) {
				return;
			} else if( $.isFunction( numPosts ) ) {
				// If only username and callback function is set
				fnk = numPosts;
				numPosts = 5;
			}
			
			var url = "http://twitter.com/status/user_timeline/" + username + ".json?count="+numPosts+"&callback=?";
			//var url = "https://api.twitter.com/1/statuses/user_timeline.json?screen_name="+username+'&count='+numPosts;

			$.getJSON( 'twitproxy.php?wrapthis='+encodeURI(url), function( data ){
				if( $.isFunction( fnk ) ) {
					fnk.call( this, data );
				}
			});
		}
	});
})( jQuery );

var twTweetsObj = function(account, renderIntoContainer, firstRenderCallback){
	this.account = account;
	this.trackingName = 'tw';
	this.firstRenderCallback = firstRenderCallback;
	this.renderIntoContainer = renderIntoContainer;
		
	var config = {
		account: account
	};
	this.data = []
	this.current = 0;
	var self = this;
	this.hasresponse = false;
	this.tweetcallback = null;
	
	this.getTweets = function(callback){
		this.tweetcallback = callback;
		self.hasresponse = false;
		self.current = 0;
		self.tweets = [];
		$.jTwitter(config.account, 20, self._tweetDataCallback);
	};
	
	this._tweetDataCallback = function(data){
		self.data = data;
		//console.log('tw length: '+self.data.length);
		if(self.tweetcallback){
			self.tweetcallback(self);
		}
		self.hasresponse = true;
		sendLoadedTrackingEventIfLoaded(self.trackingName);
	}
	
	this.next = function(){
		if(self.data.length > self.current - 1){
			self.current++;
			return self.data[self.current];
		}
		return false;
	}
	
	this.rewind = function(){
		self.current = 0;
	}
}

var twTweetsTempl = function(){
	var self = this;
	
	this.toHTML = function(post){
		//get id for auth_image
		var ids = post.id_str;
		
		var link = "http://twitter.com/#!/" + post.user.screen_name;
		//get img_url
		var image_url = post.user.profile_image_url ;
		var tmp = new Date(post.created_at);	//is a date string
		var twTime = tmp.getTime();	//now is milliseconds
		var diff_message = postRelativeTimeString(twTime);
		var postAsHTML = parseHashtag(parseUsername(parseURL(post.text)));
		
		return	'<div id = "community_item">\
					<div id = "community_poster">\
						<div class = "username">\
							<a class="trackable" objType="communityStreamClick" nstrack-asset="twitter_profile_photo" href="' + link + '" style = "color: inherit;" target = "_blank">\
								<img class = "profile_photo" src = "' + image_url + '" />\
							</a>\
							<h2>\
								<a class="trackable" objType="communityStreamClick" nstrack-asset="twitter_user_name" href="' + link + '" style = "color: inherit;" target = "_blank">' +
									post.user.name + '\
								</a>\
							</h2>\
						</div>\
						<div class = "comm_message_body">\
							<p>' + postAsHTML + '</p>\
						</div>\
						<div id = "posted_on">\
							<div id = "social_icon" class = "twitter"></div>\
							Posted on Twitter ' + diff_message + '\
						</div>\
					</div>\
				</div>\
				<div class = "clear">&nbsp;</div>\
				<div class = "msgSep">&nbsp;</div>';
	}

	/*	Noah imported most of this code from WSD's Samsung community stream.
	 *	There's no reason for there to be three string replacement functions
	 *	here.  Someone should consolidate them.
	 */
	
	function parseURL(value) {
		return value.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&~\?\/.=]+/g, function(url) {
			var r = "<a objType='communityStreamClick' class='trackable' nstrack-asset='url."+url+"' href='"+url+"' target='_blank'>"+url+"</a>";
			return r;
		});
	}
	
	function parseUsername(value) {
		return value.replace(/[@]+[A-Za-z0-9-_]+/g, function(u) {
			var username = u.replace("@","")
			var r = "<a objType='communityStreamClick' class='trackable' nstrack-asset='url.http://twitter.com/"+username+"' href='http://twitter.com/"+username+"' target='_blank'>@"+username+"</a>";
			return r;
		});
	}
	
	function parseHashtag(value) {
		return value.replace(/[#]+[A-Za-z0-9-_]+/g, function(t) {
			var tag = t.replace("#","%23")
			var r = "<a objType='communityStreamClick' class='trackable' nstrack-asset='url.http://search.twitter.com/search?q="+tag+"' href='http://search.twitter.com/search?q="+tag+"' target='_blank'>"+t+"</a>";
			return r;
		});
	}
}


function renderTweets(twobj){
	$(twobj.renderIntoContainer).empty();
	var tobj = new twTweetsTempl();
	while(tweet = twobj.next()){
		var html = tobj.toHTML(tweet);
		$(twobj.renderIntoContainer).append(html);
	}
	
	twobj.firstRenderCallback(twobj.trackingName);
	twobj.rewind();
}
