var GLOBAL = {};

GLOBAL.init = function() {
  this.tu = null;
  this.isIE = /MSIE (\d+\.\d+);/.test(navigator.userAgent);
  this.isIPhone = /iPhone/.test(navigator.userAgent);
  this.delayFactor = 5.0;
  this.xOffset = 10;
  this.yOffset = 20;	
};

GLOBAL.init();

var MAX_ITEMS_PER_PAGE = 50;

$(document).ready(function() {
	$("#countryLinks").change(function() {
		var val = $(this).val();
		if (val!="")
			window.location = $(this).val();
	});
	GLOBAL.tu.start();
	GLOBAL.tu.update()
});

TweetQueue=function(){
	this.items=[];
	this.delay=GLOBAL.delayFactor*1000;
	this.timeout=undefined;
};

TweetQueue.prototype.start=function(){
	if(!this.timeout){
		this.schedule();
	}
};

TweetQueue.prototype.stop=function(){
	if(this.timeout){
		clearTimeout(this.timeout);
		this.timeout=undefined;
	}
};

TweetQueue.prototype.pause_toggle=function(){
	if(this.timeout){
		this.stop();
		return true;
	}
	else{
		this.start();
		return false;
	}
};

TweetQueue.prototype.schedule=function(){
	var t=this;
	this.timeout=setTimeout(function(){
		t.schedule();
		t.update();
	} ,this.delay);
};

TweetQueue.prototype.update=function(){
	if($('#streams-body > div').size()>MAX_ITEMS_PER_PAGE){
		$('#streams-body > div.InfoDetails:last').fadeOut(1500,function(){
			$(this).remove();
		});
	}

	var item=this.items.shift();
	if(item){
		var element=$("#streams-update > #"+item);
		var scroll_offset = GLOBAL.isIPhone? '-72px':'-66px';
		$('.streamscroll').css('top', scroll_offset);
		$('#streams-body').prepend(element.html());
		$('#streams-body > div.InfoDetails').each(function (i, el) { $(el).css('margin', '0px 0px 0px 0px'); });
		if (GLOBAL.isIPhone)
			$('#streams-body > div.InfoDetails').each(function (i, el) { $(el).css('height', 'auto'); });
		$('#streams-body > div.InfoDetails:first').css('margin-top', '0px');
		$('#streams-body > div.InfoDetails:first').hover(
				function(){ $(this).addClass("InfoD_hover");},
				function(){ $(this).removeClass("InfoD_hover");}
		);
		//fallAnimation( $('#streams-body > div.InfoDetails:first'));
		$('.streamscroll').animate({top:0},GLOBAL.delayFactor*500, 'easeInOutQuad');
		element.remove();
	}
};

TweetQueue.prototype.add=function(id){
	this.items.push(id);
};

TweetQueue.prototype.clear=function(){
	$("#streams-update > div").each( function(index, element) {
		$(element).remove()
	});
};

var TweetSpy=function(since,url){
	this.since=since;
	this.delay=30000;
	this.timeout=undefined;
	this.queue=new TweetQueue();
	this.url=url;
};

TweetSpy.prototype.start=function(){
	if(!this.timeout){
		this.schedule();
		this.queue.start();
	}
};

TweetSpy.prototype.schedule=function(){
	var t=this;
	this.timeout=setTimeout(function(){
		t.schedule();
		t.update();
	},this.delay);
};

TweetSpy.prototype.update=function(){
	var t=this;
	//$('#loading').show();
	$.get(t.url,{since:t.since},function(data){
		var tweets = data.tweets;
		var since = data.maxtime;
		if (t.since==0 && tweets.length>5) //show the latest 5 tweets with fall effect
		{
			var staticTweets = tweets.slice(5);
			tweets.splice(5, tweets.length-5);
			for (var i in staticTweets)
			{
				$('#streams-body').append(formatTweet(staticTweets[i], true));
			}
			
			$('#streams-body > div.InfoDetails').each(function(index, element){
				$(element).hover(
					function(){ $(this).addClass("InfoD_hover");},
					function(){ $(this).removeClass("InfoD_hover");}
				);
			});
			if(!isNaN(since)){
				t.since=since;
			}
		}

		for (var i in tweets)
			$('#streams-update').prepend(formatTweet(tweets[i]));
		if(!isNaN(since)){
			t.since=since;
		}
		$('#streams-update > div:not(.ready)').each(function(index,element){
			element=$(element);
			element.addClass('ready');
			t.queue.add(element.attr('id'));
		});
		//$('#loading').hide();
	}, "json");
};

TweetSpy.prototype.pause_toggle=function(){
	return this.queue.pause_toggle();
};

TweetSpy.prototype.stop=function(){
	clearTimeout(this.timeout);
	this.queue.stop();
	this.queue.clear();
	$('#streams-body > div.InfoDetails').each(function(index, element) {
		//$(element).fadeOut(500,function(){
			$(this).remove();
		//});
	});
};


jQuery.extend(jQuery.easing,{def:'easeOutQuad',
	easeInOutQuad:function(x,t,b,c,d){if((t/=d/2)<1)return c/2*t*t+b;return-c/2*((--t)*(t-2)-1)+b;}
	}
);

fallAnimation = function (a) 
{
	a.css("margin-bottom", 0 - a.height()).css("top", -170).animate({top: "0px", marginBottom: "0px"}, GLOBAL.delayFactor*350);
}

function htmlizeTweet(text)
{
    text = text.replace(/(http:\/\/[a-z0-9.-?_&%-]*)/ig,'<a href="$&" target="_blank">$&</a>');
    text = text.replace(/@([a-z0-9.?&%_-]*)/ig,'<a href="http://twitter.com/$1" target="_blank">$&</a>')
    text = text.replace(/#([a-z0-9.?&%_-]*)/ig,'<a href="http://search.twitter.com/search?q=%23$1" target="_blank">$&</a>')
    return text;
}

function formatTweet(tweet, init)
{	
	var time = new Date();
	time.setTime(parseInt(tweet.created_at) * 1000);

    var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    var month = months[time.getMonth()];
    var hours = time.getHours();
	var mins = ((time.getMinutes()<10)? "0":"") + time.getMinutes();
	
	var html = init? '':('<div id="tweet_' + tweet.id + '">');
	html += '<div class="InfoDetails"><div class="left"><a href="http://twitter.com/' + tweet.from_user + '"><img src="' + 
		tweet.image +  '" alt="' + tweet.from_user + '" /></a></div><p class="right">' + htmlizeTweet(tweet.text) + ' - <a class="author" href="http://twitter.com/' + 
		tweet.from_user + '"><strong>' + tweet.from_user + '</strong></a>';
	
	if (tweet.politician!=null)
	{
		var image = (tweet.is_candidate=='yes')? '/images/flags/European%20Dashboard.png':'/images/infobutton.png';
		var tipContents = '';
		if (tweet.is_candidate=='yes')
			tipContents = "European Parliament Candidate <img src='/images/flags/European%20Dashboard.png'/><br/>";
		tipContents +=	'<strong>Name: </strong>' + (tweet.politician) + 
									'<br/><strong>Twitter: </strong>' + tweet.from_user + 
									'<br/><strong>Party: </strong>' + (tweet.party) + 
									'<br/><strong>Country: </strong>' + (tweet.country) + '<br/>';
		
		tipContents = tipContents.replace(/\"/g,'\\"');
		tipContents = tipContents.replace(/\'/g,'\\\'');
		
		html += '<img class="info" src="'+image+'" onmouseover="tooltip.show(\'' + tipContents + '\');" onmouseout="tooltip.hide();"/>';
	}

	html += adminLink(tweet.id);

	html +=  ' on ' + month + ' ' + time.getDate() + ' at ' + hours + ':' + mins + 
		' - <span><a href="' + replyLink(tweet) + '" target="_blank">REPLY</a></span> - <span><a href="'+retweetLink(tweet)+'" target="_blank">RETWEET</a></span></p></div>';
	html += init? '':'</div>';

	var elem = $(html);
	return elem;  
}

function filterByParty(party_id)
{
	GLOBAL.tu.stop();
	GLOBAL.tu = new TweetSpy(0, '/updates.php?entity_type=party&entity=' + party_id); 
	GLOBAL.tu.start();
	GLOBAL.tu.update();
	$("#eWpParty").trigger('click');
}

function filterByPolitician(politician_id)
{
	GLOBAL.tu.stop();
	GLOBAL.tu = new TweetSpy(0, '/updates.php?entity_type=politician&entity=' + politician_id); 
	GLOBAL.tu.start();
	GLOBAL.tu.update();
	$("#eWpFigure").trigger('click');
}

function filterByCountry(country_id, fromParty)
{
	GLOBAL.tu.stop();
	GLOBAL.tu = new TweetSpy(0, '/updates.php?entity_type=country&entity=' + country_id); 
	GLOBAL.tu.start();
	GLOBAL.tu.update();
	(fromParty)? $("#eWpParty").trigger('click'):$("#eWpFigure").trigger('click');
}

function retweetLink(tweet)
{
	return "http://twitter.com/home/?status=" + encodeURIComponent("RT @" + tweet.from_user +  " " + tweet.text);
}

function replyLink(tweet)
{
	return "http://twitter.com/timeline/home?in_reply_to="+tweet.from_user+"&in_reply_to_status_id="+tweet.id+"&status=" + encodeURIComponent("@") +tweet.from_user;
}
