// JavaScript Document


var realtimeRecentAjax = null;


var thereWasNeverAnyRecentData = null;


function realtimeAjaxRecentCheck(){
	if(realtimeRecentAjax) { realtimeRecentAjax.abort(); }
	realtimeRecentAjax = $.ajax({
	   type: "POST",
	   url: "ajax/common/recent/check.php",
	   data: ({ since_id: $('.recent:first').attr("status_id"), count: 4, right_width: $('#right').attr("width"), iphone: $('#right').attr("iphone") }),
	   success: function(data){
			if(data.length != 0) {
				thereWasNeverAnyRecentData = false;

				$(data).prependTo("#recent_tweets");
				
				var i=0;
				$(".recent").each(function() {
					if ($(this).is(":hidden")) {
						i++;
						$(this).slideToggle("fast");
					}
				});
				if(i<=4) {
					$("#recent_load_text").html("<a>Load Older Tweets</a>");
					$("#recent_load").css("cursor","pointer");
				} else {
					//$("#recent_load .text").html("");
					//$("#recent_load").css("cursor","default");
				}
				
				var c=0;
				$(".recent").each(function() {
					c++;				  
				});
				
				
				if(c > 4) {
					for(i=0;i<(c-4);i++) {
						$(".recent:last").remove();
					}
				}
				
				bindRecentThumbClicks();
			} else {
				if(thereWasNeverAnyRecentData == null) {
					$("#recent_load_text").text("No Tweets");
				}
			}
	   }
	 });
	
}

function bindRecentThumbClicks() {

	$('.recent_i').each(function() {
		var url = $(this).attr("url");
		$(this).unbind('click').click(function(){
			location.href=url;
			return false;
		});
    });
	
	$('.recent_v').each(function() {
		var url = $(this).attr("url");
		$(this).unbind('click').click(function(){
			location.href=url;
			return false;
		});
    });
	
	
	
	
}


var realtimeAjaxRecentIntervalID = setInterval("realtimeAjaxRecentCheck();", 60000);


var loadmoreRecentAjax = null;


$(document).ready(function(){
	
	
	realtimeAjaxRecentCheck();
	
	bindRecentThumbClicks();
	
	$("#recent_load").click(function () {
		if(loadmoreRecentAjax) { loadmoreRecentAjax.abort(); }
		var lastIDForScroll = $('.recent:last').attr("status_id");
		loadmoreRecentAjax = $.ajax({
		   type: "POST",
		   url: "ajax/common/recent/more.php",
		   data: ({ max_id: $('.recent:last').attr("status_id"), count: 4, right_width: $('#right').attr("width"), iphone: $('#right').attr("iphone") }),
		   success: function(data){
				if(data.length != 0) {
					$(data).appendTo("#recent_tweets");
					
					var i=0;
					$(".recent").each(function() {
						if ($(this).is(":hidden")) {
							i++;
							$(this).slideToggle("fast", function() {
								//$.scrollTo(".recent:[status_id='"+lastIDForScroll+"']");						 	
							});
						}
					});
					if(i<=4) {
						$("#recent_load_text").html("<a>Load Older Tweets</a>");
						$("#recent_load").css("cursor","pointer");
					} else {
						$("#recent_load_text").html("");
						$("#recent_load").css("cursor","default");
					}
					bindRecentThumbClicks();
					
				}
		   }
		 });
	});
	
	
});
