/* Usage:

	ModalDialog.init("images/cfu_icon.gif","Press the spacebar to close this dialog.");
	ModalDialog.height = 500;
	ModalDialog.width = 500;
	ModalDialog.setTitle("Some awesome topic");
	ModalDialog.setContent( response.innerHTML );
	ModalDialog.show();
	//...
	ModalDialog.hide();
*/


/** 
 * Allows displaying a model dialog over the document.
 *
 */
var ModalDialog = {

	// Popup code
	mask: null,
	container: null,
	isShown: false,
	hideSelects: false,
	tabIndexes: [],
	width: 0, 
	height: 0,
	
	// Pre-defined list of tags we want to disable/enable tabbing into
	tabbableTags: ["A","BUTTON","TEXTAREA","INPUT","IFRAME"],
		
	/**
	 * Initializes popup code on load.	
	 *
	 */
	init: function( iconSrc, statusbarText ) {
		
		if( !iconSrc ) iconSrc = "";
		if( !statusbarText ) statusbarText = "";
		
		// create the dialog markup
		this.createDialogHTML( iconSrc, statusbarText );

		// If using Mozilla or Firefox, use Tab-key trap.
		//
		// TODO: Is this really needed? Why do we want to kill all tab presses
		//       when the dialog is shown?
		if( !document.all ) {
			addEvent( 
				"keypress", 
				function() { if( this.isShown && e.keyCode == 9 ) return false; } 
			);
		}
		
		// handle window resizes
		addEvent( window, "resize", this.centerPopup );
		addEvent( window, "scroll", this.centerPopup );
		
		this.mask = document.getElementById("popupMask");
		this.container = document.getElementById("popupContainer");
				
//TODO: make sure this check really works:
				
		// check to see if this is IE version 6 or lower. hide select boxes if 
		// so maybe they'll fix this in version 7?
		var ieVersion = parseInt(window.navigator.appVersion.charAt(0), 10);
		if( ieVersion <= 6 ) this.hideSelects = true;
	},
	
	createDialogHTML: function( iconSrc, statusBarText ) {
	
		var popupMask = document.createElement("div");
		popupMask.id = "popupMask";
				
		var popupContainer = document.createElement("div");
		popupContainer.id = "popupContainer";
		
        popupContainer.innerHTML = '                                \
            <div id="popupInner">                                   \
              <div id="popupTitleBar">                              \
               <div id="popupIcon">                                 \
                <img src="' + iconSrc + '" alt="">                  \
               </div>                                               \
               <div id="popupTitle"></div>                          \
               <div id="popupControls">                             \
                <img src="/2009/images/close.gif" onclick="ModalDialog.hide()" alt="Close"> \
               </div>                                               \
              </div>                                                \
                <div id="popup-frame-content"></div>                \
                <p id="popup-statusbar">' + statusBarText + '</p>   \
             </div>                                                 \
        ';

		popupContainer.getElementsByTagName("img")[1].onclick = function() {
			ModalDialog.hide();
		}
		
		document.body.appendChild( popupMask );
		document.body.appendChild( popupContainer );
	},
		
	/**
	 * Displays the dialog.
	 */
	show: function() {

		this.disableTabIndexes();
		this.mask.style.display = "block";
		this.container.style.display = "block";
		
		this.isShown = true;
		
		// calculate where to place the window on screen
		this.centerPopup();
		
		var titleBarHeight = parseInt(document.getElementById("popupTitleBar").offsetHeight, 10);
		
		this.container.style.width = this.width + "px";
		this.container.style.height = (this.height+titleBarHeight) + "px";
		
		// for IE
		if( this.hideSelects ) this.hideSelectBoxes();		
	},
	
	/**
	 * Centers the dialog inside the viewport.
	 */
	centerPopup: function() {
	
		var width = ModalDialog.width;
		var height = ModalDialog.height;
	
		if( ModalDialog.isShown ) {
			
			if( width == null || isNaN(width) ) width = ModalDialog.container.offsetWidth;
			
			if( height == null ) height = ModalDialog.container.offsetHeight;
			
			var fullHeight = getViewportHeight();
			var fullWidth = getViewportWidth();
			
			var html = document.documentElement;
			
			var top = parseInt(html.scrollTop,10);
			var left = parseInt(html.scrollLeft,10);
			
			var maskStyle = ModalDialog.mask.style;
			maskStyle.height = fullHeight + "px";
			maskStyle.width = fullWidth + "px";
			maskStyle.top = top + "px";
			maskStyle.left = left + "px";
						
			var titleBarHeight = parseInt(document.getElementById("popupTitleBar").offsetHeight, 10);
			
			ModalDialog.container.style.top = (top + ((fullHeight - (height+titleBarHeight)) / 2)) + "px";
			ModalDialog.container.style.left =  (left + ((fullWidth - width) / 2)) + "px";
	
			/* Fix for safari which seems to not properly report scrollTop making the 
			 * window centering fail. This should really be done in the CSS instead of
			 * here... Firefox 1.0.7/mac seems to exhibit weird behavior too here...
			 *
			 * - Elliott Sprehn (elliott@teratech.com)
			 *   TeraTech, Inc.
			 *   May 18, 2006
			 */
			var userAgent = navigator.userAgent.toLowerCase();
			if( (userAgent.indexOf('safari')!=-1) && (userAgent.indexOf('mac')!=-1) ) {
				ModalDialog.mask.style.position = 'fixed';
				ModalDialog.container.style.position = 'fixed';
			}
		}
	},
	
	/**
	 * @argument callReturnFunc - bool - determines if we call the return function specified
	 * @argument returnVal - anything - return value 
	 */
	hide: function() {

		this.isShown = false;
		this.restoreTabIndexes();
				
// TODO: How can the mask ever not be defined?
//
//		if( !this.mask ) return;

		this.mask.style.display = "none";
		this.container.style.display = "none";

		// display all select boxes
		if( this.hideSelects ) this.displaySelectBoxes();
	},
	
	/**
	 * Sets the popup title.
	 */
	setTitle: function( value ) {
	
		document.getElementById("popupTitle").innerHTML = value;
	},
	
	/**
	 * Sets the popup content.
	 */
	setContent: function( value ) {
	
		document.getElementById("popup-frame-content").innerHTML = value;
	},
		
	/**
	 * For IE.  Go through predefined tags and disable tabbing into them.
	 *
	 * TODO: Looks like there's going to be an out of bounds index condition 
	 *       with the variable `i' in this function.
	 */
	disableTabIndexes: function() {
		
		if( document.all ) {
			var i = 0;
			for( var j = 0; j < this.tabbableTags.length; j++ ) {
				var tagElements = document.getElementsByTagName(this.tabbableTags[j]);
				for (var k = 0 ; k < tagElements.length; k++) {
					this.tabIndexes[i] = tagElements[k].tabIndex;
					tagElements[k].tabIndex="-1";
					i++;
				}
			}
		}
	},
	
	/**
	 * For IE. Restore tab-indexes.
	 */
	restoreTabIndexes: function() {
	
		if( document.all ) {
			var i = 0;
			for( var j = 0; j < this.tabbableTags.length; j++ ) {
				var tagElements = document.getElementsByTagName(this.tabbableTags[j]);
				for (var k = 0 ; k < tagElements.length; k++) {
					tagElements[k].tabIndex = this.tabIndexes[i];
					tagElements[k].tabEnabled = true;
					i++;
				}
			}
		}
	},
	
	/**
	 * Hides all drop down form select boxes on the screen so they do not appear 
	 * above the mask layer. IE has a problem with wanting select form tags to 
	 * always be the topmost z-index or layer
	 *
	 * Thanks for the code Scott! Who the hell is Scott? :P
	 */
	hideSelectBoxes: function() {
	
		for( var i = 0; i < document.forms.length; i++ ) {
			for( var e = 0; e < document.forms[i].length; e++ ){
				if( document.forms[i].elements[e].tagName.toUpperCase() == "SELECT" ) {
					document.forms[i].elements[e].style.visibility = "hidden";
				}
			}
		}
	},
	
	/**
	 * Makes all drop down form select boxes on the screen visible so they do 
	 * not reappear after the dialog is closed. IE has a problem with wanted 
	 * select form tags to always be the topmost z-index or layer
	 */
	displaySelectBoxes: function() {

		for( var i = 0; i < document.forms.length; i++ ) {
			for( var e = 0; e < document.forms[i].length; e++ ){
				if( document.forms[i].elements[e].tagName.toUpperCase() == "SELECT" ) {
					document.forms[i].elements[e].style.visibility="visible";
				}
			}
		}
	}
}