/**
 * This derivative version of subModal can be downloaded from http://gabrito.com/files/subModal/
 * Original By Seth Banks (webmaster at subimage dot com)  http://www.subimage.com/
 * Contributions by Eric Angel (tab index code), Scott (hiding/showing selects for IE users), Todd Huss (submodal class on hrefs, moving div containers into javascript, phark method for putting close.gif into CSS), Thomas Risberg (safari fixes for scroll amount), Dave Campbell (improved parsing of submodal-width-height class)
 */

// Popup code
var g2PopupMask = null;
var g2PopupContainer = null;
var g2PopFrame = null;
var g2ReturnFunc;
var g2PopupIsShown = false;
var g2HideSelects = false;
var g2Loading = "loading.html";

var g2TabIndexes = new Array();
// Pre-defined list of tags we want to disable/enable tabbing into
var g2TabbableTags = new Array("A","BUTTON","TEXTAREA","INPUT","IFRAME");	

// If using Mozilla or Firefox, use Tab-key trap.
if (!document.all) {
	document.onkeypress = key2DownHandler;
}

/**
 * Override the loading page from loading.html to something else
 */
function set2PopUpLoadingPage(loading) {
	g2Loading = loading;
}

/**
 * Initializes popup code on load.	
 */
function init2PopUp() {
	// Add the HTML to the body
	var body = document.getElementsByTagName('body')[0];
	var popmask = document.createElement('div');
	popmask.id = 'popup2Mask';
	var popcont = document.createElement('div');
	popcont.id = 'popup2Container';
	popcont.innerHTML = '' +
		'<div id="popup2Inner">' +
			'<div id="popup2TitleBar">' +
				'<div id="popup2Title"></div>' +
				'<div id="popup2Controls">' +
					'<a onclick="hide2PopWin(false);"><span>Close</span></a>' +
				'</div>' +
			'</div>' +
			'<iframe src="'+g2Loading+'" style="width:100%;height:100%;background-color:transparent;" scrolling="none" frameborder="0" allowtransparency="true" id="popup2Frame" name="popup2Frame" width="100%" height="100%"></iframe>' +
		'</div>';
	body.appendChild(popmask);
	body.appendChild(popcont);
	
	g2PopupMask = document.getElementById("popup2Mask");
	g2PopupContainer = document.getElementById("popup2Container");
	g2PopFrame = document.getElementById("popup2Frame");	
	
	// 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 brsVersion = parseInt(window.navigator.appVersion.charAt(0), 10);
	if (brsVersion <= 6 && window.navigator.userAgent.indexOf("MSIE") > -1) {
		g2HideSelects = true;
	}
	
	// Add onclick handlers to 'a' elements of class submodal or submodal-width-height
	var elms = document.getElementsByTagName('a');
	for (i = 0; i < elms.length; i++) {
		if (elms[i].className.indexOf("submodal") >= 0) { 
			elms[i].onclick = function(){
				// default width and height
				var width = 400;
				var height = 200;
				// Parse out optional width and height from className
				var startIndex = this.className.indexOf("submodal");
				var endIndex = this.className.indexOf(" ", startIndex);
				if (endIndex < 0) {
					endIndex = this.className.length;
				}
				var clazz = this.className.substring(startIndex, endIndex);
				params = clazz.split('-');
				if (params.length == 3) {
					width = parseInt(params[1]);
					height = parseInt(params[2]);
				}
				show2PopWin(this.href,width,height,null); return false;
			}
		}
	}
}
add2Event(window, "load", init2PopUp);

 /**
	* @argument width - int in pixels
	* @argument height - int in pixels
	* @argument url - url to display
	* @argument returnFunc - function to call when returning true from the window.
	* @argument showCloseBox - show the close box - default true
	*/

function show2PopWin(url, canvas, width, height, returnFunc, showCloseBox) {

  // show or hide the window close widget
	if (showCloseBox == null || showCloseBox == true) {
		document.getElementById("popup2Controls").style.display = "block";
	} else {
		document.getElementById("popup2Controls").style.display = "none";
	}

	g2PopupInner = document.getElementById("popup2Inner");
	g2PopupInner.style.backgroundImage = 'url(' + canvas + ')';
	g2PopupInner.style.backgroundRepeat = 'no-repeat';
	
	g2PopupIsShown = true;
	disableTabIndexes();
	g2PopupMask.style.display = "block";
	g2PopupContainer.style.display = "block";
	center2PopWin(width, height);
	var titleBarHeight = parseInt(document.getElementById("popup2TitleBar").offsetHeight, 10);
	g2PopupContainer.style.width = width + "px";
	g2PopupContainer.style.height = (height+titleBarHeight) + "px";
	g2PopFrame.style.width = parseInt(document.getElementById("popup2TitleBar").offsetWidth, 10) + "px";
	g2PopFrame.style.height = (height) + "px";
	g2PopFrame.src = url;
	g2ReturnFunc = returnFunc;
	// for IE
	if (g2HideSelects == true) {
		hide2SelectBoxes();
	}
	//window.setTimeout("setPopTitleAndRewriteTargets();", 100);
}

//
var gi = 0;
function center2PopWin(width, height) {
	if (g2PopupIsShown == true) {
		if (width == null || isNaN(width)) {
			width = g2PopupContainer.offsetWidth;
		}
		if (height == null) {
			height = g2PopupContainer.offsetHeight;
		}
		var fullHeight = getViewportHeight();
		var fullWidth = getViewportWidth();
		// scLeft and scTop changes by Thomas Risberg
		var scLeft,scTop;
		if (self.pageYOffset) {
			scLeft = self.pageXOffset;
			scTop = self.pageYOffset;
		} else if (document.documentElement && document.documentElement.scrollTop) {
			scLeft = document.documentElement.scrollLeft;
			scTop = document.documentElement.scrollTop;
		} else if (document.body) {
			scLeft = document.body.scrollLeft;
			scTop = document.body.scrollTop;
		} 
		g2PopupMask.style.height = fullHeight + "px";
		g2PopupMask.style.width = fullWidth + "px";
		g2PopupMask.style.top = scTop + "px";
		g2PopupMask.style.left = scLeft + "px";
		window.status = g2PopupMask.style.top + " " + g2PopupMask.style.left + " " + gi++;
		var titleBarHeight = parseInt(document.getElementById("popup2TitleBar").offsetHeight, 10);
		var topMargin = scTop + ((fullHeight - (height+titleBarHeight)) / 2);
		if (topMargin < 0) { topMargin = 0; }
		g2PopupContainer.style.top = topMargin + "px";
		g2PopupContainer.style.left =  (scLeft + ((fullWidth - width) / 2)) + "px";
	}
}
add2Event(window, "resize", center2PopWin);
//addEvent(window, "scroll", centerPopWin);
window.onscroll = center2PopWin;

/**
 * @argument callReturnFunc - bool - determines if we call the return function specified
 * @argument returnVal - anything - return value 
 */
function hide2PopWin(callReturnFunc) {
	g2PopupIsShown = false;
	restoreTabIndexes();
	if (g2PopupMask == null) {
		return;
	}
	g2PopupMask.style.display = "none";
	g2PopupContainer.style.display = "none";
	if (callReturnFunc == true && gReturnFunc != null) {
		gReturnFunc(window.frames["popup2Frame"].returnVal);
	}
	g2PopFrame.src = gLoading;
	// display all select boxes
	if (g2HideSelects == true) {
		display2SelectBoxes();
	}
}

/**
 * Sets the popup title based on the title of the html document it contains.
 * Also adds a base attribute so links and forms will jump out out of the iframe
 * unless a base or target is already explicitly set.
 * Uses a timeout to keep checking until the title is valid.
 */
function set2PopTitleAndRewriteTargets() {
	if (window.frames["popup2Frame"].document.title == null) {
		window.setTimeout("set2PopTitleAndRewriteTargets();", 10);
	} else {
		var popupDocument = window.frames["popup2Frame"].document;
		document.getElementById("popup2Title").innerHTML = popupDocument.title;
		if (popupDocument.getElementsByTagName('base').length < 1) {
			var aList  = window.frames["popup2Frame"].document.getElementsByTagName('a');
			for (var i = 0; i < aList.length; i++) {
				if (aList.target == null) aList[i].target='_parent';
			}
			var fList  = window.frames["popup2Frame"].document.getElementsByTagName('form');
			for (i = 0; i < fList.length; i++) {
				if (fList.target == null) fList[i].target='_parent';
			}
		}
	}
}

// Tab key trap. iff popup is shown and key was [TAB], suppress it.
// @argument e - event - keyboard event that caused this function to be called.
function key2DownHandler(e) {
    if (g2PopupIsShown && e.keyCode == 9)  return false;
}

// For IE.  Go through predefined tags and disable tabbing into them.
function disable2TabIndexes() {
	if (document.all) {
		var i = 0;
		for (var j = 0; j < g2TabbableTags.length; j++) {
			var tagElements = document.getElementsByTagName(g2TabbableTags[j]);
			for (var k = 0 ; k < tagElements.length; k++) {
				g2TabIndexes[i] = tagElements[k].tabIndex;
				tagElements[k].tabIndex="-1";
				i++;
			}
		}
	}
}

// For IE. Restore tab-indexes.
function restore2TabIndexes() {
	if (document.all) {
		var i = 0;
		for (var j = 0; j < g2TabbableTags.length; j++) {
			var tagElements = document.getElementsByTagName(g2TabbableTags[j]);
			for (var k = 0 ; k < tagElements.length; k++) {
				tagElements[k].tabIndex = g2TabIndexes[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 wanted select form tags to always be the topmost z-index or layer
* Thanks for the code Scott!
*/
function hide2SelectBoxes() {
	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 == "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
*/
function display2SelectBoxes() {
	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 == "SELECT") {
			document.forms[i].elements[e].style.visibility="visible";
			}
		}
	}
}

/**
 * X-browser event handler attachment and detachment
 * @argument obj - the object to attach event to
 * @argument evType - name of the event - DONT ADD "on", pass only "mouseover", etc
 * @argument fn - function to call
 */
function add2Event(obj, evType, fn){
 if (obj.addEventListener){
    obj.addEventListener(evType, fn, false);
    return true;
 } else if (obj.attachEvent){
    var r = obj.attachEvent("on"+evType, fn);
    return r;
 } else {
    return false;
 }
}

/**
 * Code below taken from - http://www.evolt.org/article/document_body_doctype_switching_and_more/17/30655/ *
 * Modified 4/22/04 to work with Opera/Moz (by webmaster at subimage dot com)
 * Gets the full width/height because it's different for most browsers.
 */
function get2ViewportHeight() {
	if (window.innerHeight!=window.undefined) return window.innerHeight;
	if (document.compatMode=='CSS1Compat') return document.documentElement.clientHeight;
	if (document.body) return document.body.clientHeight; 
	return window.undefined; 
}

function get2ViewportWidth() {
	if (window.innerWidth!=window.undefined) return window.innerWidth; 
	if (document.compatMode=='CSS1Compat') return document.documentElement.clientWidth; 
	if (document.body) return document.body.clientWidth; 
	return window.undefined; 
}


