// cache for session lists to make the app a little faster when selecting sessions
LoaderFrameCache = {}

// add extra styles
document.write("<style type='text/css'>@import 'styles/js.css';</style>");

/**
 * Scheduling Application
 *
 * Author: Elliott Sprehn (elliott [at] teratech.com)
 * Date: April, 19, 2007
 *
 * Makes the schedule application more interactive by doing requests asynchronously. :)
 */
addEvent( window, "load", function() {

	// init for generating modal dialogs
	ModalDialog.init("images/cfu_icon.gif","Press the spacebar to close this dialog.");
	ModalDialog.width = 700;
	ModalDialog.height = 700;
	
	// init progress indicator generator
	ProgressIndicator.init();
	
	// Create iframe for loading lists of sessions
	createAsyncIFrame("loader-frame",'loaderFrameHandler',loaderFrameHandler);

	// create iframe for loading details about sessions
	createAsyncIFrame("detail-frame","detailFrameHandler",detailFrameHandler);
	
	// create iframe for adding and removing sessions
	createAsyncIFrame("update-frame","updateFrameHandler",updateFrameHandler);

	/* Allow easier closing of scheduler detail windows.
	 **/
	addEvent( document.body, "keydown", keypressHandler );

	tabberAutomatic({});
});

function keypressHandler(e) {
	
	var e = (window.event) ? window.event : e;
	
	if( e.keyCode == 32 ){
		ModalDialog.hide();
		if( e.preventDefault ) {
			e.preventDefault();
		} else {
			e.returnValue = false;
		}
		return false;
	}
}

function loaderFrameHandler() {
	
	ProgressIndicator.hide();	
	
	var self = $("loader-frame");
					
	if( self.src && self.src.length && self.src != 'about:blank' ) {

		var content = getIFrameDocument(self).body.innerHTML;

		if( content.strip().length ) {
			LoaderFrameCache[self.src] = getIFrameDocument(self).body.innerHTML;
			$("session-list").innerHTML = getIFrameDocument(self).body.innerHTML;
			ModalDialog.hide();
		}
		
		self.src = 'about:blank';
	}
	
	return true;
}

function detailFrameHandler() {

	ProgressIndicator.hide();

	var self = $("detail-frame");

	if( self.src && self.src.length && self.src != 'about:blank' ) {	
		var content = getIFrameDocument(self).body.innerHTML.strip();		
		ModalDialog.hide();
		ModalDialog.setContent( content );
		ModalDialog.setTitle($("topic-title").innerHTML);
		ModalDialog.show();		
		self.src = 'about:blank';
	}
}

function updateFrameHandler() {		

	ProgressIndicator.hide();

	var self = $("update-frame");	
	var content = getIFrameDocument(self).body.innerHTML.strip();

	/* Update changes come back with a respones type in paranethasis appended to the 
	 * response HTML.
	 *
	 * ex.
	 *
	 * (day-Wednesday-schedule)
	 * <table class="data-table schedule">
	 *  <tr>
	 *    <th class="start-time">Start</th>
	 *    <th class="end-time">End</th>
	 *    <th class="speaker">Speaker</th>
	 *    <th class="title">Session</th>
	 *    <th class="track">Track</th>
	 *  </tr>
	 * ...
	 * </table>
	 *
	 * Is a success packet. The "body" of the response is the changed Schedule day to update.
	 *
	 * If there's a failure the message is in the form:
	 *
	 * (error)
	 * The session "#existingTopicName#" is already in your schedule and overlaps with 
	 * the session "#newTopicName#"
	 *
	 * The part in parenthasis is used to determine the response type.
	 */
	var result = content.substring(content.indexOf('(')+1,content.indexOf(')'));
	content = content.substring(content.indexOf(')')+1,content.length);

	ModalDialog.hide();
	
	/* If there's an error just display the message to the user. Else if it was successful
	 * then update that tab of the schedule and make it the active tab.
	 */
	if( result == 'error' ) {

		alert(content.stripTags().strip().replace('&amp;','&'));

	} else if( $(result) ) {
		
		$(result).innerHTML = content;
		var index = 0;
		var day = result.split('-')[1];
		$A($(result).parentNode.parentNode.parentNode.getElementsByTagName("a")).each( function(a){
			if( a.tabber ) {
				if( a.innerHTML == day ) {
					a.tabber.tabShow(index);
				} else {
					index++;
				}
			}
		});

	} else if( getIFrameDocument(self).title.toLowerCase() == 'cfunited scheduler: login' ) {
	
		window.location.href = "index.cfm?event=page.login";
	}
}

/* Creates a hidden iframe in the document for doing async requests to the server.
 */
function createAsyncIFrame( id, onLoadHandlerName, onLoadHandler ) {
	$("footer").innerHTML += '<iframe class="hidden-frame" id="' + id + '" onload="' + onLoadHandlerName + '()" src="about:blank"></iframe>';
}

function sessionDetailOnClick(a) {
	var frame = $("detail-frame");
	ProgressIndicator.show();
	frame.src = a.href.replace('user.','schedule.');
	return false;
}

function sessionSelectorOnClick(a) {
	ProgressIndicator.show();
	var url = a.href.replace('user.','schedule.');			
	if( !LoaderFrameCache[url] ) {
		var frame = $('loader-frame');
		frame.src = url;
	} else {
		$("session-list").innerHTML = LoaderFrameCache[url];
		ProgressIndicator.hide();
		ModalDialog.hide();
	}
	return false;
}

function sessionDeleteOnClick(a) {
	var frame = $('update-frame');
	ProgressIndicator.show();
	frame.src = a.href.toLowerCase().replace('user.deletesession','user.deletesessionasync') + '&' + Math.random();
	return false;
}

function sessionAddOnClick(a) {
	var frame = $('update-frame');
	ProgressIndicator.show();			
	frame.src = a.href.toLowerCase().replace('user.addsession','user.addsessionasync') + '&' + Math.random();
	return false;
}

/* Gets the document for the iframe. Does a little magic to get past conflicting 
 * implementations of how to get the actual document. Returns null if no suitable
 * document can be found.
 *
 * @return DOMDocument The document for the loaded iframe.
 */
function getIFrameDocument( iframe ) {

	if (iframe.contentDocument) {
		// For NS6
		return iframe.contentDocument; 
	} else if (iframe.contentWindow) {
		// For IE5.5 and IE6
		return iframe.contentWindow.document;
	} else if (iframe.document) {
		// For IE5
		return iframe.document;
	} else {
		return null;
	}
}

/* API for showing and hiding a progress indicator for when async iframes
 * are loading.
 */
ProgressIndicator = {

	/* Sets up the indicator.
	 */
	init: function() {
		var column = $("schedules");
		if( column ) {
			column = column.parentNode;
			column.innerHTML = '<p id="processing-alert" class="hidden">Processing...</p>' + column.innerHTML;
		}
	},

	/* Shows the indicator
	 */	
	show: function() {
		var node = $("processing-alert");
		if( node ) node.className = "";
	},
	
	/* Hides the indicator.
	 */	
	hide: function() {
		var node = $("processing-alert");
		if( node ) node.className = "hidden";
	}	
}