d = document;
dHtml = d.firstChild;
dHead = document.getElementsByTagName('head').item(0);
dBody = '';

//Create border Div. This is the outermost container and set properties needed for sizing and moving
pBorder = d.createElement('div');
pBorder.id = "border_protoType";
pBorder.width = "206px";
pBorder.height = "306px";
pBorder.style.left = "0px";
pBorder.style.top = "0px";
pBorder.style.position = "absolute";
pBorder.style.visibility = 'hidden';
pBorder.style.zIndex = '700';
pBorder.className = "dynamicWindowBorder";

//create external frame for window inside border div
pWindow = d.createElement('Div');
pWindow.id = 'outerDiv_protoType';
pWindow.style.width = "200px";
pWindow.style.height = "300px";
pWindow.style.overflow = 'hidden';
pWindow.className = "dynamicWindowOuter";
pBorder.appendChild(pWindow);

//create title bar div
pTitleBar = d.createElement('Div');
pTitleBar.id = 'titleBar_protoType';
pTitleBar.style.cssFloat = "left"; //for all non IE browsers
pTitleBar.style.styleFloat = "left"; //for IE browsers
pTitleBar.style.cursor = 'default';
pTitleBar.style.top = "0px";
pTitleBar.style.left = "0px";
pTitleBar.style.width = "100%";
pTitleBar.style.height = "23px";
pTitleBar.style.paddingLeft = "4px";
pTitleBar.style.overflow = "hidden";
pTitleBar.style.fontSize = "17px";
pTitleBar.className = "dynamicWindowTitleBar";
pTitleBar.onclick = "event.cancelBubble = true;";
pWindow.appendChild(pTitleBar);

//create close box
pCloseBox = d.createElement('Div');
pCloseBox.id = "closeBox_protoType";
pCloseBox.style.cssFloat = "right";
pCloseBox.style.styleFloat = "right";
//pCloseBox.style.paddingRight = '5px';
pCloseBox.style.marginRight = '5px';
pCloseBox.style.marginTop = '1px';
pCloseBox.className = "dynamicWindowCloseBox";
pTitleBar.appendChild(pCloseBox);

//create Minimize box
pMinimizeBox = d.createElement('Div');
pMinimizeBox.id = "minimizeBox_protoType";
pMinimizeBox.style.cssFloat = "right";
pMinimizeBox.style.styleFloat = "right";
pMinimizeBox.style.marginRight = '1px';
pMinimizeBox.style.marginTop = '1px';
pMinimizeBox.className = "dynamicWindowMinimizeBox";
pTitleBar.appendChild(pMinimizeBox);

//create body div
pBody = d.createElement('Div');
pBody.id = "body_protoType";
pBody.style.cssFloat = "left";
pBody.style.styleFloat = "left";
pBody.style.width = "100%";
pBody.style.overflow = 'auto';
pBody.className = "dynamicWindowBody";
pWindow.appendChild(pBody);

pContentBox = d.createElement('Div');
pContentBox.id = 'bodyContent_prototype';
pBody.appendChild(pContentBox);

//create Status Bar
pStatusBar = d.createElement('Div');
pStatusBar.id = "statusBar_protoType";
pStatusBar.style.cssFloat = "left";
pStatusBar.style.styleFloat = "left";
pStatusBar.style.height = "25px";
pStatusBar.style.width="100%";
pStatusBar.style.bottom="0px";
pStatusBar.style.visibility = "hidden";
pStatusBar.className = "dynamicWindowStatusBar";
pWindow.appendChild(pStatusBar);

//create Drag Size box
pDragSizeBox = d.createElement('Div');
pDragSizeBox.id = "dragSizeBox_protoType";
pDragSizeBox.style.position = "absolute";
pDragSizeBox.style.right="0px";
pDragSizeBox.style.bottom="0px";
pDragSizeBox.style.height = "10px";
pDragSizeBox.style.width="10px";
pDragSizeBox.style.visibility = "hidden";
pDragSizeBox.className = "dynamicWindowDragSizeBox";
pWindow.appendChild(pDragSizeBox);

//attach prototype to body element
dHead.appendChild(pBorder);

/*
function to call to create a window. No parameters are mandatory, though contentURL is used to populate the window in most cases.
id = id of the window. Different elements will have different prefixes (ie outerDiv_id)
title = the text that will appear on the title bar
height = total height of the window.
Body height is based dynamically off this value, title bar height, and if there is a status bar
Width = total width of window. Title bar window is this value - closebox and minimize box if exist
xPos = x position relative to parent.
yPos = y position relative to parent.
oParent = windows parent element. Will be the body element by default.
byId = if oParent is the id of parent element, set to true to getElementById
closable = if true displays close box. on by default.
minimizable = if true displays minimize box. off by default
(note this functionality has not yet been added)
statusBar = if true displays status bar at bottom. off by default
(note this functionality has not yet been added)
contentURL = The URL of the module to load into the body of the window. 
(note Relative pathnames are ok, and preffered. GET urls are also allowed.)
*/
function windowCreator(id,contentURL,executeAfterOpen) {	
	target = this;
	this.id = id;
	this.contentURL = contentURL;
	this.processWindowCreator = function(target) {
		// only if req shows "complete"
		if (this.req.readyState == 4) {
			// only if "OK"
			if (this.req.status == 200) {
				this.contentBody = this.req.responseText;
				this.moduleDefinitionStart = this.contentBody.indexOf('--module definition--');
				this.moduleDefinitionEnd = this.contentBody.indexOf('--end definition--');
				this.moduleDefinition = this.contentBody.substr(this.moduleDefinitionStart,this.moduleDefinitionEnd - this.moduleDefinitionStart);
				this.moduleDefinitionArray = this.moduleDefinition.split('\r\n');
				for (this.i=1; this.i<(this.moduleDefinitionArray.length); this.i++) {
						if (this.moduleDefinitionArray[this.i].indexOf('=') > 0) {
						this.expression = this.moduleDefinitionArray[this.i];
						this.varName = this.expression.substr(0,this.expression.indexOf('='));
						this.varValue = this.expression.substr(this.expression.indexOf('=')+1);
//						if(this.varName == 'exec') alert(this.varValue);
						eval("this."+this.varName+" = "+this.varValue);
					}
				}
				eval(this.id +" = this.createWindow();"); 
				eval(executeAfterOpen);
			}
		}
		this.createWindow = function() {
			if(d.getElementById('border_'+this.id)) {
				windowObject = d.getElementById('border_'+id);
				bring2front(windowObject);
				return windowObject.firstChild;
			}
			var dBody = document.getElementsByTagName('body').item(0);
			this.title = (typeof this.title != 'undefined') ? (this.title) :  ("SAGE Computing");
			this.height = (typeof this.height != 'undefined') ? (this.height) :  (300);
			this.width = (typeof this.width != 'undefined') ? (this.width) :  (400);
			this.bodyPadding = (typeof this.bodyPadding != 'undefined') ? (this.bodyPadding) :  (15);
			this.xPos = (typeof this.top != 'undefined') ? (this.left) :  ("");
			this.yPos = (typeof this.left != 'undefined') ? (this.top) :  ("");
			this.border = (typeof this.border != 'undefined') ? (this.border) :  (2);
			this.oParent = (typeof this.oParent != 'undefined') ? (typeof this.oParent == 'string') ? document.getElementById(this.oParent) : this.oParent :  (dBody);
			this.byId = (typeof this.byId != 'undefined') ? (this.byId) :  (false);
			this.closable = (typeof this.closable != 'undefined') ? (this.closable) :  (true);
			this.minimizable = (typeof this.minimizable != 'undefined') ? (this.minimizable) :  (false);
			this.statusBar = (typeof this.statusBar != 'undefined') ? (this.statusBar) :  (false);
			this.draggable = (typeof this.draggable != 'undefined') ? (this.draggable) :  (true);
			this.centerWindow = (typeof this.centerWindow != 'undefined') ? (this.centerWindow) :  (false);
			this.greyBox = (typeof this.greyBox != 'undefined') ? (this.greyBox) :  (false);
			this.cssFile = (typeof this.cssFile != 'undefined') ? (this.cssFile) :  (false);
			this.jsFile = (typeof this.jsFile != 'undefined') ? (this.jsFile) :  (false);
			this.jsFileExec = (typeof this.jsFileExec != 'undefined') ? (this.jsFileExec) :  (false);
			this.exec = (typeof this.exec != 'undefined') ? (this.exec) :  (false);
			this.closeOnEsc = (typeof this.closeOnEsc != 'undefined') ? (this.closeOnEsc) : (true);
			//create clone node
			this.protoType = d.getElementById('border_protoType');
			this.outsideContainer = this.protoType.cloneNode(true);
			this.clone = this.outsideContainer.firstChild;
			
			//store properties for recall
			this.clone.contentURL = this.contentURL;
			this.clone.windowHeight = parseInt(this.height,0);
			this.clone.windowWidth = parseInt(this.width,0);
			this.clone.windowBorder = parseInt(this.border,0);
			this.clone.displayStatus = 'visible';
			if (window.ActiveXObject)   {this.wHeight = document.body.offsetHeight; this.wWidth = document.body.offsetWidth; }
			else if (!window.ActiveXObject)    {this.wHeight = window.innerHeight; this.wWidth = window.innerWidth; }
			scrollOffsets = getScrollXY();
			if(this.xPos === '' || this.centerWindow) {
				this.xPos = (this.wWidth/2)-(parseInt(this.width,0)/2)+scrollOffsets[0];
				if(this.xPos < 50) {this.xPos = 50;}
				this.xPos = this.xPos;
			}
			if(this.yPos === '' || this.centerWindow) {
				this.yPos = (this.wHeight/2)-(parseInt(this.height,0)/2)+scrollOffsets[1];
				if(this.yPos < 100) {this.yPos = 100;}
				this.yPos = this.yPos;
			}
		
			//set border
			this.clone.style.top = this.border+"px";
			this.cloneTop = parseInt(this.border,0)+'px';
			this.cloneLeft =  parseInt(this.border,0)+'px';
			this.borderMod = parseInt(this.border,0)*2;
			this.borderHeight = parseInt(this.height,0) + parseInt(this.borderMod,0);
			this.borderHeight = this.borderHeight;
			this.borderWidth = parseInt(this.width,0) + parseInt(this.borderMod,0);
			this.borderWidth = this.borderWidth;
			this.outsideContainer.style.height = this.borderHeight+"px";
			this.outsideContainer.style.width = this.borderWidth+"px";
			this.outsideContainer.style.visibility = 'visible'
			this.outsideContainer.displayStatus = 'visible'
		
			//add '.px' to size definitions if don't exist
			//add this code later, not mandatory with proper use
		
			//set vars to each node
			this.clone.titleBar = this.clone.childNodes[0];
			this.clone.closeBox = this.clone.titleBar.childNodes[0];
			this.clone.minimizeBox = this.clone.titleBar.childNodes[1];
			this.clone.body = this.clone.childNodes[1];
			this.clone.body.content = this.clone.body.firstChild;
			this.clone.statusBar = this.clone.childNodes[2];
			this.clone.container = this.outsideContainer;
		
			//set Id vars
			this.clone.id = 'outerDiv_'+this.id;
			this.clone.titleBar.id = 'titleBar_'+this.id;
			this.clone.closeBox.id = 'closeBox_'+this.id;
			this.clone.minimizeBox.id = 'minimizeBox_'+this.id;
			this.clone.body.id = 'body_'+this.id;
			this.clone.body.content.id = 'bodyContent_'+this.id
			this.clone.statusBar.id = 'statusBar_'+this.id;
			this.clone.container.id = 'border_' + this.id;
		
			//Size based math
			//body height
			this.titleBarHeight = parseInt(this.clone.titleBar.style.height,0)+1;
			if(this.statusBar != 'false' && this.statusBar != '0'){
				this.statusBarHeight = 24;
			} else {
				this.statusBarHeight = 0;
			}
			this.bodyHeight = parseInt(this.height,0) - this.titleBarHeight - this.statusBarHeight;
		
			//apply settings to clone
			this.clone.style.height = this.height+"px";
			this.clone.style.width = this.width+"px";
			this.outsideContainer.style.top = this.yPos+"px";
			this.outsideContainer.style.left = this.xPos+"px";
			this.clone.style.margin = this.border+"px";
			this.clone.titleBar.style.overflow = 'hidden';
			this.titleContainer = d.createElement('div');
			this.titleContainer.style.display = 'inline';
			this.titleContainer.innerHTML = this.title;
			this.clone.titleBar.appendChild(this.titleContainer);
			this.clone.body.style.height = this.bodyHeight+"px";
			this.clone.body.content.style.padding = this.bodyPadding+'px';
			this.clone.statusBar.innerHTML = '';
			if(this.statusBar) {this.clone.statusBar.style.visibility = 'visible';}
			if(!this.minimizable || this.minimizable == 'false' || this.minimizable === 0) {this.clone.minimizeBox.style.display = 'none';}
			if(!this.closable || this.closable == 'false' || this.closable === 0) {this.clone.closeBox.style.visibility = 'hidden';}
			
			
			//Use greybox effect if set.
			if(this.greyBox) {
				this.greyBoxDiv = d.createElement('div');
				this.greyBoxDiv.id = 'greyBoxDiv';
				this.clone.greyBox = true;
				//styleText = '';
				//this.greyBoxDiv.setAttribute ('style',styleText)
				//this.greyBoxDiv.style.cssText = styleText;
				this.greyBoxDiv.className = 'greyBoxDiv';
				dBody.appendChild(this.greyBoxDiv);
				dBody.appendChild(this.outsideContainer);
			}
			//attach to parent element (body if not specified) 
			else if(this.oParent) this.oParent.appendChild(this.outsideContainer);
			else dBody.appendChild(this.outsideContainer);
			
			
			//set bring to front, set to visible and init dragging (if true)
			bring2front(this.clone.container);
			this.clone.style.visibility = 'visible';
			if(this.draggable) {
				this.drag = new YAHOO.util.DD(this.outsideContainer.id);
				this.drag.setHandleElId(this.clone.titleBar.id);
			}
			this.clone.onclick = function() { bring2front(this.container); };
			this.clone.body.content.onclick = keepFocus;
			this.clone.body.content.onkeyup = keepFocus;
			this.clone.fillBody = function(enterContent) {
				this.body.content.innerHTML = enterContent;
			};
			this.clone.minimizeBox.hideContainer = function() {
				if(this.parentNode.parentNode.displayStatus == 'visible') {
					this.parentNode.parentNode.displayStatus = 'minimized';
					this.className = 'dynamicWindowRestoreBox';
					this.parentNode.parentNode.style.width = '100px';
					this.parentNode.parentNode.body.style.width = '100px'
					this.parentNode.parentNode.parentNode.style.width = (100+(this.parentNode.parentNode.windowBorder*2)) + 'px';
					this.parentNode.parentNode.style.height = '23px';
					this.parentNode.parentNode.body.style.width = '0px'
					this.parentNode.parentNode.parentNode.style.height = (23+(this.parentNode.parentNode.windowBorder*2)) + 'px';
				} else {
					this.parentNode.parentNode.displayStatus = 'visible';
					this.className = 'dynamicWindowMinimizeBox';
					this.parentNode.parentNode.style.width = this.parentNode.parentNode.windowWidth+'px';
					this.parentNode.parentNode.body.style.width = this.parentNode.parentNode.windowWidth+'px';
					this.parentNode.parentNode.parentNode.style.width = (this.parentNode.parentNode.windowWidth+(this.parentNode.parentNode.windowBorder*2)) + 'px';
					this.parentNode.parentNode.style.height = this.parentNode.parentNode.windowHeight+'px';
					this.parentNode.parentNode.body.style.width = this.parentNode.parentNode.bodyHeight+'px';
					this.parentNode.parentNode.parentNode.style.height = (this.parentNode.parentNode.windowHeight+(this.parentNode.parentNode.windowBorder*2)) + 'px';
				}
			};
			this.clone.minimizeBox.onclick = function() {
				this.hideContainer();
				this.cancelBubble = true;
			};
			this.clone.setMinimizeBoxClick = function(executeFunction) {
				this.minimizeBox.onclick = function() { eval(executeFunction); this.cancelBubble=true;  };
			};
		
			this.clone.closeBox.closeContainer = function() {
				if(this.parentNode.parentNode.greyBox)this.parentNode.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode.parentNode.previousSibling);
				this.parentNode.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode.parentNode);
			};
			this.clone.closeBox.onclick = function() {
				this.click();
			};
			this.clone.closeBox.click = function() {
				this.closeContainer();
				this.cancelBubble=true;
			};
			this.clone.setCloseBoxClick = function(executeFunction) {
				this.closeBox.click = function() { eval(executeFunction); this.cancelBubble=true;  };
			};
			this.clone.statusBarText = function(statusText) {
				this.statusBar.innerHTML = statusText;
			};
			
			this.clone.setTitleBar = function(titleText) {
				this.titleBar.removeChild(this.titleBar.childNodes[2]);
				titleText = d.createTextNode(titleText);
				this.titleBar.appendChild(titleText);
			};
			
			this.clone.grabContents = function(contentsPage,showLoading) {
				targetWindow = this;
				this.contentURL = contentsPage;
				if(showLoading===undefined || showLoading === '') {showLoading = true;}
				if (window.XMLHttpRequest) { // branch for native XMLHttpRequest object
					this.req = new XMLHttpRequest();
					this.req.onreadystatechange = function() {targetWindow.loadContents(showLoading);};
					this.req.open("GET", contentsPage, true);
					this.req.send(null);
				} else if (window.ActiveXObject) { // branch for IE/Windows ActiveX version
					req = new ActiveXObject("Microsoft.XMLHTTP");
					if (req) {
						this.req.onreadystatechange = function() { targetWindow.loadContents(showLoading);};
						this.req.open("GET", contentsPage, true);
						this.req.send();
					}
				}
			};
			
			this.clone.loadContents = function(showLoading) {
				// only if req shows "complete"
				if(showLoading){
					if(this.req.readyState === 0){ this.statusBarText('Loading');}
					if(this.req.readyState == 1){ this.statusBarText('Loading.');}
					if(this.req.readyState == 2){ this.statusBarText('Loading..');}
					if(this.req.readyState == 3){ this.statusBarText('Loading...');}
					if(this.req.readyState == 4){ this.statusBarText('Done');}
				}
				if (this.req.readyState == 4) {
					// only if "OK"
					if (this.req.status == 200) {
						this.fillBody(this.req.responseText);
					}
				}
			};
			
			this.clone.refresh = function() {
				if(this.contentURL) this.grabContents(this.contentURL);
				else sageAlert ('Module not supplied URL to refresh');
			}
			
			this.clone.resize = function(height,width) {
				intHeight = parseInt(height,0);
				intWidth = parseInt(width,0);
				this.container.style.height = (intHeight + (this.windowBorder*2)) + 'px';
				this.container.style.width = (intWidth + (this.windowBorder*2)) + 'px';
				this.style.height = height;
				this.style.width = width;
				this.style.top = this.windowBorder+'px';
				this.style.left = this.windowBorder+'px';
			};
		
			this.clone.focus();
			this.clone.reposition = function(yPos,xPos) {
				this.container.style.top = yPos;
				this.container.style.left = xPos;
			};
			this.clone.fillBody(this.contentBody);
			if(this.cssFile) addStyleToDOM(this.cssFile);
			if(this.jsFile) addScriptToDOM(this.jsFile);
			if (this.jsFileExec) runScriptOnce(this.jsFileExec);
			if(this.exec) setTimeout(this.exec,500);
			this.clone.closeOnEsc = this.closeOnEsc;
			return this.clone;	
		}
	}
	
	if (window.ActiveXObject) { // branch for IE/Windows ActiveX version
		this.req = new ActiveXObject("Microsoft.XMLHTTP");
		if (this.req) {
			this.req.onreadystatechange = function() {target.processWindowCreator(target);};
			this.req.open("GET", contentURL, true);
			this.req.send();
		}
	}else if (window.XMLHttpRequest) { // branch for native XMLHttpRequest object
		this.req = new XMLHttpRequest();
		this.req.onreadystatechange = function() {target.processWindowCreator(target);};
		this.req.open("GET", contentURL, true);
		this.req.send(null);  
	}
}

function sageAlert(message,title,height,width) {
	getString = "?message="+message;
	if(title) getString += "&title="+title;
	if(height) getString += "&height="+height;
	if(width) getString += "&width="+width;
	return new windowCreator("alertWindow","/modules/alert.html"+getString)
}

function sageConfirm(execute,message,title,height,width) {
	getString = '?execute='+execute;
	if(message) getString += "&message="+message;
	if(title) getString += "&title="+title;
	if(height) getString += "&height="+height;
	if(width) getString += "&width="+width;
	return new windowCreator("confirmWindow","/modules/confirm.html"+getString)
}

function customConfirm (buttons,message,title,height,width) {
	getString = '?buttons='+buttons;
	if(message) getString += "&message="+message;
	if(title) getString += "&title="+title;
	if(height) getString += "&height="+height;
	if(width) getString += "&width="+width;
	return new windowCreator("confirmWindow","/modules/customconfirm.html"+getString)
}

function setCloseConfirm(e) {
	var targ;
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;
}
function keepFocus(e) {
	//alert('keepFocus');
	var targ;
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;
	winBody = locateWindowBody(targ);
	//alert(winBody.id);
	if (targ) {
		previousTarg = winBody.focusObject
		winBody.focusObject = targ;
		try {targ.focus()}
		catch(err){winBody.focusObject = null}
	}
	else 
		winBody.focusObject = null;
}

function setWindowScroll(that) {
}

function fillBody(oBody,target,byId) {
	if(byId) {oBody = d.getElementById(oBody);}
	oBody.innerHTML = target;
}

function changeWindowStatusText(targ,txt) {
	statusWindow = locateWindowStatusBar(targ);
	statusWindow.innerHTML = txt
}

function changeWindowTitleBarText(targ,txt) {
	titleBar = locateWindowTitleBar(targ)
	titleBar.removeChild(titleBar.childNodes[2]);
	titleText = document.createTextNode(txt);
	titleBar.appendChild(titleText);
}

function locateWindowBody(start) {
	do {
		borderWindow = false;
		if (start.id) {
			if (start.id.substring(0,7) == 'border_') 
				borderWindow = start;
			else 
				start = start.parentNode;
		}
		else 
			start = start.parentNode;
	} while (borderWindow == false)
	bodyWindow = borderWindow.firstChild.childNodes[1]
	return bodyWindow;
}
function locateWindowObject(start) {
	winBody = locateWindowBody(start);
	winObj = winBody.parentNode;
	return winObj;
}
function locateWindowStatusBar(targ) {
	targ = locateWindowBody(targ);
	do {
		statusWindow = false;
		if (targ.id) {
			if (targ.id.substring(0,10) == 'statusBar_') 
				statusWindow = targ;
			else 
				targ = targ.nextSibling;
		}
		else 
			targ = targ.nextSibling;
	} while (statusWindow == false)
	return statusWindow;
}
function locateWindowTitleBar(targ) {
	targ = locateWindowBody(targ);
	do {
		titleBarWindow = false;
		if (targ.id) {
			if (targ.id.substring(0,9) == 'titleBar_') 
				titleBarWindow = targ;
			else 
				targ = targ.previousSibling;
		}
		else 
			targ = targ.previousSibling;
	} while (titleBarWindow == false)
	return titleBarWindow;
}

function closeParentWindow(that) {
	objTitleBar = locateWindowTitleBar(that);
	objTitleBar.firstChild.click();
}

function forceCloseParentWindow(that) {
	objTitleBar = locateWindowTitleBar(that);
	objTitleBar.firstChild.closeContainer();
}

document.onkeyup = function(ev) {
	var jsEvent = (window.event) ? window.event : ev;
	var key = jsEvent.keyCode;
	var src = jsEvent.target;
	var ESC = 27;
	trgtWin = this.lastChild.lastChild.lastChild.lastChild
	switch (key){
				case ESC:
					if(trgtWin.closeOnEsc === true) trgtWin.closeBox.click();
					break;
				default:
					break;
			}
}