//When JQuery is ready, initialise
$(document).ready(init);

//Set off the first clicker event
function init(){

	//Wait a random time
	var rand_no = Math.floor(Math.random()*10)+1
	setTimeout(clicker,((rand_no+5)*60));

	//Get latest tweet
	getLatestTweet();
	
}

function open(id){
	id = '#'+id;
	$(id).slideDown();
}

function close(id){
	id = '#'+id;
	$(id).slideUp();
}

//Create the clicking effect on the home page
function clicker() {

	//Select a TV
	var tv_no = Math.floor(Math.random()*3)+1
	
	current_img = $('#tv'+tv_no).css("background-image");
	if(current_img.indexOf('_off')>=0){

		//TV is off, so switch it on
		$('#tv'+tv_no).css("background-image","url(views/default/images/tv240.png)");
	
		//Queue up the next random clicker event
		var rand_no = Math.floor(Math.random()*10)+1
		setTimeout(clicker,((rand_no+5)*60));
	
	} else {

		//Select an image and change to it
		var bogus = Math.random()*500; //Bogus does nothing expect tricks IEs cache
		$.getJSON('randompic',{bogus:bogus},function(data){
			changeblip(tv_no,data.img,data.link);
		});

		//Queue up the next random clicker event
		var rand_no = Math.floor(Math.random()*20)+1
		setTimeout(clicker,((rand_no+100)*60));

	}

}

//Set selected TV to static and then to the new image
function changeblip(tv,to,link){

	document.getElementById('scr'+tv).src = 'views/default/images/tv_static.gif'
	$('#scr'+tv).css("background-image","url('views/default/images/tv_static.gif')");
	$('#scr'+tv).unbind();
	
	setTimeout(function(){changeblip2(tv,to,link)},200);

}

//Change to new image
function changeblip2(tv,to,link){
	$('#scr'+tv).click(function(){window.location=link;});
	if(to.substr(0,4)!=='http'){
		to = 'views/default/images/'+to
	}
	$('#scr'+tv).css("background-image","url('"+to+"')");
}

function getLatestTweet(){

	//Get my latest tweet and display it
	$.getJSON('latesttweet',{},function(json){
		$('#latest_tweet').html('"'+json.tweet+'"');
		$('#latest_time').html(json.ago+' from <a href="http://twitter.com/PaulJEvans">Twitter</a>');
		$('#latest_inner').show('slow');		
	});

}
