/*
JUITTER 1.0.0 - 22/07/2009 - http://juitter.com
BY RODRIGO FANTE - http://rodrigofante.com

** jQuery 1.2.* or higher required

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.
*/
var fload=0;
function parseDate(str) {
  var v=str.split(' ');
  return new Date(Date.parse(v[1]+" "+v[2]+", "+v[5]+" "+v[3]+" UTC"));
} 
(function($) {
	var conf = {},
		// JUITTER DEFAULT CONFIGURATION ========================
		// YOU CAN CHANGE THE DYNAMIC VARS ON CALLING THE start method, see the system.js for more information about it.

		numMSG = 20; // set the number of messages to be show
		containerDiv="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 
		live:"live-20", //optional, disabled by default, the number after "live-" 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
		aURL="";msgNb=1;
		var mode,param,time,lang,contDiv,loadMSG,gifName,numMSG,readMore,fromID,ultID,filterWords;
		var running=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=";
	$.Juitter = {
		registerVar: function(opt){
			mode=opt.searchType;
			param=opt.searchObject;
			timer=opt.live;
			lang=opt.lang?opt.lang:"";
			contDiv=opt.placeHolder?opt.placeHolder:containerDiv;
			loadMSG=opt.loadMSG?opt.loadMSG:loadMSG;
			gifName=opt.imgName?opt.imgName:imgName;
			numMSG=opt.total?opt.total:numMSG;
			readMore=opt.readMore?opt.readMore:readMore;
			fromID=opt.nameUser?opt.nameUser:nameUser;
			filterWords=opt.filter;
			openLink=opt.openExternalLinks?"target='_blank'":"";
		},
		start: function(opt) {		
			ultID=0;
			if($("#"+contDiv)){	
				this.registerVar(opt);
				// show the load message
				this.loading();
				// create the URL  to be request at the Twitter API
				aURL = this.createURL();
				// 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&&!running) this.temporizador();
			}   
		},
		update: function(){
			this.conectaTwitter(2);		
			if(timer!=undefined) this.temporizador();
		},
		loading: function(){
			if(loadMSG=="image/gif"){
				$("<img></img>")
					.attr('src', gifName)
					.appendTo("#"+contDiv); 
			} else $("#"+contDiv).html(loadMSG);
		},
		createURL: 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="+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(e){
			// query the twitter api and create the tweets list
			$.ajax({
				url: "http://twitter.com/statuses/user_timeline/"+param+".json",
				type: 'GET',
				dataType: 'jsonp',
				timeout: 1000,
				error: function(){ $("#"+contDiv).html("fail#"); },
				success: function(json){
					
					if(e==1) $("#"+contDiv).html("");				
					$.each(json,function(i,item) {
						if(e==1 || (i<numMSG && item.id>ultID)){
							if(i==0){
								tultID = item.id;
								$("<ul></ul>")
									.attr('id', 'twittList'+ultID)
									.attr('class','twittList')
									.prependTo("#"+contDiv);  
							}
							if (item.text != "undefined") {
								var link =  "http://twitter.com/"+param+"/status/"+item.id;  
								
								var tweet = $.Juitter.filter(item.text);
								var currentTime = parseDate(item.created_at);
								var minute = currentTime.format("d");
								var cw = "th";
								if(minute==1||minute==11||minute==21||minute==31||minute==41||minute==51) cw="st";
								if(minute==2||minute==12||minute==22||minute==32||minute==42||minute==52) cw="nd";
								if(minute==3||minute==13||minute==23||minute==33||minute==43||minute==53) cw="rd";
								
								
								var actualTime = currentTime.format("H:MM mmm dd")+cw;
;
								if(fromID=="image") mHTML="<a href='http://www.twitter.com/"+item.from_user+"'><img src='"+item.profile_image_url+"' alt='"+item.from_user+"' class='juitterAvatar' /></a> "+$.Juitter.textFormat(tweet)+" -| <span class='time'>"+item.created_at+"</span> |- <a href='" + link + "' class='JRM' "+openLink+">"+readMore+"</a>";
								else mHTML="<span>"+$.Juitter.textFormat(tweet)+"</span><span class='secondLine'><a href='http://twitter.com/"+param+"'>@"+param+"</a> - "+actualTime+"</span>";
								//cPage = Math.ceil((i+1)/2);
								cPage=i+1;
								$("<li></li>") 
									.html("<div class='twCont'>"+mHTML+"</div>")  
									.attr('id', 'twittLI'+msgNb)
									.attr('class', 'twittLI')
									.attr('class', 'page_'+cPage)
									.appendTo("#twittList"+ultID);

								$('#twittLI'+msgNb).hide();
								
								
								
								
								// remove old entries
								$.Juitter.delRegister();
								msgNb++;								
							}
						}
					});
					// get the total of pages
					totPages = cPage>5?5:cPage;
					if($(".twitterPagination").length<=0){
						$("<ul />")
							.attr("class","boxPagination twitterPagination")	
							.appendTo("#boxTwitter");
						$("<li />")
							.attr("class","prev")
							.html("<a href='#prev'></a>")
							.appendTo(".twitterPagination");
						for(i=1;i<=totPages;i++){
							$("<li />")
							.attr("class","page_"+i)
							.html("<a href='page_"+i+"'></a>")
							.appendTo(".twitterPagination");
							if(i==1) $(".page_"+i+" A").addClass("on");
						}
						$("<li />")
							.attr("class","next")
							.html("<a href='#next'></a>")
							.appendTo(".twitterPagination");
							
						curTweet=1;
						$(".twittList > LI.page_"+curTweet).fadeIn();
						$(".twitterPagination LI A").click(function(){return false});
						$(".twitterPagination LI.prev A").click(function(){
							if(curTweet>1){
								$(".twitterPagination LI.page_"+curTweet+" A").removeClass("on");
								$(".twittList > LI.page_"+curTweet).fadeOut();
								curTweet--;
								$(".twitterPagination LI.page_"+curTweet+" A").addClass("on");
								$(".twittList > LI.page_"+curTweet).fadeIn();
							} else {
				    $(".twitterPagination LI.page_"+curTweet+" A").removeClass("on");
								$(".twittList > LI.page_"+curTweet).fadeOut();
								curTweet=5;
								$(".twitterPagination LI.page_"+curTweet+" A").addClass("on");
								$(".twittList > LI.page_"+curTweet).fadeIn();
				}
							return false;
						});
						$(".twitterPagination LI.next A").click(function(){
							if(curTweet<totPages){
								$(".twitterPagination LI.page_"+curTweet+" A").removeClass("on");
								$(".twittList > LI.page_"+curTweet).fadeOut();
								curTweet++;
								$(".twitterPagination LI.page_"+curTweet+" A").addClass("on");
								$(".twittList > LI.page_"+curTweet).fadeIn();
							} else {
				    $(".twitterPagination LI.page_"+curTweet+" A").removeClass("on");
								$(".twittList > LI.page_"+curTweet).fadeOut();
								curTweet=1;
								$(".twitterPagination LI.page_"+curTweet+" A").addClass("on");
								$(".twittList > LI.page_"+curTweet).fadeIn();
				}
							return false;
						});
						ultID=tultID;
					}
				}
			});
		},		
		filter: function(s){
			if(filterWords){
				searchWords = filterWords.split(",");				
				if(searchWords.length>0){
					cleanHTML=s;
					$.each(searchWords,function(i,item){	
						sW = item.split("->").length>0 ? item.split("->")[0] : item;
						rW = item.split("->").length>0 ? item.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://search.twitter.com/search?q=$1' class='hashLink' target='_blank'>#$1</a>"); 
			// make it bold
			if(mode=="searchWord"){
				tempParam = param.replace(/&ors=/,"");
				arrParam = tempParam.split("+");
				$.each(arrParam,function(i,item){					
					regExp=eval('/'+item+'/gi');
					newString = new String(' <b>'+item+'</b> ');
					texto = texto.replace(regExp, newString);					  
				});				
			}
			return texto;
		},
		temporizador: function(){
			// live mode timer
			running=true;
			aTim = timer.split("-");
			if(aTim[0]=="live" && aTim[1].length>0){
				tempo = aTim[1]*1000;
				setTimeout("$.Juitter.update()",tempo);
			}
		}
	};	
})(jQuery);

var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		//if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};

