/*
JUITTER 0.9.2
14/02/2009
BY RODRIGO FANTE
http://rodrigofante.com

** jQuery 1.2.* or higher required
==> if you for any reason don't have it, download at http://jquery.com


Juitter is distributed under the MIT License
Read more about the MIT License --> http://www.opensource.org/licenses/mit-license.php

This script is just a beta test version, download and use it at your own risk.
The Juitter developer shall have no responsability for data loss or damage of any kind by using this script.



martin dudek: included the relative time functionality from http://tweet.seaofclouds.com/


*/

 function relative_time(time_value) {
      var parsed_date = Date.parse(time_value);
      var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
      var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
      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 1 hour ago';
      } else if(delta < (24*60*60)) {
      return 'about ' + (parseInt(0.5 + delta / 3600)).toString() + ' hours ago';
      } else if(delta < (48*60*60)) {
      return '1 day ago';
      } else {
      return (parseInt(delta / 86400)).toString() + ' days ago';
      }
    }

(function($) {
	var conf = {},
		// JUITTER STATIC CONFIGURATION ========================
		// YOU CAN CHANGE THE DYNAMIC VARS ON CALLING THE start and changeRequest METHODS, see the system.js for more information about it.
		
		username = "twopular", // will be used user if you don't give it when you start juitter and you are looking for tweets from or to a specific user
		word = "twopular" // will be user if you don't give it when you start juitter searching for a specific word
		contDiv = "juitterContainer", // Container div that will receive the list of tweets
		loadMSG = "Loading messages..."; // Loading message, if you want to show an image, fill it with "image/gif" and go to the next variable to set witch image want to use 
		gifName = "loader.gif"; // Loading image, to enable it go to the loadMSG var and change to "image/gif"
		numMSG = 20; // number of tweets to be shown - max 100
		readMore = "view tweet"; // read more message to be shown after the tweet content
		fromID = "image"; // insert "image" to show avatar of "text" to show the name of the user that sent the tweet 
		
		// END OF CONFIG
		// ======================================
		
		
		// DO NOT TOUCH BELOW HERE ==============
		
		// Twiiter API Urls
		apifUSER = "http://search.twitter.com/search.json?q=from%3A";
		apitUSER = "http://search.twitter.com/search.json?q=to%3A";
		apiSEARCH = "http://search.twitter.com/search.json?q=";
		
		// some global vars
		aURL="";
		ultID=0;
		msgNb = 1;
		
		mode = "",
		param = "",
		time = "",
		lang=""
		
	$.Juitter = {
		registerVar: function(localMode,localParam,localTimer,localLang) {
			mode = localMode;
			param = localParam;
			timer = localTimer;
			lang = localLang;			
		},
		start: function(options) {			
			if($("#"+contDiv)){	
				this.registerVar(options.searchType,options.searchObject,options.live,options.lang);
				// show the load message
				this.loading();
				// create the URL  to be request at the Twitter API
				aURL = this.createURL(mode,param);
				// query the twitter API and create the tweets list
				this.conectaTwitter(1);		
				// if live mode is enabled, schedule the next twitter API query
				if(timer!=undefined) this.temporizador();
			}   
		},
		update: function(){
			this.conectaTwitter(2);		
			if(timer!=undefined) this.temporizador();
		},
		changeRequest: function(options){
			// create the URL  to be request at the Twitter API
			$(".jLinks").removeClass("on");
			$("#"+options.elementId).addClass("on");
			// show the load message
			this.loading();
			this.registerVar(options.searchType,options.searchObject,options.live,options.lang);
			aURL = this.createURL(mode,param);
			// query the twitter API and create the tweets list
			this.conectaTwitter(1);		
		},
		loading: function(){
			if(loadMSG=="image/gif"){
				$("<img></img>")
					.attr('src', gifName)
					.appendTo("#"+contDiv); 
			} else {
				$("#"+contDiv).html(loadMSG);
			}		
		},
		createURL: function(mode,param){
			var url = "";
			if(lang!=undefined) jlg="&lang="+lang; else jlg=""; 
			if(mode=="fromUser"){
				if(param!=undefined) username = param;
				url = apifUSER+username;
			} else if(mode=="toUser"){
				if(param!=undefined) username = param;
				url = apitUSER+username;
			}else if(mode=="searchWord"){
				if(param!=undefined) word = param;
				url = apiSEARCH+word+jlg;
			}				
			url += "&rpp="+numMSG;
			return url;
		},
		delRegister: function(){
			// remove the oldest entry on the tweets list
			if(msgNb>=numMSG){
				$(".twittLI").each(
					function(o,elemLI){
						if(o>=numMSG){
							$(this).hide("slow");
						}							  
					}
				);
			}	
		},
		conectaTwitter: function(opt){
			// query the twitter api and create the tweets list
			
			$.ajax({
				url: aURL,
				type: 'GET',
				dataType: 'jsonp',
				timeout: 1000,
				error: function(){
					$("#"+contDiv).html("fail#");
				},
				success: function(json){
					if(opt==1){
						// first request
						$("#"+contDiv).html("");
						$("<ul></ul>")
							.attr('id', 'twittList')
							.appendTo("#"+contDiv);  
						$.each(json.results,function(i,item) {
							var date = '<a href="http://twitter.com/'+item.from_user+'/statuses/'+item.id+'" title="view tweet on twitter" target="_blank"><font color="#777777">'+relative_time(item.created_at)+'</font></a>&nbsp;&nbsp;';
							if(i==0) ultID = item.id;												 
							if(i<numMSG){
								if (item.text != "undefined") {
									var link =  "http://twitter.com/"+item.from_user+"/status/"+item.id;  
									if(fromID=="image"){
										$("<li></li>") 
											.html("<a target=\"_blank\" href='http://www.twitter.com/"+item.from_user+"'><img src='"+item.profile_image_url+"' alt='"+item.from_user+"' class='juitterAvatar' /></a> "+ date +$.Juitter.textFormat(item.text))  
											.attr('id', 'twittLI'+msgNb)
											.attr('class', 'twittLI')
											.appendTo("#twittList"); 	
									} else {
										$("<li></li>") 
											.html("<a href='http://www.twitter.com/"+ date +item.from_user+"'>@"+item.from_user+":</a> "+$.Juitter.textFormat(item.text))  
											.attr('id', 'twittLI'+msgNb)
											.attr('class', 'twittLI')
											.appendTo("#twittList"); 
									}
									msgNb++;
								}
							}
						});
					} else {
						// live mode
						$.each(json.results,function(i,item) {
							var date = '<a href="http://twitter.com/'+item.from_user+'/statuses/'+item.id+'" title="view tweet on twitter" target="_blank"><font color="#777777">'+relative_time(item.created_at)+'</font></a>&nbsp;&nbsp;';
							if(i<numMSG && item.id>ultID){
								if(i==0) ultID=item.id;
								if (item.text != "undefined") {
									var link =  "http://twitter.com/"+item.from_user+"/status/"+item.id;  
									
									if(fromID=="image"){
										$("<li></li>") 
											.html("<a target=\"_blank\" href='http://www.twitter.com/"+item.from_user+"'><img src='"+item.profile_image_url+"' alt='"+item.from_user+"' class='juitterAvatar' /></a> "+ date +$.Juitter.textFormat(item.text))  
											.attr('id', 'twittLI'+msgNb)
											.attr('class', 'twittLI')
											.prependTo("#twittList");
										$('#twittLI'+msgNb).hide();
										$('#twittLI'+msgNb).show("slow");
									} else {
										$("<li></li>") 
											.html("<a href='http://www.twitter.com/"+ date +item.from_user+"'>@"+item.from_user+":</a> "+$.Juitter.textFormat(item.text))  
											.attr('id', 'twittLI'+msgNb)
											.attr('class', 'twittLI')
											.prependTo("#twittList");
										$('#twittLI'+msgNb).hide();
										$('#twittLI'+msgNb).show("slow");
									}
									// remove old entries
									$.Juitter.delRegister();
									msgNb++;
								}
							}
						});
					}
				}
			});
		},		
		textFormat: function(texto){
			//make links
			var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
			texto = texto.replace(exp,"<a href='$1' class='extLink'>$1</a>"); 
			var exp = /[\@]+([A-Za-z0-9-_]+)/ig;
			texto = texto.replace(exp,"<a href='http://twitter.com/$1' class='profileLink'>@$1</a>"); 
			var exp = /[\#]+([A-Za-z0-9-_]+)/ig;
			texto = texto.replace(exp,"<a href='http://juitter.com/#$1' onclick='$.Juitter.changeRequest(\"searchWord\",\"$1\");return false;' class='hashLink'>#$1</a>"); 
			// make it bold
			if(mode=="searchWord"){
				regExp=eval('/ '+param+'/ig');
				newString = new String(' <b>'+param+'</b> ');
				texto = texto.replace(regExp, newString);
			}
			return texto;
		},
		temporizador: function(){
			// live mode timer
			
			aTim = timer.split("-");
			if(aTim[0]=="live" && aTim[1].length>0){
				tempo = aTim[1]*60000;
				setTimeout("$.Juitter.update()",tempo);
			}
		}
	};	
})(jQuery);
