// this code is copyright Benchmarx Limited - copy it and we'll sue you.

var isIE;
var isIE7;
var isGecko;
var isSafari;
var isKonqueror;

var browser = navigator.userAgent.toLowerCase();
isIE = ((browser.indexOf('msie') != -1) && (browser.indexOf('opera') == -1) && (browser.indexOf('webtv') == -1)); 
isIE7 = (browser.indexOf('MSIE 7.0') != -1);
isGecko = (browser.indexOf('gecko') != -1);
isSafari = (browser.indexOf('safari') != -1);
isKonqueror = (browser.indexOf('konqueror') != -1);

var _username = '';
var _uc = null;
var debug = 0;

function setCookie(c_name,value,expiredays)
{
	var exdate=new Date()
	exdate.setDate(exdate.getDate()+expiredays)
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
}
function getCookie(c_name)
{
	if (document.cookie.length>0)
	{
		c_start=document.cookie.indexOf(c_name + "=")
		if (c_start!=-1)
		{ 
			c_start=c_start + c_name.length+1 
			c_end=document.cookie.indexOf(";",c_start)
			if (c_end==-1) c_end=document.cookie.length
			return unescape(document.cookie.substring(c_start,c_end))
		}
	}
	return ""
}

function deleteCookie(name)
{
	if (getCookie(name))
	{
		document.cookie = name + '=;expires=Thu, 01-Jan-1970 00:00:01 GMT;;';
	}
}

function createLink(href, text)
{
	var el = document.createElement('a');
	el.href = href;
	el.innerHTML = text;
	return el;
}

function createTextInputElement(id, cn, name, value)
{
	var el = document.createElement('input');
	el.type = 'text';
	el.id = id;
	el.className = cn;
	el.name = name;
	el.value = value;
	return el;
}

function createPasswordInputElement(id, cn, name, value)
{
	var el = document.createElement('input');
	el.type = 'password';
	el.id = id;
	el.className = cn;
	el.name = name;
	el.value = value;
	return el;
}

function createSubmitInputElement(id, cn, name, value)
{
	var el = document.createElement('input');
	el.type = 'submit';
	el.id = id;
	el.className = cn;
	el.name = name;
	el.value = value;
	return el;
}

function createSelectInputElement(id, cn, name, value)
{
	var el = document.createElement('select');
	el.id = id;
	el.className = cn;
	el.name = name;
	el.value = value;
	return el;
}

function createDivElement(id, cn, html)
{
	var el = document.createElement('div');
	el.id = id;
	el.className = cn;
	el.innerHTML = html;
	return el;
}

function createSpanElement(id, cn, html)
{
	var el = document.createElement('span');
	el.id = id;
	el.className = cn;
	el.innerHTML = html;
	return el;
}

function createHTMLElement(text)
{
	var el = document.createElement('text');
	el.innerHTML = text;
	return el;
}

function removeElementByName(name)
{
	var el = e(name);
	if (el != null)
	{
		el.parentNode.removeChild(el);
	}
}

function clearElement(el)
{
	var n = el.childNodes.length
	for (var i = 0; i < n; i++)
	{
		el.removeChild(el.childNodes[0]);
	}
}

var clre = createDivElement('clear', '', '');

createDelegate = function(instance,method)
{
	return function()
	{
		return method.apply(instance,arguments);
	}
}

ServerContext = function(m, u, d, async)
{
	this.xmlhttp = null;
	this.method = m;
	this.url = u;
	this.data = d;
	
	ServerContext.prototype.callback = function()
	{
	}
		
	ServerContext.prototype.stateChange = function()
	{
		// if xmlhttp shows "loaded"
		if (this.xmlhttp.readyState==4)
		{
			// if "OK"
			if (this.xmlhttp.status==200)
			{
				if (this.xmlhttp.responseText.substr(0, 5) == 'ERROR')
				{
					alert(this.xmlhttp.responseText.substr(5));
				}
				else
				{
					if (this.callback) 
					{
						this.callback(this.xmlhttp.responseXML, this.xmlhttp.responseText);
					}
				}
			}
			else
			{

			}
		}
	}
	
	ServerContext.prototype.post = function(data)
	{
		this.xmlhttp.open('post', this.url, true);
		this.xmlhttp.setRequestHeader('Content-type', 'text/xml');
		this.xmlhttp.setRequestHeader('Content-length', data.length);
		this.xmlhttp.setRequestHeader('Connection', 'close');
		this.xmlhttp.send(data);
	}

	// code for Mozilla, etc.
	if (window.XMLHttpRequest)
	{
		this.xmlhttp=new XMLHttpRequest();
	}
	else if (window.ActiveXObject)
	{
		this.xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	if (this.xmlhttp == null)
	{
		alert("Your browser does not support XMLHTTP.");
	}
	else
	{
		this.xmlhttp.onreadystatechange = createDelegate(this, this.stateChange);
	}
}

RPC = function(name, params, ret)
{
	var request = '<?xml version="1.0" encoding="utf-8" ?>\n';
	request += '<request>\n';
	request += '<function>' + name + '</function>\n';
	if (params != null)
	{
		for (var i = 0; i < params.length; i++)
		{
			request += '<parameter>' + params[i] + '</parameter>\n';
		}
	}
	request += '</request>';

	// create XML document for request
	var url = 'http://www.benchmarx.com/ca/ajaxhandler.aspx';
	if (window.location.href.substr(0, 5) == 'https')
		url = 'https://www.benchmarx.com/ca/ajaxhandler.aspx';
	
	if (debug)
	    url = 'http://localhost:3586/ca/ajaxHandler.aspx';
	
	var a = new ServerContext('post', url, null, true);
	a.callback = ret;
	a.post(request);
}

var siteBase = '##site-base##';
var capture = null;
var context = null;
var focus = null;

document.onmousedown = function()
{
	removeElementFromParent(context);
	context = null;
	
	return true;
}
document.onmousemove = function(ev)
{
	ev = ev || window.event;
	
	if (capture && capture.onmousemove)
	{
		capture.onmousemove(ev);
		return false;
	}

	return true;
}
document.onmouseup = function(ev)
{
	ev = ev || window.event;
	if (capture && capture.onmouseup)
	{
		capture.onmouseup(ev);
		return false;
	}
	
	return true;
}
document.onkeypress = function(ev)
{
	ev = ev || window.event;
	key = ev.keyCode || ev.which;
	
	if (key == 27)
	{
		removeElementFromParent(context);
		removeElementFromParent(focus);
		focus = null;
		context = null;
	}
}

function e(i){return document.getElementById(i);}

function mouseCoords(ev)
{
	if(ev.pageX || ev.pageY)
	{
		return {x:ev.pageX, y:ev.pageY};
	}
	return { x:ev.clientX + document.body.scrollLeft - document.body.clientLeft, y:ev.clientY + document.body.scrollTop  - document.body.clientTop };
}
function getPosition(e)
{
	var left = 0;
	var top  = 0;

	while (e.offsetParent)
	{
		left += e.offsetLeft;
		top  += e.offsetTop;
		e     = e.offsetParent;
	}

	left += e.offsetLeft;
	top  += e.offsetTop;

	return {x:left, y:top};
}
function getMouseOffset(target, ev)
{
	var docPos    = getPosition(target);
	var mousePos  = mouseCoords(ev);
	return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y + target.scrollTop};
}

function resetZIndices(top)
{
	var divs = document.getElementsByTagName('div');
	var maxz = 0;
	for (var i = 0; i < divs.length; i++)
	{
		if (divs[i].className == 'dlg') maxz++;
	}

	for (var i = 0; i < divs.length; i++)
	{
		if (divs[i].className == 'dlg' && divs[i] != top)
		{
			if (divs[i].style.zIndex >= top.style.zIndex)
				divs[i].style.zIndex = divs[i].style.zIndex - 1;
			divs[i].style.zIndex = 0;
		}
	}
	
	top.style.zIndex = maxz;
}
function setZIndex(el)
{
	var divs = document.getElementsByTagName('div');
	var maxz = 0;
	for (var i = 0; i < divs.length; i++)
	{
		if (divs[i].className == 'dlg') maxz++;
	}
	el.style.zIndex = divs.length + 1;
}

Dialog = function(title, id, x, y)
{
	this.sizing = false;
	this.dialog = null;
	this.title = null;
	this.dragging = false;
	this.resize = null;

	var offset;
	var org;
	var ow;
	var oh;

	// logic

	Dialog.prototype.setResizable = function(r)
	{
		this.resizable = r;
		if (this.resizable == true && this.resize == null)
		{
			this.addResizeGadget();
		}
	}

	Dialog.prototype.mouseDownResize = function(ev)
	{
		if (this.resizable == false) return true;
		ev = ev || window.event;

		ow = this.dialog.offsetWidth;
		oh = this.dialog.offsetHeight;
		org = mouseCoords(ev);
		this.sizing = true;
		capture = this.resize;
		focus = this.dialog;
		return false;
	}
	
	Dialog.prototype.mouseMoveResize = function(ev)
	{
		ev = ev || window.event;

		if (this.sizing)
		{
			var c = mouseCoords(ev);
			
			if (isIE == true)
			{
				this.dialog.style.width = (ow + c.x - org.x) + 'px';
				this.dialog.style.height = (oh + c.y - org.y) + 'px';
			}
			else
			{
				this.dialog.style.width = (ow + c.x - org.x - 6) + 'px';
				this.dialog.style.height = (oh + c.y - org.y - 6) + 'px';
			}

			this.resize.style.left = (ow + c.x - org.x - 19) + 'px';
			this.resize.style.top = (oh + c.y - org.y - 19) + 'px';
		}
	}

	Dialog.prototype.mouseUpResize = function(ev)
	{
		ev = ev || window.event;
		this.sizing = false;
		capture = null;
	}

	Dialog.prototype.mouseDownHeader = function(ev)
	{
		ev = ev || window.event;

		offset = getMouseOffset(this.dialog, ev);
		
		resetZIndices(this.dialog);
		this.dragging = true;
		setElementOpacity(this.dialog, 0.55);
		this.title.style.cursor = 'move';
		
		capture = this.title;
		focus = this.dialog;
		
		return false;
	}
	
	Dialog.prototype.mouseMoveHeader = function(ev)
	{
		ev = ev || window.event;

		if (this.dragging)
		{
			var c = mouseCoords(ev);
			
			this.dialog.style.left = c.x - offset.x + 'px';
			this.dialog.style.top = c.y - offset.y + 'px';
		}
		
		return false;
	}
	
	Dialog.prototype.mouseUpHeader = function(ev)
	{
		this.dragging = false;
		setElementOpacity(this.dialog, 1.0);

		capture = null;
		this.title.style.cursor = '';
		
		return false;
	}
	
	Dialog.prototype.clickClose = function()
	{
		removeElementFromParent(this.dialog);
	}

	Dialog.prototype.addResizeGadget = function()
	{
		this.resize = document.createElement('img');
		this.resize.src = '##nugget-base##/images/resize.png';
		this.resize.style.border = 'none';
		this.resize.className = 'resize';
		this.resize.style.position = 'absolute';
		this.resize.style.left = (this.dialog.offsetWidth - 19) + 'px';
		this.resize.style.top = (this.dialog.offsetHeight - 19) + 'px';
		this.resize.onmousedown = createDelegate(this, this.mouseDownResize);
		this.resize.onmousemove = createDelegate(this, this.mouseMoveResize);
		this.resize.onmouseup = createDelegate(this, this.mouseUpResize);
		this.dialog.appendChild(this.resize);

		focus = this.dialog;
	}

	// presentation

	this.dialog = document.createElement('div');
	this.dialog.id = 'dlg_' + id;
	this.dialog.className = 'dlg';
	this.dialog.style.left = x + 'px';
	this.dialog.style.top = y + 'px';
	document.body.appendChild(this.dialog);
	
	var header = document.createElement('div');
	header.className = 'dlg-header';
	this.dialog.appendChild(header);

	this.title = document.createElement('div');
	this.title.className = 'dlg-title';
	this.title.innerHTML = '&nbsp;' + title + '&nbsp;';
	this.title.onmousedown = createDelegate(this, this.mouseDownHeader);
	this.title.onmousemove = createDelegate(this, this.mouseMoveHeader);
	this.title.onmouseup = createDelegate(this, this.mouseUpHeader);
	header.appendChild(this.title);
	
	var div = document.createElement('div');
	div.className = 'dlg-close';
	header.appendChild(div);
	
	var close = document.createElement('img');
	close.src = '##nugget-base##/images/close.png';
	close.style.border = 'none';
	close.className = 'clickable';	
	close.onclick = createDelegate(this, this.clickClose);
	div.appendChild(close);

	this.body = document.createElement('div');
	this.body.className = 'dlg-body';
	this.body.id = 'dlg_' + id + '_body';
	this.body.style.position = 'relative';
	this.dialog.appendChild(this.body);

	focus = this.dialog;
}

Context = function(id, x, y)
{
	var c = document.createElement('div');
	c.id = 'context';
	c.className = 'context';
	c.style.top = y + 'px';
	c.style.left = x + 'px';
	document.body.appendChild(c);
	return c;
}

function expandCollapse(img, el)
{
	var panel = e(el);
	
	for (var i = 0; i < panel.childNodes.length; i++)
	{
		if (panel.childNodes[i].className == 'panel-body')
		{
			if (panel.childNodes[i].style.display == '')
			{
				panel.childNodes[i].style.display = 'none';	
				img.src = '##nugget-base##/images/expand.png';
				img.title = '#@expand@#';
			}
			else
			{
				panel.childNodes[i].style.display = '';
				img.src = '##nugget-base##/images/collapse.png';
				img.title = '#@collapse@#';
			}
			return;
		}
	}
}

function removeElementFromParent(el)
{
	if (el == null) return;

	var a = new FadeRemoveAnimation(el, true);
}

function setElementOpacity(element,value)
{
	if (element.filters)
	{
		var filters = element.filters;
		var createFilter = true;

		if (filters.length != 0)
		{
			var alphaFilter = filters['DXImageTransform.Microsoft.Alpha'];
			if (alphaFilter != null)
			{
				createFilter = false;
				alphaFilter.opacity = value * 100;
			}
		}
		if (createFilter)
		{
			element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity='+(value * 100)+')';
		}
	}
	else 
	{
		element.style.opacity = value;
	}
}

function getElementOpacity(element)
{
	var hasOpacity =false;
	var opacity;

	if (element.filters)
	{
		var filters =element.filters;
		if (filters.length !=0)
		{
			var alphaFilter =filters['DXImageTransform.Microsoft.Alpha'];

			if (alphaFilter !=null)
			{
				opacity =alphaFilter.opacity /100.0;hasOpacity =true;
			}
		}
	}
	else 
	{
		var computedStyle =document.defaultView.getComputedStyle;

		opacity =computedStyle(element,null).getPropertyValue('opacity');hasOpacity =true;
	}

	if (hasOpacity ==false)
	{
		return 1.0;
	}

	return parseFloat(opacity);
}

FadeRemoveAnimation = function(el, remove)
{
	var element = el;
	var timer;
	
	this.done = function()
	{
	}
	
	this.setDone = function(c)
	{
		this.done = c;
	}

	step = function()
	{
		var o = getElementOpacity(element);
		o -= 0.1;
		setElementOpacity(element, o);

		if (o <= 0.0)
		{
			window.clearInterval(timer);

			if (remove)
			{
				element.parentNode.removeChild(element);
			}
			
			if (this.done) 
			{
				this.done();
			}
		}
	}
	
	timer = window.setInterval(step, 40);
}

FadeInAnimation = function(el)
{
	var element = el;
	var timer;
	
	timer = window.setInterval(step, 40);
	
	function step()
	{
		var o = getElementOpacity(element);
		o += 0.1;
		
		if (o > 1.0)
		{
			window.clearInterval(timer);
			o = 1.0;
		}
		setElementOpacity(element, o);
	}
}

function dlg_popup_bodyClick(id, date)
{
	var el = e(id);
	var p = e(el.getAttribute('buddy'));

	p.value = date;
}

function sf(frm)
{
	var theform = e(frm);
	theform.submit();
}

FileBrowser = function()
{
	var fb = this;
	var d = new Dialog('#@navigator@#', 'nav', 100, 200);
	d.setResizable(true);
	this.fo = document.createElement('div');
	this.fo.className = 'folders';
	this.fo.name = '';
	d.body.appendChild(this.fo);
	
	this.fi = document.createElement('div');
	this.fi.className = 'files';
	d.body.appendChild(this.fi);
	
	this.parent = this.fo;
	this.busy = false;
	this.insertion = this.fo;

	FileBrowser.prototype.init = function(response)
	{
		var s = response.split('\n');
		for (var i = 0; i < s.length; i++)
		{
			if (s[i] != '')
			{
				fb.addFolder(fb.parent, s[i]);
			}
		}
		
		fb.showFolder('');
	}
	
	FileBrowser.prototype.addFolder = function(parent, name)
	{
		var d1 = document.createElement('div');
		var hs = false;

		if (name.charAt(0) == '+')
		{
			name = name.substr(1);
			hs = true;
		}
			
		d1.name = this.insertion.name + '/';
		if (name != '/') d1.name += name;
		d1.className = 'folder';
		
		var parts = d1.name.split('/');
		d1.style.marginLeft = ((parts.length - 2) * 12) + 'px';
		
		if (this.insertion == this.fo)
		{
			parent.appendChild(d1);
		}
		else
		{
			parent.insertBefore(d1, this.insertion.nextSibling);
		}
		
		if (hs)
		{
			var i = document.createElement('img');
			i.src = '##nugget-base##/images/expand.png';
			i.onclick=function() 
			{
				if (this.src == '##nugget-base##/images/expand.png')
				{
					fb.insertion = d1; 
					fb.listFolders(d1); 
					this.src = '##nugget-base##/images/contract.png';
				}	
			}
			d1.appendChild(i);
		}		
		
		var l = document.createElement('span');
		l.style.marginLeft = '5px';
		l.innerHTML = name;
		l.onclick = function()
		{
			fb.showFolder(d1.name);
			return false;
		}

		d1.appendChild(l);
	}
	
	FileBrowser.prototype.showFolder = function(dir)
	{
		var a = new ServerContext('get', '##nugget-base##/ajax/files/listfiles/' + dir, null, true);
		a.callback = this.showFiles;
		a.go();
	}
	
	FileBrowser.prototype.showFiles = function(response)
	{
		while (fb.fi.childNodes.length > 0)
		{
			fb.fi.removeChild(fb.fi.childNodes[0]);
		}
	
		var s = response.split('\n');
		for (var i = 0; i < s.length; i++)
		{
			var d1 = document.createElement('div');
			d1.innerHTML = s[i];
			d1.className = 'file';
			fb.fi.appendChild(d1);
		}
	}
	
	FileBrowser.prototype.listFolders = function(parent)
	{
		a = new ServerContext('get', '##nugget-base##/ajax/files/list/' + parent.name, null, true);
		a.callback = this.init;
		a.go();
	}

	fb.addFolder(fb.parent, '/');
	this.listFolders(fb.parent);
}

createContentEditor = function(el, id)
{
	var e1 = e(el);
	var w = parseInt(e1.offsetWidth, 10);
	var h = parseInt(e1.offsetHeight, 10);

	var pos = getPosition(e1);
	var x = parseInt(pos.x, 10);
	var y = parseInt(pos.y, 10);

	var e = new Editor(el, 'contenteditor', e1.innerHTML, x, y, w, h);
	e.updateCallback = function()
	{
		var a = new ServerContext('post', '##nugget-base##/content/update/' + id, null, true);
		a.post(encodeURI(e.cw.document.body.innerHTML));
		e1.innerHTML = e.cw.document.body.innerHTML;
		e.dispose(e);
	}
	
	e.cancelCallback = function()
	{
		e.dispose(e);
	}
	
	e.addStyleSheet(siteBase + '/styles.css');
	e.setup();
}

SearchableList = function()
{
	this.list = document.createElement('div');
	document.appendChild(this.list);
	
	var l = document.getElementsByTagName('list');
	alert(l.innerHTML);
}

function postForm(data, url, callback)
{
	var http_request = null;
	
	if (window.XMLHttpRequest)
	{
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType)
		{
			http_request.overrideMimeType('text/html');
		}
	}
	else if (window.ActiveXObject)
	{
		try
		{
			http_request = new ActiveXObject('Msxml2.XMLHTTP');
		}
		catch (e)
		{
			try
			{
				http_request = new ActiveXObject('Microsoft.XMLHTTP');
			}
			catch (e) 
			{
			}
		}
	}
	
	if (!http_request)
	{
		alert('Cannot create XMLHTTP instance');
		return false;
	}

	http_request.onreadystatechange = function()
	{
		if (http_request.readyState == 4)
		{
			if (http_request.status == 200)
			{
				if (window.execScript)
					window.execScript(callback + '()');
				else
					window.setTimeout(callback + '()', 0);
			}
			else
			{
				alert('There was a problem with the request. (' + http_request.status + ')');
			}
		}
	}

	http_request.open('POST', url, true);
	http_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
	http_request.setRequestHeader('Content-length', data.length);
	http_request.setRequestHeader('Connection', 'close');
	http_request.send(data);
	
	return false; 
}

function loadXMLDoc(method, url, el)
{
	var xmlhttp = null;
	var element = el;
	
	// code for Mozilla, etc.
	if (window.XMLHttpRequest)
	{
		xmlhttp=new XMLHttpRequest();
	}
	else if (window.ActiveXObject)
	{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	if (xmlhttp!=null)
	{
		xmlhttp.onreadystatechange=function()
		{
			// if xmlhttp shows "loaded"
			if (xmlhttp.readyState==4)
			{
				// if "OK"
				if (xmlhttp.status==200)
				{
					if (element != null && element != '')
					{
						var el = e(element);
						el.innerHTML = xmlhttp.responseText;
						updateDocument(xmlhttp);
					}
				}
				else
				{
					alert("Problem talking to server.\r\n" + url);
				}
			}
		}
		
		xmlhttp.open(method, url, true);
		xmlhttp.send(null);
	}
	else
	{
		alert("Your browser does not support XMLHTTP.");
	}
}

function compileScript(script)
{
    if (window.execScript)
        window.execScript(script);
    else
        window.setTimeout(script, 0);
}

function updateDocument(req)
{
	var matchAll = new RegExp('(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)', 'img');
	var matchOne = new RegExp('(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)', 'im');

	var results = req.responseText.match(matchAll);
	if (results == null) return;

	for (var i = 0; i < results.length; i++)
	{
		compileScript(results[i].match(matchOne)[1]);
	}
}

function loginComplete(xml)
{
    e('login-error').innerHTML = '';
	// check the result
	var doc = xml.documentElement;
	// get the user string, session ID whatever and stick it in a cookie
	if (doc.nodeName == 'success')
	{
		_uc = getCookie('session');
		
		// remove the login form
		clearElement(e('loginpanel'));
		setupLoginPanel();
	}
	else
	{
		alert(doc.childNodes[0].childNodes[0].nodeValue, 'Login failed');
	}
}

function setupLoginPanel()
{
// create
	var container = e('loginpanel');

	if (_uc == null || _uc == '')
	{
		var uidlabel = createDivElement('uidlabel', 'form-label', 'E-mail: ');
		var pwdlabel = createDivElement('pwdlabel', 'form-label', 'Password: ');
		var uid = createTextInputElement('loginuid', 'form-field', '', '');	
		var pwd = createPasswordInputElement('loginpwd', 'form-field', '', '');
		var emptylabel = createDivElement('', 'form-label', '');
		var sub = createSubmitInputElement('logindo', 'button', '', 'Login');
		var err = createDivElement('login-error', '', '');
		var reglink = createLink('register.aspx', 'Click here to register');
		var fglink = createLink('javascript:void(0);', 'Forgotten your password?');
	
	// setup
		fglink.onclick = function()
		{
			if (uid.value == '')
			{
				err.innerHTML = 'Enter your e-mail address and try again, we will e-mail you a new password';
				return;
			}
			
			forgotPassword(uid.value);
		}
	
		sub.onclick = function()
		{
			if (uid.value == '')
			{
				err.innerHTML = 'You must enter a username';
				return;
			}
			else
			{
				err.innerHTML = '';
			}
			if (pwd.value == '')
			{
				err.innerHTML = 'You must enter a password';
				return;
			}
			else
			{
				err.innerHTML = '';
			}
	
			err.innerHTML = 'Logging in';
			sub.enabled = false;
		
			var params = new Array();
			params[0] = uid.value;
			params[1] = pwd.value;
			_username = uid.value;
			var rpc = new RPC('login', params, loginComplete);
		}
			
	// layout
		container.appendChild(uidlabel);
		container.appendChild(uid);
		container.appendChild(pwdlabel);
		container.appendChild(pwd);
		container.appendChild(err);
		container.appendChild(emptylabel);
		container.appendChild(sub);
		container.appendChild(clre);
		container.appendChild(reglink);
		container.appendChild(createHTMLElement('<br/>'));
		container.appendChild(fglink);
		container.appendChild(createHTMLElement('<br/><br/>'));
	}
	else
	{
		var menu = createDivElement('', 'user-menu', '');
		var d1 = createDivElement('', 'user-menu-item', '');
		var d2 = createDivElement('', 'user-menu-item', '');
		var d3 = createDivElement('', 'user-menu-item', '');
		var certslink = createLink('http://www.benchmarx.com/ca/certificates.aspx', 'Access your certificates');
		var reqlink = createLink('http://www.benchmarx.com/ca/request.aspx', 'Request new certificate');
		var logout = createLink('javascript:void(0);', 'Logout');
		
		logout.onclick = function()
		{
			var rpc = new RPC('logout', null, logoutComplete);
		}

		container.appendChild(menu);
		menu.appendChild(d1);
		d1.appendChild(certslink);
		menu.appendChild(d2);
		d2.appendChild(reqlink);
		menu.appendChild(d3);
		d3.appendChild(logout);
	}
}

function forgotPassword()
{
	var rpc = new RPC('forgotPassword', arguments, forgotPasswordComplete);
}
function forgotPasswordComplete(xml)
{
	var doc = xml.documentElement;
	if (doc.nodeName == 'success')
	{
		e('error').innerHTML = 'Your password has been e-mailed to you.';
	}
	else
	{
		e('error').innerHTML = doc.childNodes[0].childNodes[0].nodeValue;
	}		
}

function setupRegisterPanel()
{
	var container = e('regpanel');
	if (container == null) return;

	if (_uc == '')
	{
	// create
		
		var namelabel = createDivElement('namelabel', 'form-label', 'Full Name: ');
		var emaillabel = createDivElement('uidlabel', 'form-label', 'E-mail: ');
		var pwdlabel = createDivElement('pwdlabel', 'form-label', 'Password: ');
		var cn = createTextInputElement('cn', 'form-field', '', '');
		var email = createTextInputElement('email', 'form-field', '', '');	
		var pwd = createPasswordInputElement('pass', 'form-field', '', '');
		var emptylabel = createDivElement('', 'form-label', '');
		var reg = createSubmitInputElement('register', 'button', '', 'Register');
		var err = createDivElement('reg-error', '', '');
	
	// setup
		reg.onclick = function()
		{
			err.innerHTML = '';
			
			if (cn.value == '')
			{
				err.innerHTML = 'You must enter your full name';
				return;
			}
			
			if (email.value == '')
			{
				err.innerHTML = 'You must enter a username';
				return;
			}
	
			if (pwd.value == '')
			{
				err.innerHTML = 'You must enter a password';
				return;
			}
	
			err.innerHTML = 'Registering...';
			reg.enabled = false;
		
			register(cn.value, email.value, pwd.value);
		}
			
	// layout
		container.appendChild(namelabel);
		container.appendChild(cn);
		container.appendChild(clre);
		container.appendChild(emaillabel);
		container.appendChild(email);
		container.appendChild(pwdlabel);
		container.appendChild(pwd);
		container.appendChild(err);
		container.appendChild(emptylabel);
		container.appendChild(reg);
		container.appendChild(clre);
	}
	else
	{
		e('main').appendChild(createHTMLElement('You are already logged in, you do not need to register. If you wish to register an alternative e-mail address please request a new certificate or logout and register.'));
	}
}

function register()
{
	var rpc = new RPC('register', arguments, registerComplete);
}
function registerComplete(xml)
{
	var doc = xml.documentElement;
	if (doc.nodeName == 'success')
	{
		if (e('regpanel') != null)
		{
			clearElement(e('regpanel'));
			e('regpanel').appendChild(createHTMLElement('Your registration has been successfully accepted. A personal e-mail certificate has been created with your details and will be available for collection.'));
//            e('regpanel').appendChild(createHTMLElement('<pre>' + doc.childNodes[0].nodeValue + '</pre>'));
		}
	}
	else
	{
		e('reg-error').innerHTML = doc.childNodes[0].childNodes[0].nodeValue;
	}
}

function logoutComplete()
{
	_uc = '';
	clearElement(e('loginpanel'));
	setupLoginPanel();
	window.location.href = 'http://www.benchmarx.com/ca';
}

function setupCertPanel()
{
	// get list of certificates for this user
	getCertificates();
}

function getCertificates()
{
	var rpc = new RPC('getCertificates', null, getCertificatesComplete);
}

function getCertificatesComplete(xml)
{
	var dp = e('certpanel');
	
	var container = createDivElement('', 'certcontainer', '');
	var publabel = createDivElement('', '', '<p>Copy this URL to anybody you want to have access to this certificate:</p>');
	var puburl = createDivElement('', 'boxed', '');
	
	publabel.style.visibility = 'hidden';
	
	var doc = xml.documentElement;
	if (doc.nodeName == 'success')
	{
		for (var i = 0; i < doc.childNodes.length; i++)
		{
			var certNode = doc.childNodes[i];
			var cidNode = certNode.childNodes[0];
			var cnNode = certNode.childNodes[1];
			var typeNode = certNode.childNodes[2];

			var className = 'certentry';
			if (i % 2 == 0) className = 'certentry-alt';
			var cert = createDivElement('', className, '');
			cert.cid = cidNode.childNodes[0].nodeValue;
			cert.onclick = function()
			{
				publabel.style.visibility = '';
				puburl.innerHTML = '<pre>http://www.benchmarx.com/ca/getCert.aspx?cid=' + this.cid + '</pre>';
				puburl.style.display = 'block';
			}
			
			var cn = createDivElement('', 'cert-name', cnNode.childNodes[0].nodeValue);
			cert.appendChild(cn);
			
			var privlink = createLink('http://www.benchmarx.com/ca/getP12.aspx?cid=' + cidNode.childNodes[0].nodeValue, '<img src="images/private.jpg" width="20" height="20" alt="Click here to download your private key" title="Click here to download your private key" />'); 
			cert.appendChild(privlink);

			var publink = createLink('http://www.benchmarx.com/ca/getCert.aspx?cid=' + cidNode.childNodes[0].nodeValue, '<img src="images/public.jpg" width="20" height="20" alt="Click here to download your public key" title="Click here to download your public key" />'); 
			cert.appendChild(publink);
			
			container.appendChild(cert);
		}
		
		puburl.style.display = 'none';
	
		dp.appendChild(container);
		dp.appendChild(publabel);
		dp.appendChild(puburl);
	}
	else
	{
		var reasonNode = doc.childNodes[0];
		clearElement(dp);
		dp.innerHTML = reasonNode.childNodes[0].nodeValue;
	}
}

function setupRequestPanel()
{
	var main = e('reqpanel');
	
	var reqform = createDivElement('reqform', '', '');
	var typelabel = createDivElement('typelabel', 'form-label', 'Certificate type: ');
	var type = createSelectInputElement('cert-type', 'form-field', '', 'user');
	var details = createDivElement('reqdetails', '', '');

	type.options[0] = new Option('Choose type', '');
	type.options[1] = new Option('Personal', 'user');
	type.options[2] = new Option('Server', 'server');	
	type.onchange = function() 
	{
		if (this.options[this.selectedIndex].value == 'user')
		{
			clearElement(e('reqdetails'));
			
			var main = e('reqdetails');
			
			var namelabel = createDivElement('namelabel', 'form-label', 'Full name: ');
			var cn = createTextInputElement('cn', 'form-field', '', '');
			var emaillabel = createDivElement('emaillabel', 'form-label', 'E-mail address: ');
			var email = createTextInputElement('email', 'form-field', '', '');
			var pwdlabel = createDivElement('pwdlabel', 'form-label', 'Password: ');
			var pwd = createPasswordInputElement('pwd', 'form-field', '', '');
			var err = createDivElement('error', 'form-error', '');
			var sub = createSubmitInputElement('', 'button', '', 'Submit');
			sub.onclick = function()
			{
				if (cn.value == '')
				{
					err.innerHTML = 'You must enter a full name for this certificate.';
				}
				
				request(type.options[type.selectedIndex].value, cn.value, email.value, email.value, pwd.value);
			}
			
			main.appendChild(namelabel);
			main.appendChild(cn);
			main.appendChild(emaillabel);
			main.appendChild(email);
			main.appendChild(pwdlabel);
			main.appendChild(pwd);
			main.appendChild(err);
			main.appendChild(sub);
		}
		else if (this.options[this.selectedIndex].value == 'server')
		{
			clearElement(e('reqdetails'));
			
			var main = e('reqdetails');
			
			var cnlabel = createDivElement('cnlabel', 'form-label', 'Server name: ');
			var cn = createTextInputElement('cn', 'form-field', '', '');
			var vallabel = createDivElement('vallabel', 'form-label', 'Validation address: ');
			var val = createTextInputElement('val', 'form-field', '', '');
			var pwdlabel = createDivElement('pwdlabel', 'form-label', 'Password: ');
			var pwd = createPasswordInputElement('pwd', 'form-field', '', '');
			var err = createDivElement('error', 'form-error', '');
			var sub = createSubmitInputElement('', 'button', '', 'Submit');
			sub.onclick = function()
			{
				if (cn.value == '')
				{
					err.innerHTML = 'You must enter a full name for this certificate.';
				}
				
				request(type.options[type.selectedIndex].value, cn.value, val.value, val.value, pwd.value);
			}
			
			main.appendChild(cnlabel);
			main.appendChild(cn);
			main.appendChild(vallabel);
			main.appendChild(val);
			main.appendChild(pwdlabel);
			main.appendChild(pwd);
			main.appendChild(err);
			main.appendChild(sub);
		}
	}

	reqform.appendChild(typelabel);
	reqform.appendChild(type);
	reqform.appendChild(details);
	
	main.appendChild(reqform);
}

function request()
{
	var rpc = new RPC('request', arguments, requestComplete);
}
function requestComplete(xml, text)
{
	clearElement(e('reqpanel'));
	var c = e('reqpanel');
	
	c.appendChild(createHTMLElement('Your request has been accepted. You will shortly receive an e-mail with details on how to validate your certificate.'));
}

// on starting the application we create the homepage, which is simply login or register
function start()
{
	// check cookie to see if we're logged in, if we are the server knows who we are
	_uc = getCookie('session');

	// setup login panel either way, it will check if we're logged in
	if (e('loginpanel') != null)
	{
		setupLoginPanel();
	}
	
	if (e('regpanel') != null)
	{
		setupRegisterPanel();
	}
	
	if (_uc == '')
	{
	}
	else
	{
		if (e('certpanel') != null)
		{
			setupCertPanel();
		}
		
		if (e('reqpanel') != null)
		{
			setupRequestPanel();
		}
	}
}

start();
