(function(e,b){function d(){}function t(C){c=[C]}function m(C){f.insertBefore(C,f.firstChild)}function l(E,C,D){return E&&E.apply(C.context||C,D)}function k(C){return/\?/.test(C)?"&":"?"}var n="async",s="charset",q="",A="error",r="_jqjsp",w="on",o=w+"click",p=w+A,a=w+"load",i=w+"readystatechange",z="removeChild",g="<script/>",v="success",y="timeout",x=e.browser,f=e("head")[0]||document.documentElement,u={},j=0,c,h={callback:r,url:location.href};function B(C){C=e.extend({},h,C);var Q=C.complete,E=C.dataFilter,M=C.callbackParameter,R=C.callback,G=C.cache,J=C.pageCache,I=C.charset,D=C.url,L=C.data,P=C.timeout,O,K=0,H=d;C.abort=function(){!K++&&H()};if(l(C.beforeSend,C,[C])===false||K){return C}D=D||q;L=L?((typeof L)=="string"?L:e.param(L,C.traditional)):q;D+=L?(k(D)+L):q;M&&(D+=k(D)+encodeURIComponent(M)+"=?");!G&&!J&&(D+=k(D)+"_"+(new Date()).getTime()+"=");D=D.replace(/=\?(&|$)/,"="+R+"$1");function N(S){!K++&&b(function(){H();J&&(u[D]={s:[S]});E&&(S=E.apply(C,[S]));l(C.success,C,[S,v]);l(Q,C,[C,v])},0)}function F(S){!K++&&b(function(){H();J&&S!=y&&(u[D]=S);l(C.error,C,[C,S]);l(Q,C,[C,S])},0)}J&&(O=u[D])?(O.s?N(O.s[0]):F(O)):b(function(T,S,U){if(!K){U=P>0&&b(function(){F(y)},P);H=function(){U&&clearTimeout(U);T[i]=T[o]=T[a]=T[p]=null;f[z](T);S&&f[z](S)};window[R]=t;T=e(g)[0];T.id=r+j++;if(I){T[s]=I}function V(W){(T[o]||d)();W=c;c=undefined;W?N(W[0]):F(A)}if(x.msie){T.event=o;T.htmlFor=T.id;T[i]=function(){/loaded|complete/.test(T.readyState)&&V()}}else{T[p]=T[a]=V;x.opera?((S=e(g)[0]).text="jQuery('#"+T.id+"')[0]."+p+"()"):T[n]=n}T.src=D;m(T);S&&m(S)}},0);return C}B.setup=function(C){e.extend(h,C)};e.jsonp=B})(jQuery,setTimeout);
		
		window.ify = function(){var entities={'"':'&quote;','&':'&amp;','<':'&lt;','>':'&gt;'};return{"link":function(t){return t.replace(/[a-z]+:\/\/[a-z0-9-_]+\.[a-z0-9-_:~%&amp;\?\/.=]+[^:\.,\)\s*$]/ig,function(m){return'<a href="'+m+'">'+((m.length>25)?m.substr(0,24)+'...':m)+'</a>';});},"at":function(t){return t.replace(/(^|[^\w]+)\@([a-zA-Z0-9_]{1,15})/g,function(m,m1,m2){return m1+'@<a href="http://twitter.com/'+m2+'">'+m2+'</a>';});},"hash":function(t){return t.replace(/(^|[^\w'"]+)\#([a-zA-Z0-9_]+)/g,function(m,m1,m2){return m1+'#<a href="http://search.twitter.com/search?q=%23'+m2+'">'+m2+'</a>';});},"clean":function(tweet){return this.hash(this.at(this.link(tweet)));}};}();
		
		$(function() {
			
			var content = '';
			var tweetsArray = new Array();
			
		
			// PutnamToday
			$.jsonp({
				"url": "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=putnamtoday&count=30&callback=?",
				"success": function(data) {
					
					$.each(data, function(i){
						add_tweet(this['text'], this['created_at'], "<a href='http://twitter.com/#!/putnamtoday' target='_blank'>Putnam Today</a>");
					});					
					
					// RobertLReynolds
					$.jsonp({
						"url": "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=robertlreynolds&count=30&callback=?",
						"success": function(data) {
							
							$.each(data, function(i){								
								add_tweet(this['text'], this['created_at'], "<a href='http://twitter.com/#!/robertlreynolds' target='_blank'>Robert L. Reynolds</a>");
							});
																
							
							// JeffCarney
							$.jsonp({
								"url": "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=jeffcarney&count=30&callback=?",
								"success": function(data) {
									
									$.each(data, function(i){									
										add_tweet(this['text'], this['created_at'], "<a href='http://twitter.com/#!/jeffcarney' target='_blank'>Jeffrey Carney</a>");
									});
									
									render_tweets();
								}
							});	
						}
					});
				},
				
				// PutnamToday ERROR
				"error": function(d, msg) {
				
					
					$('#error').show();
					$.ajax({
						type: "GET",
						url: "putnamtoday.json",
						contentType: "application/json; charset=utf-8",
						dataType: "json",
						complete: function(fallbackData) {
							
							$.each(eval(fallbackData['responseText']), function(i){										
								add_tweet(this['text'], this['created_at'], "<a href='http://twitter.com/#!/putnamtoday' target='_blank'>Putnam Today</a>");
							});
							
							
							// RobertLReynolds ERROR
							$.ajax({
								type: "GET",
								url: "robertlreynolds.json",
								contentType: "application/json; charset=utf-8",
								dataType: "json",
								complete: function(fallbackData) {

									$.each(eval(fallbackData['responseText']), function(i){										
										add_tweet(this['text'], this['created_at'], "<a href='http://twitter.com/#!/robertlreynolds' target='_blank'>Robert L. Reynolds</a>");
									});
									
									
									// JeffCarney ERROR
									$.ajax({
										type: "GET",
										url: "jeffcarney.json",
										contentType: "application/json; charset=utf-8",
										dataType: "json",
										complete: function(fallbackData) {

											$.each(eval(fallbackData['responseText']), function(i){										
												add_tweet(this['text'], this['created_at'], "<a href='http://twitter.com/#!/jeffcarney' target='_blank'>Jeffrey Carney</a>");
											});
											
											render_tweets();
										
										}
									});
								}
							});
						}
					});
				}
			});
			
			function add_tweet(tweet_text, tweet_date, tweet_source){
					
				if (tweet_text.toLowerCase().indexOf("#putnamclub") != -1 || tweet_text.toLowerCase().indexOf("#putnampark") != -1) {
					var tweet = ify.clean(tweet_text);
					var source = tweet_source;

					// IE UTC date fix
					var v=tweet_date.split(' ');
					var d = new Date(Date.parse(v[1]+" "+v[2]+", "+v[5]+" "+v[3]+" UTC"));
					var date_show = time_since_tweet(d);

					// add it the the array
					tweetsArray[tweetsArray.length] = {tweet:tweet, source:source, date_show:date_show, date_sort:d.getTime()};
					
				}
			}
			
			function render_tweets(){
				
				// sort by date_sort 
				tweetsArray.sort(function(a,b) {
					return a.date_sort + b.date_sort;
				});
				
				for (var i=0; i<tweetsArray.length; i++) {
					content += '<div class="tweet"><p>'+ tweetsArray[i].tweet +'</p><p class="tweet-date">' + tweetsArray[i].source + ' '+ tweetsArray[i].date_show +'</p></div>';
				}
				
				$('#twitter-feeds').append(content);
				$('#twitter-loading').remove();
				ScrollingTweets.init();
			
			}	
			
			function time_since_tweet(itemDate){
		
				var nowDate = new Date();
		
				var nTotalDiff = nowDate.getTime() - itemDate.getTime();
				var oDiff = new Object();
		
				oDiff.days = Math.floor(nTotalDiff/1000/60/60/24)  || 0;
				nTotalDiff -= oDiff.days*1000*60*60*24;
		
				oDiff.hours = Math.floor(nTotalDiff/1000/60/60)  || 0;
				nTotalDiff -= oDiff.hours*1000*60*60;
		
				oDiff.minutes = Math.floor(nTotalDiff/1000/60)  || 0;
				nTotalDiff -= oDiff.minutes*1000*60;
		
				var tempStr = "";
		
				if (oDiff.days > 0){
					 tempStr += " " + oDiff.days + " day";
					 if (oDiff.days > 1)  tempStr += "s";
				}
		
				if (oDiff.hours > 0){
					 tempStr += " " + oDiff.hours + " hour";
					 if (oDiff.hours > 1)  tempStr += "s";
				}
		
				if (oDiff.minutes > 0 & oDiff.days == 0){
					 tempStr += " " + oDiff.minutes + " minute";
					 if (oDiff.minutes > 1)  tempStr += "s";
				}
		
				tempStr = ' |' + tempStr + ' ago';
		
				return tempStr;
		
			}			
			
		});
		
		
		var ScrollingTweets = { 

			numTweets: 0, 
			curPos: 1,
			
			init: function() {		
				
				$('.tweet').each(function(){
					ScrollingTweets.numTweets++;
				});
				
				// click handelers
				$('#tweet-up').bind('click', ScrollingTweets.itemUp);
				$('#tweet-down').bind('click', ScrollingTweets.itemDown);
				
			},
			
			itemDown: function() {
				if (ScrollingTweets.curPos < ScrollingTweets.numTweets) {
					$('#twitter-feeds').scrollTo($('.tweet:eq('+ ScrollingTweets.curPos +')'), 1000, {queue:true});
					ScrollingTweets.curPos ++;
				}
				return false;
			},
			
			itemUp: function() {
				if (ScrollingTweets.curPos <= ScrollingTweets.numTweets & ScrollingTweets.curPos > 1) {
					$('#twitter-feeds').scrollTo($('.tweet:eq('+ (ScrollingTweets.curPos-2) +')'), 1000, {queue:true});
					ScrollingTweets.curPos --;
				}
				return false;
			}
		}
		
		$('a').click(function(){
		if ($(this).attr('rel') == 'external'){
			var location = '/shared/html/leaving-putnam.html?href=' + $(this).attr('href');
			$.fancybox({'type':'iframe', 'href':location, 'scrolling':'no', 'width':370, 'height':160, 'padding':0, 'modal':true});
			return false;
		}
	});
	$('area').click(function(){
		if ($(this).attr('rel') == 'external'){
			var location = '/shared/html/leaving-putnam.html?href=' + $(this).attr('href');
			$.fancybox({'type':'iframe', 'href':location, 'scrolling':'no', 'width':370, 'height':160, 'padding':0, 'modal':true});
			return false;
		}
	});
