// make sure the document.com object exists
if(typeof com=='undefined')com={};

// make sure that a copy of com.stltoday exists...
// if it doesn't exist create it but whine at the user that they're trying to run this widget on a non stltoday.com web page.
if(typeof com.stltoday=='undefined'){
	alert('com.stltoday.widgets.twitter:\n'+
		'http://images.stltoday.com/stltoday/js/stl-headerfooter.js is required for this widget to function correctly.'
	);
	com.stltoday={version:'0.0'};
}
// check to see if the ExtJS framework is loaded, if it isn't whine at the user.
if(typeof Ext=='undefined'){
	alert('com.stltoday.widgets.twitter:\n'+
		'http://images.stltoday.com/stltoday/js/stl-headerfooter.js did not load the ExtJS library, which is required.'
	);
}
// we're going to use the XTemplate class of the ExtJS but the stl-headerfooter.js doesn't have that part automatically loaded.
// at least not yet... so if it's not already defined go ahead and load it into memory.
if(typeof Ext.XTemplate=='undefined')Ext.XTemplate=function(){Ext.XTemplate.superclass.constructor.apply(this,arguments);var P=this.html;P=["<tpl>",P,"</tpl>"].join("");var O=/<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/;var N=/^<tpl\b[^>]*?for="(.*?)"/;var L=/^<tpl\b[^>]*?if="(.*?)"/;var J=/^<tpl\b[^>]*?exec="(.*?)"/;var C,B=0;var G=[];while(C=P.match(O)){var M=C[0].match(N);var K=C[0].match(L);var I=C[0].match(J);var E=null,H=null,D=null;var A=M&&M[1]?M[1]:"";if(K){E=K&&K[1]?K[1]:null;if(E){H=new Function("values","parent","xindex","xcount","with(values){ return "+(Ext.util.Format.htmlDecode(E))+"; }")}}if(I){E=I&&I[1]?I[1]:null;if(E){D=new Function("values","parent","xindex","xcount","with(values){ "+(Ext.util.Format.htmlDecode(E))+"; }")}}if(A){switch(A){case".":A=new Function("values","parent","with(values){ return values; }");break;case"..":A=new Function("values","parent","with(values){ return parent; }");break;default:A=new Function("values","parent","with(values){ return "+A+"; }")}}G.push({id:B,target:A,exec:D,test:H,body:C[1]||""});P=P.replace(C[0],"{xtpl"+B+"}");++B}for(var F=G.length-1;F>=0;--F){this.compileTpl(G[F])}this.master=G[G.length-1];this.tpls=G};Ext.extend(Ext.XTemplate,Ext.Template,{re:/\{([\w-\.\#]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?(\s?[\+\-\*\\]\s?[\d\.\+\-\*\\\(\)]+)?\}/g,codeRe:/\{\[((?:\\\]|.|\n)*?)\]\}/g,applySubTemplate:function(A,H,G,D,C){var J=this.tpls[A];if(J.test&&!J.test.call(this,H,G,D,C)){return""}if(J.exec&&J.exec.call(this,H,G,D,C)){return""}var I=J.target?J.target.call(this,H,G):H;G=J.target?H:G;if(J.target&&Ext.isArray(I)){var B=[];for(var E=0,F=I.length;E<F;E++){B[B.length]=J.compiled.call(this,I[E],G,E+1,F)}return B.join("")}return J.compiled.call(this,I,G,D,C)},compileTpl:function(tpl){var fm=Ext.util.Format;var useF=this.disableFormats!==true;var sep=Ext.isGecko?"+":",";var fn=function(m,name,format,args,math){if(name.substr(0,4)=="xtpl"){return"'"+sep+"this.applySubTemplate("+name.substr(4)+", values, parent, xindex, xcount)"+sep+"'"}var v;if(name==="."){v="values"}else{if(name==="#"){v="xindex"}else{if(name.indexOf(".")!=-1){v=name}else{v="values['"+name+"']"}}}if(math){v="("+v+math+")"}if(format&&useF){args=args?","+args:"";if(format.substr(0,5)!="this."){format="fm."+format+"("}else{format="this.call(\""+format.substr(5)+"\", ";args=", values"}}else{args="";format="("+v+" === undefined ? '' : "}return"'"+sep+format+v+args+")"+sep+"'"};var codeFn=function(m,code){return"'"+sep+"("+code+")"+sep+"'"};var body;if(Ext.isGecko){body="tpl.compiled = function(values, parent, xindex, xcount){ return '"+tpl.body.replace(/(\r\n|\n)/g,"\\n").replace(/'/g,"\\'").replace(this.re,fn).replace(this.codeRe,codeFn)+"';};"}else{body=["tpl.compiled = function(values, parent, xindex, xcount){ return ['"];body.push(tpl.body.replace(/(\r\n|\n)/g,"\\n").replace(/'/g,"\\'").replace(this.re,fn).replace(this.codeRe,codeFn));body.push("'].join('');};");body=body.join("")}eval(body);return this},applyTemplate:function(A){return this.master.compiled.call(this,A,{},1,1)},compile:function(){return this}});Ext.XTemplate.prototype.apply=Ext.XTemplate.prototype.applyTemplate;Ext.XTemplate.from=function(A){A=Ext.getDom(A);return new Ext.XTemplate(A.value||A.innerHTML)};
//
// are we the first widget loaded into the browser let's go ahead and create the widgets collection off of com.stltoday.com
if(typeof com.stltoday.widgets=='undefined')com.stltoday.widgets={};
//
// here we go, here's our widget...
if(typeof com.stltoday.widgets.twitter=='undefined')com.stltoday.widgets.twitter={
	'version':  "1.0",
	'widgets':	new Array(),
	'base_url': "http://search.twitter.com/search.json",
	'loading_msg': '<img src="http://images.stltoday.com/stltoday/images/ajax/indicator.gif"> Loading...',
	'init':		function(args) {
		var m=this.widgets.length;
		var me=this;
		this.widgets[m] = {
			'engine':	me,
			'm':		m,
			'jp':		'com.stltoday.widgets.twitter.widgets['+m+'].cb',
			'cb':   	function(d){this.engine.cb(d,this);},
			'load':	function(q){
				if(typeof q!='undefined')this.query=q;
				widget.td.mask(this.loading_msg);
				var url = this.engine.base_url+"?"+Ext.urlEncode({'callback':this.jp,'q':this.query});
				this.engine.ss(url,widget.id+"_script");
			}
		};
		var widget=this.widgets[m];
		Ext.apply(widget,args,{
			"query":	"from:stltoday OR to:stltoday OR @stltoday",
			"template":	[
			  '<tpl for="results">',
				'<div class="tweet">',
				  '<img class="tweet_img" src="{profile_image_url}">',
				  '<a target="_BLANK" href="http://twitter.com/{from_user}" class="tweet_user">{from_user}</a> ',
				  '<span class="tweet_text">{text}</span> ',
				  '<span class="tweet_time" title="{created_at}">{ago}</span>',
				  '<div style="clear:both"></div>',
				'</div>',
			  '</tpl>'
			],
			'styles':[
				'div.tweet {border-bottom:1px solid #333;font-size:12px}',
				'div.tweet img.tweet_img {display:block;float:left;padding:0 5px 5px 0}',
				'div.tweet a.tweet_user {font-weight:800;color:blue}',
				'div.tweet a.tweet_user:hover {text-decoration:underline}',
				'div.tweet span.tweet_time {font-size:10px;font-style:italic}',
				'div.tweet span.tweet_text a {color:blue}'
			]
		});
		widget.td=Ext.get(widget.id);
		Ext.onReady(function(){
			ss1 = document.createElement('style');
			ss1.setAttribute("id",widget.id+"_styles");
			ss1.setAttribute("type", "text/css");
			var id ='#'+widget.id+' ';
			var st =id+widget.styles.join('\n'+id);

			if (ss1.styleSheet) { // I.E.
				ss1.styleSheet.cssText = st;
			} else { // everybody else.
				var tt1 = document.createTextNode(st);
				ss1.appendChild(tt1);
			}
			var hh1 = document.getElementsByTagName('head')[0];
			hh1.appendChild(ss1);
			widget.load();
		});
		return widget;
	},
	'ss':	function(url,id){var d=document,s=d.createElement('script');s.id = id;s.type ='text/javascript';s.src = url;d.getElementsByTagName('head')[0].appendChild(s);},
	'rs':	function(id){var d=document,s=d.getElementById(id);if(s!=null)s.parentNode.removeChild(s);},
	'cb':function(d,w){
		w.data=d;
		var r = d.results;
		var rx=/(http:\/\/\S+)/ig;
		for(var i=0;i<r.length;i++) {
			r[i].ago = this.twitter_ts2ago(r[i].created_at);
			r[i].text = r[i].text.replace(rx,'<a href="$1">$1</a>');
		}
		var tpl = new Ext.XTemplate(w.template);
		w.td.unmask();
		tpl.overwrite(w.td,d);
		// this.rs(w.id+"_script");
	},
	'uts':function(dt){if(typeof(dt)=='undefined');dt=new Date();return Math.floor(dt.getTime()/1000);},
	'ago':function(r,n){if(typeof(n)=="undefined")n=this.uts();var d=n-r;if(d<0)return "in the future";if(d==0)return "now";if(d<60)return "in the last minute";if(d<120)return "1 minute ago";if(d<3600){var m=Math.floor(d/60);return m+" minutes ago";};if(d<7200)return "1 hour ago";if(d<86400){var h=Math.floor(d/3600);return h+" hours ago";};if(d<172800)return "1 day ago";if(d<1209600){var dd=Math.floor(d/86400);return dd+" days ago";};if(d<2592000){var w=Math.floor(d/604800);return w+" weeks ago";};if(d<5184000)return "1 month ago";if(d<31536000){var mm=Math.floor(d/2592000);return mm+" months ago";};if(d<63072000)return "1 year ago";return ""+Math.floor(d/31536000)+" years ago";},
	'twitter_ts2ago':function(tts){
	    var ts = Date.parse(tts)/1000;
	    return this.ago(ts);
	}
};
if(typeof com.stltoday.widgets.twitter.trends=='undefined')com.stltoday.widgets.twitter.trends={
	'data':{},
	'reload':function(){
		var d=document,s=d.createElement('script');
		s.id = id;
		s.type ='text/javascript';
		s.src  ='http://search.twitter.com/trends.json?callback=com.stltoday.widgets.twitter.trends.cb';
		d.getElementsByTagName('head')[0].appendChild(s);
	},
	'cb':function(d){
		this.data = d;
	}
};
