var TWPORTAL = "europatweets";

function Controller(ul_anchor)
{
	this.date 				= new Date();
	this.last_update 		= this.date.getTime();
	this.last_sync_id 		= 0;
	
	
	this.tweets_displayed	= 0;
	
	this.enabled			= false;
	
	// Settings
	this.source				= "db";
	this.keywords			= "";
	this.profile			= "";
	
	this.limit				= 10;
	this.page				= 1;
	this.refresh_timeout	= 30; // 30 seconds between two updates
	
	// hooks
	this.jNode_tweets_ul	= $("#"+ul_anchor); 

	this.update = function() 
	{		
		console.info("this.update");
		
		if(!this.enabled)
			return;
			
		controller = this;
		this.last_update = this.date.getTime();		
		$.get("http://portal1.tweetag.com/proxyapi.php?source="+this.source+"&twportal="+TWPORTAL+"&a=tweets&limit="+this.limit+"&page="+this.page+"&sync_id="+this.last_sync_id,function(msg) { controller.process_json(msg); });
	}

	this.add_tweet = function(tweet) 
	{
		console.info("this.add_tweet");

		this.update_last_sync_id(tweet.id);
		
		tweet.html = tweet2html(tweet);

		if(this.tweets_displayed==this.limit)
			this.remove_last_tweet();	
		 
		this.jNode_tweets_ul.prepend('<li id="tweetag_tweet_'+tweet.id+'">'+tweet.html+'</li>');
		
		this.tweets_displayed++;

		console.info("Tweets displayed: %i - Last sync id: %i",this.tweets_displayed,this.last_sync_id);
		return this.tweets_displayed;
	}
	
	this.remove_tweet = function(tweet_id)
	{
		console.info("this.remove_tweet");

		this.jNode_tweets_ul.find("idx="+tweet_id).hide();
	}
	
	this.flush = function()
	{
		this.jNode_tweets_ul.html("");
		this.tweets_displayed = 0;
	}
	
	this.remove_last_tweet = function(tweet_id)
	{
		size = this.jNode_tweets_ul.find("li:visible").size();
		var i=0;
		this.jNode_tweets_ul.find("li:visible").each(function() {
			if(++i==size)
				$(this).hide();
		});
	
		this.tweets_displayed--;
	}
	
	this.process_json = function(json)
	{
		console.info("this.process_json");

		
		if(!json)
		{
			console.warning("this.process_json: json empty");	
			return false;
		}
		
		json = eval(json);

		json.reverse();

		if(json.length==1)
		{
			console.warning("this.process_json: json.length == 1");	
			return false;
		}
		
		console.info("%i tweets received via json",json.length);
		
		for(var i=0;i<json.length;i++)
		{
			this.add_tweet(json[i]);
		}

	}
	
	this.start = function()
	{
		this.enabled = true;
		this.update();	
	}
	
	this.stop = function()
	{
		this.enabled = false;	
	}
	
	this.update_last_sync_id = function(id)
	{
		if(id>this.last_sync_id)
			this.last_sync_id = id;
		return id;
	}
}


