// HGUS-DebateBubbleHover.js - Handles Cluster Bubbles on the Debate Tab
// HotGrinds Canada Inc. - February 2008

function getDebateBubbleCoordinates(elementID)
{
	var parentHeight = 0;
	var parentWidth = 0;
	var parentScrollTop = 0;
	if (elementID.className == "dynamicTHover") {
		var lis = elementID.getElementsByTagName("span");
		for (var j = 0; j < lis.length; j++) {
			var li = lis[j];
			if (li.className == "tooltip") {
				foundDebateBubble = true;
				objLeft = elementID.offsetLeft;
				objTop = elementID.offsetTop;
				objParent = elementID.offsetParent;
				var style;
				if(objParent.currentStyle)
					style = objParent.currentStyle;
				else
					style = window.getComputedStyle(objParent,null);
				parentHeight = style.height;
				parentHeightVal = parseInt(parentHeight.substr(0,parentHeight.length-2));
				parentWidth = style.width;
				parentWidthVal = parseInt(parentWidth.substr(0,parentWidth.length-2));
				parentScrollTop = objParent.scrollTop;
				parentScrollHeight = objParent.scrollHeight;				
				if (objLeft<(parentWidthVal-300)) {
					li.style.left = "0px";
				} else if (((objLeft>(parentWidthVal-300))) && ((parentWidthVal-objLeft)<((parentWidthVal-300)/2))){
					li.style.left = "-280px";
				} else {
					li.style.left = (((parentWidthVal-300)/2)-objLeft)+"px";
				}
				if (objTop == 0) {
					li.style.top = "-15px";
				} else {
					li.style.top = (parentScrollTop-objTop-15)+"px";
				}
			}
		}
	}		  		
}

function getArgumentBubbleCoordinates(elementID)
{
	var parentHeight = 0;
	var parentWidth = 0;
	var parentScrollTop = 0;
	if (elementID.className == "dynamicAHover") {
		var lis = elementID.getElementsByTagName("span");
		for (var j = 0; j < lis.length; j++) {
			var li = lis[j];
			if (li.className == "tooltip") {
				foundDebateBubble = true;
				objLeft = elementID.offsetLeft;
				objTop = elementID.offsetTop;
				obj1Parent = elementID.offsetParent;
				obj2Parent = obj1Parent.offsetParent;
				obj3Parent = obj2Parent.offsetParent;
				var obj3Style;
				if (obj3Parent.currentStyle)
					obj3Style = obj3Parent.currentStyle;
				else
					obj3Style = window.getComputedStyle(obj3Parent,null);
				
				var obj1Style;
				if (obj1Parent.currentStyle)
					obj1Style = obj1Parent.currentStyle
				else
					obj1Style = window.getComputedStyle(obj1Parent,null);
				parentHeight = obj3Style.height;
				parentHeightVal = parseInt(parentHeight.substr(0,parentHeight.length-2));
				parentWidth = obj1Style.width;
				parentWidthVal = parseInt(parentWidth.substr(0,parentWidth.length-2));
				parentScrollTop = obj3Parent.scrollTop;
				parentScrollHeight = obj3Parent.scrollHeight;				
				if (objLeft<(parentWidthVal-300)) {
					li.style.left = "0px";
				} else if (((objLeft>(parentWidthVal-300))) && ((parentWidthVal-objLeft)<((parentWidthVal-300)/2))){
					li.style.left = "-280px";
				} else {
					li.style.left = (((parentWidthVal-300)/2)-objLeft)+"px";
				}
				if (objTop == 0) {
					li.style.top = "-15px";
				} else if ((parentScrollTop-objTop)<-175) {
					li.style.top = "-190px";
				} else if ((parentScrollTop-objTop)>175) {
					li.style.top = "-15px";
				} else {
					li.style.top = (parentScrollTop-objTop-15)+"px";
				}
			}
		}
	}		  		
}
// HGUS-ListToTree.js - Handles The Collapsible Facet Trees for Search Results
// HotGrinds Canada Inc. - February 2008

// Automatically attach a listener to the window onload, to convert the trees
addEvent(window,"load",convertTrees);

// Utility function to add an event listener
function addEvent(o,e,f){
	if (o.addEventListener){ o.addEventListener(e,f,true); return true; }
	else if (o.attachEvent){ return o.attachEvent("on"+e,f); }
	else { return false; }
}

// utility function to set a global variable if it is not already set
function setDefault(name,val) {
	if (typeof(window[name])=="undefined" || window[name]==null) {
		window[name]=val;
	}
}

// Fully expands a tree with a given ID
function expandTree(treeId) {
	var ul = document.getElementById(treeId);
	if (ul == null) { return false; }
	expandCollapseList(ul,nodeOpenClass);
}

// Fully collapses a tree with a given ID
function collapseTree(treeId) {
	var ul = document.getElementById(treeId);
	if (ul == null) { return false; }
	expandCollapseList(ul,nodeClosedClass);
}

// Expands enough nodes to expose an LI with a given ID
function expandToItem(treeId,itemId) {
	var ul = document.getElementById(treeId);
	if (ul == null) { return false; }
	var ret = expandCollapseList(ul,nodeOpenClass,itemId);
	if (ret) {
		var o = document.getElementById(itemId);
		if (o.scrollIntoView) {
			o.scrollIntoView(false);
		}
	}
}

// Performs 3 functions:
// a) Expand all nodes
// b) Collapse all nodes
// c) Expand all nodes to reach a certain ID
function expandCollapseList(ul,cName,itemId) {
	if (!ul.childNodes || ul.childNodes.length==0) { return false; }
	// Iterate LIs
	for (var itemi=0;itemi<ul.childNodes.length;itemi++) {
		var item = ul.childNodes[itemi];
		if (itemId!=null && item.id==itemId) { return true; }
		if (item.nodeName == "LI") {
			// Iterate things in this LI
			var subLists = false;
			for (var sitemi=0;sitemi<item.childNodes.length;sitemi++) {
				var sitem = item.childNodes[sitemi];
				if (sitem.nodeName=="UL") {
					subLists = true;
					var ret = expandCollapseList(sitem,cName,itemId);
					if (itemId!=null && ret) {
						item.className=cName;
						return true;
					}
				}
			}
			if (subLists && itemId==null) {
				item.className = cName;
			}
		}
	}
}

// Search the document for UL elements with the correct CLASS name, then process them
function convertTrees() {
	setDefault("treeClass","HGUS_FacetTree");
	setDefault("treeClassVT","HGUS_VerticalThemeTree");
	setDefault("treeClassCOE","HGUS_ChainOfEvidenceTree");	
	setDefault("nodeClosedClass","liClosed");
	setDefault("nodeOpenClass","liOpen");
	setDefault("nodeBulletClass","liBullet");
	setDefault("nodeLinkClass","bullet");
	setDefault("preProcessTrees",false);
	if (preProcessTrees) {
		if (!document.createElement) { return; } // Without createElement, we can't do anything
		uls = document.getElementsByTagName("ul");
		for (var uli=0;uli<uls.length;uli++) {
			var ul=uls[uli];
			if ((ul.nodeName=="UL" && ul.className==treeClass) || (ul.nodeName=="UL" && ul.className==treeClassVT) ||(ul.nodeName=="UL" && ul.className==treeClassCOE)){
				processList(ul);
			}
		}
	}
}

// Process a UL tag and all its children, to convert to a tree
function processList(ul) {
	if (!ul.childNodes || ul.childNodes.length==0) { return; }
	// Iterate LIs
	for (var itemi=0;itemi<ul.childNodes.length;itemi++) {
		var item = ul.childNodes[itemi];
		if (item.nodeName == "LI") {
			// Iterate things in this LI
			var subLists = false;
			for (var sitemi=0;sitemi<item.childNodes.length;sitemi++) {
				var sitem = item.childNodes[sitemi];
				if (sitem.nodeName=="UL") {
					subLists = true;
					processList(sitem);
				}
			}
			var s= document.createElement("SPAN");
			var t= '\u00A0'; // &nbsp;
			s.className = nodeLinkClass;
			if (subLists) {
				// This LI has UL's in it, so it's a +/- node
				if (item.className==null || item.className=="") {
					item.className = nodeClosedClass;
				}
				// If it's just text, make the text work as the link also
				if (item.firstChild.nodeName=="#text") {
					t = t+item.firstChild.nodeValue;
					item.removeChild(item.firstChild);
				}
				s.onclick = function () {
					this.parentNode.className = (this.parentNode.className==nodeOpenClass) ? nodeClosedClass : nodeOpenClass;
					return false;
				}
			}
			else {
				// No sublists, so it's just a bullet node
				item.className = nodeBulletClass;
				s.onclick = function () { return false; }
			}
			s.appendChild(document.createTextNode(t));
			item.insertBefore(s,item.firstChild);
		}
	}
}// Tigra Calendar v4.0.2 (01/12/2009) American (mm/dd/yyyy)
// http://www.softcomplex.com/products/tigra_calendar/
// Public Domain Software... You're welcome.

// default settins
var A_TCALDEF = {
//	'months' : ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
//	'weekdays' : ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
	'yearscroll': true, // show year scroller
//	'weekstart': 0, // first day of week: 0-Su or 1-Mo
	'centyear'  : 70, // 2 digit years less than 'centyear' are in 20xx, othewise in 19xx.
	//'imgpath' : 'img/' // directory with calendar images
	'imgpath':''
}
// date parsing function
function f_tcalParseDatemdy (s_date) {

	var re_date = /^\s*(\d{1,2})\/(\d{1,2})\/(\d{2,4})\s*$/;

	if (!re_date.exec(s_date))
		return alert ("Invalid date: '" + s_date + "'.\nAccepted format is mm/dd/yyyy.")
	var n_day = Number(RegExp.$2),
		n_month = Number(RegExp.$1),
		n_year = Number(RegExp.$3);
	
	if (n_year < 100)
		n_year += (n_year < this.a_tpl.centyear ? 2000 : 1900);
	if (n_month < 1 || n_month > 12)
		return alert ("Invalid month value: '" + n_month + "'.\nAllowed range is 01-12.");
	var d_numdays = new Date(n_year, n_month, 0);
	if (n_day > d_numdays.getDate())
		return alert("Invalid day of month value: '" + n_day + "'.\nAllowed range for selected month is 01 - " + d_numdays.getDate() + ".");
	/*if (s_date)
	{
		alert(s_date);
		
		var now = new Date();
		var earliest = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59, 999);
		alert(earliest);
		if (testDate.getTime()<= earliest.getTime())
			return alert("Date is too early - tomorrow is the earliest possible date");
			
		alert(testDate);
	}*/ 
	var testDate = new Date (n_year, n_month - 1, n_day);
	return testDate
}
// date generating function
function f_tcalGenerDatemdy (d_date) {
	var retDate = (
			 (d_date.getMonth() < 9 ? '0' : '') + (d_date.getMonth() + 1) + "/"
				+ (d_date.getDate() < 10 ? '0' : '') + d_date.getDate() + "/"
				+ d_date.getFullYear()
			); 
	return retDate;
}

function f_tcalParseDatedmy (s_date) {

	var re_date = /^\s*(\d{1,2})\-(\d{1,2})\-(\d{2,4})\s*$/;
	if (!re_date.exec(s_date))
		return alert ("Invalid date: '" + s_date + "'.\nAccepted format is dd-mm-yyyy.")
	var n_day = Number(RegExp.$1),
		n_month = Number(RegExp.$2),
		n_year = Number(RegExp.$3);

	if (n_year < 100)
		n_year += (n_year < this.a_tpl.centyear ? 2000 : 1900);
	if (n_month < 1 || n_month > 12)
		return alert ("Invalid month value: '" + n_month + "'.\nAllowed range is 01-12.");
	var d_numdays = new Date(n_year, n_month, 0);
	if (n_day > d_numdays.getDate())
		return alert("Invalid day of month value: '" + n_day + "'.\nAllowed range for selected month is 01 - " + d_numdays.getDate() + ".");

	return new Date (n_year, n_month - 1, n_day);
}
// date generating function
function f_tcalGenerDatedmy (d_date) {
	return (
		(d_date.getDate() < 10 ? '0' : '') + d_date.getDate() + "-"
		+ (d_date.getMonth() < 9 ? '0' : '') + (d_date.getMonth() + 1) + "-"
		+ d_date.getFullYear()
	);
}

// implementation
function tcal (a_cfg, a_tpl) {

	// apply default template if not specified
	if (!a_tpl)
	{
		a_tpl = A_TCALDEF;
		a_tpl.months = a_cfg.months;
		a_tpl.weekdays = a_cfg.weekdays;
		a_tpl.weekstart = a_cfg.weekstart;
	}
	// register in global collections
	if (!window.A_TCALS)
		window.A_TCALS = [];
	if (!window.A_TCALSIDX)
		window.A_TCALSIDX = [];
	
	this.s_id = a_cfg.id ? a_cfg.id : A_TCALS.length;
	window.A_TCALS[this.s_id] = this;
	window.A_TCALSIDX[window.A_TCALSIDX.length] = this;
	
	// assign methods
	this.f_show = f_tcalShow;
	this.f_hide = f_tcalHide;
	this.f_toggle = f_tcalToggle;
	this.f_update = f_tcalUpdate;
	this.f_relDate = f_tcalRelDate;
	this.f_parseDate = a_cfg.parsefunc;//f_tcalParseDate;
	this.f_generDate = a_cfg.genfunc;//f_tcalGenerDate;
	
	// create calendar icon
	this.s_iconId = 'tcalico_' + this.s_id;
	this.e_icon = f_getElement(this.s_iconId);
	if (!this.e_icon) {
		document.write('<img src="' + a_tpl.imgpath + 'cal.gif" id="' + this.s_iconId + '" onclick="A_TCALS[\'' + this.s_id + '\'].f_toggle()" class="tcalIcon" alt="Open Calendar" />');
		this.e_icon = f_getElement(this.s_iconId);
	}
	// save received parameters
	this.a_cfg = a_cfg;
	this.a_tpl = a_tpl;
}

function f_tcalShow (d_date) {

	// find input field
	if (!this.a_cfg.controlname)
		throw("TC: control name is not specified");
	if (this.a_cfg.formname) {
		var e_form = document.forms[this.a_cfg.formname];
		if (!e_form)
			throw("TC: form '" + this.a_cfg.formname + "' can not be found");
		this.e_input = e_form.elements[this.a_cfg.controlname];
	}
	else
		this.e_input = f_getElement(this.a_cfg.controlname);

	this.e_hiddenvalue = f_getElement(this.a_cfg.hiddenname);
	if (!this.e_input || !this.e_input.tagName || this.e_input.tagName != 'INPUT')
		throw("TC: element '" + this.a_cfg.controlname + "' does not exist in "
			+ (this.a_cfg.formname ? "form '" + this.a_cfg.controlname + "'" : 'this document'));

	// dynamically create HTML elements if needed
	this.btn_Div = f_getElement(this.a_cfg.divwrapper);//'publishbuttons'
	this.e_div = f_getElement('tcal');
	if (!this.e_div) {
		alert("not finding tcal");
		this.e_div = document.createElement("DIV");
		this.e_div.id = 'tcal';
		document.body.appendChild(this.e_div);
	}
	this.e_shade = f_getElement('tcalShade');
	if (!this.e_shade) {
		this.e_shade = document.createElement("DIV");
		this.e_shade.id = 'tcalShade';
		document.body.appendChild(this.e_shade);
	}
	this.e_iframe =  f_getElement('tcalIF')
	if (b_ieFix && !this.e_iframe) {
		this.e_iframe = document.createElement("IFRAME");
		this.e_iframe.style.filter = 'alpha(opacity=0)';
		this.e_iframe.id = 'tcalIF';
		this.e_iframe.src = this.a_tpl.imgpath + 'pixel.gif';
		document.body.appendChild(this.e_iframe);
	}
	
	// hide all calendars
	f_tcalHideAll();

	// generate HTML and show calendar
	this.e_icon = f_getElement(this.s_iconId);
	if (!this.f_update())
		return;

	this.e_div.style.visibility = 'visible';
	
	this.btn_Div.style.visibility='hidden';
	this.e_shade.style.visibility = 'visible';
	if (this.e_iframe)
		this.e_iframe.style.visibility = 'visible';

	// change icon and status
	this.e_icon.src = this.a_tpl.imgpath + 'no_cal.gif';
	this.e_icon.title = 'Close Calendar';
	this.b_visible = true;
}

function f_tcalHide (n_date) {
	
	// no action if not visible
	if (!this.b_visible)
		return;

	if (n_date)
	{

		var earliest = this.f_parseDate(this.a_cfg.earliest);
		if (n_date<= earliest.getTime())
			return alert("Date is too early - tomorrow is the earliest possible date");
		if (this.a_cfg.maxdate)
		{
			if (n_date >= this.a_cfg.maxdate)
			return alert("Date is too far forward - max  date is "+this.a_cfg.maxdate);
		}
		this.e_input.value = this.f_generDate(new Date(n_date));

		this.e_hiddenvalue.value = new Date(n_date).getTime();
	}
	// hide elements
	if (this.e_iframe)
		this.e_iframe.style.visibility = 'hidden';
	if (this.e_shade)
		this.e_shade.style.visibility = 'hidden';
	this.e_div.style.visibility = 'hidden';
	this.btn_Div.style.visibility='visible';
	
	// change icon and status
	this.e_icon = f_getElement(this.s_iconId);
	this.e_icon.src = this.a_tpl.imgpath + 'cal.gif';
	this.e_icon.title = 'Open Calendar';
	this.b_visible = false;
}

function f_tcalToggle () {
	return this.b_visible ? this.f_hide() : this.f_show();
}

function f_tcalUpdate (d_date) {
	
	var d_client = new Date();
	d_client.setHours(23);
	d_client.setMinutes(59);
	d_client.setSeconds(59);
	d_client.setMilliseconds(999);
	
	var d_today = this.a_cfg.today ? this.f_parseDate(this.a_cfg.today) : d_client;
	var d_selected = this.e_input.value == ''? (this.a_cfg.selected ? this.f_parseDate(this.a_cfg.selected) : d_today): this.f_parseDate(this.e_input.value);


	// figure out date to display
	if (!d_date)
		// selected by default
		d_date = d_selected;
	else if (typeof(d_date) == 'number')
		// get from number
		d_date = new Date(d_date);
	else if (typeof(d_date) == 'string')
		// parse from string
		this.f_parseDate(d_date);
		
	if (!d_date) return false;

	// first date to display
	var d_firstday = new Date(d_date);
	d_firstday.setDate(1);
	d_firstday.setDate(1 - (7 + d_firstday.getDay() - this.a_tpl.weekstart) % 7);
	
	var a_class, s_html = '<table class="ctrl"><tbody><tr>'
		+ (this.a_tpl.yearscroll ? '<td' + this.f_relDate(d_date, -1, 'y') + ' title="Previous Year"><img src="' + this.a_tpl.imgpath + 'prev_year.gif" /></td>' : '')
		+ '<td' + this.f_relDate(d_date, -1) + ' title="Previous Month"><img src="' + this.a_tpl.imgpath + 'prev_mon.gif" /></td><th>'
		+ this.a_tpl.months[d_date.getMonth()] + ' ' + d_date.getFullYear()
			+ '</th><td' + this.f_relDate(d_date, 1) + ' title="Next Month"><img src="' + this.a_tpl.imgpath + 'next_mon.gif" /></td>'
		+ (this.a_tpl.yearscroll ? '<td' + this.f_relDate(d_date, 1, 'y') + ' title="Next Year"><img src="' + this.a_tpl.imgpath + 'next_year.gif" /></td>' : '')
		+ '</tr></tbody></table><table><tbody><tr class="wd">';

	// print weekdays titles
	for (var i = 0; i < 7; i++)
		s_html += '<th>' + this.a_tpl.weekdays[(this.a_tpl.weekstart + i) % 7] + '</th>';
	s_html += '</tr>' ;

	// print calendar table
	var d_current = new Date(d_firstday);
	while (d_current.getMonth() == d_date.getMonth() ||
		d_current.getMonth() == d_firstday.getMonth()) {
	
		// print row heder
		s_html +='<tr>';
		for (var n_wday = 0; n_wday < 7; n_wday++) {

			a_class = [];
			// other month
			if (d_current.getMonth() != d_date.getMonth())
				a_class[a_class.length] = 'othermonth';
			// weekend
			if (d_current.getDay() == 0 || d_current.getDay() == 6)
				a_class[a_class.length] = 'weekend';
			// today
			if (d_current.valueOf() == d_today.valueOf())
				a_class[a_class.length] = 'today';
			// selected
			if (d_current.valueOf() == d_selected.valueOf())
				a_class[a_class.length] = 'selected';

			s_html += '<td onclick="A_TCALS[\'' + this.s_id + '\'].f_hide(' + d_current.valueOf() + ')"' + (a_class.length ? ' class="' + a_class.join(' ') + '">' : '>') + d_current.getDate() + '</td>'
			d_current.setDate(d_current.getDate() + 1);
		}
		// print row footer
		s_html +='</tr>';
	}
	s_html +='</tbody></table>';
	
	// update HTML, positions and sizes
	this.e_div.innerHTML = s_html;
	//alert(this.e_div.innerHTML);
	if (!this.n_width)
		this.n_width= this.e_div.offsetWidth;
	if (!this.n_height)
		this.n_height= this.e_div.offsetHeight;
	//var n_top  = f_getPosition (this.e_icon, 'Top') + this.e_icon.offsetHeight;
	if (!this.n_top)
		this.n_top = f_getPosition(this.e_div,'Top');
	//var n_left = f_getPosition (this.e_icon, 'Left') - n_width + this.e_icon.offsetWidth;
	if (!this.n_left)
		this.n_left = f_getPosition(this.e_div,'Left');
	var n_width = this.n_width;
	var n_height = this.n_height;
	var n_left = this.n_left;
	var n_top = this.n_top;
	if (n_left < 0) n_left = 0;
	//alert("working with width:"+n_width+" height:"+n_height+" top:"+n_top+" left:"+n_left);
	//this.e_div.style.left = n_left + 'px';
	//this.e_div.style.top  = n_top + 'px';
	this.e_shade.style.width = (n_width + 8) + 'px';
	//this.e_shade.style.left = (n_left - 1) + 'px';
	//this.e_shade.style.top = (n_top - 1) + 'px';
	this.e_shade.innerHTML = b_ieFix
		? '<table><tbody><tr><td rowspan="2" colspan="2" width="6"><img src="' + this.a_tpl.imgpath + 'pixel.gif"></td><td width="7" height="7" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + this.a_tpl.imgpath + 'shade_tr.png\', sizingMethod=\'scale\');"><img src="' + this.a_tpl.imgpath + 'pixel.gif"></td></tr><tr><td height="' + (n_height - 7) + '" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + this.a_tpl.imgpath + 'shade_mr.png\', sizingMethod=\'scale\');"><img src="' + this.a_tpl.imgpath + 'pixel.gif"></td></tr><tr><td width="7" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + this.a_tpl.imgpath + 'shade_bl.png\', sizingMethod=\'scale\');"><img src="' + this.a_tpl.imgpath + 'pixel.gif"></td><td style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + this.a_tpl.imgpath + 'shade_bm.png\', sizingMethod=\'scale\');" height="7" align="left"><img src="' + this.a_tpl.imgpath + 'pixel.gif"></td><td style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + this.a_tpl.imgpath + 'shade_br.png\', sizingMethod=\'scale\');"><img src="' + this.a_tpl.imgpath + 'pixel.gif"></td></tr><tbody></table>'
		: '<table><tbody><tr><td rowspan="2" width="6"><img src="' + this.a_tpl.imgpath + 'pixel.gif"></td><td rowspan="2"><img src="' + this.a_tpl.imgpath + 'pixel.gif"></td><td width="7" height="7"><img src="' + this.a_tpl.imgpath + 'shade_tr.png"></td></tr><tr><td background="' + this.a_tpl.imgpath + 'shade_mr.png" height="' + (n_height - 7) + '"><img src="' + this.a_tpl.imgpath + 'pixel.gif"></td></tr><tr><td><img src="' + this.a_tpl.imgpath + 'shade_bl.png"></td><td background="' + this.a_tpl.imgpath + 'shade_bm.png" height="7" align="left"><img src="' + this.a_tpl.imgpath + 'pixel.gif"></td><td><img src="' + this.a_tpl.imgpath + 'shade_br.png"></td></tr><tbody></table>';
	
	if (this.e_iframe) {
		this.e_iframe.style.left = n_left + 'px';
		this.e_iframe.style.top  = n_top + 'px';
		this.e_iframe.style.width = (n_width + 6) + 'px';
		this.e_iframe.style.height = (n_height + 6) +'px';
		
	}

	return true;
}

function f_getPosition (e_elemRef, s_coord) {
	var n_pos = 0, n_offset,
		e_elem = e_elemRef;

	while (e_elem) {
		n_offset = e_elem["offset" + s_coord];
		n_pos += n_offset;
		e_elem = e_elem.offsetParent;
	}
	// margin correction in some browsers
	if (b_ieMac)
		n_pos += parseInt(document.body[s_coord.toLowerCase() + 'Margin']);
	else if (b_safari)
		n_pos -= n_offset;
	
	e_elem = e_elemRef;
	while (e_elem != document.body) {
		n_offset = e_elem["scroll" + s_coord];
		if (n_offset && e_elem.style.overflow == 'scroll')
			n_pos -= n_offset;
		e_elem = e_elem.parentNode;
	}
	return n_pos;
}

function f_tcalRelDate (d_date, d_diff, s_units) {
	var s_units = (s_units == 'y' ? 'FullYear' : 'Month');
	var d_result = new Date(d_date);
	d_result['set' + s_units](d_date['get' + s_units]() + d_diff);
	if (d_result.getDate() != d_date.getDate())
		d_result.setDate(0);
	return ' onclick="A_TCALS[\'' + this.s_id + '\'].f_update(' + d_result.valueOf() + ')"';
}

function f_tcalHideAll () {
	for (var i = 0; i < window.A_TCALSIDX.length; i++)
		window.A_TCALSIDX[i].f_hide();
}	

f_getElement = document.all ?
	function (s_id) { return document.all[s_id] } :
	function (s_id) { return document.getElementById(s_id) };

/*if (document.addEventListener)
	window.addEventListener('scroll', f_tcalHideAll, false);
if (window.attachEvent)
	window.attachEvent('onscroll', f_tcalHideAll);
*/	
// global variables
var s_userAgent = navigator.userAgent.toLowerCase(),
	re_webkit = /WebKit\/(\d+)/i;
var b_mac = s_userAgent.indexOf('mac') != -1,
	b_ie5 = s_userAgent.indexOf('msie 5') != -1,
	b_ie6 = s_userAgent.indexOf('msie 6') != -1 && s_userAgent.indexOf('opera') == -1;
var b_ieFix = b_ie5 || b_ie6,
	b_ieMac  = b_mac && b_ie5,
	b_safari = b_mac && re_webkit.exec(s_userAgent) && Number(RegExp.$1) < 500;
var enctype="application/x-www-form-urlencoded";
var maxTables = 1;

function reappear(chkitem, rowid,tablenum){

	var chk = document.getElementById(chkitem);
	if (chk != undefined) 
	{
		chk.checked = false;
		var item = document.getElementById(chkitem + "-td");
		item.setAttribute("background","button_over.png");
	}
	//table.style.display =newDisplay;
	
	removerowSpecial(rowid,tablenum);
}

function removerow(rowid,tablenum)
{
	var table = document.getElementById("gatheredEvidence"+tablenum);
	table.deleteRow(rowid);
}

function setVerticalSearchScope()
{
	var sel = document.getElementById("NewsSearchScope_2")
	sel.checked="checked";
}

var captchaCounter = 1;
function getCaptcha(side)
{
	var id = "captcha";
	if (side !="")
		id = "captcha-"+side
	captchaCounter ++;
	var imgNew = new Image();
	imgNew.src ="/dbmgmt/register/image?"+captchaCounter; 
	var img = document.getElementById(id);
	img.src ="/dbmgmt/register/image?"+captchaCounter; 
}

function validateFeedback(nocontent, choosetype, enterfeedback)
{
	var chosen =document.HGUSSubmitReport.TypeofProblem.value;
	var content = document.HGUSSubmitReport.HGUS_UserReport.value;
	var response='';
	if (chosen == 'notchosen')
		response+= choosetype;
	if (content == '' || content == nocontent)
	response += enterfeedback;
	if (response != '')
	alert(response);
	if (response != '') 
		return false;
	else {
		document.HGUSSubmitReport.submit();
		//window.close();
	}
}
function validateReport(enteredcontent, choosetype, enterreport)
{
	var chosen =document.HGUSSubmitReport.TypeofProblem.value;
	var content = document.HGUSSubmitReport.HGUS_UserReport.value;
	var response='';
	if (chosen == 'notchosen')
		response += choosetype;
	if (content == '' || content == enteredcontent)
		response += enterreport;
	if (response != '')
		alert(response);
	if (response != '') 
		return false;
	else {
		document.HGUSSubmitReport.submit();
	//	window.close();
	}
	
}
function commentFocus(commentnum, initialString)
{
	var cmt = document.getElementById('comment'+commentnum);
	cmt.style.color='#626262';
	if(cmt.value == initialString)
	{
		cmt.value=''; 
	}
	currentTable=commentnum
	var img;
	for (var i=0; i < lastdest; i++)
	{
		if (commentnum == i)
		{
			img = document.getElementById('dest'+i+'-0');
			img.setAttribute("background","argumentToplong_on.png");
			img = document.getElementById('dest'+i+"-1");
			img.setAttribute("background","argumentbg_on.png");
			img = document.getElementById('dest'+i+"-2");
			img.setAttribute("background","argumentbottom_on.png");
		}
		else
		{
			img = document.getElementById('dest'+i+"-0");
			img.setAttribute("background","argumentToplong.png");
			img = document.getElementById('dest'+i+"-1");
			img.setAttribute("background","argumentbg.png");
			img = document.getElementById('dest'+i+"-2");
			img.setAttribute("background","argumentbottom.png");	
		}
	}
	
	/*var img = document.getElementById('dest'+commentnum+'-0');
	img.setAttribute("background","argumentToplong_on.png");
	img = document.getElementById('dest'+commentnum+"-1");
	img.setAttribute("background","argumentbg_on.png");
	img = document.getElementById('dest'+commentnum+"-2");
	img.setAttribute("background","argumentbottom_on.png");
	
	var other;
	if (commentnum == '1') {
		other = '0';
	}
	else {
		other = '1';
	}
	img = document.getElementById('dest'+other+"-0");
	img.setAttribute("background","argumentToplong.png");
	img = document.getElementById('dest'+other+"-1");
	img.setAttribute("background","argumentbg.png");
	img = document.getElementById('dest'+other+"-2");
	img.setAttribute("background","argumentbottom.png");*/
	return false;
}



function removerowSpecial(info,tablenum)
{
	var table = document.getElementById("gatheredEvidence"+tablenum);
		var rows = table.rows;
		for (i = 0, j = rows.length; i < j; i++)
		{
			if (rows[i].id == info)
			{
				table.deleteRow(i);
				break;
			}
		}
}

function validateUrl(toVal)
{
	if (toVal.substring(0,4).toLowerCase()!='http')
	return false;
	else
	return true;
}

function processResultSelect(title,url, objId, tablenum)
{
	var item = document.getElementById(objId);
	if (item.checked)
	{
		addChecked(title,url,objId,tablenum);
		var otheritem = document.getElementById(objId+"-td");
		otheritem.setAttribute("background","button_selected.png");
	}
	else
	{
		var otheritem = document.getElementById(objId+"-td");
		otheritem.setAttribute("background","button_over.png");
		for (t = 0; t < lastdest; t++) 
		{
			var table = document.getElementById("gatheredEvidence"+t);
			var rows = table.rows;
			for (i = 0, j = rows.length; i < j; i++) {
				if (rows[i].id == objId + "-row") {
					table.deleteRow(i);
					break;
				}
			}
		}
	}
}

function standardizeUrl(url)
{
	var retString = url.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); // sourced from http://blog.stevenlevithan.com/archives/faster-trim-javascript
	if ((retString.substring(0,4).toLowerCase())!='http')
		retString = "http://"+retString;
		
	retString = retString.replace(/ /g,"%20");
	return retString;
	
}
function addFrom(inpId,tablenum, blankurl)
{
	var input = document.getElementById(inpId);
	if (input.value=='' || input.value==blankurl)
		return;
		
	var newurl= standardizeUrl(input.value);
	input.value='';
	addChecked(newurl,newurl,newurl,tablenum);
}

function clearAllEvidence()
{
	var elem = document.getElementById("comment0")
	elem.value='';
	elem = document.getElementById("comment1");
	elem.value='';
	var table;
	var rowcount;
	for (tablenum = 0; tablenum < 2; tablenum++) {
		table = document.getElementById("gatheredEvidence" + tablenum);
		rowcount = table.rows.length -1;
		for (i =0; i < rowcount; i++)
		{
			table.deleteRow(0);
		}
	}
	return false;
}

var lastchosen='';
function showBio(member)
{
	var elem = document.getElementById("alltop");
	var newstyle = elem.style.display;
	elem.style.display="none";
	elem = document.getElementById("singletop");
	elem.style.display=newstyle;
	elem = document.getElementById("allpics");
	elem.style.display="none";
	elem = document.getElementById(member);
	elem.style.display=newstyle;
	lastchosen = member;
	return false;
}

function showAll()
{
	var elem = document.getElementById(lastchosen);
	var newstyle = elem.style.display;
	elem.style.display="none";
	elem = document.getElementById("alltop");
	elem.style.display=newstyle;
	elem = document.getElementById("singletop");
	elem.style.display="none";
	elem =document.getElementById("allpics");
	elem.style.display=newstyle;
	lastchose='';
}
function addChecked(title, url, reappearcode,tablenum,isurl)
{
	if (isurl == null)
		isurl = true;
	var table = document.getElementById("gatheredEvidence"+tablenum);
	var nxtRow = table.insertRow(table.rows.length-3);
	nxtRow = table.insertRow(table.rows.length-3);
	nxtRow.id = reappearcode+"-row";

	
	var rowid = nxtRow.rowIndex;
	var cell = nxtRow.insertCell(-1);
	cell.setAttribute("valign","top");
	
	
	var innerTable = document.createElement("table");
	cell.appendChild(innerTable);
	innerTable.setAttribute("cellPadding","0");
	innerTable.setAttribute("cellSpacing","0");
	nxtRow = innerTable.insertRow(-1);
	cell = nxtRow.insertCell(-1);
	cell.setAttribute("width","14px");
	cell.setAttribute("height","14px");
	if (navigator['appName']!='Microsoft Internet Explorer')// weird shit IE already puts this in which is why I need to add it elsewhere, don't know how to get IE to not put it in.
	{
		cell.style.cssText="padding-left:3px; padding-top:3px; padding-bottom:3px;";
	}
	var img = document.createElement("img");
	img.setAttribute("src","CloseTab_off_x_89.png");
	img.onmouseover=new Function("this.src='CloseTab_over_x_89.png'");
	img.onmouseout=new Function("this.src='CloseTab_off_x_89.png'");
	img.setAttribute("height", "12px");
	img.setAttribute("width","14px");
	
	var tmp = reappearcode;
	tmp = tmp.replace("'","\\\'");
	img.onclick=new Function("reappear('"+tmp+"','"+tmp+"-row',"+tablenum+")");
	cell.appendChild(img);
	cell = nxtRow.insertCell(-1);
	cell.setAttribute("height","14px");
	if (navigator['appName']!='Microsoft Internet Explorer')// weird shit IE already puts this in which is why I need to add it elsewhere, don't know how to get IE to not put it in.
	{
		cell.style.cssText="padding-left:3px;";
	}
	if (isurl)
	{
		var anchor = document.createElement("a");
		anchor.style.cssText="color:#009900; padding-left:5px;";
		anchor.setAttribute("href",url);
		anchor.setAttribute("title",title);
		anchor.setAttribute("target","_blank");
		anchor.innerHTML = shorten(title,70);
		cell.appendChild(anchor);
	}
	else
	{
		var lbl = document.createElement("label");
		lbl.style.cssText="color:#009900; padding-left:5px;";
		lbl.innerHTML = shorten(title,70);
		cell.appendChild(lbl);
	}
	
	var inp = document.getElementById("manuallyAdded"+tablenum);
	inp.onchange=new Function("savePost('manuallyAdded"+tablenum+"','"+tablenum+"-saveddocid-"+((table.rows.length-4)/2)+"');");
	
	
	/*nxtRow = innerTable.insertRow(-1);
	cell = nxtRow.insertCell(-1);
	cell.setAttribute("width","7px");
	cell.setAttribute("height","14px");
	cell = nxtRow.insertCell(-1);
	cell.setAttribute("height","14px");
	var p = document.createElement("p");
	p.style.cssText = "color:#CC9900; padding-left:5px;";
	p.innerHTML = shorten(url,75);
	p.setAttribute("title",url);
	cell.appendChild(p);*/
}

	
	function shorten(inString, maxlen)
	{
		if (inString.length > maxlen)
			return (inString.substring(0,maxlen-3)+'...');
		else
			return inString;
	}


	function newWin(element)
	{
		win= window.open('','_blank');

		var results =element.innerHTML;
		var match = "<";

		var re = new RegExp("<", "g");

		var newresults = results.replace(re, "&lt;");

		win.document.write(newresults );
	}



	function viewFilteredProfile(filter, timefilter, userid)
	{
		var form = document.createElement("form");
		form.name="filterprofile";
		form.method="post";
		form.enctype=enctype;
		form.action="/dbmgmt/debate/myprofile"; 
		form.acceptCharset="UTF-8";
		if (filter)
			form.appendChild(getinput("filter", filter));
		if (timefilter)
			form.appendChild(getinput("timefilter", timefilter));
		if (userid) {
			form.appendChild(getinput("userid", userid));
		}
		document.body.appendChild(form);
		form.submit();
		return false;
	}
	
	
	function setBlock(action, victim)
	{
		var form = document.createElement("form");
		form.name="blockset";
		form.method="post";
		form.action="/dbmgmt/action/setblock"
		form.enctype=enctype;
		form.acceptCharset="UTF-8";
		form.appendChild(getinput("victim", victim));
		form.appendChild(getinput("action",action));
		document.body.appendChild(form);
		form.submit();
		return false;	
	}
	
	function Save()
	{
		var form = document.createElement("form");
		form.name="save thing";
		form.method="post";
		form.enctype=enctype;
		form.action="/dbmgmt/action/SaveArticle"; 
		form.acceptCharset="UTF-8";
		form.appendChild(getinput("savetype","draft"))
		form.appendChild(getinput("addedSaves",addSelectedToForm(form)));
		document.body.appendChild(form);
		form.submit();
	}
	function Publish(firstpoint, secondpoint, initialtitle, initialtext, titlemessage,textmessage, noTheme, blankurl, closetext,missingdate)// ,privatedebate)
	{
		if (!checkFormStuff(firstpoint, secondpoint, initialtitle, initialtext, titlemessage,textmessage, noTheme))
			return false;
		else if (document.getElementById("autoclose").checked)
		{
			var cont = confirm(closetext);
			if (!cont)
				return false;
				
			if (document.getElementById("displaydate").value=='')
			{
				alert(missingdate);
				return false;
			} 
		}
		else
			document.article.counter.vaue = document.article.counter.value + 1;
			
		if (document.article.counter.value > 1)
		{
			return false;
		}
		
	
			
		for (var i =0; i < lastdest; i++)
			addFrom('manuallyAdded'+i,i, blankurl);
		
		var form = document.createElement("form");
		form.name="publish";
		form.method="post";
		//form.enctype=enctype;
		form.enctype="multipart/form-data";
		form.encoding=form.enctype;
		form.action="/dbmgmt/action/SaveArticle"; 
		form.acceptCharset="UTF-8";
		form.appendChild(getinput("savetype","publish"))
		form.appendChild(getinput("addedSaves",addSelectedToForm(form)));
		form.appendChild(getinput("maxtables",lastdest));
		form.appendChild(getinput("autoclose",document.getElementById("autoclose").checked));
		form.appendChild(getinput("closedate",document.getElementById("closedate").value));
		form.appendChild(getinput("debateimage",document.getElementById("file-hidden-0-0").value));
		/*if (document.getElementById("file").value != '')
		{
			form.appendChild(document.getElementById("file"));
			form.appendChild(document.getElementById("imagetitle"));
			
		}*/
		var privatedebate = document.getElementById("private").checked;
		if (privatedebate)
			form.appendChild(getinput('private','true'));
		else
			form.appendChild(getinput('private','false'));
			
		var enrich = document.getElementById("enrich").checked;
		if (enrich)
			form.appendChild(getinput('enrich','true'));
		else
			form.appendChild(getinput('enrich','false'));

		document.body.appendChild(form);		
		/*var dbimg = document.getElementById("file");

		if (dbimg.value !=null)
			form.appendChild(dbimg);*/
		form.submit();
	}
	
	function validateWallPost(formname,blanktitle, blanktext, missingmsg)
	{
		var form = document.getElementById(formname);
		form.counter.value ++;
		if (!validateTitleTextSubmit(formname, blanktitle, blanktext, missingmsg))
			return false;
		if (form.counter.value >1)
			return false;
	}
	function validateTitleTextSubmit(formname,blanktitle, blanktext, missingmsg)
	{
		var form = document.getElementById(formname);
		var title = form.title.value;
		var text = form.posting.value;
		if (text == blanktext )
		{
			text = '';
		}
		if (title == blanktitle)
		{
			title  = '';
		}
		if (text+title== '')
		{
			alert(missingmsg);
			return false;
		}
		
		form.title.value = title;
		form.posting.value = text;	
		return true;
	}
	function checkFormStuff(firstpoint, secondpoint, initialtitle, initialtext, titlemessage, textmessage, noTheme)
	{
		var title = document.article.name.value;
		if (title == initialtitle || title == '')
		{
			alert(titlemessage);
			return false;
		}
		var content = document.article.posttext.value;
		if (content == initialtext || content == '')
		{
			alert (textmessage)
			return false;
		}
		var selTheme = document.getElementById("articletheme");
		if (selTheme) {
			if (selTheme.value == 0) {
				alert(noTheme);
				return false;
			}
		}
		
		var comment = document.getElementById("comment0");
		if (comment.value == firstpoint)
			comment.value = '';
			
		for (var i = 1; i<lastdest; i++)
		{
			comment = document.getElementById("comment"+i);
			if (comment.value == secondpoint)
				comment.value = '';
		}
		return true;
	}
	
	
	function PostArgumentFromWrite(side, debate, theme, firstpoint, secondpoint, initialtitle, initialtext, titlemessage, textmessage, noTheme, blankurl)
	{
		document.article.counter.value = document.article.counter.value + 1;
		if (document.article.counter.value > 1)
		{
			return false;
		}
		if (!checkFormStuff(firstpoint, secondpoint, initialtitle, initialtext, titlemessage, textmessage, noTheme))
			return false;
			for (var i =0; i < lastdest; i++)
			addFrom('manuallyAdded'+i,i, blankurl);
		var dt = new Date();
		var form = document.createElement("form");
		form.name="postargfromwrite"+dt.getTime();
		form.method = "post";
		form.enctype = enctype;
		form.action = "/dbmgmt/action/postdebate"
		form.acceptCharset = "UTF-8";
		form.appendChild(getinput("debateid", debate))
		form.appendChild(getinput("posting", document.article.posttext.value))
		form.appendChild(getinput("title", document.article.name.value))
		form.appendChild(getinput("themeid", theme))
		form.appendChild(getinput("side", side))
		form.appendChild(getinput("addedSaves",addSelectedToForm(form)));
		form.appendChild(getinput("maxtables",lastdest));
		if (respargid!=null)
			form.appendChild(getinput("respargid",respargid));
		document.body.appendChild(form);
		form.submit();
		respargid = null;
	}
	
	
	function WriteArgument(title, text,side,tableid, debateid, themeid)
	{
		var form = document.createElement("form");
		form.name="writeargument";
		form.method="post";
		form.enctype=enctype;
		form.action="/dbmgmt/debate/write"; 
		form.appendChild(getinput("title",title.value));
		form.appendChild(getinput("argument",text.value))
		form.appendChild(getinput("side",side))
		form.appendChild(getinput("debateid",debateid));
		form.appendChild(getinput("themeid",themeid));
		var table = document.getElementById(tableid);
		for (i=0, j = table.rows.length; i < j; i++)
		{
			var row = table.rows[i];
			var cell = row.cells[0];
			var anks = cell.getElementsByTagName("a");
			form.appendChild(getinput("url-"+i, anks[0].href));
		}
		form.appendChild(getinput("urls",table.rows.length));
		document.body.appendChild(form);
		form.submit();
		return false;
	}
 
	function addSelectedToForm(form){
		for (t = 0; t < lastdest; t++) 
		{
			var table = document.getElementById("gatheredEvidence" + t);
			
			if (table) {
				var rows = table.rows;
				var counter = 0;
				for (i = 1, j = rows.length; i < j; i++) {
					if (rows[i].id != '')
					{
						form.appendChild(getinput(t+"-saveddocid-" + counter, rows[i].id));
						counter++;
					}
				}
				form.appendChild(getinput("table"+t+"saves",counter));
			}
		}
		var sel = document.article.ThemeForArticle;
		if (sel) 
			form.appendChild(getinput('articletheme', sel.options[sel.selectedIndex].value));
		form.appendChild(getinput('name', document.article.name.value));
		form.appendChild(getinput('posting', document.article.posttext.value));
		
		try
		{
			if (lastdest > 0)
			{
				for (t = 0; t < lastdest; t++) 
				{
					var comment = document.getElementById("comment" + t);
					form.appendChild(getinput('comment' + t, comment.value));
				}
			}
		}
		catch (ex){}
		
		var side = document.getElementById("side");
		if (side)
			form.appendChild(getinput('side',side.value));
		var articleid = document.getElementById("articleid");
		if (articleid)
			form.appendChild(getinput("articleid",articleid.value));
		var themeid = document.getElementById("themeid");
		if (themeid)
			form.appendChild(getinput("themeid",themeid.value));
			
		/*var alertelem = document.getElementById("alert");
		if (alertelem.checked)
			form.appendChild(getinput('alert','yes'));*/
		return counter-1;
	}
	
	
	function doMoreQuery(backwards)
	{
		var form = document.createElement("form");
		form.name="morequery";
		form.acceptCharset="UTF-8";
		form.action="/dbmgmt/debate/query";
		form.method="post"
		if (document.getElementById("gatheredEvidence0")) 
			form.appendChild(getinput("addedSaves", addSelectedToForm(form)));
	
		form.appendChild(getinput("searchScope","last"));
		try
		{
			form.appendChild(getinput("maxtables",lastdest));
		}
		catch (ex)
		{
			form.appendChild(getinput("maxtables",maxTables));
		}
		if (backwards)
			form.appendChild(getinput("direction","back"));
		document.body.appendChild(form);
		form.submit();
	}
	
	/*function googleResultsProcessor(){}
	googleResultsProcessor.prototype.procResults = function()
	{
		var olTable = document.getElementById("resultol");
		olTable.add
		var retTable = document.createElement("table");
		var li = document.createElement("li");
		alert("got here "+googleSearch.results.length);
	}

	var googleSearch;
	var resProc;
	function google(query)
	{
		if (googleSearch == undefined) {
			resProc = new googleResultsProcessor(); 
			googleSearch = new GwebSearch();
			googleSearch.setResultSetSize(GSearch.LARGE_RESULTSET);
			googleSearch.setNoHtmlGeneration();
			googleSearch.setSearchCompleteCallback(resProc,googleResultsProcessor.prototype.procResults);
		}	
		googleSearch.execute(query);
	}*/

	function doQuery()
	{
		var query = document.HGUSSearch.queryString.value;
		if (query=='Enter query here'  || query=='')
			return false;
			
		/*if (document.HGUSSearch.google.checked)
		{
			google(query);
			return false;
		}*/
		var form = document.createElement("form");
		form.name="morequery";
		form.acceptCharset="UTF-8";
		form.action="/dbmgmt/debate/query";
		form.method="post"
		form.enctype=enctype;
		if (document.HGUSSearch.debateid != null)
		{
			form.appendChild(getinput("debateid", document.HGUSSearch.debateid.value));
		}	
		form.appendChild(getinput("clearfacets",document.HGUSSearch.clearfacets.value));
		form.appendChild(getinput("queryString",query));
		var vertSel = document.HGUSSearch.searchScopeSelect;
		var optVal = vertSel.options[vertSel.selectedIndex].value
		if (optVal.indexOf("vertical")>-1)
		{
			var bits = optVal.split(/-/);
			form.appendChild(getinput("vertical",bits[1]));
			form.appendChild(getinput("searchScope", "vertical"));
		}	
		else
			form.appendChild(getinput("searchScope", optVal));
	
		if (document.getElementById("gatheredEvidence0")) 
		{
			form.appendChild(getinput("addedSaves", addSelectedToForm(form)));
		}
		try
		{
			form.appendChild(getinput("maxtables",lastdest));
		}
		catch (ex)
		{
			form.appendChild(getinput("maxtables",maxTables));
		}
		if (document.getElementById("file-hidden-0-0"))
		{
			form.appendChild(getinput("debateimage",document.getElementById("file-hidden-0-0").value));
		}
		//}
		
		document.body.appendChild(form);
		form.submit();
		
	}
	
	function addToEvidence(tableid, inpelem, blankurl)
	{
		if (inpelem.value == '' || inpelem.value == blankurl)
			return;
		var url = standardizeUrl(inpelem.value);
		var table = document.getElementById(tableid);
		var nxtRow = table.insertRow(-1);
		var cell = nxtRow.insertCell(-1);
		cell.style.cssText="padding-left=10px;";
		var anchor = document.createElement("a");
		anchor.setAttribute("target","_blank");
		anchor.setAttribute("href",url);
		anchor.style.cssText="color:#9c8f27;";
		anchor.innerHTML = url.substring(0,50);
		cell.appendChild(anchor);
		inpelem.value = '';
	}
	
	var friendadd = 0;
	function addFriend(ownerid,friendid,type)
	{
		friendadd++;
		if (friendadd > 1)
			return false;
		var form = document.createElement("form");
		form.name="addfriend";
		form.method="post";
		form.enctype=enctype;
		form.action="/dbmgmt/debate/myprofile"; 
		form.acceptCharset="UTF-8";
		form.appendChild(getinput("userid", friendid));
		form.appendChild(getinput("palid",ownerid));
		form.appendChild(getinput("paltype",type));
		document.body.appendChild(form);
		form.submit();
		return false;
	}
	
	function viewProfile(userid)
	{
		viewProfile(userid,null);
	}
	function viewProfile(userid, wall)
	{
		var subform = document.createElement("form");
		subform.name="setview";
		subform.method="post";
		subform.action="/dbmgmt/debate/setprofile"
		subform.enctype=enctype;
		subform.acceptCharset="UTF-8";
		
		if (userid) {
			subform.appendChild(getinput("userid", userid));
		}
		if (wall)
		{
			subform.appendChild(getinput("wall","yesplease"));
		}
		document.body.appendChild(subform);
		subform.submit();
	}
	
	function postAnonymousVote(article, title, debateid, themeid, side, thankyoumsg)
	{
		var subform = document.createElement("form");
		subform.name="vote";
		subform.method="post";
		subform.action="/dbmgmt/authaction/postanynomousvote"  
		subform.acceptCharset="UTF-8";
		subform.appendChild(getinput("article",article));
		subform.appendChild(getinput("title",title));
		subform.appendChild(getinput("posting",""));
		subform.appendChild(getinput("debateid",debateid));
		subform.appendChild(getinput("themeid",themeid));
		subform.appendChild(getinput("side",side));
		subform.appendChild(getinput("justavote","yes"));
		document.body.appendChild(subform);
		alert(thankyoumsg);
		subform.submit();
	}
	function postVote(article, title, debateid, themeid, side)
	{
		var subform = document.createElement("form");
		subform.name="vote";
		subform.method="post";
		subform.action="/dbmgmt/action/postdebate"  
		subform.acceptCharset="UTF-8";
		subform.appendChild(getinput("article",article));
		subform.appendChild(getinput("title",title));
		subform.appendChild(getinput("posting",""));
		subform.appendChild(getinput("debateid",debateid));
		subform.appendChild(getinput("themeid",themeid));
		subform.appendChild(getinput("side",side));
		subform.appendChild(getinput("justavote","yes"));
		document.body.appendChild(subform);
		subform.submit();
	}
	
	function postDebate(formname, tablename, inpelem, blanktext, blanktitle, missingmsg, blankurl){
		
		addToEvidence(tablename,inpelem, blankurl);
		var form = document.getElementById(formname);
		form.counter.value = form.counter.value + 1;
		if (form.counter.value > 1)
		{
			return false;
		}
		if (!validateTitleTextSubmit(formname, blanktitle, blanktext, missingmsg)) {
			form.counter.value --;
			return false;
		}
		var subform = document.createElement("form");
		subform.method="post";
		subform.action="/dbmgmt/action/postdebate"  
		subform.acceptCharset="UTF-8";
		for (i = 0, j = form.elements.length; i < j; i++)
		{
			if (form.elements[i].name=='alert')
			{
				if (!form.elements[i].checked)
					continue;
			}
			
			subform.appendChild(getinput(form.elements[i].name, form.elements[i].value));
		}
		var table = document.getElementById(tablename);
		var ctr = 0;
		for (i = 0, j = table.rows.length; i < j; i++) 
		{
			var row = table.rows[i];
			var cell = row.cells[0];
			var anks = cell.getElementsByTagName("a");
			subform.appendChild(getinput("url-" + i, anks[0].href));
		}
		subform.appendChild(getinput("urls",table.rows.length));
		if (respargid!=null)
			subform.appendChild(getinput("respargid",respargid));
		document.body.appendChild(subform);
		subform.submit();
		respargid=null;
		//document.removeChild(subform);
		
	}
	
	function moreQuery(query, scope, cmuid, fname, fvalueid, fvalue, clearf, startFacet)
	{
		var form = document.createElement("form");
		form.name="morequery";
		form.acceptCharset="UTF-8";
		form.action="/dbmgmt/debate/query";
		form.method="post"
		form.appendChild(getinput("queryString",query));
		form.appendChild(getinput("searchScope",scope));
		form.appendChild(getinput("cid",cmuid));
		form.appendChild(getinput("facetname",fname));
		form.appendChild(getinput("facetvalue",fvalue));
		form.appendChild(getinput("facetvalueid",fvalueid));
		form.appendChild(getinput("clearfacets",clearf));
		form.appendChild(getinput("facetstart",startFacet));
		try
		{
			form.appendChild(getinput("maxtables",lastdest));
		}
		catch (ex)
		{
			form.appendChild(getinput("maxtables",maxTables));
		}
		if (document.getElementById("gatheredEvidence0" )) 
			form.appendChild(getinput("addedSaves", addSelectedToForm(form)));
			
		if (document.getElementById("querydebateid"))
		{
			form.appendChild(getinput("debateid",document.getElementById("querydebateid").value));
		}
		
		document.body.appendChild(form);
		form.submit();
	}
	
	function getinput(inName, inValue)
	{
		var input = document.createElement("input");
		input.type ='hidden';
		input.name = inName;
		input.value = inValue;
		return input;	
	}

	function lessQuery(query, scope, cmuid, fname, fvalueid, fvalue)
	{
		var form = document.createElement("form");
		form.name="lessquery";
		form.acceptCharset="UTF-8";
		form.action="/dbmgmt/debate/query";
		form.method="post"
		form.appendChild(getinput("queryString",query));
		form.appendChild(getinput("searchScope",scope));
		form.appendChild(getinput("cid",cmuid));
		form.appendChild(getinput("lastfacetname",fname));
		form.appendChild(getinput("lastfacetvalue",fvalue));
		form.appendChild(getinput("lastfacetvalueid",fvalueid));
		try
		{
			form.appendChild(getinput("maxtables",lastdest));
		}
		catch (ex)
		{
			form.appendChild(getinput("maxtables",maxTables));
		}
		if (document.getElementById("gatheredEvidence0")) 
			form.appendChild(getinput("addedSaves", addSelectedToForm(form)));
		
		document.body.appendChild(form);
		form.submit();
	}
	
	var checkedArray = new Array();

	function addCheckedObj(domid, url, docid)
	{
		checkedObj = new Object();
		checkedObj.id = domid;
		checkedObj.url = url;
		checkedObj.docid = docid;
		checkedArray.push(checkedObj);
	}
	
	function setCallQueryForm(querystring, verticalid, articleid)
	{
		document.bubblequery.queryString.value=querystring;
		document.bubblequery.searchScope.value="bubble:"+verticalid;
		document.bubblequery.article.value=articleid;
		document.bubblequery.vertical.value=verticalid;
		document.bubblequery.submit();
		return false;
	}

	
	var last = ""
	function getOutLogo()
	{
		var logo = document.getElementById("HGUS_Grinder");
		if (last=="highlight")
		{
			logo.src="logo_on.png";
		}
		else
		{
			logo.src="logo_off.gif";	
		}
	}
	function getOverLogo()
	{
		var logo = document.getElementById("HGUS_Grinder");
		if (last=="highlight")
		{
			logo.src="logo_on_over.png";
		}
		else
		{
			logo.src="logo_off_over.png";	
		}
	}
	
	var remCounter = 0;
	var remImage = new Image();
	function changeCookie()
	{
		var inp = document.getElementById("rememberme");
		remImage.src="/dbmgmt/action/rememberme?remember="+inp.checked+"&cnt="+(remCounter++);
	}
	
	var wallCounter = 0;
	var wallImage = new Image();
	function setWallParam()
	{
		var sel = document.getElementById("whoposts");
		wallImage.src="/dbmgmt/action/setwall?type="+sel.value+"&cnt="+(wallCounter++);
	}
	
	var toggleCounter = 0;
	var toggleImage = new Image();
	function persistHighlights()
	{
		var newSetting = "off";
		if (last =="highlight")
			newSetting = "on";
		toggleImage.src="/dbmgmt/authaction/sethltoggle?newval="+newSetting+"&cnt="+(toggleCounter++);
		
	}
	function toggleHighlights(small, med, large)
	{
		if (!small)
			small = 'dynamic1Hover';
		if (!med)
			med = 'dynamic10Hover';
		if (!large)
			large = 'dynamic20Hover';
		var logo = document.getElementById("HGUS_Highlights");
		if (last=="highlight")
		{

			logo.src="turnhighlightson.png";
			hideCluster(getElementsByName_iefix("span","bigtip"));
			hideCluster(getElementsByName_iefix("span","medtip"));
			hideCluster(getElementsByName_iefix("span","smalltip"));
			hideCluster(getElementsByName_iefix("span","atip"));
			
			changePVisibility(getElementsByName_iefix("p", "highlighted"), "hiddenPic");
			changePVisibility(getElementsByName_iefix("p", "nothighlighted"), "");

			last="";
			changeClass("bigtip","noethis");
			changeClass("medtip","noethis");
			changeClass("smalltip","noethis");
			changeClass("tooltip","nope");
			changeClass("atip","noethis");
			
		}
		else
		{
			logo.src="turnhighlightsoff.png";
			
			showCluster(getElementsByName_iefix("span","bigtip"));
			showCluster(getElementsByName_iefix("span","medtip"));
			showCluster(getElementsByName_iefix("span","smalltip"));
			showCluster(getElementsByName_iefix("span","atip"));
			
			changePVisibility(getElementsByName_iefix("p", "nothighlighted"), "hiddenPic");
			changePVisibility(getElementsByName_iefix("p", "highlighted"), "");
			
			
	
			last="highlight";
			changeClass("bigtip",large);
			changeClass("medtip",med);
			changeClass("smalltip",small);
			changeClass("tooltip","tooltip");
			changeClass("atip","dynamicAHover");

		}
	}
	
	function changePVisibility(elements, newClass)
	{
		for (i = 0, j = elements.length; i < j; i++) 
		{
			elements[i].className=newClass;
		}
	}		
	function changeClass(elemName, newClass)
	{
		var elements = getElementsByName_iefix("span",elemName);
		for (i = 0, j = elements.length; i < j; i++) 
		{
			elements[i].className=newClass;
		}
	}
	
	var lastfontcolour;
	function showCluster(elements)
	{
		for (i = 0, j = elements.length; i < j; i++)
			{
				elements[i].style.backgroundColor= "#d2feff";
				elements[i].style.fontWeight="bold";
				lastfontcolour = elements[i].style.foregroundColor;
			}
	}
	
	
	function hideCluster(elements)
	{
		for (i = 0, j = elements.length; i < j; i++)
			{
				elements[i].style.backgroundColor= "transparent";
				elements[i].style.fontWeight="normal";
				elements[i].style.foregroundColor = lastfontcolour;
			}
	}
	function changeColour(elemName, newColour)
	{
		var elements = getElementsByName_iefix("span",elemName);
		for (i = 0, j = elements.length; i < j; i++)
		{
			elements[i].style.color = newColour;
		}
	}
		
	function getElementsByName_iefix(tag, name) 
	{
		var elem = document.getElementsByTagName(tag);
	    var arr = new Array();
    	for(i = 0,iarr = 0; i < elem.length; i++) 
		{
        	att = elem[i].getAttribute("name");
          	if(att == name) 
			{
            	arr[iarr] = elem[i];
               	iarr++;
          	}
     	}
     	return arr;
	}




var ratingImage= new Image();
function rateArgument(argid, rating, debateid, debateargid)
{
	var dt = new Date();
	var elem = document.getElementById(argid+"-rating");
	var newContent = '<ul class="rating"><li class="rating-'+rating+'"/></ul>';
	elem.innerHTML= newContent;
	ratingImage.src="/dbmgmt/action/setrating?debateid="+debateid+"&dbargid="+debateargid+"&rating="+rating+"&time="+dt.getTime();
	ratingImage.onload=function(){	if (this.width==10 && this.height ==10)
	{
		//not auth so out of here - probably session expired.
		location.href="/dbmgmt/debate/main";
		return false;
	}}
	return false;
}

var ratingDebate= new Image();
function rateDebate(argid, rating,debateid)
{
	var dt = new Date();
	var elem = document.getElementById(argid)
	var newContent = '<ul class="rating"><li class="rating-'+rating+'"/></ul>';
	elem.innerHTML= newContent;
	ratingDebate.src="/dbmgmt/action/setrating?debateid="+debateid+"&rating="+rating+"&time="+dt.getTime();
	ratingDebate.onload=function(){	if (this.width==10 && this.height ==10)
	{
		//not auth so out of here - probably session expired.
		location.href="/dbmgmt/debate/main";
		return false;
	}}
	return false;
}

function changeListItem (nodeId)
{
	var lItem = document.getElementById(nodeId);
	var currClass = lItem.className;
	if (currClass == 'liOpen')
	{
		lItem.className = 'liClosed';
		}
	else
	{
		lItem.className = 'liOpen';
		}
		
	return false;
}

var sendmeDebateImg = new Image();
function sendMeDebate(debateid, msg)
{
	var dt = new Date();
	sendmeDebateImg.src = "/dbmgmt/debate/SendToMe?debate="+debateid+"&counter="+dt.getTime();
	alert(msg);
	return false;
}

var debateAlertImg= new Image();
function swapAlertImage(debateid, setting, yestext, notext)
{
	var dt = new Date();
	debateAlertImg.src="/dbmgmt/action/setAlert?debateid="+debateid+"&setting="+setting+"&counter="+dt.getTime()
	debateAlertImg.onload=function(){	if (this.width==10 && this.height ==10)
	{
		//not auth so out of here - probably session expired.
		location.href="/dbmgmt/debate/main";
		return false;
	}}
	var cbox = document.getElementById("alertcheckbox"+debateid);
	var img = document.getElementById("debatealert"+debateid);
	var parg = document.getElementById("alerttext"+debateid);
	if (setting=='yes')
	{
		cbox.src="/dbmgmt/webpages/images/selected.png";
		//cbox.setAttribute("onclick","swapAlertImage('"+debateid+"','no','"+yestext+"','"+notext+"');");// this doesn't work in IE, left it here for everyone else.
		cbox.onclick = function(){swapAlertImage(debateid,'no',yestext,notext);};
		img.src = "/dbmgmt/webpages/images/watching.png";
		parg.style.color="#fe3557";
		parg.innerHTML = yestext;
	}
	else
	{
		//cbox.setAttribute("onclick","swapAlertImage('"+debateid+"','yes','"+yestext+"','"+notext+"');");// this doesn't work in IE, left it here for everyone else.
		cbox.onclick = function(){swapAlertImage(debateid,'yes',yestext,notext);};
		cbox.src = "/dbmgmt/webpages/images/unselected.png";
		img.src = "/dbmgmt/webpages/images/alertme.png";
		parg.style.color="#0e72c0";
		parg.innerHTML = notext;
	}
	return false;
}

function showAvatarForm(savetext, oopstext, instructions,badfiletype,hasone, areyousure, revert)
{
	var nomore;
	var nomorespan;
	if (hasone!='')
	{
		nomorespan="2"
		nomore='<img src="nomoreavatar.png" onclick="removeAvatar';
		nomore+= "('"+areyousure+"')";
		nomore+= ';return false;"><a href="" onclick="removeAvatar(';
		nomore+= "'"+areyousure+"')";		nomore += ';return false;">'+revert+'</a>';
	}
	else
	{
		nomorespan="2"
		nomore='';	
	}
	var img = document.getElementById("avatarimg");
	var td = document.getElementById("avatarspace");
	var innercode ="<form name='avatarsubmit' accept='image/gif,image/jpeg,image/png ' ENCTYPE='multipart/form-data' accept-charset='UTF-8' action='/dbmgmt/action/setAvatar' method='post'>";
	innercode += '<table cellPadding="0" cellSpacing="0" style="margin-left:-6px">';
	innercode += '<tr>'
	innercode += '<td colspan="2">';
	innercode+= '<p style="font-size:12px; color:#0e72c0;">';
	innercode += instructions
	innercode += "</p></td></tr>";
	innercode += '<tr><td colspan="2">';
	innercode +=  '<input id="avatarfileid" type="file" name="filename" size = "10"/>';
	innercode += "</td></tr>"
	innercode += '<tr><td align="left" >';
	innercode += '<input type="image" src="webpages/savenewimage.png" onclick="checkavatar();return false;" style="margin-top:6px;"/>';
	innercode += '<td align="left">';
	innercode += '<input type="image" src="webpages/oopsnevermind.png" onclick="showAvatar(';
	innercode += "'"+savetext+"','"+oopstext+"',";
	innercode += "'"+img.getAttribute("src")+"','"+instructions+"'";
	innercode += ');return false;" style="margin-top:6px;"/>';
	innercode += '</td></tr><tr><td align="left" colspan="2">'+nomore+'</td></tr></table>';
	innercode += '</form>'
	td.innerHTML = innercode;
}

function checkavatar()
{
	var img = document.getElementById('avatarfileid');
	if (img.value != '' && img.value!=null)
	{
		document.avatarsubmit.submit();
	}
	return false;
}
function showAvatar(savetext, oopstext, src, instructions)
{
	var td = document.getElementById("avatarspace");
	var innercode = '<img id="avatarimg" style="clip: rect(auto, auto, auto, auto)" width="206px" height="151px" src="'+src+'" onclick="showAvatarForm(';
	innercode+= "'"+savetext+"','"+oopstext+"','"+instructions+"')";
	innercode+= ';return false;"/>';
	td.innerHTML = innercode;
}

function removeAvatar(text)
{
	if (!confirm(text))
		return false;
	var form = document.createElement("form");
	form.name="publish";
	form.method="post";
	form.enctype=enctype;
	form.action="/dbmgmt/action/removeAvatar"; 
	form.acceptCharset="UTF-8";
	document.body.appendChild(form);
	form.submit();	
	
}

function showRatings(argid,debateid, debateargid, hatetext,disliketext,indifferenttext,liketext,lovetext)
{
	var td = document.getElementById(argid);
	var newContent = '<ul class="rating">';
	newContent+= '<li class="hate">';
	newContent += '<a href="" title="' +hatetext+'" onclick="rateArgument(';
	newContent+= argid+",'hate',"+debateid+","+debateargid;
	newContent += ');return false;"></a></li>';
	newContent += '<li class="dislike"><a href="" title="';
	newContent+= disliketext +'"';
	newContent +=' onclick="rateArgument(';
	newContent += argid +",'dislike',"+debateid+","+debateargid;
	newContent += ');return false;"></a></li>';
	newContent += '<li class="indifferent"><a href="" title="';
	newContent += indifferenttext +'"';
	newContent += ' onclick="rateArgument(';
	newContent += argid+",'indifferent',"+debateid+","+debateargid;
	newContent += ');return false;"></a></li>';
	newContent += '<li class="like"><a href="" title="';
	newContent += liketext +'"';
	newContent += ' onclick="rateArgument(';
	newContent += argid+",'like',"+debateid+","+debateargid;
	newContent += ');return false;"></a></li>';
	newContent += '<li class="love"><a href="" title="'
	newContent += lovetext+'"';
	newContent += ' onclick="rateArgument(';
	newContent += argid+",'love', "+debateid+","+debateargid;
	newContent += ');return false;"></a></li></ul>';
	td.innerHTML = newContent;
	return false;
}

function revertDebate(argid, initrating, debateid, hatetext, disliketext, indifferenttext, liketext, lovetext)
{
	var td= document.getElementById(argid);
	var newContent = '<ul class="rating">';
	newContent += '<li class="'+initrating+'" onmouseout="showDebateRatings('+argid;
	newContent += ","+debateid+",'"+hatetext+"','"+disliketext+"','"+indifferenttext+"','"+liketext+"','"+lovetext+"','"+initrating+"')";
	newContent += '"/></ul>';
	td.innerHTML = newContent;
	return false;
}
function showDebateRatings(argid, debateid, hatetext,disliketext,indifferenttext,liketext,lovetext, initrating)
{
	var td = document.getElementById(argid);
	var newContent = '<ul class="rating" onmouseout="revertDebate('+argid;
	newContent+= ",'"+initrating+"',"+debateid+",'"+hatetext+"','"+disliketext+"','"+indifferenttext+"','"+liketext+"','"+lovetext+"' )";
	newContent += '">';
	newContent+= '<li class="hate" >';
	newContent += '<a href="" title="' +hatetext+'" onclick="rateDebate(';
	newContent+= argid+",'hate',"+debateid;
	newContent += ');return false;"></a></li>';
	newContent += '<li class="dislike"><a href="" title="';
	newContent+= disliketext +'"';
	newContent +=' onclick="rateDebate(';
	newContent += argid+",'dislike',"+debateid;
	newContent += ');return false;"></a></li>';
	newContent += '<li class="indifferent"><a href="" title="';
	newContent += indifferenttext +'"';
	newContent += ' onclick="rateDebate(';
	newContent += argid+",'indifferent',"+debateid;
	newContent += ');return false;"></a></li>';
	newContent += '<li class="like"><a href="" title="';
	newContent += liketext +'"';
	newContent += ' onclick="rateDebate(';
	newContent += argid+",'like',"+debateid;
	newContent += ');return false;"></a></li>';
	newContent += '<li class="love"><a href="" title="'
	newContent += lovetext+'"';
	newContent += ' onclick="rateDebate(';
	newContent += argid+",'love', "+debateid;
	newContent += ');return false;"></a></li></ul>';
	td.innerHTML = newContent;
	return false;
}

function addEvidenceSection(destid, pointtext, describe, supportingEvidence, addexternal, copy , add, foundevidence,searchresultspresent, getmoreevidence, point)
{
	lastdest ++;
	if (lastdest>6)
	{
		/*var evbutton = document.getElementById("evbutton");
		evbutton.disabled=true;
		* in the earlier version it was an input.
		*/
		lastdest --;
		return false;
	}
	//NOTE IE7 seems very picky about attribute case eg use cellPadding, cellSpacing colSpan
	var evTable= document.createElement("table");
	evTable.setAttribute("cellPadding","0");
	evTable.setAttribute("cellSpacing","0");
	evTable.style.cssText="margin-left:7px";
	evTable.setAttribute("width","541px");
	var row = evTable.insertRow(-1);
	var cell = row.insertCell(-1);
	cell.setAttribute("height","10px"); 
	var anch = document.createElement("a");
	anch.name="anch"+destid;
	cell.appendChild(anch);
	row = evTable.insertRow(-1);
	cell = row.insertCell(-1);
	cell.setAttribute("height","6px");
	cell.setAttribute("background","argumentToplong_on.png");
	cell.setAttribute("id","dest"+destid+"-0");
	row = evTable.insertRow(-1);
	cell = row.insertCell(-1);
	cell.setAttribute("height","125px");
	cell.setAttribute("id","dest"+destid+"-1");
	cell.setAttribute("background","argumentbg_on.png");
	var pointTable = document.createElement("table");
	pointTable.setAttribute("cellPadding","0");
	pointTable.setAttribute("cellSpacing","0");
	pointTable.style.cssText="margin-left:10px";
	cell.appendChild(pointTable);
	row = pointTable.insertRow(-1);
	cell = row.insertCell(-1);
	cell.setAttribute("colSpan","3");
	var p = document.createElement("p");
	p.style.cssText = "font-size:18px; color:#0e72c0;"
	p.innerHTML = '<strong>'+pointtext+'</strong> '+describe ;
	cell.appendChild(p);
	row = pointTable.insertRow(-1);
	cell = row.insertCell(-1);
	cell.setAttribute("width","7px");
	cell.setAttribute("height","14px");
	var img = document.createElement("img");
	img.setAttribute("src","chainlinkofevidence.png");
	cell.appendChild(img);
	cell = row.insertCell(-1);
	cell.setAttribute("width","2px");
	cell = row.insertCell(-1);
	var input;
	input = document.createElement("input");
	var test = pointtext.substring(0, pointtext.length-1);
	//input.value = test 
	input.value=pointtext;
	input.id="comment"+destid;
	input.name="comment"+destid;
	input.type="text";
	input.size="35";
	input.maxlength="256";
	input.align="bottom";
	input.style.cssText = "margin-top:2px; width:493px; color: #666666; border:1px solid #CCCCCC; background-image: url('Title.png')";
	input.onfocus = new Function("commentFocus('"+destid+"','"+test+"')");
	input.onchange=new Function("savePost('comment"+destid+"','comment"+destid+"')");
	cell.appendChild(input);
	row = pointTable.insertRow(-1);
	cell = row.insertCell(-1)
	cell.setAttribute("colSpan","3");
	var urlTable = document.createElement("table");
	urlTable.setAttribute("cellPadding","0");
	urlTable.setAttribute("cellSpacing","0");
	urlTable.style.cssText = "padding-left:10px";
	urlTable.id = "gatheredEvidence"+destid;
	cell.appendChild(urlTable);
	row = urlTable.insertRow(-1);
	cell = row.insertCell(-1);
	p = document.createElement("p");
	p.style.cssText="font-size:12px; font-weight:bold; color:#0099FF;";
	p.innerHTML = supportingEvidence;
	cell.appendChild(p);
	row = urlTable.insertRow(-1);
	cell = row.insertCell(-1);
	p = document.createElement("p");
	p.style.cssText = "font-size: 9px; color:#FFFFFF;";
	p.innerHTML = "______________________________________________________________________________________";
	cell.appendChild(p);
	row = urlTable.insertRow(-1);
	cell = row.insertCell(-1);
	cell.setAttribute("height","5px");
	row = urlTable.insertRow(-1);
	cell = row.insertCell(-1);
	var form = document.createElement("form");
	form.onsubmit=new Function( "trywith('adder"+destid+"');return false;");
	var manTable = document.createElement("table");
	form.appendChild(manTable);
	manTable.setAttribute("cellSpacing","0");
	manTable.setAttribute("cellPadding","0");
	cell.appendChild(form);
	row = manTable.insertRow(-1);
	cell = row.insertCell(-1);
	cell.setAttribute("colSpan","3");
	p = document.createElement("p");
	p.style.cssText = "font-size:12px; color:#999999;";
	p.innerHTML = '<strong>'+addexternal+'</strong>'+copy +'<strong>'+add+'</strong>';
	cell.appendChild(p);
	row = manTable.insertRow(-1);
	cell = row.insertCell(-1);
	cell.setAttribute("height","22px");
	cell.setAttribute("width","25px");
	input = document.createElement("input");
	input.name="AddURLEvidence";
	input.setAttribute("type","image");
	input.setAttribute("src","addurl.png")
	input.id="adder"+destid;
	input.onclick = new Function("addFrom('manuallyAdded"+destid+"',"+destid+",'"+ foundevidence + "');return false;");
	cell.appendChild(input);
	cell = row.insertCell(-1);
	cell.setAttribute("width","2px");
	cell = row.insertCell(-1);
	cell.setAttribute("height","22px");                                                
	input = document.createElement("input");
	input.value = foundevidence;
	input.onfocus = new Function("if (this.value=='"+foundevidence+"'){this.value='';this.style.color='#ac9814';}");
	input.onchange=new Function("savePost('manuallyAdded"+destid+"','"+destid+"-saveddocid-0');")
	input.id="manuallyAdded"+destid;
	input.name="HGUS_AddURLEvidence"; 
	input.type="text";
	input.size="35";
	input.maxlength="256";
	input.align="bottom";
	input.style.cssText="padding-left:4px; width:450px; font-weight: bold; color: #CCCCCC; border:1px solid #998d43; background-image: url('additionalurl.png')";
	cell.appendChild(input);
	if (searchresultspresent == '')
	{
		row = pointTable.insertRow(-1);
		cell = row.insertCell(-1);
		cell.setAttribute("colSpan","3");
		p = document.createElement("p");
		p.style.cssText="color:#0e72c0; font-size:13px; font-weight: bold; padding-left:10px;";
		p.innerHTML = getmoreevidence;
		cell.appendChild(p);
	}
	row = manTable.insertRow(-1);
	cell = row.insertCell(-1);
	cell.setAttribute("colspan","3");
	var div = document.createElement("div");
	cell.appendChild(div);
	div.id = "file-evidence-"+destid;
	input = document.createElement("input");
	input.type="file";
	input.style.width="450px";
	input.maxlength="256";
	input.size="35";
	input.name="file-evidence-"+destid+"-0";
	input.id="file-evidence-"+destid+"-0";
	input.onchange= new Function("uploadevidence('file-evidence','0','"+destid+"');return false;");
	div.appendChild(input);
	row = evTable.insertRow(-1);
	cell = row.insertCell(-1);
	cell.setAttribute("height","6px");
	cell.setAttribute("background","argumentbottom_on.png");
	cell.setAttribute("id","dest"+destid+"-2");
	cell.innertHTML=" ";
		
	
	
	/*var section = '<table width="541px" cellpadding="0" cellspacing="0" style="margin-left:7px;">';
	section+= '<td height="10px"/><tr/>';
	section += '<td height="6px" background="argumentToplong_on.png" id="dest'+destid+'-0" />';
	section += '<tr/>';
	section += '<td height="125px" id="dest'+destid+'-1" background="argumentbg_on.png">';
	section += '	<table cellpadding="0" cellspacing="0"  style="margin-left:10px;">';
	section += '		<td colspan="3">';
	section += '			<p style="font-size:18px; color:#0e72c0;"><strong>'+pointtext+'</strong> '+describe +'</p>';
	section += '		</td><tr/>';
	section += '		<td width="7px" height="14px">';
	section += '			<img src="chainlinkofevidence.png"/>';
	section += '		</td>';
	section += '		<td width="2px"/>';
	section += '		<td >';
	section += '			<input type="text" dir="ltr" lang="en" maxlength="256" align="bottom" style="margin-top:2px; width:493px; color: #666666; border:1px solid #CCCCCC; background-image: url(';
	section += "'/dbmgmt/webpages/images/en/Title.png'";
	section += ');" id="comment'+destid+'" name="comment'+destid+'" onfocus="commentFocus('+"'"+destid+"','"+pointtext+"')" +'" value="'+pointtext+'" />';
	section += '		</td>';
	section += '		<tr/>';
	section += '		<td colspan="3">';
	section += '			<table cellpadding="0" cellspacing="0" style="padding-left:10px;" id="gatheredEvidence'+destid+'" >';
	section += '				<td><p style="font-size:12px; font-weight:bold; color:#0099FF;">'+supportingEvidence +' </p></td><tr/>';                                
	section += '				<td><p style="font-size: 9px; color:#FFFFFF;">______________________________________________________________________________________</p></td><tr/>';
	section += '				<td height="5px"/><tr/>';
	section += '				<td>';
	section += '					<table cellpadding="0" cellspacing="0">';
	section += '						<td colspan="3"><p style=" font-size:12px; color:#999999;"><strong>'+addexternal+'</strong>'+copy +'<strong>'+add+'</strong></p></td><tr/>';
	section += '						<td height="22px" width="25px">';
	section += '							<input name="AddURLEvidence" type="image" src="addurl.png" onclick="addFrom('+"'"+'manuallyAdded'+destid+"',"+destid+",'"+ foundevidence + "'" +')"/>';
	section += '						</td>';
	section += '						<td width="2px"/>';                                                
	section += '						<td height="22px">';
	section += '							<input value="'+foundevidence+'" onfocus=" if (this.value=='+"'"+foundevidence+"'"+'){this.value='+"''"+';this.style.color='+"'#ac9814'"+';}"  id="manuallyAdded'+destid+'" name="HGUS_AddURLEvidence" type="text" dir="ltr" lang="en" size="35" maxlength="256" align="bottom" style="padding-left:4px; width:450px; font-weight: bold; color: #CCCCCC; border:1px solid #998d43; background-image: url('+"'additionalurl.png'"+')"; />';
	section += '						</td>';
	section += '						<tr/>';
	section += '					</table>';
	section += '				</td>';
	section += '			</table>';
	section += '		</td>';
	section += '		<tr/>';
	if (searchresultspresent == '1')
	{
		section += '	<td colspan="3"><p style="color:#0e72c0; font-size:13px;  font-weight: bold; padding-left:10px;">'+getmoreevidence+'</p></td><tr/>';
	}
		
	section += '	</table>';
	section += '</td><tr/>';
	section += '<td height="6px" background="argumentbottom_on.png" id = "dest'+destid+'-2" />';
	section += '<tr/>';
	section += '</table>';*/
	var div = document.getElementById("evidencediv");
	div.appendChild(evTable);
	commentFocus(destid, pointtext);	
	
	
	location.href="#anch"+destid;
	
}


var wallNotifyImg= new Image();
function changeWallNotifySetting()
{
	var dt = new Date();
	wallNotifyImg.src="/dbmgmt/action/setNotifyState?counter="+dt.getTime()
	var curImg = document.getElementById("alertnotify");
	if (curImg.src.search(/unselected.png/)>-1)
		curImg.src = "selected.png";
	else
		curImg.src = "unselected.png";
	return false;
}

var defaultDebateImg= new Image();
function changeDefaultDebate()
{
	var dt = new Date();
	defaultDebateImg.src="/dbmgmt/action/setDefaultDebateState?counter="+dt.getTime()
	var curImg = document.getElementById("watchmynewdebates");
	if (curImg.src.search(/unselected.png/)>-1)
		curImg.src = "selected.png";
	else
		curImg.src = "unselected.png";
	return false;
}
var changeAlertonArgumentImg= new Image();
function changeAlertonArgument()
{
	var dt = new Date();
	changeAlertonArgumentImg.src="/dbmgmt/action/toggleAlertonArgument?counter="+dt.getTime()
	var curImg = document.getElementById("watchmynewarguments");
	if (curImg.src.search(/unselected.png/)>-1)
		curImg.src = "selected.png";
	else
		curImg.src = "unselected.png";
	return false;
}

var changePostviaShareImg= new Image();
function changePublishViaShare()
{
	var dt = new Date();
	changePostviaShareImg.src="/dbmgmt/action/togglePublishviaShare?counter="+dt.getTime()
	var curImg = document.getElementById("publishviashare");
	if (curImg.src.search(/unselected.png/)>-1)
		curImg.src = "selected.png";
	else
		curImg.src = "unselected.png";
	return false;
}

var changePostviaEnrichImg= new Image();
function changePublishViaEnrich()
{
	var dt = new Date();
	changePostviaEnrichImg.src="/dbmgmt/action/togglePublishviaEnrich?counter="+dt.getTime()
	var curImg = document.getElementById("publishviaenrich");
	if (curImg.src.search(/unselected.png/)>-1)
		curImg.src = "selected.png";
	else
		curImg.src = "unselected.png";
	return false;
}



var watchingImg = new Image();
function setUserWatch(imageToSwitch, userid)
{
	var dt = new Date();
	var curImg = document.getElementById(imageToSwitch);
	if (curImg.src.search(/unselected.png/)>-1)
	{
		watchingImg.src="/dbmgmt/action/setWatchedUser?userid="+userid+"&setting=on&counter="+dt.getTime();
		curImg.src = "selected.png";
	}
	else
	{
		watchingImg.src="/dbmgmt/action/setWatchedUser?userid="+userid+"&setting=off&counter="+dt.getTime();
		curImg.src = "unselected.png";
	}
	return false;
	
}

function removeUserWatch(userid, username)
{
	var dt = new Date();
	var curImg = document.getElementById("img"+userid);
	watchingImg.src="/dbmgmt/action/setWatchedUser?userid="+userid+"&setting=off&counter="+dt.getTime();
	if (curImg != null)
	{
		curImg.src = "unselected.png";
		curImg.onclick=new Function("addUserWatch('"+username.replace("'","\\\'")+"',"+userid+");");
		
	}	
	var usertable = document.getElementById("useralerttable");
	if (usertable == null)
	return false;
	
	for (var i=0; i < usertable.rows.length; i++)
	{
		if (usertable.rows[i].getAttribute("userrow")==userid)
		{
			usertable.deleteRow(i);
			usertable.deleteRow(i);
			break;
		}
	}
	return false;
}
function addUserWatch(username, userid)
{
	var dt = new Date();
	var curImg = document.getElementById("img"+userid);
	watchingImg.src="/dbmgmt/action/setWatchedUser?userid="+userid+"&setting=on&counter="+dt.getTime();
	curImg.src="selected.png";
	curImg.onclick=new Function("removeUserWatch("+userid+",'"+username.replace("'","\\\'")+"');");
	var usertable = document.getElementById("useralerttable");
	if (usertable== null)
		return false;
	var found = false;
	for (var i =0;i < usertable.rows.length; i+=2)
	{
		if (usertable.rows[i].cells[1].childNodes[0].innerHTML>username)
		{
			addToUserTable(userid, username, i, usertable);		
			found = true;
			break;
		}	
	}
	if (!found)
	{
		addToUserTable(userid, username, -1, usertable);
	}
	
}

function addToUserTable(userid, username, pos, usertable)
{
	var row;
	var cell;
	if (pos == -1)
	{
		row = usertable.insertRow(pos);
		cell = row.insertCell(-1);
		row.setAttribute("userrow",userid);
		cell.width="14px";
		var img = new Image();
		img.src="selected.png";
		img.onclick=new Function("removeUserWatch("+userid+",'"+username.replace("'","\\\'")+"');");
		cell.appendChild(img);
		cell = row.insertCell(-1);
		var anchor = document.createElement("a");
		anchor.style.cssText=" font-size:11px; color:#0e72c0; text-decoration:none;";
		anchor.onclick=new Function("viewProfile("+userid+");return false;");
		anchor.innerHTML = username;
		cell.appendChild(anchor);
		
		row = usertable.insertRow(pos);
		cell = row.insertCell(-1);
		cell.colspan="2";
		cell.height="5px";
	}
	else
	{
		row = usertable.insertRow(pos);
		cell = row.insertCell(-1);
		cell.colspan="2";
		cell.height="5px";
		
		row = usertable.insertRow(pos);
		cell = row.insertCell(-1);
		row.setAttribute("userrow",userid);
		cell.width="14px";
		var img = new Image();
		img.src="selected.png";
		img.onclick=new Function("removeUserWatch("+userid+",'"+username.replace("'","\\\'")+"');");
		cell.appendChild(img);
		cell = row.insertCell(-1);
		var anchor = document.createElement("a");
		anchor.style.cssText=" font-size:11px; color:#0e72c0; text-decoration:none;";
		anchor.onclick=new Function("viewProfile("+userid+");return false;");
		anchor.innerHTML = username;
		cell.appendChild(anchor);
		
	}
	
}

var vertImage = new Image();
function toggleVerticalView(vid)
{
	var dt = new Date();
	var curImg = document.getElementById("vert-"+vid);
	if (curImg.src.search("/unselected.png")>-1)
	{
		// currently unselected - user has selected it so we turn it on
		vertImage.src = "/dbmgmt/action/setVerticalAlert?action=add&type=vertical&id="+vid+"&counter="+dt.getTime();
		curImg.src="selected.png"
	}
	else
	{
		vertImage.src = "/dbmgmt/action/setVerticalAlert?action=remove&type=vertical&id="+vid+"&counter="+dt.getTime();
		curImg.src="unselected.png"
	}
}

function toggleThemeView(themeid)
{
		var dt = new Date();
	var curImg = document.getElementById("theme-"+themeid);
	if (curImg.src.search("/unselected.png")>-1)
	{
		// currently unselected - user has selected it so we turn it on
		vertImage.src = "/dbmgmt/action/setVerticalAlert?action=add&type=theme&id="+themeid+"&counter="+dt.getTime();
		curImg.src="selected.png"
	}
	else
	{
		vertImage.src = "/dbmgmt/action/setVerticalAlert?action=remove&type=theme&id="+themeid+"&counter="+dt.getTime();
		curImg.src="unselected.png"
	}
}

var heartImage = new Image();
function heartbeat()
{
	var dt = new Date();
	heartImage.src="/dbmgmt/action/heartbeat?counter="+dt.getTime();
}

var textSaveImg = new Image();
function savePost(keyid, otherkey)
{
	var tmp = document.getElementById(keyid);
	saveWIP(otherkey,tmp.value)
}
function saveWIP(key,text)
{
	if (factory==null)
	{
		setFactory();
	}
	var xreq = factory();
	xreq.open("POST","/dbmgmt/action/savepost");
	xreq.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	var ting='value='+encodeURIComponent(text).replace(/%20/g,"+");
	ting+='&';
	ting+='key='+key
	xreq.send(ting);
}

function saveNotepad(fred)
{
	if (factory==null)
	{
		setFactory();
	}
	var xreq = factory();
	xreq.open("POST","/dbmgmt/action/saveNotepad");
	xreq.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	var ting='value='+encodeURIComponent(document.getElementById("notepad").value).replace(/%20/g,"+");
	xreq.send(ting);
}

var factory = null;
var factories = [
                function() { return new XMLHttpRequest();},
                function() { return new ActiveXObject("Msxml2.XMLHTTP");},
                function() {return new ActiveXObject("Microsoft.XMLHTTP");}
                 ];

function validateToU(message)
{
	var ret = document.getElementById("touviewed");
	if (!ret.checked)
	{
		alert(message)
	}
	return ret.checked;
}

function addFriendTodebate(defaultText, list, selectsource, allstring)
{
	var textArea = document.getElementById(list);
	if (textArea.value == defaultText)
		textArea.value='';
	
	var selsrc = document.getElementById(selectsource);
	var opt = selsrc.options[selsrc.selectedIndex];
	if (opt.value == allstring)
	{
		for (var i = 0; i < selsrc.options.length; i++)
		{
			opt =selsrc.options[i];
			if (opt.value != allstring)
			{
				textArea.value = textArea.value + opt.value+", ";
			}
		}
		for (var i =selsrc.options.length-1; i >-1 ; i--)
		{
			selsrc.options[i] = null;
		}
	}
	else
	{
		textArea.value = textArea.value + opt.value+", ";
		selsrc.options[selsrc.selectedIndex] = null;
	}
}



var inviteCounter = 0;
function addInvites(emailblank, friendblank, foeblank, baddelimiter, msgblank)
{
	var form = document.createElement("form");
	form.name="publish";
	form.method="post";
	form.enctype=enctype;
	form.action="/dbmgmt/action/addInvitations"; 
	form.acceptCharset="UTF-8";	
	var temp = document.getElementById("emailinvites").value;
	if (temp == emailblank)
		temp="";
	
	var comma = temp.indexOf(",");
	var firstat = temp.indexOf("@");
	var secondat
	if (firstat > -1)
	{
		secondat = temp.indexOf("@",firstat+1);
		if (secondat > -1 && ((comma > -1  && secondat < comma) || comma==-1))
		{
			alert(baddelimiter);
			return false;
		}
	}
	inviteCounter++;
	
	if (inviteCounter > 1)
		return false;

	form.appendChild(getinput("emailinvites",temp));
	
	temp = 	document.getElementById("friendlist").value;
	if (temp == friendblank)
		temp="";
	
	form.appendChild(getinput("friendinvites",temp));
		
	temp = document.getElementById("foelist").value;
	if (temp == foeblank)
		temp="";
	
	form.appendChild(getinput("foeinvites",temp));
	
	temp = document.getElementById("message").value;
	if (temp == msgblank)
		temp="";
		
	form.appendChild(getinput("message",temp));
	
	form.appendChild(getinput("alert", document.getElementById("debatealert").checked));
	
	document.body.appendChild(form);
	form.submit();
	
}	


var panelCounter= 0;
function addPanelists(emailblank, baddelimiter, msgblank)
{
	var form = document.createElement("form");
	form.name="publish";
	form.method="post";
	form.enctype=enctype;
	form.action="/dbmgmt/action/addInvitations"; 
	form.acceptCharset="UTF-8";	
	var temp = document.getElementById("emailinvites").value;
	if (temp == emailblank)
		temp="";
	
	var comma = temp.indexOf(",");
	var firstat = temp.indexOf("@");
	var secondat
	if (firstat > -1)
	{
		secondat = temp.indexOf("@",firstat+1);
		if (secondat > -1 && ((comma > -1  && secondat < comma) || comma==-1))
		{
			alert(baddelimiter);
			return false;
		}
	}
	inviteCounter++;
	
	if (inviteCounter > 1)
		return false;

	form.appendChild(getinput("emailinvites",temp));
	
			
	temp = document.getElementById("message").value;
	if (temp == msgblank)
		temp="";
		
	form.appendChild(getinput("message",temp));
	
	form.appendChild(getinput("alert", document.getElementById("debatealert").checked));
	
	document.body.appendChild(form);
	form.submit();
	
}

function trywith(item)
{
	document.getElementById(item).click();
	return false;
}

function setFactory()
{
	for (var i =0;i< factories.length;i++)
		{
			try
			{
				factory = factories[i];
				if (factory()!=null)
					break;
			}
			catch (e)
			{
				continue;
			}
			
		}
}

function swapreplaceable(userid, newtab)
{
	var dvEl = document.getElementById("replaceable");
	if (factory==null)
	{
		setFactory();	
	}
	var dt = new Date();
	var xreq = factory();
	
	document.body.style.cursor="progress";
	if (newtab=='alerttab')
	{
		xreq.open("POST","/dbmgmt/action/getAlerts",false);
		xreq.setRequestHeader("Content-type","application/x-www-form-urlencoded");
		xreq.send(null);
		activateProfileTab('alerttab', userid);
	}
	else if (newtab=="conttab")
	{
		xreq.open("POST","/dbmgmt/action/getContributions",false);
		xreq.setRequestHeader("Content-type","application/x-www-form-urlencoded");
		xreq.send(null);
		activateProfileTab('conttab', userid);
	}
	else if (newtab=="settingstab")
	{
		xreq.open("POST","/dbmgmt/action/getProfileSettings",false);
		xreq.setRequestHeader("Content-type","application/x-www-form-urlencoded");
		xreq.send(null);
		activateProfileTab('settingstab', userid);
	}
	else if (newtab=="notetab")
	{
		xreq.open("POST","/dbmgmt/action/getNotepad",false);
		xreq.setRequestHeader("Content-type","application/x-www-form-urlencoded");
		xreq.send(null);
		activateProfileTab('notetab', userid);
	}
	else if (newtab=="invitestab")
	{
		xreq.open("POST","/dbmgmt/action/getInvites",false);
		xreq.setRequestHeader("Content-type","application/x-www-form-urlencoded");
		xreq.send(null);
		activateProfileTab('invitestab', userid);
	}
	if (xreq.status == 401)
		location.href = "/dbmgmt/debate/main";
	else
		dvEl.innerHTML=xreq.responseText;
	document.body.style.cursor="default";
	return false;
}

function activateProfileTab(tabname, userid)
{
	var profiletabs = new Array();
	profiletabs[0]='conttab';
	profiletabs[1]='alerttab';
	profiletabs[2]='settingstab';
	profiletabs[3]='notetab';
	profiletabs[4]='invitestab';
	
	
	
	for (var i = 0; i < profiletabs.length; i++)
	{
		if (profiletabs[i]==tabname)
		break;	
	}
	
	
	for (var j=0; j < profiletabs.length; j++ )
	{
		var tab=document.getElementById(profiletabs[j])
		if (j==i)
		{
			tab.className="current";
			var anch = tab.childNodes[0];
			anch.href="";
			anch.onclick="";
		}
		else
		{
			tab.className="";
			var anch = tab.childNodes[0];
			anch.href="";
			anch.onclick=new Function("swapreplaceable("+userid+",'"+profiletabs[j]+"');return false;");
		}
	}
	return false;
	
}

function removealert(debateid, rowpos, text)
{
	if (!confirm(text))
		return false;
		
	var alerttable = document.getElementById("alertdebates");
	if (factory==null)
	{
		setFactory();
	}
	var xreq = factory();
	xreq.open("POST","/dbmgmt/action/removeAlert");
	xreq.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	var ting='debateid='+debateid;
	xreq.send(ting);
	for (var i=0; i < alerttable.rows.length; i++)
	{
		if (alerttable.rows[i].getAttribute("pos")==rowpos)
		{
			alerttable.deleteRow(i+i);
			alerttable.deleteRow(i);
			break;
		}
	}
	return false;
}



function toggleDebateAlert(debateid, setting, yestext, notext)
{
	var dt = new Date();
	debateAlertImg.src="/dbmgmt/action/setAlert?debateid="+debateid+"&setting="+setting+"&counter="+dt.getTime()
	debateAlertImg.onload=function(){	if (this.width==10 && this.height ==10)
	{
		//not auth so out of here - probably session expired.
		location.href="/dbmgmt/debate/main";
		return false;
	}}
	var cbox = document.getElementById("alertcheckbox"+debateid);
	var img = document.getElementById("debatealert"+debateid);
	if (setting=='activate')
	{
		cbox.src="/dbmgmt/webpages/images/selected.png";
		//cbox.setAttribute("onclick","swapAlertImage('"+debateid+"','no','"+yestext+"','"+notext+"');");// this doesn't work in IE, left it here for everyone else.
		cbox.onclick = function(){toggleDebateAlert(debateid,'no',yestext,notext);};
		img.src = "/dbmgmt/webpages/images/watching.png";
	}
	else
	{
		//cbox.setAttribute("onclick","swapAlertImage('"+debateid+"','yes','"+yestext+"','"+notext+"');");// this doesn't work in IE, left it here for everyone else.
		cbox.onclick = function(){toggleDebateAlert(debateid,'activate',yestext,notext);};
		cbox.src = "/dbmgmt/webpages/images/unselected.png";
		img.src = "/dbmgmt/webpages/images/alertme.png";
	}
	return false;
}

function registerdniuser()
{
	var displayname = document.getElementById("displayname").value;
	if (displayname == null || displayname.length == 0)
	{
		alert("display name missing");
		return false;
	}		
	
	if (!isDisplayNameUsable(displayname))
	{
		alert("User name is already used - try a different one");
		return false;
	}
	else
	{
		location.href="/dbmgmt/authaction/registerdniuser";
		return false;
	}
}

function isDisplayNameUsable(displayname)
{
	if (factory==null)
	{
		setFactory();
	}
	var xreq = factory();
	xreq.open("POST","/dbmgmt/authaction/checkdisplayname",false);
	xreq.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	var ting='value='+encodeURIComponent(displayname).replace(/%20/g,"+");
	ting += "&outputformat=purexml";
	xreq.send(ting);
	if (xreq.status != 200 || xreq.responseText == 'not ok')
	{
		return false;
	}
	else
	{
		return true;
	}
}

function closeDebate(debateid)
{
	var closeDiv = document.getElementById("closure");
	closeDiv.style.visibility = 'visible';
	closeDiv.style.zIndex=50;
	closeDiv = document.getElementById("HGUS_ForNewComment");
	closeDiv.style.visibility='hidden';
	closeDiv = document.getElementById("HGUS_AgainstNewComment");
	closeDiv.style.visibility='hidden';
	closeDiv = document.getElementById("closedebatebutton");
	closeDiv.style.visibility='hidden';
	if (factory==null)
	{
		setFactory();
	}
	var xreq = factory();
	xreq.open("POST","/dbmgmt/action/startDebateClosure");
	xreq.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	var ting='value='+debateid;
	xreq.send(ting);
}


function cancelCloseDebate(debateid)
{
	var closeDiv = document.getElementById("closure");
	closeDiv.style.visibility = 'hidden';
	closeDiv.style.zIndex=50;
	closeDiv = document.getElementById("HGUS_ForNewComment");
	closeDiv.style.visibility='visible';
	closeDiv = document.getElementById("HGUS_AgainstNewComment");
	closeDiv.style.visibility='visible';
	closeDiv = document.getElementById("closedebatebutton");
	closeDiv.style.visibility='visible';
	if (factory==null)
	{
		setFactory();
	}
	var xreq = factory();
	xreq.open("POST","/dbmgmt/action/cancelDebateClosure");
	xreq.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	var ting='value='+debateid;
	xreq.send(ting);
}

function saveClosureInProgress(debateid)
{
	var title = document.getElementById("closuretitle");
	var text = document.getElementById("closuretext");
	if (factory==null)
	{
		setFactory();
	}
	var xreq = factory();
	xreq.open("POST","/dbmgmt/action/saveDebateClosureWIP");
	xreq.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	var ting='debateid='+debateid;
	ting += "&title="+encodeURIComponent(title.value).replace(/%20/g,"+");
	ting+="&text="+encodeURIComponent(text.value).replace(/%20/g,"+");
	xreq.send(ting);
	
}
function sendClosure(debateid)
{
	var title = document.getElementById("closuretitle");
	var text = document.getElementById("closuretext");
	var form = document.createElement("form");
	form.name="closureform";
	form.method="post";
	form.enctype=enctype;
	form.action="/dbmgmt/action/saveDebateClosure"; 
	form.acceptCharset="UTF-8";
	form.appendChild(getinput("debateid", debateid));
	form.appendChild(getinput("title", title.value));
	form.appendChild(getinput("text", text.value));
	document.body.appendChild(form);
	form.submit();
	return false;
}

function validateMarketRegistration()
{
	var valForm = document.getElementById("HGRegister");
	for (var i=0; i < valForm.elements.length; i++)
	{
		if (valForm[i].value=="")
		{
			alert(valForm[i].name+" is empty - please fill");
			return false;
		}
	}
}	


function validateMarketSubscription()
{
	var valForm = document.getElementById("HGSubscribe");
	for (var i=0; i < valForm.elements.length; i++)
	{
		if (valForm[i].value=="")
		{
			alert(valForm[i].name+" is empty - please fill");
			return false;
		}
	}
}

function checkSubscriberDisplayName()
{
	var fld = document.getElementById("name");
	var displayname = fld.value;
	if (displayname == null || displayname.length == 0)
	{
		alert("Name cannot be empty");
		fld.focus();
		return false;
	}
	
	if (!isDisplayNameUsable(displayname))
	{
		alert(displayname+" is already in use, please try another one");
		fld.value="";
		fld.focus();
		return false;
	}
}

function validateUrls(badurlmessage)
{
	var urltext = document.getElementById("inurls");
	var urls = urltext.value.split("\n");
	var goodurls="";
	var badurls="";
	//var tester = new RegExp(/\https?:\/\/(www\.)?[a-z0-9-^;]*\.[a-z][a-z][a-z]?[a-z0-9\-_\/^:]*\??.*/i);
	var tester = new RegExp(/https?:\/\/(www\.)?[a-z0-9-^;].*.?[a-z0-9-^;]*\.[a-z][a-z][a-z]?[a-z0-9\-_\/^:]*\??.*/i);
	if (urls.length == 0)
		return;
	for (i = 0; i < urls.length; i++)
	{
		if (tester.test(urls[i]))
			goodurls += urls[i] + "\n";
		else if (tester.test("http://"+urls[i]))
			goodurls += "http://"+urls[i]+"\n";
		else
			badurls += urls[i] + "\n";
	}
	urltext.value=goodurls;
	if (badurls.length>1)
	{
		var cont = confirm(badurlmessage+badurls);
		badurls="";
		if (!cont)
			return false;
	}
	var form = document.createElement("form");
	form.name="urlblockform";
	form.method="post";
	form.enctype="multipart/form-data";
	form.encoding=form.enctype;
	form.action="/dbmgmt/action/addBlockUrls"; 
	form.acceptCharset="UTF-8";
	form.appendChild(getinput("urls", goodurls));
	form.appendChild(getinput("newdebate",document.getElementById("newdebate").value));
	form.appendChild(getinput("frequency",document.getElementById("frequency").value))
	document.body.appendChild(form);
	form.submit();
	return false;
}	

function oktopostanonymous(side, placeholder)
{
	var item = document.getElementById("span-"+side);
	var title = document.getElementById("title-"+side);
	var area = document.getElementById("area-"+side);
	var img = document.getElementById("img-"+side);
	var div = document.getElementById("div-"+side);
	
	if (area.value == "" || area.value== placeholder)
	{
		div.style.display='none';
		item.className=""
	}
	else if (area.value != "" )
	{
		item.className="anonymous";
		div.style.display="";
		
	}
}

function postanonymous(side, captchatext, title, text, debateid, badmsg)
{
	var ctext = document.getElementById(captchatext).value;
	if (factory==null)
	{
		setFactory();
	}
	var xreq = factory();
	xreq.open("POST","/dbmgmt/authaction/checkforpost",false);
	xreq.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	var ting='value='+encodeURIComponent(ctext)+"&debateid="+debateid;
	ting += "&outputformat=purexml";
	xreq.send(ting);
	if (xreq.status != 200 || xreq.responseText == 'not ok')
	{
		alert(badmsg);
		getCaptcha(side);
		return false;
	}
	else
	{
		var form = document.createElement("form");
		form.name="anonpost";
		form.method="post";
		form.enctype=enctype;
		form.action="/dbmgmt/authaction/postanonymousargument"; 
		form.acceptCharset="UTF-8";
		form.appendChild(getinput("title", document.getElementById(title).value));
		form.appendChild(getinput("posting",document.getElementById(text).value));
		form.appendChild(getinput("debateid",debateid));
		form.appendChild(getinput("side",side));
		if (respargid!=null)
		{
			form.appendChild(getinput("respargid",respargid));
		}
		document.body.appendChild(form);
		form.submit();
		respargid = null;
	}
}	

function removeImage()
{

	var newInp = document.createElement("input");
	newInp.type="file";
	newInp.maxlength="256";
	newInp.align="bottom";
	newInp.cssText = "margin-top:2px; width:220px;  border:1px solid #CCCCCC; background-image: url('Title.png');";
	newInp.id = "file-0-0";
	newInp.onchange=new Function("uploadfile('file','-0-0');return false;");
	var destdiv = document.getElementById("debateimageupload");
	destdiv.appendChild(newInp);
	var img = document.getElementById("debuploadimg");
	img.style.display="none";
	var docname = document.getElementById("file-hidden-0-0");
	docname.style.display="none";
}
function uploadfile(name, suffix)
{
	var frame = document.createElement("iframe");
	frame.style.display = "none";
	var now = new Date().getTime();
	frame.id = 'name'+now;
	frame.name = 'name'+now;
	var form = document.createElement("form");
	form.name="uploadfile";
	form.method="post";
	form.enctype="multipart/form-data";
	form.encoding=form.enctype;
	form.action="/dbmgmt/action/UploadFile";
	form.target = 'name'+now;
	var fileinp = document.getElementById(name+suffix);
	var docname = document.getElementById(name+"-hidden"+suffix);
	docname.value = fileinp.value;
	docname.style.display=fileinp.style.display;
	var img = document.getElementById("debuploadimg");
	img.style.display=fileinp.style.display;
 
	if (docname.value != '')
	{
		form.appendChild(getinput("imagetitle",document.getElementById("imagetitle").value));
		form.appendChild(getinput("filename",fileinp.value));
		form.appendChild(fileinp);
	}
	document.body.appendChild(frame);
	frame.appendChild(form);
	form.submit();
	fileinp.id="lost";
	
	return false;
}

function uploadevidence(name, suffix, tablenum)
{
	var frame = document.createElement("iframe");
	frame.style.display = "none";
	var now = new Date().getTime();
	frame.id = 'name'+now;
	frame.name = 'name'+now;
	var form = document.createElement("form");
	form.name="uploadfile";
	form.method="post";
	form.enctype="multipart/form-data";
	form.encoding=form.enctype;
	form.action="/dbmgmt/action/UploadFile";
	form.target = 'name'+now;
	var fileinp = document.getElementById(name+"-"+tablenum+"-"+suffix);
	addChecked(fileinp.value,fileinp.value,fileinp.value,tablenum, false)
 	
	if (fileinp.value != '')
	{
		form.appendChild(getinput("filename",fileinp.value));
		form.appendChild(fileinp);
	}
	document.body.appendChild(frame);
	frame.appendChild(form);
	form.submit();
	var div = document.getElementById("file-evidence-"+tablenum);
	var input = document.createElement("input");
	input.type="file";
	input.style.width='450px';
	input.maxlength="256";
	input.size="35";
	var temp = Number(suffix) + 1;
	input.id = "file-evidence-"+tablenum+"-"+temp;
	input.name = "file-evidence-"+tablenum+"-"+temp;
	input.onchange = new Function("uploadevidence('file-evidence',"+temp+","+tablenum+");return false;");
	div.appendChild(input);
	return false;
}

var respargid = null;
function setupReply(argid, pos, name, resptext)
{
	var inp = document.getElementById('title-pro');
	inp.value=resptext+name+" @"+pos+" ";
	inp = document.getElementById('title-con');
	inp.value=resptext+name+" @"+pos+" ";
	respargid = argid;
}	

function switchsides(dbargid)
{
	var form = document.createElement("form");
	form.name="uploadfile";
	form.method="post";
	form.enctype=enctype;
	form.encoding=form.enctype;
	form.action="/dbmgmt/action/SwitchSides";
	form.appendChild(getinput("dbargid",dbargid));
	document.body.appendChild(form);
	form.submit();
	return false;
	
}

function checkDelete(msg, argid, debateid)
{
	if (confirm(msg))
	{
		var form = document.createElement("form");
		form.name="deleteArgument";
		form.method="post";
		form.enctype=enctype;
		form.encoding=form.enctype;
		form.action="/dbmgmt/action/deleteWebSurvey";
		form.appendChild(getinput("argid",argid));
		form.appendChild(getinput("debateid", debateid))
		document.body.appendChild(form);
		form.submit(); 
	}
	return false;
}
var bridge = new Object();
bridge.replaceHeader = replaceHeader;
function replaceHeader(thing)
{
	return false;
}