//////////////////////////////////////////////////////////
// cTweetTicker - v 2.0
// (c)2011 evulc
// use however you like license.
// you only get support if you have seen me in person.
// it's part of the license ;)
// see bottom of file for suggested usage.
//////////////////////////////////////////////////////////

var CTT=function(opts){

	div = $('#'+opts.div);
	cdiv = $('#content',div);
	show_overlay = true;
	refresh_url = false;
	tweetlist = [];
	duration = opts.duration;
	flipdur = opts.flipdur;
	fadedur = opts.fadedur;
	query = opts.query;
	theme = opts.theme;
	
	cur = 0;

	this.loadtheme = function(){
		$('head').append(
			'<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/themes/'+
			theme+
			'/jquery-ui.css" media="screen" rel="stylesheet" type="text/css" />'
		);

	}
	
	this.searchTwitter = function(){
		var uu = 'http://search.twitter.com/search.json'; 
		if(refresh_url)
			u = uu + refresh_url;
		else
			u = uu + '?include_entities=1&rpp=50&q=' + escape(query);

		$.ajax({
			url: u,
			dataType: 'jsonp',
			success: $.proxy(this.searchTwitterResult,this)
		});
	}

	this.searchTwitterResult = function(data){
		if(data.refresh_url)
			refresh_url = data.refresh_url;
		_this = this;
		if(data.results.length > 0){
			$(data.results).each(function(i,u){
				var ct = new CTTT(u,_this);
				tweetlist.push(ct);
			});
			if(cur==0)
				tweetlist[0].div.show();
		}else{
			if(tweetlist.length==0)
				cdiv.html('<div style="padding:5px">Twitter currently shows no results for: \'' + query + '\'. checking again soon.</div>');
		}

		setTimeout($.proxy(this.searchTwitter,this),duration);		
		
		if(show_overlay){
			$('#overlay').hide();
			show_overlay = false;
		}
		
	}

	this.rotate = function(){
	
		if(tweetlist.length == 0)
			return
		
		tweetlist[cur].div.fadeOut(fadedur,function(){
			tweetlist[cur].div.fadeIn(fadedur);
		});

		if(cur == tweetlist.length -1)
			cur = 0
		else
			cur++
	}

	this.updateTimes = function(){
		var l = $('#date',div);
		$(l).each(function(i,v){
			$(v).html( prettyDate($(v).data('twdate')) );
		});
	}
	
	this.loadtheme();
	this.searchTwitter();
	setInterval($.proxy(this.rotate,this),flipdur);
}

var CTTT=function(tweet,owner){

	this.tweet = tweet;
	this.owner = owner;
	this.div = null;

	this.draw = function(){
		var md = $('#itemTemp').clone();
		md.attr('id',tweet.id);
		cdiv.append(md);

		this.div = md;
		$('#date',md).html(prettyDate(tweet.created_at));
		$('#twerp',md).html(tweet.from_user);
		
		//tweep thumbnail preloader.
		var ti = $('<img>');
		ti.data('myimg',$('#twitImage',md));
		ti.attr('src',tweet.profile_image_url);
		ti.load(function(e){
			var t = $(e.currentTarget);
			var td = t.data('myimg');
			td.attr('src',t.attr('src'));
			t.remove();
		});
		ti.hide();

		if(tweet.entities.media){
			var ml = $(tweet.entities.media);
			var mll = ml.length;
			ml.each(function(i,u){
				var im = $('#extImg',md);
				im.attr('src',u.media_url);
				im.show();
				var ia = $('<a target="_blank" href="'+u.expanded_url+'"></a>');
				im.wrap(ia);

				var tout = tweet.text.substring(0,u.indices[0] - 1) +
				' <a href="' +  u.expanded_url + '" target="_blank">' + 
				u.url + '</a> ' + 
				tweet.text.substring(u.indices[1] + 1);
				tweet.text = tout;
			});
		}
		
		if(tweet.entities.urls){
			var ul = $(tweet.entities.urls);
			var ull = ul.length;
			_this = this;
			ul.each(function(i,u){
				tout = ' <a href="' +  u.expanded_url + 
					'" target="_blank">' + 
					u.url + '</a>';
				
				tweet.text = tweet.text.replace(u.url,tout);
				if(i==0){ //only preview the first image
					var im = $('#extImg',_this.div);
					if(u.expanded_url.indexOf('yfrog.com') > 0){
						im.attr('src',u.expanded_url+':small');
						im.show();
					}else if(u.expanded_url.indexOf('twitpic.com') > 0){
						im.attr('src',u.expanded_url.replace('.com/','.com/show/thumb/'));
						im.show();
					}
					
					var ia = $('<a target="_blank" href="'+u.expanded_url+'"></a>');
					im.wrap(ia);
				}
			});
		}
		md.data('twdate',tweet.created_at);
		//Linkify GC
		tweet.text = tweet.text.replace(/(^| )(GC[A-Z0-9]+)/g,' <a href="http://coord.info/$2" target="_blank" class="ui-corner-all ui-state-highlight">$2</a>');
		$('#tweet',md).html(tweet.text);
		$(document.body).append(ti);
	};
	
	this.updatetime = function(){
		var d = $('#date',this.div);
		d.html(prettyDate(this.tweet.created_at));
	};
	
	this.show = function(){
		this.div.show();
	};

	this.hide = function(){
		this.div.hide();
	};
	
	this.draw();
	setInterval($.proxy(this.updatetime,this),5000);
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
 * JavaScript Pretty Date
 * Copyright (c) 2008 John Resig (jquery.com)
 * Licensed under the MIT license.
 */

// Takes an ISO time and returns a string representing how
// long ago the date represents.
function prettyDate(time){
	var date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ")),
		diff = (((new Date()).getTime() - date.getTime()) / 1000),
		day_diff = Math.floor(diff / 86400);
			
	if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
		return;
			
	return day_diff == 0 && (
			diff < 60 && "just now" ||
			diff < 120 && "1 minute ago" ||
			diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
			diff < 7200 && "1 hour ago" ||
			diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
		day_diff == 1 && "Yesterday" ||
		day_diff < 7 && day_diff + " days ago" ||
		day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
}
