/*
JUITTER 1.0.0 - 22/07/2009 - http://juitter.com
BY RODRIGO FANTE - http://rodrigofante.com

** jQuery 1.2.* or higher required

JuitterTM 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 JuitterTM developer shall have no responsability for data loss or damage of any kind by using this script.
*/
(function($) {
	var confTM = {},
		// JUITTER DEFAULT CONFIGURATION ========================
		// YOU CAN CHANGE THE DYNAMIC VARS ON CALLING THE starttm method, see the system.js for more information about it.

		numMSGTM = 20; // set the number of messages to be show
		containerDivTM="juitterContainer", // //Set a place holder DIV which will receive the list of tweets example <div id="juitterContainer"></div>
		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 which image you want to use on 
		imgName="loader.gif", // Loading image, to enable it, go to the loadMSG var above and change it to "image/gif"
		readMore="Read it on Twitter", // read more message to be show after the tweet content
		nameUser="image" // insert "image" to show avatar of "text" to show the name of the user that sent the tweet 
		liveTM:"liveTM-20", //optional, disabled by default, the number after "liveTM-" indicates the time in seconds to wait before request the Twitter API for updates, I do not recommend to use less than 60 seconds.
		// end of configuration
	
		// some global vars
		aURLTM="";msgNbTM=1;
		var mode,param,time,lang,contDivTM,loadMSG,gifName,numMSGTM,readMore,fromIDTM,ultID,filterWords;
		var runningTM=false;
		// Twitter API Urls
		apifMultipleUSER = "http://search.twitter.com/search.json?from%3A";
		apifUSER = "http://search.twitter.com/search.json?q=from%3A";
		apitMultipleUSER = "http://search.twitter.com/search.json?to%3A";
		apitUSER = "http://search.twitter.com/search.json?q=to%3A";
		apiSEARCH = "http://search.twitter.com/search.json?q=";
	$.JuitterTM = {
		registerVarTM: function(opt){
			mode=opt.searchType;
			param=opt.searchObjectTM;
			timerTM=opt.liveTM;
			lang=opt.lang?opt.lang:"";
			contDivTM=opt.placeHolderTM?opt.placeHolderTM:containerDivTM;
			loadMSG=opt.loadMSG?opt.loadMSG:loadMSG;
			gifName=opt.imgName?opt.imgName:imgName;
			numMSGTM=opt.total?opt.total:numMSGTM;
			readMore=opt.readMore?opt.readMore:readMore;
			fromIDTM=opt.nameUser?opt.nameUser:nameUser;
			filterWords=opt.filter;
			openLink=opt.openExternalLinks?"target='_blank'":"";
		},
		starttm: function(opt) {		
			ultID='TM';
			if($("#"+contDivTM)){	
				this.registerVarTM(opt);
				// show the load message
				this.loadingTM();
				// create the URL  to be request at the Twitter API
				aURLTM = this.createURLTM();
				// query the twitter API and create the tweets list
				this.conectaTwitterTM(1);		
				// if liveTM mode is enabled, schedule the next twitter API query
				if(timerTM!=undefined&&!runningTM) this.temporizadortm();
			}   
		},
		updateTM: function(){
			this.conectaTwitterTM(2);		
			if(timerTM!=undefined) this.temporizadortm();
		},
		loadingTM: function(){
			if(loadMSG=="image/gif"){
				$("<img></img>")
					.attr('src', gifName)
					.appendTo("#"+contDivTM); 
			} else $("#"+contDivTM).html(loadMSG);
		},
		createURLTM: function(){
			var url = "";
			jlg=lang.length>0?"&lang="+lang:jlg=""; 
			var seachMult = param.search(/,/);
			if(seachMult>0) param = "&ors="+param.replace(/,/g,"+");
			if(mode=="fromUser" && seachMult<=0) url=apifUSER+param;
			else if(mode=="fromUser" && seachMult>=0) url=apifMultipleUSER+param;
			else if(mode=="toUser" && seachMult<=0) url=apitUSER+param;
			else if(mode=="toUser" && seachMult>=0) url=apitMultipleUSER+param;
			else if(mode=="searchWord") url=apiSEARCH+param+jlg;
			url += "&rpp="+numMSGTM;		
			return url;
		},
		delRegister: function(){
			// remove the oldest entry on the tweets list
			if(msgNbTM>=numMSGTM){
				$(".twittLITM").each(
					function(o,elemLI){
						if(o>=numMSGTM) $(this).hide("slow");													  
					}
				);
			}	
		},
		conectaTwitterTM: function(e){
			// query the twitter api and create the tweets list
			$.ajax({
				url: aURLTM,
				type: 'GET',
				dataType: 'jsonp',
				timeout: 1000,
				error: function(){ $("#"+contDivTM).html("fail#"); },
				success: function(json){
					if(e==1) $("#"+contDivTM).html("");				
					$.each(json.results,function(i,itemTM) {
						if(e==1 || (i<numMSGTM && itemTM.id>ultID)){
							if(i==0){
								tultIDTM = itemTM.id;
								$("<ul></ul>")
									.attr('id', 'twittList'+ultID)
									.attr('class','twittList')
									.prependTo("#"+contDivTM);  
							}
							if (itemTM.text != "undefined") {
								var linkTM =  "http://twitter.com/"+itemTM.from_user+"/status/"+itemTM.id;  
								
								var tweet = $.JuitterTM.filter(itemTM.text);
								var current_date = new Date(); 
								var tweet_date = new Date(itemTM.created_at); 
								var months = new Array("Styczeń","Luty","Marzec","Kwiecień","Maj","Czerwiec","Lipiec","Sierpień","Wrzesień","Październik","Listopad","Grudzień");
								var days = new Array("niedziela","poniedziałek","wtorek","środa","czwartek","piątek","sobota");
								var tweet_day = tweet_date.getDate();
								var tweet_weekday = tweet_date.getDay();
								var tweet_mon = tweet_date.getMonth();
								var tweet_month = months[tweet_mon];
								var tweet_year = tweet_date.getFullYear();
								var tweet_hours = tweet_date.getHours();
								var tweet_minutes = tweet_date.getMinutes();
								if (tweet_hours < 10) { tweet_hours = "0" + tweet_hours; }
								if (tweet_minutes < 10) { tweet_minutes = "0" + tweet_minutes; }

								if(fromIDTM=="image") tmHTML="<a href='http://www.twitter.com/"+itemTM.from_user+"' class='author'><img src='"+itemTM.profile_image_url+"' alt='"+itemTM.from_user+"' class='juitterAvatar' /></a> "+$.JuitterTM.textFormat(tweet)+" <span class='time'>"+(tweet_date)+"</span>";
								else tmHTML=$.JuitterTM.textFormat(tweet)+" <span class='time'>"+days[tweet_weekday]+", "+tweet_day+" "+tweet_month+", "+tweet_year+", "+tweet_hours+":"+tweet_minutes+"</span>";
								
								$("<li></li>") 
									.html(tmHTML)  
									.attr('id', 'twittLITM'+msgNbTM)	
									.attr('class', 'twittLITM')
									.appendTo("#twittList"+ultID);

								$('#twittLITM'+msgNbTM).hide();
								$('#twittLITM'+msgNbTM).show("slow");
								
								// remove old entries
								$.JuitterTM.delRegister();
								msgNbTM++;								
							}
						}
					});	
					ultID=tultIDTM;
				}
			});
		},	
		filter: function(s){
			if(filterWords){
				searchWords = filterWords.split(",");				
				if(searchWords.length>0){
					cleanHTML=s;
					$.each(searchWords,function(i,itemTM){	
						sW = itemTM.split("->").length>0 ? itemTM.split("->")[0] : itemTM;
						rW = itemTM.split("->").length>0 ? itemTM.split("->")[1] : "";					
						regExp=eval('/'+sW+'/gi');					
						cleanHTML = cleanHTML.replace(regExp, rW);							
					});
				} else cleanHTML = s;			
				return cleanHTML;
			} else return s;
		},
		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' "+openLink+">$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='$.JuitterTM.starttm({searchType:\"searchWord\",searchObjectTM:\"$1\"});return false;' class='hashLink'>#$1</a>"); 
			// make it bold
			if(mode=="searchWord"){
				tempParam = param.replace(/&ors=/,"");
				arrParam = tempParam.split("+");
				$.each(arrParam,function(i,itemTM){					
					regExp=eval('/'+itemTM+'/gi');
					newString = new String(' <b>'+itemTM+'</b> ');
					texto = texto.replace(regExp, newString);					  
				});				
			}
			return texto;
		},
		temporizadortm: function(){
			// liveTM mode timerTM
			runningTM=true;
			aTimTM = timerTM.split("-");
			if(aTimTM[0]=="liveTM" && aTimTM[1].length>0){
				tempoTM = aTimTM[1]*1000;
				setTimeout("$.JuitterTM.updateTM()",tempoTM);
			}
		}
	};	
})(jQuery);