// Eonic Ltd

/*
 * Content-seperated javascript tree widget
 * Copyright (C) 2005 SilverStripe Limited
 * Feel free to use this on your websites, but please leave this message in the fies
 * http://www.silverstripe.com/blog
*/



// Wellards specific
function showTimer() {
	/* Note - this is just a clientside countdown of what is being maintained from the server end */
	/* The quiz/exam server does not rely on this to run the timer */
	var dy = document.getElementById("time_d");
	var h = document.getElementById("time_h");
	var m = document.getElementById("time_m");
	var s = document.getElementById("time_s");
	var nd,nh,nm,ns;

	var d = Date();
	var udMSSecond = 1000;
	
	var bHasAlreadyBeenSubmitted = false
	for (i=0; i<document.forms[0].length;i++ ) {
		oElem = document.forms[0].elements[i];
		if (oElem.value == "Please Wait..." && (oElem.type == "submit" || oElem.type=="button")) {bHasAlreadyBeenSubmitted = true}
	}		
	
	if (!bHasAlreadyBeenSubmitted) {
		var nSecsPassed = nTimeSecs - Math.floor((Date.parse(d)-Date.parse(dDateOriginal))/udMSSecond);
		
		nd = Math.floor(nSecsPassed/86400);
		nh = Math.floor((nSecsPassed%86400)/3600);
		nm = Math.floor((nSecsPassed%3600)/60);
		ns = Math.floor(nSecsPassed%60);
		
		if (dy!=undefined) {dy.innerHTML=nd;}
		if (h!=undefined) {h.innerHTML=nh;}
		if (m!=undefined) {m.innerHTML=nm;}
		if (s!=undefined) {s.innerHTML=ns;}
	}

	
	if (nd<=0 && nh<=0 && nm<=0 && ns<=0 && !bHasAlreadyBeenSubmitted) {
		// Check if the form has been submitted		
		alert('The time limit has been reached.\n Press OK to Finish the Quiz.');
		var oHInput = document.createElement("input")
		oHInput.type="hidden"
		oHInput.name="qmCmd"
		oHInput.value="Out of Time"
		document.forms[0].appendChild(oHInput)
		document.forms[0].submit();
	} else if (!bHasAlreadyBeenSubmitted) {
		setTimeout('showTimer()',1000)
	}
}

function stripSelect(oElmt) {
	if(oElmt){
		if(oElmt.type=="select-one"){
			oElmt.selectedIndex = 0;
			while(oElmt.length > 1)
			{
				oElmt.removeChild(oElmt.lastChild)
			}
		}
	}
}

function toggleclass(oElmt,cClass) {
	if (oElmt.className.indexOf(cClass) >= 0) {
		oElmt.className = oElmt.className.replace(cClass,"")
	}
	else {
		oElmt.className += (" " + cClass)
	}
}

function showClearForm(formName,link) {
	document.getElementById('tr_'+formName).style.display='block'; 
	link.style.display='none';
	document.getElementById('button_' + formName).focus();
	return false;
}

function toggle(obj) {

	if (obj.style) {
		obj.style.display = (obj.style.display!="block" ||  obj.style.display=="") ?  "block" : "none" 
	}

}
function results_toggle(oLink, oChild) {
    
    // Toggle parent class of Parent
    if ($(oLink).parent('*').hasClass('aClosed')) {
        $(oLink).parent('*').removeClass('aClosed');
        $(oLink).parent('*').addClass('aOpen');
    } else if ($(oLink).parent('*').hasClass('aOpen')) {
        $(oLink).parent('*').removeClass('aOpen');
        $(oLink).parent('*').addClass('aClosed');
    }

    // Toggle parent class of course
    if ($(oLink).parent('*').hasClass('cClosed')) {
        $(oLink).parent('*').removeClass('cClosed');
        $(oLink).parent('*').addClass('cOpen');
    } else if ($(oLink).parent('*').hasClass('cOpen')) {
        $(oLink).parent('*').removeClass('cOpen');
        $(oLink).parent('*').addClass('cClosed');
    }

    // show child
    if (oChild.style) {
        oChild.style.display = (oChild.style.display != "block" || oChild.style.display == "") ? "block" : "none"
    }

}
// Common functions
var lockmenu = 0;
var menuNode;

function adminMenu(elmnt,condn){

	var oPop = document.getElementById("popup_menu")
	var nGutter = 4

	switch (condn) {
		case "on":
			if (lockmenu == 0){
	
				// Get the menu we wish to clone.  Display it briefly to get it's positional information
				var oUL = getChildUL(elmnt)
				oUL.style.display = "block";				

				var nL = getLeft(oUL) 		
				var nT = getTop(oUL)
				var nH = oUL.clientHeight
				var nW = oUL.clientWidth
				var nB = nT + nH;
				var nR = nL + nW;
				oUL.style.display = "none";
				var sB = getVisHeight() + getScrollTop();
				var sR = getVisWidth() + getScrollLeft();				

				if (nB > sB) { nT = sB - nH - nGutter }
				if (nR > sR) { nL = sR - nW - nGutter }
				
				// Transfer the inner HTML and position to our popup menu
				oPop.innerHTML = oUL.innerHTML 

				
				// Display the popup menu
				oPop.className+=" overpop";
				
				// Adjust the positioning (accounts for the exact rendering of the popup div, in case it's different from the cloned UL), 
				// hence we only re-adjust once the popup is visible
				nL = getLeft(elmnt) + getWidth(elmnt) - getWidth(oPop) - nGutter
				nH = oPop.clientHeight
				nW = oPop.clientWidth
				nB = nT + nH;
				nR = nL + nW;
				
				if (nB > sB) { nT = sB - nH - nGutter  }
				if (nR > sR - nGutter) { nL = sR - nW - nGutter }
								
				oPop.style.top=nT + "px"
				oPop.style.left=nL + "px"
			}
		break	
		case "off":
			if (lockmenu == 0){
				oPop.className = oPop.className.replace(' overpop','');
			}
		break
		case "onMenu":
			lockmenu = 1;		
			oPop.className+=" overpop";
		break
		
		case "offMenu":
			lockmenu = 0;
			oPop.className = oPop.className.replace(' overpop','');
		break
	}
}

function getChildUL(obj) {
	for (i=0; i<obj.childNodes.length; i++){
		child = obj.childNodes[i]
		if (child.className != null) {
			if (child.className.indexOf("inlinePopupLabel") >= 0){
				for (j=0; j<child.childNodes.length; j++){
					if (child.childNodes[j].nodeName=="UL") { return child.childNodes[j];break;}
				}
			}
		}
	}
}

function gallerySwitch(imgName,imgSrc,nWidth,nHeight,cCaption){
	var img = document.images["pic"]
	var cap = document.getElementById("imgCaption")
	
	// Change the img
	img.src = imgSrc;
	img.width = nWidth
	img.height = nHeight
	
	// Change the caption
	// cap.firstChild.nodeValue = cCaption

}

function getAppVersion() {
	appname= navigator.appName;
	appversion = navigator.appVersion;
	majorver = appversion.substring(0, 1);
	if ( (appname == "Netscape") && ( majorver >= 3 ) ) return 1;
	if ( (appname == "Microsoft Internet Explorer") && (majorver >= 4) ) return 1;
	return 0;
}



function loadImageArray() {
		if (getAppVersion()) {
		img = new Array();
		for (i = 0; i < imgsrc.length; i++) {
			img[i] = new Image();
			img[i].src = imgsrc[i];
		}
	}
}

function loadImageArray2() {
		if (getAppVersion()) {
		img2 = new Array();
		for (i = 0; i < imgsrc2.length; i++) {
			img2[i] = new Image();
			img2[i].src = imgsrc2[i];
		}
	}
}

function loadImageArray3() {
		if (getAppVersion()) {
		img3 = new Array();
		for (i = 0; i < imgsrc3.length; i++) {
			img3[i] = new Image();
			img3[i].src = imgsrc3[i];
		}
	}
}

function setHome(arg, urlName){
	
if(navigator.appVersion.charAt(navigator.appVersion.indexOf("MSIE") + 5) >= 5 && navigator.platform.indexOf("Win16") == -1 
 && navigator.platform.indexOf("Mac") == -1){
 		arg.style.behavior='url(#default#homepage)';
 		arg.setHomePage(urlName);
 		arg.href="#";
 		return true;
 	}
 	else {return false}
}

function swtch(num, imgname) {
	if (getAppVersion()) {
		document[imgname].src = img[num].src;
	}
}

function swtch2(num, imgname) {
	if (getAppVersion()) {
		document[imgname].src = img2[num].src;
	}
}

function swtch3(num, imgname) {
	if (getAppVersion()) {
		document[imgname].src = img3[num].src;
	}
}

function arrayStep(num, dir, imgname) {
	if (getAppVersion()) {
	
	if (dir=="next"){
		if (imgpos==img.length-1){
			imgpos=1
		}
		else {
			imgpos=num+1;
			}
		}
	else	{
		if (imgpos<=1){
			imgpos=img.length-1;
		}
		else{
			imgpos=num-1;
		}
	}

	document[imgname].src = img[imgpos].src;
	}
}

function rollover(imgpath,imgName) {
	var newSrc = imgpath + "_ov.gif"
	document.images[imgName].src = newSrc
}

function imgReplace(imgpath,imgName) {
	var newSrc = imgpath
	document.images[imgName].src = newSrc
}

function rollout(imgpath,imgName) {
	var newSrc = imgpath + ".gif"
	document.images[imgName].src = newSrc
}

function OpenWindow(theURL,winName,features) { 
//featureStr = 'toolbar=yes,scrollbars=yes,resize=yes,location=no,menubar=yes,width=700,height=560' 
  featureStr = features;
  opener = window.open(theURL,winName,featureStr);
}

function openWindow350450(theURL,winName) { 
	featureStr = 'toolbar=no,scrollbars=yes,resize=no,location=no,menubar=no,width=350,height=450' 
 // featureStr = features;
  opener = window.open(theURL,winName,featureStr);
}

function openWindow600600(theURL,winName) { 
	featureStr = 'toolbar=no,scrollbars=yes,resize=no,location=no,menubar=no,width=600,height=600' 
 // featureStr = features;
  opener = window.open(theURL,winName,featureStr);
}

function openWindow600600Resize(theURL,winName) { 
	featureStr = 'toolbar=no,scrollbars=yes,resize=yes,location=no,menubar=no,width=600,height=600' 
 // featureStr = features;
  opener = window.open(theURL,winName,featureStr);
}

 function showHideExplorer(){
  if(document.body) var iWidth = document.body.clientWidth;
  if(iWidth > 950) 
		{
		document.getElementById('explorerSpan').style.display = "";
		
		
		}
		else
		{
			 document.getElementById('explorerSpan').style.display = 'none';
		}
 }

function makedate(formName,dateField){
	var dayval;
	
	if ("undefined" == typeof(document.forms[formName].elements['day_' + dateField])) {
		dayval = '01';
	} else {
		dayval = document.forms[formName].elements['day_' + dateField].value
	}
	document.forms[formName].elements[dateField].value = dayval + " " + document.forms[formName].elements['month_' + dateField].value + " " + document.forms[formName].elements['year_' + dateField].value;
}

function loaddate(formName,dateField){
   dateStr = document.forms[formName].elements[dateField].value
   dateArr = dateStr.split(" ",4)
   
    document.forms[formName].elements['day_' + dateField].value = dateArr[0]
    document.forms[formName].elements['month_' + dateField].value = dateArr[1]
    document.forms[formName].elements['year_' + dateField].value = dateArr[2]
    // alert(document.forms[formName].elements['month_' + dateField].selectedIndex)
}


// XML DATE VARIANTS
function makeXmlDate(formName,dateField){
	var f = document.forms[formName]
	var dayval;
	
	if ("undefined" == typeof(f.elements['day_' + dateField])) {
		dayval = '01';
	} else {
		dayval = f.elements['day_' + dateField].value
	}
	
	f.elements[dateField].value = f.elements['year_' + dateField].value + "-" + f.elements['month_' + dateField].value + "-" + dayval;
	//alert(f.elements[dateField].value)
}

function loadXmlDate(formName,dateField){
	var f = document.forms[formName]
		
   dateStr = f.elements[dateField].value
   dateArr = dateStr.split("-",4)
   
    f.elements['day_' + dateField].value = dateArr[2].substr(0,2)
    f.elements['month_' + dateField].value = dateArr[1]
    f.elements['year_' + dateField].value = dateArr[0]
    // alert(document.forms[formName].elements['month_' + dateField].selectedIndex)
}

//function makedatemmyy(formName,dateField){
//	document.forms[formName].elements[dateField].value = document.forms[formName].elements['month_' + dateField].value + " " + document.forms[formName].elements['year_' + dateField].value;
//}

function loaddatemmyy(formName,dateField){
   dateStr = document.forms[formName].elements[dateField].value
   dateArr = dateStr.split(" ",4)
   
    document.forms[formName].elements['month_' + dateField].value = dateArr[0]
    document.forms[formName].elements['year_' + dateField].value = dateArr[1]
    // alert(document.forms[formName].elements['month_' + dateField].selectedIndex)
}

function passImgToForm(targetFeild){

	cUrl = document.forms['imageDetailsForm'].elements['cURL'].value
	cAlt = document.forms['imageDetailsForm'].elements['cAlt'].value
	cWidth = document.forms['imageDetailsForm'].elements['cWidth'].value
	cHeight = document.forms['imageDetailsForm'].elements['cHeight'].value
	cName = document.forms['imageDetailsForm'].elements['cName'].value
	cImgHtml = '<img src="' + cUrl + '" width="' + cWidth + '" height="' + cHeight + '" alt="' + cAlt + '"'
	if (cName != ''){
		cImgHtml = cImgHtml + ' class="' + cName + '"'
		}
	cImgHtml = cImgHtml + '/>'
	opener.document.forms['pageContentForm'].elements[targetFeild].value = cImgHtml
	window.close()
}

function passFilePathToForm(targetFeild, filepath){

	opener.document.forms['pageContentForm'].elements[targetFeild].value = filepath
	window.close()
}

// Links dropdown
function getSelect(s) {
  return s.options[s.selectedIndex].value
}

// --------------------------------- Date and Time ----------------------------------

function screenDate(){
// Store the date in a variable
d = new Date()
dateText = ""

// Get the current day and convert it to the name of the day
dayValue = d.getDay()
if (dayValue == 0)
    dateText += "Sunday"
else if (dayValue == 1)
    dateText += "Monday"
else if (dayValue == 2)
    dateText += "Tuesday"
else if (dayValue == 3)
    dateText += "Wednesday"
else if (dayValue == 4)
    dateText += "Thursday"
else if (dayValue == 5)
    dateText += "Friday"
else if (dayValue == 6)
    dateText += "Saturday"

// Get the current month and convert it to the name of the month
monthValue = d.getMonth()
dateText += " "
if (monthValue == 0)
    dateText += "January"
if (monthValue == 1)
    dateText += "February"
if (monthValue == 2)
    dateText += "March"
if (monthValue == 3)
    dateText += "April"
if (monthValue == 4)
    dateText += "May"
if (monthValue == 5)
    dateText += "June"
if (monthValue == 6)
    dateText += "July"
if (monthValue == 7)
    dateText += "August"
if (monthValue == 8)
    dateText += "September"
if (monthValue == 9)
    dateText += "October"
if (monthValue == 10)
    dateText += "November"
if (monthValue == 11)
    dateText += "December"

// Get the current year; if it's before 2000, add 1900
if (d.getYear() < 2000) 
    dateText += " " + d.getDate() + ", " + (1900 + d.getYear())
else 
    dateText += " " + d.getDate() + ", " + (d.getYear())

// Get the current minutes
minuteValue = d.getMinutes()
if (minuteValue < 10)
    minuteValue = "0" + minuteValue

// Get the current hours
hourValue = d.getHours()

// Customize the greeting based on the current hours
if (hourValue < 12)
    {
    greeting = "Good morning!"
    timeText = " - " + hourValue + ":" + minuteValue + " AM"
    }
else if (hourValue == 12)
    {
    greeting = "Good afternoon!"
    timeText = " - " + hourValue + ":" + minuteValue + " PM"
    }
else if (hourValue < 17)
    {
    greeting = "Good afternoon!"
    timeText = " - " + (hourValue-12) + ":" + minuteValue + " PM"
    }
else
    {
    greeting = "Good evening!"
    timeText = " - " + (hourValue-12) + ":" + minuteValue + " PM"
    }
// Write the greeting, the date, and the time to the page
// document.write(greeting + " It's " + dateText + timeText)
document.write(dateText + timeText)
}

var i=0
var intHide
var intShow

function ewShowMenu(elmnt)
{
//alert(elmnt);
document.getElementById(elmnt).style.visibility="visible"
//clearInterval(intHide)
//intShow=setInterval("show("+ elmnt +")",10)
}
function ewHideMenu(elmnt)
{
document.getElementById(elmnt).style.visibility="hidden"
//clearInterval(intShow)
//intHide=setInterval("hide("+ elmnt +")",10)
}

function ewShow(elmnt)
{
if (i>-100)
	{
	i=i-1
	document.getElementById(elmnt).style.bottom=i
	}
}

function ewHide(elmnt)
{
if (i<0)
	{
	i=i+1
	document.getElementById(elmnt).style.bottom=i
	}
}

  function areyousure(qText,link){
     var agree = false;
     agree = confirm(qText);
     if(agree){
      location=link
       }
    }
    
    
 

//define objects for the main list
function ListItem(nvalue,description){
        //function for defining the elements of the main list
        this.nvalue=nvalue;
        this.description=description;
}

//define objects for the dependent list
function ListSubItem(category,nvalue,description){
        //function for defining the elements of the sublists
        this.category=category;
        this.nvalue=nvalue;
        this.description=description;
}


function reFillList(formName,mainlist,sublist,ArrList){
 var selValue;
 var nOption;
 selValue=document.forms[formName].elements[mainlist][document.forms[formName].elements[mainlist].selectedIndex].value;
 
 // clear the actual list by setting its length to 0
 document.forms[formName].elements[sublist].length=0
 document.forms[formName].elements[sublist].options[0]=new Option('Please Select','0');
 for (var i=0; i < ArrList.length;i++){
        //fill the box with the values corresponding to
        //the category in the first box
       //alert(ArrList[i].category + " - " + selValue + "(" + mainlist + ")")
        if (Number(ArrList[i].category)==Number(selValue)) {
                nOption=document.forms[formName].elements[sublist].length;
                document.forms[formName].elements[sublist].options[nOption]=new Option(ArrList[i].description,ArrList[i].nvalue);
        }
 }
 document.forms[formName].elements[sublist].options[0].selected=true;
}

function reFillList1(){
 var selValue;
 var nOption;
 selValue=document.form1.sublist[document.form1.sublist.selectedIndex].value;
 //alert("Selected value=" +selValue);
 // clear the actual list by setting its length to 0
 document.form1.sublist1.length=0
 for (var i=0; i < SubList1.length;i++){
        //fill the box with the values corresponding to
        //the category in the first box
        if (SubList1[i].category==selValue) {
                nOption=document.form1.sublist1.length;
                document.form1.sublist1.options[nOption]=new Option(SubList1[i].description,SubList1[i].nvalue);
        }
 }
 document.form1.sublist1.options[0].selected=true;
 return;
}

function clearList(formname,ddName){

	//alert("options - " + document.forms[formname].elements[ddName].options.length)
	document.forms[formname].elements[ddName].options.length = 0
	return;
}

function populate(sId,formname,biglist) {
	//find sId in lowest level -- levels below are length = 0 or please select
	var sLevel;
	var nOptionIndex;
	var arr = new Array(0,0,0,0);
	var nId = document.forms[formname].elements[sId].value;
	for (var i=2;i >= 0;i--){
		for(var j=0;j < biglist[i].length;j++){
//			alert(i + ',' + j + '> ' + biglist[i][j].nvalue + ' == ' + nId + ' ?');
			if (Number(nId) == Number(biglist[i][j].nvalue)) {
//			alert('hiya');
				arr[i]= biglist[i][j].nvalue;
				nId = biglist[i][j].category;
				j = biglist[i].length;
			}
		}
	}
	//here we have our values for each of the 4 levels
	// just need to 'select' the right option in each 
	//alert( 'PgId is' + sId + 'array is...' + arr[0] + ',' + arr[1] + ',' + arr[2] + ',' + arr[3]);
	for (var i=0;i<3;i++){
		
		sLevel = 'level_' + (i + 1) + '_' + sId;
		nOptionIndex = 0;
	//alert(sLevel);
	//	alert(i+':'+ document.forms[formname].elements[sLevel].options.length);
		for (j=0;j<document.forms[formname].elements[sLevel].options.length;j++) {
	//		alert(j+' == ' + arr[i]);
			if (Number(document.forms[formname].elements[sLevel].options[j].value) == Number(arr[i])) {
				nOptionIndex = j;
				j = document.forms[formname].elements[sLevel].options.length;
			}
		}
		
		document.forms[formname].elements[sLevel].selectedIndex = nOptionIndex;
		//alert(i + '> selected ' + nOptionIndex);
		if (i < 2) {
			sLevelNext = 'level_' + (i + 2) + '_' + sId;
			reFillList(formname,sLevel,sLevelNext,biglist[i+1])
		}
	}
	return;
}

function setsId(formname,sId) {
	var sListName;
	var sLink;
	sLink = '';
	for (var i=3; i > 0;i--){
		sListName='level_' + i + '_' + sId;
	//	alert(sListName);
		if (document.forms[formname].elements[sListName].length!=0) {
			selValue=document.forms[formname].elements[sListName][document.forms[formname].elements[sListName].selectedIndex].value;
	//		alert('selValue=' + selValue + ',i=' + i);
			if (selValue!='0') {
				i=0;
				document.forms[formname].elements[sId].value = selValue;
			}
		} 
		//alert(document.forms[formname].elements[sId].value);
	}
	return;
}

function tmpsetsId(formname,sId) {
	var sListName;
	var sLink;
	sLink = '';
	for (var i=4; i > 0;i--){
		sListName='level_' + i + '_' + sId;
		alert(sListName);
		if (document.forms[formname].elements[sListName].length == 0) {
		} else {
			selValue=document.forms[formname].elements[sListName][document.forms[formname].elements[sListName].selectedIndex].value;
			sLink += '>';
			sLink += selValue;
		}
	}
	document.forms[formname].elements[sId].value = sLink
	return;
}



function checkvalues(){
//show the selected values
        var val1;
        var val2;
		var val3;
        var cString;
        val1=document.form1.mainlist[document.form1.mainlist.selectedIndex].value;
        val2=document.form1.sublist[document.form1.sublist.selectedIndex].value;
		val3=document.form1.sublist1[document.form1.sublist1.selectedIndex].value;
        cString="Main List=value:" + val1 + "-Description:"+MainList[val1].description
        cString+="\n"
        cString+="Sub List=value:" + val2+ "-Description:"+SubList[val2].description
        cString+="\n"
        cString+="Sub List1=value:" + val3+ "-Description:"+SubList1[val3].description

        alert(cString);
}   

function setEditableDropdown(editfield,formName,fieldName){
//show the selected values
        var lastIndex;
        lastIndex = document.forms[formName].elements[fieldName].options.length - 1;      
        document.forms[formName].elements[fieldName].options[lastIndex].selected=true;
        document.forms[formName].elements[fieldName][document.forms[formName].elements[fieldName].selectedIndex].value = editfield.value      
}


// Admin function for Shipping Options Valid Regions List
function checkShippingLocationsForm(oCurrent) {
	toggleShipLocList(oCurrent.parentNode, oCurrent.checked, true)
}

function toggleShipLocList(oLI, bChecked, bIsTopLevel) {
	
	var oChildren, oChild, oListChildren, i, j, bCheckbox
	
	// Check the children, if they exist
	oChildren = oLI.childNodes
	bCheckbox = false
	for(i=0;i<oChildren.length;i++){
		oChild = oChildren.item(i)
		if (oChild.nodeName == 'SPAN' && !bIsTopLevel) { (bChecked)?oChild.className = 'locationName locationDisabled':oChild.className = 'locationName' }		
		if (oChild.type == 'checkbox' && !bIsTopLevel) { oChild.disabled = bChecked; bCheckbox = oChild.checked;}
		if (oChild.nodeName == 'UL') { 
		    oListChildren = oChild.childNodes
		    for(j=0;j<oListChildren.length;j++){
				toggleShipLocList(oListChildren.item(j), (bChecked || bCheckbox), false)
			}
		}
	}
	
}

function setupShipLocUL(oUL) {
	var oChildren, oChild
	// Check the children LIs
	oChildren = oUL.childNodes
	for(i=0;i<oChildren.length;i++){
		oChild = oChildren.item(i)
		if (oChild.nodeName == 'LI') { setupShipLocList(oChild, false) }
	}
}

function setupShipLocList(oLI, bChecked) {
	
	var oChildren, oChild, oListChildren, i, j, bParCheck
	
	// Check the children, if they exist
	oChildren = oLI.childNodes
	bParCheck = bChecked
	for(i=0;i<oChildren.length;i++){
		oChild = oChildren.item(i)
		if (oChild.nodeName == 'SPAN') { (bChecked)?oChild.className = 'locationName locationDisabled':oChild.className = 'locationName' }		
		if (oChild.type == 'checkbox') { 
			oChild.disabled = bChecked; 
			if (!bParCheck) {bParCheck = oChild.checked}
		}
		if (oChild.nodeName == 'UL') {			
		    oListChildren = oChild.childNodes
		    for(j=0;j<oListChildren.length;j++){
				setupShipLocList(oListChildren.item(j), bParCheck)
			}
		}
	}
	
}

//validate forms, checking that all required fields/options have been specified
function validate(oForm)
{
	emailAdd=oForm.sEmail.value.indexOf("@");
//	txt=oForm.txt.value;
	submitOK="True";
	
	if (oForm.sCompany.value=="")
	{
		alert("Please enter your Company");
		submitOK="False";
	}

	if (emailAdd==-1) 
	{
		alert("Please enter a valid e-mail address");
		submitOK="False";
	}

	if (submitOK=="False")
	{
		return false;
	}
}

function formReset(oForm)
{
	oForm.reset()
}

function form_check_old(oForm) {
	return true;
}

function disableButton(oBtn) {
	
	var oElem,i;
	var oForm = oBtn.form

	// Create a hidden input field spoofing the information of the submit button
	var oNewElem = document.createElement('input')
	oNewElem.type = 'hidden'
	oNewElem.id = 'ewSubmitClone_' + oBtn.id
	oNewElem.name = 'ewSubmitClone_' + oBtn.name
	oNewElem.value = oBtn.value
	oForm.appendChild(oNewElem)

}

//shadow confirm funtion use as onSubmit="return form_are_you_sure('are you sure you want to submit?')"
function form_are_you_sure(qText) {
     return confirm(qText);
    }
    
function form_Send_Reminders(oForm,cControlName,cAlertMessage) {
    formCheckForSelected(oForm, cControlName, cAlertMessage, 'Are you sure you want to send emails to those selected?');
}

function formCheckForSelected(theForm, selectedControl, alertMessage, finalConfirmationMessage) {
    var sControls = '';
    for (i = 0; i < theForm.elements.length; i++) {
        if (theForm.elements[i].name == selectedControl) {
            if (theForm.elements[i].checked) {
                sControls = sControls + theForm.elements[i].value
            }
        }
    }

    if (sControls == '') {
        alert(alertMessage)
        return false;
    }
    else if (finalConfirmationMessage=='') {
        // no Final confirmation needed
        return true;
    } 
    else {
        return confirm(finalConfirmationMessage);
    }
}



function form_check(oForm) {
	var oElem, i,bValid,cCheckRadio,cTestName,oOptions,bSelected, nElemTypeGroup, cId, cName;
	var aRadioCheck = new Array();
	var bHasDisabledButton = false
	bValid = true;
	
	// Only run through validation if the question has not been skipped
	if (oForm.className.indexOf("skipquestion")<0) {
		for (i=0; i<oForm.length;i++ ) {
			oElem = oForm.elements[i]
			
			switch (oElem.type) {
				case "text": nElemTypeGroup = 1; break;
				case "textarea": nElemTypeGroup = 1; break;
				case "checkbox": nElemTypeGroup = 3; break;
				case "radio": nElemTypeGroup = 3; break;
				case "select-one": nElemTypeGroup = 2; break;
				case "select-multiple": nElemTypeGroup =2; break;
				default: nElemTypeGroup = 1; break;
			}
			
			// Check if the element is required
			if (oElem.className.toLowerCase().indexOf("required")>=0) {
				switch (nElemTypeGroup) {
				
					case 1:
						if (form_check_value(oElem.value)) {
							form_alert("required",oElem,"","")
							bValid = false
						}
						break;
					case 2: 
						if (oElem.selectedIndex < 0) {
							form_alert("required",oElem,"","")
							bValid = false						
						}
						else if (form_check_value(oElem.options[oElem.selectedIndex].text)) {
							form_alert("required",oElem,"","")
							bValid = false					
						}
						break;					
					case 3:
						// Check if the checkbox group has already been checked through
						cCheckRadio = "," + aRadioCheck.join(",") + ","
						cTestName = "," + oElem.name + ","
						if (cCheckRadio.indexOf(cTestName)<0) {
							
							// Not found - let's do the checks
							aRadioCheck.push(oElem.name)
							oOptions = document.getElementsByName(oElem.name)
							bSelected = false;
							if (oOptions.length>1) {
								for (i=0; i<oOptions.length;i++) { if(oOptions[i].checked) { bSelected = true; break } }
							}
							if (!bSelected && oOptions.length>1) {
								form_alert("required",oElem,"","")
								bValid = false	
							}
						}
						break;		
				}
				if (!bValid) { break }
			}
		}
		
		if (bValid) {
			// Check the labels for multi answer solutions
			var oLabels, oLabel,cFor, nTotal, nCount
			oLabels = document.getElementsByTagName("label")
		
			for (i=0; i<oLabels.length;i++ ) {
				oLabel = oLabels[i]
				// The first step checks if this label is the child of a label node, a result of XSLT using copy-of
				// for labels, and subsequently ending up with <label *my-true-node*><label *copy-of node*> etc.
				if (oLabel.parentNode.nodeName != 'label') {
					if (oLabel.className.indexOf("multianswer_")==0){
						nCount = 0
						nFirstElem = -1
						nTotal = oLabel.className.replace(/multianswer_/,"")
						for (j=0; j<oForm.length;j++ ) {
							oElem = oForm.elements[j]		
							if (oElem.name == oLabel.htmlFor) {
								if (nFirstElem==-1) {nFirstElem=j}
								if (oElem.checked) {nCount++;}
							}
						}
						if (nCount!=nTotal) {	
							form_alert("multi",oForm.elements[nFirstElem], nTotal, oLabel)
							bValid = false
							break;
						}
					}
				}
			}
		}
	}	
	
	if (bValid) {
		for (i=0; i<oForm.length;i++ ) {
			oElem = oForm.elements[i]		
			if (nElemTypeGroup == 1) {
				if (form_check_value(oElem.value)) {oElem.value = '';}
			}
		}
	}

	if (bValid) {
		// Check for Disabled Buttons
		for (i=0; i<oForm.length;i++ ) {
			oElem = oForm.elements[i];
			if (oElem.type=="hidden" && oElem.id.indexOf("ewSubmitClone_")==0) {
				cId = oElem.id.replace(/ewSubmitClone_/,"")
				cName = oElem.name.replace(/ewSubmitClone_/,"")
				form_disable_button(oForm,cId,cName)
				oElem.id=cId
				oElem.name=cName
				bHasDisabledButton = true;
			}
		}
		
		if (bHasDisabledButton) {
			for (i=0; i<oForm.length;i++ ) {
				oElem = oForm.elements[i];
				if (oElem.type=="submit" || oElem.type=="button") {oElem.disabled=true;}
			}
		}	
	}
	
	return bValid;
}
function setSkip(oElem) {
	oElem.form.className += ' skipquestion'
}
function disableButtonsFromEnter(e, oElem) {

	if(window.event) // IE
	{
		keynum = e.keyCode
	}
	else if(e.which) // Netscape/Firefox/Opera
	{
		keynum = e.which
	}
	
	if(keynum==13) {
		// Go and find the submit button
		oForm = oElem.form
		for (i=0; i<oForm.length;i++ ) {
			oElem = oForm.elements[i];
			if (oElem.type=="submit" && oElem.value=="Submit") {disableButton(oElem);break;}
		}
	}
	return true;

}

function disableButton(oBtn, disableMessage) {

    var oElem, i;
    var oForm = oBtn.form
    if (disableMessage) {
        disableButtonMessage = disableMessage
    }

    // Create a hidden input field spoofing the information of the submit button
    var oNewElem = document.createElement('input')
    oNewElem.type = 'hidden'
    oNewElem.id = 'ewSubmitClone_' + oBtn.id
    oNewElem.name = 'ewSubmitClone_' + oBtn.name
    oNewElem.value = oBtn.value
    oForm.appendChild(oNewElem)

}
function form_disable_button(oForm, btnID, btnName) {
    for (i = 0; i < oForm.length; i++) {
        oElem = oForm.elements[i];
        if (oElem.id == btnID && oElem.name == btnName) {
            oElem.id += '_old'
            oElem.name += '_old'
            oElem.value = disableButtonMessage
        }
    }
}
function form_alert(cAlertType,oElem, cParam,vLabel) {

	var cLabel

	switch (cAlertType) {
	
		case "required":
			// Get the label	
			cLabel = form_get_label(oElem)
			if (cLabel=="") {
				alert("You have not entered all the required information")
			}
			else {
				alert("You have not entered any information in the field : " + cLabel)
			}
			oElem.focus()
			break;
		case "multi":
			//cLabel = vLabel.firstChild.nodeValue
			cLabel = form_flatten_label(vLabel)
			if (cLabel.length > 60) {
				// Truncate the long line
				cLabel=cLabel.substr(0,60)
				// Replace the last series of letters after a space with ellipses
				cLabel=cLabel.replace(/\s(\w+)$/,"...")
			}
			alert("You must select " + cParam + " answer(s) in the question : \n\n \"" + cLabel + "\"") 
			oElem.focus()
			break;
			
	}
}

function form_flatten_label(oLabel) {
	// This takes the innerHTML of a node, and tries to remove the nodes
	// This also cleans up the label node specifically
	var cLabel, re
	cLabel = oLabel.innerHTML
	
	// Step 1: Remove any multilabel legend that has been added (this looks for <SPAN class=ma_label>##ANY TEXT THAT ISN'T >##</SPAN>)
	cLabel=cLabel.replace(/<SPAN class=ma_label>([^<])*<\/SPAN>/i,"")
	
	// Step 2: Remove all TAGS
	//		    Match 1: <
	//		    Match 2: /			- zero or one time, this will pick up closing tags
	//			Match 3: one letter - this indicates that it's a tag
	//			Match 4: any character that isn't a > repeated zero or more times - this is the gumph in the tag
	//			Match 5: >
	//			Flag is set to be global.
	cLabel=cLabel.replace(/<\/?[A-Za-z]([^>])*>/g,"")
	
	// Step 3: Replace &nbsp; with a space
	cLabel=cLabel.replace(/&nbsp;/g," ")
	
	// Step 4: Remove the white space characters (not including space)
	cLabel=cLabel.replace(/[\f\n\r\t\v]/g,"")

	// Step 5: Trim any leading white space
	cLabel=cLabel.replace(/^[\s]*/,"")
	
	// Step 5: Trim any trailing white space
	cLabel=cLabel.replace(/[\s]*$/,"")
	return cLabel;
	
}

function form_get_label(oElem) {

	var cLabel, oLabels, i

	cLabel=""
	oLabels = document.getElementsByTagName("label")

	for (i=0; i<oLabels.length;i++ ) {
		if (oLabels[i].htmlFor == oElem.name) { cLabel = form_flatten_label(oLabels[i]); break; }
	}
	
	return cLabel;


}

function form_check_value(cValue) {

	var aKeyDefs = new Array("please enter","[please enter","[select ","please select","[please select")
	var bIsDefault,i
	
	bIsDefault = false
	cValue = cValue.toString()
	cValue = cValue.toLowerCase()
	
	for (i=0; i<aKeyDefs.length;i++ ) {
		if (cValue.substr(0,aKeyDefs[i].length) == aKeyDefs[i].toLowerCase() || cValue=="") { bIsDefault = true }
	}
	
	return bIsDefault
}

function form_batch_checkbox(oForm, bChecked) {
	var oElem, i
	a = 0
	for (i=0; i<oForm.length;i++ ) {
		oElem = oForm.elements[i];
		if (oElem.type=="checkbox") {oElem.checked = bChecked;}
	} 
}

function pollCheck(o) { 
	var pVal;
	pVal = false;
	for(i=0;i<o.length; i++) {
		if (o.elements[i].type=='radio' && o.elements[i].checked) { pVal = true; }
	}
	if (!pVal) {alert('You have not selected anything to vote for!');}
	return pVal;
}

// AliG functions - recursive position finders.
  function getLeft(obj) {
    var nLeft=obj.offsetLeft;
    while((obj=obj.offsetParent)!=null) { nLeft+=obj.offsetLeft; }
    return nLeft;
  }

  function getTop(obj) {
    var nTop=obj.offsetTop;
    while((obj=obj.offsetParent)!=null) { nTop+=obj.offsetTop; }
    return nTop;
  }  

  function getRight(obj) {
    var nRight=obj.offsetRight;
    while((obj=obj.offsetParent)!=null) { nRight+=obj.offsetRight; }
    return nRight;
  }

  function getBottom(obj) {
    var nBottom=obj.offsetBottom;
    while((obj=obj.offsetParent)!=null) { nBottom+=obj.offsetBottom; }
    return nBottom;
  } 

  function getWidth(obj) {
    var nWidth=obj.offsetWidth;
    return nWidth;
  } 

  function getScrollTop() {
	return document.documentElement['scrollTop'] ? document.documentElement['scrollTop'] : document.body['scrollTop'];
  }

  function getScrollLeft() {
	return document.documentElement['scrollLeft'] ? document.documentElement['scrollLeft'] : document.body['scrollLeft'];
  }
  function getVisHeight() {
    return document.documentElement['clientHeight'] ? document.documentElement['clientHeight'] : document.body['clientHeight']
  }
  function getVisWidth() {
    return document.documentElement['clientWidth'] ? document.documentElement['clientWidth'] : document.body['clientWidth']
  }
//
//
//
//

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) { //wellardsCommon.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 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 xfrmClearCalendar(formRef, fieldRef){
	document.forms[formRef].elements[fieldRef].value = '';
	document.getElementById('dateDisplay-' + fieldRef).innerHTML = '';
}

function setHeight(e){
	var eHeight;
	if(e.contentDocument){
		eHeight = e.contentDocument.body.offsetHeight + 35;
	} else {
		eHeight = e.contentWindow.document.body.scrollHeight;
	}
	e.height = Math.max(eHeight , 10800);
}

function addEvent(obj, evType, fn){
	if(obj.addEventListener)
	{
	obj.addEventListener(evType, fn,false);
	return true;
	} else if (obj.attachEvent){
	var r = obj.attachEvent("on"+evType, fn);
	return r;
	} else {
	return false;
	}
}

function setIFrameHeight(){

	var o = document.getElementsByTagName('iframe');
	for(i=0;i<o.length;i++){
		if (/\bautoHeight\b/.test(o[i].className)){
			setHeight(o[i]);
			//addEvent(o[i],'load', setIFrameHeight);
			
			// Hide the sidebar
			//$("#frame").contents().find("body>table>tbody>tr>td:first").hide();
			//$("#frame").contents().find("#divStayTopLeft").hide();
			
			
			// Move the menu to the main menu
			//$("ul.sectionMenu>li").append("<ul class=\"spoof\"><li/></ul>");
			//var sm = $("ul.sectionMenu>li>ul>li");
			
			// Get the iframe side bar floating content
			//var ifsm = $("#frame").contents().find("#divStayTopLeft table");
			//sm.html("<table>" + ifsm.html() + "</table>");
			
		}
	}
}

addEvent(window, 'load', setIFrameHeight);


function scoreboardShow(clicked, scoreboardId, hiddenId, buttonId) {

    var isVisible = isHiddenVisible(hiddenId);

    // if currentUser exists in hidden, we know we have to hide the other
    if ($(hiddenId + " .currentuser").length > 0) {
        
        if (isVisible) {
            $($(scoreboardId + " .currentuser:first")).slideDown();
        } else {
            $($(scoreboardId + " .currentuser:first")).slideUp();
        }
    }

    // Hide and show 
    if (!isVisible) {
        $(hiddenId).slideDown('3000');
    } else {
        $(hiddenId).slideUp();
    }

    // Change button wording round
    var newWords = $(buttonId).attr('rel');
    var oldWords = $(buttonId).html();
    $(buttonId).attr('rel', oldWords);
    $(buttonId).html(newWords);
}
function isHiddenVisible(id) { 
    if ( $(id).is(':visible') ){
        return true;
    } else {
        return false;
    }
}
