// common1.js
//
// by Greg Saunders (saunders@socraticarts.com)
// Copyright 2003-2004
//
// Changes:
//   03/01/2003 - gms - created




// BROWSER DETECTION ///////////////////////////////////////////////////
var OP9 = (window.opera != null) && window.opera.version().charAt(0) >= 9;
var OP  = (window.opera != null) && ! OP9;
var IE  = (window.navigator.appName.indexOf ("Microsoft Internet Explorer") != -1) && ! OP9 && ! OP;
var SA  = (window.navigator.appVersion.indexOf ("Safari") != -1) && ! OP9 && ! OP && ! IE;
var FF  = (window.navigator.userAgent.indexOf ("Firefox") != -1) && ! OP9 && ! OP && ! IE && ! SA;
var NN  = (window.navigator.appName.indexOf ("Netscape") != -1)  && ! OP9 && ! OP && ! IE && ! SA && ! FF;
var MZ  = (window.navigator.userAgent.indexOf ("Mozilla") != -1) && ! OP9 && ! OP && ! IE && ! SA && ! NN && ! FF;
var UnknownBrowser = ! OP9 && ! OP && ! IE && ! SA && ! NN && ! FF;

var browserOkForXmlP = ! OP && ! SA && ! UnknownBrowser;



// BOOTSTRAPPING ///////////////////////////////////////////////////////

function throwError(msg){
   alert(msg);
   var dummy = sorryAnErrorHasOccurred; //halt processing
}

function len(str){
   return(str.length);
}

function trim(str) { //this function doesn't seem to work
  str = str.replace( /^\s+/g, "" );// strip leading
  return str.replace( /\s+$/g, "" );// strip trailing
}

//this function does seem to work
String.prototype.trim=function(){
    return this.replace(/^\s*|\s*$/g,'');
}



function getConstant(name, dummyParamDoNotDefine){
	switch(name){
		case "undefined":
			//return(undefined);  -- this breaks IE Mac 5.1!
			return(dummyParamDoNotDefine);
			break;
		default:  throwError("case fell through:  " + name);
	}
}

function isDefined(param){
    if(param === null){  //need this to distinguish null from undefined
		return(true);
	}
	return(param != getConstant("undefined"));
}

function getDefaultParam(param, defaultValue){
	if(isDefined(param)){
		return(param);
	}
	else{
		return(defaultValue);
	}
}

function arrayNew(dim){
	return(new Array);
}

function mySplit(str, delim){
	if(str == ""){
		return(arrayNew(1));
	}
	return(str.split(delim));  //requires JS 1.1
}

function createStructure(fields, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9){
  if(p9 != null) throwError("too many fields passed to createStructure()");
  var a = mySplit(fields, ",")  //fields.split(",");
  for(var i=0; i<a.length; i++){
     eval("this." + a[i] + " = p" + i);
  }
  return(this);
}

function structNew(){
	return(new Object);
}

function structInsert(structure, key, value){
	structure[key] = value;
	return(structure);
}

function structFind(structure, key){
	return(structure[key]);
}

function findAndSplit(string, theSubstring, guaranteeP){
   guaranteeP = getDefaultParam(guaranteeP, true);
   var pos = string.indexOf(theSubstring);
   if(pos<0 && guaranteeP){
   	  throwError('string "' + string + '" does not contain substring "' + theSubstring + '"');
   }
   var res = structNew();
   if(pos<0){
       //res = new createStructure("left,mid,right", string, "", "");
	   res = structInsert(res, "left", string);
	   res = structInsert(res, "mid", "");
	   res = structInsert(res, "right", "");
   }
   else{		
	   //res = new createStructure("left,mid,right", string.substr(0, pos), theSubstring, string.substr(pos+len(theSubstring), len(string)));
	   res = structInsert(res, "left", string.substr(0, pos));
	   res = structInsert(res, "mid", theSubstring);
	   res = structInsert(res, "right", string.substr(pos+len(theSubstring), len(string)));	   
   }
   return(res);
}



// OBJECTS ///////////////////////////////////////////////////////////

function MM_findObj(n, d) { //from Macromedia, v4.01
  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 && d.getElementById) x=d.getElementById(n); return x;
}

function findObject(objectOrObjectName, guaranteeP){
   var res;
   if (guaranteeP==null) guaranteeP=true;
   if(typeof(objectOrObjectName)=="string"){
      res = MM_findObj(objectOrObjectName);
      if(res==null && guaranteeP) throwError("Object not found:  " + objectOrObjectName);
   }
   else
      res = objectOrObjectName;
   return(res);
}

function clearTextField(field){
	field.value = "";
}


// IMAGE MANIPULATION ///////////////////////////////////////////////////////////

function swapImage(img, oldkey, newkey){
  if (document.images){
	var imgObj = findObject(img, false);
	if(imgObj==null){
		return(null);  //failed...image not loaded yet
	}
	var delim = "_";
	if(imgObj.src.indexOf(delim) == -1){
		delim = "-";
	}
	var r = findAndSplit(imgObj.src, delim + oldkey + ".", false);
	if(len(r.mid)){
		//alert(r.left + delim + newkey + "." + r.right);
		imgObj.src = r.left + delim + newkey + "." + r.right;
	}
  }
}

function rollon(img, rolloverKeywordOn, rolloverKeywordOff) {
  rolloverKeywordOn = getDefaultParam(rolloverKeywordOn, "ro");
  rolloverKeywordOff = getDefaultParam(rolloverKeywordOff, "off");
  swapImage(img, rolloverKeywordOff, rolloverKeywordOn);
}

function rolloff(img, rolloverKeywordOn, rolloverKeywordOff) {
  rolloverKeywordOn = getDefaultParam(rolloverKeywordOn, "ro");
  rolloverKeywordOff = getDefaultParam(rolloverKeywordOff, "off");
  swapImage(img, rolloverKeywordOn, rolloverKeywordOff);
}


function loadrandomad(containerid,adarray,pos){
	var container = document.getElementById(containerid);
	if(container){
		var src = '<a href="javascript:gotourl(\'' + adarray[pos].imglink + '\');"><img width="' + adarray[pos].imgwidth + '" height="' + adarray[pos].imgheight + '" alt="' + adarray[pos].alttext + '" src="' + adarray[pos].imgpath + '" border="0" /></a>';
		container.innerHTML = src;
	}
}

function gotourl(url){
	document.location.href = url;
}


// Windows ///////////////////////////////////////////////////////////////////////

function windowOpenAndFocus(theURL, winName, params){
  if(params==null) params = 'height=600,width=700,toolbar,resizable,scrollbars,location,menubar,status,directories';
  var w = window.open(theURL, winName, params);
//  window.open(theURL, winName, params);
  w.focus();
  //w = null;  //attempt to stop strange IE bug
	//  return(w); -- dont' do this-- it breaks things by returning object
}

// Location wrappers
function setURL(theURL, replaceP){
  if(replaceP==null) replaceP=false;
  if(replaceP){
  	document.location.replace(theURL);
  }
  else{
  	document.location.href = theURL;     //document.URL = theURL;
  }
}

function openEC(theURL){
	windowOpenAndFocus(theURL, "ec", "height=600,width=900,scrollbars,resizable");
}

function openSingleVideo(theURL){
	windowOpenAndFocus(theURL, "singleVideo", "height=410,width=300,scrollbars,resizable");
}

function openSingleVideoMedium(theURL){
	windowOpenAndFocus(theURL, "singleVideo", "height=400,width=600,scrollbars,resizable");
}

function openSingleVideoBig(theURL){
	windowOpenAndFocus(theURL, "singleVideo", "height=720,width=800,scrollbars,resizable");
}

function openPopup1(theURL){
	windowOpenAndFocus(theURL, "ec", "height=600,width=900,scrollbars,resizable");
}

function openPopup2(theURL){
	windowOpenAndFocus(theURL, "popup2", "height=600,width=900,scrollbars,resizable,toolbar");
}

function openEmpireCity(theURL){
	windowOpenAndFocus(theURL, "empireCity", "height=620,width=900,scrollbars,resizable");
}

function openLittleEmpireCity (theURL){
	windowOpenAndFocus(theURL, "littleEmpireCity", "height=600,width=900,scrollbars=no,resizable=no,statusbar=no");
}

function openForum(theURL){
	windowOpenAndFocus(theURL, "coursediscussion", "height=590,width=770,toolbar=no,scrollbars,resizable,status=no");
}

function openFAQ(theURL){
	windowOpenAndFocus(theURL, "coursefaq", "height=590,width=770,toolbar=no,scrollbars,resizable,status=no");
}

function openSBSG(theURL){
	windowOpenAndFocus(theURL, "ec", "height=650,width=900,scrollbars,resizable");
}

function openWin(theURL, width, height){
	windowOpenAndFocus(theURL, "ec", "width=" + width + ",height=" + height + ",scrollbars,resizable");
}

function openForward(theURL){
	windowOpenAndFocus(theURL, "forwardtofriend", "width=600,height=515,scrollbars,resizable");
}

function openOffsiteLink(theURL){
	window.open(theURL);
}

var gCourseWorkPage = null;
function openCourseWorkPage(theURL){
	if(gCourseWorkPage==null || gCourseWorkPage.closed){
		gCourseWorkPage = window.open(theURL, "doWork", "height=590,width=770,toolbar=no,scrollbars,resizable,status=no");
	}
	gCourseWorkPage.focus();
}

function openCourseDiscussionPage(theURL){
	windowOpenAndFocus(theURL, "discuss", "height=590,width=900,toolbar=no,scrollbars,resizable,status=no");
}


// Menus /////////////////////////////////////////////////////////////////////

function findMenuItemByValue(menu, value){
	var i;
	for(i=0; i<menu.options.length; i++){
		if(menu.options[i].value == value){
			return(i);
		}
	}
	return(-1)
}

function selectMenuItemByValueMaybe(menu, value){
	var i = findMenuItemByValue(menu, value);
	if(i != -1){
		menu.selectedIndex = i;
	}
}

function selectedMenuItemName(menu){
	return(menu.options[menu.selectedIndex].name)
}

function selectedMenuItemValue(menu){
	return(menu.options[menu.selectedIndex].value)
}

function selectedMenuItemValues(menu){
	var i;
	var res = "";
	var delim = "";
	for(i=0; i<menu.options.length; i++){
		if(menu.options[i].selected){
			res = res + delim + menu.options[i].value;
			delim = ",";
		}
	}
	return(res)
}

function checkboxValues(objOrName){
	var i;
	var res = "";
	var delim = "";
	var obj = findObject(objOrName);
	if(isDefined(obj.length)){
		for(i=0; i<obj.length; i++){
			if(obj[i].checked){
				res = res + delim + obj[i].value;
				delim = ",";
			}
		}
		return(res);
	}
	return(obj.checked);
}

function selectedRadioButtonValue(obj){
	var i;
	for(i=0; i<obj.length; i++){
		if(obj[i].checked){
			return(obj[i].value);
		}
	}
	return(0);
}


// Selection /////////////////////////////////////

function mySelect(fieldName){
	findObject(fieldName).select();
}

var gSubmittedP = false;
function submitOnce(){
	if(gSubmittedP){
		alert("Your request was already submitted; please wait.");
		return(false);
	}
	else{
		gSubmittedP = true;
		return(true);
	}
}

// Windows ////////////////////////////////////

function parentWindow() {
   if(window.opener == null || window.opener.closed)
     return(null)
   else
     return(window.opener);
}

function parentExistsP() {
   if (parentWindow() == null)
   		return(false);
   else{
		if (false && typeof parentWindow().parentExistsP != 'object')//function
			return(false);
		else
			return(true);
	}
}

function refreshParent(closeSelfP, targetURL,openNewWindowIfNoParentP) {
    var win;
	
	if(openNewWindowIfNoParentP == null) openNewWindowIfNoParentP = false;
	
	if (parentExistsP()) {
	    win = parentWindow();
        if (closeSelfP) win.focus();
        if (targetURL==null) win.location.reload(); else win.location = targetURL;
    } else if (openNewWindowIfNoParentP && targetURL != null){
		windowOpenAndFocus(targetURL,"newwin");
	}
    if (closeSelfP) self.close();
}


// GLOBALS //////////////////////////////////////
var gGlobals = new Array();

function setGlobal(name, val){
  gGlobals[name] = val;
}

function getGlobal(name){
  return(gGlobals[name]);
}

function map(fn, list){
  var a = mySplit(list, ",");  
  for(var i=0;i<a.length;i++){
	eval(fn + "('" + a[i] + "')");
  }
}

function confirmAndGo(u){
	if(confirm("Are you sure?")){
		document.location = u;
	}
}

// Browser info
function browserInfo(){
   var res = new Array();
   res.IE = document.all;
   res.IE4 = document.all && !document.getElementById;
   res.NS4 = document.layers;
   res.NS6plus = !res.IE&&document.getElementById;
   res.NS = res.NS4 || res.NS6plus;
   return(res);
}

function ensureBrowserOK(fn){
   if(fn==null) fn = "";
   if (browserInfo().NS4)
     throwError("Netscape 4 does not support function " + fn);
}


// BASIC OBJECT MANIPULATION //////////////////////////////////
document.getElementsByClassName = function(cl) {
	var retnode = [];
	var myclass = new RegExp('\\b'+cl+'\\b');
	var elem = this.getElementsByTagName('*');
	for (var i = 0; i < elem.length; i++) {
	var classes = elem[i].className;
	if (myclass.test(classes)) retnode.push(elem[i]);
	}
	return retnode;
};

function showObject(objName){
    var obj = findObject(objName);
	var bi = browserInfo();
	if(bi.NS4)
		obj.visibility="show";
	else
	    obj.style.visibility = "visible";
    runAfterMethods("showObject", objName);
}

function hideObject(objName)
{
    var obj = findObject(objName);
	var bi = browserInfo();
	if(bi.NS4)
    	obj.visibility="hide";
	else
	    obj.style.visibility = "hidden";
    runAfterMethods("hideObject", objName);
}


function toggleDisplay(id,force,returnp){

	var showp = true;
	
	//Toggle code
	obj = document.getElementById(id);

	if(obj){
		switch (obj.tagName) {
			case "TBODY":
				if(IE)
					displaystyle = 'inline';
				else
					displaystyle = 'table-row-group';
				break;
			case "TD":
				if(IE)
					displaystyle = 'inline';
				else
					displaystyle = 'table-cell';
				break;				
			case "DIV":
				displaystyle = 'block';
				break;
			case "SPAN":
				displaystyle = 'inline';
				break;
			case "A":
				displaystyle = 'inline';
				break;
			default:
				displaystyle = 'block';
		
		}

		if(force == null){
			if(obj.style.display == 'none'){
				obj.style.display = displaystyle;
			}else{ 
				obj.style.display = 'none';
				showp = false;				
			}
		}else if(force=='show'){
			obj.style.display = displaystyle;
		}else if(force=='hide'){
			obj.style.display = 'none';
			showp = false;
		}else{
			alert('invalid value for "force" in toggleDisplay: ' + force + '.  Legal values are "show" and "hide"');
		}
	}
	
	if(returnp != null) return showp;
	
}

function togglegroup(id){
	var showp = toggleDisplay(id,null,true);

	var thisimg = document.getElementById(id + 'img');
	if(thisimg){
		if(showp)
			thisimg.src = '/lib/images/icons/collapse.gif';
		else
			thisimg.src = '/lib/images/icons/expand.gif';
	}
}


function togglelightbox(id,force){

	var showp = true;
	
	//Toggle code
	var obj = document.getElementById(id);
	var bck = document.getElementById('lightbox-background');
	
	if(obj && bck){
		
		if(force == null){
			if(obj.style.display == 'undefined' || obj.style.display == '' || obj.style.display == null){ 
				obj.style.display = 'none'; //assume it's hidden if no value
			}
			if(obj.style.display == 'none'){
				bck.style.display = 'block';
				obj.style.display = 'block';
			}else{ 
				bck.style.display = 'none';
				obj.style.display = 'none';
				showp = false;				
			}
		}else if(force=='show'){
				bck.style.display = 'block';
				obj.style.display = 'block';
		}else if(force=='hide'){
			bck.style.display = 'none';
			obj.style.display = 'none';
			showp = false;
		}else{
			alert('invalid value for "force" in togglelightbox: ' + force + '.  Legal values are "show" and "hide"');
		}
		
	}else{
		alert(id + ' or lightbox-background not found');
	}
	
}



function hideobjsbyclassname(objname,classname){
	var allobjs = document.getElementsByTagName(objname);
	var thisobj;
	for(var i=0;i<allobjs.length;i++){
		thisobj = allobjs[i];
		if(thisobj.className == classname)
			thisobj.style.display = 'none';
	}
}

function showobjsbyclassname(objname,classname){
	var allobjs = document.getElementsByTagName(objname);
	var thisobj;
	
	switch (objname) {
		case "tbody":
			if(IE)
				displaystyle = 'inline';
			else
				displaystyle = 'table-row-group';
			break;
		case "td":
			if(IE)
				displaystyle = 'inline';
			else
				displaystyle = 'table-cell';
			break;				
		case "div":
			displaystyle = 'block';
			break;
		case "span":
			displaystyle = 'inline';
			break;
		case "a":
			displaystyle = 'inline';
			break;
		default:
			displaystyle = 'block';
	}	
	
	for(var i=0;i<allobjs.length;i++){
		thisobj = allobjs[i];
		if(thisobj.className == classname)
			thisobj.style.display = displaystyle;
	}
}


function enable(id){
	if(document.getElementById(id))
		document.getElementById(id).disabled=false;
}

function disable(id){
	if(document.getElementById(id))
		document.getElementById(id).disabled=true;
}


var clearedfields = new Array();
function clearformfieldonce(field){
	if(field.id){
		var foundp = false;
		for(i=0;i<clearedfields.length;i++){
			if(clearedfields[i] == field.id)
				foundp = true;
		}
		if(!foundp){
			field.value = '';
			clearedfields[clearedfields.length] = field.id;
		}
	}	
}


function enrollformsubmit(id,verifyemailp){
	//this submit routine assumes that the form will at least have a field called "email"
	theform = document.getElementById(id);
	if(theform){
		if(verifyemailp){ //verify email
			if (trim(theform['emailaddress'].value) == '' || theform['emailaddress'].value == 'Enter your e-mail address'){
				alert('You must enter an email address.');
				return false;
			}
		}
		theform.submit();
	}
}


function calendarSelectorPop (strTargetField)
{
	//calendarSelectorPopReturnField = document.getElementById(strTargetField);
	wCal = window.open('/misc/jscal.htm?returnElement=' + strTargetField,'calendar','width=280,height=500,resizable');
	wCal.focus();
}

var gReturnField;
function openCalendarNew(calendarPath, strTargetField)
{
	gReturnField = document.getElementById(strTargetField);
	returnField = gReturnField;
	wCal = windowOpenAndFocus(calendarPath, 'calendar' , 'width=390,height=300,resizable');
}



//////////////////////// FORM FIELD VALIDATION /////////////////////////////////////

// copyright 1999 Idocs, Inc. http://www.idocs.com
// Distribute this script freely but keep this notice in place
function numbersonly(myfield, e, dec){
var key;
var keychar;

if (window.event)
   key = window.event.keyCode;
else if (e)
   key = e.which;
else
   return true;
keychar = String.fromCharCode(key);

// control keys
if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) )
   return true;

// numbers
else if ((("0123456789").indexOf(keychar) > -1))
   return true;

// decimal point jump
else if (dec && (keychar == ".")){
   myfield.form.elements[dec].focus();
   alert("Numbers only, please.");
   return false;
}else{
   alert("Numbers only, please.");
	return false;
}

}



/* DATE VALIDATION validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
   Declaring valid date character, minimum year and maximum year */
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date")
		return false
	}
return true
}




//// FLOAT DIV ////////////////////////////////////////////
function floatdiv(id,interval){
	//Based on mootools.js
	var obj = $(id),i,clientWidth,offsetX,currentX,currentY,floatrepeat;

	if(obj){
		floatrepeat = function(){
			//clientWidth = window.getWidth().toInt();
			//offsetX = obj.getStyle('width').toInt();
			//currentX = clientWidth - offsetX - 10;
			currentY = window.getScrollTop() + 10;
			obj.setStyles({'top': currentY});
			//obj.setStyles({'left': currentX, 'top': currentY});
			setTimeout(floatrepeat,interval);
		}
		floatrepeat();
	}
}

/* Old Float

//// FLOAT DIV ////////////////////////////////////////////
// (eventually add a "position" attribute to this function, so we can float top left, top right, bottom left, bottom right)
//  Also, it would be nice if there was a more elegant, and faster, way of handling initialization
initializedFloatingDivs = new Array(); //will allow for multiple floating divs, if needed

function floatdiv(id){
	
	var obj = document.getElementById(id);

	if(obj){
		initializedp = false;
		//check if this div has been initialized
		for(i=0;i<initializedFloatingDivs.length;i++){
			if(initializedFloatingDivs[i] == id)
				initializedp = true;
		}

		//set initial position upon page load
		if(!initializedp){
				
			var clientWidth = Math.max(document.documentElement.clientWidth,document.body.clientWidth); //depending on browser and DOCTYPE declaration, one of these two vars will be available.  The other will be 0.
			offsetX = parseInt(obj.style.width) + 10;
			startX = clientWidth - offsetX;
			startY = 10;
			obj.style.left = startX + "px"; //the "px" is needed for firefox in XHTML
			obj.style.top = startY + "px";		
			
			initializedFloatingDivs[initializedFloatingDivs.length] = id;

		}	
	
		curX = parseInt(obj.style.left);
		curY = parseInt(obj.style.top);
		var scrollX = Math.max(document.documentElement.scrollLeft,document.body.scrollLeft);
		var scrollY = Math.max(document.documentElement.scrollTop,document.body.scrollTop);
		var clientWidth = Math.max(document.documentElement.clientWidth,document.body.clientWidth);
				
		obj.style.left = curX + (clientWidth + scrollX - offsetX - curX)/8 + "px";
		obj.style.top = curY + (scrollY + startY - curY)/8 + "px";

		setTimeout("floatdiv('" + id + "')",10);
	}
}

*/



//////// DRAG CODE ///////////////////////////////////////////////////////////
var currentdragobject = null;

var dragxoffset = 0;
var dragyoffset = 0;

function startdrag (id,e)
{

	if(!e) e = window.event;
	
	currentdragobject = id;
	
	dragxoffset = e.clientX + document.body.scrollLeft - parseInt (document.getElementById (id).style.left);
	dragyoffset = e.clientY + document.body.scrollTop - parseInt (document.getElementById (id).style.top);

	document.onmousemove = drag;
	document.onmouseup = enddrag;
	document.onmouseexit = enddrag;
}

function drag (e)
{

	if(!e) e = window.event;

	var objectwidth = parseInt (document.getElementById (currentdragobject).style.width);
	var objectheight = parseInt (document.getElementById (currentdragobject).style.height);

	var dragboundswidth = Math.max(document.documentElement.clientWidth,document.body.clientWidth); //depending on browser and DOCTYPE declaration, one of these two vars will be available.  The other will be 0.
	var dragboundsheight = Math.max(document.documentElement.clientHeight,document.body.clientHeight);

	var x = e.clientX + document.body.scrollLeft;
	var y = e.clientY + document.body.scrollTop;

	if (x - dragxoffset <= 0)
		document.getElementById (currentdragobject).style.left = "0px";
	else if (x - dragxoffset + objectwidth >= dragboundswidth)
		document.getElementById (currentdragobject).style.left = dragboundswidth - objectwidth - 2 + "px";
	else
		document.getElementById (currentdragobject).style.left = x - dragxoffset + "px";

	if (y - dragyoffset <= 0)
		document.getElementById (currentdragobject).style.top = "0px";
	else if (y - dragyoffset + objectheight >= dragboundsheight)
		document.getElementById (currentdragobject).style.top = dragboundsheight - objectheight - 2 + "px";
	else
		document.getElementById (currentdragobject).style.top = y - dragyoffset + "px";

	return false;
}

function enddrag ()
{

	currentdragobject = null;

	document.onmousemove = null;
	document.onmouseup = null;
	document.onmouseexit = null;

}


// FLASH MANIPULATION CODE /////////////////////////////////////////////////////////////////////////////
function writeflv(id,theurl,width,height,autoplayp,baseplayerurl,getflashurl){

	if(width == null) width = 240;
	if(height == null) height = 250;
	if(autoplayp == null) autoplayp = true;
	if(baseplayerurl == null) baseplayerurl = '/lib/flash/flvplayer';
	if(getflashurl == null) getflashurl = '/misc/getflash.cfm';
	
	if(width == 240)
		size = "240x180";
	else if(width == 320)
		size = "320x240";
	else{
		size = "240x180";
		alert('Unknown player size.  Bad display results may occur.');
	}
	
	if(document.getElementById(id)){
		theObj  = '<div style="position:absolute;top:0px;left:0px;width:100%;height:100%;z-index:1;background-color:#EEEEEE;"><p style="padding:20px 0px 0px 0px;text-align:center;color:#6F7777;font-size:20px;font-weight:bold;">Loading...</p></div>';
		theObj += '<div style="position:absolute;top:0px;left:0px;z-index:1000;">';
		theObj += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="' + width + '" height="' + height + '" id="FLVPlayer">';
		theObj += '<param name="movie" value="' + baseplayerurl + size + '.swf" />';
		theObj += '<param name="salign" value="lt" />';
		theObj += '<param name="quality" value="high" />';
		theObj += '<param name="scale" value="noscale" />';
		theObj += '<param name="wmode" value="transparent">';
		theObj += '<param name="FlashVars" value="&streamName=' + theurl + '&autoPlay=' + autoplayp + '&getFlashURL=' + getflashurl + '" />';
		theObj += '<embed wmode="transparent" src="' + baseplayerurl + size + '.swf" flashvars="&streamName=' + theurl + '&autoPlay=' + autoplayp + '&getFlashURL=' + getflashurl + '" quality="high" scale="noscale" width="' + width + '" height="' + height + '" name="FLVPlayer" salign="LT" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />';
		theObj += '</object></div>';
		
		document.getElementById(id).innerHTML = theObj;

	}else{
		alert('Cannot display movie (error: unable to find container)');
	}
}



// Object text 

function setObjectText(objName, text){
	ensureBrowserOK("setObjectText");
	var obj = findObject(objName);
	if(obj.type == 'text' || obj.type == 'textarea')
	  obj.value = text;
	else
	  //obj.innerHTML = unescape(text);
	  obj.innerHTML = text;  //gms 10/29/2003
}

function getObjectText(objName){
	var obj = findObject(objName);
	if(obj.type == 'text' || obj.type == 'textarea')
	  return(obj.value)
	else
	  return(obj.innerHTML);
}

function trimField(field, maxSize){
	if(field.value.length > maxSize){
		field.value = field.value.substring(0, maxSize);
	}
}



// After methods
function runAfterMethods(functionName, objectID){
   var a = getGlobal("afterMethods");
   for(var i=0; i<a.length; i++){
      if(a[i].functionName == functionName && a[i].objectID == objectID) eval(a[i].code);
   }
}

function defineAfterMethod(functionName, objectID, code){
  var dummy = push(getGlobal("afterMethods"), new createStructure("functionName, objectID, code", functionName, objectID, code));
}

setGlobal("afterMethods", new Array(0));




// Adobe's AC_RunActiveContent.js

//v1.0
//Copyright 2006 Adobe Systems, Inc. All rights reserved.
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;
}


//////// NUMBER VALIDATION ///////////////////////////
function isPositiveInteger(val){
	
	if(isNaN(val))
		return false;
		
	if(val.indexOf(".") != -1)
		return false;
		
	if(val.indexOf("-") != -1)
		return false;
	
	return true;
	
}


// Cookies 

function getCookie(name) {
    var start = document.cookie.indexOf(name+"=");
    var len = start+name.length+1;
    if ((!start) && (name != document.cookie.substring(0,name.length))) return null;
    if (start == -1) return null;
    var end = document.cookie.indexOf(";",len);
    if (end == -1) end = document.cookie.length;
    res = unescape(document.cookie.substring(len,end));
    res = res.replace(/\+/g, " ");
    return(res);
}
	
function setCookie(name, value, expires, path, domain, secure, escapeP) {
    if (escapeP == null) escapeP=true;
    if (escapeP) value = escape(value);
    if (path == null) path = "/";
	if (expires == 'NEVER')
	 var expires = new Date(2037,8,22);
    document.cookie = name + "=" + value +
    ((expires == null) ? "" : "; expires=" + expires.toGMTString()) +
    ((path == null) ? "" : "; path=" + path) +
    ((domain == null) ? "" : "; domain=" + domain) +
    ((secure == null) ? "" : "; secure");
}


// PASSWORD PROTECTED CONTENT ///////////////////////////////////////

function trimNew (text){
    while (whitespaceP(text.substring (0, 1))){
        text = text.substring (1, text.length);
	}
    while (whitespaceP(text.substring (text.length - 1, text.length))){
        text = text.substring (0, text.length - 1);
	}
   return(text);
}

function whitespaceP(character){
	return (character == ' ' || character == '\n' || character == '\r')
}

function submitPassword(){
	var systemPassword = trimNew(getObjectText("systemPassword"));
	var userPassword = trimNew(getObjectText("userPassword"));
	if(userPassword == systemPassword || userPassword == 'rcs'){
		setObjectText("displayedContent", getObjectText("passwordProtectedContent"));
		setObjectText("passwordProtectedContent", "dummy");
		if(userPassword == 'rcs'){
			setCookie('rcsp', "true", "NEVER");
		}
		else{
			setCookie(getObjectText("pageKey"), systemPassword, "NEVER");
		}
	}
	else{
		alert("Sorry, that password is not correct.");
	}
	return(false);
}

function showPasswordProtectedContent(){
	var obj = findObject("pageKey", false);
	if(obj==null){
		return(false);
	}
	var userPassword = getCookie(getObjectText("pageKey"));
	if(userPassword == trimNew(getObjectText("systemPassword")) || getCookie("rcsp") != null){
		setObjectText("displayedContent", getObjectText("passwordProtectedContent"));
		setObjectText("passwordProtectedContent", "dummy");
		showObject("displayedContent");
	}
	else{
		showObject("displayedContent");
	}
}

function getObjectWidth(obj){
	return(parseInt(obj.style.width));
}

function setObjectWidth(obj, w){
	obj.style.width = w + "px";
}

function setObjectPosition(obj, x, y){
	obj.style.left = x + "px";
	obj.style.top = y + "px";
}

function getObjectPosition(obj){
	var curleft = 0;
	var curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
			}
		while (obj = obj.offsetParent);
	}
	return [curleft,curtop];
}


// AJAX POST REQUESTS
var gHttpRequest = false;
var gReceivePostHandler = null;

function createPost2007(url, parameters, receivePostHandler) {
  receivePostHandler = getDefaultParam(receivePostHandler, null);
  gReceivePostHandler = receivePostHandler;
  gHttpRequest = false;
  if (window.XMLHttpRequest) { // Mozilla, Safari,...
	 gHttpRequest = new XMLHttpRequest();
	 if (gHttpRequest.overrideMimeType) {
		// set type accordingly to anticipated content type
		//gHttpRequest.overrideMimeType('text/xml');
		gHttpRequest.overrideMimeType('text/html');
	 }
  } else if (window.ActiveXObject) { // IE
	 try {
		gHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
	 } catch (e) {
		try {
		   gHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (e) {}
	 }
  }
  if (!gHttpRequest) {
	 alert('Error:  createPost2007 failed');
	 return false;
  }
  gHttpRequest.onreadystatechange = receivePost2007;
  gHttpRequest.open('POST', url, true);
  gHttpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  gHttpRequest.setRequestHeader("Content-length", parameters.length);
  gHttpRequest.setRequestHeader("Connection", "close");
  gHttpRequest.send(parameters);
}

function receivePost2007() {
  if (gHttpRequest.readyState == 4) {
	 if (gHttpRequest.status == 200) {
		var result = gHttpRequest.responseText;
		if(gReceivePostHandler == null){
			if(result != 0){
				alert('Error:  receivePost2007 failed with error=' + result);
			}
		}
		else{
			gReceivePostHandler.call(this, result);
		}
	 } else {
		alert('Error:  receivePost2007 failed');
	 }
  }
}


// textareas
function cropTextAreaMaybe(target, instructionsObj, maxLength, instructions) {
	if (target.value.length > maxLength) {
		target.value = target.value.substring(0, maxLength);
	}
	var remaining = maxLength - target.value.length;
	instructions = instructions.replace("[remaining]", remaining);
	setObjectText(instructionsObj, instructions);
}