

<!-- 

// ############		START DATE FORMAT FUNCTIONS 		###########################################
 
// ===================================================================
// Author: Matt Kruse <matt@mattkruse.com>
// WWW: http://www.mattkruse.com/
//
// NOTICE: You may use this code for any purpose, commercial or
// private, without any further permission from the author. You may
// remove this notice from your final code if you wish, however it is
// appreciated by the author if at least my web site address is kept.
//
// You may *NOT* re-distribute this code in any way except through its
// use. That means, you can include it in your product, or your web
// site, or any other form where the code is actually being used. You
// may not put the plain javascript up on your site for download or
// include it in your javascript libraries for download. 
// If you wish to share this code with others, please just point them
// to the URL instead.
// Please DO NOT link directly to my .js files from your site. Copy
// the files to your server and use them there. Thank you.
// ===================================================================

// HISTORY
// ------------------------------------------------------------------
// May 17, 2003: Fixed bug in parseDate() for dates <1970
// March 11, 2003: Added parseDate() function
// March 11, 2003: Added "NNN" formatting option. Doesn't match up
//                 perfectly with SimpleDateFormat formats, but 
//                 backwards-compatability was required.

// ------------------------------------------------------------------
// These functions use the same 'format' strings as the 
// java.text.SimpleDateFormat class, with minor exceptions.
// The format string consists of the following abbreviations:
// 
// Field        | Full Form          | Short Form
// -------------+--------------------+-----------------------
// Year         | yyyy (4 digits)    | yy (2 digits), y (2 or 4 digits)
// Month        | MMM (name or abbr.)| MM (2 digits), M (1 or 2 digits)
//              | NNN (abbr.)        |
// Day of Month | dd (2 digits)      | d (1 or 2 digits)
// Day of Week  | EE (name)          | E (abbr)
// Hour (1-12)  | hh (2 digits)      | h (1 or 2 digits)
// Hour (0-23)  | HH (2 digits)      | H (1 or 2 digits)
// Hour (0-11)  | KK (2 digits)      | K (1 or 2 digits)
// Hour (1-24)  | kk (2 digits)      | k (1 or 2 digits)
// Minute       | mm (2 digits)      | m (1 or 2 digits)
// Second       | ss (2 digits)      | s (1 or 2 digits)
// AM/PM        | a                  |
//
// NOTE THE DIFFERENCE BETWEEN MM and mm! Month=MM, not mm!
// Examples:
//  "MMM d, y" matches: January 01, 2000
//                      Dec 1, 1900
//                      Nov 20, 00
//  "M/d/yy"   matches: 01/20/00
//                      9/2/00
//  "MMM dd, yyyy hh:mm:ssa" matches: "January 01, 2000 12:30:45AM"
// ------------------------------------------------------------------

var MONTH_NAMES=new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
var DAY_NAMES=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sun','Mon','Tue','Wed','Thu','Fri','Sat');
function LZ(x) {return(x<0||x>9?"":"0")+x}

// ------------------------------------------------------------------
// isDateEX ( date_string, format_string )
// Returns true if date string matches format of format string and
// is a valid date. Else returns false.
// It is recommended that you trim whitespace around the value before
// passing it to this function, as whitespace is NOT ignored!
// ------------------------------------------------------------------
function isDateEX(val,format) {
	var date=getDateFromFormat(val,format);
	if (date==0) { return false; }
	return true;
	}

// -------------------------------------------------------------------
// compareDates(date1,date1format,date2,date2format)
//   Compare two date strings to see which is greater.
//   Returns:
//   1 if date1 is greater than date2
//   0 if date2 is greater than date1 of if they are the same
//  -1 if either of the dates is in an invalid format
// -------------------------------------------------------------------
function compareDates(date1,dateformat1,date2,dateformat2) {
	var d1=getDateFromFormat(date1,dateformat1);
	var d2=getDateFromFormat(date2,dateformat2);
	if (d1==0 || d2==0) {
		return -1;
		}
	else if (d1 > d2) {
		return 1;
		}
	return 0;
	}

// ------------------------------------------------------------------
// formatDate (date_object, format)
// Returns a date in the output format specified.
// The format string uses the same abbreviations as in getDateFromFormat()
// ------------------------------------------------------------------
function formatDate(date,format) {
	format=format+"";
	var result="";
	var i_format=0;
	var c="";
	var token="";
	var y=date.getYear()+"";
	var M=date.getMonth()+1;
	var d=date.getDate();
	var E=date.getDay();
	var H=date.getHours();
	var m=date.getMinutes();
	var s=date.getSeconds();
	var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
	// Convert real date parts into formatted versions
	var value=new Object();
	if (y.length < 4) {y=""+(y-0+1900);}
	value["y"]=""+y;
	value["yyyy"]=y;
	value["yy"]=y.substring(2,4);
	value["M"]=M;
	value["MM"]=LZ(M);
	value["MMM"]=MONTH_NAMES[M-1];
	value["NNN"]=MONTH_NAMES[M+11];
	value["d"]=d;
	value["dd"]=LZ(d);
	value["E"]=DAY_NAMES[E+7];
	value["EE"]=DAY_NAMES[E];
	value["H"]=H;
	value["HH"]=LZ(H);
	if (H==0){value["h"]=12;}
	else if (H>12){value["h"]=H-12;}
	else {value["h"]=H;}
	value["hh"]=LZ(value["h"]);
	if (H>11){value["K"]=H-12;} else {value["K"]=H;}
	value["k"]=H+1;
	value["KK"]=LZ(value["K"]);
	value["kk"]=LZ(value["k"]);
	if (H > 11) { value["a"]="PM"; }
	else { value["a"]="AM"; }
	value["m"]=m;
	value["mm"]=LZ(m);
	value["s"]=s;
	value["ss"]=LZ(s);
	while (i_format < format.length) {
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		if (value[token] != null) { result=result + value[token]; }
		else { result=result + token; }
		}
	return result;
	}
	
// ------------------------------------------------------------------
// Utility functions for parsing in getDateFromFormat()
// ------------------------------------------------------------------
function _isInteger(val) {
	var digits="1234567890";
	for (var i=0; i < val.length; i++) {
		if (digits.indexOf(val.charAt(i))==-1) { return false; }
		}
	return true;
	}
function _getInt(str,i,minlength,maxlength) {
	for (var x=maxlength; x>=minlength; x--) {
		var token=str.substring(i,i+x);
		if (token.length < minlength) { return null; }
		if (_isInteger(token)) { return token; }
		}
	return null;
	}
	
// ------------------------------------------------------------------
// getDateFromFormat( date_string , format_string )
//
// This function takes a date string and a format string. It matches
// If the date string matches the format string, it returns the 
// getTime() of the date. If it does not match, it returns 0.
// ------------------------------------------------------------------
function getDateFromFormat(val,format) {
	val=val+"";
	format=format+"";
	var i_val=0;
	var i_format=0;
	var c="";
	var token="";
	var token2="";
	var x,y;
	var now=new Date();
	var year=now.getYear();
	var month=now.getMonth()+1;
	var date=1;
	var hh=now.getHours();
	var mm=now.getMinutes();
	var ss=now.getSeconds();
	var ampm="";
	
	while (i_format < format.length) {
		// Get next token from format string
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		// Extract contents of value based on format token
		if (token=="yyyy" || token=="yy" || token=="y") {
			if (token=="yyyy") { x=4;y=4; }
			if (token=="yy")   { x=2;y=2; }
			if (token=="y")    { x=2;y=4; }
			year=_getInt(val,i_val,x,y);
			if (year==null) { return 0; }
			i_val += year.length;
			if (year.length==2) {
				if (year > 70) { year=1900+(year-0); }
				else { year=2000+(year-0); }
				}
			}
		else if (token=="MMM"||token=="NNN"){
			month=0;
			for (var i=0; i<MONTH_NAMES.length; i++) {
				var month_name=MONTH_NAMES[i];
				if (val.substring(i_val,i_val+month_name.length).toLowerCase()==month_name.toLowerCase()) {
					if (token=="MMM"||(token=="NNN"&&i>11)) {
						month=i+1;
						if (month>12) { month -= 12; }
						i_val += month_name.length;
						break;
						}
					}
				}
			if ((month < 1)||(month>12)){return 0;}
			}
		else if (token=="EE"||token=="E"){
			for (var i=0; i<DAY_NAMES.length; i++) {
				var day_name=DAY_NAMES[i];
				if (val.substring(i_val,i_val+day_name.length).toLowerCase()==day_name.toLowerCase()) {
					i_val += day_name.length;
					break;
					}
				}
			}
		else if (token=="MM"||token=="M") {
			month=_getInt(val,i_val,token.length,2);
			if(month==null||(month<1)||(month>12)){return 0;}
			i_val+=month.length;}
		else if (token=="dd"||token=="d") {
			date=_getInt(val,i_val,token.length,2);
			if(date==null||(date<1)||(date>31)){return 0;}
			i_val+=date.length;}
		else if (token=="hh"||token=="h") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<1)||(hh>12)){return 0;}
			i_val+=hh.length;}
		else if (token=="HH"||token=="H") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<0)||(hh>23)){return 0;}
			i_val+=hh.length;}
		else if (token=="KK"||token=="K") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<0)||(hh>11)){return 0;}
			i_val+=hh.length;}
		else if (token=="kk"||token=="k") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<1)||(hh>24)){return 0;}
			i_val+=hh.length;hh--;}
		else if (token=="mm"||token=="m") {
			mm=_getInt(val,i_val,token.length,2);
			if(mm==null||(mm<0)||(mm>59)){return 0;}
			i_val+=mm.length;}
		else if (token=="ss"||token=="s") {
			ss=_getInt(val,i_val,token.length,2);
			if(ss==null||(ss<0)||(ss>59)){return 0;}
			i_val+=ss.length;}
		else if (token=="a") {
			if (val.substring(i_val,i_val+2).toLowerCase()=="am") {ampm="AM";}
			else if (val.substring(i_val,i_val+2).toLowerCase()=="pm") {ampm="PM";}
			else {return 0;}
			i_val+=2;}
		else {
			if (val.substring(i_val,i_val+token.length)!=token) {return 0;}
			else {i_val+=token.length;}
			}
		}
	// If there are any trailing characters left in the value, it doesn't match
	if (i_val != val.length) { return 0; }
	// Is date valid for month?
	if (month==2) {
		// Check for leap year
		if ( ( (year%4==0)&&(year%100 != 0) ) || (year%400==0) ) { // leap year
			if (date > 29){ return 0; }
			}
		else { if (date > 28) { return 0; } }
		}
	if ((month==4)||(month==6)||(month==9)||(month==11)) {
		if (date > 30) { return 0; }
		}
	// Correct hours value
	if (hh<12 && ampm=="PM") { hh=hh-0+12; }
	else if (hh>11 && ampm=="AM") { hh-=12; }
	var newdate=new Date(year,month-1,date,hh,mm,ss);
	return newdate.getTime();
	}

// ------------------------------------------------------------------
// parseDate( date_string [, prefer_euro_format] )
//
// This function takes a date string and tries to match it to a
// number of possible date formats to get the value. It will try to
// match against the following international formats, in this order:
// y-M-d   MMM d, y   MMM d,y   y-MMM-d   d-MMM-y  MMM d
// M/d/y   M-d-y      M.d.y     MMM-d     M/d      M-d
// d/M/y   d-M-y      d.M.y     d-MMM     d/M      d-M
// A second argument may be passed to instruct the method to search
// for formats like d/M/y (european format) before M/d/y (American).
// Returns a Date object or null if no patterns match.
// ------------------------------------------------------------------
function parseDate(val) {
	var preferEuro=(arguments.length==2)?arguments[1]:false;
	generalFormats=new Array('y-M-d','MMM d, y','MMM d,y','y-MMM-d','d-MMM-y','MMM d');
	monthFirst=new Array('M/d/y','M-d-y','M.d.y','MMM-d','M/d','M-d');
	dateFirst =new Array('d/M/y','d-M-y','d.M.y','d-MMM','d/M','d-M');
	var checkList=new Array('generalFormats',preferEuro?'dateFirst':'monthFirst',preferEuro?'monthFirst':'dateFirst');
	var d=null;
	for (var i=0; i<checkList.length; i++) {
		var l=window[checkList[i]];
		for (var j=0; j<l.length; j++) {
			d=getDateFromFormat(val,l[j]);
			if (d!=0) { return new Date(d); }
			}
		}
	return null;
	}

 

  
// ############		END DATE FORMAT FUNCTIONS 		###########################################

function setClosestTime(sId, nPlusMinutes) {
	var nHour = 0
	var nMinute = '00'
	var MeridianIndicator = ''
	var timeSelect = document.getElementById(sId)	

	if (location.href.indexOf('site.cb.create.asp') < 0) {
		// not a new block
		return;
	}
	
	var d = new Date()
	
	if(nPlusMinutes) {
		d.setMinutes(d.getMinutes() + nPlusMinutes)
    	} 	

	 
	 if (d.getHours()==12) {
		nHour = d.getHours()
		MeridianIndicator = 'PM'
	} else if (d.getHours() == 0) {
		nHour = 12
		MeridianIndicator = 'AM'	
	} else if (d.getHours()>12) {
		nHour = d.getHours()-12
		MeridianIndicator = 'PM'
	} else {
		nHour = d.getHours()
		MeridianIndicator = 'AM'
	}


	 if (d.getMinutes() <= 30) {
	 	nMinute = '30'
	 } else {
	 	nMinute = '00'
	 	if (nHour == 12) {
	 		nHour = 1;
	 	} else {
			nHour += 1;
		}
	 }	

	if (timeSelect) {
		for(var i = 0 ; i<timeSelect.length; i++) {
			if (timeSelect[i].value == nHour + ':' + nMinute +  MeridianIndicator) {
				timeSelect.selectedIndex = i;
				break;
			}
		}
	}
}



/*
Function to do real Image preloading.
Should be called in the head of the page.
*/
function preloadImages() {
	var a=preloadImages.arguments;
	var n;
	var imagesLoaded = ""
	for(n=0; n<a.length; n++){
		var oIMG = new Image();
		oIMG.src = a[n];
		var i = document.createElement("img");
		i.src = oIMG.src;
		imagesLoaded += oIMG.src + "\n";
	}
	//alert(imagesLoaded)
}

function getBase()
{
	var baseTag = document.getElementsByTagName("base");
	for(var i=0; i<baseTag.length; i++)
	{
		var baseId = baseTag[i].id;
		var baseHref = baseTag[i].href;
		//alert("ID = "+ baseId +"\nhref = "+ baseHref);
		return baseHref;
	}
}

function cleanText(text)
{
	text = text.replace(/\n/gi,"<br>");
	text = text.replace(/\r/gi,"");
	text = text.replace(/\'/gi,"\"");
	return text;
}

function MM_preloadImages() { //v3.0
	var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
	var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
	if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
	var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.0
	
	var p,i,x;
	if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
		d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);
	}
		
	if(!(x=d[n])&&d.all){
		x=d.all[n];
	}
	for (i=0;!x&&i<d.forms.length;i++){
		x=d.forms[i][n];
	}
	for(i=0;!x&&d.layers&&i<d.layers.length;i++){
		x=MM_findObj(n,d.layers[i].document);
	}
	if(!x && document.getElementById){
		x=document.getElementById(n);
	}
	return x;

}

function MM_swapImage() { //v3.0
	var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
	if ((x=MM_findObj(a[i]))!=null) {
		document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];
	}
}

function MM_showHideLayers() { //v3.0
	var i,p,v,obj,args=MM_showHideLayers.arguments;
	for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) {
		v=args[i+2];
		if (obj.style) {
			obj=obj.style; v=(v=='show')?'visible':(v='hide')?'hidden':v;
		}
		obj.visibility=v;
	}
}


function toggleToolbar(toolbarDiv)
{
	if(toolbarDiv.style.display == "none")
	{
		toolbarDiv.style.display = "block";
		setCookie('toolbarDiv','on');
	}	
	else
	{
		toolbarDiv.style.display = "none";
		setCookie('toolbarDiv','off');
	}
}

function showCB(hideToolsCB,showToolsCB,showInfoCB,showFormCB,showAddItemCB) {
	hideToolsCB.style.display = 'none';
	showToolsCB.style.display = 'block';
	showInfoCB.style.display = 'block';

	if(showFormCB) {
		showFormCB.style.display = 'block';
	}

	if(showAddItemCB) {
		showAddItemCB.style.display = 'block';
	}
}

function hideCB(hideToolsCB,showToolsCB,showInfoCB,showFormCB,showAddItemCB) {
	hideToolsCB.style.display = 'block';
	showToolsCB.style.display = 'none';
	showInfoCB.style.display = 'none';

	if(showFormCB) {
		showFormCB.style.display = 'none';
	}
	
	if(showAddItemCB) {
		showAddItemCB.style.display = 'none';
	}
}


function showCBItems() {
	var cb = showCBItems.arguments[0][0];
	var li = '';

	if(document.getElementById('HIDETOOLSCB' + cb).length) {
		for(var i = 0; i < document.getElementById('HIDETOOLSCB' + cb).length; i++) {
			var hideToolsCB = document.getElementById('HIDETOOLSCB' + cb)[i];
			var showToolsCB = document.getElementById('SHOWTOOLSCB' + cb)[i];
			var showInfoCB = document.getElementById('SHOWINFOCB' + cb)[i];
			
			if(document.getElementById('SHOWFORMCB' + cb)) {
				var showFormCB = document.getElementById('SHOWFORMCB' + cb)[i];	
			}
			
			if(document.getElementById('SHOWADDITEMCB' + cb)) {
				var showAddItemCB = document.getElementById('SHOWADDITEMCB' + cb)[i];
			}
			
			showCB(hideToolsCB,showToolsCB,showInfoCB,showFormCB,showAddItemCB)
		}
	} else {
		
		var hideToolsCB = document.getElementById('HIDETOOLSCB' + cb);
		var showToolsCB = document.getElementById('SHOWTOOLSCB' + cb);
		var showInfoCB = document.getElementById('SHOWINFOCB' + cb);
		var showFormCB = document.getElementById('SHOWFORMCB' + cb);
		if(document.getElementById('SHOWADDITEMCB' + cb)) {
			var showAddItemCB = document.getElementById('SHOWADDITEMCB' + cb);
		}
		showCB(hideToolsCB,showToolsCB,showInfoCB,showFormCB,showAddItemCB)
	}

	for (i = 1; i < showCBItems.arguments[0].length; i++) {
		
		li = showCBItems.arguments[0][i];
		setDisplayStyle('SHOWTOOLSLI' + li, 'block')
		setDisplayStyle('SHOWINFOLI' + li, 'block')		
		setDisplayStyle('SHOWBODYLI' + li, 'block')
	}
}

function setDisplayStyle(sId, sNewDisplay) {
	if (document.getElementById(sId)) {
		if (document.getElementById(sId).length) {
			for(var j = 0; j < document.getElementById(sId).length; j++) {
				document.getElementById(sId)[j].style.display = sNewDisplay;
			}
		} else {
			document.getElementById(sId).style.display = sNewDisplay;
		}		
	} else {
		window.status = 'Did not find element id ' + sId
		return
	}
	
	
	
	
			
}

function hideCBItems() {
	var cb = hideCBItems.arguments[0][0];
	var li = '';


	if(document.getElementById('HIDETOOLSCB' + cb).length) {
		for(var i = 0; i < document.getElementById('HIDETOOLSCB' + cb).length; i++) {
			var hideToolsCB = document.getElementById('HIDETOOLSCB' + cb)[i];
			var showToolsCB = document.getElementById('SHOWTOOLSCB' + cb)[i];
			var showInfoCB = document.getElementById('SHOWINFOCB' + cb)[i];

			if(document.getElementById('SHOWFORMCB' + cb)) {
				var showFormCB = document.getElementById('SHOWFORMCB' + cb)[i];	
			}			
			if(document.getElementById('SHOWADDITEMCB' + cb)) {
				var showAddItemCB = document.getElementById('SHOWADDITEMCB' + cb)[i];
			}
			hideCB(hideToolsCB,showToolsCB,showInfoCB,showFormCB,showAddItemCB)
		}
	} else {
		
		var hideToolsCB = document.getElementById('HIDETOOLSCB' + cb);
		var showToolsCB = document.getElementById('SHOWTOOLSCB' + cb);
		var showInfoCB = document.getElementById('SHOWINFOCB' + cb);
		var showFormCB = document.getElementById('SHOWFORMCB' + cb);
		if(document.getElementById('SHOWADDITEMCB' + cb)) {
			var showAddItemCB = document.getElementById('SHOWADDITEMCB' + cb);
		}
		hideCB(hideToolsCB,showToolsCB,showInfoCB,showFormCB,showAddItemCB)
	}

	for (i = 1; i < hideCBItems.arguments[0].length; i++) {
		li = hideCBItems.arguments[0][i];
		setDisplayStyle('SHOWTOOLSLI' + li, 'none')
		setDisplayStyle('SHOWINFOLI' + li, 'none')
		setDisplayStyle('SHOWBODYLI' + li, 'none')
	}


}



function toggleCBItem() {


	// make all arg good ints
	for(var i = 0; i < toggleCBItem.arguments.length; i++) {
		//toggleCBItem.arguments[i] =parseInt(toggleCBItem.arguments[i])
	}
			
	if(document.getElementById('HIDETOOLSCB' + toggleCBItem.arguments[0]).length) {
		var objHideToolsCB = document.getElementById('HIDETOOLSCB' + toggleCBItem.arguments[0])[0];		
	} else {
		var objHideToolsCB = document.getElementById('HIDETOOLSCB' + toggleCBItem.arguments[0]);		
	}

	
		
	
	if (objHideToolsCB.style.display == 'none') { 
		hideCBItems(toggleCBItem.arguments);		
	} else {			
		showCBItems(toggleCBItem.arguments);	
		
	}
}


/***************************************************************************
* START very important js for navigation
***************************************************************************/
var g_lastHoverMenu = null;
var g_arrTimeouts = new Array();
//millisecond delay before clearing nav on mouse out
var g_delayTime = 1000;

sfHover = function() {
	var portalMainNav = document.getElementById("portalMainNav")

	if(portalMainNav == null) {
		return;			
	} 	
	
	var sfEls = portalMainNav.getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			for(var TOIndex=0; TOIndex < g_arrTimeouts.length; TOIndex++)
			{
				clearTimeout(g_arrTimeouts.pop());				
			}
			
			if(g_lastHoverMenu != null)
			{
				g_lastHoverMenu.className=g_lastHoverMenu.className.replace(new RegExp(" sfhover\\b"), "");
			}
			
			this.className+=" sfhover";
		}
		 
		sfEls[i].onmouseout=function() {
			g_lastHoverMenu = this;			
			g_arrTimeouts.push(setTimeout('g_lastHoverMenu.className=g_lastHoverMenu.className.replace(new RegExp(" sfhover\\\\b"), "");', g_delayTime));
			
		}
	}
}

if (window.addEventListener) { //DOM method for binding an event
	window.addEventListener("load", sfHover, false)
} else if (window.attachEvent) { //IE exclusive method for binding an event
	window.attachEvent("onload", sfHover)
} else if (document.getElementById) { //support older modern browsers	
	window.onload=sfHover
}



/***************************************************************************
* END very important js for navigation
***************************************************************************/



function showSubNav(sSubNavId) {   	
	var subNavUL = document.getElementById(sSubNavId)
   	if(subNavUL) {
   		subNavUL.style.display = 'block';
 	}
   
 }

/*** COOKIE FUNCTIONS ***/

/**
 * Sets a Cookie with the given name and value.
 *
 * name       Name of the cookie
 * value      Value of the cookie
 * [expires]  Expiration date of the cookie (default: end of current session)
 * [path]     Path where the cookie is valid (default: path of calling document)
 * [domain]   Domain where the cookie is valid
 *              (default: domain of calling document)
 * [secure]   Boolean value indicating if the cookie transmission requires a
 *              secure transmission
 */
function setCookie(name, value, expires, path, domain, secure)
{
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

/**
 * Gets the value of the specified cookie.
 *
 * name  Name of the desired cookie.
 *
 * Returns a string containing value of specified cookie,
 *   or null if cookie does not exist.
 */
function getCookie(name)
{
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1)
    {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else
    {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

/**
 * Deletes the specified cookie.
 *
 * name      name of the cookie
 * [path]    path of the cookie (must be same as path used to create cookie)
 * [domain]  domain of the cookie (must be same as domain used to create cookie)
 */
function deleteCookie(name, path, domain)
{
    if (getCookie(name))
    {
        document.cookie = name + "=" + 
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}


function getAllCookieNames()
{					
    	var ca = document.cookie.split(';');
	var cookieNames = Array()
	
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') {
			c = c.substring(1,c.length);
		}				
		cookieNames[cookieNames.length] = c.substring(0, c.indexOf("="));				
	}	
				
	return cookieNames;
}

function showListView(nContentblockId) {
	
	var sNewURL = ''
	if(window.location.search.length > 0) {
		sNewURL = window.location.href.substring(0,window.location.href.indexOf(window.location.search))
	} else {
		sNewURL	= window.location.href
	}
	
	sNewURL += '?contentscreen_id=' + queryString('contentscreen_id') + '&show_event_titles=' + queryString('show_event_titles') + '&date_offset_cal=' + queryString('date_offset_cal') + '#CB' + nContentblockId
	window.location.href = sNewURL	
}
function hideDiv(sID) {
	var oDiv = document.getElementById(sID)
	if(oDiv) {
		oDiv.style.display = 'none'	
	}
}

function showDiv(sID) {
	var oDiv = document.getElementById(sID)
	if(oDiv) {
		oDiv.style.display = 'block'	
	}
}

function PageQuery(q) {
	if(q.length > 1) 
		this.q = q.substring(1, q.length);
	else
	 	this.q = null;
	this.keyValuePairs = new Array();
	if(q) {
		for(var i=0; i < this.q.split("&").length; i++) {
			this.keyValuePairs[i] = this.q.split("&")[i];
		}
	}
	this.getKeyValuePairs = function() { return this.keyValuePairs; }
	
	this.getValue = function(s) {
		for(var j=0; j < this.keyValuePairs.length; j++) {
			if(this.keyValuePairs[j].split("=")[0] == s)
				return this.keyValuePairs[j].split("=")[1];
		}
		return false;
	}
	this.getParameters = function() {
		var a = new Array(this.getLength());
		for(var j=0; j < this.keyValuePairs.length; j++) {
			a[j] = this.keyValuePairs[j].split("=")[0];
		}
		return a;
	}
	this.getLength = function() { return this.keyValuePairs.length; }
}
function queryString(key){
	var page = new PageQuery(window.location.search);
	return unescape(page.getValue(key));
}
function displayItem(key){
	if(queryString(key)=='false')
	{
		document.write("you didn't enter a ?name=value querystring item.");
	}else{
	document.write(queryString(key));
}
}


function focusFirstFormElement() {
	var s = '';
	var oForm = window.document.forms[0]
	if(oForm) {

		for(var i = 0; i<oForm.elements.length; i++) {
			try {
				oForm.elements[i].focus();
				break;

			} catch(e) {

			}
		}
	}
}


function toggleRowSelection(sID, sForceState) {
	var oRow=document.getElementById('row_for_'+ sID);
	var oHiddenInput=document.getElementById('send__'+ sID);
	
	if(getCookie('updateEditFormEmailAction')=='0') {
		return;	
	}
	
	if(oRow) {
		if(sForceState) {
			if(sForceState == 'on') {
				oRow.className="gray";
				oHiddenInput.value = '1';
				editFormSendList(sID,'add')
			} else { 
				oRow.className="";	
				oHiddenInput.value = '0';			
				editFormSendList(sID,'delete')
			}
		} else {
			if(oRow.className == "gray") {
				oRow.className="";	
				oHiddenInput.value = '0';			
				editFormSendList(sID,'delete')
			} else {
				oRow.className="gray";
				oHiddenInput.value = '1';
				editFormSendList(sID,'add')
			}	
		}
		
	}
}

function editFormSendList(sID, sAction) {
	var sEditFormSendList = getCookie('editFormSendList')
	
	if(sEditFormSendList == null) {
		sEditFormSendList = '';	
	}
	
	sEditFormSendList = sEditFormSendList.replace(/,+$/,'')
	
	var arrEditFormSendList = sEditFormSendList.split(',')
		
	if(sAction == 'query') {
		
		for(var i = 0 ; i < arrEditFormSendList.length; i++) {
			if(arrEditFormSendList[i] == sID) {
				return true;	
			}						
		}
		return false;
		
	} else if(sAction == 'add') {
		var bFound = false;
		for(var i = 0 ; i < arrEditFormSendList.length; i++) {
			if(arrEditFormSendList[i] == sID) {
				bFound = true;
				break;				
			}						
		}
		if(!bFound) {
			if(sEditFormSendList.length == 0) {
				sEditFormSendList = sID
			} else {
				sEditFormSendList += ',' + sID
			}
			
			setCookie('editFormSendList',sEditFormSendList)
		}
				
	} else if(sAction == 'delete') {
		sEditFormSendList = ''
		for(var i = 0 ; i < arrEditFormSendList.length; i++) {
			if(arrEditFormSendList[i] == sID) {
				arrEditFormSendList[i] = null;				
			}
		}
		
		for(var i = 0 ; i < arrEditFormSendList.length; i++) {
			if(arrEditFormSendList[i] != null) {
				sEditFormSendList += arrEditFormSendList[i] + ','
			}
		}
		
		sEditFormSendList = sEditFormSendList.replace(/,+$/,'')
		setCookie('editFormSendList',sEditFormSendList)
	} else if(sAction == 'queryraw') {
		return sEditFormSendList;
		
	} else if(sAction == 'deleteall') {
		setCookie('editFormSendList','')
		
	}
	
} 


function syncEditFormToggleStatus(oForm) {
	
	if(!getCookie('updateEditFormEmailAction')) {
		setCookie('updateEditFormEmailAction','0')
	}
	
	if(oForm.send_mail_to_submitter[0].value == getCookie('updateEditFormEmailAction')) {
		oForm.send_mail_to_submitter[0].checked = true;
		updateEditFormEmailAction(oForm)
	} else {
		oForm.send_mail_to_submitter[1].checked = true;
	}
	//alert(getCookie('updateEditFormEmailAction'))
	
	
	if(getCookie('updateEditFormEmailAction')=='1') {
		document.getElementById('send_mail_to_submitter_options').style.display='block';
		//alert('show')
	} else {
		document.getElementById('send_mail_to_submitter_options').style.display='none';
		//alert('hide')
	}
	
	
	
	for(var i = 0; i<oForm.elements.length;i++) {
		if(oForm.elements[i].name.indexOf('send__field') == 0 ) {
			if(editFormSendList(oForm.elements[i].name.substring(6),'query')) {
				toggleRowSelection(oForm.elements[i].name.substring(6), 'on')
			}
		}
	}
}

function updateEditFormEmailAction(oForm){

	
	if(oForm.send_mail_to_submitter[0].value == '0' && oForm.send_mail_to_submitter[0].checked) {
		setCookie('updateEditFormEmailAction','0')
		document.getElementById('send_mail_to_submitter_options').style.display='none';
		// do not send email
		var s = '';
		for(var i = 0; i<oForm.elements.length ; i++) {
			if(oForm.elements[i].name.indexOf('field') == 0 ) {
				var oRow=document.getElementById('row_for_'+ oForm.elements[i].name);
				var oHiddenInput=document.getElementById('send__'+ oForm.elements[i].name);
				if(oRow) {
					oRow.className="";
					oHiddenInput.value = '0';
				}
				s += oForm.elements[i].name + '\n'

			}
			//alert(s)
		}
	} else {
		setCookie('updateEditFormEmailAction','1')
		document.getElementById('send_mail_to_submitter_options').style.display='block';
		// do send email
		syncEditFormToggleStatus(oForm)
	}

}

// note: less strict than VBScript's isDate, since JS allows invalid dates to overflow (e.g. Jan 32 transparently becomes Feb 1)
function isDate(p_Expression){
	return !isNaN(new Date(p_Expression));		// <<--- this needs checking
}


// REQUIRES: isDate()
function dateAdd(p_Interval, p_Number, p_Date){
	if(!isDate(p_Date)){return "invalid date: '" + p_Date + "'";}
	if(isNaN(p_Number)){return "invalid number: '" + p_Number + "'";}	

	p_Number = new Number(p_Number);
	var dt = new Date(p_Date);
	switch(p_Interval.toLowerCase()){
		case "yyyy": {// year
			dt.setFullYear(dt.getFullYear() + p_Number);
			break;
		}
		case "q": {		// quarter
			dt.setMonth(dt.getMonth() + (p_Number*3));
			break;
		}
		case "m": {		// month
			dt.setMonth(dt.getMonth() + p_Number);
			break;
		}
		case "y":		// day of year
		case "d":		// day
		case "w": {		// weekday
			dt.setDate(dt.getDate() + p_Number);
			break;
		}
		case "ww": {	// week of year
			dt.setDate(dt.getDate() + (p_Number*7));
			break;
		}
		case "h": {		// hour
			dt.setHours(dt.getHours() + p_Number);
			break;
		}
		case "n": {		// minute
			dt.setMinutes(dt.getMinutes() + p_Number);
			break;
		}
		case "s": {		// second
			dt.setSeconds(dt.getSeconds() + p_Number);
			break;
		}
		case "ms": {		// second
			dt.setMilliseconds(dt.getMilliseconds() + p_Number);
			break;
		}
		default: {
			return "invalid interval: '" + p_Interval + "'";
		}
	}
	return dt;
}


// REQUIRES: isDate()
// NOT SUPPORTED: firstdayofweek and firstweekofyear (defaults for both)
function dateDiff(p_Interval, p_Date1, p_Date2, p_firstdayofweek, p_firstweekofyear){
	if(!isDate(p_Date1)){return "invalid date: '" + p_Date1 + "'";}
	if(!isDate(p_Date2)){return "invalid date: '" + p_Date2 + "'";}
	var dt1 = new Date(p_Date1);
	var dt2 = new Date(p_Date2);

	// get ms between dates (UTC) and make into "difference" date
	var iDiffMS = dt2.valueOf() - dt1.valueOf();
	var dtDiff = new Date(iDiffMS);

	// calc various diffs
	var nYears  = dt2.getUTCFullYear() - dt1.getUTCFullYear();
	var nMonths = dt2.getUTCMonth() - dt1.getUTCMonth() + (nYears!=0 ? nYears*12 : 0);
	var nQuarters = parseInt(nMonths/3);	//<<-- different than VBScript, which watches rollover not completion
	
	var nMilliseconds = iDiffMS;
	var nSeconds = parseInt(iDiffMS/1000);
	var nMinutes = parseInt(nSeconds/60);
	var nHours = parseInt(nMinutes/60);
	var nDays  = parseInt(nHours/24);
	var nWeeks = parseInt(nDays/7);


	// return requested difference
	var iDiff = 0;		
	switch(p_Interval.toLowerCase()){
		case "yyyy": return nYears;
		case "q": return nQuarters;
		case "m": return nMonths;
		case "y": 		// day of year
		case "d": return nDays;
		case "w": return nDays;
		case "ww":return nWeeks;		// week of year	// <-- inaccurate, WW should count calendar weeks (# of sundays) between
		case "h": return nHours;
		case "n": return nMinutes;
		case "s": return nSeconds;
		case "ms":return nMilliseconds;	// millisecond	// <-- extension for JS, NOT available in VBScript
		default: return "invalid interval: '" + p_Interval + "'";
	}
}


// REQUIRES: isDate()
// NOT SUPPORTED: firstdayofweek and firstweekofyear (defaults for both)
function dateDiff(p_Interval, p_Date1, p_Date2, p_firstdayofweek, p_firstweekofyear){
	if(!isDate(p_Date1)){return "invalid date: '" + p_Date1 + "'";}
	if(!isDate(p_Date2)){return "invalid date: '" + p_Date2 + "'";}
	var dt1 = new Date(p_Date1);
	var dt2 = new Date(p_Date2);

	// get ms between dates (UTC) and make into "difference" date
	var iDiffMS = dt2.valueOf() - dt1.valueOf();
	var dtDiff = new Date(iDiffMS);

	// calc various diffs
	var nYears  = dt2.getUTCFullYear() - dt1.getUTCFullYear();
	var nMonths = dt2.getUTCMonth() - dt1.getUTCMonth() + (nYears!=0 ? nYears*12 : 0);
	var nQuarters = parseInt(nMonths/3);	//<<-- different than VBScript, which watches rollover not completion
	
	var nMilliseconds = iDiffMS;
	var nSeconds = parseInt(iDiffMS/1000);
	var nMinutes = parseInt(nSeconds/60);
	var nHours = parseInt(nMinutes/60);
	var nDays  = parseInt(nHours/24);
	var nWeeks = parseInt(nDays/7);


	// return requested difference
	var iDiff = 0;		
	switch(p_Interval.toLowerCase()){
		case "yyyy": return nYears;
		case "q": return nQuarters;
		case "m": return nMonths;
		case "y": 		// day of year
		case "d": return nDays;
		case "w": return nDays;
		case "ww":return nWeeks;		// week of year	// <-- inaccurate, WW should count calendar weeks (# of sundays) between
		case "h": return nHours;
		case "n": return nMinutes;
		case "s": return nSeconds;
		case "ms":return nMilliseconds;	// millisecond	// <-- extension for JS, NOT available in VBScript
		default: return "invalid interval: '" + p_Interval + "'";
	}
}


function userObservesDaylightSaving() {
	var oDate = new Date()
	var oDate1 = dateAdd('m', 6, oDate)

	//oDate.getTimezoneOffset()
	if(oDate.getTimezoneOffset() != oDate1.getTimezoneOffset()) {
		return '1';
	} else {
		return '0';
	}
}

function userIsInDaylightSavingTime() {
	if(userObservesDaylightSaving() == '0') {
		return '0';	
	} else {
		var oDate = new Date()
		var oDate1 = dateAdd('m', 6, oDate)
		var nCurrOffset = oDate.getTimezoneOffset()
		var nLaterOffset = oDate1.getTimezoneOffset()
		//alert(nCurrOffset+  ' ; ' +  nLaterOffset)
		if(nCurrOffset < nLaterOffset) {
			return '1';
		} else {
			return '0';
		}
	}
}

/** EXPAND-COLLAPSE CONTENTBLOCK FUNCTIONS **/
cookieDate = new Date();
document.cbArray = new Array();


function toggleCBViewSize(CBID, setState)
{
	var fullview = document.getElementById("fullview" + CBID);
	var shortview = document.getElementById("shortview" + CBID);
	var toggleImg = document.getElementById("toggleCBViewImg" + CBID);
	var viewState;
	
	if(setState != undefined)
	{
		viewState = setState;
	}
	else
	{
		viewState = "";
	}
	
	if((fullview.style.display == 'block' || viewState == "collapse") && viewState != "expand")
	{
		fullview.style.display = 'none';
		shortview.style.display = 'block';
		toggleImg.src = "images/btn.collapse.gif";
		removeViewCookie(CBID, "fullview" + siteUser);
		appendViewCookie(CBID, "shortview" + siteUser);		
	}
	else// if(fullview.style.display != 'block' || viewState == "expand")
	{
		fullview.style.display = 'block';
		shortview.style.display = 'none';
		toggleImg.src = "images/btn.contract.gif";
		removeViewCookie(CBID, "shortview" + siteUser);
		appendViewCookie(CBID, "fullview" + siteUser);
	}
	
	// resize this iframe now..
	// ideally we'd also check to make sure that this iframe block is set to auto height.
	var iFrames = document.getElementsByTagName("IFRAME")
	for(var i = 0; i<iFrames.length;i++) {
 		if(iFrames[i].id.indexOf('iframe_block_'+CBID) == 0) {
  			setIframeHeightToScrollHeight(iFrames[i].id)
 		}
	}
}

function appendViewCookie(CBID, viewType)
{
	var viewCookie = getCookie(viewType);
	if(viewCookie != null)
	{
		var bCBIDExists = false;
		var cbidArray = viewCookie.split(",");
		for(var x = 0; x < cbidArray.length; x++)
		{
			if(cbidArray[x] == CBID)
			{
				bCBIDExists = true;
				break;	
			}
		}
		
		if(!bCBIDExists)
		{
			cbidArray.push(CBID);
			setCookie(viewType, cbidArray.join(","), new Date(cookieDate.getFullYear() + 1, cookieDate.getMonth(), cookieDate.getDate()));
		}
	}
	else
	{
		setCookie(viewType, CBID, new Date(cookieDate.getFullYear() + 1, cookieDate.getMonth(), cookieDate.getDate()));
	}
}

function removeViewCookie(CBID, viewType)
{
	var viewCookie = getCookie(viewType);
	if(viewCookie != null)
	{
		var cbidArray = viewCookie.split(",");
		for(var x = 0; x < cbidArray.length; x++)
		{
			if(cbidArray[x] == CBID)
			{
				cbidArray.splice(x,1);
				break;	
			}
		}
		
		setCookie(viewType, cbidArray.join(","), new Date(cookieDate.getFullYear() + 1, cookieDate.getMonth(), cookieDate.getDate()));
	}
}


function isInViewCookie(CBID, viewType)
{
	var bCBIDExists = false;
	var viewCookie = getCookie(viewType);
	
	if(viewCookie != null)
	{
		var cbidArray = viewCookie.split(",");	
			
		for(var x = 0; x < cbidArray.length; x++)
		{
			if(cbidArray[x] == CBID)
			{
				bCBIDExists = true;
				break;	
			}
		}
	}

	return bCBIDExists;
}


function syncCBViewState(CBID, defaultView)
{
	var viewSizeImg;
	//alert("syncCBViewState CALLED")
	if(document.getElementById("toggleCBViewImg" + CBID))
	{
		if(defaultView == "fullview" && isInViewCookie(CBID,"shortview" + siteUser))
		{
			toggleCBViewSize(CBID);	
		}
		else if(defaultView == "shortview" && isInViewCookie(CBID,"fullview" + siteUser))
		{
			toggleCBViewSize(CBID);	
		}
		
	}
	//alert("syncCBViewState DONE")
}

function clearAllViewCookies()
{
		clearShortViewCookie();
		clearFullViewCookie();
		window.location.reload();
}

function clearShortViewCookie()
{
	deleteCookie("shortview" + siteUser);	
}

function clearFullViewCookie()
{
	deleteCookie("fullview" + siteUser);	
}



function showTools(sCSid, sCBid)
{
	var sLinkId = 'showToolsLinkCB' + sCBid + 'CS' + sCSid
	var aLink = document.getElementById(sLinkId)
	if (aLink) {  
	    var clickText = aLink.onclick + ''	    
	    clickText = clickText.replace(/.*\n?{/gm,'').replace(/}[\s\n]*$/gm,'')
	    eval(clickText)
	}
}

function toggleToolCookie()
{
	var sCookie = '' + getCookie('showHideTools');
	sCookie = (sCookie == 'on') ? 'off' : 'on';
	
	setCookie('showHideTools', sCookie);
}

function showHideTools()
{
	var allDivs = document.getElementsByTagName("div");
	var allSpans = document.getElementsByTagName("span");
	var allPs = document.getElementsByTagName("p");
	var allAnchors = document.getElementsByTagName("a");
	
	
	//first, close all the CB editing tools
	for(var x=0; x < allAnchors.length; x++)
	{
		if(allAnchors[x].onclick)
		{
			if((allAnchors[x].onclick).toString().indexOf("toggleCBItem") > -1)
			{
				var clickString = (allAnchors[x].onclick).toString();
				var start = clickString.indexOf("toggleCBItem");
				var CBID = clickString.substring(start + 14, clickString.indexOf("'", start + 15))
				var theDiv = document.getElementById("SHOWTOOLSCB" + CBID);
				
				if(theDiv)
				{
					if(theDiv.style.display != "none")
					{
						eval(clickString.substring(start, clickString.indexOf(";", start) +1));
					}
				}
			}
		}
	}
	
	if(document.getElementById("f_trigger_b"))
	{
		var dateLink = document.getElementById("f_trigger_b");
		
		if(dateLink.style.display != "none")
		{
			dateLink.style.display = "none";
		}
		else
		{
			dateLink.style.display = "inline";
		}		
	}
	
	
	//hide the Add Block link and editing tools
	for(var x=0; x < allDivs.length; x++)
	{
		if(allDivs[x].className != "")
		{
			if(allDivs[x].className == "newblock" ||
				allDivs[x].className == "blocktools" ||
				allDivs[x].className == "pendingExpiredBlocksDiv")
			{
				if(allDivs[x].style.display == "none")
				{
					allDivs[x].style.display = "block";
				}
				else
				{
					allDivs[x].style.display = "none";	
				}
			}
		}
	}
	
	//hide workflow text and LI-related buttons
	for(var x=0; x<allSpans.length; x++)
	{
		if(allSpans[x].className != "")
		{
			if(allSpans[x].className == "workflow")
			{
				if(allSpans[x].style.display == "none")
				{
					allSpans[x].style.display = "inline";		
				}
				else
				{
					allSpans[x].style.display = "none";	
				}
			}
		}
	}

}  //end showHideTools()

function expandAllCB()
{
	var cbs = document.cbArray;
	var img;
	for(var x=0; x < cbs.length; x++)
	{
		if(document.getElementById("toggleCBViewImg" + cbs[x]))
		{
			toggleCBViewSize(cbs[x], "expand");
		}
	}
}

function collapseAllCB()
{
	var cbs = document.cbArray;
	var img;
		
	for(var x=0; x < cbs.length; x++)
	{
		if(document.getElementById("toggleCBViewImg" + cbs[x]))
		{
			toggleCBViewSize(cbs[x], "collapse");
		}
	}
	

}





function swapObjectLocations(oA, oB) {
	var sTempHTML = oA.innerHTML
	var sTempID = oA.id
	oA.innerHTML = oB.innerHTML
	oA.id = oB.id
	oB.innerHTML = sTempHTML
	oB.id = sTempID
}

function getMovableCSId(sID){
	if(sID.indexOf('movable-') != 0 ) {
		return -1;
	} else {
		return sID.split('-')[2].split('_')[1]
	}
}

function getMovableCBId(sID){
	if(sID.indexOf('movable-') != 0 ) {
		return -1;
	} else {
		return sID.split('-')[1].split('_')[1]
	}
}



function getMovableLILIId(sID){
	if(sID.indexOf('limovable-') != 0 ) {
		return -1;
	} else {
		return sID.split('-')[3].split('_')[1]
	}
}

function getMovableLICBId(sID){
	if(sID.indexOf('limovable-') != 0 ) {
		return -1;
	} else {
		return sID.split('-')[1].split('_')[1]
	}
}

function getMovableLICSId(sID){
	if(sID.indexOf('limovable-') != 0 ) {
		return -1;
	} else {
		return sID.split('-')[2].split('_')[1]
	}
}


function getPortalBaseURL() {
	// should be like [http://www.pmg.net:81/portal]
	// var sBasePath = document.location.href.substring(0,document.location.href.indexOf('/',document.location.href.indexOf('/',document.location.href.indexOf('//')+2)+1))
	var sBasePath = document.location.href.substring(0,document.location.href.indexOf('/',8)) + '/' + document.portalid
	return sBasePath
}

function moveThisBlock(sThisId, sDirection) {
	var sIDToSwapWith = findNeighborCB(sThisId,sDirection)
	//alert('swaping ' + sThisId + ' -- with ' + sIDToSwapWith)
	
	if(sIDToSwapWith != '') {
		var sURL = ''
		
		// 1 == down
		// 0 == up
		if(sDirection == 'down') {
			sURL = getPortalBaseURL() + '/site.cb.move.asp?contentblock_id=' + getMovableCBId(sThisId) + '&contentscreen_id=' + getMovableCSId(sThisId) + '&contentblock_direction=1'
		} else {
			sURL = getPortalBaseURL() +'/site.cb.move.asp?contentblock_id=' + getMovableCBId(sThisId) + '&contentscreen_id=' + getMovableCSId(sThisId) + '&contentblock_direction=0'
		}
		//alert(sURL)
	
		setTimeout('makeMoveBlockCall(\'' + sURL + '\')',1);		
		//makeMoveBlockCall(sURL)
		swapObjectLocations(document.getElementById(sThisId), document.getElementById(sIDToSwapWith))
	}
}

function moveThisLI(sThisId, sDirection) {
	var sIDToSwapWith = findNeighborLI(sThisId,sDirection)
	//alert('swaping ' + sThisId + ' -- with ' + sIDToSwapWith)
	
	if(sIDToSwapWith != '') {
		var sURL = ''
		
		// 1 == down
		// 0 == up
		if(sDirection == 'down') {
			sURL = getPortalBaseURL() + '/site.li.move.asp?listitem_id=' + getMovableLILIId(sThisId) + '&contentblock_id=' + getMovableLICBId(sThisId) + '&contentscreen_id=' + getMovableLICSId(sThisId) + '&contentblock_direction=1'
		} else {
			sURL = getPortalBaseURL() +'/site.li.move.asp?listitem_id=' + getMovableLILIId(sThisId) + '&contentblock_id=' + getMovableLICBId(sThisId) + '&contentscreen_id=' + getMovableLICSId(sThisId) + '&contentblock_direction=0'
		}
		//alert(sURL)	
		swapObjectLocations(document.getElementById(sThisId), document.getElementById(sIDToSwapWith))
		setTimeout('makeMoveLICall(\'' + sURL + '\')',5);		
		//makeMoveLICall(sURL)
		//swapObjectLocations(document.getElementById(sThisId), document.getElementById(sIDToSwapWith))
	}
}





function findNeighborCB(sID,sDirection) {
	var sThisCB = getMovableCBId(sID)
	var sThisCS = getMovableCSId(sID)
	var sNeighborID = ''
	var arrCBs = document.getElementsByTagName('DIV')
	var bFoundSelf = false
	if(sDirection == 'down') {
		for(var i = 0; i < arrCBs.length ;i++){
			// if pending or expired, skip
			if(arrCBs[i].parentNode.id.indexOf('CBPENDING_')==0 || arrCBs[i].parentNode.id.indexOf('CBEXPIRED_')==0) {
				continue;
			}
			
			if(getMovableCSId(arrCBs[i].id) == sThisCS) {
				if(getMovableCBId(arrCBs[i].id) == sThisCB) {
					bFoundSelf = true
				}

				if(getMovableCBId(arrCBs[i].id) != sThisCB && bFoundSelf) {
					sNeighborID = arrCBs[i].id
					break;
				}
			}
		}
	}

	if(sDirection == 'up') {
		for(var i = arrCBs.length-1; i >= 0 ;i--){
			// if pending or expired, skip
			if(arrCBs[i].parentNode.id.indexOf('CBPENDING_')==0 || arrCBs[i].parentNode.id.indexOf('CBEXPIRED_')==0) {
				continue;
			}
			if(getMovableCSId(arrCBs[i].id) == sThisCS) {
				if(getMovableCBId(arrCBs[i].id) == sThisCB) {
					bFoundSelf = true
				}

				if(getMovableCBId(arrCBs[i].id) != sThisCB && bFoundSelf) {
					sNeighborID = arrCBs[i].id
					break;
				}
			}
		}
	}


	return sNeighborID;
}



function findNeighborLI(sID,sDirection) {
	var sThisCB = getMovableLICBId(sID)
	var sThisCS = getMovableLICSId(sID)
	var sThisLI = getMovableLILIId(sID)
	
	var sNeighborID = ''
	var arrLIs = document.getElementsByTagName('LI')
	var bFoundSelf = false
	if(sDirection == 'down') {
		for(var i = 0; i < arrLIs.length ;i++){
			if(getMovableLICSId(arrLIs[i].id) == sThisCS) {
				if(getMovableLICBId(arrLIs[i].id) == sThisCB) {
					if(getMovableLILIId(arrLIs[i].id) == sThisLI) {
						bFoundSelf = true
					}
				}

				if(getMovableLILIId(arrLIs[i].id) != sThisLI && getMovableLICBId(arrLIs[i].id) == sThisCB && bFoundSelf) {
					sNeighborID = arrLIs[i].id
					break;
				}
			}
		}
	}

	
	if(sDirection == 'up') {		
		for(var i = arrLIs.length-1; i >= 0 ;i--){
			if(getMovableLICSId(arrLIs[i].id) == sThisCS) {
				if(getMovableLICBId(arrLIs[i].id) == sThisCB) {
					if(getMovableLILIId(arrLIs[i].id) == sThisLI) {
						bFoundSelf = true						
					}
				}

				if(getMovableLILIId(arrLIs[i].id) != sThisLI && getMovableLICBId(arrLIs[i].id) == sThisCB && bFoundSelf) {
					sNeighborID = arrLIs[i].id
					break;
				}
			}
		}
	}
	

	return sNeighborID;
}


function getHTTPRequest()  {
	var C=null;
	try {
		C=new ActiveXObject("Msxml2.XMLHTTP")
	}
	catch(e) {
		try {
			C=new ActiveXObject("Microsoft.XMLHTTP")
		}
		catch(sc) {
			C=null
		}
	}
	if(!C&&typeof XMLHttpRequest!="undefined") {
		C=new XMLHttpRequest()
	}
	return C
}

function makeMoveLICall(sURL) {	
	var nResponse = parseInt(ajaxRawQuery(sURL))	
	if(nResponse != 1){
		alert('The list item was not moved.')
	}
}

function makeMoveBlockCall(sURL) {
	if(!parseInt(ajaxRawQuery(sURL))){
		alert('The block was not moved.')
	}
}

function ajaxRawQuery(sURL, sParams)
{
	var xmlDoc;
	var xReq = getHTTPRequest();	
	if(sParams) {
		xReq.open("POST", sURL, false);
		xReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		xReq.send(sParams);
	} else {
		xReq.open("GET", sURL, false);
		xReq.send(null);
	}
	
	return xReq.responseText;	
}


function objectToHTML(obj){
	var s = '<xmp>';
	var sVal = '';
	for(var x in obj) {
		try {
			eval('sVal = obj.' + x)
		} catch (error) {
			eval('sVal = null')
		}
		
		if(sVal != null) {		
			s += x + ':' + sVal + '\n\n'
		}		
	}
	
	s += '</xmp>'
	
	return s;		
}


function getOuterHTML(oObject) {
	
	var sOuterHTML = ''
	var oClonedObject = oObject.cloneNode(true)	
	var objSpan = document.createElement("SPAN");
	objSpan.appendChild(oClonedObject)	
	sOuterHTML = objSpan.innerHTML
	objSpan.removeChild(oClonedObject)
	objSpan = null	
	return sOuterHTML;
	
	
}

function showCBEditBox(oEditControl, nCB, nCS){
	var bFoundCBSpan = false
	var oCBSpan = oEditControl
	while(oCBSpan.parentNode) {
		oCBSpan = oCBSpan.parentNode
		
		if(oCBSpan.id && oCBSpan.id.indexOf('movable-')==0){
			bFoundCBSpan = true
			break;
		}
	}
	
	if(bFoundCBSpan) {
		loadEditIframe(oCBSpan, nCB, nCS)		
	}	
}

function hideCBEditIframe() {
	var tempIFrame=getCBEditIframe();		
	 tempIFrame.style.position = 'absolute'
	 tempIFrame.style.border='0px';
    tempIFrame.style.width='0px';   
    tempIFrame.style.top = '-500'
    tempIFrame.style.left = '-500'
    tempIFrame.style.height='0px';
}



function updateCBEditIframe(bShowTools, nCB, nCS) {
	var sActions = 'closeAllCBEditIframes();hideSubmittedForms();'
	
	if(bShowTools) {
		sActions += 'showTools(' + nCS + ', ' + nCB + ');'
	}
	
	setTimeout(sActions,1);	
}

function duplicateCB(nCB, nCS) {
	var sURL = getPortalBaseURL() + '/site.cb.create.asp?contentblock_id=' + nCB + '&contentscreen_id=' + nCS + '&Validate=1&makeDuplicate=1'
	var sResponse = ajaxRawQuery(sURL)
	
	
	// change to make lots of data
	var nCopyCount = 0
	if((nCopyCount>0) && confirm('Really make ' + nCopyCount + ' extra copies?')) {
		for(var i = 1; i < nCopyCount ; i++) {
			var sResponse = ajaxRawQuery(sURL)
		}
	}
	
	
	
	if(parseInt(sResponse) == 1){
		alert('Copy success, page reloading.')
		window.location = window.location.href
	} else if(parseInt(sResponse) == 0){
		alert('Copy failed. Permission denied')
	} else {
		alert('Copy failed.\n' + sResponse)
	}
		
		
	
}

function closeAllCBEditIframes() {
	if(document.tempCBs) {
		for(var x in document.tempCBs) {
			document.getElementById(x).innerHTML = document.tempCBs[x]			
			document.tempCBs[x] = ""
			if(document.getElementById('CBEditiFrame-' + x)){
				//alert('found iframe: ' + 'CBEditiFrame-' + x)	
			}
		}
	}
	document.tempCBs = new Object()
}

//if(document.iframeForCloning == null){
//	document.iframeForCloning = document.createElement('iframe');
//}

function loadEditIframe(oCBSpan, nCB, nCS) {		
	if(!document.tempCBs) {
		document.tempCBs = new Object()
	}

	
	document.tempCBs[oCBSpan.id] = oCBSpan.innerHTML
	//alert(document.tempCBs[oCBSpan.id])
	//alert(document.tempCBs.length)
	for(var x in document.tempCBs) {
		if(oCBSpan.id != x) {
			document.getElementById(x).innerHTML = document.tempCBs[x]
		}
	}
	
	var sURL = getPortalBaseURL() + '/site.cb.edit.asp?contentblock_id=' + nCB + '&contentscreen_id=' + nCS
	
	//var tempIFrame = document.createElement('iframe');	
	//var tempIFrame = document.iframeForCloning.cloneNode(false)
	var tempIFrame = document.getElementById('cloneIFrameForCBEdit').cloneNode(false)
	
	tempIFrame.setAttribute('id','CBEditiFrame-' + oCBSpan.id);
	tempIFrame.id = 'CBEditiFrame-' + oCBSpan.id
	//tempIFrame.onload = setIframeHeightToScrollHeight('CBEditiFrame-' + oCBSpan.id);
	//tempIFrame.style.width='100%';
	tempIFrame.style.width='500px';
	tempIFrame.style.height='0px';
	tempIFrame.style.display = 'block'
	
	
	if(true){
		// this seems to make loading go faster (it appears that way to the end users!)
		var sExecString = ''
		sExecString = 'document.getElementById(\'CBEditiFrame-' + oCBSpan.id + '\').src = \'' + sURL + '\';'
		setTimeout(sExecString,1)
		//movable-CB_365-CS_11		
	} else {
		tempIFrame.src = sURL
	}
	//oCBSpan.parentNode.appendChild(tempIFrame)

	oCBSpan.innerHTML = '<span id="editLoadingText">' + oCBSpan.innerHTML + 'loading editor, please wait.</span><div style="text-align:center">' + getOuterHTML(tempIFrame) + '</div>'
   return tempIFrame;
   
}



function validateCustomForm(sForm, sValidateArgs) {
	var bValidated = true;
	
	
	if(sValidateArgs.length == 0) {
		return true;
	}

	if(sValidateArgs.length > 2) {
		if(sValidateArgs.substring(sValidateArgs.length-2) == '||') {
			sValidateArgs = sValidateArgs.substring(0,sValidateArgs.length-2)
		}
	}

	var arrValidateArgs = sValidateArgs.split('||')

	for(var i=0;i < arrValidateArgs.length;i+=3){
		//alert(arrValidateArgs[i] + ' - ' + arrValidateArgs[i+1] + ' ; ' + arrValidateArgs[i+2])
		var fTempFunc = null
		var oTempFormObject = null
		var sTempMessage = ''
		var oTempForm = null

		eval('fTempFunc = ' + arrValidateArgs[i])
		eval('oTempFormObject = document.forms["' + sForm + '"].elements["' + arrValidateArgs[i+1] + '"]')
		eval('oTempForm = document.forms["' + sForm + '"]')
		sTempMessage = arrValidateArgs[i+2]

		//alert(typeof(fTempFunc))
		//alert(typeof(oTempFormObject))
		if (bValidated) {
			bValidated = fTempFunc(oTempFormObject,sTempMessage) ? true : false;
		}
		if(!bValidated) {
			break;
		}		
	}


	if (bValidated) {

		for(i = 0; i<oTempForm.elements.length; i++){
			if(oTempForm.elements[i].type=="button"){
				oTempForm.elements[i].disabled=true;
			}
			if(oTempForm.elements[i].type=="submit"){
				oTempForm.elements[i].disabled=true;
			}
		}
	}

	return bValidated;
}//end function


function setupLICalendar(sID) {
	Calendar.setup({inputField:"dp_date" + sID,
		ifFormat       :    "%m/%d/%Y",
		daFormat       :    "%m/%d/%Y",
		showsTime      :    false,
		button:"dp_trigger" + sID,displayArea:"dp_span" + sID,
		singleClick    :    true,
		step           :    1,
		bDatePicker	   :    true
	});	
}



function toggleShowHideCBResponses(sID) {
	
	var oObject = document.getElementById('SHOWRESPONSESCB' + sID)	
	if(oObject==null) {
		alert('falied to get ' + 'SHOWRESPONSESCB' + sID)
		return
	}
	if(oObject.style.display != 'block') {
		oObject.style.display = 'block'
	} else {
		oObject.style.display = 'none'
	}
	
	setIframeHeightToScrollHeight('portalContent')
}


function updateFileTitle(sSrc, sDest) {
	var arrDests = sDest.split(',')
	
	for(var i = 0; i < arrDests.length;i++) {
		if(arrDests[i].length > 0) {
			var sFile = document.getElementById(sSrc).value
			var sFilename = document.getElementById(arrDests[i])
			
			if(sFilename == null){
				continue;
			}
			
	
			sFile = sFile.replace(/\//g,"\\")
			if(sFile.lastIndexOf("\\")>=0) {
   				sFilename.value = sFile.substring(sFile.lastIndexOf("\\")+1)
			}		
		}		
	}
}

function createUpdateFileTitleEvent(/*sSrc, sDest1, sDest2, etc. */) {
	var sSrc = createUpdateFileTitleEvent.arguments[0]
	var sTemp = ''
	
	if(document.getElementById(sSrc) == null){
		return;
	}
	
	for(var i = 1; i<createUpdateFileTitleEvent.arguments.length;i++) {
		sTemp += createUpdateFileTitleEvent.arguments[i] + ',';
		
	}
	document.getElementById(sSrc).onchange = function() {eval('updateFileTitle(\'' + sSrc + '\',\'' + sTemp + '\');')}

}

function hideSubmittedForms(){
	
	var sSubmittedFormCbs = getCookie('submittedFormCbs')
	
	
	if(sSubmittedFormCbs==null) {
		return;
	}
		
	var arrSubmittedFormCbs = sSubmittedFormCbs.split(",");
	for(var i=0; i<	arrSubmittedFormCbs.length;i++) {		
		if(document.getElementById("no_multiple_submit_msg_" + arrSubmittedFormCbs[i]) != null) {
			document.getElementById("no_multiple_submit_msg_" + arrSubmittedFormCbs[i]).style.display = 'block'
			document.getElementById("no_multiple_submit_form_" + arrSubmittedFormCbs[i]).style.display = 'none'
		}
	}
}

function deleteContentBlock(nCB, nCS) {
	if(confirm('Really delete this content block?')){
		var sURL = getPortalBaseURL() + '/site.cb.delete.asp?contentblock_id=' + nCB + '&contentscreen_id=' + nCS + '&Validate=1'
		var nResponse = parseInt(ajaxRawQuery(sURL))	
		if(nResponse != 1){
			alert('Error, the item was not deleted.')
		} else {
			var sSpanIdToKill = 'movable-CB_' + nCB + '-CS_' + nCS
			var oBlockParent = document.getElementById(sSpanIdToKill).parentNode
			oBlockParent.removeChild(document.getElementById(sSpanIdToKill))
		}
	}
}

function deleteListItem(nCB, nCS, nLId) {
	if(confirm('Really delete this list item?')){
		var sURL = getPortalBaseURL() + '/site.li.delete.asp?contentblock_id=' + nCB + '&contentscreen_id=' + nCS + '&listitem_id=' + nLId + '&Validate=1'
		var nResponse = parseInt(ajaxRawQuery(sURL))			
		if(nResponse != 1){
			alert('Error, the item was not deleted. ' + ajaxRawQuery(sURL))
			
		} else {
			var sSpanIdToKill = 'limovable-CB_' + nCB + '-CS_' + nCS + '-LI_' + nLId
			var oBlockParent = document.getElementById(sSpanIdToKill).parentNode
			oBlockParent.removeChild(document.getElementById(sSpanIdToKill))
		
		}
	}
}

/*** START ***  IF using MOZ (non-IE) these make it work more like IE *************/
if(document.all == null){
	
	Node.prototype.removeNode = function( removeChildren ) {
		var self = this;
		if ( Boolean( removeChildren ) ) {
			return this.parentNode.removeChild( self );
		} else {
			var range = document.createRange();
			range.selectNodeContents( self );
			return this.parentNode.replaceChild( range.extractContents(), self );		
		}
	}
	
	Node.prototype.__defineGetter__("xml", 
		function _Node_getXML() {
   	    //create a new XMLSerializer
   		var objXMLSerializer = new XMLSerializer;
   
	    //get the XML string
   		var strXML = objXMLSerializer.serializeToString(this);
   
   	 	//return the XML string
   		return strXML;
		}
	);
		
	Node.prototype.__defineGetter__("text", 
		function _Node_getText() {return this.textContent;}
	);
		
	Node.prototype.__defineSetter__("text", 
		function _Node_setText(newText) {this.textContent = newText}
	);
	
	Node.prototype.namespaceResolver = function(prefix) { 
	        switch(prefix){ 
	                case 'soap': return 'http://schemas.xmlsoap.org/soap/envelope/'; 
	                case 'xsi':  return 'http://www.w3.org/2001/XMLSchema-instance'; 
	                case 'xsd':  return 'http://www.w3.org/2001/XMLSchema'; 
	                case 'xul':  return 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul'; 
	        } 
	        return null; 
	} 
	
	
	Document.prototype.createNode = function(nIgnored,sName,sIgnored) {
		return document.implementation.createDocument("","",null).createElement(sName); 		
	}
		
	
	Document.prototype.selectNodes = Node.prototype.selectNodes = function(xpath) { 
	        var nodes = document.evaluate(xpath,this,this.namespaceResolver,0,null); 
	        var nodelist = new Array(); 
	        var node = nodes.iterateNext(); 
	        while( node ){nodelist.push( node );node = nodes.iterateNext();} 
	        return nodelist; 
	} 
	

	Document.prototype.selectSingleNode = Node.prototype.selectSingleNode = function(xpath) { 
	        var nodes = document.evaluate(xpath,this,this.namespaceResolver,0,null); 
	        return nodes.iterateNext();
	} 
	
	HTMLElement.prototype.__defineGetter__("innerText", 
              function () { 
              	var sTemp = this.textContent	              	
              	sTemp = sTemp.replace(/^[\s\n]*/g,"")
              	sTemp = sTemp.replace(/[\s\n]{1,}/g," ")
              	return(sTemp); 
   });
   
	HTMLElement.prototype.__defineSetter__("innerText", 
              function (txt) { this.textContent = txt; });
	

}

/*** END ***  IF using MOZ (non-IE) these make it work more like IE *************/

function importXML(sXML)
{
	var xmlDoc;

	if (document.implementation && document.implementation.createDocument) 	{
		// not sure what is needed here yet...

		var domParser = new DOMParser();
		
		xmlDoc = domParser.parseFromString(sXML, 'text/xml');
		

		
		
		
	} else if (window.ActiveXObject) {
		
		if(document.STR_IE_XML_ACTIVEX != null){
			var xmlDoc = new ActiveXObject(document.STR_IE_XML_ACTIVEX)
		} else {
			var ARR_ACTIVEX = ["MSXML4.DOMDocument",
			"MSXML3.DOMDocument",
			"MSXML2.DOMDocument",
			"MSXML.DOMDocument",
			"Microsoft.XmlDom"]
			//define found flag
			var bFound = false;
	
			//iterate through strings to determine which one to use
			for (var i=0; i < ARR_ACTIVEX.length && !bFound; i++) {
	
				//set up try...catch block for trial and error
				//of strings
				try {
	
					//try to create the object, it will cause an
					//error if it doesn't work
					var xmlDoc = new ActiveXObject(ARR_ACTIVEX[i]);
	
					//if it gets to this point, the string worked,
					//so save it
					document.STR_IE_XML_ACTIVEX = ARR_ACTIVEX[i];
					bFound = true
	
				} catch (objException) {
					;			
				} //End: try
			} //End: for
	
			//if we didn't find the string, send an error
			if (!bFound) {
				alert("MSXML not found on your computer.")
			}
		}
		
		xmlDoc.loadXML(sXML);
	} else {
		alert("Your browser can\'t handle this XML script");
		return;
	}

	return xmlDoc;
}

/*
workflow related functions
*/


function loadAndSetWorkflow(sID) {
	var sSelectedValue = loadWorkflows(sID)
	
	var oSelect = document.getElementById(sID)
	for(var i = 0; i<oSelect.options.length; i++) {
		if(sSelectedValue == oSelect.options[i].value) {
			oSelect.selectedIndex = i;
			return;
		}
	}
	
	
}

function loadWorkflows(sID) {	
	
	var txtWorkflow = document.getElementById(sID)
	if(!txtWorkflow) {
		alert('Did not find sID: ' + sID)
		return;
	}
	var sRetVal  = txtWorkflow.value
	var oParent = txtWorkflow.parentNode
	oParent.removeChild(txtWorkflow)
	
	var oReq = getHTTPRequest() 		

	oReq.open("GET", document.WORKFLOW_ENGINE_URL + "StartWF.aspx?getwfnames=1", false);
	oReq.send(null);
	//alert(oReq.responseText)
	
	xmlDoc = importXML(oReq.responseText);
	
	var WFNodes = xmlDoc.selectNodes("/workflows/workflow");
	
	var objSelect = document.createElement("SELECT");
	
	if(document.all == null) {
		objSelect.appendChild(new Option('Select Workflow', ''));			
	} else {
		objSelect.add(new Option('Select Workflow', ''));			
	}
		
	for(var s = 0; s < WFNodes.length; s++)
	{
		if(document.all == null) {
			objSelect.appendChild(new Option(WFNodes[s].text, WFNodes[s].text));			
		} else {
			objSelect.add(new Option(WFNodes[s].text, WFNodes[s].text));			
		}
	}
	
	objSelect.id = sID;
	objSelect.name = sID;
	
	oParent.appendChild(objSelect)
	
	return sRetVal;
}
	

function setFormDisabled(oForm, bDisabled) {
	
	if(!oForm) {
		alert('Form Not Found')
	}
	for(var i=0;i<oForm.length;i++) {
		oForm[i].disabled = bDisabled
	}
	oForm.disabled = bDisabled		
}


function getFirstChildCheckbox(oO) {	
	var arrCkBoxes = oO.getElementsByTagName("INPUT")	
	for(var i = 0; i < arrCkBoxes.length ; i++ ) {
		if(arrCkBoxes[i].type == 'checkbox') {
			return arrCkBoxes[i];			
		}
	}	
}

function getParentTR(oObject) {
	while(oObject.tagName != 'TR' && oObject!=null) {		
		oObject = oObject.parentNode
	}
	return oObject	
}


function checkAllTemplateTypes() {
	
	for(var i = 0; i< document.screenform.template_ids.length;i++) {
		getParentTR(document.screenform.template_ids[i]).onclick()
	}
	
}

function toggleChildCheckbox(oTR, checkedStyle, unCheckedStyle) {
	var oCheckbox = getFirstChildCheckbox(oTR)
	oCheckbox.checked = !oCheckbox.checked

	if(oCheckbox.checked) {
		oTR.className = checkedStyle
	} else {
		oTR.className = unCheckedStyle
	}	
			
	/*	
	var arrCkBoxes = oTR.getElementsByTagName("INPUT")	
	for(var i = 0; i < arrCkBoxes.length ; i++ ) {
		if(arrCkBoxes[i].type == 'checkbox') {
			arrCkBoxes[i].checked = !arrCkBoxes[i].checked
						
			if(arrCkBoxes[i].checked) {
				oTR.className = checkedStyle
			} else {
				oTR.className = unCheckedStyle
			}	
			break;
		}
	}	
	*/
}


function flashTR(oRow,sStyleA, sStyleB) {
	var oldStyle = oRow.className
	if(!document['flashTRArray']) {
		document['flashTRArray'] = new Array()
		document['flashTRTimersArray'] = new Array()
	}
	var nNewIndex = document['flashTRArray'].length
	document['flashTRArray'][nNewIndex] = oRow
	
	for(var i = 0; i < document['flashTRTimersArray'].length; i++) {
		//clearTimeout(document['flashTRTimersArray'][i])
	}
	document['flashTRTimersArray'] = new Array()
	
	var nFlashTime = 400
	var nFlashInterval = 75
	var i = 0
	for(i = nFlashInterval; i < nFlashTime; i+=nFlashInterval*2) {
		document['flashTRTimersArray'][document['flashTRTimersArray'].length] = setTimeout('document[\'flashTRArray\'][' + nNewIndex + '].className = \'' + sStyleA + '\'', i)
		document['flashTRTimersArray'][document['flashTRTimersArray'].length] = setTimeout('document[\'flashTRArray\'][' + nNewIndex + '].className = \'' + sStyleB + '\'', i + nFlashInterval)
	}
	setTimeout('document[\'flashTRArray\'][' + nNewIndex + '].className = \'' + oldStyle + '\';document[\'flashTRArray\'][' + nNewIndex + ']=null',i+nFlashInterval)
	
}


function hideUnselectedUsers(userCBs) {
	
	if(!userCBs) {
		return;
	}
	if(document.all) { 
		for(var i=0;i<userCBs.length;i++) {			
   			if(userCBs[i].checked) {
   				userCBs[i].parentNode.parentNode.style.display = 'block'
   			} else {
   				userCBs[i].parentNode.parentNode.style.display = 'none'
   			}
   		}
	} 
	
}

function findUser(oInput,userCBs) {
	
	if(oInput.value != '' && document['lastfindUser'] == oInput.value) {
		return;
	}	
	document['lastfindUser'] = oInput.value
		
	if(document.all) {
				
		if(oInput.value == '') {
			hideUnselectedUsers(userCBs)
			return;
		}
		
		for(var i=0;i<userCBs.length;i++) {
   			var sHayStack = userCBs[i].parentNode.parentNode.innerText.toLowerCase()		   	
		   	if(!userCBs[i].checked) {
	   			userCBs[i].parentNode.parentNode.style.display = 'none'
	   		}
	   		
	   		if(oInput.value == '*' || sHayStack.indexOf(oInput.value.toLowerCase()) >= 0 ) {
	   			userCBs[i].parentNode.parentNode.style.display = 'block'		   					
			}	  
   		}		
	} else {
		
		if(oInput.value == '') {
			return;
		}		
		for(var i=0;i<userCBs.length;i++) {
	   		var sHayStack = userCBs[i].value.toLowerCase()		   	
		   	if(sHayStack.indexOf(oInput.value.toLowerCase()) >= 0 ) {
				userCBs[i].focus()
			   	flashTR(userCBs[i].parentNode.parentNode,'flashTRStyle','')
			   	oInput.focus()
		   	   break;
			}
		}		
	}
	
   
	userCBs = null	
}


function openWorkItems(){
	window.open(getPortalBaseURL()+'/bsthrm.link.asp?action=loadWorkItems','WorkItems','resizable=yes,status=yes,toolbar=no,menubar=no,location=no');	
}


function buildUserGroupCheckboxTable(sTable, sCBNames, sSearch, sDomain, sXML, sPermsFor) {
	var oTable = document.getElementById(sTable)
	var sURL = ''
	var sADXML = ''
	var oADXML = null
	var oADNodes = null
	var bLoadingCurrent = false
	
	var nCurrentRows = oTable.rows.length
	
	var arrCheckedValues = new Array()
	
	// remove those that have not been checked...
	for(var i=(nCurrentRows-1);i>=0;i--) {			
		var oCheckBox = getFirstChildCheckbox(oTable.rows[i])		
		if(! (oCheckBox.checked)) {
			oTable.deleteRow(i);						
		} else {
			arrCheckedValues[arrCheckedValues.length] = oCheckBox.value			
		}				
	}
	
	
	
	
	
	if(sXML) {
		sADXML = sXML
		bLoadingCurrent = true					
	} else {
		if(trim(sSearch)=='') {
			return;
		}
		if(sPermsFor=='cs') {
			sURL = getPortalBaseURL() + '/ajax.worker.asp?action=QueryADObjectsForCSPerms&domain=' + encodeURIComponent(sDomain) + '&searchtext=' + encodeURIComponent(sSearch)
		} else if(sPermsFor=='cb') {
			sURL = getPortalBaseURL() + '/ajax.worker.asp?action=QueryADObjectsForCBPerms&domain=' + encodeURIComponent(sDomain) + '&searchtext=' + encodeURIComponent(sSearch)	
		}
		
		sADXML = ajaxRawQuery(sURL)
		
		
	}
	
	oADXML = importXML(sADXML)
	//oADNodes = oADXML.selectNodes("/adobjects/adobject[@type='group']")
	oADNodes = oADXML.selectNodes("/adobjects/adobject")
	var bInSetAlready = false
	for(var i=0; i < oADNodes.length ;  i++) {
		bInSetAlready = false
		for(var x = 0; x < arrCheckedValues.length;x++) {		
			
			//alert(arrCheckedValues[x].toLowerCase() + "==" + oADNodes[i].getAttribute("adobject_id").toLowerCase() + " : " + (arrCheckedValues[x].toLowerCase() == oADNodes[i].getAttribute("adobject_id").toLowerCase()))
			if(arrCheckedValues[x].toLowerCase() == oADNodes[i].getAttribute("adobject_id").toLowerCase()) {
				bInSetAlready = true;
				continue;
				
			}
			
		}
		if(bInSetAlready) {
			continue;
		}
		
		var oRow = oTable.insertRow(oTable.rows.length);
		
		
		oRow.onclick=function(){toggleChildCheckbox(this,'selectedCheckboxRow','')}
		
		oTD = oRow.insertCell(0);					
		oTD.innerHTML = '<input type="checkbox" onClick="this.checked = !this.checked" class="checkbox" name="' + sCBNames + '" value="' +oADNodes[i].getAttribute("adobject_id") + '" />';
		if(oADNodes[i].getAttribute("type")=='group') {
			oTD.innerHTML += '<input type="hidden" name="' + sCBNames + '_group" value="' +oADNodes[i].getAttribute("adobject_id") + '" />';
		}
		
		oTD.style.width='5%'
		
		oTD = oRow.insertCell(1);
		if(oADNodes[i].getAttribute("type") == 'group') {
			oTD.innerHTML = '(G) '
		} else if (oADNodes[i].getAttribute("type") == 'user') {
			oTD.innerHTML = '(U) '
		}
		
		if(trim(oADNodes[i].text) != '') { 
			oTD.innerHTML += oADNodes[i].text;	
		} else {
			oTD.innerHTML += oADNodes[i].getAttribute("adobject_id");
		}
		
		
		
		
		if(bLoadingCurrent) {
			oRow.onclick()
		}
		
	}
	
}


function saveScreenPageIndex(nContentscreenId, nPageIndex) {
	if (!document.savedScreenPageIndexes) {
		document.savedScreenPageIndexes = new Object()
	}		
	document.savedScreenPageIndexes[nContentscreenId] = nPageIndex	
}

function loadMultiPage(sDirection, nContentscreenId) {		
	
	
	var sCookieName = 'pageIndex' + nContentscreenId
	var lastIndex = 0
	if ((document.savedScreenPageIndexes!=null) && (document.savedScreenPageIndexes[nContentscreenId]!=null)) {
		lastIndex = parseInt(document.savedScreenPageIndexes[nContentscreenId],10)
	}		
	
	if(getCookie(sCookieName)==null) {
		setCookie(sCookieName,0)
	}
		
	if (sDirection=='last') {
		setCookie(sCookieName,lastIndex - 1)
	} else if (sDirection=='next') {
		setCookie(sCookieName,lastIndex + 1)
	} else {
		setCookie(sCookieName,parseInt(sDirection,10))
	}		
	window.location = window.location.href
	
	
}

function obscureWindow(bOn) {
	
	version = parseFloat(navigator.appVersion.split("MSIE")[1]);
	
	
	
	if(!document.nonHiddenSelects) {
		document.nonHiddenSelects = Array()
	}
	

		
	if(bOn) {		
		var oDiv = document.getElementById('obscureWindowDiv')
		if(!oDiv) {
			oDiv = document.createElement("div");
			oDiv.id = 'obscureWindowDiv'
		}
		oDiv.style.position = "absolute";
		oDiv.className = 'classobscureWindowDiv'
		oDiv.style.right = oDiv.style.bottom = '0px'
		//oDiv.innerHTML = '<BR><B><BR>ddddd : <a style="cursor:pointer" onclick="obscureWindow(false)">go</a>'
		//oDiv.innerText = '<a style="cursor:pointer" onclick="obscureWindow(false)">go</a>'
		oDiv.onclick=function() {obscureWindow(false);}
		
		iScrollHeight = document.documentElement.scrollHeight
		if(iScrollHeight==0) {
			iScrollHeight = oIFrame.contentWindow.document.body.scrollHeight;
		}
		oDiv.style.width = oDiv.style.height = iScrollHeight +"px";								
		
		if(version == 6) {
			var oSelects = document.getElementsByTagName('SELECT')
			for(var i = 0 ; i < oSelects.length ; i++) {
				if(oSelects[i].style.display != 'none') {
					document.nonHiddenSelects[document.nonHiddenSelects.length] = oSelects[i]
					oSelects[i].style.display = 'none'
				}			
			}
		}	
		
		
		document.body.appendChild(oDiv)		

	} else {
		for(var i = 0 ; i < document.nonHiddenSelects.length ; i++) {
			document.nonHiddenSelects[i].style.display = 'block'
		}
		var oDiv = document.getElementById('obscureWindowDiv')
		if(oDiv) {
			oDiv.parentNode.removeChild(oDiv)		
		}
	}
}

function loadObscuringIframe(sID, bOn) {
	// only needed for IE 6
	version = parseFloat(navigator.appVersion.split("MSIE")[1]);
	if(version != 6) {
		return
	}	
	
	var sIframeId = 'obscureDivIframe_' + sID
	if(bOn) {
		var oDiv = document.getElementById(sID)	
		var oIframe = document.createElement("iframe");
		oIframe.id = sIframeId
		//oIframe.src = 'http://yahoo.com'
		
		oIframe.style.position = "absolute";
		
		oIframe.style.top = oDiv.style.top
		oIframe.style.left = oDiv.style.left
		oIframe.style.width = (parseInt(oDiv.style.width,10)+2) + 'px'
		oIframe.style.height = oDiv.scrollHeight + 'px'
		document.body.appendChild(oIframe)
	} else {
		
		var oIframe = document.getElementById(sIframeId)
		if(oIframe) {
			oIframe.parentNode.removeChild(oIframe)		
		}
		
	}		
}

function getQueryStringValue(sName) {
	var sRetVal = null
	var qs=location.search.substring(1,location.search.length)
	if (qs.length == 0) {
		return sRetVal
	}
	
	// Turn <plus> back to <space>
	// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
	qs = qs.replace(/\+/g, ' ')
	var args = qs.split('&') // parse out name/value pairs separated via &
	
	for (var i=0;i<args.length;i++) {
		var value;
		var pair = args[i].split('=')
		if(sName == unescape(pair[0])) {
			if (pair.length == 2) {
				sRetVal = unescape(pair[1])
			}
		}
	}	
	return sRetVal
}
			
/***************************************************************************
* START very important js for .PNG images
***************************************************************************/
if (navigator.platform == "Win32" && navigator.appName == "Microsoft Internet Explorer" && window.attachEvent) {
	document.writeln('<style type="text/css">img, input.image { visibility:hidden; } </style>');
	window.attachEvent("onload", fnLoadPngs);
}

function fnLoadPngs() {
	var rslt = navigator.appVersion.match(/MSIE (\d+\.\d+)/, '');
	var itsAllGood = (rslt != null && Number(rslt[1]) >= 5.5);

	for (var i = document.images.length - 1, img = null; (img = document.images[i]); i--) {
		if (itsAllGood && img.src.match(/\.png$/i) != null) {
			fnFixPng(img);
			img.attachEvent("onpropertychange", fnPropertyChanged);
		}
		img.style.visibility = "visible";
	}

	var nl = document.getElementsByTagName("INPUT");
	for (var i = nl.length - 1, e = null; (e = nl[i]); i--) {
		if (e.className && e.className.match(/\bimage\b/i) != null) {
			if (e.src.match(/\.png$/i) != null) {
				fnFixPng(e);
				e.attachEvent("onpropertychange", fnPropertyChanged);
			}
			e.style.visibility = "visible";
		}
	}
}

function fnPropertyChanged() {
	if (window.event.propertyName == "src") {
		var el = window.event.srcElement;
		if (!el.src.match(/x\.gif$/i)) {
			el.filters.item(0).src = el.src;
			el.src = "images/x.gif";
		}
	}
}

function dbg(o) {
	var s = "";
	var i = 0;
	for (var p in o) {
		s += p + ": " + o[p] + "\n";
		if (++i % 10 == 0) {
			alert(s);
			s = "";
		}
	}
	alert(s);
}
function fnFixPng(img) {
	var src = img.src;
	img.style.width = img.width + "px";
	img.style.height = img.height + "px";
	img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='scale')"
	img.src = "images/x.gif";
}
/***************************************************************************
* END very important js for .PNG images
***************************************************************************/


function formToXML(oForm) {
	
	var oFormXML = importXML("<elements/>")
	if(oForm) {
		for(var i=0; i<oForm.length; i++) {
			var oMyFormElements = oForm[i]
			if(oMyFormElements.type == 'select-one' || oMyFormElements.type == 'select-multiple') {
				addSelectToXml(oFormXML,oMyFormElements)
	
			} else {
				addGenereicToXml(oFormXML,oMyFormElements)
			}
		
		}
	}
	return oFormXML.xml;
	
}


function addSelectToXml(oFormXML, oSelect) {
	var objAjaxItemNode = oFormXML.createNode(1, "element", "")
	objAjaxItemNode.text = ''

	var oAjaxAttr1 = oFormXML.createAttribute("selectedIndex")
	oAjaxAttr1.value = oSelect.selectedIndex
	var ajaxNamedNodeMap = objAjaxItemNode.attributes
	ajaxNamedNodeMap.setNamedItem(oAjaxAttr1)

	var oAjaxAttr1 = oFormXML.createAttribute("type")
	oAjaxAttr1.value = oSelect.type
	var ajaxNamedNodeMap = objAjaxItemNode.attributes
	ajaxNamedNodeMap.setNamedItem(oAjaxAttr1)

	var oAjaxAttr1 = oFormXML.createAttribute("id")
	oAjaxAttr1.value = oSelect.id
	var ajaxNamedNodeMap = objAjaxItemNode.attributes
	ajaxNamedNodeMap.setNamedItem(oAjaxAttr1)

	var oAjaxAttr1 = oFormXML.createAttribute("name")
	oAjaxAttr1.value = oSelect.name
	var ajaxNamedNodeMap = objAjaxItemNode.attributes
	ajaxNamedNodeMap.setNamedItem(oAjaxAttr1)


	for(var i = 0; i<oSelect.length; i++) {
		var objAjaxItemNodeOption = oFormXML.createNode(1, "option", "")
		objAjaxItemNodeOption.text = oSelect[i].text

		var oAjaxAttr1 = oFormXML.createAttribute("value")
		oAjaxAttr1.value = oSelect[i].value
		var ajaxNamedNodeMap = objAjaxItemNodeOption.attributes
		ajaxNamedNodeMap.setNamedItem(oAjaxAttr1)

		if(oSelect[i].selected) {
			var oAjaxAttr1 = oFormXML.createAttribute("selected")
			oAjaxAttr1.value = "1"
			var ajaxNamedNodeMap = objAjaxItemNodeOption.attributes
			ajaxNamedNodeMap.setNamedItem(oAjaxAttr1)

		}


		objAjaxItemNode.appendChild(objAjaxItemNodeOption)
	}

	oFormXML.documentElement.appendChild(objAjaxItemNode)
}
	

function addGenereicToXml(oFormXML, oFormElement) {
	var objAjaxItemNode = oFormXML.createNode(1, "element", "")
	objAjaxItemNode.text = oFormElement.value

	var oAjaxAttr1 = oFormXML.createAttribute("type")
	oAjaxAttr1.value = oFormElement.type
	var ajaxNamedNodeMap = objAjaxItemNode.attributes
	ajaxNamedNodeMap.setNamedItem(oAjaxAttr1)


	if(oFormElement.checked) {
		var oAjaxAttr1 = oFormXML.createAttribute("checked")
		oAjaxAttr1.value = "1"
		var ajaxNamedNodeMap = objAjaxItemNode.attributes
		ajaxNamedNodeMap.setNamedItem(oAjaxAttr1)			
	}

	var oAjaxAttr1 = oFormXML.createAttribute("id")
	oAjaxAttr1.value = oFormElement.id
	var ajaxNamedNodeMap = objAjaxItemNode.attributes
	ajaxNamedNodeMap.setNamedItem(oAjaxAttr1)

	var oAjaxAttr1 = oFormXML.createAttribute("name")
	oAjaxAttr1.value = oFormElement.name
	var ajaxNamedNodeMap = objAjaxItemNode.attributes
	ajaxNamedNodeMap.setNamedItem(oAjaxAttr1)

	oFormXML.documentElement.appendChild(objAjaxItemNode)

}				
function getAbsX(elt) { return (elt.x) ? elt.x : getAbsPos(elt,"Left"); }
function getAbsY(elt) { return (elt.y) ? elt.y : getAbsPos(elt,"Top"); }
function getAbsPos(elt,which) {
 iPos = 0;
 while (elt != null) {
  iPos += elt["offset" + which];
  elt = elt.offsetParent;
 }
 return iPos;
}


function setIframeURL(iframeId, sAppURL, iReplaceADParams) {
	document.getElementById(iframeId).src= getPortalBaseURL() + "/html/loading.html";
	
	if(iReplaceADParams == 1) {
	
		var sXML = ajaxRawQuery(getPortalBaseURL() + '/ajax.worker.asp?action=getADUser');
		var oXML = importXML(sXML);
		var userAttrs = new Object();
		var oNodes = oXML.selectNodes("/aduser/*");
		
		for(var i = 0; i < oNodes.length; i++) {
			userAttrs[oNodes[i].nodeName] = oNodes[i].text;
		}
		
		for(var oAttr in userAttrs){
			var sRegEx = "\[" + oAttr + "\]";
			if(userAttrs[oAttr])
			{
				sAppURL = sAppURL.replace(sRegEx, encodeURIComponent(userAttrs[oAttr]));
			}
		}
	}
	
	setTimeout("document.getElementById('" + iframeId + "').src='" + sAppURL + "';",1);
}

function getSessionPref(sVarName) {
	var sURL = getPortalBaseURL() + '/ajax.worker.asp'
	var sParams = 'action=getSessionPref&varname=' + encodeURIComponent(sVarName)
	return ajaxRawQuery(sURL,sParams)
}

function saveSessionPref(sVarName, sVarVal) {
	var sURL = getPortalBaseURL() + '/ajax.worker.asp'
	var sParams = 'action=saveSessionPref&varname=' + encodeURIComponent(sVarName) + '&varval=' + encodeURIComponent(sVarVal)
	ajaxRawQuery(sURL,sParams)
}


// temp code for showing column header for files...				
var nfileTemplateHeaderCounter = 0
for(var i = 0; i < document.getElementsByTagName("table").length ; i++) {
	if(document.getElementsByTagName("table")[i].className == 'fileTemplateHeader') {		
		if(nfileTemplateHeaderCounter % 5 == 0){
			document.getElementsByTagName("table")[i].style.display = 'block'
		}
		nfileTemplateHeaderCounter++;
		//break;
	}
}


function toggleDisplay(toggleMe) {
	document.getElementById(toggleMe).style.visibility = "visible";
	if(document.getElementById(toggleMe).style.display == "none" ) {
		document.getElementById(toggleMe).style.display = "";
	}
	else {
		document.getElementById(toggleMe).style.display = "none";
	}
}

function extractPageName(hrefString){
	var arr = hrefString.split('.');
	arr = arr[arr.length-2].split('/');
	return arr[arr.length-1].toLowerCase();		
}
function setActiveMenu(arr, crtPage){
	for(var i=0; i < arr.length; i++)
		if(arr[i].href == window.location.href.split("#")[0]){
			arr[i].className = "current";
			arr[i].parentNode.className = "current";
		}
}
function setPage(){
	if(document.location.href) 
		hrefString = document.location.href;
	else
		hrefString = document.location;

	if (document.getElementById("sidenav")!=null) 
		setActiveMenu(document.getElementById("sidenav").getElementsByTagName("a"), extractPageName(hrefString));
}
window.onload=function(){setPage();}