/*
* Written by Christopher Pietsch
* Licensed under the GPL (http://www.gnu.org/licenses/gpl-3.0.html).
*/


var lastItem = "?";
var last=0;
var aktiv = window.setInterval("queue2(lastItem)", 4000);

queue2(lastItem);
var height, width, num=50;

$(window).resize(function(){
	calcSize();	
});


function calcSize(){
	width=parseInt( $(window).width()/150);
	height=parseInt( $(window).height()/150);
	num=height*width;
	$("#images").css("height", height*150);
	//console.log(width);
}


function queue2(sinceId){
	$.getJSON("http://search.twitter.com/search.json?q=twitpic&since_id="+sinceId+"&rpp=40&callback=?",
	function(data){
		if(!data.error){

			lastItem= data.max_id;
			$.each(data.results, function(i,item){
				//$("<img/>").attr("src", item.profile_image_url).appendTo("#images");
				//console.log(item);
				var twitpicHash=item.text.match(/http:\/\/twitpic.com\/(\w*)/);
			
				if(twitpicHash){
					var img = new Image();
					$(img)
					.load(function () {
						/*for (var i=40; i !=0; i--) {
							$('#image'+i).html($('#image'+(i-1)).html());
							//console.log($('#image'+i+' img'));.wrap('<span></span>')
						}*/
						$(this).hide();
						$('#image'+last).html($(this));
						$(this).fadeIn(300);
						//$(this).slideDown();
						last++;
						if(last>=num) last=0;
	
					})
					.error(function () { })
					.attr("src", "http://twitpic.com/show/thumb/"+twitpicHash[1])
				}
						
				
			});
		}


	});
}

function queuess(sinceId){
	$.getJSON("http://search.twitter.com/search.json?q=twitpic&since_id="+sinceId+"&rpp=80&callback=?",
	function(data){
		//console.log(data);
		if(!data.error){
				if(data.results.length-1!=0){
					lastItem=data.results[data.results.length-1];
				}
			$.each(data.results, function(i,item){
				//$("<img/>").attr("src", item.profile_image_url).appendTo("#images");
				
				var twitpicHash=item.text.match(/http:\/\/twitpic.com\/(\w*)/);
			
				if(twitpicHash){
					var img = new Image();
					$(img)
					.load(function () {
						var $self=$(this)
						.prependTo("#images")
						.wrap('<span><a target="_blank" href="'+twitpicHash[0]+'"></a></span>')

						//$self.slideDown(100);

					})
					.error(function () { })
					.attr("src", "http://twitpic.com/show/thumb/"+twitpicHash[1])
				}

			});
			$("#images span:gt(100)").remove();
		}


	});
}






$(document).ready(function() {
	
	//var string= "T @vickytcobra: http://twitpic.com/n91lf - @gabrielsapor";
	//var search = /http:\/\/twitpic.com\/(\w*)/;
	//var res = string.match(/http:\/\/twitpic.com\/(\w*)/);
	
	
	//console.log(res);
	calcSize();
	for (var i=0; i < 100; i++) {
		$('<span id="image'+i+'"><img src="spin.gif"></div>').appendTo("#images");
	};
	$("span").click(function(){
		var url = $("img",this).attr("src").replace("/show/thumb", "");
		window.open(url,"Twitpic");
		return false;
	})
	
	$("#stop").click(function(){
		window.clearInterval(aktiv);
	})

});

