/**
 * Main functions for TodaysMeet.com
 * Depends on Prototype, Scriptaculous.
 *
 * Copyright 2008 James Socol All Rights Reserved.
 */

// Preload images
if ( Image ) {
	var ImagePreload = new Image(12,12);
	var images = {};
	images.ok = "http://todaysmeet.com/images/ok.gif";
	images.no = "http://todaysmeet.com/images/no.gif";
	images.blank = "http://todaysmeet.com/images/blank.gif";
	for ( var img in images ) {
		ImagePreload.src = img;
	}
}

function checkname () {
	if ( Interactive() ) return;
	var name = $F('roomname');
	$('extra-room-name').innerHTML=name;
	$('createRoomForm').action='/'+name;
	window.allowSubmit = false;

	if ( name != '' ) {
		Interactive(true);
		var A = new Ajax.Request('/check/'+name+'.json', {
								 method: 'get',
								 evalJSON: 'force',
								 onSuccess: function (ajax) {
									 var json = ajax.responseText.evalJSON();
									 switch (json.result) {
										case 'available':
											$('extra-room-result').width = 12;
											$('extra-room-result').src = images.ok;
											$('submitRoom').disabled = false;
											window.allowSubmit = true;
											break;
										case 'taken':
										case 'reserved':
										default:
											$('extra-room-result').width = 12;
											$('extra-room-result').src = images.no;
											$('submitRoom').disabled = true;
									 }
								 },
								 onFailure: function() {
									 Error("Could not check name!");
								 },
								 onComplete: function() {
									 Interactive(false);
								 }
								 });
	} else {
		$('extra-room-result').width = 0;
	}
}

function Interactive(state) {
	if ( state === true ) {
		window.Interacting = true;
		$('ajax-loading').show();
	} else if ( state === false ) {
		window.Interacting = false;
		$('ajax-loading').hide();
	}
	return window.Interacting;
}

function Error ( msg ) {
	var errors = new Element('div', {id:'errors'});
	errors.innerHTML = '<ul><li>'+msg+'</li></ul>';
	errors.observe('click',function(e){errors.remove()});
	$('todaysmeet').insertBefore(errors,$('header').nextSibling);
}

window.onload = function () {
	// Reset the "interactive" state
	Interactive(false);
	
	// If we're on a create-a-room form, dynamically check
	// the current room name
	if ( $('roomname') ) {
		checkname();
		$('roomname').observe('keyup',checkname);
	}
	
	// if we're on a listening room, run the
	// updateRoom() function to get the posts, and
	// set it to run every 15 seconds
	if ( $('post-scroller') ) {
		window.maxId = 0;
		updateRoom();
		window.updater = setInterval(updateRoom, 15000);
	}
	
	// if we're on a talking/listening room, put the
	// setName() listener on the sender-name dialog
	if ( $('sender-name-dialog') && typeof setName == 'function' ) {
		$('save-sender-name').observe('click', setName);
	}
}