/*
 * TwitStream - A jQuery plugin for the Twitter Search API
 * Version 1.2
 * http://kjc-designs.com/TwitStream
 * Copyright (c) 2009 Noah Cooper
 * Licensed under the GNU General Public License <http://www.gnu.org/licenses/>
*/

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){
		return '<a href="http://twitter.com/'+u.replace("@","")+'" title="'+u.replace("@","")+'" class="tweep">'+u+'</a>';
	});
};

String.prototype.linktag=function(){
	return this.replace(/[]+[A-Za-z0-9-_]+/,function(t){
		return t;
	});
};

//Variable que indica si muestra links
var showTweetLinks='none';
var cache = [];
var last_id = 0;
//Cantidad de tweets a levantar
var num = 4;
// Funcion para levantar por primera vez los tweets
function inicializarTweets()
{

	//URL para levantar los tweets desde twitter
	var url = "http://api.twitter.com/1/statuses/user_timeline/bilzypap.json?&count="+num+"&callback=?";
	//Se levantan los tweets para el listado de la izquierda.
	$.getJSON(url,function(json){
		//Ciclo para acceder a los tweets levantados. 
		$(json).each(function(){
			
			if(this.id > last_id){
				last_id = this.id;			
			}
			
			//Se crea un nuevo array con los datos del tweet
			nueva_posicion = new Array('id', 'created_at', 'user_name', 'screen_name', 'text', 'tweet_html');
			nueva_posicion['id'] = this.id;
			nueva_posicion['created_at'] = this.created_at;
			nueva_posicion['user_name'] = this.user.name;
			nueva_posicion['screen_name'] = this.user.screen_name;
			nueva_posicion['text'] = this.text.linkify();
			nueva_posicion['tweet_html'] = generarTweet(nueva_posicion);
			
			//Se agrega el array creado al array que contienen todos los tweets
			cache.push(nueva_posicion);
		});

		//Se limpia el array para no acumular muchos tweets. La cantidad max se pasa por parámetro (3)
		limpiarArray(cache, num);
			
		//Se muestra el listado
		mostrarListado();
	});
	
	return(false);
}

// Funcion para actualizar el listado de tweets
function actualizarTweets()
{
	
	//Variable que indica si hay nuevos tweets para mostrar
	var nuevos_tweets = 0;
	//Array que acumula los tweets
	var aux = new Array();
	
	//URL para levantar los tweets desde twitter
	var url = "http://api.twitter.com/1/statuses/user_timeline/bilzypap.json?&count="+num+"&callback=?";
	//Se levantan los tweets
	$.getJSON(url,function(data){
	
		//Ciclo para acceder a los tweets levantados. Ingresa solo si hay nuevos tweets para mostrar 
		$(data).each(function(){
			
			//Se verifica que tenga distinto id que el último. Sino carga otra vez el último.
			if(this.id != last_id){
			
				//Se indica que hay nuevos tweet para mostrar
				nuevos_tweets = 1;
				
				//Se guarda el mayor id de los tweets publicados para la próxima búsqueda
				if(this.id > last_id){
					last_id = this.id;			
				}

				//Se crea un nuevo array con los datos del tweet
				nueva_posicion = new Array('id', 'created_at', 'user_name', 'screen_name','text', 'tweet_html');
				nueva_posicion['id'] = this.id;
				nueva_posicion['created_at'] = this.created_at;
				nueva_posicion['user_name'] = this.user.name;
				nueva_posicion['screen_name'] = this.user.screen_name;
				nueva_posicion['text'] = this.text.linkify();
				nueva_posicion['tweet_html'] = generarTweet(nueva_posicion, 1);
				//Se agrega el array creado al array que contienen todos los tweets
				aux.push(nueva_posicion);
				
			}
				
		});
		
		//Se verifica si hay nuevos tweet para agregar
		if(nuevos_tweets==1){
			
			//Se cuentan las posiciones del array auxiliar
			var i = (aux.length)-1;
			
			while(i>=0){
				cache.unshift(aux[i]);
				i--;
			}
			
			//Se limpia el array para no acumular muchos tweets. La cantidad max se pasa por parámetro
			limpiarArray(cache, num);
			
			//Se limpia el div
			$("#tweets2").html('');
			
			//Se muestra el listado
			mostrarListado();
			
			//Se actualizan los tiempos de creación del listado
			actualizarTiempos();
			
		}else{
		
			//Si no hay nuevos tweets se actualizan los tiempos de creación del listado
			actualizarTiempos();
			
		}
	});
	
	return(false);
}

//Función que retorna el HTML del tweet
function generarTweet(array)
{

	//Se captura el tiempo de creación del tweet
	var v = array['created_at'].split(' ');
	var tTime = new Date(Date.parse(v[1]+" "+v[2]+", "+v[5]+" "+v[3]+" UTC"));
	
	//Se crea la variable con el tiempo actual
	var cTime = new Date();
	
	//Se calcula la diferencia entre la creación y el tiempo actual 
	var sinceMin = Math.round((cTime-tTime)/60000);
	
	//Se verifica la diferencia para agragar el texto a mostrar
	if(sinceMin==0)
	{
		var sinceSec=Math.round((cTime-tTime)/1000);
				
		if(sinceSec<10){
			var since='hace menos de 10 segundos';
		}else if(sinceSec<20){
			var since='hace menos de 20 segundos';
		}else{
			var since='hace 30 segundos';
		}
	}
	else if(sinceMin==1)
	{
		var sinceSec=Math.round((cTime-tTime)/1000);
		if(sinceSec==30){
			var since='hace 30 segundos';
		}else if(sinceSec<60){
			var since='hace menos de 1 minuto';
		}else{
			var since='hace 1 minuto';
		}
	}
	else if(sinceMin<45)
	{
		var since='hace '+sinceMin+' minutos';
	}
	else if(sinceMin>44&&sinceMin<60)
	{
		var since='hace 1 hora';
	}
	else if(sinceMin<1440)
	{
		var sinceHr=Math.round(sinceMin/60);
		if(sinceHr==1){
			var since='hace 1 hora';
		}else{
			var since='hace '+sinceHr+' horas';
		}
	}
	else if(sinceMin>1439&&sinceMin<2880)
	{
		var since='hace 1 día';
	}
	else
	{
		var sinceDay=Math.round(sinceMin/1440);
		var since='hace '+sinceDay+' días';
	}
	
	//Se arma el html del tweet
	var tweetBy='<label class="tweet-time" id="'+array['id']+'">'+since+'</label>'
	
	tweet='<div class="tweet2">';
	tweet+='<p class="text" id="'+array['id']+'">@'+array['screen_name']+' '+array['text']+'</p></div>';
	
	return tweet;
}

//Función que muestra el listado de tweets
function mostrarListado()
{
	
	var array_mostrar = cache;
	var id = "#tweets2";
	var id_tweet = ".tweet2";
	var id_tweet_first = ".tweet2:first";
	
	var cant = array_mostrar.length;
	var i=0;
	
	while(i < cant){
		
		//Se muestra el tweet
		$(id).append(array_mostrar[i]['tweet_html']);
		/*
		//Se verifca que sea más de 1 para mosrtar con efecto
		if(cant>1){
			//Se agregan con efecto slidedown
			if ($(id_tweet_first).is(":hidden")){
				$(id_tweet).slideDown("slow");
			}else{
				$(id_tweet).hide();
			}
		}*/
		i++;
	}
}

//Función que actualiza los tiempos de creación de los tweets
function actualizarTiempos()
{

	var array_mostrar = cache;

	var cant = array_mostrar.length;
	var i=0;

	while(i<cant){

		//Se calcula nuevamente el tiempo para asignar el texto correspondiente
		var v = array['created_at'].split(' ');
		var tTime = new Date(Date.parse(v[1]+" "+v[2]+", "+v[5]+" "+v[3]+" UTC"));
		var cTime = new Date();
		var sinceMin = Math.round((cTime-tTime)/60000);
				
		if(sinceMin==0){
			var sinceSec=Math.round((cTime-tTime)/1000);
					
			if(sinceSec<10){
				var since='hace menos de 10 segundos';
			}else if(sinceSec<20){
				var since='hace menos de 20 segundos';
			}else{
				var since='hace 30 segundos';
			}
		}else if(sinceMin==1){
			var sinceSec=Math.round((cTime-tTime)/1000);
			if(sinceSec==30){
				var since='hace 30 segundos';
			}else if(sinceSec<60){
				var since='hace menos de 1 minuto';
			}else{
				var since='hace 1 minuto';
			}
		}else if(sinceMin<45){
			var since='hace '+sinceMin+' minutos';
		}else if(sinceMin>44&&sinceMin<60){
			var since='hace 1 hora';
		}else if(sinceMin<1440){
			var sinceHr=Math.round(sinceMin/60);
			if(sinceHr==1){
				var since='hace 1 hora';	
			}else{
				var since='hace '+sinceHr+' horas';
			}
		}else if(sinceMin>1439&&sinceMin<2880){
			var since='hace 1 día';
		}else{
			var sinceDay=Math.round(sinceMin/1440);
			var since='hace '+sinceDay+' días';
		}
		
		//Se reemplaza el tiempo de creación
		document.getElementById(array_mostrar[i]['id']).innerHTML = since;
		
		i++;
	}
}

//Función que limpia el array para liberar recursos
function limpiarArray(array, maximo)
{

	var cant = array.length;
	
	//Se verifica si supera el máximo de tweets indicado por parámetro.	
	if(cant>maximo){
		
		var i=maximo;
		
		//Se eliminan las posiciones
		while(i<cant){
			array.pop();
			i++;
			
		}
		
	}

}

//Funcion que levanta la foto del usuario con la twitter search api
function buscar_foto(elem)
{
	var elem=$(elem);
	var url="http://search.twitter.com/search.json?q=@bilzypap&rpp=1&callback=?";
	$.getJSON(url,function(json){
		$(json.results).each(function(){
			var foto='<a href="http://twitter.com/'+this.user_name+'" class="tweep"><img width="48" height="48" alt="'+this.user_name+' on Twitter" src="'+this.profile_image_url+'" /></a>';
			elem.append(foto);
		});
	});
	return(false);
}

//Funcion para actualizar el twitSteam
function actualizar() 
{
	
	//Se ocualta la cuenta regresiva
	//$('#countdown').hide();
	
	var showTweetLinks='none';
		
	showTweetLinks=showTweetLinks.toLowerCase();
	
	if(showTweetLinks.indexOf('all')!=-1){
		showTweetLinks='reply,view,rt';
	}
	
	//Se actualizan los tweets
	actualizarTweets();
	
}

//Llamamos a la funcion que levanta los tweets por primera vez y a la que levanta la foto.
$(document).ready(function()
{
	
	showTweetLinks=showTweetLinks.toLowerCase();
	
	if(showTweetLinks.indexOf('all')!=-1){
		showTweetLinks='reply,view,rt';
	}
	
	$('#foto_pd').each(function(){
		buscar_foto(this);
	});
	
	inicializarTweets();
	
});

//Se setea el intervalo de tiempo para la actualización de los tweets
//setInterval('actualizar()',60000);
