var MAX_ITEMS_PER_PAGE = 30;

TweetQueue=function(){
	this.items=[];
	this.delay=2000;
	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(){
	var scroll_offset=($('#popoutinner').length>0)?'-105px':'-120px';
	if($('#streams-body > ul').size()>MAX_ITEMS_PER_PAGE){
		$('#streams-body > ul.twitupdate:last').fadeOut(3000,function(){
			$(this).remove();
		});
	}

	var item=this.items.shift();
	if(item){
		var element=$("#streams-update > #"+item);
		$('.streamscroll').css('top',scroll_offset);
		$('#streams-body').prepend(element.html());
		$('.streamscroll').animate({top:0},1500,'easeInOutQuad');
			element.remove();
	}
};

TweetQueue.prototype.add=function(id){
	this.items.push(id);
};

var TweetSpy=function(since,url){
	this.since=since;
	this.delay=15000;
	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){
		for (var tweet in data["results"])
			$('#streams-update').prepend(data["results"][tweet]);
		
		var since_parsed = data["max_time"];
		if(!isNaN(since_parsed)){
			t.since=since_parsed;
		}
		$('#streams-update > div:not(.ready)').each(function(index,element){
			element=$(element);
			var localTime = getTime($(".timestamp", element).attr("unixtime"));
			$(".timestamp", element).html(localTime);
			$(".author", element).attr('title', $(".author", element).attr('title') + ' ' + localTime);
			element.addClass('ready');
			t.queue.add(element.attr('id'));

		});
		$('#loading').hide();
	}, "json");
};

TweetSpy.prototype.pause_toggle=function(){
	return this.queue.pause_toggle();
};


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;}
	}
);

function popUp(URL){
	day=new Date();
	id=day.getTime();
	eval("page"+id+" = window.open(URL, '"+id+"', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=660,height=600');");
}

function toggle()
{
	$('#togglelink').attr("src", tu.pause_toggle()? "/img/break.png":"/img/break.png"); 
}

jQuery.fn.twitterCounter = function(options)
{
	if(!$(this)[0])
		return false;
	var curSize=$(this).val().length;
	var charsLeft=options['limit']-curSize;
	var types=['ok','watch','warning','error'];
	var x={};$.each(types,function(){
		var el=this.toString();
		x[el]={'Max':options[el+'Size'],'Style':options[el+'Style'].substring(0,1)=='.'||options[el+'Style'].substring(0,1)=='#'?options[el+'Style'].substring(1,options[el+'Style'].length):options[el+'Style'],'Type':options[el+'Style'].substring(0,1)=='.'?'class':'id'};
	});
	for(var i=0;i<types.length;i++)
	{
		var el=types[i].toString();
		if(i+1<types.length){
			var nextEl=types[i+1].toString();
			if(charsLeft>x[nextEl]['Max']&&charsLeft<x[el]['Max']+1){
				clean();
			}
		}
		else
		{
			if(charsLeft<x[el]['Max'])
				clean();
		}
	}
	$(options['counter']).text(charsLeft);
	$(this).one('keyup',function(){
		$(this).twitterCounter(options);
	});

	function clean(){
		if(x[el]['Type']=='class'){
			$.each(types,function(){
				var temp=this.toString();
				if($(options['counter']).hasClass(temp)){
					$(options['counter']).removeClass(temp);
				}
			});
			$(options['counter']).addClass(x[el]['Style']);
		}
		else
		{
			$(options['counter']).id(x[el]['Style']);
		}
	}
};

function replyTo(screen_name, status_id){
	oldValue=$('#postfield').val();
	var text=$('#postfield').val("@"+screen_name+" "+oldValue);
	window.scroll(0,0);
	//limitChars('postfield',140,'length');
	$('#reply_to').val(status_id); //Set the reply_to_status_id here. This will be sent to server while posting the form
	$('#postfield').trigger('keyup');
	$("#postfield").focus();
}

function rtreplyTo(screen_name, status){
	var text=$('#postfield').val("RT @"+screen_name+" "+status);
	window.scroll(0,0);
	$('#postfield').trigger('keyup');
	$("#postfield").focus();
}

function remove(anchor, status_id){
	$('#errorMessage').remove();
	$.get("/moderate.php?",{id:status_id},function(data){
		if (data.error)
			$('.yui-g').prepend('<div id="errorMessage">' + data.error + '</div>');
		else
		{
			$(anchor).remove();
			$('.yui-g').prepend('<div id="errorMessage">Tweet #' + status_id + ' has been removed</div>');
		}
	}, "json");
}

function tweetTicker(ticker_symbol){
	oldValue=$('#postfield').val();
	var text=$('#postfield').val(oldValue+" "+"$"+ticker_symbol);
	window.scroll(0,0);
	$('#postfield').trigger('keyup');
	$("#postfield").focus();
}


function onPost(form)
{
	if ($('#postfield').val().length > 140) { 
		alert('That update is over 140 characters!'); 
		return false; 
	} 

	if ($('#postfield').val().length == 0) { 
		alert('Please enter a valid status'); 
		return false; 
	} 
	
	$.ajax({
		beforeSend:function(request){
			$('#twitter_update_submit').attr('disabled','true');
			$('#twitter_update_submit').attr('value','Updating...');
			$('#errorMessage').remove();
		}, 
		complete:function(request){
			$('#twitter_update_submit').removeAttr('disabled');
			$('#twitter_update_submit').attr('value','Update');
		}, 
		data:$.param($(form).serializeArray()), 
		dataType:'json', 
		type:'post',
		url:'/tweet.php',
		success:function(data, textStatus) {
			if (data.error)
				$('.yui-g').prepend('<div id="errorMessage">' + data.error + '</div>');
			else
			{
				$('#postfield').val("");
				$('#textcounter').html('140');
				//Clear the hidden field of "reply to status id"
				$('#reply_to').val("0");
			}
		},
		error:function(XMLHttpRequest, textStatus, errorThrown) {
			$('.yui-g').prepend('<div id="errorMessage">' + textStatus + '</div>');
		}
		}); 
	return false;
}

function getTime(atime)
{
	var time = new Date();
	time.setTime(parseInt(atime) * 1000);

    var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    var month = months[time.getMonth()];
    var ampm = 'am';
    var hours = time.getHours();
 
    if(hours > 12)
    {
        hours = hours - 12;
        ampm = 'pm';
    }
    if(hours == 0)
    {
        hours = 12;
    }

	var ttime = month + '. ' + time.getDate() + ' at ' + hours + ':' + ((time.getMinutes()<10)? "0":"") + time.getMinutes()  + ampm;
	return ttime;
}

$(document).ready(function () {
	$('#streams-body > .message').each(function(index, element){
		var localTime = getTime($(".timestamp", element).attr("unixtime"));
		$(".timestamp", element).html(localTime);
		$(".author", element).attr('title', $(".author", element).attr('title') + ' ' + localTime);
	});
});