var timer;

function pageLoaded(iPhone){
	if($$('#f input[name="testo"]').getStyle('display') != 'none')
		$('f').testo.focus();

	// Countdown
	if(now - lu < 120 * 1000){
		countdown();
		timer = countdown.periodical(1000);
	}
	
	if(iPhone)
		setTimeout(function(){window.scrollTo(0, 1);}, 500);
}


function countdown(){
	seconds--;
	var minutes = Math.floor(seconds / 60);
	
	var s = seconds - 60 * minutes;
	if(s.toString().length == 1) s = '0' + s;
	
	$('message').innerHTML = 'You can submit again in ' + minutes + ':' + s;
	
	if(seconds <= 0){
		$clear(timer);
		$('message').innerHTML = 'Now you can write a new message.';
		$('f').testo.style.display = 'block';
		$('f').testo.focus();		
	}
}


function voteIt(id, direction){
	var msgs = $$('li.message_' + id);

	msgs.each(function(el){
		el.getElement('div.voting').innerHTML = 'sending...';
	});
	
	new Request({
		url: '/vote',
		onSuccess: function(txt){
			if(isNaN(txt)){
				alert(txt);
			}
			else{
				msgs.each(function(el){
					el.getElement('span.coolness').innerHTML = txt;
					el.getElement('div.voting').innerHTML = 'Voted';
					
					if(txt < 0)
						el.getElement('span.coolness').addClass('worst');
					else
						el.getElement('span.coolness').removeClass('worst');
				});
			}
		}
	}).send('id=' + id + '&direction=' + direction);
}


function deleteIt(id){
	if(!confirm('Are u sure?')) return false;
	
	var msgs = $$('li.message_' + id);

	new Request({
		url: '/delete',
		onSuccess: function(txt){
			msgs.each(function(el){
				el.set('tween', {onComplete: function(){el.destroy();}});
				el.tween('opacity', 0);
			});
		}
	}).send('id=' + id);
}


function showInfo(el){
	var form = $('f');
	var margin = form.getStyle('margin-top').toInt();

	if(margin < 0){
		form.tween('margin-top', 0);
		el.src = '/img/info.gif';
	}
	else{
		form.tween('margin-top', -100);
		el.src = '/img/close.gif';
	}
}


function shareOnFacebook(url){
	var mywin = window.open(url, 'sharer', 'toolbar=0,status=0,width=626,height=436');
	mywin.moveTo(300, 100);
}