    var array_tweets = Array();
    var last_id = 0;
    var setIntPointer; 
    var setIntPointerTimer;

	var whenPosted;
	var array_dates= Array();
	var http = getHTTPObject();
	var httpDate = getHTTPObject();
	var httpMessage=getHTTPObject();
	var httpPhoto = getHTTPObject();
	var httpReceived = getHTTPObject();

	var user_input_rad='';
	var buf_xml_photo='';
	var loaded= false;
	var logintudActual=0;
	var myFriends= Array();


	if ((readCookie("user_username") != null) && (readCookie('prefs_type')=="5"))
	{
		//alert('entro');

		var username = readCookie("user_username");
		var password = readCookie("user_password"); password=myUrlEncode(password);
		var url2='';
		//alert (username);
		url2 =getServerAddress() + '/operator.php?type=8&username=' + username + '&password=' + password ;
		httpPhoto = getHTTPObject();

		httpPhoto.open("GET", url2, true);
		httpPhoto.onreadystatechange = handleHttpResponsePhoto;
		httpPhoto.send(null);

	}

    //var pp=self.setInterval("stats()", 60*60*1000); NO ESTA EN USO

    function debug_script(msg)
    {
        //alert (document.getElementById("debug").value += msg + '\n');
    }

    function doLoad()
    {	

        debug_script('doLoad');

		//stats(); NO ESTA EN USO

        if (readCookie("user_username") != null)
        {
            validate_user(); 
            user_login(); 
        } else {
            validate_user(); 
            getNewData();  
       }

    }



function stats() //NO ESTA EN USO
{
	username = readCookie("user_username"); //alert(username);
    password = readCookie("user_password"); //alert(password); 
	
	password=myUrlEncode(password);

	if (username == null)
	{
		$('#statbox').html('');
		$('#statbox').append( 'Stats: Please login to see your stats ');

	}
	else 
	{ 
		
		var following='';
		var follower='';
		
		/*AJAX FOLLOWINGS*/
		$.ajax({
		type: "get",
		url: getServerAddress() + "/operator.php",
		contentType: "application/x-www-form-urlencoded",
			//async:false,
		data: 'type=7&username=' + username + '&password=' + password,
		success: function(datos){	
				following=$('users',datos).children().get().length;
				createCookie('following',following,1);
				//alert(following);
		
			
				/*AJAX FOLLOWERS*/
				$.ajax({
				type: "get",
				url: getServerAddress() + "/operator.php",
				contentType: "application/x-www-form-urlencoded",
				//async:false,
				data: 'type=8&username=' + username + '&password=' + password,
				success: function(datos){	
							follower=$('users',datos).children().get().length;
							createCookie('follower',follower,1);
							//alert(follower);
										
					
					
							follower=readCookie('follower');
							following=readCookie('following');


							//alert(follower);
							//alert(following);
							if ((follower == 0) || (following==0))
							{
								$('#statbox').html('');
								eraseCookie('follower');
								eraseCookie('following');
								$('#statbox').append( 'Stats: Unfortunately you\'ve exceeded Twitter\'s maximum hourly requests, please check back in a bit. ');

							}
							else {
									$('#statbox').html('');
									$('#statbox').append( "Stats: <a href='http://twitter.com/friends' target='blank'>" + following + " Following</a> | <a href='http://twitter.com/followers' target='blank'>" + follower +" Followers</a>");
	
								 }
					
					
					}
				
				}); //end ajax

				
			
			}
		}); //end ajax

		

		
	}//end else

}
  
 function getNewData() //FUNCIONA
    {
		
		debug_script('getNewData'); 

		//alert(readCookie('prefs_type'));

        //user_input_rad = "";
        var username = "";
        var password = "";

        //VERIFY WHICH RADIO IS CLICKED
        user_input_rad =1;
        if (document.frm_prefs.radType[0].checked == true)
        {
            //PUBLIC TIMELINE
    		user_input_rad =1;
            username = readCookie("user_username");
                 
            if (username == null){ username = '';}

        } else {
            //FRIENDS TIMELINE OR D MESSAGE OR @ MESSAGE
            username = readCookie("user_username");
            password = readCookie("user_password"); password=myUrlEncode(password);

			 if (document.frm_prefs.radType[1].checked == true) //FRIEND
			{
				 user_input_rad =2;
			} else { 
					 if (document.frm_prefs.radType[2].checked == true) // D
					{
						 user_input_rad =5;
					} else {
							 if (document.frm_prefs.radType[3].checked == true) //@
							{
								 user_input_rad =6;
							}
					}
					
			}

        }




    url =getServerAddress() + "/operator.php?type=" + user_input_rad + '&username=' + username + '&password=' + password;
        debug_script(url);

	//alert (url);
    http = getHTTPObject();

	http.open("GET", url, true);
	http.onreadystatechange = handleHttpResponseGetNewData;
	http.send(null);


    }


function handleHttpResponseGetNewData() //FUNCIONA
{
	/*	0 = uninitialized --->onFailure: NADA
	1 = loading --->onRequest:
	2 = loaded ---->onComplete: NADA
	3 = interactive
	4 = complete ---->onSuccess:*/ 

		if (http.readyState == 4) //estado 4 es listo
		{
			xml_data=http.responseXML;
			//alert (http.responseText);
			
			//alert(user_input_rad ==5);
			if (user_input_rad ==5)
			{cargarFechas (xml_data.getElementsByTagName("direct_message"));}
			else {
			cargarFechas (xml_data.getElementsByTagName("status"));

			}

		}
		if (http.readyState == 1) //estado 1 es cargando
		{
			hide_logout();
			show_loading("fetching");
		

		}
}

function getHTTPObject() //FUNCIONA
{
		var xmlhttp;
		if (window.ActiveXObject) //IE
		{
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
			

		}
		else
			if (window.XMLHttpRequest) //MOZILLA
			{
				xmlhttp=new XMLHttpRequest()

			}

		return xmlhttp;
}


function show_loading(msg)//FUNCIONA
{
        debug_script('showloading');
        var div_loading;

        if (msg == "")
            msg = "loading";

        div_loading = document.getElementById("div_loading");
        div_loading.innerHTML = msg;
		div_loading.style.visibility = "";
}
    
function hide_loading()//FUNCIONA
{
        debug_script('hideloading');
        var div_loading;
        div_loading = document.getElementById("div_loading");
		div_loading.style.visibility = "hidden";
}


   

function update_tweets(xml_data) //FUNCIONA
{
        debug_script('updatetweets');
    	var table = document.getElementById("tweet_table");
        var index_linha = -1;
        noOfRows = table.rows.length;
        for (i = 0 ; i < noOfRows ; i++)
        {
            table.deleteRow(0);
        }
		
		var ppp=xml_data.getElementsByTagName("error");
	
		//if (ppp[0].firstChild) {ppp[0].firstChild.nodeValue;});
		//alert(ppp[0]);

		if (ppp[0]!= null)
		{
			var table = document.getElementById("tweet_table");
            var index_linha = -1;
            noOfRows = table.rows.length;
            var new_row = table.insertRow(0);
            generated_innerHTML = '<br><br><strong><div align=center>Unfortunately you\'ve exceeded Twitter\'s maximum hourly requests.<br><br>Please check back in a bit.</div></strong>';
    		cell_instance = new_row.insertCell(0);
    		cell_instance.innerHTML = generated_innerHTML;
		}
		
		
		if (!xml_data)
        //if (raw_data.length == 0)
        {	
        	var table = document.getElementById("tweet_table");
            var index_linha = -1;
            noOfRows = table.rows.length;
            var new_row = table.insertRow(0);
            generated_innerHTML = '<br><br><strong><div align=center>Twitter\'s API servers are not responding at the moment.<br><br>Please hit refresh, or try again in a few minutes.</div></strong>';
    		cell_instance = new_row.insertCell(0);
    		cell_instance.innerHTML = generated_innerHTML;
        } else {
			
			if (user_input_rad ==5)
			{
				update_tweets_d_array(xml_data);
			}
			else update_tweets_array(xml_data);


            update_tweets_html();//
            validate_user();//
            hide_loading();//
        }
}
   
function update_tweets_html()//FUNCIONA
{
		
        debug_script('updatetweetshtml');

		//alert(array_tweets.length);
		

        for (i = array_tweets.length - 1 ; i >= 0 ; i--)
        {
            if (i % 2 == 0)
                tweet_class = "1";
            else
                tweet_class = "2";

            add_tweet(tweet_class, array_tweets[i][0] , array_tweets[i][1] , array_tweets[i][2] , array_tweets[i][3] , array_tweets[i][4]);
        }
		/*this new row on the table, was added to fix xpi error, all links on first row didnt open on new tabs, 
		because that row wasnt excecuted by the xpi, so adding a new hidden row we fix the problem*/
		var table = document.getElementById("tweet_table");
		var new_row = table.insertRow(0);
			new_row.style.display="none";
			cell_instance = new_row.insertCell(0);
			cell_instance.innerHTML = "";
		

}


function add_tweet(tweet_class , id , created_at , text , profile_image_url , screen_name) //FUNCIONA
{
        debug_script('addtweet');
    	var table = document.getElementById("tweet_table");
        var index_linha = -1;

        noOfRows = table.rows.length; //alert(noOfRows);

        var new_row = table.insertRow(0);
        new_row.id = "tr_" + id;
 

        var html_template  = '';
        html_template += '          <div class="tweet' + tweet_class + '">';
        html_template += '          <a href="http://www.twitter.com/##screen_name##" target="blank" title="##screen_name##\'s twitter"><img width=24 height=24 src="##profile_image_url##" border=0 alt="pic" align="left" /></a><a href="http://www.twitter.com/##screen_name##" target="blank" title="##screen_name##\'s twitter">##screen_name##</a> ##text##';
		html_template += '          </div>';


        generated_innerHTML = html_template;
        generated_innerHTML = generated_innerHTML.replace("##id##",id);
        generated_innerHTML = generated_innerHTML.replace("##created_at##",created_at);
        generated_innerHTML = generated_innerHTML.replace("##text##",text);
        generated_innerHTML = generated_innerHTML.replace("##profile_image_url##",profile_image_url);
        generated_innerHTML = generated_innerHTML.replace(/##screen_name##/g,screen_name);



		/*ESTO*/

		cell_instance = new_row.insertCell(0);
		cell_instance.innerHTML = generated_innerHTML; //alert(cell_instance.innerHTML);
		$(cell_instance).find('span.arroba').bind(
				'click', 
				function(){
					document.getElementById('tweet').value="@" + screen_name + " ";
					document.getElementById('tweet').focus();
					return false;
				}
			);

		/*$(cell_instance).find('span.direct').bind(
				'click', 
				function(){
					document.getElementById('tweet').value="D " + screen_name  + " ";
					document.getElementById('tweet').focus();
					return false;
				}
			);*/


}

function update_tweets_d_array(xml_data)
{
		debug_script('updatetweetsDarray');
        var tweets_list = "";
        tweets_collection = xml_data.getElementsByTagName("direct_message");

		var dates= getDates(); 

		var photo=getPhoto(); //alert(photo);

        array_tweets = Array();
		var i=0;
        for (i = 0 ; i < tweets_collection.length ; i++)
        {

				if (window.ActiveXObject) 
				{
					//GET TWEET DATA---------------->//IE

					id = tweets_collection[i].childNodes[2].firstChild.nodeValue; //alert (id.slice(8, 10));
					created_at = tweets_collection[i].childNodes[1].firstChild.nodeValue; //alert(created_at);
					text = tweets_collection[i].childNodes[1].firstChild.nodeValue; //alert(text);
					screen_name = tweets_collection[i].childNodes[5].firstChild.nodeValue; //alert (screen_name);

				}
				else
					if (window.XMLHttpRequest)
					{
						//GET TWEET DATA----------------> //mozilla
						id = tweets_collection[i].childNodes[9].firstChild.nodeValue; //alert (id.slice(11,19));
						created_at = tweets_collection[i].childNodes[5].firstChild.nodeValue; //alert(created_at);
						
						text = tweets_collection[i].childNodes[3].firstChild.nodeValue; //alert(text);
						screen_name = tweets_collection[i].childNodes[11].firstChild.nodeValue; //alert (screen_name);

					}
			
			var link='';
			var linkAux='';//alert(photo.length);
			for (j=0; j < photo.length ; j++ )
			{
				if (window.ActiveXObject) 
				{
					if (screen_name == photo[j].childNodes[2].firstChild.nodeValue)
					{
						profile_image_url=photo[j].childNodes[5].firstChild.nodeValue;
						if(photo[j].childNodes[6].firstChild) {link=photo[j].childNodes[6].firstChild.nodeValue;}

					}
				}	
				else
					if (window.XMLHttpRequest)
					{
						if (screen_name == photo[j].childNodes[5].firstChild.nodeValue)
						{
							profile_image_url=photo[j].childNodes[11].firstChild.nodeValue;
							if(photo[j].childNodes[13].firstChild) {link=photo[j].childNodes[13].firstChild.nodeValue;}

						}
					}

			}

			if (link!='')
			{
					
			    linkAux= '<span> - <a href="' + link +'" target="_content" style="text-decoration:none;">W</a></span>';
			}
			
		var linkArroba="";

		if (readCookie("user_username") != null)
		{	
			linkArroba="<span class='arroba'/><a href='#' style='text-decoration:none;'>@</a></span>";
		
		}

		var linkDirect="";

		/*ESTO*/
		/*var linkDirect="<span class='direct'/> - <a href='#' style='text-decoration:none;'>D</a></span>";

		if (myFriends.indexOf(screen_name)== -1)
		{
			linkDirect="";
		}*/

			//PARSE TEXT TO MAKE LINKS CLICABLE

			text=convertToLink("http://", text);
			text=convertToLink("https://", text);


           /* start_pos = text.indexOf("http://");
            if (start_pos >= 0)
            {
                end_pos = text.indexOf(" ", start_pos + 1);
                if (end_pos == -1)
                    end_pos = text.length;

                var new_link = text.substring(start_pos, end_pos);
                newtext = text.substring(0, start_pos) + '<a href="' + new_link + '" target="_content">link »</a>' + text.substring(end_pos);
                text = newtext;
            }*/
			
			
			text=  '<span >(' + linkArroba  + linkDirect  +  linkAux+ '): </span>' + text + '<span style="color:#003399">'+  ' ' + dates[i] + '</span>';// ---> Global var that has all times
			//text=  '<span >' + linkAux + ' </span>' + text + '<span style="color:#003399">'+  ' ' + dates[i] + '</span>';// ---> Global var that has all times

            array_tweets[i] = Array(id , created_at , text , profile_image_url , screen_name);
        }
}

function convertToLink(str, text)
{ //ESTA FUNCION LO QUE HACE ES CONVERTIR LOS LINKS CON TEXTO EXPLICITO EN LINK>>

			var indice=1; var noTermino=false; var inicio=0; var cantidad=0; var newtext='';
			var anterior=0; var e=''; var s='';
			while (noTermino==false)
			{
			
			
				var s = text.indexOf(str, inicio);
				if (s >= 0)
				{	//alert(s);
					e = text.indexOf(" ", s + 1);
					if (e != -1) //no termino el texto
					{
						
						indice++;
						
					}
					else {noTermino=true;}

					cantidad++;
					if (e==-1) //si no encontre a ninguno mas y es justo termina el texto
					{
						//alert('es -1');
						var new_link = text.substring(s, text.length); //alert(new_link);

						newtext = newtext + text.substring(anterior, s) + '<a href="' + new_link + '" target="_content">link »</a>';
						
					}
					else {	
							var new_link = text.substring(s, e); //alert(new_link);
							if (anterior==0) //es el primero
							{
								newtext = newtext + text.substring(0, s) + '<a href="' + new_link + '" target="_content">link »</a>';
								
							}
							else {
						/**/	newtext = newtext + text.substring(anterior, s) + '<a href="' + new_link + '" target="_content">link »</a>';
								
						
							}
							anterior=e;
						}
					
					inicio=e; //o e +1
				}
				else {noTermino=true;}
				
			}
			
			if (((e!=text.length) && (e != '')) && (e!= -1))
			{
				newtext = newtext + text.substring(e, text.length)
			}

			if (cantidad!=0)
			{
				return newtext;
				//alert(cantidad);
			}
			else {return text;}

			

}

function arrobaLink(text)
{

			/**/

			var indice=1; var noTermino=false; var inicio=0; var cantidad=0; var newtext=''; var aux="";
			var anterior=0; var e=''; var s='';
			while (noTermino==false)
			{
			
			
				s = text.indexOf("@", inicio);
				if (s >= 0)
				{						
					if ((((text.substring(s-1, s)).charCodeAt(' ')=="32") || (text.substring(s-1, s) =='')))
					{
					
					
						e = text.indexOf(" ", s + 1);
						if (e != -1) //no termino el texto
						{
							indice++;
						}
						else {noTermino=true;}

						cantidad++;
						if (e==-1) //si no encontre a ninguno mas y es justo termina el texto
						{
						
							var new_link = text.substring(s+1, text.length); //alert(new_link.substring(new_link.length-1, new_link.length));
						
							//alert(new_link.split(/[\W]+/));

							/**/

							var car=new_link.substring(new_link.length-1, new_link.length);
							var ok3=false;
							var u=0; var ini=0; var fin=1; 
							var emp=0; var term=0;
							if (car.search( /[\W]+/) >= 0)
							{
								
								while ((ok3==false) && (u < new_link.length))
								{
									if ((new_link.substr(ini, fin)).search( /[\W]+/) >=0) 
									{ emp= ini; term=fin; ok3=true;}
									else {
										ini++; term++; u++;
									}
								}
							}

							if (car.search( /[\W]+/) == -1)
								{
									
									newtext = newtext + text.substring(anterior, s) + '@<a href="http://twitter.com/' + new_link + '" target="_content">'+new_link+'</a>';
								}
								else {//si hay algun caracter especial
										newtext = newtext + text.substring(anterior, s) + '@<a href="http://twitter.com/' + new_link.substr(0, ini) + '" target="_content">'+new_link.substr(0, ini)+'</a>' + new_link.substr(ini, fin);
								}

							/**/

							
						}
						else {	
								var new_link = text.substring(s+1, e);
								

								/**/
								var car=new_link.substring(new_link.length-1, new_link.length);
							
								var ok3=false;
								var u=0; var ini=0; var fin=1; 
								var emp=0; var term=0;
								if (car.search( /[\W]+/) >= 0)
								{
								
									while ((ok3==false) && (u < new_link.length))
									{	
										if ((new_link.substr(ini, fin)).search( /[\W]+/) >=0) 
										{ emp= ini; term=fin; ok3=true;}
										else {
											ini++; term++; u++;
										}
									}
								}
								/**/
								if (anterior==0) //es el primero
								{
									if (car.search( /[\W]+/) == -1)
									{
										newtext = newtext + text.substring(0, s) + '@<a href="http://twitter.com/' + new_link + '" target="_content">'+new_link+'</a>';
									}
									else {//si hay algun caracter especial
											newtext = newtext + text.substring(0, s) + '@<a href="http://twitter.com/' + new_link.substr(0, ini) + '" target="_content">'+new_link.substr(0, ini)+'</a>' + new_link.substr(ini, fin);
									}
								}
								else {

										if (car.search( /[\W]+/) == -1)
										{
											newtext = newtext + text.substring(anterior, s) + '@<a href="http://twitter.com/' + new_link + '" target="_content">'+new_link+'</a>';
										}
										else { //si hay algun caracter especial
											newtext = newtext + text.substring(anterior, s) + '@<a href="http://twitter.com/' + new_link.substr(0, ini) + '" target="_content">'+new_link.substr(0, ini)+'</a>' + new_link.substr(ini, fin);
										}							
								}
								anterior=e; 
						}
					
						inicio=e; //o e +1
					}else{
							aux=e; //dir del ultimo pedacito de texto
							e = text.indexOf(" ", s + 1); 
							if (e!= -1){
											if (text.indexOf("@", s+1)==-1) //no hay mas arrobas
											{
												newtext = newtext + text.substring(inicio, e);
											} 

											inicio=e;
							}else{e=aux; noTermino=true;}
						 }
				
				}//end if (s>=0)
				else{
					//si s no es mayor o igual a 0 es que es =-1
						
						if (s == -1)
						{
								noTermino=true;
						}
				
				}//end else 

		
				/* if (s == -1)
				{
					noTermino=true;
				}*/

			}//end while
			
			if (((e!=text.length) && (e != '')) && (e!= -1))
			{
				newtext = newtext + text.substring(e, text.length)
			}
			
			//alert(cantidad);
			if (cantidad!=0)
			{
				return newtext;
				//alert(cantidad);
			}
			else {return text;}

			/**/

}

function update_tweets_array(xml_data)//FUNCIONA
{
        debug_script('updatetweetsarray');
        var tweets_list = "";
        tweets_collection = xml_data.getElementsByTagName("status");


		dates= getDates(); 


        array_tweets = Array();
		var i=0;
        for (i = 0 ; i < tweets_collection.length ; i++)
        {

				if (window.ActiveXObject) 
				{
					//GET TWEET DATA---------------->//IE

					id = tweets_collection[i].childNodes[0].firstChild.nodeValue; //alert (id.slice(8, 10));
					created_at = tweets_collection[i].childNodes[1].firstChild.nodeValue; //alert(created_at);
					text = tweets_collection[i].childNodes[2].firstChild.nodeValue; //alert(text);
				}
				else
					if (window.XMLHttpRequest)
					{
						//GET TWEET DATA----------------> //mozilla
						id = tweets_collection[i].childNodes[1].firstChild.nodeValue; //alert (id.slice(11,19));
						created_at = tweets_collection[i].childNodes[3].firstChild.nodeValue; //alert(created_at);
						
						text = tweets_collection[i].childNodes[5].firstChild.nodeValue; //alert(text);

					}


            var link='';
			var linkAux='';
			if (window.ActiveXObject)             
			{
				//GET USER DATA in IE			
				user_data = tweets_collection[i].getElementsByTagName("user");
				screen_name = user_data[0].childNodes[2].firstChild.nodeValue; //alert (screen_name);
				profile_image_url = user_data[0].childNodes[5].firstChild.nodeValue; //alert (profile_image_url);
				if(user_data[0].childNodes[6].firstChild) {link=user_data[0].childNodes[6].firstChild.nodeValue;}
				
			}
			else
				if (window.XMLHttpRequest)
				{
				
				 //GET USER DATA in en MOZILLA
				 user_data = tweets_collection[i].getElementsByTagName("user");
				 screen_name = user_data[0].childNodes[5].firstChild.nodeValue; //alert (screen_name);
				 profile_image_url = user_data[0].childNodes[11].firstChild.nodeValue; //alert (profile_image_url);
				 if(user_data[0].childNodes[13].firstChild) {link=user_data[0].childNodes[13].firstChild.nodeValue;}

				}
			
			if (link!='')
			{
					
			    linkAux= '<span><a href="' + link +'" target="_content" style="text-decoration:none;">W</a></span>';
			}

		var linkArroba="";

		if (readCookie("user_username") != null)
		{	
			linkArroba="<span class='arroba'/><a href='#' style='text-decoration:none;'>@</a></span>";
		
		}
				
		var linkDirect="";

		/*ESTO*/
		/*var linkDirect="<span class='direct'/> - <a href='#' style='text-decoration:none;'>D</a></span>";
		
		if ((readCookie("user_username") == null) || (myFriends.indexOf(screen_name)== -1))
		{linkDirect="";}*/

		




			 //PARSE TEXT TO MAKE LINKS CLICABLE 5px

			text=convertToLink("http://", text);
			text=convertToLink("https://", text);
			text=arrobaLink(text);

			
            /*start_pos = text.indexOf("http://"); //alert(start_pos);
            if (start_pos >= 0)
            {
                end_pos = text.indexOf(" ", start_pos + 1); //busca el primer blanco a partir de http
                if (end_pos == -1)
                    end_pos = text.length;

                var new_link = text.substring(start_pos, end_pos); //saco address
                newtext = text.substring(0, start_pos) + '<a href="' + new_link + '" target="_content">link »</a>' + text.substring(end_pos);
                text =newtext;
            }*/

			if (((linkArroba=="") && (linkAux=="")) &&(linkDirect==""))
			{
				
				text= '<span>' + linkArroba + linkDirect + linkAux+ ': </span>'+text + '<span style="color:#003399">' + ' ' + dates[i] + '</span>';// ---> Global var that has all times
				
			}
			else{

				if (((linkArroba !="") && (linkAux=="")) || ((linkArroba=="") && (linkAux!="")))
				{
					text= '<span>(' + linkArroba + linkDirect + linkAux+ '): </span>'+text + '<span style="color:#003399">' + ' ' + dates[i] + '</span>';// ---> Global var that has all times

				}
				else {
					 if ((linkArroba !="") && (linkAux!=""))
					 {
						 text= '<span>(' + linkArroba + ' - ' + linkDirect + linkAux+ '): </span>'+text + '<span style="color:#003399">' + ' ' + dates[i] + '</span>';// ---> Global var that has all times

					 }

				}
			}
			
			//alert(dates[i]);
			//text= '<span>(' + linkArroba + linkDirect + linkAux+ '): </span>'+text + '<span style="color:#003399">' + ' ' + dates[i] + '</span>';// ---> Global var that has all times

            array_tweets[i] = Array(id , created_at , text , profile_image_url , screen_name);
        }
        
    }


function month (month)
{
switch (month)
{
case 'Jan': return '01'; break;
case 'Feb': return '02'; break;
case 'Mar': return '03'; break;
case 'Apr': return '04'; break;
case 'May': return '05'; break;
case 'Jun': return '06'; break;
case 'Jul': return '07'; break;
case 'Aug': return '08'; break;
case 'Sep': return '09'; break;
case 'Oct': return '10'; break;
case 'Nov': return '11'; break;
case 'Dec': return '12'; break;

}
}



function cargarFechas (tweets_collection)
{	var i =0;
	var string_dates='';
	var senders_names='';
	var user_data='';

	// ID has created_At information
	
	if (user_input_rad !=5)
	{
	
		for (i = 0 ; i < tweets_collection.length; i++)
		 {
			if (window.ActiveXObject) 
			{
				//GET TWEET DATA---------------->//IE
	
				id = tweets_collection[i].childNodes[0].firstChild.nodeValue; //alert (id.slice(8, 10));
				
				user_data = tweets_collection[i].getElementsByTagName("user"); //IE7
				sender_screen_name = user_data[0].childNodes[2].firstChild.nodeValue; 

			}
			else
				if (window.XMLHttpRequest)
					{
						//GET TWEET DATA----------------> //mozilla
						id = tweets_collection[i].childNodes[1].firstChild.nodeValue; //alert (id);

						user_data = tweets_collection[i].getElementsByTagName("user"); //mozilla
						sender_screen_name = user_data[0].childNodes[5].firstChild.nodeValue; 
						//alert(sender_screen_name);
					}

			string_dates=string_dates + id.slice(26, 30)+ '-' + month(id.slice(4, 7)) + '-'+ id.slice(8, 10) + ' ' + id.slice(11,19) + ' ';
			senders_names=senders_names + sender_screen_name + '*';

		}//end for


	} else { //IF THERE ARE D_MESSAGE
				//alert(tweets_collection.length);
				for (i = 0 ; i < tweets_collection.length; i++)
				{
					if (window.ActiveXObject) 
					{
						//GET TWEET DATA---------------->//IE
	
						id = tweets_collection[i].childNodes[4].firstChild.nodeValue; //alert (id);
						sender_screen_name = tweets_collection[i].childNodes[5].firstChild.nodeValue; //IE7;

					}
					else
						if (window.XMLHttpRequest)
						{
							//GET TWEET DATA----------------> //mozilla
							id = tweets_collection[i].childNodes[9].firstChild.nodeValue; //alert (id);
							sender_screen_name = tweets_collection[i].childNodes[11].firstChild.nodeValue; //mozilla;

						}

					string_dates=string_dates + id.slice(26, 30)+ '-' + month(id.slice(4, 7)) + '-'+ id.slice(8, 10) + ' ' + id.slice(11,19) + ' ';
					senders_names=senders_names + sender_screen_name + '*';

				}//end for
				
	}//end else
	
	if ((readCookie("user_username") != null) && ((user_input_rad ==5) || (user_input_rad ==6)))
	{

		url2 =getServerAddress() + '/storeMessage.php?created=' + string_dates + '&senders=' + senders_names + '&count=' + i;
		httpReceived = getHTTPObject();

		httpReceived.open("GET", url2, true);
		httpReceived.onreadystatechange = handleHttpResponseStoreMessage;
		httpReceived.send(null);
	}


	if (readCookie("user_username") != null)
	{

		var username = readCookie("user_username");
		var password = readCookie("user_password"); password=myUrlEncode(password);
		var url2='';
		//alert (username);
		url2 =getServerAddress() + '/operator.php?type=8&username=' + username + '&password=' + password ;
		httpPhoto = getHTTPObject();

		httpPhoto.open("GET", url2, true);
		httpPhoto.onreadystatechange = handleHttpResponsePhoto;
		httpPhoto.send(null);
	}
	
	url = getServerAddress() + '/dates.php?created=' + string_dates + '&count=' + i;
	httpDate = getHTTPObject();

	httpDate.open("GET", url, true);
	httpDate.onreadystatechange = handleHttpResponseText;
	httpDate.send(null);

}

function handleHttpResponseStoreMessage()

{
	//do nothing, php only inserts new message received today
	//alert (httpReceived.responseText);
}


function getPhoto()
{
	return buf_xml_photo;
}

function setPhoto(xml_photo)
{
	buf_xml_photo=xml_photo;

	for (j=0; j < buf_xml_photo.length ; j++ )
	{
		if (window.ActiveXObject) 
		{
				myFriends[j]=buf_xml_photo[j].childNodes[2].firstChild.nodeValue
					
		}	
		else
		{
			if (window.XMLHttpRequest)
			{
				myFriends[j]=buf_xml_photo[j].childNodes[5].firstChild.nodeValue
					
			}
		}
		//alert (myFriends[j]);
	}
}

function handleHttpResponsePhoto()
{

		if (httpPhoto.readyState == 4) //estado 4 es listo
		{
				xml_photo=httpPhoto.responseXML.getElementsByTagName('user');
			    setPhoto(xml_photo);
				//alert (httpPhoto.responseText);
		}
}

function setDates (dates)
{
		array_dates=dates;
}

function getDates ()
{
		return array_dates;
}

function handleHttpResponseText()
{
	/*	0 = uninitialized --->onFailure: NADA
	1 = loading --->onRequest:
	2 = loaded ---->onComplete: NADA
	3 = interactive
	4 = complete ---->onSuccess:*/ 

		var i=0;
		if (httpDate.readyState == 4) 
		{   dates= new Array();
			
			xml_data=http.responseXML; //alert(http.responseText);
			whenPosted=httpDate.responseXML.getElementsByTagName("date");

			//global array
			for (i = 0 ; i < whenPosted.length ; i++)
			 {

				if (window.ActiveXObject) 
				{
					//GET date DATA---------------->//IE

					dates[i] = whenPosted[i].childNodes[0].nodeValue; //alert (id.slice(8, 10));
				}
				else
					if (window.XMLHttpRequest)
					{
						//GET date DATA----------------> //mozilla
						dates[i] = whenPosted[i].childNodes[0].nodeValue; //alert (id.slice(11,19));
					}
			}//end for

			//alert(http.responseText);
			setDates (dates); //alert(dates);
			update_tweets(xml_data); 
			hide_loading(); 

		}//end if


} //end function

function readCookie(name) //FUNCIONA
{
        debug_script('readCookie');
    	var nameEQ = name + "=";
    	var ca = document.cookie.split(';');
    	for(var i=0;i < ca.length; i++) {
    		var c = ca[i];
    		while (c.charAt(0)==' ') {c = c.substring(1, c.length);}
			
    		if (c.indexOf(nameEQ) == 0) {
												
											//return c.substring(nameEQ.length, c.length);
											if ((name=="user_password") || (name=="user_username"))
											{ 
												var value= c.substring(nameEQ.length, c.length);
												//alert( myUrlDecode(value));
												return myUrlDecode(value);
											}
											else {return c.substring(nameEQ.length, c.length);}
											
										}
    	}
    	return null;
}

function validate_user() //FUNCIONA
{
        debug_script('validateuser');
        //SET THE TIME TO CONSTANTLY RETRIEVE THE TWEETS
		//alert(readCookie("prefs_reload_time"));
        if (readCookie("prefs_reload_time") != null)
        {
            prefs_reload_time = readCookie("prefs_reload_time");

            if (prefs_reload_time == 3)
                Index = 0;
			if (prefs_reload_time == 5)
                Index = 1;
            if (prefs_reload_time == 10)
                Index = 2;
			if (prefs_reload_time == 30)
                Index = 3;
			if (prefs_reload_time == 45)
                Index = 4;

            document.frm_prefs.reload_time.selectedIndex = Index;
        }
        else
        {
            prefs_reload_time = 5;
            document.frm_prefs.reload_time.selectedIndex = 1;
        }

        self.clearInterval(setIntPointer);
        setIntPointer = self.setInterval("getNewData()", prefs_reload_time * 60 * 1000);

		//SELECT HIS TWEET VIEW OPTION BASED ON HIS COOKIE
        
		//alert(readCookie('prefs_type'));
		/*joya, me tira el correcto*/
		switch (readCookie('prefs_type'))
		{
			case "1": document.frm_prefs.radType[0].checked = true; //PUBLIC
					break;
			case "2": document.frm_prefs.radType[1].checked = true; //FRIEND
					break;
			case "5": document.frm_prefs.radType[2].checked = true; //D
					break;
			case "6": document.frm_prefs.radType[3].checked = true; //@
					break;
			//SI NO HAY NADA EN LA COOKIE, PONER POR DEFAULT EL DE AMIGOS

			default: document.frm_prefs.radType[0].checked = true; //PUBLIC
					break;


		}

        //VERIFY HIS COOKIE TO SE IF HIS IS LOGGED IN
        //IF HE IS NOT LOGGED IN THEN DISABLE THE SECOND RADIO
        //AND SELECT THE FIRST
        if (readCookie("user_username") != null)
        {
            document.frm_prefs.radType[1].disabled = false; //FRIEND
			document.frm_prefs.radType[2].disabled = false; //D 
			document.frm_prefs.radType[3].disabled = false; //@
            document.frm_login.txtUsername.value = readCookie("user_username");
            document.frm_login.txtPassword.value = readCookie("user_password");
			
            show_logout(); 
            return 1;
        } else {
            document.frm_prefs.radType[1].disabled = true; //FRIEND
			document.frm_prefs.radType[2].disabled = true; //D 
			document.frm_prefs.radType[3].disabled = true; //@
            document.frm_prefs.radType[0].checked = true; //PUBLIC
            document.frm_login.txtUsername.value = "";
            document.frm_login.txtPassword.value = "";

            return 0;
        }

}


function hide_logout() //FUNCIONA
{
        var div_logout;
        div_logout = document.getElementById("div_logout");
		div_logout.style.visibility = "hidden";
}

////////////////////////////////////////////////Login////////////////////

function show_login()
{
        hide_prefs();
        var div_login;
        div_login = document.getElementById("div_login");
		div_login.style.visibility = "";
}


function hide_prefs()
{
        var div_prefs;
        div_prefs = document.getElementById("div_prefs");
		div_prefs.style.visibility = "hidden";
}
    

function user_login()
{

        debug_script('userlogin');

        //VALIDATES USER ON TWITTERS ON SITE MAKING A REQUEST FOR THE
        //THE USERS FRIENDS TIMELINE

        //ON FAILURE
        //- ALERTS THE USERS THAT THE COMBINATION USERNAME/PASSWORD IS INVALID
        
        //ON SUCCESS
        //- CREATES THE USERNAME/PASSWORD COOKIE
        //- REFRESHES USERS PERMISSIONS ON PAGE

        var username = document.frm_login.txtUsername.value;
        var password = document.frm_login.txtPassword.value; password=myUrlEncode(password);

        if (username == "")
        {
            alert("Please fill in your username");
            document.frm_login.txtUsername.focus();
            return false;
        }
        if (password == "")
        {
            alert("Please fill in your password");
            document.frm_login.txtPassword.focus();
            return false;
        }

        url =getServerAddress() + '/operator.php?type=3&username=' + username + '&password=' + password + '&last_id=' + last_id;
	
		http = getHTTPObject();

		http.open("GET", url, true);
		http.onreadystatechange = handleHttpResponseUser_Login;
		http.send(null);


}


function handleHttpResponseUser_Login()
{
	/*	0 = uninitialized --->onFailure: NADA
	1 = loading --->onRequest:
	2 = loaded ---->onComplete: NADA
	3 = interactive
	4 = complete ---->onSuccess:*/ 

	    var username = document.frm_login.txtUsername.value;
        var password = document.frm_login.txtPassword.value;

		if (http.readyState == 4) 
		{
			//alert (http.responseXml);//http.responseXML;
			raw_data=http.responseText; 
			user_login_process(raw_data, username, password);
			


		}
		if (http.readyState == 1) 
		{
			hide_logout();
            hide_login();
            show_loading("login");
		

		}
}

function hide_login()
{
        var div_login;
        div_login = document.getElementById("div_login");
		div_login.style.visibility = "hidden";
}
    
function user_login_process(raw_data, username, password)
{
        debug_script('userloginprocess');
		//alert(raw_data);
        if (raw_data == 1)
        {
            createCookie('user_username',username,1); 
            createCookie('user_password',password,1); 
            document.frm_prefs.radType[1].disabled = false;
            document.frm_prefs.radType[0].checked = false;
            document.frm_prefs.radType[1].checked = true;

			//stats(); NO ESTA EN USO


        } else {
            alert("Username/Password not valid");
            user_logout();
            return;
        }

		
        validate_user();
        hide_loading();
        hide_login();
		getNewData();
		
 
}

	

function show_logout()
{
        var div_logout;
        div_logout = document.getElementById("div_logout");
		div_logout.style.visibility = "";
		
}

function user_logout()
{
        debug_script('userlogout');
        eraseCookie('user_username');
        eraseCookie('user_password');
		//eraseCookie('follower');
		//eraseCookie('following');
        hide_logout();
		//stats(); NO ESTA EN USO
        validate_user();
        getNewData();
}

function eraseCookie(name) 
{
		
    	createCookie(name,"",-1);
}

function createCookie(name,value,days) 
{
		
		if ((name=="user_password") || (name=="user_username"))
		{ 
			value=myUrlEncode(value);									
		}

    	if (days) {
    		var date = new Date();
    		date.setTime(date.getTime()+(days*24*60*60*1000));
    		var expires = "; expires="+date.toGMTString();
    	}
    	else var expires = "";
    	document.cookie = name+"="+value+expires+"; path=/";
}



//////////////////////////////////// PREFERENCES//////////////////////////


  function update_prefs()
    {
        debug_script('updateprefs');
        eraseCookie('prefs_type');
        eraseCookie('prefs_reload_time');
        if (document.frm_prefs.radType[0].checked == true)
            type = 1;
        else
		{	
			if (document.frm_prefs.radType[1].checked == true)
            { 
				type = 2;
			} else {
						if (document.frm_prefs.radType[2].checked == true)
						{ 
							type = 5;
						} else type = 6;
			}
			
		}
        reload_time = document.frm_prefs.reload_time.value;
        createCookie('prefs_type',type,30);
        createCookie('prefs_reload_time',reload_time,30);
        validate_user();
        hide_prefs();
        getNewData();
    }

    function show_prefs()
    {
        hide_login();
        var div_prefs;
        div_prefs = document.getElementById("div_prefs");
		div_prefs.style.visibility = "";
    }
    

    function updateSeconds()
    {
//        document.getElementById("div_time").innerHTML = document.getElementById("div_time").innerHTML - 1;
    }




    function sendTweet()
    {
        debug_script('sendtweet');

        //CHECKS IF USER HAS LOGGED IN WITH A VALID ID
        if (validate_user() == 1)
        {
            var username = "";
            var password = "";

    		user_input_rad = 4;
            username = readCookie("user_username");
            password = readCookie("user_password"); password=myUrlEncode(password);
            tweet = document.frm_tweet.tweet.value;
            tweet = encodeURIComponent(tweet);
            url = getServerAddress() + "/operator.php?source=twitbin&type=" + user_input_rad + '&username=' + username + '&password=' + password + '&tweet=' + tweet;
		
		http = getHTTPObject();

		http.open("GET", url, true);
		http.onreadystatechange = handleHttpResponseSend_Sweet;
		http.send(null);

		}
    }


	function handleHttpResponseSend_Sweet()
	{
	/*	0 = uninitialized --->onFailure: NADA
	1 = loading --->onRequest:
	2 = loaded ---->onComplete: NADA
	3 = interactive
	4 = complete ---->onSuccess:*/ 


		if (http.readyState == 4) 
		{
			getNewData();


		}
		if (http.readyState == 1) 
		{
			hide_logout();
            show_loading("posting");

		}
	}


function getServerAddress ()
{
 //return window.location.protocol + '//' + window.location.hostname + '/tweetbin'; //alfa
 return window.location.protocol + '//' + window.location.hostname + '/beta';

}
	
function updateStatusTextCharCounter(value, key)
{
      /* if (document.getElementById("tweet").value == "") //USED IN AUTOCOMPLETE, NOT IN USE IN THIS VERSION
       {
		   eraseSelect();
       }*/
	
        
		//CAPTURE ENTER HERE AND SEND TWEET

		if (key == 13)
        {
            if (document.getElementById("tweet").value != "")
            {
                sendTweet();
                document.getElementById("tweet").value = "";
                document.getElementById("div_logout").innerHTML = '<a href="javascript:void(0)" onClick="user_logout()">logout</a> -140';
            }
            return false;
        }


        //IF COUNTING REMOVE RETURN
        //return;
        if ((140 - value.length) >= 0)
		{  
			document.getElementById("div_logout").innerHTML = '<a href="javascript:void(0)" onClick="user_logout()">logout</a> -' + (140 - value.length);
			
		}	
		else 
				document.getElementById("div_logout").innerHTML = '<a href="javascript:void(0)" onClick="user_logout()">logout</a> -140';
			
		
		
		/*if (readCookie("user_username") != null) //IS USED IN AUTOCOMPLETE, NOT IN USE IN THIS VERSION
		{
			var username = readCookie("user_username");
			var password = readCookie("user_password"); password=myUrlEncode(password);
			var url2='';

			if (value.slice(0,1)=='@')
				{
					url2 = getServerAddress() + '/operator.php?type=7&username=' + username + '&password=' + password;

				}else if ((value.slice(0,1) == 'd') ||(value.slice(0,1) == 'D'))
					{	   //alert (value);

						url2 =getServerAddress() + '/operator.php?type=8&username=' + username + '&password=' + password ;
					}

			if (( value.slice(0,1) =='@') || ((value.slice(0,1) == 'd') || (value.slice(0,1) == 'D')) )
			{	
				httpMessage=getHTTPObject();

				httpMessage.open("GET", url2, true);
				httpMessage.onreadystatechange = handleHttpResponseMessage;
				httpMessage.send(null);
			}

		}*/

	
}


/* CODE FOR AUTOCOMPLETE, THIS CODE WORKS VERY WELL, BUT ITS VERY SLOW, SO IN THIS VERSION WE DONT USE THAT */

/*function handleHttpResponseMessage ()

{
 var xml_data;

		

		if (httpMessage.readyState == 4) //estado 4 es listo
		{
			var select_auto=document.getElementById("select_auto");
			var screen_name='';

			//IF SELECT HAS OPTIONS...ERASE
			eraseSelect();
		
						
			var i=0;
			var child=0;
			xml_data=httpMessage.responseXML.getElementsByTagName("user");

			for (i = 0 ; i < xml_data.length ; i++)
			{

				if (window.ActiveXObject) 
				{
					//GET TWEET DATA---------------->//IE
					screen_name = xml_data[i].childNodes[2].firstChild.nodeValue; //alert (screen_name);
				}
				else
					if (window.XMLHttpRequest)
					{
						//GET TWEET DATA----------------> //mozilla
						screen_name = xml_data[i].childNodes[5].firstChild.nodeValue; //alert (screen_name);
					}
				
				option= document.createElement("option");

				var ok=true;
				

				if ((document.getElementById("tweet").value.slice(0,1)=='D') ||(document.getElementById("tweet").value.slice(0,1)=='d'))
				{
					if ((document.getElementById("tweet").value.length==1) || ((document.getElementById("tweet").value.length==2) &&  document.getElementById("tweet").value.slice(1,2)==' '))//solo se escribio D o d
					{
						option.id="option" + i;
						option.name="option" + i;
						textOp=document.createTextNode ("D " + screen_name);

					} else {
							if ((document.getElementById("tweet").value.length>=3) && (loaded== false)) //ahy algo mas ademas de d y un blanco
							{
							
								var aux=document.getElementById("tweet").value.slice(2, document.getElementById("tweet").value.length);
								
								for (m=0; m<= aux.length-1;m++ ) //chequea caracter a caracter
								{
									
									if (aux.slice(m,m+1)!=screen_name.slice(m,m+1))	{ok=false;} //no hay coincidencia

								}//end for
								
								if (ok) //hubo conincidencia en la comparacion
								{
									option= document.createElement("option");
									option.id="option" + child;
									option.name="option" + child;
									textOp=document.createTextNode ("D " + screen_name);
									child++;
								}
							}//end if
					}//end else

				}else {
					if (document.getElementById("tweet").value.slice(0,1)=='@')
					{
						
						if (document.getElementById("tweet").value.length==1) //solo se escribio @
						{
							option.id="option" + i;
							option.name="option" + i;
							textOp=document.createTextNode ("@" + screen_name);

						} else {
								if ((document.getElementById("tweet").value.length>=2) && (loaded== false)) //ahy algo mas ademas de d y un blanco
								{
							
									var aux=document.getElementById("tweet").value.slice(1, document.getElementById("tweet").value.length);
								
									for (m=0; m<= aux.length-1;m++ ) //chequea caracter a caracter
									{
										if (aux.slice(m,m+1)!=screen_name.slice(m,m+1))	{ok=false;} //no hay coincidencia

									}//end for
								
									if (ok) //hubo conincidencia en la comparacion
									{
										option= document.createElement("option");
										option.id="option" + child;
										option.name="option" + child;
										textOp=document.createTextNode ("@" + screen_name);
										child++;
									}
								}//end if
						}//end else

					}//end else
				}
				if (ok)
				{
					option.appendChild(textOp);
					select_auto.appendChild(option);
					
					
				}
				
			} //end for

			if (document.getElementById('select_auto').options.length > 0)
			{
				show_auto_select();
				
			}
		}//end if completed



}

function show_auto_select()
{

	document.getElementById("auto_complete").style.visibility ="";

}


function eraseSelect()
{
	var length=document.getElementById('select_auto').options.length;

	if (length > 0)
	{	
		for (i=0; i<= length-1; i++)
		{
			 option = document.getElementById("option" + i);
			 padre = option.parentNode;
			 hijoRemovido = padre.removeChild(option);

		}
	}
	document.getElementById("auto_complete").style.visibility ="hidden";
	loaded= false;

}

function autocomplete()
{
	var index=document.getElementById('select_auto').selectedIndex;
	var text=document.getElementById('select_auto').options[index].text;

	eraseSelect();

	document.getElementById("tweet").value= text;

	loaded= true;

	if ((140 - document.getElementById("tweet").value.length) >= 0)
		document.getElementById("div_logout").innerHTML = '<a href="javascript:void(0)" onClick="user_logout()">logout</a> -' + (140 - document.getElementById("tweet").value.length);
	else
		document.getElementById("div_logout").innerHTML = '<a href="javascript:void(0)" onClick="user_logout()">logout</a> -140';


}*/