(function($) {

	var elements = null;

	var rpp = 100;
	var hashtag = "";
	var maxId = 0;

	$.fn.reload = function(options) {
		elements.empty();
		maxId = 0;
		return $(this).getTweet(options);
	};

	$.fn.getTweet = function(options) {

		if (elements == null) {
			elements = this;
		}
		function initialize(){
			$.ajax({
				url:"../skinoption.xml",
				dataType:"xml",
				success:skinoptionSuccess,
				error:skinoptionError
			})
			
		}
		function skinoptionSuccess(xml){
				var skinoptionHashtags = $(xml).find("twitter").attr("tags");
				if(twitter_hashtag.length>0){
					hashtag = twitter_hashtag;
				}else{
					var splitedtags = skinoptionHashtags.split(",");
					if(splitedtags.length>1){
						hashtag = splitedtags[0];
						for(i = 1;i<splitedtags.length;i++){
							hashtag += "%20%23" + splitedtags[i];
						}
					}else{
						hashtag = skinoptionHashtags;
					}
				}
				disp()
			}
			function skinoptionError(){
				hashtag = twitter_hashtag;
				disp();
			}
		
		function disp() {

			var url = "http://search.twitter.com/search.json?q=%23"+hashtag+"&rpp="+rpp+"&since_id="+maxId+"&callback=?";

			$.getJSON(url, function(json) {
				var len = $(json.results).length;
				var i = 1;

				var result = xsort($(json.results), "id", 1);
				
				result.each(function() {
				
					var urlLinkText = createURLLink(this.text);
					var linkText = createTwitterLink(urlLinkText);
					
					var value = '<div class="childTwitter" id="twitone">';
					value += '<img width="50" height="50" class="childTwitter-img" src="'+this.profile_image_url+'">';
					value += '<div class="childtwit">';
					value += '<strong><a href="http://twitter.com/'+this.from_user+'" target="blank">';
					value += this.from_user;
					value += '</a></strong>';
					value += '<span class="childTwitterText">'+' '+urlLinkText+'</span>';
					value +='<div class="list-twit-status">'+relativeTime(this.created_at)+'</div>';
					value += '</div></div>';


					
					
					elements.prepend(value);
					
					
					i++;
				});

				$(json).each(function() {
					maxId = this.max_id;
				});
			});

		}

		function createURLLink(value) {
			var result = value.match(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%#;&\?\/.=]+/);
			if (result == null || result[0] == null) {
				return value;
			}
			
			var lwurl = result[0].match(/http:\/\/sc.logosware.com\/(.+)/);
			if (lwurl == null || lwurl[1] == null) {
				value = value.replace(/([A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%#;&\?\/.=]+)/g, '<a href="javascript:window.open(\'$1\');void(0);">$1</a>');
				return value;
			}
			
			value = value.replace(/([A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%#;&\?\/.=]+)/g, '<a class="flipperLink" href="javascript:void(0);" params="'+lwurl[1]+'">$1</a>');
			return value;
		}

		function createTwitterLink(value) {
			value = value.replace("[%23]","#");
			value = value.replace(/( )(@)([A-Za-z0-9-_]+)( |:)/g, ' <a href="http://twitter.com/$3" target="_blank">$2$3</a>$4');
			value = value.replace(/( )(#)([A-Za-z0-9-_]+)$/, ' <b><a href="http://twitter.com/#search?q=%23$3" target="_blank">$2$3</a></b> ');
			return value;
		}
		
		function relativeTime(value) {

			timeValues = value.split(" ");
			timeValue = timeValues[2] + " " + timeValues[1] + ", " + timeValues[3] + " " + timeValues[4] + " UTC+0000";

			var parsedDate = Date.parse(timeValue);
			var relativeTo = (arguments.length > 1) ? arguments[1] : new Date();
			var delta = parseInt((relativeTo.getTime() - parsedDate) / 1000);
			delta = delta + (relativeTo.getTimezoneOffset() * 60);

			if(delta < 60) {
				return "less than a minute ago";
			} else if(delta < 120) {
				return "about a minute ago";
			} else if(delta < (45*60)) {
				return (parseInt(delta / 60)).toString() + " minutes ago";
			} else if(delta < (90*60)) {
				return "about an hour ago";
			} else if(delta < (24*60*60)) {
				return "about " + (parseInt(delta / 3600)).toString() + " hours ago";
			} else if(delta < (48*60*60)) {
				return "1 day ago";
			} else {
				return (parseInt(delta / 86400)).toString() + " days ago";
			}
		}

		$("a.flipperLink").live("click", function(){

			var params = $(this).attr("params");
		
			var url = "http://sc.logosware.com/api/getLongURL.php?type=JSON&target="+params+"&callback=?";
		
			$.getJSON(url, function(json) {
				var longUrl = json.result;
				var parentParams = longUrl.match(/index.html#page=(.+)$/);
				if (parentParams == null || parentParams[1] == null) {
					return null;
				}
				parent.location.href = "../index.html#page=" + parentParams[1];
			});
			return false;
		});

		elements.each(function() {
			initialize();
		});

		return this;
	};
	function xsort(value, col, order)
	{
		value.sort(function(a, b) {
			return((a[col] - b[col]) * order);
		});
		return(value);
	}
})(jQuery);