(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)
					.attr('style', 'padding-top:75px')
					.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){
			var selectatweet = new Array();
			// 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(e==1) $("#"+contDiv).html("");				

					var tultID;

					$.each(json.results,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/"+item.from_user+"/status/"+item.id;  
								
								var tweet = $.Juitter.filter(item.text);
							
								var timex = item.created_at;
								timex = timex.split(" ");
								
								var clocktime = timex[4].split(":");
								var shift = -7;
							
							    clocktime[0] = parseFloat(clocktime[0]);
								clocktime[0] = clocktime[0] + shift;
								if (clocktime[0] < 0){clocktime[0] += 24};
								clocktime[0] += '';
								
								if (msgNb == 1){
									var parsethehour = (Math.ceil(clocktime[0]*1 / 8));
									if (parsethehour == 1){selectatweet = [1,2];};
									if (parsethehour == 2){selectatweet = [1,3];};
									if (parsethehour == 3){selectatweet = [2,3];};
								};
								
								
								var banned = "iscool";

								if(item.iso_language_code == "pt"){banned = "isbanned"};
								if(item.iso_language_code == "fr"){banned = "isbanned"};
								if(item.iso_language_code == "it"){banned = "isbanned"};
								
								if(tweet.search(/exchange/i)>=0){banned = "isbanned"};
								if(tweet.search(/dividends/i)>=0){banned = "isbanned"};
								if(tweet.search(/BodyofBreen/i)>=0){banned = "isbanned"};
								if(tweet.search(/wines/i)>=0){banned = "isbanned"};
								if(tweet.search(/fund/i)>=0){banned = "isbanned"};
								if(tweet.search(/coffee/i)>=0){banned = "isbanned"};
								if(tweet.search(/window/i)>=0){banned = "isbanned"};
								if(tweet.search(/hotel/i)>=0){banned = "isbanned"};
								if(tweet.search(/melverley/i)>=0){banned = "isbanned"};
								if(tweet.search(/folkestone/i)>=0){banned = "isbanned"};
								if(tweet.search(/restaurant/i)>=0){banned = "isbanned"};
								if(tweet.search(/tontine st/i)>=0){banned = "isbanned"};
								if(tweet.search(/tontine street/i)>=0){banned = "isbanned"};
								if(tweet.search(/insurance/i)>=0){banned = "isbanned"};
								if(tweet.search(/itunes/i)>=0){banned = "isbanned"};
								if(tweet.search(/cuadclub/i)>=0){banned = "isbanned"};
								if(tweet.search(/fishing/i)>=0){banned = "isbanned"};
								if(tweet.search(/insulation/i)>=0){banned = "isbanned"};
								if(tweet.search(/tontine partners/i)>=0){banned = "isbanned"};
								
								if(item.from_user == "lovecatx"){banned = "isbanned"};								
								if(item.from_user == "adrianhunter"){banned = "isbanned"};								
								if(item.from_user == "BodyofBreen"){banned = "isbanned"};								
								if(item.from_user == "tontinereport"){banned = "isbanned"};								
								if(item.from_user == "TheTontineHotel"){banned = "isbanned"};								
								if(item.from_user == "holliegalloway"){banned = "isbanned"};																
								if(item.from_user == "delong"){banned = "isbanned"};																
								if(item.from_user == "gurufocus"){banned = "isbanned"};																
								if(item.from_user == "MTPT"){banned = "isbanned"};																
								if(item.from_user == "tfgtrading"){banned = "isbanned"};																
								if(item.from_user == "rieriik"){banned = "isbanned"};																
								if(item.from_user == "rarassatiti"){banned = "isbanned"};																
								if(item.from_user == "sassycrass"){banned = "isbanned"};																
								if(item.from_user == "rohitdass"){banned = "isbanned"};																
								if(item.from_user == "Danielleblue"){banned = "isbanned"};																
								if(item.from_user == "captiveyak"){banned = "isbanned"};																
								if(item.from_user == "bookmooch"){banned = "isbanned"};																
								if(item.from_user == "ChrisGerth"){banned = "isbanned"};																
														
								if(banned =="isbanned"){selectatweet[0]++; selectatweet[1]++;};
								
								
								
								
								clocktime = clocktime[0]+":"+clocktime[1]+":"+clocktime[2]; 
								
								var newtime = timex[0]+" "+timex[1]+" "+timex[2]+" "+timex[3]+" "+clocktime+" PST";
								

								

								
								//So if we want it, get it up on the feed.
								if(banned == "iscool")
								{								
									if(fromID=="image") mHTML="<div class='twiticon'><a href='http://www.twitter.com/"+item.from_user+"' target='_blank'><img src='"+item.profile_image_url+"' class='juitterAvatar' /></a></div><div class='twitbod'> "+$.Juitter.textFormat(tweet, link)+" <span class='time'>"+newtime+"</span></div><div class='clear'> </div>";
									else mHTML="<a href='http://www.twitter.com/"+item.from_user+"'>@"+item.from_user+":</a> "+$.Juitter.textFormat(tweet, link)+" -| <span class='time'>"+newtime+"</span> |-  <a href='" + link + "' "+openLink+">"+readMore+"</a>";
										
									if(mHTML.search(/www.tontinemassacre.com/i)>=0 && tweet.search(/http/i) < 0)
									{
										mHTML = mHTML.replace(/www.tontinemassacre.com/i, "<a href=http://www.tontinemassacre.com>www.tontinemassacre.com</a>");
									};	
									
									if(mHTML.search(/www.tontine2.com/i)>=0 && tweet.search(/http/i) < 0)
									{
										mHTML = mHTML.replace(/www.tontine2.com/i, "<a href=http://www.tontine2.com>www.tontine2.com</a>");
									};	
	
										
									$("<li></li>") 
										.html(mHTML)  
										.attr('id', 'twittLI'+msgNb)
										.attr('class', ('twittLI '+banned))
										.appendTo("#twittList"+ultID);
	
									$('#twittLI'+msgNb).hide();
									$('#twittLI'+msgNb).show();
									
									// remove old entries
									$.Juitter.delRegister();
								}
								msgNb++;								
							}
						}

					});	
					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, link){
			//make links
	
			var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;

			//Find the URLS
			var searchit = texto.match(exp);
			
			//Set Exclusions to the search.
			if (searchit != null && searchit[0].search(/youtube/i) >= 0){var is_excluded = true;};
			if (searchit != null && searchit[0].search(/tontine2.com/i) >= 0){var is_excluded = true;};
			if (searchit != null && searchit[0].search(/tontinemassacre.com/i) >= 0){var is_excluded = true;};
						
			//Filter URLS by exclusions, only grab those longer than 26 chars.
			if (searchit != null && searchit[0].length > 26 && is_excluded != true)
			{
				var textlink = searchit[0].slice(0,24)+"...";
				texto = texto.replace(exp,"<a href='$1' class='extLink' "+openLink+">"+textlink+"</a>"); 
			}
			else
			{
				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='"+link+"' class='profileLink'>@$1</a>"); 
			var exp = /[\#]+([A-Za-z0-9-_]+)/ig;
			texto = texto.replace(exp,"<a href='"+link+"' 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);