/*Copyright © 2010 
*
*Licensed under the GPL license:
*   http://www.gnu.org/licenses/gpl.html
*
*URL:
*   http://midnightprogrammer.net
*
*Author:
*   Prashant Khandelwal
*
*/

function GetLastTweet(UserName) {
    url = 'http://api.twitter.com/1/statuses/user_timeline/' + UserName + '.json?callback=?';
    $.getJSON(url, function (tweet) {
        $("#tweet").html(tweet[0].text);
    });
}

function GetTweets(UserName, NoOfTweets) {
    url = 'http://api.twitter.com/1/statuses/user_timeline/' + UserName + '.json?callback=?';
    $.getJSON(url, function (tweets) {

	var myclass  = "first";

        for (var i = 0; i < NoOfTweets; i++) {
            
		$("#tweet").append("<li class=" + myclass + "><h3>" + relativeTime(tweets[i].created_at)+"</h3><p>" + formatTwitString(tweets[i].text) + "</p><li/>");
		myclass  = "";
        }
    });
}

function GetProfileImage(UserName) {
    url = 'http://api.twitter.com/1/statuses/user_timeline/' + UserName + '.json?callback=?';
    $.getJSON(url, function (image) {
        $("#ProfileImage").attr('src', image[0].user.profile_image_url);
    });
}

function relativeTime(pastTime)
{	
	var origStamp = Date.parse(pastTime);
	var curDate = new Date();
	var currentStamp = curDate.getTime();
	
	var difference = parseInt((currentStamp - origStamp)/1000);

	if(difference < 0) return false;

	if(difference <= 5)				return "Just now";
	if(difference <= 20)			return "Seconds ago";
	if(difference <= 60)			return "A minute ago";
	if(difference < 3600)			return parseInt(difference/60)+" minutes ago";
	if(difference <= 1.5*3600) 		return "One hour ago";
	if(difference < 23.5*3600)		return Math.round(difference/3600)+" hours ago";
	if(difference < 1.5*24*3600)	return "One day ago";
	
	var dateArr = pastTime.split(' ');
	//return dateArr[4].replace(/\:\d+$/,'')+' '+dateArr[2]+' '+dateArr[1]+(dateArr[3]!=curDate.getFullYear()?' '+dateArr[3]:'');
	return dateArr[2]+' '+dateArr[1]+(dateArr[3]!=curDate.getFullYear()?' '+dateArr[3]:'');

}

function formatTwitString(str)
{
	str=' '+str;
	str = str.replace(/((ftp|https?):\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?)/gm,'<a href="$1" target="_blank">$1</a>');
	str = str.replace(/([^\w])\@([\w\-]+)/gm,'$1@<a href="http://twitter.com/$2" target="_blank">$2</a>');
	str = str.replace(/([^\w])\#([\w\-]+)/gm,'$1<a href="http://twitter.com/search?q=%23$2" target="_blank">#$2</a>');
	return str;
}
