/*
	Copyright 2006-2007 Zygo Consulting Limited. All rights reserved.
*/

/*
	Tooltip/citataion boxes

	Use:
		Declare each cite with code similar to:
		<a href="#xxx" onmouseover="citePrep(this);" onmouseout="citeRemove(this);">xxx</a>
		The content for the cite box will be the innerHTML of whatever element has an id matching the href
		e.g. <div id="xxx">This is the cite text</div>

	You can override default config values by calling:
		citeConfig(width, style, cssclass);
		width    - is the desired width of cite boxes in pixels (default 400)
		style    - if defined the cite div will be given a style attribute containing the passed string
		cssclass - if defined the cite div will be given a class attribute containing the passed string
*/

/*
	WYSIWYG Textareas

	Use:
		Call wysConvertTextarea(name)
		This will convert the textarea with id 'name' into a WYSIWYG control if the browser supports it

	You can set content to be inserted in the <HEAD> of the control (e.g. stylesheet links)
		wysSetHeaderContent(str);
		str  - string to be included in the head section

	You can add to the default links collection with:
		wysAddLink(title, url);
		title - title of link
		url   - url of link
		links are appended to the list, call as many times as neccessary to add all links

	You can add to the images collection with:
		wysAddImage(title, url, preview);
		title   - image title to display in list
		url     - url of image
		preview - (optional) lower resolution image to show on the selection menu
		images are appended to the list, call as many times as necessary to add all images
	
	You can add custom styles with:
		wysAddStyle(title, html);
		title 	- name of the style
		html	- span tag to insert (e.g. '<span class="test">') an </span> will be automatically added

	You can add custom HTML blocks with:
		wysAddHTMLBlock(title, starthtml, endhtml);
		title		- name of the style
		starthtml	- start html tag
		endhtml		- end html tage
*/

/*
	Colour selection

	Use:
		Call colConvertInput(name)
		This will convert an input with id 'name' into a colour selection box 
	or call manually as
		onclick="colShowSelector('colsel', 'colprev', callback)
		colsel  - is the id of the input to receive the colour
		colprev - is the id of the colour preview element, this element is used to position the colour 
			selector and will also have its background colour set to the selected colour
		callback - JavaScript function reference, to be called upon colour selection. The callback
			will be called with 3 arguments (col, colsel, colprev) - col is the selected colour (string) and 
			colsel and colprev are repeated from the initial call

	You can override default configuration values by calling:
		colConfig(cols, swidth, cwidth, cheight);
		cols	- is an Array object containing a list of colours to use in the swatch
		swidth	- is the width of the swatch in pixels
		cwidth	- is the width of an individual swatch cell in pixels
		cheight	- is the height of an individual swatch cell in pixels
*/

/*
	Popup 'windows' - display a chunk of HTML in a transient div - will disappear if user clicks outside of 'window'

	Use:
		Call popShowWindow(parentid, pos, html, width, height)
		parentid - element on page to position relative to
		pos      - string indicating how to position:
			'right'  - popup will be positioned to the right of parent id
			'bottom' - popup will be positioned underneath parent id
			'over'   - popup will be positioned over parent id
		html     - HTML string to be displayed in the popup
		width    - (optional) specify width of popup in pixels
		height   - (optional) specify height of popup in pixels

	You can override the default styles used with:
		popConfig(bstyle, bgcol, cssclass);
		bstyle   - is the border style
		bgcol    - is the background colour of the window
		cssclass - is the class for the window's div
*/


// Try to work out our path
var g_zygoDefaultPath = "";
var zygoScripts = document.getElementsByTagName("script");
for (var i = 0; i < zygoScripts.length; i++) {
	if (zygoScripts[i].src.match(/zygolib\.js$/)) {
		g_zygoDefaultPath = zygoScripts[i].src.replace(/zygolib\.js$/, "");
	}
}
var g_zygoResourcePath = g_zygoDefaultPath;

/*
	Popup code...
*/

// Config
var c_popBorderStyle = "1px solid black";
var c_popBackgroundColour = "white";
var c_popCssClass = null;

// Globals
var g_popCurrentWindow = null;
var g_popNamedBlock = null;
var g_popOldBodyClick = null;

function popConfig(bstyle, bgcol, cssclass) {
	c_popBorderStyle = bstyle;
	c_popBackgroundColour = bgcol;
	c_popCssClass = cssclass;
}

function popShowWindow(parentid, pos, html, width, height) {
	popCloseWindow();

	var pelem = document.getElementById(parentid);
	if (!pelem) {
		utilRaiseError("Attempt to position popup near non-existent element '" + parentid + "'");
		return;
	}

	var ppos = utilGetElementPosition(pelem);
	var x = 0;
	var y = 0;
	switch (pos) {
		case 'right':
			x = ppos.left + ppos.width;
			y = ppos.top;
			break;

		case 'bottom':
			x = ppos.left;
			y = ppos.top + ppos.height;
			break;

		case 'over':
			x = ppos.left;
			y = ppos.top;
			break;

		default:
			utilRaiseError("Attempt to position popup with unsupported position '" + pos + "'");
			return;
	}

	var div = document.createElement("div");
	div.style.position = "absolute";
	div.style.left = x + "px";
	div.style.top = y + "px";
	if (width) {
		div.style.width = width + "px";
	}
	if (height) {
		div.style.height = height + "px";
	}
	if (c_popBackgroundColour) {
		div.style.backgroundColor = c_popBackgroundColour;
	}
	if (c_popBorderStyle) {
		div.style.border = c_popBorderStyle;
	}
	if (c_popCssClass) {
		div.className = c_popCssClass;
	}
	div.onclick = function (e) {
		e = e || event;
		e.cancelBubble = true;
	};

	div.innerHTML = html;
	document.body.appendChild(div);

	pos = utilGetElementPosition(div);
	var ww = window.innerWidth || document.body.clientWidth;
	if (pos.left + pos.width > ww) {
		div.style.left = (ww - pos.width) + "px";
	}

	g_popCurrentWindow = div;
	g_popOldBodyClick = document.body.onclick;
	document.body.onclick = popCloseWindow;
}

function popShowElement(parentid, pos, name, width, height) {
	popCloseWindow();

	var pelem = document.getElementById(parentid);
	if (!pelem) {
		utilRaiseError("Attempt to position popup near non-existant element '" + parentid + "'");
		return;
	}

	var ppos = utilGetElementPosition(pelem);
	var x = 0;
	var y = 0;
	switch (pos) {
		case 'right':
			x = ppos.left + ppos.width;
			y = ppos.top;
			break;

		case 'bottom':
			x = ppos.left;
			y = ppos.top + ppos.height;
			break;

		case 'over':
			x = ppos.left;
			y = ppos.top;
			break;

		default:
			utilRaiseError("Attempt to position popup with unsupported position '" + pos + "'");
			return;
	}

	var div = document.getElementById(name);
	div.style.display = "block";
	div.style.position = "absolute";
	div.style.left = x + "px";
	div.style.top = y + "px";
	if (width) {
		div.style.width = width + "px";
	}
	if (height) {
		div.style.height = height + "px";
	}
	if (c_popBackgroundColour) {
		div.style.backgroundColor = c_popBackgroundColour;
	}
	if (c_popBorderStyle) {
		div.style.border = c_popBorderStyle;
	}
	if (c_popCssClass) {
		div.className = c_popCssClass;
	}
	div.onclick = function (e) {
		e = e || event;
		e.cancelBubble = true;
	};

	pos = utilGetElementPosition(div);
	var ww = window.innerWidth || document.body.clientWidth;
	if (pos.left + pos.width > ww) {
		div.style.left = (ww - pos.width) + "px";
	}

	g_popNamedBlock = name;
	g_popOldBodyClick = document.body.onclick;
	document.body.onclick = popCloseWindow;
}

function popCloseWindow() {
	if (g_popCurrentWindow) {
		document.body.removeChild(g_popCurrentWindow);
		g_popCurrentWindow = null;
	} else if (g_popNamedBlock) {
		document.getElementById(g_popNamedBlock).style.display = "none";
		g_popNamedBlock = null;
	}
	if (document.body.onclick == popCloseWindow) {
		document.body.onclick = g_popOldBodyClick;
	}
}

/*
	Colour selector code...
*/

// Install onload handler
if (typeof(g_ZygoLibLoaded) == 'undefined') {
	var _oldLoader = window.onload;
	window.onload = function () { colReplaceControls(); if (_oldLoader) { _oldLoader(); } };
}

// Config
var c_colColourList = [
'#ffff00',
'#00ff00', 
'#00ffff', 
'#ff00ff', 
'#0000ff', 
'#ff0000', 
'#000080', 
'#008080', 
'#008000', 
'#800080', 
'#800000', 
'#808000', 
'#000000', 
'#808080', 
'#c0c0c0', 
'#ffffff'
];
var c_colSwatchCellWidth = 10;
var c_colSwatchCellHeight = 10;
var c_colSwatchWidth = 94;

// Globals
var g_colControls = new Array();
var g_colSelector = null;
var g_colCurrentId;
var g_colOldBodyClick = null;

function colConfig(cols, swidth, cwidth, cheight) {
	c_colColourList = cols;
	c_colSwatchWidth = swidth;
	c_colSwatchCellWidth = cwidth;
	c_colSwatchCellHeight = cheight;
}

function colReplaceControl(colid) {
	var obj = new Object();
	obj.name = colid;
	g_colControls.push(obj);
}

function colReplaceControls() {
	for (var i = 0; i < g_colControls.length; i++) {
		var ct = document.getElementById(g_colControls[i].name);
		if (ct) {
			g_colControls[i].input = ct;
			ct.style.display = "none";
			var sp = document.createElement("img");
			colMakeSelector(sp, ct.value, ct.id);
			var pid = "COL_" + ct.id + "_preview";
			g_colControls[i].previd = pid;
			sp.id = pid;
			ct.parentNode.insertBefore(sp, ct);
		} else {
			utilRaiseError("Attempt to convert non-existent control '" + g_colControls[i].name + "'");
			g_colControls.splice(i, 1);
			i--;
		}
	}
}

function colMakeSelector(elem, currcol, colid) {
	elem.style.border = "1px solid black";
	elem.style.width = "32px";
	elem.style.backgroundColor = "#" + currcol;
	elem.style.verticalAlign = 'middle';
	elem.src = g_zygoResourcePath + 'images/cselector.png';
	elem.onclick = function (e) { e = e || event; e.cancelBubble = true; colShowSelector(colid); };
}

function colFindControl(colid) {
	for (var i = 0; i < g_colControls.length; i++) {
		if (g_colControls[i].name == colid) {
			return g_colControls[i];
		}
	}
	return null;
}

function colShowSelector(colid, previd, callback) {
	if (arguments.length > 1) {
		// Auto add control for manual system
		var obj = new Object();
		obj.name = colid;
		var ct = document.getElementById(colid);
		obj.input = ct;
		obj.previd = previd;
		obj.callback = callback;
		g_colControls.push(obj);
	}
	var obj = colFindControl(colid);
	previd = obj.previd;
	var pv = document.getElementById(previd);
	var pos = utilGetElementPosition(pv);
	var div = document.createElement("div");
	div.innerHTML = colSelectorHTML();
	div.style.backgroundColor = "#ffffff";
	div.style.border = "1px solid black";
	div.style.position = "absolute";
	div.style.left = (pos.left + pos.width) + "px";
	div.style.top = pos.top + "px";
	document.body.appendChild(div);
	g_colSelector = div;
	g_colCurrentId = colid;

	g_colOldBodyClick = document.body.onclick;
	document.body.onclick = colHideSelector;
}

function colHideSelector() {
	if (g_colSelector) {
		document.body.removeChild(g_colSelector);
		g_colSelector = null;
	}
	if (document.body.onclick == colHideSelector) {
		document.body.onclick = g_colOldBodyClick;
	}
}

function colSelectorHTML() {
	var html = "<div style='width: " + c_colSwatchWidth + "px;'>";
	for (var i = 0; i < c_colColourList.length; i++) {
		html+= "<div style='width: " + c_colSwatchCellWidth + "px; height: " + c_colSwatchCellHeight + "px; float: left; border: 1px solid black; background-color: " + c_colColourList[i] + ";margin: 5px;' onmouseover='this.style.border=\"1px solid white\";' onmouseout='this.style.border=\"1px solid black\";' onclick='colChooseColour(\"" + c_colColourList[i] + "\");'></div>";
	}
	html+= "</div>";

	return html;
}

function colChooseColour(col) {
	var obj = colFindControl(g_colCurrentId);
	var colour =  col.replace(/^#/, '');
	if (obj.input) {
		obj.input.value = colour;
	}
	var pc = document.getElementById(obj.previd);
	pc.style.backgroundColor = col;
	document.body.removeChild(g_colSelector);
	g_colSelector = null;
	if (obj.callback) {
		obj.callback(colour, obj.name, obj.previd);
	}
}

/*
	WYSIWYG control code....
*/

// Install onload handler
if (typeof(g_ZygoLibLoaded) == 'undefined') {
	var _oldHandler = window.onload;
	window.onload = function () { wysInstallControls(); if (_oldHandler) { _oldHandler(); } };
}

// Config
var c_wysBlockStyles = [
	["<h1>", "Heading 1"],
	["<h2>", "Heading 2"],
	["<h3>", "Heading 3"],
	["<h4>", "Heading 4"],
	["<p>",  "Normal"]
	];
var c_wysLinks = new Array();
var c_wysImages = new Array();
var c_wysCustomImageSelector = null;
var c_wysStyles = new Array();
var c_wysHTMLBlocks = new Array();
var c_wysHeadContent = null;

// Globals
var g_wysObjects = new Array();
var g_wysColourObject = null;
var g_wysCurrentForeColour = '#ff0000';
var g_wysCurrentBackColour = '#ffff00';
var g_wysMinControlWidth = 200;
var g_wysMaxControlWidth = 2000;
var g_wysMinControlHeight = 250;
var g_wysMaxControlHeight = 1000;
var g_wysSaveCursor;

function wysConvertTextarea(name, tblevel) {
//	var elem = document.getElementById(name);
//	if (elem) {
//		if (elem.nodeName == "TEXTAREA") {
			var control = new wysControl(name);
			control.tblevel = tblevel;
			control.type = "textarea";
			g_wysObjects.push(control);
//		} else {
//			utilRaiseError("wysConvertTextarea called for an element that is not a textarea");
//		}
//	} else {
//		utilRaiseError("wysConvertTextarea called for non-existent element");
//	}
}

function wysConvertDiv(name, tblevel) {
	var elem = document.getElementById(name);
	if (elem) {
		if (elem.nodeName == "DIV") {
			var control = new wysControl(name);
			control.tblevel = tblevel;
			control.type = "div";
			g_wysObjects.push(control);
			wysInstallControl(control);

			return control;
		} else {
			utilRaiseError("wysConvertDiv called for an element that is not a div");
		}
	} else {
		utilRaiseError("wysConvertDiv called for non-existent element");
	}
}

function wysGetControl(name) {
	return wysFindControl(name);
}

function wysSetMinMaxSizes(minw, maxw, minh, maxh) {
	g_wysMinControlWidth = minw;
	g_wysMaxControlWidth = maxw;
	g_wysMinControlHeight = minh;
	g_wysMaxControlHeight = maxh;
}

function wysSetHeaderContent(str) {
	if (c_wysHeadContent) {
		c_wysHeadContent += str;
	} else {
		c_wysHeadContent = str;
	}
}

function wysInstallControls() {
	if (!wysCompat()) {
		return;
	}
	for (var i = 0; i < g_wysObjects.length; i++) {
		if (g_wysObjects[i].type == "textarea") {
			wysInstallControl(g_wysObjects[i]);
		}
	}
}

function wysAddLink(title, url) {
	c_wysLinks.push( {title: title, url: url} );
}

function wysAddImage(title, url, preview, folder) {
	if (folder == null) {
		c_wysImages.push( {title: title, url: url, preview: preview, type: 'img'} );
	} else {
		for (var i = 0; i < c_wysImages.length; i++) {
			if (c_wysImages[i].type == 'folder' && c_wysImages[i].title == folder) {
				c_wysImages[i].content.push( {title: title, url: url, preview: preview, type: 'img'} );
				break;
			}
		}
	}
}

function wysAddImageFolder(title) {
	c_wysImages.push( {title: title, type: 'folder', content: new Array()} );
}

function wysUseCustomImageSelector(html) {
	c_wysCustomImageSelector = html;
}

function wysAddStyle(title, html) {
	c_wysStyles.push( {title: title, html: html} );
}

function wysAddHTMLBlock(title, starthtml, endhtml) {
	c_wysHTMLBlocks.push( {title: title, start: starthtml, end: endhtml} );
}

function wysControl(name) {
	this.name = name;
	this.destroy = function () { wysDestroyControl(this); };
	this.getContent = function () { return wysGetContent(this); };
	this.setContent = function (content) { wysSetContent(this, content); }; 
	this.resize = function () { wysResizeFrame(this); };
	this.designMode = function (on) { wysDesignMode(this.name, on); };
}

function wysGetContent(obj) {
	if (!obj.designMode) {
		document.getElementById(obj.iframeid).contentWindow.document.body.innerHTML = document.getElementById(obj.itextid).value;
	}
	obj.content = wysGetHTMLSource(document.getElementById(obj.iframeid).contentWindow.document.body);

	return obj.content;
}

function wysSetContent(obj, str) {
 if (!obj.itextid || !obj.iframeid)
   return;

 if (!obj.designMode) {
   document.getElementById(obj.itextid).value = str;
 } else {
   document.getElementById(obj.iframeid).contentWindow.document.body.innerHTML = str;
 }
} 

function wysDestroyControl(obj) {
	if (obj.type == "textarea") {
		obj.div.parentNode.removeChild(obj.div);
		obj.textarea.style.display = "";
	} else {
		obj.textarea.innerHTML = obj.getContent();
	}

	var newList = new Array();
	for (var i = 0; i < g_wysObjects.length; i++) {
		if (g_wysObjects[i].name != obj.name)
			newList.push(g_wysObjects[i]);
	}
	g_wysObjects = newList;
}

function wysInstallControl(obj) {
	var textarea = document.getElementById(obj.name);
	if (!textarea) {
		return;
	}

	obj.textarea = textarea;
	var pos = utilGetElementPosition(textarea);
	obj.width = pos.width > g_wysMaxControlWidth ? g_wysMaxControlWidth : pos.width < g_wysMinControlWidth ? g_wysMinControlWidth : pos.width;
	obj.height = pos.height > g_wysMaxControlHeight ? g_wysMaxControlHeight : pos.height < g_wysMinControlHeight ? g_wysMinControlHeight : pos.height;

  wysCreateFrame(obj);

	if (obj.type == "textarea") {
		var oldOnSubmit = obj.textarea.form.onsubmit;
		obj.textarea.form.onsubmit = function () {
			obj.textarea.value = wysGetContent(obj);
			if (oldOnSubmit) { oldOnSubmit() }
		};
	}

	obj.designMode = false;

	// Delay for FF caching issue with stylesheet
	window.setTimeout("wysDesignMode('" + obj.name + "', true);", 50);
}

function wysCreateFrame(obj) {
	var div = document.createElement("div");
  obj.div = div;
	div.style.border = "1px solid black";
	div.style.width  = obj.width + "px";
	div.style.height = obj.height + "px";
	div.style.position = "relative";
	div.style.overflow = "hidden";
	div.onclick = function (e) { var evt = e ? e : event; evt.cancelBubble = true; };
	
	obj.toolbarid = "WYS_" + obj.name + "_toolbar";
	var content = "<div style='margin: 1px; position: absolute; top: 0px; left: 0px; width: " + (obj.width) + "px;' id='" + obj.toolbarid + "'>" + wysToolbarHTML(obj.name, false) + "</div>";
	obj.iframeid = "WYS_" + obj.name + "_iframe";
	content+= "<iframe frameborder='0' id='" + obj.iframeid + "'></iframe>";
	obj.itextid = "WYS_" + obj.name + "_source";
	content+= "<textarea id='" + obj.itextid + "' style='display: none;'></textarea>";
	obj.footbarid = "WYS_" + obj.name + "_footbar";
  if (obj.tblevel != 0) {
	  content+= "<div style='margin: 1px; position: absolute; bottom: 0px; left: 0px;' id='" + obj.footbarid + "'>" + wysFootbarHTML(obj.name) + "</div>";
  }
	div.innerHTML = content;

	// Fill with content
	if (obj.type == "textarea") {
		obj.content = obj.textarea.value;
		obj.textarea.parentNode.insertBefore(div, obj.textarea);
		obj.textarea.style.display = "none";
	} else {
		obj.content = obj.textarea.innerHTML;
		obj.textarea.innerHTML = "";
		obj.textarea.appendChild(div);
	}

	wysResizeFrame(obj);

	document.getElementById(obj.itextid).value = obj.content;
	var doc = document.getElementById(obj.iframeid).contentWindow.document;
	doc.designMode = 'On';
	// Keep IE happy
	var iframe = document.getElementById(obj.iframeid);
	doc = iframe.contentWindow.document;
	doc.open();
	doc.write("<html><head>");
	doc.write("<style>\ntable, td { border: 1px solid #ccc; }\n</style>");
	if (c_wysHeadContent) {
		doc.write("\n" + c_wysHeadContent + "\n");
	}
	doc.write("</head><body>");
	doc.write(obj.content);
	doc.write("</body></html>");
	doc.close();

	obj.designMode = false;
}

function wysRecreateControl(id) {
  var obj = wysFindControl(id);
  obj.div.parentNode.removeChild(obj.div);
  wysCreateFrame(obj);

}

function wysEnableDesignMode(id) {
  var obj = wysFindControl(id);
	var doc = document.getElementById(obj.iframeid).contentWindow.document;
	doc.designMode = 'On';
}


function wysShowToolbar(frameid) {
	for (var i = 0; i < g_wysObjects.length; i++) {
		if (frameid == g_wysObjects[i].iframeid) {
			var tb = document.getElementById(g_wysObjects[i].toolbarid);
			tb.style.display = "block";
			wysResizeFrame(g_wysObjects[i]);
			return;
		}
	}
}

function wysHideToolbar(frameid) {
	for (var i = 0; i < g_wysObjects.length; i++) {
		if (frameid == g_wysObjects[i].iframeid) {
			var tb = document.getElementById(g_wysObjects[i].toolbarid);
			tb.style.display = "none";
			wysResizeFrame(g_wysObjects[i]);
			return;
		}
	}
}

function wysFindControl(name) {
	for (var i = 0; i < g_wysObjects.length; i++) {
		if (g_wysObjects[i].name == name) {
			return g_wysObjects[i];
		}
	}

	return null;
}

function wysDesignMode(name, on) {
	var obj = wysFindControl(name);
	if (obj.designMode == on) {
		return;
	}

	var iframe = document.getElementById(obj.iframeid);
	var itext = document.getElementById(obj.itextid);
	var tbar = document.getElementById(obj.toolbarid);
  if (obj.tblevel != 0) {
		var deslink = document.getElementById("WYS_" + name + "_deslink");
		var htmllink = document.getElementById("WYS_" + name + "_htmllink");
  }
	if (!on) {
		itext.value = wysGetHTMLSource(iframe.contentWindow.document.body);
		itext.style.display = "block";
		iframe.style.display = "none";

		// Update toolbar HTML - IE7 croaks sometimes if you try to set with innerHTMl!?
		var tbhtml = wysToolbarHTML(name, true);
		var kid = tbar.firstChild;
		while (kid) {
			kid.parentNode.removeChild(kid);
			kid = tbar.firstChild;
		}
		var nb = document.createElement("div");
		nb.innerHTML = tbhtml;
		tbar.appendChild(nb);

    if (obj.tblevel != 0) {
  	  deslink.style.border = "1px solid #fff";
  		htmllink.style.border = "1px solid #008";
    }
	} else {
    if (!iframe.contentWindow.document.body) {
      window.setTimeout("wysDesignMode('" + name + "',true)", 500);
      return;
    }
		iframe.contentWindow.document.body.innerHTML = itext.value;
		itext.style.display = "none";
		iframe.style.display = "block";

		// Update toolbar HTML - IE7 croaks sometimes if you try to set with innerHTMl!?
		var tbhtml = wysToolbarHTML(name, false);
		var kid = tbar.firstChild;
		while (kid) {
			kid.parentNode.removeChild(kid);
			kid = tbar.firstChild;
		}
		var nb = document.createElement("div");
		nb.innerHTML = tbhtml;
		tbar.appendChild(nb);

    if (obj.tblevel != 0) {
			deslink.style.border = "1px solid #008";
			htmllink.style.border = "1px solid #fff";
		}
  }
	obj.designMode = on;
}

function wysGetHTMLSource(parentElem) {
	if (document.all) {
		// IE - let's clean up that bad HTML...
		for (var i = 0; i < parentElem.all.length; i++) {
			var elem = parentElem.all[i];
			if (elem.nodeType == 1) {
				// Element
				if (elem.nodeName.match(/^\//)) {
					// Tag name beginning with a / - WTF? yup it's true!
					// Kill it
					elem.parentNode.removeChild(elem);
					i--;
				} else if (elem.nodeName == 'TBODY') {
					// Clean up stray table tags as IE preserves bad HTML in the DOM...
					if (!elem.parentNode || elem.parentNode.nodeName != 'TABLE') {
						elem.parentNode.removeChild(elem);
						// alert("TBODY not in TABLE at position "+i+" "+elem.outerHTML);
					}
				} else if (elem.nodeName == 'TR') {
					if (!elem.parentNode || elem.parentNode.nodeName != 'TBODY') {
						elem.parentNode.removeChild(elem);
						// alert("TR not in TBODY at position "+i+" "+elem.outerHTML);
					}
				} else if (elem.nodeName == 'TD' || elem.nodeName == 'TH') {
					if (!elem.parentNode || elem.parentNode.nodeName != 'TR') {
						elem.parentNode.removeChild(elem);
						// alert("TD not in TR at position "+i+" "+elem.outerHTML);
					}
				}
			}
		}
	}

	return parentElem.innerHTML;
}

function wysResizeFrame(obj) {
	var tbpos = utilGetElementPosition(document.getElementById(obj.toolbarid));
  var fbheight = 0
  if (obj.tblevel != 0) {
  	var fbpos = utilGetElementPosition(document.getElementById(obj.footbarid));
    fbheight = fbpos.height;
  }
	obj.frameWidth = (obj.width - 10);
	obj.frameHeight = (obj.height - tbpos.height - fbheight - 10);

	var iframe = document.getElementById(obj.iframeid);
	iframe.style.position = "absolute";
	iframe.style.left = "3px";
	iframe.style.top = (tbpos.height + 2) + "px";
	iframe.style.border = "1px inset #888";
//	iframe.style.margin = "1px;";
	iframe.style.width = obj.frameWidth + "px";
	iframe.style.height = obj.frameHeight + "px";
	var itext = document.getElementById(obj.itextid);
	itext.style.position = "absolute";
	itext.style.left = "3px";
	itext.style.top = (tbpos.height + 2) + "px";
//	itext.style.margin = "1px;";
	itext.style.border = "1px inset #888";
	itext.style.width = obj.frameWidth + "px";
	itext.style.height = obj.frameHeight + "px";
}

function wysToolbarHTML(name, disabled) {
	var content = "";

	// Styles
//	content+= "<table><tr><td valign='top'>";

  var obj = wysFindControl(name);
  if (obj.tblevel != 0) {
  	content+= "<select style='width: 70px;' onchange='wysApplyCommand(this, \"" + name + "\", \"formatblock\", this.options[this.selectedIndex].value);this.selectedIndex=0;'";
	  if (disabled) {
	  	content+= " disabled='true'";
	  }
	  content+= ">";
	  content+= "<option value=''>Style...</option>";
	  for (var i = 0; i < c_wysBlockStyles.length; i++) {
	  	content+= "<option value='" + c_wysBlockStyles[i][0] + "'>" + c_wysBlockStyles[i][1] + "</option>";
	  }
	  content+= "</select>&nbsp;";
	  content+= "<select style='width: 64px' onchange='wysApplyCommand(this, \"" + name + "\", \"fontsize\", this.options[this.selectedIndex].value);this.selectedIndex=0;'";
	  if (disabled) {
	  	content+= " disabled='true'";
	  }
	  content+= ">";
		content+= "<option value=''>Size...</option>";
		content+= "<option value='1'>1</option>";
		content+= "<option value='2'>2</option>";
		content+= "<option value='3'>3</option>";
		content+= "<option value='4'>4</option>";
		content+= "<option value='5'>5</option>";
		content+= "<option value='6'>6</option>";
		content+= "<option value='7'>7</option>";
		content+= "<option value='8'>8</option>";
		content+= "</select>";

  	if (c_wysStyles.length > 0) {
  		content+= "&nbsp;<select onchange='wysApplyCommand(this, \"" + name + "\", \"style\", this.options[this.selectedIndex].value);this.selectedIndex=0;'";
  		if (disabled) {
  			content+= " disabled='true'";
  		}
  		content+= ">";
  		content+= "<option value=''>CSS...</option>";
  		for (var i = 0; i < c_wysStyles.length; i++) {
  			content+= "<option value='" + i + "'>" + c_wysStyles[i].title + "</option>";
  		}
  		content+= "</select>";
  	}

		if (c_wysHTMLBlocks.length > 0) {
			content+= "&nbsp;<select style='width: 80px' onchange='wysApplyCommand(this, \"" + name + "\", \"custom\", this.options[this.selectedIndex].value);'";
			if (disabled) {
				content+= " disabled='true'";
			}
			content+= ">";
			content+= "<option value=''>Special...</option>";
			for (var i = 0; i < c_wysHTMLBlocks.length; i++) {
				content+= "<option value='" + i + "'>" + c_wysHTMLBlocks[i].title + "</option>";
			}
			content+= "</select>";
		}

//	content+= "</td><td valign='top'>";

  	content+= "|";
  }
	// Buttons
	content+= wysToolbarButton(name, 'Bold', 'images/bold.png', 'bold', '', !disabled);
	content+= wysToolbarButton(name, 'Italic', 'images/italic.png', 'italic', '', !disabled);
	content+= wysToolbarButton(name, 'Underline', 'images/underline.png', 'underline', '', !disabled);
	// content+= wysToolbarButton(name, 'Small', 'images/fontsm.png', 'small', '', !disabled);
	content+= "|";
	content+= wysToolbarButton(name, 'Left', 'images/left.png', 'justifyleft', '', !disabled);
	content+= wysToolbarButton(name, 'Centre', 'images/centre.png', 'justifycenter', '', !disabled);
	content+= wysToolbarButton(name, 'Right', 'images/right.png', 'justifyright', '', !disabled);
	content+= wysToolbarButton(name, 'Full', 'images/full.png', 'justifyfull', '', !disabled);
	content+= "|";
	content+= wysToolbarButton(name, 'Numbered list', 'images/numberedlist.png', 'insertorderedlist', '', !disabled);
	content+= wysToolbarButton(name, 'Bulleted list', 'images/bulletlist.png', 'insertunorderedlist', '', !disabled);
	content+= wysToolbarButton(name, 'Indent', 'images/indent.png', 'indent', '', !disabled);
	content+= wysToolbarButton(name, 'Outdent', 'images/outdent.png', 'outdent', '', !disabled);
	content+= "|";
	content+= wysToolbarButton(name, 'Font colour', 'images/fontcol.png', 'applyforecolour', '', !disabled);
	content+= wysToolbarButton(name, 'Choose font colour', 'images/submenu.png', 'forecolour', '', !disabled);
	content+= wysToolbarButton(name, 'Highlight colour', 'images/bgcol.png', 'applyhilightcolour', '', !disabled);
	content+= wysToolbarButton(name, 'Choose highlight colour', 'images/submenu.png', 'hilightcolour', '', !disabled);

  if (obj.tblevel != 0) {
		content+= "|";
		content+= wysToolbarButton(name, 'Make link', 'images/link.png', 'createlink', '', !disabled);
		content+= wysToolbarButton(name, 'Remove link', 'images/nolink.png', 'unlink', '', !disabled);
		content+= wysToolbarButton(name, 'Insert table', 'images/table.png', 'inserttable', '', !disabled);
		content+= wysToolbarButton(name, 'Insert image', 'images/image.png', 'insertimage', '', !disabled);
  }
	content+= "|";
	content+= wysToolbarButton(name, 'Remove formatting', 'images/nostyle.png', 'removeformat', '', !disabled);

//	content+= "</td></tr></table>";

	return content;
}

function wysToolbarButton(name, title, img, command, option, enabled) {
	var html = "";
	if (enabled) {
		html+= "<a id='WYS_" + name + "_" + command + "_button' href='javascript:wysApplyCommand(this, \"" + name + "\", \"" + command + "\", \"" + option;
		html+= "\");'";
		if (command == 'applyforecolour') {
			html+= " style='background-color: " + g_wysCurrentForeColour + ";'";
		} else if (command == 'applyhilightcolour') {
			html+= " style='background-color: " + g_wysCurrentBackColour + ";'";
		}
		html+= ">";
	}
	html+= "<img alt='" + title + "' title='" + title + "' src='" + g_zygoResourcePath + img + "'";
	html+= " style='border: 1px solid white; vertical-align: middle;";
	if (!enabled) {
		html+= "opacity: 0.5; filter:Alpha(Opacity=50, Style=0);";
	}
	html+= "'";
	html+= " onmouseover='this.style.border=\"1px outset white\";' onmouseout='this.style.border=\"1px solid white\";' onmousedown='this.style.border=\"1px inset white\";'";
	html+= " border='0' height='22'>";
	if (enabled) {
		html+= "</a>";
	}

	return html;
}

function wysFootbarHTML(name) {
	var content = "";
	content+= "<a id='WYS_" + name + "_deslink' style='display: block; float: left;' href='javascript:wysDesignMode(\"" + name + "\", true);'><img src='" + g_zygoResourcePath + "images/design.png' alt='Design' border='0'></a>";
	content+= "<a id='WYS_" + name + "_htmllink' style='display: block; float: left;' href='javascript:wysDesignMode(\"" + name + "\", false);'><img src='" + g_zygoResourcePath + "images/html.png' alt='HTML' border='0'></a>";

	return content;
}

function wysApplyCommand(link, name, command, option) {
	var obj = wysFindControl(name);
	if (!obj.designMode) {
		return;
	}

	// Save cursor for IE
	if (document.all) {
		document.getElementById(obj.iframeid).contentWindow.focus();
		g_wysSaveCursor=document.getElementById(obj.iframeid).contentWindow.document.selection.createRange();
	}
	if (command == 'forecolour') {
		g_wysColourObject = obj;
		colShowSelector(name + "_forecolour", "WYS_" + name + "_applyforecolour_button", wysApplyForeColour);
		return;
	} else if (command == 'applyforecolour') {
		command = "forecolor";
		option = g_wysCurrentForeColour;
	} else if (command == 'hilightcolour') {
		g_wysColourObject = obj;
		colShowSelector(name + "_backcolour", "WYS_" + name + "_applyhilightcolour_button", wysApplyBgColour);
		return;
	} else if (command == 'applyhilightcolour') {
		command = document.all ? 'backcolor' : 'hilitecolor';
		option = g_wysCurrentBackColour;
	} else if (command == 'inserttable') {
		var html = "<form name='WYS_TABLE_FORM' onsubmit='this.okbutt.onclick(); return false;'><table><tr><td>Columns</td><td><input type='text' size='4' name='cols' value='2'></td></tr>";
		html+= "<tr><td>Rows</td><td><input type='text' size='4' name='rows' value='2'></td></tr>";
		html+= "<tr><td>Border</td><td><input type='checkbox' checked='true' name='border' value='1'></td></tr>";
		html+= "<tr><td colspan='2' align='right'><input type='button' onclick='popCloseWindow()' value='Cancel'>";
		html+= " <input type='button' onclick='wysInsertTable(\"" + name + "\", this.form.cols.value, this.form.rows.value, this.form.border.checked);popCloseWindow();' value=' OK ' name='okbutt'></td></tr>";
		html+= "</table></form>";
		popShowWindow("WYS_" + name + "_inserttable_button", "bottom", html);
		return;
	} else if (command == 'createlink') {
		var html = "<form name='WYS_LINK_FORM' onsubmit='this.okbutt.onclick(); return false;'><table>";
		if (c_wysLinks.length > 0) {
			html+= "<tr><td>Page:</td><td><select name='page'>";
			for (var i = 0; i < c_wysLinks.length; i++) {
				html+= "<option value='" + i + "'>" + c_wysLinks[i].title + "</option>";
			}
			html+= "</select></td></tr>";
		}
		html+= "<tr><td>http://</td><td><input type='text' name='url'></td></tr>";
		html+= "<tr><td colspan='2' align='right'><input type='button' value='Cancel' onclick='popCloseWindow()'>";
		html+= " <input type='button' value=' OK ' name='okbutt' onclick='wysMakeLink(\"" + name + "\", this.form.url.value, this.form.page ? this.form.page.selectedIndex : -1);popCloseWindow();'></td></tr>";
		html+= "</table></form>";
		popShowWindow("WYS_" + name + "_createlink_button", "bottom", html);
		return;
	} else if (command == 'insertimage') {
		if (c_wysCustomImageSelector) {
			g_wysCustomImageObject = name;
			popShowElement("WYS_" + name + "_insertimage_button", "bottom", c_wysCustomImageSelector);
		} else {
			var html = "<div style='width: 600px; height: 300px; overflow: auto;'>";
			for (var i = 0; i < c_wysImages.length; i++) {
				html+= wysMakeImageSelectorHTML(c_wysImages[i], name, i);
				if (c_wysImages[i].type == 'folder') {
					html+= "<div id='IMGOPN_" + name + "_" + i +"' style='display: none;'>";
					for (var j = 0; j < c_wysImages[i].content.length; j++) {
						html+= wysMakeImageSelectorHTML(c_wysImages[i].content[j], name, j, i);
					}
					html+= "</div>";
				}
			}
			html+= "</div>";
			popShowWindow("WYS_" + name + "_insertimage_button", "bottom", html);
		}
		return;
	} else if (command == 'custom') {
		if (option == "") {
			return;
		}
		var index = parseInt(option);
		wysInsertCustomHTML(obj, c_wysHTMLBlocks[index].start, c_wysHTMLBlocks[index].end);
		return;
	} else if (command == 'style') {
		if (option == "") {
			return;
		}
		var index = parseInt(option);
		wysApplyInlineSpan(obj, c_wysStyles[index].html);
		return;
	} else if (command == 'formatblock' && option == '') {
		return;
	} else if (command == "fontsize" && option == '') {
		return;
	} else if (command == "small") {
		wysApplyInlineSpan(obj, "<span class='small'>");
		return;
	} else if (command == "removeformat") {
		if (document.all) {
			document.getElementById(obj.iframeid).contentWindow.focus();
			var range = document.getElementById(obj.iframeid).contentWindow.document.selection.createRange();
			range.text = range.text;
			return;
		}
	}
			
	var doc = document.getElementById(obj.iframeid).contentWindow.document;
	if (doc.queryCommandEnabled(command)) {
		doc.execCommand(command, false, option);
	}
}

function wysMakeImageSelectorHTML(imgObj, ctlName, imgIndex, folderIndex) {
	var html = "";

	html+= "<div style='border: 1px solid black; background-color: white; height: 50px;'";
	if (imgObj.type == 'img') {
		if (folderIndex == null) {
			html+= " onclick='wysInsertImage(\"" + ctlName + "\", " + imgIndex + ");popCloseWindow();'";
		} else {
			html+= " onclick='wysInsertImage(\"" + ctlName + "\", " + imgIndex + ", " + folderIndex + ");popCloseWindow();'";
		}
	} else {
		html+= " onclick='wysOpenImageFolder(\"" + ctlName + "\", " + imgIndex + ");'";
	}
	html+= ">";
	html+= "<table border='0' width='570' height='50'><tr "
	html+= " onmouseover='this.style.backgroundColor=\"#000080\"; this.style.color=\"#ffffff\";'";
	html+= " onmouseout='this.style.backgroundColor=\"#ffffff\"; this.style.color=\"#000000\";'";
	html+= ">";
	if (imgObj.type == 'img') {
		html+= "<td valign='middle'>";
		html+= "" + imgObj.title + "</td><td align='right' width='46'>";
		var url = imgObj.preview || imgObj.url;
		html+= "<img src='" + url + "' style='width: 46px; height: 46px;' />";
	} else {
		// Folder
		html+= "<td valign='middle' colspan='2'>";
		html+= "<img src='" + g_zygoResourcePath + "images/folder.gif' align='middle' /> " + imgObj.title;
	}
	html+= "</td></tr></table></div>";

	return html;
}

function wysOpenImageFolder(ctlName, index) {
	var elem = document.getElementById("IMGOPN_" + ctlName + "_" + index);
	if (elem) {
		if (elem.style.display == "none") {
			elem.style.display = "block";
		} else {
			elem.style.display = "none";
		}
	}
}

function wysInsertImage(name, imageno, folderno) {
	var obj = wysFindControl(name);

	if (document.all) {
		g_wysSaveCursor.select();
	}
/*
	var cw = document.getElementById(obj.iframeid).contentWindow;
	cw.focus();
	var command = "insertimage";
	var doc = document.getElementById(obj.iframeid).contentWindow.document;
	if (doc.queryCommandEnabled(command)) {
		doc.execCommand(command, false, c_wysImages[imageno].url);
	}
*/
	var html;
	if (folderno == null) {
		html = "<img src='" + c_wysImages[imageno].url + "' border='0'>";
	} else {
		html = "<img src='" + c_wysImages[folderno].content[imageno].url + "' border='0'>";
	}
	if (document.all) {
		// Do it the IE way
		g_wysSaveCursor.select();
		var cw = document.getElementById(obj.iframeid).contentWindow;
		cw.focus();
		var range = cw.document.selection.createRange();
		range.pasteHTML(html);
		cw.focus();
	} else {
		var cw = document.getElementById(obj.iframeid).contentWindow;
		cw.focus();
		var command = "inserthtml";
		var doc = document.getElementById(obj.iframeid).contentWindow.document;
		if (doc.queryCommandEnabled(command)) {
			doc.execCommand(command, false, html);
		}
		cw.focus();
	}
}

var g_wysCustomImageObject = null;
function wysInsertCustomImage(url) {
	var obj = wysFindControl(g_wysCustomImageObject);
	if (!obj)
		return;

	if (document.all) {
		g_wysSaveCursor.select();
	}

	var html = "<img src='" + url + "' border='0'>"
	if (document.all) {
		// Do it the IE way
		g_wysSaveCursor.select();
		var cw = document.getElementById(obj.iframeid).contentWindow;
		cw.focus();
		var range = cw.document.selection.createRange();
		range.pasteHTML(html);
		cw.focus();
	} else {
		var cw = document.getElementById(obj.iframeid).contentWindow;
		cw.focus();
		var command = "inserthtml";
		var doc = document.getElementById(obj.iframeid).contentWindow.document;
		if (doc.queryCommandEnabled(command)) {
			doc.execCommand(command, false, html);
		}
		cw.focus();
	}
	popCloseWindow();
}

function wysMakeLink(name, url, linkno) {
	var obj = wysFindControl(name);

	if (document.all) {
		g_wysSaveCursor.select();
	}

	var option;
	if (url && url.length > 0) {
		option = "http://" + url;
	} else {
		option = c_wysLinks[linkno].url;
	}
	var cw = document.getElementById(obj.iframeid).contentWindow;
	cw.focus();
	var command = "createlink";
	var doc = document.getElementById(obj.iframeid).contentWindow.document;
	if (doc.queryCommandEnabled(command)) {
		doc.execCommand(command, false, option);
	}
}

function wysInsertTable(name, cols, rows, border) {
	var obj = wysFindControl(name);
	var html = "<table border='";
	if (border) {
		html+= "1";
	} else {
		html+= "0";
	}
	html+= "'>";
	for (var r = 0; r < rows; r++) {
		html+= "<tr>";
		for (var c = 0; c < cols; c++) {
			html+= "<td></td>";
		}
		html+= "</tr>";
	}
	html+= "</table>";

	if (document.all) {
		// Do it the IE way
		g_wysSaveCursor.select();
		var cw = document.getElementById(obj.iframeid).contentWindow;
		cw.focus();
		var range = cw.document.selection.createRange();
		range.pasteHTML(html);
		cw.focus();
	} else {
		var cw = document.getElementById(obj.iframeid).contentWindow;
		cw.focus();
		var command = "inserthtml";
		var doc = document.getElementById(obj.iframeid).contentWindow.document;
		if (doc.queryCommandEnabled(command)) {
			doc.execCommand(command, false, html);
		}
		cw.focus();
	}
}

function wysApplyInlineSpan(obj, spanhtml) {
	document.getElementById(obj.iframeid).contentWindow.focus();

	var cw = document.getElementById(obj.iframeid).contentWindow;
	try {cw.document.execCommand("useCSS", false, false);} catch (ex) {}
	try {cw.document.execCommand("styleWithCSS", false, false);} catch (ex) {}

	cw.document.execCommand("FontName", false, "#secret_font_name#");

	// Now find all of those font tags and replace with our custom spans
	var fonts = cw.document.getElementsByTagName("font");
	for (var i = 0; i < fonts.length; i++) {
		if (fonts[i].face = "#secret_font_name#") {
			if (document.all) {
				fonts[i].outerHTML = spanhtml + fonts[i].innerHTML + "</span>";
			} else {
				var elem = document.createElement("div");
				elem.innerHTML = spanhtml + fonts[i].innerHTML + "</span>";
				fonts[i].parentNode.replaceChild(elem.firstChild, fonts[i]);
			}
			i--;
		}
	}
}

function wysInsertCustomHTML(obj, starthtml, endhtml) {
	document.getElementById(obj.iframeid).contentWindow.focus();

	if (document.all) {
		var cw = document.getElementById(obj.iframeid).contentWindow;
		var tr = cw.document.selection.createRange();
		var tr2 = tr.duplicate();
		tr.collapse(false);
		tr.text = "#replace_end_html#";
		tr2.select();
		tr2.collapse(true);
		tr2.text = "#replace_start_html#";
	} else {
		var cw = document.getElementById(obj.iframeid).contentWindow;
		var tr = cw.getSelection().getRangeAt(0);
		var tr2 = tr.cloneRange();
		tr.collapse(false);
		tr.insertNode(cw.document.createTextNode("#replace_end_html#"));
		tr2.collapse(true);
		tr2.insertNode(cw.document.createTextNode("#replace_start_html#"));
	}

	if (0) {
	// Fix for document start
	var elem = cw.document.body;
	while (elem) {
		elem = elem.firstChild;
		if (elem && elem.nodeType == 3) {		// Text node
			while (elem && elem.nodeType == 3) {
				if (elem.nodeValue.match(/^#replace_start_html#/)) {
					// Move it
					elem.nodeValue = elem.nodeValue.replace(/^#replace_start_html#/, "");
					cw.document.body.insertBefore(cw.document.createTextNode("#replace_start_html#"), cw.document.body.firstChild);
					break;
				}
				elem = elem.nextSibling;
			}
		}
	}

	var elem = cw.document.body;
	while (elem) {
		elem = elem.lastChild;
		if (elem && elem.nodeType == 3) {		// Text node
			while (elem && elem.nodeType == 3) {
				if (elem.nodeValue.match(/#replace_end_html#$/)) {
					// Move it
					elem.nodeValue = elem.nodeValue.replace(/#replace_end_html#$/, "");
					cw.document.body.appendChild(cw.document.createTextNode("#replace_end_html#"));
					break;
				}
				elem = elem.previousSibling;
			}
		}
	}
	}
						
	var allhtml = cw.document.body.innerHTML;
	allhtml = allhtml.replace(/#replace_start_html#/, starthtml);
	allhtml = allhtml.replace(/#replace_end_html#/, endhtml);
	cw.document.body.innerHTML = allhtml;
}

function wysApplyForeColour(col) {
	var obj = g_wysColourObject;
	if (obj) {
		if (document.all) {
			g_wysSaveCursor.select();
		}
		var doc = document.getElementById(obj.iframeid).contentWindow.document;
		g_wysCurrentForeColour = "#"+col;
		if (doc.queryCommandEnabled('forecolor')) {
			doc.execCommand('forecolor', false, "#"+col);
		}
	}
}

function wysApplyBgColour(col) {
	var obj = g_wysColourObject;
	if (obj) {
		if (document.all) {
			g_wysSaveCursor.select();
		}
		var doc = document.getElementById(obj.iframeid).contentWindow.document;
		var command = document.all ? 'backcolor' : 'hilitecolor';
		g_wysCurrentBackColour = "#"+col;
		if (doc.queryCommandEnabled(command)) {
			doc.execCommand(command, false, "#"+col);
		}
	}
}

function wysCompat() {
  return true;
/*
	if (!document.getElementById) return false;

	var frame = document.createElement("iframe");
	frame.style.display = "none";
	document.body.appendChild(frame);
	if (typeof(frame.contentWindow) == "object") {
		return true;
	}

	return false;
*/
}


/*
	Tooltip/citation code...
*/

// Config vars
var c_citeBoxWidth = 400;
var c_citeBoxStyle = "border: 1px solid black; background-color: #fffbd9; font-family: arial; font-size: x-small; padding: 5px;"
var c_citeBoxClass = null;

// Globals
var g_citeBox = null;
var g_citeElem = null;
var g_citeTimer = null;

// Install onload handler if browser is up to it
if (typeof(g_ZygoLibLoaded) == 'undefined') {
	if (document.getElementById) {
		var _oldOnload = window.onload;
		window.onload = function () { citeSetUp(); if (_oldOnload) {_oldOnload();} }
	}
}

function citeConfig(width, style, cssclass) {
	c_citeBoxWidth = width;
	c_citeBoxStyle = style;
	c_citeBoxClass = cssclass;
}

function citeSetUp() {
	g_citeBox = document.createElement( "div" );
	g_citeBox.style.visibility = "hidden";
	document.body.appendChild( g_citeBox );
}

function citePrep(el) {
	g_citeElem = el;
	if ( g_citeTimer ) {
		window.clearTimeout( g_citeTimer );
		g_citeTimer = null;
	}
	g_citeTimer = window.setTimeout( "citeShow()", 500 );
}

function citeShow() {
	g_citeTimer = null;
	var ref = g_citeElem.hash.replace( /^#/, '' );
	var elem = document.getElementById( ref );
	if ( elem ) {
		var divHTML = "<div ";
		if (c_citeBoxStyle) {
			divHTML+= "style='" + c_citeBoxStyle + "'";
		}
		if (c_citeBoxClass) {
			divHTML+= "class='" + c_citeBoxClass + "'";
		}
		divHTML+= ">";
		g_citeBox.innerHTML = divHTML + elem.innerHTML + "</div>";
		var pos = utilGetElementPosition( g_citeElem );
		g_citeBox.style.position = "absolute";
		g_citeBox.style.top = Math.max( pos.top - g_citeBox.offsetHeight, 0 ) + "px";
		var ww = window.innerWidth || document.body.clientWidth;
		g_citeBox.style.left = Math.min( pos.left + 8, ww - c_citeBoxWidth + 20 ) + "px";
		g_citeBox.style.width = c_citeBoxWidth + "px";
		g_citeBox.style.visibility = "visible";
	}
}

function citeRemove() {
	if ( g_citeTimer ) {
		window.clearTimeout( g_citeTimer );
		g_citeTimer = null;
	}
	g_citeTimer = window.setTimeout( "citeHide()", 500 );
}

function citeHide() {
	g_citeTimer = null;
	g_citeBox.style.visibility = "hidden";
}	

/*
	Date selection
*/

/*
	Convert some form inputs into a date selector:
	Call dateConvertInputs(cday, cmonth, cyear, div);
	cday	- ID of the day input
	cmonth	- ID of the month input
	cyear	- ID of the year input
	div		- ID of container to install control in
*/

var g_dateObjects = new Array();

function dateConvertInputs(cday, cmonth, cyear, div) {
	var eday, emonth, eyear, ediv;
	eday = document.getElementById(cday);
	emonth = document.getElementById(cmonth);
	eyear = document.getElementById(cyear);
	ediv = document.getElementById(div);
	if (eday && emonth && eyear && ediv) {
		if (eday.nodeName != "INPUT") {
			utilRaiseError("dateConvertInputs cday must be an input element");
		} else if (emonth.nodeName != "INPUT") {
			utilRaiseError("dateConvertInputs cmonth must be an input element");
		} else if (eyear.nodeName != "INPUT") {
			utilRaiseError("dateConvertInputs cyear must be an input element");
		} else {
			dateInstallControl(eday, emonth, eyear, ediv);
		}
	} else {
		utilRaiseError("dateConvertInputs for non-existent element");
	}
}

function dateInstallControl(eday, emonth, eyear, ediv) {
	var obj = new Object();
	obj.dayInput = eday;
	obj.monthInput = emonth;
	obj.yearInput = eyear;
	obj.idNum = g_dateObjects.length;
	g_dateObjects.push(obj);

	ediv.innerHTML = dateSelectButton(obj);
}

function dateSelectButton(obj) {
	var html;
	obj.openerControlId = "ZDATESEL_" + obj.idNum;
	html = '<a id="' + obj.openerControlId + '" href="javascript:dateChooseDate(' + obj.idNum + ');">Select</a>'

	return html;
}

function dateChooseDate(id) {
	var obj = g_dateObjects[id];

	var vday = obj.dayInput.value;
	var vmonth = obj.monthInput.value;
	var vyear = obj.yearInput.value;
	var vDate = new Date();
	try {
		vDate = new Date(parseInt(vyear), parseInt(vmonth) - 1, parseInt(vday));
	} catch (e) {
	}

	var html = dateSelectionHTML(vDate);
	popShowWindow(document.getElementById(obj.openerControlId), "over", html, 200, 150);
}

function dateSelectionHTML(theDate) {
	var html = "Something...";

	return html;
}


/*
	Utils
*/

function utilRaiseError(msg) {
	alert(msg);
}

function utilGetElementPosition(elem) {
	var offsetLeft = 0;
	var offsetTop = 0;
	var offsetWidth = elem.offsetWidth;
	var offsetHeight = elem.offsetHeight;

	while ( elem ) {
		offsetLeft+= elem.offsetLeft;
		offsetTop+= elem.offsetTop;
		elem = elem.offsetParent;
	}
	if ( navigator.userAgent.indexOf("Mac") != -1 && typeof document.body.leftMargin != "undefined" ) {
		offsetLeft+= document.body.leftMargin;
		offsetTop+= document.body.topMargin;
	}
	return {left:offsetLeft, top:offsetTop, width:offsetWidth, height:offsetHeight};
}


g_ZygoLibLoaded = 1;
