var twitter_profile_widget = (function () {

	var config = {
		handles: [],
		pageSize: 5,
		rpp: 50,
		baseUrl: 'http://twitter.com/',
  		userTimlineApiMethod: "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=",
  		feeds: [],
  		autoStart: true
	};

	return {
		init: function (values) {
			for (var property in values)
				config[property] = values[property];

				if (config.autoStart) {
					if (config.handles.length > 0) {
						this.getFeed();
					}
				}
		},

		getFeed: function () {
			$.ajax({
				type: "GET",
				url: this.getUrl(),
				cache: true,
				async: true,
				dataType: 'jsonp',
				success: function (data) {
					twitter_profile_widget.render(data);
					// $('#twitter').MoreOrLess();
				}
			});
		},

	    getUrl: function () {
			var url = config.userTimlineApiMethod;
	
			for (var i = 0; i < config.handles.length; i++) {
				url = url + config.handles[i];
			}

			return url;
	    },

    	render: function (data) {
			var self = this,
					handle = '',
					template = '',
					profileImageUrl = '';

			for (var i=0; i < 8; i++) {
				var text = data[i].text,
					text = profile_widget_helpers._autoLinkText(text),
					text = profile_widget_helpers._autoLinkUsernames(text),
					text = profile_widget_helpers._autoLinkHashTags(text),
					date = profile_widget_helpers.twitterFormatDate(data[i].created_at),
					permalink = config.baseUrl + data[i].user.screen_name + '/status/' + data[i].id_str;

				handle = config.baseUrl + data[i].user.screen_name;
				profileImageUrl = data[i].user.profile_image_url;

				var created_at = '<div class="widget_item_actions"><a href="' + permalink + '" class="time" target="_blank">' + date + '</a></div>';
				var tweetHtml = '<p>' + text + '</p>';

				if (i > 2) {
					template += '<li class="more_item" style="display:none;">' + tweetHtml + created_at + '</li>';
				} else {
					template += '<li>' + tweetHtml + created_at + '</li>';
				}
			}

			$('#tweet_list').append(template);
			jq14('#twitter').MoreOrLess();
    	}
	}
})();

var profile_widget_helpers = {
	
	urlRegex: /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/,
	usernameRegex: /(@)(\w+)/g,
	hashTagRegex: /(#)(\w+)/g,
	
	/* Convert links to hyperlinked text
	   @param  text  (string) original plain text */
  	_autoLinkText: function(text) {
		if (this.urlRegex.test(text)) {
      		return text.replace(this.urlRegex, "<a href='$1'>$1</a>");
    	} else {
      		return text;
    	}
  	},

  	/* Convert twitter usernames to hyperlinked usernames
	   @param  text  (string) original plain text */
  	_autoLinkUsernames: function(text) {
    	if (this.usernameRegex.test(text)) {
      		return text.replace(this.usernameRegex, "<a href='http://twitter.com/#!/$2'>$1$2</a>");
    	} else {
      		return text;
    	}
  	},

	_autoLinkHashTags: function(text) {
		if (this.hashTagRegex.test(text)) {
			return text.replace(this.hashTagRegex, "<a href='http://twitter.com/#!/search?q=%23$2'>$1$2</a>");
		} else {
			return text;
		}
	},

	twitterFormatDate: function(dStr) {
		var date = dStr.split(' ');
			date = date[0] + ', ' + date[2] + ' ' + date[1] + ' ' + date[5] + ' ' + date[3] + ' ' + date[4];

    	return (this.formatDate(date));
	},
		
	formatDate: function (date) {
		var created = null;
  
		try {
			created = new Date(date);
		} catch (e) {
			return '';
   		}

		// today
		var today = new Date();

		// how much time since (ms)
		var duration = today.getTime() - created.getTime();

		var second = 1000;
		var minute = second * 60;
		var hour = minute * 60;
		var day = hour * 24;

		if (duration < second * 7) {
			return "right now";
		}

		if (duration < minute) {
     		var n = parseInt(Math.floor(duration / second));
     		return n + " seconds ago";
   		}

   		if (duration < minute * 2) {
     		return "about 1 minute ago";
   		}

   		if (duration < hour) {
     		var n = parseInt(Math.floor(duration / minute));
     		return n + " minutes ago";
   		}

   		if (duration < hour * 2) {
     		return "about 1 hour ago";
   		}

   		if (duration < day) {
     		var n = parseInt(Math.floor(duration / hour));
     		return n + " hours ago";
   		}

   		if (duration > day && duration < day * 2) {
     		return "yesterday";
   		}

   		if (duration < day * 365) {
     		var n = parseInt(Math.floor(duration / day));
     		return n + " days ago";
   		} else {
     		return "over a year ago";
   		}
	}
}
