chatzoo = {

	params: {
		API_LOOKUP_URI: "http://www.userplane.com/directory/api/search/community.cfc?"
	},

	init: function () {
		//console.log("chatzoo.init");
		chatzoo.registerEventHandlers();
	},
	
	util: {

		showHideLoader: function () {
			// if no loader is present make one
			if ( $("#searchLoader").length > 0 ) {
				//console.log("writing new element for loader");
				$("#searchResults").append( $("<div id='loader'></div>") );
			}
			// destroy it
			else {
				$("#searchLoader").remove();
			}
		}
			
	},
	
	events: {
	
		onSearch: function (event) {
			
			// Remove any previous search results
			$("#results").find("li").remove();	
			
			// show/hide loader
			chatzoo.util.showHideLoader();
		
			// Call to instant api to lookup communities
			//console.log("chatzoo.onSearch",event);
			
			// place call to the api and pass results to the handler.
			$.getJSON( chatzoo.params.API_LOOKUP_URI + "method=search&q="+$('#q').val()+"&callback=?", chatzoo.events.onSearchComplete);
			
			// show the search results pane
			$("#searchResults").show();
		},
		
		onSearchComplete: function (event) {
			
			//console.log("chatzoo.onSearchComplete", event);

			// response handler from the call to search from the instant api
			chatzoo.renderers.communityList( event.RESPONSE );
			
		},
		
		launchChat: function(instanceID) 
		{
			var url = 'http://www.userplane.com/directory/index.cfm?action=chat.loadChatFrameset&domainCode=' + instanceID + '&app=ch';
			window.open( url, "UserplaneChatWindow", "width=800,height=600,toolbar=0,directories=0,menubar=0,status=0,location=0,scrollbars=0,resizable=1" );
		}
	
	},
	
	renderers: {
		
		communityList: function (array) {
			//console.log("rendering community list",array);
			jQuery.each( array, function(i) {
				$("#results").append( $("<li></li>").html( "<a href='#' onclick=\"chatzoo.events.launchChat('"+array[i].ID+"');\"><h1 class='community'> Chat In: "+array[i].TITLE+"</h1></a><p>"+array[i].DESCRIPTION+"</p>" ) );
			});
		}
		
	},
	
	registerEventHandlers: function() {
		$("#searchForm").bind("submit",chatzoo.events.onSearch);
	}


};
$(document).ready(chatzoo.init);
