/**
 * beta.juptr.js - Beta build twitter extension for jQuery.
 * @author Will Thomas
 * TODO
	- parameter to open links in new tabs
	- target elem without using ID
	- hide messages to: for user timelines
	- comment all code
 */

// format the text to make raw text links.
function twitterFormat(text) {
	var tweet = text.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g, function(url) {
		var wrap = document.createElement('div');
		var anch = document.createElement('a');
		anch.href = url;
		anch.target = "_blank";
		anch.innerHTML = url;
		wrap.appendChild(anch);
		return wrap.innerHTML;
	});
	tweet = tweet.replace(/(^|\s)@(\w+)/g, '$1@<a href="http://www.twitter.com/$2" target="_blank">$2</a>');
	return tweet.replace(/(^|\s)#(\w+)/g, '$1#<a href="http://search.twitter.com/search?q=%23$2" target="_blank">$2</a>');
}
//set date object as human readable.
function human_time_diff(from, to){
var since;
 if(!to)
   to = new Date();
 diff = Math.abs(to.getTime() / 1000 - from.getTime() / 1000);
 if(diff <= 3600) {
   var mins = Math.round(diff / 60);
   if(mins <= 1) {
     mins = 1;
   }
   since = mins + (mins > 1 ? " minutes" : " minute");
 } else if((diff <= 86400) && (diff > 3600)) {
   var hours = Math.round(diff / 3600);
   if(hours <= 1) {
     hours = 1;
   }
   since = hours + (hours > 1 ? " hours" : " hour");
 } else if(diff >= 86400) {
   var days = Math.round(diff / 86400);
   if(days <= 1) {
     days = 1;
   }
   since = days + (days > 1 ? " days" : " day");
 }
 return since;
}

jQuery.fn.juptr = function (settings) {
	
	//set default params. 
	settings = jQuery.extend({
				query: null,//Null query defaults to public timeline.
				count: 5,//Number of tweets to show defaults to 5.
				api: 'rest',//API will default to rest.
				date: true,//Date and time are shown by default.
				showName: true, //default always show author name.
				avatar: false,//User avatars are not shown by default.
				className: 'tweets-'//prepended to classes for unobtrusive markup i.e.(juptr-wrap).
				}, settings);
	//check api type.
	if (settings.api == 'search'){
		//Set search API. Build JSON URI. Encode query for safe use as URI and parse count as Int.
		var URI = 'http://search.twitter.com/search.json?q='+encodeURI(settings.query)+'&rpp='+parseInt(settings.count)+'&callback=?';
	} else {
		//invalid params deafault to rest API.
		if (settings.query){
			//take first word rom query to produce username.
			var getUser = settings.query.split(' ');
			//remove at symbol
			var user = getUser[0].replace(/@/,'');
			//produce query string and parse count as Int.
			var queryString = 'user_timeline.json?include_rts=1&screen_name='+user+'&count='+parseInt(settings.count)+'&callback=?';
		} else {
			//If query is not set default to public timeline.
			var queryString = 'public_timeline.json?'+parseInt(settings.count)+'&callback=?';
		}
		//set rest API. Build JSON URI.
		var URI = 'http://api.twitter.com/1/statuses/'+queryString;
	}
	var elem = $(this).attr('id');
	//start building the DOM using unobtrusive custom classes.
	var html = '<ul class="'+settings.className+'wrap">';
	//get JSON using our URI.
	console.log(URI);
	$.getJSON(URI, function(d){
		//sets results array as primary array, this merely allows us to use the same function for both API types as the search 'results' array is nested.
		if(d.results){
			d = d.results;
		}
		//run through each of the items returned, index by 'i'.
		$(d).each(function(i,item) {
			if (i >= settings.count){
				return false;
			}
			//define status content.
			var content = item.text;
			var date = item.created_at;
			var id = item.id_str;
			//check api as user data is handled in subarrays using rest api.
			if (settings.api == 'search'){	
				var screenName = item.from_user;
			} else {	
				if(item.retweeted_status){
					if (settings.showName){
						content = item.retweeted_status.text;	
					}	
					item = item.retweeted_status.user;
				} else {
					item = item.user;
				}
				var screenName = item.screen_name;
			}
			//linkify content using the twitterFormat function.
			var content = twitterFormat(content);
			//add usernames if set.
			if (settings.showName){
				var userName = '<h3 class="'+settings.className+'user"><a href="http://twitter.com/#!/'+screenName+'">'+screenName+'</a></h3>';		
				content = userName+content;		
			}
			//format and add the date if set.
			if(settings.date == true){
				//create human readable date using the human_time_diff function.
				var newDate = human_time_diff( new Date( date.replace(/^([^\-+]+) ([-+][0-9]{4}) (.+)$/g, '$1 $3 $2') ) );
				//build link for the DOM.
				var dateLink = '<a href="http://twitter.com/#!/'+screenName+'/status/'+id+'" class="'+settings.className+'date">'+newDate+' ago.</a>';
				content = content+dateLink;
			}
			//add avatars if set.
			if(settings.avatar){
				var userAvatar = '<a href="http://twitter.com/#!/'+screenName+'" class="'+settings.className+'avatar"><img src="'+item.profile_image_url+'" alt="'+screenName+'" title="'+screenName+'"/></a>';
				content = userAvatar+content;
			} 
			var getClasses = new Array();
			if (i % 2 === 0 ){
				getClasses.push(settings.className + 'odd');
			} 
			if (i == 0){
				getClasses.push(settings.className + 'top');
			}
			if (i == (parseInt(settings.count)-1)){
				getClasses.push(settings.className + 'bottom');
			}
			var setClasses = ' class="'+getClasses.join(' ')+'"';
			html+='<li'+setClasses+'>'+content+'</li>';
		});
		html+='</ul>';
		$('#'+elem).html(html);
	});	
}
