/**
 * POPUP WINDOW CODE
 * Used for displaying DHTML only popups instead of using buggy modal windows.
 *
 * By Seth Banks (webmaster at subimage dot com)
 * http://www.subimage.com/
 * *(Extensive modifications by DRC/CDeutsch)
 *
 * Contributions by Eric Angel (tab index code) and Scott (hiding/showing selects for IE users)
 *
 * Up to date code can be found at http://www.subimage.com/dhtml/subModal
 *
 * This code is free for you to use anywhere, just keep this comment block.
 */

var g_modalDivCol = new modalDivCol();

function modalDivCol()
{
  this.count = 0;
  this.collection = new Array();
}

modalDivCol.prototype.createModalDiv = function(clientId, width, height, title)
{
  
  this.count++;
  var objDiv = new modalDiv(clientId, width, height, title);
  this.collection.push(objDiv);
  
  return objDiv;
}

modalDivCol.prototype.getModalDiv = function(clientId)
{
	for (var i=0; i < this.count; i++) {
		if (this.collection[i].gClientId == clientId) return this.collection[i];
	}
}

modalDivCol.prototype.removeModalDiv = function(clientId)
{
	for (var i=0; i < this.count; i++) 
	{
		if(clientId==this.collection[i].gClientId ) 
		{
			this.collection.splice(i, 1);
			this.count--;
			break;
		}
	}	
}




 
function modalDiv(clientId, width, height, title)
{
    //set defaults.
    if (width == null || isNaN(width)) width = 300;
    if (height == null || isNaN(height)) height = 200;
    if (title == null) title = '';
    
    //globals that are safe to overwrite.
    this.gClientId       = clientId;
    this.gWidth          = width;
    this.gHeight         = height;
    this.gTitle          = title;

    // div elements.
    this.gPopupMask = null;
	  this.gPopupContainer = null;
	  this.gPopFrame = null;	
	  this.gPopTitleBar = null;	
	  this.gPopTitle = null;	
	  this.gCloseButton = null;	
	
	  //iframe shim.
	  this.gPopShim = null;
	
    // display properites.
    this.gPopupIsShown    = false;
    
    this.arguments = null;
    this.gReturnFunc = null;
    
    this.initPopWin();
}




            modalDiv.prototype.showMessage = function(text, title, width, height) 
            {
                this.sizePopWin('', parseInt(width), parseInt(height));
                var msgFrame = document.getElementById(this.gClientId+"iframePopup");
                msgFrame.contentWindow.document.write(this.buildMessage(text, null, "Close"));
                this.showPopWin(title, parseInt(width), parseInt(height)); 
            }


            modalDiv.prototype.showHTML = function(html, title, width, height) 
            {
                this.sizePopWin('', parseInt(width), parseInt(height));
                var msgFrame = document.getElementById(this.gClientId+"iframePopup");
                msgFrame.contentWindow.document.write(html);
                this.showPopWin(title, parseInt(width), parseInt(height)); 
            }

            modalDiv.prototype.buildMessage = function(text, okText, cancelText) 
            {
                var str = ""
                str += "<div style='margin:20px; font-family: Arial,Helvetica,sans-serif; font-size:small; '>";
                str += text;
                str += "</div>";
                str += "<br />";
                str += "<div class='dialogButtonDiv' style='margin:20px;text-align:right;'>";
                if (okText)
                  str += "<button style='width:80px;'>" + okText + "</button>";
                if (cancelText)
                  str += "<button style='width:80px;' onclick=\"window.top.g_modalDivCol.getModalDiv('" + this.gClientId + "').hidePopup(false);\">" + cancelText + "</button>";
                str += "</div>"
                
                return str;
            }


            modalDiv.prototype.loadPopup = function(url, width, height) 
            {
                this.sizePopWin('', parseInt(width), parseInt(height));

								// replace the location of the iframe instead of changing the src so we don't add to history
								var cw = document.getElementById(this.gClientId+"iframePopup").contentWindow;
								if (cw) cw.location.replace(url);
                //document.getElementById(this.gClientId+"iframePopup").src = url; 
            }

            modalDiv.prototype.showPopup2 = function(width, height, title, returnFunc) 
            {
              this.gReturnFunc = returnFunc;
              this.showPopWin(title, parseInt(width), parseInt(height)); 
            }

            modalDiv.prototype.showPopup = function(url, width, height, title, returnFunc) 
            {
                this.loadPopup(url, parseInt(width), parseInt(height)); 
                this.showPopup2(parseInt(width), parseInt(height), title, returnFunc); 
            }

            modalDiv.prototype.hidePopup = function(callReturnFunc) 
            {
                this.hidePopWin();
                if (callReturnFunc == true) { this.retVal = window.frames[document.getElementById(this.gClientId+"iframePopup").name].returnValue; }

								// replace the location of the iframe instead of changing the src so we don't add to history
								var cw = document.getElementById(this.gClientId+"iframePopup").contentWindow;
								if (cw) cw.location.replace("about:blank");
                //document.getElementById(this.gClientId+"iframePopup").src = "about:blank";

                if (callReturnFunc == true && this.gReturnFunc != null) { this.gReturnFunc(this.retVal); }
                $(this.gPopupContainer).fireEvent('popupclosed', this );
            }

            modalDiv.prototype.showCloseButton = function() {
                this.showCloseButton(); 
            }

            modalDiv.prototype.hideCloseButton = function() {
                this.hideCloseButton(); 
            }





















modalDiv.prototype.initPopWin = function() {

  this.createModalDivTags(this.gClientId);
  
	this.gPopupMask = document.getElementById(this.gClientId + "_popupMask");
	this.gPopupContainer = document.getElementById(this.gClientId + "_popupContainer");
	this.gPopFrame = document.getElementById(this.gClientId + "_popupFrame");	
	this.gPopTitleBar = document.getElementById(this.gClientId + "_popupTitleBar");	
	this.gPopTitle = document.getElementById(this.gClientId + "_popupTitle");	
	this.gPopShim = document.getElementById(this.gClientId + "_popupShim");	
	this.gCloseButton = document.getElementById(this.gClientId + "_closeButton");
}

modalDiv.prototype.createModalDivTags = function(baseId) 
{
  //assumes use of mootools.js
  
  var tObj = $(baseId+'_popupMask');
  if (!$(baseId+'_popupMask')) 
    tObj = new Element('div', { 'id': baseId+'_popupMask', 'class': 'ModalDivPopupMask' }).setStyle('display', 'none').setText('&nbsp').inject(document.body);
  if (!$(baseId+'_popupShim'))  
    tObj = new Element('iframe', { 'id': baseId+'_popupShim', 'src': '', 'scrolling': 'no', 'frameborder': 'no'})
                      .setStyles( { 'position': 'absolute', 'top': '0px', 'left': '0px', 'display': 'none' } ).inject(document.body);   

  if (!$(baseId+'_popupContainer'))
  {
    tObj = new Element('div', { 'id': baseId+'_popupContainer', 'class': 'ModalDivPopupContainer' }).setStyles({'z-index':'999', 'display':'none'}).inject(document.body);
    var inObj = new Element('div', { 'id': baseId+'_popuppopupInner', 'class': 'ModalDivPopupInner' }).inject(tObj);
    var tbObj = new Element('div', { 'id': baseId+'_popupTitleBar', 'class': 'ModalDivPopupTitleBar' }).inject(inObj);
    tObj = new Element('div', { 'id': baseId+'_popupTitle', 'class': 'ModalDivPopupTitle' }).inject(tbObj);
    tObj = new Element('div', { 'id': baseId+'_popupControls', 'class': 'ModalDivPopupControls' }).inject(tbObj);
    tObj = new Element('a', { 'id': baseId+'_closeButton', 'class': 'ModalDivCloseButton', 'href': '#',
                                  'events': { 'click': function(item){ g_modalDivCol.getModalDiv(baseId).hidePopup(false); } }}).inject(tObj);
                                  
    tObj = new Element('div', { 'id': baseId+'_popupFrame', 'class': 'ModalDivPopupFrame' }).inject(inObj);
    iObj = new Element('iframe', { 'id': baseId+'iframePopup', 'refid': baseId, 'src':'', 'scrolling':'auto', 'frameborder':'0', 'allowtransparency':'true', 'name':'MasterModalPopup', 'width':'100%', 'height':'100%'}).setStyles({'width':'100%', 'height':'100%', 'background-color':'transparent'}).inject(tObj);
  }
}

modalDiv.prototype.showPopWin = function(title, width, height) {
    if (this.gPopupMask == null) {
		this.initPopWin();
	}	
	
	this.gPopupIsShown = true;
	modalDivShared.gPopupCount += 1;
	modalDivShared.disableTabIndexes();
	this.gPopupMask.style.display = "block";
	this.gPopupContainer.style.display = "block";
	this.gPopShim.style.display="block";
	
	this.sizePopWin(title, width, height);
	
	// for IE
	if (modalDivShared.gHideSelects == true) {
		modalDivShared.hideSelectBoxes();
	}
}

modalDiv.prototype.sizePopWin = function(title, width, height) {
	if (this.gPopupMask == null) {
		this.initPopWin();
	}
	if (width == null || isNaN(width)) width = this.gWidth;
    if (height == null || isNaN(height)) height = this.gHeight;
    if (title == null) title = this.gTitle;
    
	// calculate where to place the window on screen
	modalDivShared.centerPopWin(width, height);
	
	var titleBarHeight = parseInt(this.gPopTitleBar.offsetHeight, 10);
	
	this.gPopupContainer.style.width = width + "px";
	this.gPopupContainer.style.height = (height+titleBarHeight) + "px";
	// need to set the width of the iframe to the title bar width because of the dropshadow
	// some oddness was occuring and causing the frame to poke outside the border in IE6
	this.gPopFrame.style.width = parseInt(this.gPopTitleBar.offsetWidth, 10) + "px";
	this.gPopFrame.style.height = (height) + "px";
	
	//use our iframe shim to hide content that likes to be on top.	
	modalDivShared.syncPopShim(this);
	
	this.gPopTitle.innerHTML = title;
}

modalDiv.prototype.hidePopWin = function() {
	this.gPopupIsShown = false;
	modalDivShared.gPopupCount += -1;
	modalDivShared.restoreTabIndexes();
	if (this.gPopupMask == null) {
		return;
	}
	this.gPopupMask.style.display = "none";
	this.gPopupContainer.style.display = "none";
	this.gPopShim.style.display="none";
	
	// display all select boxes
	if (modalDivShared.gHideSelects == true) {
		modalDivShared.displaySelectBoxes();
	}
}

modalDiv.prototype.hideCloseButton = function() {
    if (this.gCloseButton) {
	    this.gCloseButton.style.visibility="hidden";
    }
}

modalDiv.prototype.showCloseButton = function() {
    if (this.gCloseButton) {
	    this.gCloseButton.style.visibility="visible";
    }
}

//shared globals.
function modalDivShared()
{
}

modalDivShared.gPopupCount   = 0;
modalDivShared.gHideSelects  = false;
modalDivShared.gTabIndexes   = new Array();
// Pre-defined list of tags we want to disable/enable tabbing into
modalDivShared.gTabbableTags = new Array("A","BUTTON","TEXTAREA","INPUT","IFRAME");	
modalDivShared.gDragEnabled  = false;
modalDivShared.gIE           = document.all;
modalDivShared.gNS6          = document.getElementById && !document.all;
modalDivShared.gPrevX        = 0;
modalDivShared.gPrevY        = 0;

/**
 * Initializes popup code on load.	
 */
modalDivShared.initPopUp = function() {
	// 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) {
		modalDivShared.gHideSelects = true;
	}
}

modalDivShared.maskScreen = function() {
	//load page in disabled state.
	modalDivShared.disableTabIndexes();
    
    // for IE
	if (modalDivShared.gHideSelects == true) {
		modalDivShared.hideSelectBoxes();
	}
	
	modalDivShared.fixMask();
}

modalDivShared.centerPopWin = function(width, height) {
	
	var objDiv = null;
	for (var i=0; i < g_modalDivCol.count; i++) {
		objDiv = g_modalDivCol.collection[i];		
		if (objDiv.gPopupIsShown == true) {
			if (width == null || isNaN(width)) {
				width = objDiv.gPopupContainer.offsetWidth;
			}
			if (height == null) {
				height = objDiv.gPopupContainer.offsetHeight;
			}
			
			var fullHeight = modalDivShared.getViewportHeight();
			var fullWidth = modalDivShared.getViewportWidth();
			
			var theBody = document.documentElement;
			
			var scTop = parseInt(theBody.scrollTop,10);
			var scLeft = parseInt(theBody.scrollLeft,10);
			
			objDiv.gPopupMask.style.height = fullHeight + "px";
			objDiv.gPopupMask.style.width = fullWidth + "px";
			objDiv.gPopupMask.style.top = scTop + "px";
			objDiv.gPopupMask.style.left = scLeft + "px";
			
			var titleBarHeight = parseInt(objDiv.gPopTitleBar.offsetHeight, 10);
			
			objDiv.gPopupContainer.style.top = (scTop + ((fullHeight - (height+titleBarHeight)) / 2)) + "px";
			objDiv.gPopupContainer.style.left =  (scLeft + ((fullWidth - width) / 2)) + "px";
			
			//save current x, y to support drag functionality.
			modalDivShared.gPrevX = parseInt(objDiv.gPopupContainer.style.top);
			modalDivShared.gPrevY = parseInt(objDiv.gPopupContainer.style.left);
			
			//use our iframe shim to hide content that likes to be on top.	
			modalDivShared.syncPopShim(objDiv);
		}
	}
}

modalDivShared.syncPopShim = function(objDiv) {
    //use our iframe shim to hide content that likes to be on top.	
    objDiv.gPopShim.style.width=objDiv.gPopupContainer.offsetWidth;
    objDiv.gPopShim.style.height=objDiv.gPopupContainer.offsetHeight;
    objDiv.gPopShim.style.top=objDiv.gPopupContainer.style.top;
    objDiv.gPopShim.style.left=objDiv.gPopupContainer.style.left;
    objDiv.gPopShim.style.zIndex=objDiv.gPopupContainer.style.zIndex-1;
    objDiv.gPopShim.style.display="block";
}

modalDivShared.startDrag = function(e) {
    if (!modalDivShared.gIE && !modalDivShared.gNS6) return;
    
    //find the object that fired the event.
    var objFired = modalDivShared.gNS6? e.target : event.srcElement;

	
	//only handle this if they're clicking on the title bar.
	if(objFired.className != 'ModalDivPopupTitleBar' && objFired.className != 'ModalDivPopupTitle'  && 
	   objFired.className != 'ModalDivPopupControls') return;
     
    //find the div that is currently visible.
    var objDiv = null;
    for (var i=0; i < g_modalDivCol.count; i++) {
        objDiv = g_modalDivCol.collection[i];		
        if (objDiv.gPopupIsShown == true) {
	        modalDivShared.gDragEnabled = true;
	        
	        modalDivShared.gPrevX = (modalDivShared.gNS6 ? e.screenX: event.screenX);
          modalDivShared.gPrevY = (modalDivShared.gNS6 ? e.screenY: event.screenY);
          modalDivShared.addEvent(document, "mousemove", modalDivShared.move);

					var tNode = e.srcElement;
					while (tNode && tNode.nodeName!="#document" && tNode.hasClass('ModalDivPopupInner')==false) tNode=tNode.getParent();
					if(tNode && tNode.nodeName!="#document")
					{
						tNode = tNode.getElement('iframe').contentWindow;
						if (tNode)
							$(tNode.document.body).addEvent("mousemove", function(event){ modalDivShared.move(event); });          
					}

          return false;
        }   
    }
}

modalDivShared.stopDrag = function(e) {
    //cancel mouse move handler.
    modalDivShared.gDragEnabled = false;
    modalDivShared.removeEvent(document, "mousemove", modalDivShared.move, false);


		for (var i=0; i<g_modalDivCol.collection.length; i++)
		{
			var obj = g_modalDivCol.collection[i].gPopupContainer;
			if (obj) obj = obj.getElement('iframe');
			if (obj) obj = obj.contentWindow;
			if (obj) obj = $(obj.document.body);
			if (obj) obj.removeEvents('mousemove');
		}

}

modalDivShared.move = function(e) {
	
    if (modalDivShared.gDragEnabled) {

		if (!e) e = event;

		// sometime the drop action is not caught so check to make sure the button is still pressed.
		if (e.button != 1)  { modalDivShared.stopDrag(); return; }

        //calculate new X, Y coords.
		//var eventX = (modalDivShared.gNS6 ? e.screenX : event.screenX);
		//var eventY = (modalDivShared.gNS6 ? e.screenY : event.screenY);
		var eventX = e.screenX;
		var eventY = e.screenY;

        //find the div that is currently visible.
        var objDiv = null;
        for (var i=0; i < g_modalDivCol.count; i++) {
	        objDiv = g_modalDivCol.collection[i];		
	        if (objDiv.gPopupIsShown == true) {
	            //move the container div.
	            var newLeft = parseInt(objDiv.gPopupContainer.style.left) + (eventX - modalDivShared.gPrevX);
	            var newTop = parseInt(objDiv.gPopupContainer.style.top) + (eventY - modalDivShared.gPrevY);
	            if (newLeft < 0) newLeft = 0;
	            if (newTop < 0) newTop = 0;
	            objDiv.gPopupContainer.style.left = newLeft;
	            objDiv.gPopupContainer.style.top = newTop;
                //use our iframe shim to hide content that likes to be on top.	
			   			modalDivShared.syncPopShim(objDiv);
			
			    //update current x, y coords.
              modalDivShared.gPrevX = eventX;
              modalDivShared.gPrevY = eventY; 
                
              modalDivShared.fixMask();
                
              return false;
	        }
        }
    }
}


modalDivShared.fixMask = function() {
	var objDiv = null;
	for (var i=0; i < g_modalDivCol.count; i++) {
		objDiv = g_modalDivCol.collection[i];		
		if (objDiv.gPopupIsShown == true) {
			width = objDiv.gPopupContainer.offsetWidth;
			height = objDiv.gPopupContainer.offsetHeight;
			
			var fullHeight = modalDivShared.getViewportHeight();
			var fullWidth = modalDivShared.getViewportWidth();
			
			var theBody = document.documentElement;
			
			var scTop = parseInt(theBody.scrollTop,10);
			var scLeft = parseInt(theBody.scrollLeft,10);
			
			objDiv.gPopupMask.style.height = fullHeight + "px";
			objDiv.gPopupMask.style.width = fullWidth + "px";
			objDiv.gPopupMask.style.top = scTop + "px";
			objDiv.gPopupMask.style.left = scLeft + "px";
		}
	}
}

modalDivShared.hideAllOnError = function() {
    modalDivShared.hideAll();
    return false;
}

modalDivShared.hideAll = function() {
    var objDiv = null;
	for (var i=0; i < g_modalDivCol.count; i++) {
		objDiv = g_modalDivCol.collection[i];		
		if (objDiv.gPopupIsShown == true) {
		    objDiv.hidePopWin();
		}
	}
}

// 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.
modalDivShared.keyDownHandler = function(e) {
    if (modalDivShared.gPopupCount > 0 && e.keyCode == 9)  return false;
}

// For IE.  Go through predefined tags and disable tabbing into them.
modalDivShared.disableTabIndexes = function() {
	if (document.all) {
		var i = 0;
		for (var j = 0; j < modalDivShared.gTabbableTags.length; j++) {
			var tagElements = document.getElementsByTagName(modalDivShared.gTabbableTags[j]);
			for (var k = 0 ; k < tagElements.length; k++) {
				modalDivShared.gTabIndexes[i] = tagElements[k].tabIndex;
				tagElements[k].tabIndex="-1";
				i++;
			}
		}
	}
}

// For IE. Restore tab-indexes.
modalDivShared.restoreTabIndexes = function() {
	if (document.all) {
		var i = 0;
		for (var j = 0; j < modalDivShared.gTabbableTags.length; j++) {
			var tagElements = document.getElementsByTagName(modalDivShared.gTabbableTags[j]);
			for (var k = 0 ; k < tagElements.length; k++) {
				tagElements[k].tabIndex = modalDivShared.gTabIndexes[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!
*/
modalDivShared.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 == "SELECT") {
				document.forms[i].elements[e].style.visibility="hidden";
			}
		}
	}
	var objDiv = null;
	for (var i=0; i < g_modalDivCol.count; i++) {
		objDiv = g_modalDivCol.collection[i];		
		if (objDiv.gPopupIsShown == true) {
		    var ctrls = objDiv.gPopFrame.getElementsByTagName("SELECT");
		    for (var x = 0; x < ctrls.length; x++) {
		        if(ctrls[x].tagName == "SELECT") {
		            ctrls[x].style.visibility="visible";	            
		        }
		    }
		}
	}
}

/**
* 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
*/
modalDivShared.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 == "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
 */
modalDivShared.addEvent = function(obj, evType, fn){
 if (obj.addEventListener){
    obj.addEventListener(evType, fn, true);
    return true;
 } else if (obj.attachEvent){
    var r = obj.attachEvent("on"+evType, fn);
    return r;
 } else {
    return false;
 }
}
modalDivShared.removeEvent = function(obj, evType, fn, useCapture){
  if (obj.removeEventListener){
    obj.removeEventListener(evType, fn, useCapture);
    return true;
  } else if (obj.detachEvent){
    var r = obj.detachEvent("on"+evType, fn);
    return r;
  } else {
    alert("Handler could not be removed");
  }
}

/**
 * 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.
 */
modalDivShared.getViewportHeight = function() {
	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; 
}
modalDivShared.getViewportWidth =  function() {
	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; 
}

modalDivShared.initPopUp();
    
window.onerror = modalDivShared.hideAllOnError;
modalDivShared.addEvent(document, "mousedown", modalDivShared.startDrag);
modalDivShared.addEvent(document, "mouseup", modalDivShared.stopDrag);
modalDivShared.addEvent(window, "resize", modalDivShared.fixMask);
modalDivShared.addEvent(window, "scroll", modalDivShared.fixMask);

// If using Mozilla or Firefox, use Tab-key trap.
if (!document.all) {
	document.onkeypress = modalDivShared.keyDownHandler;
}



