/*
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.
*/
(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-60", //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
	
	
	
	apiSEARCH = "http://search.twitter.com/search.json?q=";

	/*
		Arfaetha Mod
		
	*/
	var tultID=0
	var stack_array=[];var stack_count=0;var json_result_array=[];
	var QUERY_LENGTH_LIMIT=140;
	var QUERY_FROMUSER_POSTFIX="";
	var QUERY_FROMUSER_GLUE="+OR+";
	var GMT_MODIFIER_VALUE=9;
	
	$.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'":"";
			
			/*
				Arfaetha Mod
				 受信側の新仕様に沿ったクエリに修正
			
				xxx
				q=from%3Axxxx
				xxx,yyy
				q=from%3Axxxx+OR+from%3Ayyy
				q=to%3Axxxx+OR+to%3Ayyy
				q=xxx+OR+yyy
			
			*/
			if(mode=="fromUser") {
				QUERY_FROMUSER_POSTFIX="from%3A";
			} else if(mode=="toUser") {
				QUERY_FROMUSER_POSTFIX="to%3A";
			} else if(mode=="searchWord") {
				QUERY_FROMUSER_POSTFIX="";
			}
			
		},
		start: function(opt) {
			ultID=0;
			if($("#"+contDiv)){
				this.registerVar(opt);
				// show the load message
				this.loading();

				/*
					Arfaetha Mod
					パラメータが長くて140文字を超えそうな場合、複数回の通信とスタックを利用する。
				*/
				this.divideParam();
				
				this.count_and_judge(1);
				
			}   
		},

		/* 
			Arfaetha Mod
			カンマ区切り文字列param
			項目数 n
			140 > 7*n+4*(n-1)+(param.length-(n-1))
			
		*/
		divideParam:function(){
			
			var whole_array=param.split(",");
			stack_array[stack_count]=[];
			var temp_array=[];
			
			for(var i=0,L=whole_array.length;i<L;i++){
				var current_value=whole_array[i]
				temp_array.push(current_value);
				var paramLength = this.getLengthAfterProcess(temp_array,QUERY_FROMUSER_POSTFIX,QUERY_FROMUSER_GLUE)
				if(paramLength > QUERY_LENGTH_LIMIT) {
					stack_count++;
					stack_array[stack_count] =[];
					temp_array=[];
				}
				stack_array[stack_count].push(current_value);
			}
			
			
			
		},
		/*
			Arfaetha Mod
			
		*/
		getLengthAfterProcess:function(array,pfix,glue){
			var ret_array=[];
			jQuery.each(array,function(key,value){
				ret_array.push(pfix+value)
			});
			var ret_string="";
			ret_string=ret_array.join(glue);
			return ret_string.length;
		},
		count_and_judge: function(e){
			if(stack_array.length > 1){
				
				for(var i=0,L=stack_array.length;i<L;i++){
					var current_stack_key= i;
					var _url=this.createURL(stack_array[i].join(","));
					this.conectAndStackTwitter(_url,current_stack_key,e);
				}
				
			} else {
			
				// create the URL  to be request at the Twitter API
				aURL = this.createURL(param);
				// query the twitter API and create the tweets list
				this.conectaTwitter(e);
				// if live mode is enabled, schedule the next twitter API query
				
				
			}
			if(timer!=undefined&&!running) this.temporizador();
		},
		
		
		update: function(){
			this.count_and_judge(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(param){
			var url = "";
			jlg=lang.length>0?"&lang="+lang:jlg=""; 
			var seachMult = param.search(/,/);
			
			if(seachMult>0) {
				var params = param.split(",");
				jQuery.each(params, function(key,value){
					params[key] = QUERY_FROMUSER_POSTFIX + value;
				})
				param=params.join(QUERY_FROMUSER_GLUE);
			}
			url=apiSEARCH+param;
			if(mode=="searchWord") url += 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: aURL,
				type: 'GET',
				dataType: 'jsonp',
				timeout: 1000,
				error: function(){ $("#"+contDiv).html("fail#"); },
				success: function(json){
					$.Juitter.parseJson(json.results,e);
				}
			});
		},
		/*
			Arfaetha Mod
				複数送信版の通信とパース
		*/
		conectAndStackTwitter: function(aURL,current_stack_key,e){
			$.ajax({
				url: aURL,
				type: 'GET',
				dataType: 'jsonp',
				timeout: 1000,
				error: function(){ $("#"+contDiv).html("fail#"); },
				success: function(json){
					json_result_array=json_result_array.concat(json.results);
					if((current_stack_key+1)==stack_array.length) $.Juitter.parseJson(json_result_array,e);
				}
			});
		},
		parseJson:function(json_result_array,e){
			if(e==1) $("#"+contDiv).html("");
			json_result_array=$.Juitter.sort_by_timestamp(json_result_array);
			//var tultID=0;
			$.each(json_result_array,function(i,item) {
															 
				if(e==1 || (i<numMSG && item.id>ultID)){
				//if(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/"+item.from_user+"/status/"+item.id;  
						
						var tweet = $.Juitter.filter(item.text);
						
						//>Thu, 15 Apr 2010 11:38:28 +0000<
						try {
							var dateObject=new Date(item.created_at);
							var mod_timestamp =dateObject.toLocaleString();
						} catch(e){
							var mod_timestamp = item.created_at
						}
						
						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'>"+mod_timestamp+"</span> |- <a href='" + link + "' class='JRM' "+openLink+">"+readMore+"</a>";
						else mHTML="<a href='http://www.twitter.com/"+item.from_user+"'>@"+item.from_user+":</a> "+$.Juitter.textFormat(tweet)+" -| <span class='time'>"+mod_timestamp+"</span> |-  <a href='" + link + "' "+openLink+">"+readMore+"</a>";
						
						$("<li></li>") 
						.html(mHTML)  
						.attr('id', 'twittLI'+msgNb)
						.attr('class', 'twittLI')
						.appendTo("#twittList"+ultID);
						
						$('#twittLI'+msgNb).hide();
						$('#twittLI'+msgNb).show("slow");
						
						// remove old entries
						$.Juitter.delRegister();
						msgNb++;
					}
				}
			});
			ultID=tultID;

		},
		/*
			Arfaetha Mod
				search.twitterが返す 、[あっち式]のタイムスタンプを数字に変換、ソートに使用
		*/
		sort_by_timestamp:function(array){
			
			var exchangeStamp=function(timestamp){
				try{
					var dateObject=new Date(timestamp)
					return dateObject.getTime();
				} catch(e){
					return timestamp
				}
				
			}
			var comparingFunction = function(firstObject,secondObject){
				var timestamp1=firstObject["created_at"];
				var timestamp2=secondObject["created_at"];
				
				var number1=exchangeStamp(timestamp1)
				var number2=exchangeStamp(timestamp2)
				
				// 新しい日付が上！
				if( number1 <  number2 ) return  1;
				if( number1 == number2 ) return  0;
				if( number1 >  number2 ) return -1;
				
			}
			ret_array=array.sort(comparingFunction);
								 
			return ret_array;
			
		},
		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://juitter.com/#$1' onclick='$.Juitter.start({searchType:\"searchWord\",searchObject:\"$1\"});return false;' class='hashLink'>#$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);
