$j= jQuery.noConflict();
jQuery.fn.reverse=Array.prototype.reverse;String.prototype.linkify=function()
{return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g,function(m)
{return m.link(m);});};String.prototype.linkuser=function()
{return this.replace(/[@]+[A-Za-z0-9-_]+/g,function(u)
{var username=u.replace("@","")
return u.link("http://twitter.com/"+username);});};String.prototype.linktag=function()
{return this.replace(/[#]+[A-Za-z0-9-_]+/,function(t)
{var tag=t.replace("#","%23")
return t.link("http://search.twitter.com/search?q="+tag);});};function fetch_tweets(elem)
{elem=$j(elem);input=elem.attr('title');key=elem.attr('title');token=elem.attr('token'); from=elem.attr('rel');refresh=elem.attr('refresh');lang=elem.attr('lang');params=elem.attr('params'); if(input!=window.monitter['text-'+input])
{window.monitter['last_id'+input]=0;window.monitter['text-'+input]=input;window.monitter['max']=3;window.monitter['count-'+input]=12; ;}
if(window.monitter['count-'+input]>10)
{window.monitter['count-'+input]=0;}
	if(from != undefined) {
	var filter = ((params != '')?'&filter='+params:'');
	$j.getJSON("http://ximosoft.com/portfolio/wp-content/plugins/monitor/api/twitter_fetch.php?from="+from+"&format=json"+filter,function (json) {	
	if(json.results != undefined && json.results.request== undefined) { 
		$j('div.tweet:gt('+window.monitter['limit']+')',elem).each(function(){
		$j(this).fadeOut('slow')});
		$j(json.results).reverse().each(
		function(){
		if($j('#tw'+this.id,elem).length==0){window.monitter['count-'+input]++; 
		var thedate=new Date(Date.parse(this.created_at)); 
		var verified = (this.user != undefined && this.user.verified==true)?" verified":" ";
		var thedatestr= $j.prettyDateEs(this.created_at); 
		var user = (this.user != undefined)?this.user.screen_name:this.from_user;
		var user_name = (this.user != undefined)?this.user.name:this.from_user;
		var url = (this.user != undefined)?this.user.url:"";
		var divstr='<div id="tw'+this.id+'" class="entry'+verified+'"><div class="thumbnail"><a href="http://twitter.com/'+user+'" target="_blank"><img width="48" height="48" src="'+((this.profile_image_url==undefined)?this.user.profile_image_url:this.profile_image_url)+'" ></a></div><div class="description"><span class="content"> <a href="http://twitter.com/'+user+'" target="_blank">'+user+': </a> '+((this.text==undefined)?"":this.text.linkify().linkuser().linktag())+'</div><span class="actions"><a title="reply to '+user+'" href="http://twitter.com/?status=@'+user+'%20&amp;in_reply_to_status_id='+this.id+'&amp;in_reply_to='+user+'" class="reply"> </a></span></span><span class="status"> &nbsp;<span class="date">'+thedatestr+'</span></div></div>';
		var divstr_short='<div id="tw'+this.id+'" class="entry'+verified+'"><div class="thumbnail"><span class="content"> '+((this.text==undefined)?"":this.text.linkify().linkuser().linktag())+'</div><span class="actions"><a title="reply to '+user+'" href="http://twitter.com/?status=@'+user+'%20&amp;in_reply_to_status_id='+this.id+'&amp;in_reply_to='+user+'" class="reply"> </a></span></span><span class="status"> &nbsp;<span class="date">Por '+user+' '+thedatestr+'</span></div></div>';
		window.monitter['last_id'+input]=this.id;elem.prepend(divstr);
		$j('#tw'+this.id,elem).hide();
		$j('#tw'+this.id+' img',elem).hide();
		$j('#tw'+this.id+' img',elem).fadeIn(4000);
		$j('#tw'+this.id,elem).fadeIn('slow');
		}});
		input=escape(input);
		$j('div.tweet:lt('+window.monitter['last_id']+')',elem).remove();

		
	}
	if(json.followers != undefined && json.followers.request== undefined) { 
		$j('div.tweet:gt('+window.monitter['limit']+')',elem).each(function(){
		$j(this).fadeOut('slow')});
		$j(json.followers).reverse().each(
		function(){
		if($j('#tw'+this.id,elem).length==0){window.monitter['count-'+input]++; 
		var verified = (this.verified==true)?" verified":" ";
		var protected = (this.protected==true)?" protected":" ";
		var datestr = (this.status!=undefined)?$j.prettyDateEs(this.status.created_at):"When?";
		var divstr='<div id="tw'+this.id+'" class="entry"><div class="thumbnail"><a href="http://twitter.com/'+this.screen_name+'" target="_blank" alt="'+this.name+'"><img width="48" height="48" src="'+this.profile_image_url+'"  ></a></div><a href="http://twitter.com/'+this.screen_name+'" target="_blank" alt="'+this.name+'"><strong>'+this.name+' </strong></a><span class="description">'+((this.status==undefined)?"":this.status.text.linkify().linkuser().linktag())+'</span><span class="status'+verified+protected+'"><span class="date">'+datestr+'</span><span class="friends">'+this.friends_count+'</span><span class="tweets"></span></span></div>';
		window.monitter['last_id'+input]=this.id;elem.prepend(divstr);
		}});
		input=escape(input);rrp=1;
	}
 
	}); 
  }
   
  return(false);
}

	
function refresh_tweets(counter,params){$j('.box > .box-body').each(function(e){rrp=6;fetch_tweets(this);}); 

$j.prettyDate = function(time){
	var date = new Date((time || "").replace(/-/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 "When?";
			
	return day_diff == 0 && (
			diff < 30 && "about half a minute" ||
			diff < 60 && "less than a minute ago" ||
			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";
}

$j.prettyDateEs = function(time){
	var date = new Date((time || "").replace(/-/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 "Cuando?";
			
	return day_diff == 0 && (
			diff < 30 && "hace medio minuto" ||
			diff < 60 && "hace menos de 1 minuto" ||
			diff < 120 && "hace 1 minuto" ||
			diff < 3600 && "hace "+ Math.floor( diff / 60 ) + " minutos" ||
			diff < 7200 && "hace 1 hora" ||
			diff < 86400 && "hace " + Math.floor( diff / 3600 ) + " horas") ||
		day_diff == 1 && "Ayer" ||
		day_diff < 7 && "hace " + day_diff + " dias" ||
		day_diff < 31 &&  "hace " + Math.ceil( day_diff / 7 ) + " semanas";
}

 
};	

jQuery.fn.sort = function() {  
  return this.pushStack( [].sort.apply( this, arguments ), []);  
};  
  
function sortAscending(a,b){  
	 return a.innerHTML > b.innerHTML ? 1 : -1;  
}; 
 
jQuery.fn.counter = function(params) {
	var self = this;

	self.display = $j(this);
	self.hour = params.hour?params.hour:"0";
	self.min = params.min?params.min:"0";
	self.sec = params.sec?params.sec:"0";
	self.hour_end = params.hour_end?params.hour_end:"0";
	self.min_end = params.min_end?params.min_end:"0";
	self.sec_end = params.sec_end?params.sec_end:"0";
	self.message = params.message?params.message:"FINISHED";
	self.delimiter = params.delimiter?params.delimiter:":";
	self.return_url = params.return_url?params.return_url:"";
	self.finish_function = params.finish_function?params.finish_function:"";
	self.interval = params.interval?params.interval*1000:"1000";
	self.iteration = params.iteration?params.iteration:"1";
	self.direction = params.direction?params.direction:"down";
	self.restart = params.restart?params.restart:false;
	
	self.timestamp = (self.hour * 60 * 60) + (self.min * 60) + (self.sec*1);
	self.timestamp_end = (self.hour_end * 60 * 60) + (self.min_end * 60) + (self.sec_end*1);
            
    self.onTick = params.onTick?params.onTick:function() { return true; };
    self.onFinish = params.onFinish?params.onFinish:function() { return true; };


	
	
	/** update the countdown while running **/
	self._updateCounter = function(params) {
		self.change_hour = params.change_hour?params.change_hour:"0";
		self.change_min = params.change_min?params.change_min:"0";
		self.change_sec = params.change_sec?params.change_sec:"0";
		self.change_direction = params.change_direction?params.change_direction:"up";
		self.hour = params.hour?params.hour:self.hour;
		self.min = params.min?params.min:self.min;
		self.sec = params.sec?params.sec:self.sec;
		self.hour_end = params.hour_end?params.hour_end:self.hour_end;
		self.min_end = params.min_end?params.min_end:self.min_end;
		self.sec_end = params.sec_end?params.sec_end:self.sec_end;
		self.message = params.message?params.message:self.message;
		self.delimiter = params.delimiter?params.delimiter:self.delimiter;
		self.return_url = params.return_url?params.return_url:self.return_url;
		self.finish_function = params.finish_function?params.finish_function:self.finish_function;
		self.interval = params.interval?params.interval*1000:self.interval;
		self.iteration = params.iteration?params.iteration:self.iteration;
		self.direction = params.direction?params.direction:self.direction;

		self.timestamp_end = (self.hour_end * 60 * 60) + (self.min_end * 60) + (self.sec_end*1);
		
		/** if we want to change the current countdown, there a two ways **/
		if(self.change_hour != 0 || self.change_min != 0 || self.change_sec != 0) {
			
			/** first, we can change the countdown with an specific time **/
			var temp_timestamp = self._createTimestamp(self.change_hour,self.change_min,self.change_sec);
			if(self.change_direction.match(/up/)) {
				self.timestamp += temp_timestamp;
			} else if(self.change_direction.match(/down/)) {
				self.timestamp -= temp_timestamp;
			} else {
				return;
			}
		} else {
			
			/** or we change the countdown to a specific time **/
			self.timestamp = (self.hour * 60 * 60) + (self.min * 60) + (self.sec*1);
		}
		return;
		
	};
	
	
	self._createTimestamp = function(hour,min,sec) {
		return (hour * 60 * 60) + (min * 60) + (sec*1)
	}

	/** get a counter from an timestamp **/
	self._getCounterFromTimestamp = function(t) {
		if (t > 0) {
			hours = Math.floor(t / 3600)
			minutes = Math.floor( (t / 3600 - hours) * 60)
	    	seconds = Math.round( ( ( (t / 3600 - hours) * 60) - minutes) * 60)
	    } else {
	        hours = 0;
	        minutes = 0;
	        seconds = 0;
	    }
	    
	    if (seconds == 60)  {
	    	seconds = 0;
	    }
	    
	    if(seconds == 0)  {
	    	if(hours != 0) 	{
	    		minutes = minutes/1 + 1;
	    	}
	    }
	    
	    if (minutes < 10)  {
	    	if (minutes < 0) {
	    		minutes = 0;
	    	}
		    minutes = '0' + minutes;
	    }
	    if (seconds < 10) {
	    	if (seconds < 0) {
	    		seconds = 0;
	    	}
	    	seconds = '0' + seconds;
	    }
	    
	    if (hours < 10) {
	    	if (hours < 0) {
	    		hours = 0;
	    	}
	    	hours = '0' + hours;
	    }
		
		if(hours > 0) {
		    return hours + self.delimiter + minutes + self.delimiter + seconds;
		} else {
			return minutes + self.delimiter + seconds;
		}
	};
       
    /** update the text for the countdown timer **/
    self._tick = function() {

    	if(self.timestamp > 0 && self.timestamp != self.timestamp_end) {
	    	var counter = self._getCounterFromTimestamp(self.timestamp);
	    	
	    	/** show the current time **/
	        self.display.html(counter);
	        
	        if(self.direction == "down") {
		        self.timestamp = self.timestamp*1 - self.iteration*1;
	        } else if(self.direction == "up") {
	        	self.timestamp = self.timestamp*1 + self.iteration*1;
	        } else {
	        	return;
	        }
    	} else {
    		window.clearInterval(self._interval);
            if (!self.onFinish(self.display)) { 
            	return;
            }
            
            /** display the finish message **/
            self.display.html(self.message);
            
            /** if there is a function to call, call it **/
            if(self.finish_function != "") {
            	eval(self.finish_function);
            }
            /** if there is a function to call, call it **/
            if(self.restart != false) {
            	self._restart();
            }
            
            /** if there is a return url, go there **/
            if(self.return_url != "") {
	            window.location.href = self.return_url;
            }
            return;
    	}
    };
    
    	/** restart **/
	self._restart = function() {
	    	self.timestamp = (self.hour * 60 * 60) + (self.min * 60) + (self.sec*1);
		self.timestamp_end = (self.hour_end * 60 * 60) + (self.min_end * 60) + (self.sec_end*1);
	    	self._interval = window.setInterval(self._tick,self.interval);
	};
	
    /** do it **/
    self._tick();
    self._interval = window.setInterval(
        self._tick,
        self.interval
        );

    return this;
};

$(document).ready(function(){
 window.monitter={};
 window.monitter['max']=10;

 var counter = $j("#counter").counter({sec:"20",min:"1", restart: true, message:"Go!", finish_function: "refresh_tweets()" });
 refresh_tweets();

 }); 
