//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// site-specific declarations
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
var m_blnDoBodyUnload = false;
var m_winAddressManager;
var m_BlinkTopAlertBarTID;

//the following "BarHeight" values MUST equal height + border-width as defined in global_base.css
var m_iTopAlertBarHeight = 21;
var m_iTopToolBarHeight = 25;

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// site-specific functions
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function WriteAdminNavBar(LinkedMemberExists, HasMemberAuthID, MemberName, IsContentAdmin)
{
	try{if(m_blnSuppressAdminNavBar) return;}catch(e){};
	
	var sContent = '';
	if(HasMemberAuthID) {
		sContent += '<div style="float:left">YOU ARE SIGNED IN AS: ';
		sContent += ('<span style="text-transform:uppercase">'+ MemberName);
		sContent += '</span> (<a href="/general/logout.asp">SIGN OUT</a>)&nbsp;&nbsp;</div>';
		sContent += '<div style="float:right">';
	} else if(LinkedMemberExists) {
		sContent += '<div style="float:center">';
		sContent += '<a href="/general/login_admin_as_linked_member.asp">SIGN IN TO THE COMMUNITY</a>&nbsp; ';
	} else {
		sContent += '<div style="float:center"> ';
	}
	
	sContent += '&nbsp;&nbsp;<a href="/admin/">RETURN TO BACKEND</a>';
	
	if(IsContentAdmin) {
		sContent += ' &nbsp; &nbsp;<a href="#" onclick="openPopup(\'/admin/content/resource_manager.asp\',\'winResMgr\',\'toolbar=false,status,scrollbars,resizable\',\'700\',\'600\'); return false;">SITE RESOURCE MANAGER</a>';
	}
	
	sContent += '</div>';
	
	WriteTopAlertBar(sContent);
}

function WriteTopAlertBar(sContent, iBlinks)
{
	var TopAlertBarText = document.getElementById('TopAlertBarText');
	if(TopAlertBarText)
	{	//update alert bar text
		TopAlertBarText.innerHTML = sContent;
	} else {
		//create the alert bar
		var TopAlertBar = document.createElement('div');
		TopAlertBar.setAttribute('id','TopAlertBar');
		
		TopAlertBarText = document.createElement('div');
		TopAlertBarText.setAttribute('id','TopAlertBarText');
		
		TopAlertBarText.onmouseover = function(){
			document.getElementById('TopAlertBarText').style.display = '';
			clearTimeout(m_BlinkTopAlertBarTID);
		};
		
		TopAlertBarText.innerHTML = sContent;
		TopAlertBar.appendChild(TopAlertBarText);
		
		var docBody = document.getElementsByTagName('body')[0];
		var iMarginTop = parseInt(docBody.style.marginTop);
		if(isNaN(iMarginTop)) iMarginTop = 0;
		iMarginTop = ((iMarginTop*1)+(m_iTopAlertBarHeight*1));
		
		docBody.appendChild(TopAlertBar);
		docBody.style.marginTop = iMarginTop.toString()+'px';
	}
	
	if((!isNaN(iBlinks)) && iBlinks>0) BlinkTopAlertBar(iBlinks);
}

function WriteTopToolBar(sContent)
{
	var TopToolBarText = document.getElementById('TopToolBarText');
	if(TopToolBarText)
	{	//update top toolbar text
		TopToolBarText.innerHTML = sContent;
	} else {
		//create the toolbar
		var iTop = 0;
		if(document.getElementById('TopAlertBar')) {
			iTop = (m_iTopAlertBarHeight*1);
		}
		
		var TopToolBar = document.createElement('div');
		TopToolBar.setAttribute('id','TopToolBar');
		TopToolBar.style.top = iTop.toString();
		
		TopToolBarText = document.createElement('div');
		TopToolBarText.setAttribute('id','TopToolBarText');
		
		TopToolBarText.innerHTML = sContent;
		TopToolBar.appendChild(TopToolBarText);
		
		var docBody = document.getElementsByTagName('body')[0];
		var iMarginTop = parseInt(docBody.style.marginTop);
		if(isNaN(iMarginTop)) iMarginTop = 0;
		iMarginTop = ((iMarginTop*1)+(m_iTopToolBarHeight*1));
		
		docBody.appendChild(TopToolBar);
		docBody.style.marginTop = iMarginTop.toString()+'px';
	}
}

function BlinkTopAlertBar(HowManyTimes, i)
{
	if(isNaN(i)) i = 1;
	
	if(i%2==0) {
		document.getElementById('TopAlertBarText').style.display = '';
	} else {
		document.getElementById('TopAlertBarText').style.display = 'none';
	}
	
	if(i<(HowManyTimes*2)) {
		i++;
		m_BlinkTopAlertBarTID = setTimeout(function(){ BlinkTopAlertBar(HowManyTimes, i) }, 300);
	}
}

function CheckCityStateZip(oForm,sCityField,sZipField,sStateField,sStateList)
{
	if(eval('oForm.'+sCityField).value=='') return false;
	if(eval('oForm.'+sZipField).value=='') return false;
	if(eval('oForm.'+sStateField).value=='')
	{
		var oStateList = eval('oForm.'+sStateList);
		if(oStateList.options[oStateList.selectedIndex].value=='') return false;
	}
	
	return true;
}

function CheckMultipartForms(blnAllowSubmit)
{
	if(blnAllowSubmit) return;
	if(!document.forms.length>0) return;
	
	var blnFoundOne = false;
	for(var i = 0; i<document.forms.length; i++)
	{
		if(document.forms[i].enctype.toLowerCase()=='multipart/form-data')
		{
			blnFoundOne = true;
			document.forms[i].onsubmit = function(){return false;}
		}
	}
	
	if(blnFoundOne) alert('We\'\re sorry, file uploads and forms containing file uploads\nhave been temporarily disabled. Please check back in a few minutes.');
}

function DoUploadProgress(sender)
{	//does the hidden field exist for storing the progress-id?
	var sUid = '', sPid = '';
	if(sender.UploadID) {
		sUid = sender.UploadID.value;
	} else if(sender.ProgressID) {
		sPid = sender.ProgressID.value;
	} else {
		return true;
	}
	
	//are there any files being uploaded?
	var fields = sender.elements;
	var bHasFile = false;
	FieldLoop: for(var i=0; i<fields.length; i++) {
		if(fields[i].type.toLowerCase()=='file' && fields[i].value!='') {
			bHasFile = true;
			break FieldLoop;
		}
	}
	
	if(!bHasFile) return true;
	
	var sAction = sender.action;
	
	var rx = new RegExp("\\?.+=","i");
	if(rx.test(sAction)) {
		sAction +='&';
	} else {
		rx.compile("\\?$","i");
		if(!rx.test(sAction)) sAction +='?';
	}
	
	var sIdArg = sUid.length>0 ? 'uid='+ sUid : 'pid='+ sPid;
	
	sAction += sIdArg;
	sender.action = sAction;
	
	openPopup('/general/upload_progress.asp?'+ sIdArg,'UploadProgress','status,toolbar=false',250,120);
	
	return true;
}

function openCsvExport(unicode,alternateUrl,extraQueryArgs)
{
	var Url = alternateUrl==null ? '/admin/database/csv_export.asp' : alternateUrl;
	if(extraQueryArgs==null) extraQueryArgs = '';
	openPopup(Url +'?unicode='+ unicode.toString() +'&'+ extraQueryArgs.toString(),'_blank','resizable,status,toolbar=false',350,150);
	return false;
}

//address-manager window functions
function openAddressManager(AddrMgrUrl,MasterElementId,QueryArgs)
{
	m_winAddressManager = returnPopup(AddrMgrUrl+'?OpenerMasterElementId='+MasterElementId+'&'+QueryArgs,'AddressManager','resizable,scrollbars,status,toolbar=false',660,475);
	m_winAddressManager.focus()
	return false;
}

function closeAddressManager()
{
	try{m_winAddressManager.close();}catch(e){};
}

function openMugshotPopup(Url)
{
	return openPopup(Url,'MemberMugshot','resizable,scrollbars,status,toolbar=false',537,405);
}

function openPrintView(Url, OpenDialog, QueryArgs)
{
	openPopup(Url +"?PrintView=1&OpenDialog="+ OpenDialog +"&"+ QueryArgs,
		"PrintView","menubar,scrollbars,status,toolbar=false",640,640);
	return false;
}

//begin dynamic help functions
var m_blnInlineHelpIsOn = false;

function switchInlineHelpDisplay()
{
	if(m_blnInlineHelpIsOn)
	{
		doInlineHelpOff();
	} else {
		doInlineHelpOn();
	}
	return false;
}

function doInlineHelpOn()
{
	//show inline help areas
	setInlineHelpDisplay('block');
	//switch toggle link
	dhtmlDisplay('InlineHelpLinkShow','none');
	dhtmlDisplay('InlineHelpLinkHide','');
	//set current state
	m_blnInlineHelpIsOn = true;
	//preserve current state in cookie
	setInlineHelpCookie();
}

function doInlineHelpOff()
{
	//hide inline help areas
	setInlineHelpDisplay('none');
	//switch toggle link
	dhtmlDisplay('InlineHelpLinkShow','');
	dhtmlDisplay('InlineHelpLinkHide','none');
	//set current state
	m_blnInlineHelpIsOn = false;
	//preserve current state in cookie
	setInlineHelpCookie();
}

function setInlineHelpCookie()
{
	if(document.cookie)
	{	//set cookie expiry at 1 year
		var datExpires = new Date();
		datExpires.setTime(datExpires.getTime()+31536000000);
		if(m_blnInlineHelpIsOn)
		{
			document.cookie = 'InlineHelpDisplay=InlineHelpDisplayOn; expires='+datExpires.toGMTString()+'; path=/';
		} else {
			document.cookie = 'InlineHelpDisplay=InlineHelpDisplayOff; expires='+datExpires.toGMTString()+'; path=/';
		}
	}
}

function setInlineHelpDisplay(value)
{
	setInlineHelpDisplayItems(document.anchors,value);
	setInlineHelpDisplayItems(document.links,value);
}

function setInlineHelpDisplayItems(items,value)
{
	for(var i=0;i<items.length;i++)
	{
		if(items[i].className.toLowerCase()=='inlinehelp')
		{
			items[i].style.display = value.toString();
		}
	}
}

function initInlineHelpDisplay()
{
	if((document.cookie)&&(document.cookie.toString().indexOf('InlineHelpDisplayOff')>=0))
	{
		doInlineHelpOff();
	} else {
		doInlineHelpOn()
	}
}

function mediaPopup(theURL) {
	openPopup(theURL,'winMediaPopup','status,toolbar=false',622,496);
	return false;
}

function AlertAppUpdate()
{
	if(confirm('There have been updates to the\nsystem since your last visit!\n\nClick OK to review the latest features, \nenhancements and bug fixes.'))
		location.href='/admin/client_services/updates.asp';
}

function ConfirmSignIn(strMemberName)
{
	return confirm('You will now be signed in as '+ strMemberName +'. \n\nAre you sure you want to continue? ');
}

//search form functions
function SearchForm_q_OnKeyPress(e,sender)
{
	if(getkey(e)==13) {
		return SearchForm_Validate(sender);
	}
	return true;
}

function SearchForm_Validate(sender, element)
{
	if(!element) element = sender.form.q;
	
	var sVal = element.value;
	
	if(sVal=='' || /^[\s]+$/.test(sVal))
	{
		alert('Please enter some search criteria. ');
		element.focus();
		return false;
	}
	
	return true;
}

function StartNewSearch(FormId)
{
	var SearchForm = document.getElementById(FormId);
	if(SearchForm)
	{
		SearchForm.q.value = '';
		SearchForm.style.display = '';
		SearchForm.q.focus();
	}
	return false;
}

function FilterSearchByCatalog(CatalogEnum)
{
	var win = (parent) ? parent : self;
	var sQuery = win.location.search.replace(/\&?c=[^\&]*\&?/, "");
	if (sQuery.length == 0) {
		sQuery = '?';
	} else if (sQuery != '?') {
		sQuery += '&';
	}

	win.location.href = win.location.pathname + sQuery + "c=" + CatalogEnum.toString();

	return false;
}

function emoticon(code, txtarea)
{
	if((!txtarea) || typeof(txtarea)=='undefined') {
		txtarea = document.frmMessage.strBody;
	}
	
	try { insertAtCaret(txtarea, code) } catch(e) {}
}

var m_bYuiGenericDialogResult;

function YuiGenericDialog(Id, BodyText, Callback, TrueText, FalseText, ContainerId, PanelWidth)
{
	if(!objectExists(TrueText)) TrueText = 'Yes';
	if(!objectExists(FalseText)) FalseText = 'No';
	if(!objectExists(PanelWidth)) PanelWidth = '300px';
	
	var dialog = new YAHOO.widget.SimpleDialog(Id, {
		text:BodyText,
		iframe:false,
		visible:false,
		close:false,
		draggable:false,
		fixedcenter:true,
		constraintoviewport:true,
		modal:true,
		postmethod:'none',
		underlay:'shadow',
		width:PanelWidth }
	);
	
	dialog.setHeader("Attention");
	dialog.cfg.setProperty("icon",YAHOO.widget.SimpleDialog.ICON_HELP);
	
	dialog.cfg.queueProperty("buttons", [
	{ text:TrueText, handler:function() {
		m_bYuiGenericDialogResult = true;
		this.hide();
		Callback();
	}, isDefault:true },
	{ text:FalseText, handler:function() {
		m_bYuiGenericDialogResult = false;
		this.hide();
		Callback();
	}}
]);
	
	if(!objectExists(ContainerId)) ContainerId = "PageBase_RaiseAlert";
	
	var container = document.getElementById(ContainerId);
	if(!container) return;
	
	m_bYuiGenericDialogResult = null;
	
	dialog.render(container);
	dialog.show();
}

function YuiGenericDialogCallback_ButtonClick(button)
{
	if(m_bYuiGenericDialogResult) {
		button.onclick = function() { return true; }
		button.click();
	}
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// common functions
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function getCurrentTime()
{
	var now = new Date();
	return now.getTime();
}

function fixnewlines(val)
{             
	// Adjust newlines so can do correct character counting for MySQL. MySQL counts a newline as 2 characters.
	if (val.indexOf('\r\n')!=-1)
	; // this is IE on windows. Puts both characters for a newline, just what MySQL does. No need to alter
	else if (val.indexOf('\r')!=-1)
		val = val.replace ( /\r/g, "\r\n" ); // this is IE on a Mac. Need to add the line feed
	else if (val.indexOf('\n')!=-1)
		val = val.replace ( /\n/g, "\r\n" ); // this is Firefox on any platform. Need to add carriage return
	else 
	; // no newlines in the textarea  
	return val;
}

function objectExists(o)
{
	if(typeof o=='undefined' || o==null) return false;
	return true;
}

function isEmpty(val)
{
	return (!val || val==null || val.toString()=='');
}

function replaceAccents(sVal)
{
	var RetVal = new String(sVal);
	
	var regExps = [ /[\xC0-\xC5]/g,
		/[\xE0-\xE5]/g,
		/[\xC8-\xCB]/g,
		/[\xE8-\xEB]/g,
		/[\xCC-\xCF]/g,
		/[\xEC-\xEF]/g,
		/[\xD2-\xD6]/g,
		/[\xF2-\xF6]/g,
		/[\xD9-\xDC]/g,
		/[\xF9-\xFC]/g,
		/\xDD/g, /\xFD/g,
		/\xC7/g, /\xE7/g,
		/\xD1/g, /\xF1/g ];
	
	var repChar = ['A','a','E','e','I','i','O','o','U','u','Y','y','C','c','N','n'];
	
	for(var i=0; i<regExps.length; i++)
		RetVal = RetVal.replace(regExps[i],repChar[i]);
	
	return RetVal;
}

function replaceReturns(sVal)
{
	var RetVal = fixnewlines(sVal.toString());
	return RetVal.replace(/\r\n/g,'<br/>');
}

function insertAtCaret(obj, text)
{
	if(document.selection) {
		obj.focus();
		var orig = obj.value.replace(/\r\n/g, "\n");
		var range = document.selection.createRange();

		if(range.parentElement() != obj) {
			return false;
		}

		range.text = text;
		
		var actual = tmp = obj.value.replace(/\r\n/g, "\n");

		for(var diff = 0; diff < orig.length; diff++) {
			if(orig.charAt(diff) != actual.charAt(diff)) break;
		}

		for(var index = 0, start = 0; 
			tmp.match(text) 
				&& (tmp = tmp.replace(text, "")) 
				&& index <= diff; 
			index = start + text.length
		) {
			start = actual.indexOf(text, index);
		}
	} else if(obj.selectionStart) {
		var start = obj.selectionStart;
		var end   = obj.selectionEnd;

		obj.value = obj.value.substr(0, start) 
			+ text 
			+ obj.value.substr(end, obj.value.length);
	}
	
	if(start != null) {
		setCaretTo(obj, start + text.length);
	} else {
		obj.value += text;
	}
}

function setCaretTo(obj, pos) {
	if(obj.createTextRange) {
		var range = obj.createTextRange();
		range.move('character', pos);
		range.select();
	} else if(obj.selectionStart) {
		obj.focus();
		obj.setSelectionRange(pos, pos);
	}
}

function stripHtml(sVal)
{
	return sVal.toString().replace(/<[\?\/!A-Za-z]+[^<>]*>?/ig,' ');
}

function urlDecode(sVal)
{
	if(isEmpty(sVal)) return sVal;
	return decodeURIComponent(sVal.toString()).replace(/\+/g, ' ');
}

function setCookie(name, value, path, expiredays)
{
	var sCookie = name +'='+ escape(value);
	
	if(expiredays && typeof(expiredays)!='undefined') {
		var exdate = new Date();
		exdate.setDate(exdate.getDate()+expiredays);
		sCookie += ('; expires='+ exdate.toGMTString());
	}
	
	if(path && typeof(path)!='undefined') sCookie += ('; path='+ path);
	
	document.cookie = sCookie;
}

function getCookie(name)
{
	if((!document.cookie) || document.cookie.length==0) return '';
	
	var iStart = document.cookie.indexOf(name +'=');
	if(iStart>=0) { 
		iStart += (name.length+1);
		var iEnd = document.cookie.indexOf(";",iStart);
		if(iEnd<0) iEnd = document.cookie.length;
		return unescape(document.cookie.substring(iStart,iEnd));
	}
	
	return '';
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// helpers for wiring-up event handlers
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function addEventHandler_OnLoad(oFunc)
{
	var oldHandler = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = oFunc;
	} else {
		window.onload = function() {
			oldHandler();
			oFunc();
		}
	}
}

function addEventHandler_OnUnload(oFunc)
{
	var oldHandler = window.onunload;
	if (typeof window.onunload != 'function') {
		window.onunload = oFunc;
	} else {
		window.onunload = function() {
			oldHandler();
			oFunc();
		}
	}
}

function addEventHandler_OnLoadAndUnload(oFunc)
{
	addEventHandler_OnLoad(oFunc);
	addEventHandler_OnUnload(oFunc);
}

function addEventHandler_OnSubmit(oForm,oFunc)
{
	var oldHandler = oForm.onsubmit;
	if (typeof oForm.onsubmit != 'function') {
		oForm.onsubmit = oFunc;
	} else {
		oForm.onsubmit = function() {
			oldHandler();
			oFunc();
		}
	}
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// window functions
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
var blnRefreshWindow = false;

function getWinSize()
{
	var iWinW = 0;
	var iWinH = 0;
	if(typeof(window.innerWidth)!='undefined')
	{
		iWinW = window.innerWidth;
		iWinH = window.innerHeight;
	} else {
		var d = document;
		if(d.documentElement && typeof(d.documentElement.clientWidth)!='undefined' && 
			d.documentElement.clientWidth!==0)
		{
			iWinW = d.documentElement.clientWidth;
			iWinH = d.documentElement.clientHeight;
		} else if(document.body && typeof(d.body.clientWidth)!='undefined')
		{
			iWinW = d.body.clientWidth;
			iWinH = d.body.clientHeight;
		}
	}
	
	var aRetVal = new Array(1);
	aRetVal[0] = iWinW;
	aRetVal[1] = iWinH;
	
	return aRetVal;
}

function windowIsOpen(objWindow)
{
	var blnIsOpen = false;
	
	if (typeof(objWindow)=='object') {
		if (!objWindow.closed) {
			blnIsOpen = true;
		}
	}
	return blnIsOpen;
}

function setOpenerRefresh()
{
	if (windowIsOpen(opener)) {
		opener.blnRefreshWindow = true;
	}
}

function reloadSelf()
{
	var now = new Date();
	var newHref = location.protocol +'//'+ location.hostname + location.pathname;
	var qString = location.search.replace(/\&?reloadtime=[^\&]*\&?/,'');
	
	if(qString.length==0) {
		qString = '?'
	} else if(qString!='?') {
		qString += '&';
	}
	
	newHref += qString +'reloadtime='+ now.getTime();
	
	location.href = newHref;
}

function refreshOpener(strDefaultURL,blnCloseMe)
{
	var blnExists = false;
	
	if (windowIsOpen(opener)) {
	 	if (opener.blnRefreshWindow==true) {
			opener.location.reload();
			opener.focus();
		}
		blnExists = true;
	}
	
	if (blnExists==false) {
		window.open(strDefaultURL);
		blnCloseMe = true;
	}
	
	if (blnCloseMe==true) window.close(self);
}

function openerLocation(strLocation,blnCloseMe)
{
	if (windowIsOpen(opener)) {
		opener.location.href=strLocation;
		if(blnCloseMe) opener.focus();
	} else {
		window.open(strLocation);
	}
	
	if(blnCloseMe) window.close(self);
}

function focusPopup(objPopup,theURL,winName,features,width,height)
{
	var blnIsOpen = true;
	if (typeof(objPopup) != 'object') {
		blnIsOpen = false;
	} else if (objPopup.closed) {
		blnIsOpen = false;
	}
	if (blnIsOpen== false) {
		objPopup = returnPopup(theURL,winName,features,width,height);
	}
	 objPopup.focus();
	 return objPopup;
}

function goToUrlOnClick(Url)
{
	location.href = Url;
	return false;
}

function openPopup(theURL,winName,features,width,height)
{
	var objPopup = returnPopup(theURL,winName,features,width,height);
	objPopup.focus();
}

function returnPopup(theURL,winName,features,width,height)
{
	var winWidth	= width;
	var winHeight	= height;
	var strWinSize	= ",width=" + winWidth + ",height=" + winHeight;

	if (window.screen) {
		var winPosL = (screen.availWidth - winWidth) / 2;
		var winPosT = (screen.availHeight - winHeight) / 2;
		strWinSize += ",left=" + winPosL + ",screenX=" + winPosL + ",top=" + winPosT + ",screenY=" + winPosT;
	}	
	
	return window.open(theURL,winName,features + strWinSize);
}

function closePopup()
{
	window.close(self);
}

function setWinStatus(value)
{
	window.status=value;
	return true;
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// form functions
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function addOptionToSelectList(DomID, value)
{
	var SelectList = document.getElementById(DomID);
	SelectList.options[SelectList.length] = new Option(value,value);
}

function removeSelectedOption(DomID)
{
	var SelectList = document.getElementById(DomID);
	SelectList.options[SelectList.selectedIndex] = null;
}

function addHiddenInputToForm(form, name, value)
{
	var newInput = document.createElement('INPUT');
	if(document.all) {
		newInput.type = 'hidden';
		newInput.id  = name;
		newInput.name = name;
		newInput.value = value;
	} else {
		newInput.setAttribute('type','hidden');
		newInput.setAttribute('id',name);
		newInput.setAttribute('name',name);
		newInput.setAttribute('value',value);
	}
	form.appendChild(newInput);
}

function ClearDefaultValue(o)
{
	if(o && o.value && o.defaultValue && o.value.toLowerCase()==o.defaultValue.toLowerCase()) o.value = '';
}

function checkRadioByValue(oRadio, value)
{
	if(oRadio) {
		if(oRadio.length>0)	{
			for(var i=0; i<oRadio.length; i++)
				oRadio[i].checked = (oRadio[i].value==value.toString());
		} else {
			oRadio.checked = (oRadio.value==value.toString());
		}
	}
}

function getCheckedRadioValue(oRadio)
{
	if(oRadio) {
		if(oRadio.length>0)	{
			for(var i=0; i<oRadio.length; i++) {
				if(oRadio[i].checked) return oRadio[i].value;
			}
		} else if(oRadio.checked) {
			return oRadio.value;
		}
	}
	return null;
}

function getSelectedText(elmnt)
{
	if(elmnt && elmnt.options) {
		return elmnt.options[elmnt.selectedIndex].text;
	}
	return '';
}

function getSelectedTextById(elementId)
{
	var elmnt = document.getElementById(elementId);
	return getSelectedText(elmnt);
}

function getSelectedValue(elmnt)
{
	if(elmnt && elmnt.options) {
		return elmnt.options[elmnt.selectedIndex].value;
	}
	return '';
}

function getSelectedValueById(elementId)
{
	var elmnt = document.getElementById(elementId);
	return getSelectedValue(elmnt);
}

function selectOptionByValue(oSelect, value)
{
	if(oSelect) {
		for(var i=0; i<oSelect.length; i++) {
			if(oSelect.options[i].value==value.toString()) {
				oSelect.selectedIndex = i;
				break;
			}
		}
	}
}

function verifyMsg(jsStrURL, jsStrMsg) 
{
	if (confirm (jsStrMsg)) 
	{		
		this.window.location=jsStrURL;
		return true;
	}
}

function CheckALL(objCheckbox)
{
	if (objCheckbox)
	{
		var len = objCheckbox.length;
		
		if (len > 0)
		{
			var i=0;
			for (i=0 ; i<len ; i++)
			{
				objCheckbox[i].checked=true;
			}
		} else {
			objCheckbox.checked=true;
		}
	}
}

function UnCheckALL(objCheckbox)
{
	if (objCheckbox)
	{
		var len = objCheckbox.length;
		
		if (len > 0)
		{
			var i=0;
			for (i=0 ; i<len ; i++)
			{
				objCheckbox[i].checked=false;
			}
		} else {
			objCheckbox.checked=false;
		}
	}
}

function formFocus(strFormname, strElement) 
{
	var objE = eval('document.' + strFormname + '.' + strElement);
	if (objE) objE.focus();
}

function buildHumanSQL(objElement, strHeadline) {

	var inputLocal	= objElement;
	var strSQLHuman	= '<b>' + strHeadline + '</b>\n';
		strSQLHuman	+='<ul>\n';
	
	if (inputLocal) {
		var len = inputLocal.length;
		var i=0;
		for (i=0 ; i<len ; i++) {
		
			if (inputLocal.options[i].selected) {
			
				strSQLHuman += '<li>' + inputLocal.options[i].text + '<br></li>\n';
			}
		}
	}
	
	strSQLHuman += '</ul>'
	objElement.form.txt_sqlHuman.value = strSQLHuman;
	return true;
}

function ClickOnCrKeyPress(e,button)
{
	if(getkey(e)==13)
	{
		button.click();
		return false;
	}
	else return true;
}

function DoOnCrKeyPress(e,oFunc)
{
	if(getkey(e)==13)
	{
		oFunc();
		return false;
	}
	else return true;
}

function SubmitOnCrKeyPress(e,sender)
{
	if(getkey(e)==13)
	{
		sender.form.submit();
		return false;
	}
	else return true;
}

function VoidOnCrKeyPress(e)
{
	return (getkey(e)!=13);
}

function getkey(e) {
	if (window.event)
	   return window.event.keyCode;
	else if (e)
	   return e.which;
	else
	   return null;
}

function confirmDelete(objForm, strElement, strValue)
{
	var ItemRow = document.getElementById(strValue.toString());
	var strPrevClass = '';
	
	if(ItemRow)
	{
		strPrevClass = ItemRow.className;
		ItemRow.className = 'delitem';
	}
	
	if(confirm('Are you sure you want to delete the selected item? '))
	{
		eval('objForm.'+ strElement).value = strValue;
		return true;
	}
	else
	{
		if(ItemRow) ItemRow.className = strPrevClass;
		return false;
	}
}

function InlineDelete_Submit(sender,keyfield,id)
{
	return confirmDelete(sender.form,keyfield,id);
}

function InlineItem_Delete(sender,ItemID)
{
	return confirmDelete(sender.form,'ItemID',ItemID);
}

//adds a new option to a userlist element
function UserListAdd(sender, ID, AllowComma, DefaultValue)
{
	var SelectList = eval('sender.form.'+ ID +'_select');
	var UserInput = eval('sender.form.'+ ID +'_input');
	
	if(SelectList && UserInput) {
		var val = stripHtml(UserInput.value.toString());
		if(!AllowComma) val = val.replace(/,/g,'');
		if(val!='') {
			SelectList.options[SelectList.length] = new Option(val,val);
			RebuildUserList(sender.form, ID);
		}
		if(DefaultValue!=null) UserInput.value = DefaultValue;
		try{ //IE throws an exception if the focus() method of an invisible object is called
			UserInput.focus();
		}catch(e){};
	}
}

//removes the selected option from a userlist element
function UserListRemove(sender, ID)
{
	var SelectList = eval('sender.form.'+ ID +'_select');
	if(SelectList) {
		SelectList.options[SelectList.selectedIndex] = null;
		RebuildUserList(sender.form, ID);
	}
}

//rebuilds the hidden value of a userlist element
function RebuildUserList(form, ID)
{
	var HiddenInput = eval('form.'+ ID);
	if(!HiddenInput) {
		addHiddenInputToForm(form, ID, '');
		HiddenInput = eval('form.'+ ID);
	}
	HiddenInput.value = '';
	
	var SelectList = eval('form.'+ ID +'_select');
	if(SelectList) {
		for(var i=0; i<SelectList.length; i++)
			HiddenInput.value += SelectList.options[i].value +'\r\n';
	}
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// DHTML display functions
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function adjustIFrameHeight(DomID)
{
	var frame = document.getElementById(DomID);
	var frameDoc = getIFrameDoc(DomID);
	
	if(frameDoc==null) return;
	
	frame.height = frameDoc.body.offsetHeight;
}

function getIFrameDoc(FrameID)
{
	var frame = document.getElementById(FrameID);
	var ret = null;
	
	if(frame.contentDocument)
	{	// W3C compliant (Mozilla)
		ret = frame.contentDocument;
	} else {
		// IE
		ret = document.frames[FrameID].document;
	}
	
	return ret;
}

function ul_onclick(jsObj)
{
   var i;
   var style;
  
   for (i = 0; i < jsObj.children.length; i++)
   {
       style = jsObj.children[i].style;
       if (style.display == "none")
       {
           style.display = "";
       }
       else
       {
           style.display = "none";
       }
   } 
}

function setDisplay(DomId, Value)
{
	var element = document.getElementById(DomId);
	if(element) element.style.display = Value;
	return false;
}

function switchDisplay(strDomID)
{
	var CssStyle = document.getElementById(strDomID).style;
	if(CssStyle)
	{
		if(CssStyle.display=='')
		{
			CssStyle.display = 'none';
		}
		else
		{
			CssStyle.display = '';
		}
		setCssDisplayCookie(strDomID);
	}
	return false;
}

function switchDisplayToggle(parentId,childOn,childOff)
{
	var CssStyle = document.getElementById(parentId).style;
	if((CssStyle)&&(CssStyle.display==''))
	{
		dhtmlDisplay(childOff,'');
		dhtmlDisplay(childOn,'none');
	}
	else
	{
		dhtmlDisplay(childOff,'none');
		dhtmlDisplay(childOn,'');
	}
	return false;
}

function getCssDisplayCookie(domId)
{
	if(document.cookie)
	{
		var CssStyle = document.getElementById(domId).style;
		if((CssStyle)&&(document.cookie.toString().indexOf(domId+'DisplayOn')<0))
		{
			CssStyle.display = 'none';
		}
		else
		{
			CssStyle.display = '';
		}
	}
}

function setCssDisplayCookie(domId)
{
	if(document.cookie)
	{
		var CssStyle = document.getElementById(domId).style;
		if((CssStyle)&&(CssStyle.display==''))
		{
			document.cookie = domId+'Display='+domId+'DisplayOn';
		}
		else
		{
			document.cookie = domId+'Display='+domId+'DisplayOff';
		}
	}
}

function textCounter(field,cntfield,maxlimit)
{
	var val = fixnewlines(field.value.toString());
	var len = val.length;
	
	//if aready too long, trim it before making any adjustments
	if(len > maxlimit) {
 		val = val.substring(0, maxlimit);
		len = val.length;
		field.value = val;
	}
	
	//update 'characters left' counter
	cntfield.value = (maxlimit - len);
}

function TextCounter_Window_OnLoad(FormName,InputName,MaxLen)
{
	var form = eval('document.'+FormName);
	var TextInput = eval('form.'+InputName);
	
	TextInput.onkeyup = function(){
		textCounter(this,eval('this.form.'+InputName+'_Counter'),MaxLen);
	}
	
	textCounter(TextInput,eval('form.'+InputName+'_Counter'),MaxLen);
}

function InitTextCounter(FormName,InputName,MaxLen)
{
	addEventHandler_OnLoad(function(){TextCounter_Window_OnLoad(FormName,InputName,MaxLen);});
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// DTHML edit functions 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function dhtmlDisplay(domID,dVal) {
	var element = document.getElementById(domID);
	if(element) element.style.display = dVal;
}

function dhtmlFormEdit(objForm,domLEN,domID) {

	var styleView;
	var styleEdit;
	var i=1;
	for (i=1 ; i<=domLEN ; i++) {
	
		var styleView = document.getElementById('view'+i.toString()).style;
		var styleEdit = document.getElementById('edit'+i.toString()).style;
		
		if ((i.toString()==domID.toString())&&(styleView.display=="")) {
			styleView.display = "none";
			styleEdit.display = "";
			intLastOpenRow = i.toString();
		} else {
			styleView.display = "";
			styleEdit.display = "none";
		}
	}
	
	objForm.reset();
	return false;

}

function dhtmlFormSubmit(objForm1,objForm2,domID,sysAction) {

	var i=0;
	for (i=0 ; i<objForm2.length ; i++) {
	
		var objE = eval('objForm1.' + objForm2[i].name + domID);
				
		if (objE) {
			if (objE.type == 'checkbox'|objE.type == 'radio') {
				if (objE.checked) {
					objForm2[i].value = objE.value;
				}
			} else if (objE.type == 'select') {
				var j=0;
				for (j=0 ; j<objE.length ; j++) {
					if (objE.options[i].selected) {
						objForm2[i].value = objE.options[j].value;
					}
				}
			} else {
				objForm2[i].value = objE.value;
			}
		}
	}
	
	objForm2.sys_id.value = domID;
	objForm2.sys_action.value = sysAction;
	
	var blnSubmit;
	if (sysAction == 'delete') {
		blnSubmit = confirm('Click OK to delete this record.');
	} else {
		blnSubmit = true;
	}
	
	if (blnSubmit) objForm2.submit();
	return false;

}

function MaximizeScrollingBlock(DomId)
{
	var o = document.getElementById(DomId);
	
	if(o)
	{
		o.style.overflow = 'visible';
		o.style.height = 'auto';
	}
	
	return false;
}

function RestoreScrollingBlock(DomId, Height)
{
	var o = document.getElementById(DomId);
	
	if(o)
	{
		o.style.overflow = 'auto';
		o.style.height = Height;
	}
	
	return false;
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// "AJAX" functions ;)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function setInnerHtmlFromHttpRequest(Id, Url)
{
	var xmlhttp = null;
	if (window.XMLHttpRequest)
	{	//code for Mozilla, etc.
		xmlhttp = new XMLHttpRequest();
	} else if(window.ActiveXObject)
	{	//code for IE
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	if(xmlhttp)
	{	//wire up the event to handle the response on successful load
		xmlhttp.onreadystatechange = function() {
			if(xmlhttp.readyState==4 && xmlhttp.status==200 && xmlhttp.responseText!='') {
				var container = document.getElementById(Id);
				container.innerHTML = xmlhttp.responseText;
				container.style.display = '';
			}
		}
		
		xmlhttp.open("GET",Url,true);
		xmlhttp.send(null);
	}
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// 3rd-party functions
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//

// Countdown in Java Script .. Cameron Gregory http://www.bloke.com/
// permission to use and modify as long as you leave these 4 comment
// lines in tact and unmodified.
// http://www.bloke.com/javascript/Countdown/
var clockForm, clockTime, clockTimeout, clockFormat, clockTid, clockRefresh;

function doDate() {

		dt = new Date();
		
		if (clockTime != 0) {			
			v1 = Math.round(( clockTime - dt )/1000);
			//add timeout value to time
			v1 += Math.round(clockTimeout * 60);
			if (v1 <= 0) {
				clockForm.date.value = "expired";
				//dont set the timer again
			}
			else {
				if (clockFormat == 1)
					clockForm.date.value = v1;
				else if (clockFormat ==2) {
					sec = v1%60;
					v1 = Math.floor(v1/60);
					min = v1 %60 ;
					hour = Math.floor(v1/60);
					if (sec < 10 ) sec = "0"+sec;
					if (min < 10 ) min = "0"+min;
					if (hour > 0) {
				        clockForm.date.value = hour+"h "+min+"m "+sec+"s";
						} else {
						clockForm.date.value = min+"m "+sec+"s";
					}
				}
				else if (clockFormat ==3) {
					sec = v1%60;	
					v1 = Math.floor( v1/60);
					min = v1 %60 ;
					v1 = Math.floor(v1 / 60);
					hour = v1 %24 ;
					day = Math.floor(v1 / 24);
					if (sec < 10 ) sec = "0"+sec;
					if (min < 10 ) min = "0"+min;
					if (hour < 10 ) hour = "0"+hour;
					clockForm.date.value = day+"d "+hour+"h "+min+"m "+sec+"s";
				}
				else if (clockFormat ==4 ) {
					sec = v1%60;
					v1 = Math.floor( v1/60);
					min = v1 %60 ;
					v1 = Math.floor(v1 / 60);
					hour = v1 %24 ;
					day = Math.floor(v1 / 24);
					clockForm.date.value = day+(day==1?"day ":"days ")+hour+(hour==1?"hour ":"hours ")+min+(min==1?"min ":"mins ")+sec+(sec==1?"sec ":"secs ")
				}
				else {
					clockForm.date.value = "invalid format";
				}
			 	clockTid=window.setTimeout("doDate()",clockRefresh);
			}
		}
		else
			clockForm.date.value = "error";
}

function startCountdown(objForm,time,timeout,format) {
	clockForm = objForm;
	clockTime = new Date(time);
	clockTimeout = timeout;
	clockFormat = format;
	clockTid = 0;
	clockRefresh = 1000;
	if (Math.round((clockTime - new Date())/1000) < -60) {
		//clock is too far out of sync
		clockForm.date.value = "unknown";
	}
	else {
		clockTid=window.setTimeout("doDate()",clockRefresh);
	}
}

//shift all the characters in the inval by shiftval characters from the charset
//  example:  "cat", 2, "abcdefghijklmnopqrstuvwxyz"
// would become "ecv"
// if a character is not found in charset, it is untouched.
//if a shift operation goes out of bounds, it will roll to the other side of charset
function CharShiftDecrypt(strInVal, shiftval, shiftCharSet) {
	var strInString = new String(strInVal);
	var intInString = strInString.length;
	var strCharSet = new String(shiftCharSet);
	var intCharSetLen = strCharSet.length;
	var strOutVal = new String('');
	
	var nextchar, nextindex, ascii_nextchar, i;
	
	//for each character
	for (i=0 ; i < intInString ; i++) {
		// grab the next character to encrypt
		nextchar = strInString.substr(i, 1);

		//look it up in charset
		nextindex = strCharSet.indexOf(nextchar,0)
		if (nextindex >= 0){ //found it
			nextindex = (nextindex  - shiftval) % intCharSetLen // modulo this so can stay in bounds for next operation
			
			//check bounds of nextindex
			if (nextindex < 0) {
				nextindex = nextindex + intCharSetLen //wrap around to high end of charset
			}
			else if (nextindex >= intCharSetLen){ //this wont happen btw, becuase of modulo, but anyway
				nextindex = nextindex - intCharSetLen
			}
			strOutVal += strCharSet.charAt(nextindex);
		}	
		else{ //char not found in set, so add it as is
			strOutVal += nextchar;
		}
	}
	
	return strOutVal;

}

//function used with jupload version 2.4+
function jupload_result(result_html)
{
window.setTimeout(function() {
document.open();
document.write(result_html);
document.close();
}, 1000);
}


//returns the value of an xml node's child node by tag name
function GetChildNodeValue(Node, TagName)
{
	var RetVal;
	try {
		RetVal = Node.getElementsByTagName(TagName)[0].childNodes[0].nodeValue;
	} catch(e) {
		RetVal = '';
	}
	return RetVal;
}

//returns the value of an xml node
function GetNodeValue(Node)
{
	var RetVal;
	try {
		RetVal = Node.childNodes[0].nodeValue;
	} catch(e) {
		RetVal = '';
	}
	return RetVal;
}

//creates a new xml node and assigns a value if supplied
function NewNode(xmlDoc, Name, Value)
{
	if(!xmlDoc) return null;
	
	var RetNode = xmlDoc.createElement(Name);
	if(Value) {
		var nValue = xmlDoc.createTextNode(Value.toString());
		RetNode.appendChild(nValue);
	}
	
	return RetNode;
}

//creates a new xml node and assigns a CDATA value if supplied
function NewCdataNode(xmlDoc, Name, Value)
{
	if(!xmlDoc) return null;
	
	var RetNode = xmlDoc.createElement(Name);
	if(Value) {
		var nValue = xmlDoc.createCDATASection(Value.toString());
		RetNode.appendChild(nValue);
	}
	
	return RetNode;
}



var FORM_VALIDATION_URL = '/global_engine/validate_form.asp';

function defaultBadBrowserHandler()
{
	alert('This interface requires features which your browser does not supprt. \n\n'+
		'You will now be redirected to the Client Services Support Center, \n'+
		'where you will find additional information on browser requirements. ');
	location.href = '/admin/client_services/backend_technical_requirements.asp';
	return null;
}

function ignoreBadBrowser()
{
	return null;
}

function DisableToolbarButton(DomId)
{
	var btn = document.getElementById(DomId);
	btn.className = 'disabled';
	btn.onclick = function(){return false;};
}

function EnableToolbarButton(DomId)
{
	var btn = document.getElementById(DomId);
	btn.className = '';
	btn.onclick = eval(DomId +'_OnClick');
}

function newXmlDoc()
{
	var xmldoc = null;
	if(window.ActiveXObject) {
		// browser is IE
		xmldoc = new ActiveXObject('Microsoft.XMLDOM');
	} else if(document.implementation && document.implementation.createDocument) {
		// browser is Mozilla, Firefox, Opera, etc.
		xmldoc = document.implementation.createDocument('','',null);
	} else {
		return null;
	}
	xmldoc.async = false;
	return xmldoc;
}

function newXmlHttp(BadBrowserHandler)
{
	var xmlhttp = null;
	if(window.ActiveXObject) {
		// browser is IE
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	} else if(window.XMLHttpRequest) {
		// browser is Mozilla, Firefox, Opera, etc.
		xmlhttp = new XMLHttpRequest();
	} else {
		if(BadBrowserHandler && typeof(BadBrowserHandler)!='undefined') {
			return BadBrowserHandler();
		} else {
			return defaultBadBrowserHandler();
		}
	}
	return xmlhttp;
}

function sendSimpleHttpRequest(url, callback, formData, xmlhttp)
{
	if(!objectExists(xmlhttp)) xmlhttp = newXmlHttp(function(){});
	
	var bAsync = objectExists(callback);
	var bPost = objectExists(formData);
	var sMethod = bPost ? "POST" : "GET";
	
	if(bAsync) {
		//wire up the callback
		xmlhttp.onreadystatechange = function() {
			if(xmlhttp.readyState==4 && xmlhttp.status==200) callback();
		}
	}
	
	xmlhttp.open(sMethod, url, bAsync);
	if(bPost) xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xmlhttp.send(formData);
	
	return xmlhttp;
}

function getXml(xmlNode)
{
	if(xmlNode==null) return null;
	if(xmlNode.xml) {
		return xmlNode.xml;
	} else {
		var s = new XMLSerializer();
		return s.serializeToString(xmlNode);
	}
}

function loadNewXml(sXml)
{
	var xmlDoc;
	if(window.ActiveXObject) {
		// browser is IE
		xmlDoc = newXmlDoc();
		xmlDoc.loadXML(sXml);
	} else {
		// browser is Mozilla, Firefox, Opera, etc.
		xmlDoc = (new DOMParser()).parseFromString(sXml,'text/xml');
	}
	return xmlDoc;
}

function ValidateForm(FormData, ErrorListDomId, ValidateCaptchaCode)
{
	try {
		var xmlhttp = newXmlHttp(ignoreBadBrowser);
		
		var sUrl = FORM_VALIDATION_URL;
		if(ValidateCaptchaCode) sUrl += "?captcha=1"
		
		xmlhttp.open("POST", sUrl, false);
		xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
		xmlhttp.send(FormData);
		
		if(xmlhttp.status==200) {
			var xmlDoc;
			if(xmlhttp.responseXml) {
				xmlDoc = xmlhttp.responseXml;
			} else {
				xmlDoc = (new DOMParser()).parseFromString(xmlhttp.responseText,'text/xml');
			}
			var n =  xmlDoc.documentElement;
			
			var iErrCount = parseInt(n.getElementsByTagName('ErrCount')[0].childNodes[0].nodeValue);
			if(iErrCount==0) return true;
			
			var sErrorList = n.getElementsByTagName('ErrorList')[0].childNodes[0].nodeValue;
			document.getElementById(ErrorListDomId).innerHTML = sErrorList;	
		}
	} catch(e) {}
	
	return false;
}


//IMPORTANT! This library assumes that the following libraries have been loaded by the calling page:
//	javascript_library.js
//	yui/build/yahoo/yahoo-min.js
//	yui/build/yahoo/dom-min.js
//	yui/build/yahoo/event-min.js
//	yui/build/yahoo/container-min.js

YAHOO.namespace("container");

function YAHOOinitContextualHelp() {
	YAHOO.container.ContextualHelp = 
		new YAHOO.widget.Panel("ContextualHelp", { visible:false,
			iframe:false,
			visible:false,
			close:true,
			draggable:true,
			modal:false,
			underlay:'none',
			width:'400px'
		} );

	YAHOO.container.ContextualHelp.render();
}

YAHOO.util.Event.onDOMReady(YAHOOinitContextualHelp);

function HelpLink_OnClick(HelpID)
{
	var ContainerHd = document.getElementById('ContextualHelpHead');
	if(ContainerHd.innerHTML.length==0)
		ContainerHd.innerHTML = '<img src="/global_graphics/icons/icon_more_info.gif" align="left" alt="" border=0 height=16 width=16 vspace=3> Help';
	
	var ContainerBd = document.getElementById('ContextualHelpBody');
	ContainerBd.innerHTML = 'Loading...';
	
	YAHOO.container.ContextualHelp.cfg.setProperty('context', ['HelpLink_'+ HelpID,'tl','br']);
	
	//IE hack: underlay size does not change with panel size; resize it now
	if(document.all) YAHOO.container.ContextualHelp.sizeUnderlay();
	
	YAHOO.container.ContextualHelp.show();
	
	var xmlhttp = null;
	if (window.XMLHttpRequest)
	{	//code for Mozilla, etc.
		xmlhttp = new XMLHttpRequest();
	} else if(window.ActiveXObject)
	{	//code for IE
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	if(xmlhttp)
	{	//wire up the event to handle the response on successful load
		xmlhttp.onreadystatechange = function() {
			if(xmlhttp.readyState==4 && xmlhttp.status==200 && xmlhttp.responseText!='') {
				ContainerBd.innerHTML = xmlhttp.responseText;
				
				//IE hack: underlay size does not change with panel size; resize it now
				if(document.all) YAHOO.container.ContextualHelp.sizeUnderlay();
			}
		}
		
		xmlhttp.open("GET",'/get_help_topic.asp?id='+ HelpID,true);
		xmlhttp.send(null);
	}
	
	return false;
}

function getHelpLink(HelpID)
{
	document.write('<a id="HelpLink_'+ HelpID +
		'" href="#" title="Help is available" onclick="return HelpLink_OnClick(\''+ HelpID +
		'\')"><img src="/global_graphics/icons/helpme.gif" border=0 height=13 width=11 vspace=2></a>'
	);
}


function AutoCompleteField(dataURL, refreshDataEachFocus)
{
	this.Init = function(domID)
	{
		addEventHandler_OnLoad(function(){
		
			var element = document.getElementById(domID);
			actb(element);
			var oldHandler = element.onfocus;
		
			if (typeof element.onfocus != 'function') {
				element.onfocus = function() {
					if (typeof AutoCompleteField_OnFocus.handleEvent == 'function')
					{
						AutoCompleteField_OnFocus.handleEvent(domID, dataURL);
						if (!refreshDataEachFocus)
						{
							//eliminate the focus event handler to avoid refresh
							AutoCompleteField_OnFocus.handleEvent = null;
						}
					}
				}
			} 
			else 
			{
				element.onfocus = function() {
					if (typeof AutoCompleteField_OnFocus.handleEvent == 'function')
					{
						AutoCompleteField_OnFocus.handleEvent(domID, dataURL);
						if (!refreshDataEachFocus)
						{
							//eliminate the focus event handler to avoid refresh
							AutoCompleteField_OnFocus.handleEvent = null;
						}
					}
					oldHandler();
				}
			}
		})	
	}
}

AutoCompleteField_OnFocus = new AutoCompleteField_FocusHandler()

function AutoCompleteField_FocusHandler() 
{
	this.handleEvent = function(domID, dataURL) 
	{
		BindAutoCompleteValues(domID, dataURL);
	}
}

function BindAutoCompleteValues(domID, dataURL)
{
	var xmlhttp = newXmlHttp();
	if(!xmlhttp) return false;
	
	var now = new Date();
	dataURL += '?ts='+ now.getTime();
	
	//submit to ajax post handler
	xmlhttp.open("GET", dataURL, true);
	xmlhttp.send(null);
	
	xmlhttp.onreadystatechange = function() {
		if(xmlhttp.readyState==4 && xmlhttp.status==200 && xmlhttp.responseText!="")
		{
			//the response should be a JSON string
			var jsonData
			try { //to parse the string into a js-object
				jsonData = YAHOO.lang.JSON.parse(xmlhttp.responseText.toString()); 
			} catch(e) { return; }
			
			//set the values on the form from the JSON response
			actb(document.getElementById(domID), jsonData.arrValues);
		}
	}

	return false;
}

function actb(obj,ca){
	/* ---- Public Variables ---- */
	this.actb_timeOut = -1; // Autocomplete Timeout in ms (-1: autocomplete never time out)
	this.actb_lim = 4;    // Number of elements autocomplete can show (-1: no limit)
	this.actb_firstText = false; // should the auto complete be limited to the beginning of keyword?
	this.actb_mouse = true; // Enable Mouse Support
	this.actb_delimiter = new Array(';',',');  // Delimiter for multiple autocomplete. Set it to empty array for single autocomplete
	this.actb_startcheck = 1; // Show widget only after this number of characters is typed in.
	/* ---- Public Variables ---- */

	/* --- Styles --- */
	this.actb_bgColor = '#888888';
	this.actb_textColor = '#FFFFFF';
	this.actb_hColor = '#000000';
	this.actb_fFamily = 'Verdana';
	this.actb_fSize = '11px';
	this.actb_hStyle = 'text-decoration:underline;font-weight="bold"';
	/* --- Styles --- */

	/* ---- Private Variables ---- */
	var actb_delimwords = new Array();
	var actb_cdelimword = 0;
	var actb_delimchar = new Array();
	var actb_display = false;
	var actb_pos = 0;
	var actb_total = 0;
	var actb_curr = null;
	var actb_rangeu = 0;
	var actb_ranged = 0;
	var actb_bool = new Array();
	var actb_pre = 0;
	var actb_toid;
	var actb_tomake = false;
	var actb_getpre = "";
	var actb_mouse_on_list = 1;
	var actb_kwcount = 0;
	var actb_caretmove = false;
	this.actb_keywords = new Array();
	/* ---- Private Variables---- */
	
	this.actb_keywords = ca;
	var actb_self = this;

	actb_curr = obj;
	
	addEvent(actb_curr,"focus",actb_setup);
	function actb_setup(){
		addEvent(document,"keydown",actb_checkkey);
		addEvent(actb_curr,"blur",actb_clear);
		addEvent(document,"keypress",actb_keypress);
	}

	function actb_clear(evt){
		if (!evt) evt = event;
		removeEvent(document,"keydown",actb_checkkey);
		removeEvent(actb_curr,"blur",actb_clear);
		removeEvent(document,"keypress",actb_keypress);
		actb_removedisp();
	}
	function actb_parse(n){
		if (actb_self.actb_delimiter.length > 0){
			var t = actb_delimwords[actb_cdelimword].trim().addslashes();
			var plen = actb_delimwords[actb_cdelimword].trim().length;
		}else{
			var t = actb_curr.value.addslashes();
			var plen = actb_curr.value.length;
		}
		var tobuild = '';
		var i;

		if (actb_self.actb_firstText){
			var re = new RegExp("^" + t, "i");
		}else{
			var re = new RegExp(t, "i");
		}
		var p = n.search(re);
				
		for (i=0;i<p;i++){
			tobuild += n.substr(i,1);
		}
		tobuild += "<font style='"+(actb_self.actb_hStyle)+"'>"
		for (i=p;i<plen+p;i++){
			tobuild += n.substr(i,1);
		}
		tobuild += "</font>";
			for (i=plen+p;i<n.length;i++){
			tobuild += n.substr(i,1);
		}
		return tobuild;
	}
	function actb_generate(){
		if (document.getElementById('tat_table')){ actb_display = false;document.body.removeChild(document.getElementById('tat_table')); } 
		if (actb_kwcount == 0){
			actb_display = false;
			return;
		}
		a = document.createElement('table');
		a.cellSpacing='1px';
		a.cellPadding='2px';
		a.style.position='absolute';
		a.style.top = eval(curTop(actb_curr) + actb_curr.offsetHeight) + "px";
		a.style.left = curLeft(actb_curr) + "px";
		a.style.backgroundColor=actb_self.actb_bgColor;
		a.id = 'tat_table';
		document.body.appendChild(a);
		var i;
		var first = true;
		var j = 1;
		if (actb_self.actb_mouse){
			a.onmouseout = actb_table_unfocus;
			a.onmouseover = actb_table_focus;
		}
		var counter = 0;
		for (i=0;i<actb_self.actb_keywords.length;i++){
			if (actb_bool[i]){
				counter++;
				r = a.insertRow(-1);
				if (first && !actb_tomake){
					r.style.backgroundColor = actb_self.actb_hColor;
					first = false;
					actb_pos = counter;
				}else if(actb_pre == i){
					r.style.backgroundColor = actb_self.actb_hColor;
					first = false;
					actb_pos = counter;
				}else{
					r.style.backgroundColor = actb_self.actb_bgColor;
				}
				r.id = 'tat_tr'+(j);
				c = r.insertCell(-1);
				c.style.color = actb_self.actb_textColor;
				c.style.fontFamily = actb_self.actb_fFamily;
				c.style.fontSize = actb_self.actb_fSize;
				c.innerHTML = actb_parse(actb_self.actb_keywords[i]);
				c.id = 'tat_td'+(j);
				c.setAttribute('pos',j);
				if (actb_self.actb_mouse){
					c.style.cursor = 'pointer';
					c.onclick=actb_mouseclick;
					c.onmouseover = actb_table_highlight;
				}
				j++;
			}
			if (j - 1 == actb_self.actb_lim && j < actb_total){
				r = a.insertRow(-1);
				r.style.backgroundColor = actb_self.actb_bgColor;
				c = r.insertCell(-1);
				c.style.color = actb_self.actb_textColor;
				c.style.fontFamily = 'arial narrow';
				c.style.fontSize = actb_self.actb_fSize;
				c.align='center';
				replaceHTML(c,'\\/');
				if (actb_self.actb_mouse){
					c.style.cursor = 'pointer';
					c.onclick = actb_mouse_down;
				}
				break;
			}
		}
		actb_rangeu = 1;
		actb_ranged = j-1;
		actb_display = true;
		if (actb_pos <= 0) actb_pos = 1;
	}
	function actb_remake(){
		document.body.removeChild(document.getElementById('tat_table'));
		a = document.createElement('table');
		a.cellSpacing='1px';
		a.cellPadding='2px';
		a.style.position='absolute';
		a.style.top = eval(curTop(actb_curr) + actb_curr.offsetHeight) + "px";
		a.style.left = curLeft(actb_curr) + "px";
		a.style.backgroundColor=actb_self.actb_bgColor;
		a.id = 'tat_table';
		if (actb_self.actb_mouse){
			a.onmouseout= actb_table_unfocus;
			a.onmouseover=actb_table_focus;
		}
		document.body.appendChild(a);
		var i;
		var first = true;
		var j = 1;
		if (actb_rangeu > 1){
			r = a.insertRow(-1);
			r.style.backgroundColor = actb_self.actb_bgColor;
			c = r.insertCell(-1);
			c.style.color = actb_self.actb_textColor;
			c.style.fontFamily = 'arial narrow';
			c.style.fontSize = actb_self.actb_fSize;
			c.align='center';
			replaceHTML(c,'/\\');
			if (actb_self.actb_mouse){
				c.style.cursor = 'pointer';
				c.onclick = actb_mouse_up;
			}
		}
		for (i=0;i<actb_self.actb_keywords.length;i++){
			if (actb_bool[i]){
				if (j >= actb_rangeu && j <= actb_ranged){
					r = a.insertRow(-1);
					r.style.backgroundColor = actb_self.actb_bgColor;
					r.id = 'tat_tr'+(j);
					c = r.insertCell(-1);
					c.style.color = actb_self.actb_textColor;
					c.style.fontFamily = actb_self.actb_fFamily;
					c.style.fontSize = actb_self.actb_fSize;
					c.innerHTML = actb_parse(actb_self.actb_keywords[i]);
					c.id = 'tat_td'+(j);
					c.setAttribute('pos',j);
					if (actb_self.actb_mouse){
						c.style.cursor = 'pointer';
						c.onclick=actb_mouseclick;
						c.onmouseover = actb_table_highlight;
					}
					j++;
				}else{
					j++;
				}
			}
			if (j > actb_ranged) break;
		}
		if (j-1 < actb_total){
			r = a.insertRow(-1);
			r.style.backgroundColor = actb_self.actb_bgColor;
			c = r.insertCell(-1);
			c.style.color = actb_self.actb_textColor;
			c.style.fontFamily = 'arial narrow';
			c.style.fontSize = actb_self.actb_fSize;
			c.align='center';
			replaceHTML(c,'\\/');
			if (actb_self.actb_mouse){
				c.style.cursor = 'pointer';
				c.onclick = actb_mouse_down;
			}
		}
	}
	function actb_goup(){
		if (!actb_display) return;
		if (actb_pos == 1) return;
		document.getElementById('tat_tr'+actb_pos).style.backgroundColor = actb_self.actb_bgColor;
		actb_pos--;
		if (actb_pos < actb_rangeu) actb_moveup();
		document.getElementById('tat_tr'+actb_pos).style.backgroundColor = actb_self.actb_hColor;
		if (actb_toid) clearTimeout(actb_toid);
		if (actb_self.actb_timeOut > 0) actb_toid = setTimeout(function(){actb_mouse_on_list=0;actb_removedisp();},actb_self.actb_timeOut);
	}
	function actb_godown(){
		if (!actb_display) return;
		if (actb_pos == actb_total) return;
		document.getElementById('tat_tr'+actb_pos).style.backgroundColor = actb_self.actb_bgColor;
		actb_pos++;
		if (actb_pos > actb_ranged) actb_movedown();
		document.getElementById('tat_tr'+actb_pos).style.backgroundColor = actb_self.actb_hColor;
		if (actb_toid) clearTimeout(actb_toid);
		if (actb_self.actb_timeOut > 0) actb_toid = setTimeout(function(){actb_mouse_on_list=0;actb_removedisp();},actb_self.actb_timeOut);
	}
	function actb_movedown(){
		actb_rangeu++;
		actb_ranged++;
		actb_remake();
	}
	function actb_moveup(){
		actb_rangeu--;
		actb_ranged--;
		actb_remake();
	}

	/* Mouse */
	function actb_mouse_down(){
		document.getElementById('tat_tr'+actb_pos).style.backgroundColor = actb_self.actb_bgColor;
		actb_pos++;
		actb_movedown();
		document.getElementById('tat_tr'+actb_pos).style.backgroundColor = actb_self.actb_hColor;
		actb_curr.focus();
		actb_mouse_on_list = 0;
		if (actb_toid) clearTimeout(actb_toid);
		if (actb_self.actb_timeOut > 0) actb_toid = setTimeout(function(){actb_mouse_on_list=0;actb_removedisp();},actb_self.actb_timeOut);
	}
	function actb_mouse_up(evt){
		if (!evt) evt = event;
		if (evt.stopPropagation){
			evt.stopPropagation();
		}else{
			evt.cancelBubble = true;
		}
		document.getElementById('tat_tr'+actb_pos).style.backgroundColor = actb_self.actb_bgColor;
		actb_pos--;
		actb_moveup();
		document.getElementById('tat_tr'+actb_pos).style.backgroundColor = actb_self.actb_hColor;
		actb_curr.focus();
		actb_mouse_on_list = 0;
		if (actb_toid) clearTimeout(actb_toid);
		if (actb_self.actb_timeOut > 0) actb_toid = setTimeout(function(){actb_mouse_on_list=0;actb_removedisp();},actb_self.actb_timeOut);
	}
	function actb_mouseclick(evt){
		if (!evt) evt = event;
		if (!actb_display) return;
		actb_mouse_on_list = 0;
		actb_pos = this.getAttribute('pos');
		actb_penter();
	}
	function actb_table_focus(){
		actb_mouse_on_list = 1;
	}
	function actb_table_unfocus(){
		actb_mouse_on_list = 0;
		if (actb_toid) clearTimeout(actb_toid);
		if (actb_self.actb_timeOut > 0) actb_toid = setTimeout(function(){actb_mouse_on_list = 0;actb_removedisp();},actb_self.actb_timeOut);
	}
	function actb_table_highlight(){
		actb_mouse_on_list = 1;
		document.getElementById('tat_tr'+actb_pos).style.backgroundColor = actb_self.actb_bgColor;
		actb_pos = this.getAttribute('pos');
		while (actb_pos < actb_rangeu) actb_moveup();
		while (actb_pos > actb_ranged) actb_movedown();
		document.getElementById('tat_tr'+actb_pos).style.backgroundColor = actb_self.actb_hColor;
		if (actb_toid) clearTimeout(actb_toid);
		if (actb_self.actb_timeOut > 0) actb_toid = setTimeout(function(){actb_mouse_on_list = 0;actb_removedisp();},actb_self.actb_timeOut);
	}
	/* ---- */

	function actb_insertword(a){
		if (actb_self.actb_delimiter.length > 0){
			str = '';
			l=0;
			for (i=0;i<actb_delimwords.length;i++){
				if (actb_cdelimword == i){
					prespace = postspace = '';
					gotbreak = false;
					for (j=0;j<actb_delimwords[i].length;++j){
						if (actb_delimwords[i].charAt(j) != ' '){
							gotbreak = true;
							break;
						}
						prespace += ' ';
					}
					for (j=actb_delimwords[i].length-1;j>=0;--j){
						if (actb_delimwords[i].charAt(j) != ' ') break;
						postspace += ' ';
					}
					str += prespace;
					str += a;
					l = str.length;
					if (gotbreak) str += postspace;
				}else{
					str += actb_delimwords[i];
				}
				if (i != actb_delimwords.length - 1){
					str += actb_delimchar[i];
				}
			}
			actb_curr.value = str;
			setCaret(actb_curr,l);
		}else{
			actb_curr.value = a;
		}
		actb_mouse_on_list = 0;
		actb_removedisp();
	}
	function actb_penter(){
		if (!actb_display) return;
		actb_display = false;
		var word = '';
		var c = 0;
		for (var i=0;i<=actb_self.actb_keywords.length;i++){
			if (actb_bool[i]) c++;
			if (c == actb_pos){
				word = actb_self.actb_keywords[i];
				break;
			}
		}
		actb_insertword(word);
		l = getCaretStart(actb_curr);
	}
	function actb_removedisp(){
		if (actb_mouse_on_list==0){
			actb_display = 0;
			if (document.getElementById('tat_table')){ document.body.removeChild(document.getElementById('tat_table')); }
			if (actb_toid) clearTimeout(actb_toid);
		}
	}
	function actb_keypress(e){
		if (actb_caretmove) stopEvent(e);
		return !actb_caretmove;
	}
	function actb_checkkey(evt){
		if (!evt) evt = event;
		a = evt.keyCode;
		caret_pos_start = getCaretStart(actb_curr);
		actb_caretmove = 0;
		switch (a){
			case 38:
				actb_goup();
				actb_caretmove = 1;
				return false;
				break;
			case 40:
				actb_godown();
				actb_caretmove = 1;
				return false;
				break;
			case 13: case 9:
				if (actb_display){
					actb_caretmove = 1;
					actb_penter();
					return false;
				}else{
					return true;
				}
				break;
			default:
				setTimeout(function(){actb_tocomplete(a)},50);
				break;
		}
	}

	function actb_tocomplete(kc){
		if (kc == 38 || kc == 40 || kc == 13) return;
		var i;
		if (actb_display){ 
			var word = 0;
			var c = 0;
			for (var i=0;i<=actb_self.actb_keywords.length;i++){
				if (actb_bool[i]) c++;
				if (c == actb_pos){
					word = i;
					break;
				}
			}
			actb_pre = word;
		}else{ actb_pre = -1};
		
		if (actb_curr.value == ''){
			actb_mouse_on_list = 0;
			actb_removedisp();
			return;
		}
		if (actb_self.actb_delimiter.length > 0){
			caret_pos_start = getCaretStart(actb_curr);
			caret_pos_end = getCaretEnd(actb_curr);
			
			delim_split = '';
			for (i=0;i<actb_self.actb_delimiter.length;i++){
				delim_split += actb_self.actb_delimiter[i];
			}
			delim_split = delim_split.addslashes();
			delim_split_rx = new RegExp("(["+delim_split+"])");
			c = 0;
			actb_delimwords = new Array();
			actb_delimwords[0] = '';
			for (i=0,j=actb_curr.value.length;i<actb_curr.value.length;i++,j--){
				if (actb_curr.value.substr(i,j).search(delim_split_rx) == 0){
					ma = actb_curr.value.substr(i,j).match(delim_split_rx);
					actb_delimchar[c] = ma[1];
					c++;
					actb_delimwords[c] = '';
				}else{
					actb_delimwords[c] += actb_curr.value.charAt(i);
				}
			}

			var l = 0;
			actb_cdelimword = -1;
			for (i=0;i<actb_delimwords.length;i++){
				if (caret_pos_end >= l && caret_pos_end <= l + actb_delimwords[i].length){
					actb_cdelimword = i;
				}
				l+=actb_delimwords[i].length + 1;
			}
			var ot = actb_delimwords[actb_cdelimword].trim(); 
			var t = actb_delimwords[actb_cdelimword].addslashes().trim();
		}else{
			var ot = actb_curr.value;
			var t = actb_curr.value.addslashes();
		}
		if (ot.length == 0){
			actb_mouse_on_list = 0;
			actb_removedisp();
		}
		if (ot.length < actb_self.actb_startcheck) return this;
		if (actb_self.actb_firstText){
			var re = new RegExp("^" + t, "i");
		}else{
			var re = new RegExp(t, "i");
		}

		actb_total = 0;
		actb_tomake = false;
		actb_kwcount = 0;
		for (i=0;i<actb_self.actb_keywords.length;i++){
			actb_bool[i] = false;
			if (re.test(actb_self.actb_keywords[i])){
				actb_total++;
				actb_bool[i] = true;
				actb_kwcount++;
				if (actb_pre == i) actb_tomake = true;
			}
		}

		if (actb_toid) clearTimeout(actb_toid);
		if (actb_self.actb_timeOut > 0) actb_toid = setTimeout(function(){actb_mouse_on_list = 0;actb_removedisp();},actb_self.actb_timeOut);
		actb_generate();
	}
	return this;
}

/* Event Functions */

// Add an event to the obj given
// event_name refers to the event trigger, without the "on", like click or mouseover
// func_name refers to the function callback when event is triggered
function addEvent(obj,event_name,func_name){
	if (obj.attachEvent){
		obj.attachEvent("on"+event_name, func_name);
	}else if(obj.addEventListener){
		obj.addEventListener(event_name,func_name,true);
	}else{
		obj["on"+event_name] = func_name;
	}
}

// Removes an event from the object
function removeEvent(obj,event_name,func_name){
	if (obj.detachEvent){
		obj.detachEvent("on"+event_name,func_name);
	}else if(obj.removeEventListener){
		obj.removeEventListener(event_name,func_name,true);
	}else{
		obj["on"+event_name] = null;
	}
}

// Stop an event from bubbling up the event DOM
function stopEvent(evt){
	evt || window.event;
	if (evt.stopPropagation){
		evt.stopPropagation();
		evt.preventDefault();
	}else if(typeof evt.cancelBubble != "undefined"){
		evt.cancelBubble = true;
		evt.returnValue = false;
	}
	return false;
}

// Get the obj that starts the event
function getElement(evt){
	if (window.event){
		return window.event.srcElement;
	}else{
		return evt.currentTarget;
	}
}
// Get the obj that triggers off the event
function getTargetElement(evt){
	if (window.event){
		return window.event.srcElement;
	}else{
		return evt.target;
	}
}
// For IE only, stops the obj from being selected
function stopSelect(obj){
	if (typeof obj.onselectstart != 'undefined'){
		addEvent(obj,"selectstart",function(){ return false;});
	}
}

/*    Caret Functions     */

// Get the end position of the caret in the object. Note that the obj needs to be in focus first
function getCaretEnd(obj){
	if(typeof obj.selectionEnd != "undefined"){
		return obj.selectionEnd;
	}else if(document.selection&&document.selection.createRange){
		var M=document.selection.createRange();
		try{
			var Lp = M.duplicate();
			Lp.moveToElementText(obj);
		}catch(e){
			var Lp=obj.createTextRange();
		}
		Lp.setEndPoint("EndToEnd",M);
		var rb=Lp.text.length;
		if(rb>obj.value.length){
			return -1;
		}
		return rb;
	}
}
// Get the start position of the caret in the object
function getCaretStart(obj){
	if(typeof obj.selectionStart != "undefined"){
		return obj.selectionStart;
	}else if(document.selection&&document.selection.createRange){
		var M=document.selection.createRange();
		try{
			var Lp = M.duplicate();
			Lp.moveToElementText(obj);
		}catch(e){
			var Lp=obj.createTextRange();
		}
		Lp.setEndPoint("EndToStart",M);
		var rb=Lp.text.length;
		if(rb>obj.value.length){
			return -1;
		}
		return rb;
	}
}
// sets the caret position to l in the object
function setCaret(obj,l){
	obj.focus();
	if (obj.setSelectionRange){
		obj.setSelectionRange(l,l);
	}else if(obj.createTextRange){
		m = obj.createTextRange();		
		m.moveStart('character',l);
		m.collapse();
		m.select();
	}
}
// sets the caret selection from s to e in the object
function setSelection(obj,s,e){
	obj.focus();
	if (obj.setSelectionRange){
		obj.setSelectionRange(s,e);
	}else if(obj.createTextRange){
		m = obj.createTextRange();		
		m.moveStart('character',s);
		m.moveEnd('character',e);
		m.select();
	}
}

/*    Escape function   */
String.prototype.addslashes = function(){
	return this.replace(/(["\\\.\|\[\]\^\*\+\?\$\(\)])/g, '\\$1');
}
String.prototype.trim = function () {
    return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
};
/* --- Escape --- */

/* Offset position from top of the screen */
function curTop(obj){
	toreturn = 0;
	while(obj){
		toreturn += obj.offsetTop;
		obj = obj.offsetParent;
	}
	return toreturn;
}
function curLeft(obj){
	toreturn = 0;
	while(obj){
		toreturn += obj.offsetLeft;
		obj = obj.offsetParent;
	}
	return toreturn;
}
/* ------ End of Offset function ------- */

/* Types Function */

// is a given input a number?
function isNumber(a) {
    return typeof a == 'number' && isFinite(a);
}

/* Object Functions */

function replaceHTML(obj,text){
	while(el = obj.childNodes[0]){
		obj.removeChild(el);
	};
	obj.appendChild(document.createTextNode(text));
}


function Pulse(dateLastHeartbeat)
{
	// time of the last heartbeat
	if(isNaN(Date.parse(dateLastHeartbeat))) {
		this.TimeLastHeartbeat = Date.parse('1970-01-01 00:00:00'); 
	} else {
		this.TimeLastHeartbeat = Date.parse(dateLastHeartbeat);
	}
	
	this.Url = '/pulse.asp'; // the location of pulse.asp (or any heartbeat handler)
	this.Heartrate = 540; // the heartbeat interval (in seconds)
	this.TID = null;
	
	this.Heartbeat = function()
	{
		var xmlhttp = null;
		if (window.XMLHttpRequest)
		{	//code for Mozilla, etc.
			xmlhttp = new XMLHttpRequest();
		} else if(window.ActiveXObject)
		{	//code for IE
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		
		if(xmlhttp)
		{
			xmlhttp.open("GET",this.Url,true);
			xmlhttp.send(null);
			this.LastHeartbeat = new Date();
			
			var self = this;
			this.TID = setTimeout(function(){ self.Heartbeat(); }, Math.round(this.Heartrate*1000)); 
		}
		
		//alert('thump!');
	}
	
	this.Start = function()
	{
		//alert(this.TimeLastHeartbeat);
		
		var now = new Date();
		var nextHeartbeat = Math.round((this.Heartrate*1000) - (now.getTime() - this.TimeLastHeartbeat));
		
		//should the next heartbeat happen within the next 10 seconds?
		if(nextHeartbeat<10000) {
			//go ahead and do it now
			this.Heartbeat();
		} else {
			//wire it up on a delay
			var self = this;
			this.TID = setTimeout(function(){ self.Heartbeat(); }, nextHeartbeat);
		}
	}
}



var m_ChatTID;
var m_ChatRequestAlert;

function alertBadBrowser()
{
	alert('The chat system requires features which your browser does not supprt. \n\n'+
		'The following browsers are recommended: \n\nInternet Explorer 7 (Windows) \n'+
		'Firefox 3 (Windows, Mac) \nSafari 2+ (Mac) ');
	self.close();
	return null;
}

function openNewChatWindow(recip)
{
	openPopup('/members/chat.asp?recip='+ recip, '_blank', 'status,resizable,toolbar=false', 550, 400);
	return false;
}

function openChatWindow(GUID, ChatID)
{
	openPopup('/members/chat.asp?cid='+ GUID, getChatWinName(ChatID), 'status,resizable,toolbar=false', 550, 400);
	return HideChatRequestAlert();
}

function getChatWinName(ChatID)
{
	return 'Chat_'+ ChatID.toString();
}

function getChatCookie(id)
{
	return getCookie('Chat_'+ id.toString());
}

function setChatCookie(id, value)
{
	setCookie('Chat_'+ id.toString(),value,'/');
}

function getChats()
{
	try {
		var sTime = (new Date()).getTime().toString();
		var xmlhttp = newXmlHttp(ignoreBadBrowser);
		xmlhttp.open("GET", '/global_inc/xml/chat_xml.asp?type=chats&ts='+ sTime, false);
		xmlhttp.send(null);
		
		var xmlDoc, xmlRoot;
		if(xmlhttp.status==200 && xmlhttp.responseText!='') {
			xmlDoc = loadNewXml(xmlhttp.responseText);
			xmlRoot = xmlDoc.documentElement;
		}
		
		var bInitialBuild = (!document.getElementById('ActiveChatList'));
		var sActiveChatList = '';
		
		var iChatCount = parseInt(GetChildNodeValue(xmlRoot, "Count"));
		if(!(isNaN(iChatCount) || iChatCount==0))
		{	//spin through chats; we only want display an alert when the participant has not yet been notified
			var iAlerts = -1;
			var aChatID = new Array();
			var aGUID = new Array();
			var aName = new Array();
			
			var nChats = xmlRoot.getElementsByTagName("Chats")[0].getElementsByTagName("Chat");
			var ChatID;
			for(var n = 0; n<nChats.length; n++) {
				ChatID = GetChildNodeValue(nChats[n],"ID");
				if(GetChildNodeValue(nChats[n],"Notfied")!='1') {
					iAlerts++;
					
					aChatID.length = iAlerts;
					aChatID[iAlerts] = ChatID;
					aGUID.length = iAlerts;
					aGUID[iAlerts] = GetChildNodeValue(nChats[n],"GUID");
					aName.length = iAlerts;
					aName[iAlerts] = GetChildNodeValue(nChats[n],"Name");
					
					AddToChatToolBar(ChatID, aGUID[iAlerts], aName[iAlerts]);
				} else if(bInitialBuild) {
					AddToChatToolBar(ChatID,
						GetChildNodeValue(nChats[n],"GUID"),
						GetChildNodeValue(nChats[n],"Name")
					);
				}
				
				if(GetChildNodeValue(nChats[n],"Unread")!='0') {
					//unread messages; flash the toolbar button
					ChatToolBarFlash(ChatID, 3);
				}
			}
			
			if(iAlerts>=0) {
				var sAlertBody = '', sNameTrailer = '';
				if(iAlerts==0)
				{	//single chat alert
					sNameTrailer = ' wants to chat!';
				} else {
					//multiple alerts
					sAlertBody = 'You have chat requests from:<br><br>';
				}
				
				for(var i = 0; i<aGUID.length; i++) {
					if(i>0) sAlertBody += '<br>';
					sAlertBody += ('<a href=# onclick="return openChatWindow(\''+ aGUID[i] +
						'\','+ aChatID[i] +');">'+ aName[i] + sNameTrailer + '</a>');
				}
				
				RaiseChatRequestAlert(sAlertBody);
			}
		}
		
	} catch(e) {}
	
	pollForChats();
}

function pollForChats(retrys)
{	//chat polling must fire without exception
	try {
		//check for new conversations every 30 seconds
		m_ChatTID = setTimeout(function(){ getChats() }, 30000);
	} catch(e) {
		//retry 9 times before giving up
		if(isNaN(retrys)) retrys = 0;
		
		if(retrys<9) {
			retrys++;
			m_ChatTID = setTimeout(function(){ pollForChats(retrys) }, 1000);
		}
	}
}

function RaiseChatRequestAlert(sAlertBody)
{
	var container = document.getElementById('PageBase_RaiseAlert');
	if(container) {
		if(m_ChatRequestAlert) {
			m_ChatRequestAlert.setBody(sAlertBody);
			
			//IE hack: underlay size does not change with panel size; resize it now
			if(document.all) m_ChatRequestAlert.sizeUnderlay();
			
			m_ChatRequestAlert.show();
		} else {
			m_ChatRequestAlert = new YAHOO.widget.SimpleDialog("ChatRequestAlert", {
				text:sAlertBody,
				iframe:false,
				visible:true,
				close:true,
				draggable:false,
				modal:false,
				underlay:'shadow',
				width:'270px',
				fixedcenter:true
				}
			);
			
			m_ChatRequestAlert.setHeader("Chat Request");
			m_ChatRequestAlert.render(container);
		}
	}
}

function HideChatRequestAlert()
{
	if(m_ChatRequestAlert) m_ChatRequestAlert.hide();
	return false;
}

function AddToChatToolBar(ChatID, GUID, Name)
{
	var ActiveChatList = document.getElementById('ActiveChatList');
	if(!ActiveChatList) {
		WriteTopToolBar('<label>AVAILABLE CHATS</label>');
		var TopToolBarText = document.getElementById('TopToolBarText');
		ActiveChatList = document.createElement('span');
		ActiveChatList.setAttribute('id','ActiveChatList');
		TopToolBarText.appendChild(ActiveChatList);		
	}
	
	var sNewLink = '<a href=# id="ChatTB_'+ ChatID +'" title="'+ Name +'"'+
		' onclick="return openChatWindow(\''+ GUID + '\','+ ChatID +');"'+
		' onmouseover="ChatToolBar_OnMouseOver(this);" onmouseout="ChatToolBar_OnMouseOut(this);">'+
		Name.substr(0,6) + '...</a>';
	
	ActiveChatList.innerHTML = sNewLink + ActiveChatList.innerHTML;
}

function ChatToolBarFlash(ChatID, HowManyTimes, i)
{
	var ChatLink = document.getElementById('ChatTB_'+ ChatID);
	if(!ChatLink) return;
	
	if(isNaN(i)) i = 1;
	
	if(i%2==0) {
		ChatLink.style.backgroundColor = 'Transparent';
	} else {
		ChatLink.style.backgroundColor = 'White';
	}
	
	if(i<(HowManyTimes*2)) {
		i++;
		setTimeout(function(){ ChatToolBarFlash(ChatID, HowManyTimes, i) }, 300);
	}

}

function ChatToolBar_OnMouseOver(sender)
{
	sender.style.backgroundColor = '#F2F6F9';
}

function ChatToolBar_OnMouseOut(sender)
{
	sender.style.backgroundColor = 'Transparent';
}


function AC_AddExtension(src,ext){if(src.indexOf('?')!=-1)return src.replace(/\?/,ext+'?');else return src+ext}function AC_Generateobj(objAttrs,params,embedAttrs){var str='<object ';for(var i in objAttrs)str+=i+'="'+objAttrs[i]+'" ';str+='>';for(var i in params)str+='<param name="'+i+'" value="'+params[i]+'" /> ';str+='<embed ';for(var i in embedAttrs)str+=i+'="'+embedAttrs[i]+'" ';str+=' ></embed></object>';document.write(str)}function AC_FL_RunContent(){var ret=AC_GetArgs(arguments,".swf","movie","clsid:d27cdb6e-ae6d-11cf-96b8-444553540000","application/x-shockwave-flash");AC_Generateobj(ret.objAttrs,ret.params,ret.embedAttrs)}function AC_SW_RunContent(){var ret=AC_GetArgs(arguments,".dcr","src","clsid:166B1BCA-3F9C-11CF-8075-444553540000",null);AC_Generateobj(ret.objAttrs,ret.params,ret.embedAttrs)}function AC_GetArgs(args,ext,srcParamName,classid,mimeType){var ret=new Object();ret.embedAttrs=new Object();ret.params=new Object();ret.objAttrs=new Object();for(var i=0;i<args.length;i=i+2){var currArg=args[i].toLowerCase();switch(currArg){case"classid":break;case"pluginspage":ret.embedAttrs[args[i]]=args[i+1];break;case"src":case"movie":args[i+1]=AC_AddExtension(args[i+1],ext);ret.embedAttrs["src"]=args[i+1];ret.params[srcParamName]=args[i+1];break;case"onafterupdate":case"onbeforeupdate":case"onblur":case"oncellchange":case"onclick":case"ondblClick":case"ondrag":case"ondragend":case"ondragenter":case"ondragleave":case"ondragover":case"ondrop":case"onfinish":case"onfocus":case"onhelp":case"onmousedown":case"onmouseup":case"onmouseover":case"onmousemove":case"onmouseout":case"onkeypress":case"onkeydown":case"onkeyup":case"onload":case"onlosecapture":case"onpropertychange":case"onreadystatechange":case"onrowsdelete":case"onrowenter":case"onrowexit":case"onrowsinserted":case"onstart":case"onscroll":case"onbeforeeditfocus":case"onactivate":case"onbeforedeactivate":case"ondeactivate":case"type":case"codebase":ret.objAttrs[args[i]]=args[i+1];break;case"width":case"height":case"align":case"vspace":case"hspace":case"class":case"title":case"accesskey":case"name":case"id":case"tabindex":ret.embedAttrs[args[i]]=ret.objAttrs[args[i]]=args[i+1];break;default:ret.embedAttrs[args[i]]=ret.params[args[i]]=args[i+1]}}ret.objAttrs["classid"]=classid;if(mimeType)ret.embedAttrs["type"]=mimeType;return ret}

function AC_AX_RunContent(){var ret=AC_AX_GetArgs(arguments);AC_Generateobj(ret.objAttrs,ret.params,ret.embedAttrs)}function AC_AX_GetArgs(args){var ret=new Object();ret.embedAttrs=new Object();ret.params=new Object();ret.objAttrs=new Object();for(var i=0;i<args.length;i=i+2){var currArg=args[i].toLowerCase();switch(currArg){case"pluginspage":case"type":case"src":ret.embedAttrs[args[i]]=args[i+1];break;case"data":case"codebase":case"classid":case"id":case"onafterupdate":case"onbeforeupdate":case"onblur":case"oncellchange":case"onclick":case"ondblClick":case"ondrag":case"ondragend":case"ondragenter":case"ondragleave":case"ondragover":case"ondrop":case"onfinish":case"onfocus":case"onhelp":case"onmousedown":case"onmouseup":case"onmouseover":case"onmousemove":case"onmouseout":case"onkeypress":case"onkeydown":case"onkeyup":case"onload":case"onlosecapture":case"onpropertychange":case"onreadystatechange":case"onrowsdelete":case"onrowenter":case"onrowexit":case"onrowsinserted":case"onstart":case"onscroll":case"onbeforeeditfocus":case"onactivate":case"onbeforedeactivate":case"ondeactivate":ret.objAttrs[args[i]]=args[i+1];break;case"width":case"height":case"align":case"vspace":case"hspace":case"class":case"title":case"accesskey":case"name":case"tabindex":ret.embedAttrs[args[i]]=ret.objAttrs[args[i]]=args[i+1];break;default:ret.embedAttrs[args[i]]=ret.params[args[i]]=args[i+1]}}return ret}

