﻿// JScript File
// javaScript functions to support Digital Generation Survey input questions

//Mouseover notes
//
// Indicate that mouseover (tooltip) is available by grey dashed underline. The actual mouseover word must be within a span as
// this is what the style sheet looks for (.hastooltip span).
//
//   <div>This is some text that will have a mouseover word in it,
//       <span class='hastooltip' title='this is the mouseover text that will appear'><span>here</span></span>
//       The word has been underlined in grey (#7777777, dashed) to show that help is available.
//  /</div>
//
// For a mouseover with html content, use new class hasHtmlTimp. Use span as before to underline actual mouseover word. A div contains
// the mouseover content (initially hidden off the page by css by virtue of the class 'hiddenmo').
//    
//    <span>This is the second load of text that will have a mouseover word in it,
//        <span class='hasHtmlTip' >
//            <div style="background-color:Lime" class='hiddenmo'>this is the <b><i>mouseover</i></b> text with <br />HTML markup and an image <img src="images/Neutral.gif" /></div>
//            <span>here</span>.
//        </span> 
//    The word has been underlined in grey to show that help is available.
//    </span>

//GENERIC FUNCTIONS
//=================

//FUNCTIONS that are to be run when the document is loaded should be registered using
//addLoadListener.
//


//FUNCTIONS to be executed each time a page loads


//This global variable keeps track of the number of errors on a page.
var globalErrorCount;
globalErrorCount = 0;

var turnOffGlobalErrors;
turnOffGlobalErrors = false;

addLoadListener(loadImages);
addLoadListener(findExtraElements);
addLoadListener(initMenuTabs);
addLoadListener(checkSuperAssets);
addLoadListener(initTooltips);
addLoadListener(initHtmlTips);
addLoadListener(startList);

//addLoadListener(disableBackButton);



//FUNCTION to allow any number of load event handlers to be assigned without conflicts.
function addLoadListener(fn)
{
//debugger;
  if (typeof window.addEventListener != 'undefined')
  {
    window.addEventListener('load', fn, false);  //Firefox
  }
  else if (typeof document.addEventListener != 'undefined')
  {
    document.addEventListener('load', fn, false); //Opera
  }
  else if (typeof window.attachEvent != 'undefined')
  {
    window.attachEvent('onload', fn); //IE
  }
  else
  {
    var oldfn = window.onload;
    if (typeof window.onload != 'function')
    {
      window.onload = fn;
    }
    else
    {
      window.onload = function()
        {
          oldfn();
          fn();
        };
    }
  }
}

function getElementsByAttribute(attribute, attributeValue)
{
  var matchedArray = new Array();
  var elementArray = new Array();
  
  if (document.all)
  {
    elementArray = document.all;
  }
  else
  {
    elementArray = document.getElementsByTagName("*");
  }
  
  
  for (var i=0; i<elementArray.length; i++)
  {
    if (attribute == "class")
    {
       var pattern = new RegExp("(^| )" +
           attributeValue + "( |$)");
           
       if (pattern.test(elementArray[i].className))
       {
          matchedArray[matchedArray.length] = elementArray[i];
       }
    }
    else if (attribute == "for")
    {
       if (elementArray[i].getAttribute("htmlFor") ||
           elementArray[i].getAttribute("for"))
       {
           if (elementArray[i].htmlFor == attributeValue)
           {
              matchedArray[matchedArray.length] = elementArray[i];
           }
       }
     }
     else if (elementArray[i].getAttribute(attribute) == attributeValue)
     {
        matchedArray[matchedArray.length] = elementArray[i];
     }
  }
  return matchedArray;
}

//FUNCTION that looks for 'extra' attributes which contain a function name
//and the function's parameters. These functions are then executed.
//Timing info to check this isn't too much of an overhead.
function findExtraElements ()
{
//debugger;

   var startTime = new Date();
   //var hour = startTime.getHours();
   //var minutes = startTime.getMinutes();
   //var seconds = startTime.getSeconds();   

   //console operations only available in Firefox
   //console.log("In window.onload (findExtraElements) function. Hours %d, minutes %d, seconds %d",hour,minutes,seconds);
   
   //console.profile();
   //console.time("timing extra");
   var attrs = document.getElementsExtra();
   //console.timeEnd("timing extra");
   
   for (var i=0; i<attrs.length; i++)
   {
      var funcstring = attrs[i].nodeValue;
      eval(funcstring);
   }
   
   var endTime = new Date();
   //alert('Time to execute findExtraElements is ' + (endTime.getTime() - startTime.getTime()) + 'ms\n');
   
   //console.profileEnd();
}



//FUNCTION for 360 survey to see if super assets page should be skipped
function checkSuperAssets()
{
   // If we are loading page 6 (super assets - note, only for 360 survey), and there are no checkboxes on the page, change the text.
   
   
   //debugger;
   var pageHeader;
   var newText;
   var headerElement;
   var elementToChange;
   
   
   //Look to see if we are on the Super Assets page
   headerElement = document.getElementById("SuperAssetID")  //This id is set up in AIESEC360AssetsPage.html
   if (headerElement != null) 
   {
         var arrayOfInputs = document.getElementsByTagName("input");
         if ((arrayOfInputs.length > 6) && (arrayOfInputs[4].type=="checkbox"))
         {
             // do nothing - we want to display the strong and regular checkboxes
         }
         else
         {
             // change the text on the page to say that there were not enough regular and strong competencies
             elementToChange = document.getElementsByClassName("TextPanel")[0]
             newText = "<br />Fewer than five 'Almost Always' or 'Always' competencies were selected in ";
             newText += "the previous pages so the 'Super Assets' stage is omitted for this assessment. <br /><br />";
             newText += "Please continue onto the next page. <br /><br /><br />";
             elementToChange.innerHTML = newText;
         }
   }
}

//function removeDOM_id(element)
//{
//     var e = document.getElementById(element);
//     if(!e)
//          alert("There is no element with the id: "+element);
//     e.removeChild(e.childNodes[0]);
//}

// This is the code needed for IE6 to implement 'hover' functionality for the menu
function startList() 
{
var navRoot;
var node;
//debugger;
   if (document.all && document.getElementById) {
       navRoot = document.getElementById("mainnav");
       if (navRoot != null) {
          for (i=0; i<navRoot.childNodes.length; i++) {
               node = navRoot.childNodes[i];
               if (node.nodeName=="LI") {
                  node.onmouseover=function() {
                     //debugger;
                     this.className+=" over";
                     var i = i++;
                  }
                  node.onmouseout=function() {
                     //debugger;
                     this.className=this.className.replace(" over", "");
                     var i = i++;
                  }
               }
          }
       }
   }
}

//window.onload=startList;

function initMenuTabs()
{
//debugger;
var mainMenu;
var allTabs = new Array();
var mainMenuTabs = new Array();
var mainSelected = -1;
var subMenuTabs = new Array();
var subSelected = -1;
var fileNameURL;
var fileNameTab;
var logoutMenuTab; 
var eraseLogout = true;
var pageURL = self.location.pathname

//var frameNamesRE = /Tasks.aspx|InitiateAIESEC.aspx|Contributors.aspx|NewSiteUser.aspx|RenameProfile.aspx|DeleteProfile.aspx| _
//MergeAccounts.aspx|InviteContributionNewUser.aspx|InviteContributionSiteUser.aspx|DisplayProfileActions.aspx|DisplayProfileInformation.aspx| _
//PickSiteUsers.aspx|SetProfilePermissions.aspx|PublicLinkInfo.aspx/
//if (!frameNamesRE.test(fileNameURL)) {  NO LONGER LIST 'DETAILS' FRAMES INDIVIDUALLY, LOOK FOR THE 'DETAILS' DIRECTORY INSTEAD

  if (pageURL.search("/Details/") == -1) {
  //Skip execution if the Tasks panel, Contributors panel etc. is being loaded as the menu has already been initialised

    fileNameURL = self.location.pathname.substring(location.pathname.lastIndexOf('/')+1);

    logoutMenuTab = document.getElementById("MenuLogoutTab");
    if (logoutMenuTab != null) {
       //Check whether the logout tab should be removed (i.e. noone is logged in but the outline of the tab is displayed)
       for (var i=0; i<logoutMenuTab.childNodes.length; i++)
         {
            if (logoutMenuTab.childNodes[i].tagName=="A") eraseLogout = false;
            //Found the logout hyperlink, don't want to remove the logout tab
         }
         
       if (eraseLogout)
         {
            //remove the logout tab
            logoutMenuTab.parentNode.removeChild(logoutMenuTab);
         }
    }
      
    mainMenu = document.getElementById("mainnav");
    allTabs = mainMenu.getElementsByTagName("li");

    for (var i=0;i<allTabs.length;i++)
	    {
	       if (allTabs[i].className == "on" || allTabs[i].className == "off") 
		       //Found a main tab rather than a sub tab
		       mainMenuTabs.push(allTabs[i]);
	    }

    //Find out which main tab has been selected
    for (var i=0;i<mainMenuTabs.length;i++)
	    {
		    //Check the start of the tab id (MenuX-)
		    if (fileNameURL.indexOf(mainMenuTabs[i].id.substr(0,6)) != -1) {
			    mainMenuTabs[i].className = "on";
			    mainSelected = i;
		    }
		    else
		    {
			    mainMenuTabs[i].className = "off";
		    }
	    }

    if (mainSelected == -1) {
	    //Default to the home tab for every page apart from the menu pages (e.g. Default.aspx, ClosedLanding.aspx
	    //ContributeNew.aspx etc.)
	    mainSelected = 0;
		mainMenuTabs[0].className = "on";
    }
      
    //Collect the subtabs and find the one that matches the page name from the URL
    subMenuTabs = mainMenuTabs[mainSelected].getElementsByTagName("li");
    //debugger;   
    for(var i = 0;i < subMenuTabs.length;i++)
	    {
		    if (fileNameURL.indexOf(subMenuTabs[i].id) != -1) {
			    subMenuTabs[i].className = "subon"
			    subSelected = i;
		    }
			    else 
		    {
			    subMenuTabs[i].className = "suboff"          
		    }
	    }   
     
     if (subSelected == -1) {
	    //Is the page name 'Default' or 'ClosedLanding'? If so, the first tab is the selected one.
	    if ((fileNameURL == "Default.aspx") || (fileNameURL == "ClosedLanding.aspx")) {
		    subSelected = 0;
		    subMenuTabs[0].className = "subon";
	    }   
     }         
   } //Endif for Tasks.aspx check
}


function getQueryString(key)
{
// Build an empty URL structure in which we will store
		// the individual query values by key.
		
		var objURL = new Object();
 
 
		// Use the String::replace method to iterate over each
		// name-value pair in the query string. Location.search
		// gives us the query string (if it exists).
		window.location.search.replace(
			new RegExp( "([^?=&]+)(=([^&]*))?", "g" ),
 
			// For each matched query string pair, add that
			// pair to the URL struct using the pre-equals
			// value as the key.
			function( $0, $1, $2, $3 ){
				objURL[ $1 ] = $3;
			}
			);
	     // Loop over the URL values that we collected.
			for (var strKey in objURL){
 
                if (strKey == key) return objURL[strKey];
			}
 
}

 
//FUNCTION to add a load event to windows.onload. Don't use this at
//present but it may be useful at some point.
function addLoadEvent(func)   //Don't overwrite existing load events for the window.
{   
    var oldonload = window.onload;
    if (typeof window.onload != 'function'){
        window.onload = func;
    } else {
        window.onload = function(){
        oldonload();
        func();
        }
    }
}


//FUNCTION to get all the elements of a particular class name
document.getElementsByClassName = function(clsName){
    //debugger;
    var retVal = new Array();
    var elements = document.getElementsByTagName("*");
    for(var i = 0;i < elements.length;i++){
        if(elements[i].className.indexOf(" ") >= 0){
            var classes = elements[i].className.split(" ");
            for(var j = 0;j < classes.length;j++){
                if(classes[j] == clsName)
                    retVal.push(elements[i]);
            }
        }
        else if(elements[i].className == clsName)
            retVal.push(elements[i]);
    }
    return retVal;
}

//FUNCTION to get all the 'extra' attributes that have been
//given to a control
document.getElementsExtra = function()
{
    //debugger;
    var retVal = new Array();
    var elements = document.getElementsByTagName("*");
    for(var i = 0;i < elements.length;i++)
    {
        if (elements[i].attributes != null)
           {
             var attributes = elements[i].attributes;
             if (attributes.length > 0)
               {
                 for (var j=0; j < attributes.length; j++)
                   {
                     if(attributes[j].nodeName == "extra")
                       {
                       //var func = attributes[j].nodeValue;
                       retVal.push(attributes[j])
                       }
                   }
               }
           }
    }
    return retVal;
}



function addClass(target, classValue)
{
   var pattern = new RegExp("(^| )" + classValue + "( |$)");
   
   if (!pattern.test(target.className))
   { 
      if (target.className == "")
      {
         target.className = classValue;
      }
      else
      {
         target.className += " " + classValue;
      }
   }
   
   return true;
}

function removeClass(target, classValue)
{
  var removedClass = target.className;
  var pattern = new RegExp("(^| )" + classValue + "( |$)");
  
  removedClass = removedClass.replace(pattern, "$1");
  removedClass = removedClass.replace(/ $/, "");
  
  target.className = removedClass;
  
  return true;
}

function attachEventListener(target, eventType, functionRef, capture)
{
  if (typeof target.addEventListener != "undefined")
  {
    target.addEventListener(eventType, functionRef, capture);
  }
  else if (typeof target.attachEvent != "undefined")
  {
    target.attachEvent("on" + eventType, functionRef);
  }
  else
  {
    eventType = "on" + eventType;

    if (typeof target[eventType] == "function")
    {
      var oldListener = target[eventType];

      target[eventType] = function()
      {
        oldListener();

        return functionRef();
      }
    }
    else
    {
      target[eventType] = functionRef;
    }
  }

  return true; 
}

function detachEventListener(target, eventType, functionRef, capture)
{
  if (typeof target.removeEventListener != "undefined")
  {
    target.removeEventListener(eventType, functionRef, capture);
  }
  else if (typeof target.detachEvent != "undefined")
  {
    target.detachEvent("on" + eventType, functionRef);
  }
  else
  {
    target["on" + eventType] = null;
  }

  return true;
}


function stopDefaultAction(event)
{
  event.returnValue = false;

  if (typeof event.preventDefault != "undefined")
  {
    event.preventDefault();
  }

  return true;
}


function getEventTarget(event)
{
  var targetElement = null;

  if (typeof event.target != "undefined")
  {
    targetElement = event.target;
  }
  else
  {
    targetElement = event.srcElement;
  }

  while (targetElement.nodeType == 3 && targetElement.parentNode != null)
  {
    targetElement = targetElement.parentNode;
  }

  return targetElement;
}


function stopEvent(event)
{
  if (typeof event.stopPropagation != "undefined")
  {
    event.stopPropagation();
  }
  else
  {
    event.cancelBubble = true; //IE
  }

  return true;
}



function loadImages()
{
  var img = new Image();
  img.src = '~/imagesUserPicture/BlankImage.JPG';
  var img1 = new Image();
  img1.src = '~/imagesUserPicture/DefaultPicture.jpg';
  var img13 = new Image();
  img13.src = '~/images/TickQMark-Selected.gif';
  var img14 = new Image();
  img14.src = '~/images/TickQMark-Unselected.gif';
  var img3 = new Image();
  img3.src = '~/images/Rate0-Selected.jpg';
  var img4 = new Image();
  img4.src = '~/images/Rate0-Unselected.jpg';
  var img5 = new Image();
  img5.src = '~/images/Rate1-Selected.jpg';
  var img6 = new Image();
  img6.src = '~/images/Rate1-Unselected.jpg';
  var img7 = new Image();
  img7.src = '~/images/Rate2-Selected.jpg';
  var img8 = new Image();
  img8.src = '~/images/Rate2-Unselected.jpg';
  var img9 = new Image();
  img9.src = '~/images/Rate3-Selected.jpg';
  var img10 = new Image();
  img10.src = '~/images/Rate3-Unselected.jpg';
  var img11 = new Image();
  img11.src = '~/images/Rate4-Selected.jpg';
  var img12 = new Image();
  img12.src = '~/images/Rate4-Unselected.jpg';
}

function initTooltips()
{
  //debugger;
  //pre-load background image and other images that we need (e.g. ratings boxes)
  var imgTooltip = new Image();
  imgTooltip.src = '~/images/WhiteBackground.png';  
  
  
  var tips = getElementsByAttribute("class", "hastooltip");

  for (var i = 0; i < tips.length; i++)
  {
    attachEventListener(tips[i], "mouseover", showTip, false);
    attachEventListener(tips[i], "mouseout", hideTip, false);
  }

  return true;
}

function initHtmlTips()
{
  //debugger;
  //pre-load background image
  
  
  var tips = getElementsByAttribute("class", "hasHtmlTip");

  for (var i = 0; i < tips.length; i++)
  {
    attachEventListener(tips[i], "mouseover", showHtmlTip, false);
    attachEventListener(tips[i], "mouseout", hideHtmlTip, false);
  }

  return true;
}

function showTip(event)
{
  //Function to show a tooltip where the text is held in 'title'.
  //debugger;
  if (typeof event == "undefined")
  {
    event = window.event;
  }

  var target = getEventTarget(event);

  while (target.className == null || !/(^| )hastooltip( |$)/.test(target.className))
  {
    target = target.parentNode;
  }

  var tip = document.createElement("div");
  var content=target.getAttribute("title");
  
  
  target.tooltip = tip;
  target.setAttribute("title", "");

  if (target.getAttribute("id") != "")
  {
    tip.setAttribute("id", target.getAttribute("id") + "tooltip");
  }

  tip.className = "tooltip";
  tip.appendChild(document.createTextNode(content));

  var scrollingPosition = getScrollingPosition();
  var cursorPosition = [0, 0];

  if (typeof event.pageX != "undefined" && typeof event.x != "undefined")
  {
    cursorPosition[0] = event.pageX;
    cursorPosition[1] = event.pageY;
  }
  else
  {
    cursorPosition[0] = event.clientX + scrollingPosition[0];
    cursorPosition[1] = event.clientY + scrollingPosition[1];
  }

  tip.style.position = "absolute";
  tip.style.left = cursorPosition[0] + 10 + "px";
  tip.style.top = cursorPosition[1] + 10 + "px";
  tip.style.visibility = "hidden";

  document.getElementsByTagName("body")[0].appendChild(tip);

  var viewportSize = getViewportSize();

  if (cursorPosition[0] - scrollingPosition[0] + 10 + tip.offsetWidth > viewportSize[0] - 25)
  {
    tip.style.left = scrollingPosition[0] + viewportSize[0] - 25 - tip.offsetWidth + "px";
  }
  else
  {
    tip.style.left = cursorPosition[0] + 10 + "px";
  }

  if (cursorPosition[1] - scrollingPosition[1] + 10 + tip.offsetHeight > viewportSize[1] - 25)
  {
    if (event.clientX > (viewportSize[0] - 25 - tip.offsetWidth))
    {
      tip.style.top = cursorPosition[1] - tip.offsetHeight - 10 + "px";
    }
    else
    {
      tip.style.top = scrollingPosition[1] + viewportSize[1] - 25 - tip.offsetHeight + "px";
    }
  }
  else
  {
    tip.style.top = cursorPosition[1] + 10 + "px";
  }

  tip.style.visibility = "visible";

  return true;
}

function showHtmlTip(event)
{
  //Function for mouseover help where the text to be shown is in a div rather than in 'title'.
  //debugger;
  if (typeof event == "undefined")
  {
    event = window.event;
  }

  var target = getEventTarget(event);

  while (target.className == null || !/(^| )hasHtmlTip( |$)/.test(target.className))
  {
    target = target.parentNode;
  }

  var tip = document.createElement("div");
  //The html to be displayed in the mouseover text is contained within the first div of the hasHtmlTip class
  tip.innerHTML = target.getElementsByTagName("div")[0].innerHTML

  target.tooltip = tip;
  target.setAttribute("title", "");

  if (target.getAttribute("id") != "")
  {
    tip.setAttribute("id", target.getAttribute("id") + "tooltip");
  }

  tip.className = "tooltip";
  //tip.appendChild(document.createTextNode(content));

  var scrollingPosition = getScrollingPosition();
  var cursorPosition = [0, 0];

  if (typeof event.pageX != "undefined" && typeof event.x != "undefined")
  {
    cursorPosition[0] = event.pageX;
    cursorPosition[1] = event.pageY;
  }
  else
  {
    cursorPosition[0] = event.clientX + scrollingPosition[0];
    cursorPosition[1] = event.clientY + scrollingPosition[1];
  }

  tip.style.position = "absolute";
  tip.style.left = cursorPosition[0] + 10 + "px";
  tip.style.top = cursorPosition[1] + 10 + "px";
  tip.style.visibility = "hidden";

  document.getElementsByTagName("body")[0].appendChild(tip);

  var viewportSize = getViewportSize();

  if (cursorPosition[0] - scrollingPosition[0] + 10 + tip.offsetWidth > viewportSize[0] - 25)
  {
    tip.style.left = scrollingPosition[0] + viewportSize[0] - 25 - tip.offsetWidth + "px";
  }
  else
  {
    tip.style.left = cursorPosition[0] + 10 + "px";
  }

  if (cursorPosition[1] - scrollingPosition[1] + 10 + tip.offsetHeight > viewportSize[1] - 25)
  {
    if (event.clientX > (viewportSize[0] - 25 - tip.offsetWidth))
    {
      tip.style.top = cursorPosition[1] - tip.offsetHeight - 10 + "px";
    }
    else
    {
      tip.style.top = scrollingPosition[1] + viewportSize[1] - 25 - tip.offsetHeight + "px";
    }
  }
  else
  {
    tip.style.top = cursorPosition[1] + 10 + "px";
  }

  tip.style.visibility = "visible";

  return true;
}

function hideTip(event)
{
//Function to hide a tooltip
//debugger;
  if (typeof event == "undefined")
  {
    event = window.event;
  }

  var target = getEventTarget(event);

  while (target.className == null || !target.className.match(/(^| )hastooltip( |$)/))
  {
    target = target.parentNode;
  }

  if (target.tooltip != null)
  {
    target.setAttribute("title", target.tooltip.childNodes[0].nodeValue);
    target.tooltip.parentNode.removeChild(target.tooltip);
  }

  return false;
}

function hideHtmlTip(event)
{
//Function to hide an html tip (uses a 'div' rather than 'title' to hold the mouseover text).
//debugger;
  if (typeof event == "undefined")
  {
    event = window.event;
  }

  var target = getEventTarget(event);

  while (target.className == null || !target.className.match(/(^| )hasHtmlTip( |$)/))
  {
    target = target.parentNode;
  }

  if (target.tooltip != null)
  {
    target.tooltip.parentNode.removeChild(target.tooltip);
  }

  return false;
}


function getViewportSize()
{
  var size = [0,0];

  if (typeof window.innerWidth != 'undefined')
  {
    size = [
        window.innerWidth,
        window.innerHeight
    ];
  }
  else if (typeof document.documentElement != 'undefined'
      && typeof document.documentElement.clientWidth != 'undefined'
      && document.documentElement.clientWidth != 0)
  {
    size = [
        document.documentElement.clientWidth,
        document.documentElement.clientHeight
    ];
  }
  else
  {
    size = [
        document.getElementsByTagName('body')[0].clientWidth,
        document.getElementsByTagName('body')[0].clientHeight
    ];
  }

  return size;
}

function getScrollingPosition()
{
  //array for X and Y scroll position
  var position = [0, 0];

  //if the window.pageYOffset property is supported
  if(typeof window.pageYOffset != 'undefined')
  {
    //store position values
    position = [
        window.pageXOffset,
        window.pageYOffset
    ];
  }

  //if the documentElement.scrollTop property is supported
  //and the value is greater than zero
  if(typeof document.documentElement.scrollTop != 'undefined'
    && document.documentElement.scrollTop > 0)
  {
    //store position values
    position = [
        document.documentElement.scrollLeft,
        document.documentElement.scrollTop
    ];
  }

  //if the body.scrollTop property is supported
  else if(typeof document.body.scrollTop != 'undefined')
  {
    //store position values
    position = [
        document.body.scrollLeft,
        document.body.scrollTop
    ];
  }

  //return the array
  return position;
}

//FUNCTION to hide the 'other' text box for a list of radio buttons. Called when page is loaded.
function initialHideRBOther(RB_ID, TBO_ID, IndexOther)
{
//debugger;
//alert("Inside initialHideRBOther function");

//IndexOther will be the number of the radion button which is labelled 'Other'.
//The RadioButton is a table, childNodes[1] gets the tbody, get the right row,
//then the second childNodes[1] is the td and the firstChild is the actual input.
var Index = IndexOther - 1;  // Subtract one to get the array index


if (RB_ID.getElementsByTagName("input")[Index].checked == false)
    TBO_ID.style.display="none";
}

//FUNCTION to hide the 'other' text box for a Check Box List. Called when page is loaded.
function initialHideCBOther(CB_ID, TBO_ID, IndexOther)
{
//debugger;
//alert("Inside initialHideCBOther function");

//IndexOther will be the number of the Check Box which is labelled 'Other'.
//Actually, the 'Other' check box must always be the last so search for all inputs
//and then look to see if the last one is checked.

var Index = IndexOther - 1;  // Subtract one to get the array index
var CB_Array = new Array();
var NumLabels;

CB_Array=CB_ID.getElementsByTagName("input");
//'Other' option will be the last one in the list. Table must have horizontal layout.
NumLabels=CB_Array.length;

if (CB_Array[NumLabels-1].checked == false)

    TBO_ID.style.display="none";
}

//FUNCTION to hide the 'other' text box for a Drop Down List. Called when page is loaded.
function initialHideDDLOther(DDL_ID, TBO_ID, IndexOther)
{
//debugger;

//The 'Other' item must be the last in the list so check whether it has been selected.

var lastIndex = DDL_ID.length - 1;  // Subtract one to get the array index

if (DDL_ID.selectedIndex != lastIndex)

    TBO_ID.style.display="none";
}

//FUNCTION to hide or reveal a text box associated with an item in a Radio Button list.
function hideshowRBOther(RB_ID, TextBox_ID, IndexOther)
{
  //debugger;
  
  // This function will be fired when one of the Radio Buttons is selected. If the TextBox is already
  // visible when any of the elements except 'other' is chosen, it needs to be hidden. If 'other'
  // is chosen when the TextBox is hidden, it should be revealed.
  
  // Return immediately if there is no 'other' text box
  
  if (typeof TextBox_ID == "undefined") return;  
  
  var RBotherselected = false;   //Set to true if the 'other' item in the Radio Button is selected.
  var Index = IndexOther - 1;
  
  var seeit = TextBox_ID.style.display;                         
  
  RBotherselected = (RB_ID.getElementsByTagName("input")[Index].checked == true);
  
  
  if (seeit == 'none' && RBotherselected)
  {
    //TextBox is currently hidden, make it visible again
    //Clear out any text that may have been previously entered
    TextBox_ID.style.display='';
    TextBox_ID.value="";
  }
  else if (seeit != 'none' && !RBotherselected)
  {
    //TextBox is currently visible, hide it again
    TextBox_ID.style.display='none';
  }
}

//FUNCTION to hide or reveal a text box associated with an item in a Drop Down list.
function hideshowDDLOther(DDL_ID, TextBox_ID)
{
  // debugger;
  
  // This function will be fired when an item in a Drop Down List is selected. If the TextBox is already
  // visible when any of the elements except 'other' is chosen, it needs to be hidden. If 'other'
  // is chosen when the TextBox is hidden, it should be revealed.
  
  // Return immediately if there is no 'other' text box
  if (TextBox_ID == null) return;
  if (TextBox_ID == undefined) return;  
  if (TextBox_ID.className.indexOf("OtherTextBoxDDL") == -1) return;
    
  var DDLotherselected = false;   //Set to true if the 'other' item in the Drop Down List is selected.
  var lastIndex = DDL_ID.length - 1;
  
  var seeit = TextBox_ID.style.display;                         
  
  DDLotherselected = (DDL_ID.selectedIndex == lastIndex);
  
  
  if (seeit == 'none' && DDLotherselected)
  {
    //TextBox is currently hidden, make it visible again
    //Clear out any text that may have been previously entered
    TextBox_ID.style.display='';
    TextBox_ID.value="";
  }
  else if (seeit != 'none' && !DDLotherselected)
  {
    //TextBox is currently visible, hide it again
    TextBox_ID.style.display='none';
  }
}


//FUNCTION to hide or reveal a text box associated with an item in a Check Box list.
function hideshowCBOther(CB_ID, TextBox_ID)
{
  //debugger;
  
  // This function will be fired when one of the Check Boxes is selected. If the TextBox is already
  // visible when any of the elements except 'other' is chosen, it needs to be hidden. If 'other'
  // is chosen when the TextBox is hidden, it should be revealed.
  
  // Return immediately if there is no 'other' text box
  if (TextBox_ID == undefined) return;    
    
  var CBotherselected = false;   //Set to true if the 'other' item in the Check Box List is selected.
  
  var seeit = TextBox_ID.style.display;   
  
  var CB_Array = new Array();
  var NumLabels;

  CB_Array=CB_ID.getElementsByTagName("input");
  //'Other' option will be the last one in the list. Table must have horizontal layout.
  NumLabels=CB_Array.length;      //NumLabels should be the same as IndexOther              
  
  CBotherselected = (CB_Array[NumLabels-1].checked == true);
  
  
  if (seeit == 'none' && CBotherselected)
  {
    //TextBox is currently hidden, make it visible again
    //Clear out any text that may have been previously entered
    TextBox_ID.style.display='';
    TextBox_ID.value="";
  }
  else if (seeit != 'none' && !CBotherselected)
  {
    //TextBox is currently visible, hide it again
    TextBox_ID.style.display='none';
  }
}

//FUNCTIONS to test last key pressed
function key_pressed(e) 
{
  //debugger;
  if (window.event)
      last_key = window.event.keyCode;  //IE
  else last_key = e.which;              //Firefox
}


function submit_it()
{
  if(last_key == 13)    //value for 'enter' - does the user really want to submit?
     alert("Do you want to submit the form now?");
}

function checkForEnter(e)
{
   //debugger;
   if (window.event)
      last_key = window.event.keyCode;  //IE
   else last_key = e.which     //Firefox
   if (last_key == 13)   //value for 'enter' - don't want to submit if enter is pressed
      return false
   else
      return true;
   
}

function textCounter(field, countfield, maxlimit) 
{
//debugger;
   if (field.value.length > maxlimit) // if too long...trim it!
   {
       field.value = field.value.substring(0, maxlimit);
       alert('your input has been truncated!');
   }
   else   // otherwise, update 'characters left' counter
   {
       countfield.firstChild.nodeValue = maxlimit - field.value.length;
   }
}

//Function to give a warning and truncate a text field when a character limit has been
//reached. 
//e.g. <textarea cols="20" rows="2" value="" name="test" id="test" onkeyup="textLimit(this.form.test, 40);"></textarea>
function textLimit(field, maxlen) 
{
  if (field.value.length > maxlen) 
  {
    field.value = field.value.substring(0, maxlen);
    alert('your input has been truncated!');
  } 
}

function taLimit() {
	var taObj=event.srcElement;
	if (taObj.value.length==taObj.maxLength*1) return false;
}

function taCount(visCnt) { 
	var taObj=event.srcElement;
	if (taObj.value.length>taObj.maxLength*1) taObj.value=taObj.value.substring(0,taObj.maxLength*1);
	if (visCnt) visCnt.innerText=taObj.maxLength-taObj.value.length;
}

 //FUNCTIONS to sort a DDL in either ascending or descending order    
 function sortFuncAsc(record1, record2) {
            var value1 = record1.optText.toLowerCase();
            var value2 = record2.optText.toLowerCase();
            if (value1 > value2) return(1);
            if (value1 < value2) return(-1);
            return(0);
 }

 // sort function - descending (case-insensitive)
 function sortFuncDesc(record1, record2) {
            var value1 = record1.optText.toLowerCase();
            var value2 = record2.optText.toLowerCase();
            if (value1 > value2) return(-1);
            if (value1 < value2) return(1);
            return(0);
 }

 function sortSelect(selectToSort, ascendingOrder) {
 //debugger;
            if (arguments.length == 1)
              {
                ascendingOrder = true;    // default to ascending sort
              }
              

            // copy options into an array
            var myOptions = [];
            for (var loop=0; loop<selectToSort.options.length; loop++) {
                myOptions[loop] = { optText:selectToSort.options[loop].text, optValue:selectToSort.options[loop].value };
            }

            // sort array
            if (ascendingOrder) {
                myOptions.sort(sortFuncAsc);
            } else {
                myOptions.sort(sortFuncDesc);
            }

            // copy sorted options from array back to select box
            selectToSort.options.length = 0;
            for (var loop=0; loop<myOptions.length; loop++) {
                var optObj = document.createElement('option');
                optObj.text = myOptions[loop].optText;
                optObj.value = myOptions[loop].optValue;
                selectToSort.options.add(optObj);
            }
  }     
  
  
  //FUNCTION TO SORT A DROP DOWN LIST but keep the header in position 0 
  //e.g. PLEASE SELECT ONE
  function sortSelectMinusHeader(selectToSort)
  {
    //debugger;
    //Copy DDL header to new temp array
    var tempOptions = [];
    var optObj = document.createElement('option');
    optObj.text = selectToSort.options[0].text;
    optObj.value = selectToSort.options[0].value;
    tempOptions[0] = { optText:optObj.text, optValue:optObj.value };
    
    //Remove the header from the DDL and then sort it
    removeOption(selectToSort,0)
    sortSelect(selectToSort,true);
    
    //Copy the sorted original array to the temp array
    for (var loop=0; loop<selectToSort.length; loop++) {
                var optObj = document.createElement('option');
                optObj.text = selectToSort[loop].text;
                optObj.value = selectToSort[loop].value;
                tempOptions[loop+1] = { optText:optObj.text, optValue:optObj.value };
    }
    
    //Clear the original array
    selectToSort.options.length=0;
    
    //Copy the temp array back to the original
    for (var loop=0; loop<tempOptions.length; loop++) {
                var optObj = document.createElement('option');
                optObj.text = tempOptions[loop].optText;
                optObj.value = tempOptions[loop].optValue;
                selectToSort.options.add(optObj);
                //selectToSort[loop] = { optText:optObj.text, optValue:optObj.value };
    }
  }
    


//FUNCTION to popup an information window
function popup(URL)
{
   //debugger;
   newwindow=window.open(URL,'newPopup','width=300,height=300,toolbar=0,scrollbars=auto,location=0,status=0,menubar=0,resizeable=yes');
   if (window.focus) {newwindow.focus()}
}  




//FUNCTIONS for Text Boxes
//========================
//FUNCTION to hide or reveal an Open Text Box (and its counter), depending upon whether a Check Box
//has been checked or not. 
function hideshowOpenTextBox(CheckBox_ID, TextBox_ID, CountLabel_ID, MaxChars)
{
  //debugger;
  
  // This function will be fired when the TextBox needs to be hidden or revealed.
    
  var CBchecked = false;   //Set to true if the checkbox has been checked.
                           
  var seeit = TextBox_ID.style.display;                         
  
  
  CBchecked = CheckBox_ID.checked;
  
  if (seeit == 'none' && CBchecked)
  {
    //TextBox is currently hidden, make it visible again
    //Clear out any text that may have been previously entered
    TextBox_ID.style.display='';
    TextBox_ID.value="";
    CountLabel_ID.style.display='';
    CountLabel_ID.firstChild.nodeValue = MaxChars;
  }
  else if (seeit != 'none' && !CBchecked)
  {
    //TextBox is currently visible, hide it again
    TextBox_ID.style.display='none';
    CountLabel_ID.style.display='none';
  }
  else if (seeit != 'none' && CBchecked)
    //TextBox is currently visible (e.g. may have hit page reload)
    CountLabel_ID.firstChild.nodeValue = 250 - TextBox_ID.value.length;
}


//FUNCTION to hide or reveal an Open Text Box, depending upon whether a Check Box
//has been checked or not. A maximum of 5 boxes can be checked, strong competencies
//must be chosen before regular competencies.
function hideshowOpenTextBoxMax5(CheckBox_ID, TextBox_ID, CountLabel_ID, Index, MaxChars)
{
  //debugger;
  
  // This function will be fired when the TextBox needs to be hidden or revealed.
    
  var CBchecked = false;   //Set to true if the checkbox has been checked.
                           
  var seeit = TextBox_ID.style.display; 
  
  var arrayOfInputs = new Array();
  var arrayOfCBs = new Array();
  
  //Pick out all the inputs and then refine to get just the check boxes.
  arrayOfInputs = document.getElementsByTagName("input");
  
  for(var i=0;i<arrayOfInputs.length;i++)
    {
       if (arrayOfInputs[i].type == "checkbox")
        {
          arrayOfCBs.push(arrayOfInputs[i]);
        }  
    } 
             
  //Each time a box is ticked, check that it isn't the 6th.
  //Index will be 0 for first item in array
  toomany = max5checksArrayRegStrong(arrayOfCBs, Index);
    
  var count = arrayOfCBs.length;
  
  
  CBchecked = CheckBox_ID.checked;
  
  if (seeit == 'none' && CBchecked)
  {
    //TextBox is currently hidden, make it visible again
    //Clear out any text that may have been previously entered
    TextBox_ID.style.display='';
    TextBox_ID.value="";
    CountLabel_ID.style.display='';
    CountLabel_ID.firstChild.nodeValue=MaxChars;
  }
  else if (seeit != 'none' && !CBchecked)
  {
    //TextBox is currently visible, hide it again
    TextBox_ID.style.display='none';
    CountLabel_ID.style.display='none';
  }
}


//FUNCTION to allow only five checkboxes to be checked
//Requires ID of a checkboxlist

function max5checks(CB,myValue)
{
//debugger;
var boxes = CB.getElementsByTagName("input");
var count = 0;

for (var i=0; i<boxes.length; i++)
  {
    if (boxes[i].checked) count++;
    if (count > 5) 
       {
         alert("Please select no more than 5 boxes");
         boxes[myValue].checked = false;
         break;
       }
  }
}

//FUNCTION to allow only five checkboxes to be checked
//Requires ID of an array of checkbox inputs

function max5checksArray(CBarray,myValue)
{
//debugger;

var count = 0;

for (var i=0; i<CBarray.length; i++)
  {
    if (CBarray[i].checked) count++;
    if (count > 5) 
       {
         alert("Please select no more than 5 items");
         CBarray[myValue].checked = false;
         break;
       }
  }
}

//FUNCTION to allow only five checkboxes to be checked
//Requires an array of checkboxes and the index of the selected box.
function max5checksArrayRegStrong(CBarray,myValue)
{
//debugger;

var toomany = false;
var totalCount = 0;
var strongCount = 0;
var regularCount = 0;
var strongTickedCount = 0;
var k = 0;
var j = 0;

//Find out how many strong competencies are in the array, how many strong have been ticked
//and how many have been ticked altogether.
//Also need to know if any regular competencies have been ticked; we won't allow a strong
//to be unticked, if a regular has already been ticked.
//debugger;
for (j=0; j<CBarray.length; j++)
  {
    if (CBarray[j].title == "This competency is always shown") strongCount++;  //How many strongs are available to tick
    
    if ((CBarray[j].checked == true) && (CBarray[j].title == "This competency is always shown"))
       {
          strongTickedCount++;
          totalCount++;
        }
       else if (CBarray[j].checked == true)
       {
          regularCount++;
          totalCount++;
       }
    if (totalCount > 5)
       {
         alert("Please select no more than 5 characteristics");
         CBarray[myValue].checked = false;  //Uncheck the box which has just been chosen
         toomany = true;
         break;
       }
  }
  

//Don't allow a regular competency to be ticked if there are unticked strong ones.
if ((CBarray[myValue].checked == true) && (CBarray[myValue].title == "This competency is almost always shown") && (strongTickedCount < strongCount))
  {
    alert("Please select ALWAYS competencies before ALMOST ALWAYS ones");
    CBarray[myValue].checked = false;
  }
  
//Don't allow a strong competency to be unticked if there are ticked regular ones.
if ((CBarray[myValue].checked == false) && (CBarray[myValue].title == "This competency is always shown") && (regularCount > 0))
  {
    alert("You cannot deselect an ALWAYS competency as you have already selected at least one ALMOST ALWAYS. Please deselect all ALMOST ALWAYS first")
    CBarray[myValue].checked = true; //Re-check the strong box which has just been deselected.
  }
  
return toomany;
}


//FUNCTION to disable a continue button
function disableContinue(imgContinue)
{
//debugger;

imgContinue.disabled=true;

var i = 0;
              
}



//FUNCTION to calculate the length of the string in the open text box and set the value in the counter appropriately
function calculateCharCount(openTextBox, countLabel, maxChars)
{
//debugger;

var numberChars;

numberChars = maxChars - openTextBox.value.length;
countLabel.firstChild.nodeValue = numberChars;
   
}

//FUNCTION to find the enclosing QContainer div for a question, then find the last child which will hold the corresponding error message
function findErrorMessageField(target)
{
//debugger;
var em;
var regexAsterisk = /Asterisk/;
var regexErrorMessage = /ErrorMessage/;

  //For INVITE NEW USER form, the error message is in a different place.
  if (target.parentNode.className == "NewMemberData")
  {
     em=target.parentNode.getElementsByTagName("span");
     return em[0];
  }

  //For normal questions
  while (target.className != "QContainer")
  {
     target = target.parentNode;
     if (target == null) return undefined;  //CPD log entries don't conform to question layout and so error field won't be found.
  }

  
  //Need to look for either an asterisk or a full error message field.
  if (regexErrorMessage.test(target.lastChild.className))
  {
     //em = target.lastChild; -without the extra span holding the class name
     em=target.lastChild.firstChild;
     return em;
  }
  else
  {
     if (regexAsterisk.test(target.firstChild.className))
     {
        em = target.firstChild;
        return em;
     }
  }
}



//FUNCTION to see if all inputs on a page have been completed.
//If so, re-enable the continue button.
function testInputComplete(imgContinue_ID)
{
//debugger;
//Pick out all the elements that the user must complete; DDLs, radion buttons etc.
  
  var arrayOfInputs = new Array();
  var arrayOfUserInputs = new Array();
  var datePeriodCorrect = true;
  var DDLsCompleted = true;
  var RBselected = true;
  var CBselected = true;
  var ImageSelected = true;
  var AllImagesSelected = true;
  var textBoxCompleted = true;
  var textareaCompleted = true;
  var searchRE = /radio|checkbox|text/;
  var emailRegEx = /^([0-9a-zA-Z]+[-._+&!#%=?'])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$/;
  var alphaRegEx = /^[\sa-zA-Z0-9\-\'\.\;,!\|\+\$\?\(\)\/]*$/;
  var nameRegEx = /^[a-zA-Z\-\'\.\;\,\/]+( [a-zA-Z\-\'\.\;\,\/]+)*$/;
  var regExpTestString = alphaRegEx;
  var pageValid = true;
  
  arrayOfInputs = document.getElementsByTagName("input");
  //First look for radio buttons, checkboxes and text boxes.
  for (var i=0;i<arrayOfInputs.length;i++)
    {
         if (searchRE.test(arrayOfInputs[i].type)) arrayOfUserInputs.push(arrayOfInputs[i]);
    } 
       
  arrayOfInputs = document.getElementsByTagName("textarea");
  //Look for any textareas.
  for (var i=0;i<arrayOfInputs.length;i++)
    {
       arrayOfUserInputs.push(arrayOfInputs[i]); 
    } 
    
    
  arrayOfInputs = document.getElementsByTagName("select");
  //Now look for any DDLs.
  //debugger;
  for (var i=0;i<arrayOfInputs.length;i++)
    {
       if (arrayOfInputs[i].getAttribute("MustBeCompleted") == "No")
       {
         //if we are dealing with a datePeriod, call a routine to check that the end date is later than the start date.
         //the start DAY DDL will have the check period ID set, ignore the other parts of the DDL whilst verifying.
         if (arrayOfInputs[i].getAttribute("StartDateDDL") == "Yes") 
         {
           //debugger;
           datePeriodCorrect = checkDatePeriod(arrayOfInputs[i],arrayOfInputs[i+3]);
           if (!datePeriodCorrect)
           {
               var em = findErrorMessageField(arrayOfInputs[i]);
               em.style.color = "red"; 
           }
          }
       }
       else
       {
         arrayOfUserInputs.push(arrayOfInputs[i]); 
       }
    } 
    
  //Look for ImageList questions
  //debugger;
  arrayOfInputs = document.getElementsByClassName("QInputArea");
  for (var i=0;i<arrayOfInputs.length;i++)
    {
       if ((arrayOfInputs[i].childNodes.length > 0) && (arrayOfInputs[i].childNodes[0].className == "HorizontalListItems"))
          {
             arrayOfUserInputs.push(arrayOfInputs[i].childNodes)
          }
    }
  
  //Go through the list of user inputs that have been collected and validate each appropriately.
  for (var i=0;i<arrayOfUserInputs.length;i++)
    {
    //debugger;
    var itemToVerify = arrayOfUserInputs[i];
     
    //First check for an image list. itemToVerify will be an array and won't have a 'type'.
    if ((itemToVerify.length > 0) && (itemToVerify[0].className == "HorizontalListItems"))
    {
       ImageSelected = testImageSelected(itemToVerify);
       if (!ImageSelected)
       {
          AllImagesSelected = false;
          //Just pass the first element of the list of images to the routine to find the error message field
          var em = findErrorMessageField(itemToVerify[0]);
          incrementGlobalErrorCount();
          em.style.color = "red";
       }
    }
    else
    {
       switch(itemToVerify.type)
       {
       case "textarea":
       var userString = itemToVerify.value;
            //debugger;
            if (userString == "") break; //An empty open text box is ok
            var invalidChars = '<>\{\}';
            for (n=0; n<invalidChars.length; n++) 
            {
              if (userString.indexOf(invalidChars.charAt(n),0) > -1)
              {
                 //If the erroneous textarea is for the Super Assets page with the Regular/Strong checkboxes, issue an alert.
                 if (itemToVerify.getAttribute("OTBtype") == "RegStrong")
                 {
                     alert("Please remove the following characters from your input: /\\{}<>  ");
                     turnOffGlobalErrors = true; //Don't want the global error message to appear as we've issued an alert
                     textareaCompleted = false;
                     break;  //Don't want the alert to appear for each type of incorrect character.
                 }
                 else
                 //Otherwise send the error message to the error field.
                 {
                     var em = findErrorMessageField(itemToVerify);
                     incrementGlobalErrorCount();
                     em.style.color = "red";
                     textareaCompleted = false;
                     break;
                 }
              }
            }
            break;
       case "text":
            //For a text box, check the MustBeCompleted attribute. If set to 'Yes', the box must not be empty and must 
            //conform to a regular expression

            var userString = itemToVerify.value;
            var mustBeCompleted = itemToVerify.getAttribute("MustBeCompleted")
            var nameField = itemToVerify.getAttribute("NameTextField")
            var emailAddress = itemToVerify.getAttribute("EmailAddress")
            var emailInvitationPage = itemToVerify.getAttribute("FirstNameForEmail")
            var CPDLogNumeric = itemToVerify.getAttribute("CPDLogNumeric")
            
            if (CPDLogNumeric == "Yes") //this is needed for the CPD log
            {
                //checkCPDLogEntry will deal with the whole page so just return with its result.
                return(checkCPDLogEntry());
            }
            
            if (emailInvitationPage == "Yes")
            {
                //checkEmailInvitationPage will deal with the whole page so just return with its result.
                return(checkEmailInvitationPage());
            }
            
            if ((mustBeCompleted == "No") && (userString == "")) break;
            
            if (emailAddress == "Yes") 
            {
                if (emailRegEx.test(userString))
                //Check for a valid email address
                {
                  //do nothing
                }
                else
                {
                  var em = findErrorMessageField(itemToVerify);
                  incrementGlobalErrorCount();
                  em.style.color = "red";
                  textBoxCompleted = false;
                }
             }
             else
             {
                nameField=="Yes" ? regExpTestString = nameRegEx : regExpTestString = alphaRegEx;
                if (regExpTestString.test(userString))
                //Allow letters, hyphens, forward slashes and apostrophes. Also optional space and then the pattern multiple times again (e.g. Mary Jane)
                {
                  //do nothing
                }
                else
                {
                  var em = findErrorMessageField(itemToVerify);
                  if (em != undefined) em.style.color = "red";
                  incrementGlobalErrorCount();                
                  textBoxCompleted = false;
                }
             } 
             break;
       case "checkbox":
            //If we are dealing with a CheckBox/Text input for the CPD Log, jump to a separate routine.
            if (itemToVerify.disabled == true) break; //For CPD log - if an entry has already been confirmed, this will be true
    
            var CPDLogCheckBox = itemToVerify.getAttribute("ConfirmCPDLogCheckBox")
            var CPDLogCheckBoxSubject = itemToVerify.getAttribute("ConfirmCPDLogCheckBoxSubject")
            
            if (CPDLogCheckBoxSubject == "Yes")
            {
                //checkCPDLogEntry will deal with the whole page so just return with its result.
                return(checkCPDLogEntry());
            }
            
            if (CPDLogCheckBox == "Yes")
            {
                //checkCPDLogConfirmation only looks at one log entry at a time so set a flag and carry on verifying.
                CBselected = checkCPDLogConfirmation(itemToVerify);
                break;
            }
            
            //For a generic list of checkboxes, at least one must have been selected
            
            //See if there is a maximum number of checkboxes that can be checked.
            var maxNumberToSelect = itemToVerify.parentNode.parentNode.parentNode.parentNode.getAttribute("MaximumNumberToSelect")
            
            //Determine what sort of check box list we are dealing with           
            if (itemToVerify.offsetParent.className == "Top5Checkbox")
            {
                //Find all the 'Top 5' checkboxes and put them in an array for validation. Increment j so
                //that we effectively deal with them altogether.
                var CBTop5 = new Array();
                var j = 0;
                do
                {
                  CBTop5.push(arrayOfUserInputs[i+j]);
                  j++;
                  //Don't want to fall off the end of the array
                  if (i+j == arrayOfUserInputs.length) break;
                } while (arrayOfUserInputs[i+j].offsetParent.className == "Top5Checkbox")
                
                //Call a function to find out how many have been checked, max. is 5. Use an alert to warn user
                //if too many have been selected
                CBcheck = verifyTop5CheckBox(CBTop5)
                if (!CBcheck) CBselected=false; //set the global variable to false to stop the page from moving on
            }
            else if(maxNumberToSelect > 0)
            {             
                CBcheck = true;
               
                var CBTopX = new Array();
                var j = 0;
                do
                   {
                       CBTopX.push(arrayOfUserInputs[i+j]);
                       j++;
                       //Don't want to fall off the end of the array
                       if (i+j == arrayOfUserInputs.length) break;
                    } while (arrayOfUserInputs[i+j].type == "checkbox")
                    
                    //Call a function to find out how many have been checked, max. is 5. Use an alert to warn user
                    //if too many have been selected
                 CBcheck = verifyRestrictedCheckBox(CBTopX,maxNumberToSelect)
                 //debugger;
                 if (!CBcheck) CBselected=false; //set the global variable to false to stop the page from moving on
             }
             else if((itemToVerify.parentNode.className == "ConfirmPeriodCheckBox") || (itemToVerify.parentNode.className == "ConfirmedTextCheckBox"))
             {
               var j = 1; //Single check box so inner count always 1
               var CBcheck = true;
               //debugger;
               CBcheck = checkConfirmBoxAndText(itemToVerify,itemToVerify.parentNode.nextSibling.nextSibling);
               if (!CBcheck) 
               {
                 //Display the error message under the check boxes
                 //Look for the table containing the check boxes and error message field
                 //debugger;
                 var em = findErrorMessageField(itemToVerify);
                 incrementGlobalErrorCount();
                                
                 em.style.color = "red";
                 CBselected=false;  //set the global variable to false to stop the page from moving on
               }
             }
             else if ((itemToVerify.getAttribute("CheckBoxType") == "RegStrong"))
             {
                var j = 0;
                var CBcheck = false; //local variable to see if one checkbox has been selected
                    do
                    {
                        if (arrayOfUserInputs[i+j].checked == true) CBcheck = true;
                        j++;
                        //Don't want to fall off the end of the array
                        if (i+j == arrayOfUserInputs.length) break;
                    } while (arrayOfUserInputs[i+j].type == "checkbox")
            
                    if (!CBcheck) 
                    {
                        alert("Please select at least one competency which is ALWAYS shown");
                        turnOffGlobalErrors = true;  //Don't want to show global error message
                        CBselected=false;  //set the global variable to false to stop the page from moving on
                    }
            
                    i=i+j-1;
                    break;
             }
             else
             {
            // ordinary check box list
              var mustBeCompleted = itemToVerify.parentNode.parentNode.parentNode.parentNode.getAttribute("MustBeCompleted")
              var CBcheck = true;
          
              if (mustBeCompleted == "No") break;  //This will be true for a check box list with one item, maybe others.
           
              var j = 0;
           
              CBcheck = false; //local variable to see if one checkbox has been selected
              do
              {
                if (arrayOfUserInputs[i+j].checked == true) CBcheck = true;
                j++;
                //Don't want to fall off the end of the array
                if (i+j == arrayOfUserInputs.length) break;
              } while (arrayOfUserInputs[i+j].type == "checkbox")
            
              if (!CBcheck) 
              {
                //Display the error message under the check boxes
                //Look for the table containing the check boxes and error message field
                //debugger;
                var em = findErrorMessageField(itemToVerify);
                incrementGlobalErrorCount();
                                
                em.style.color = "red";
                CBselected=false;  //set the global variable to false to stop the page from moving on
              }
            }
            
            i=i+j-1;
            break;
       case "select-one":
            //For a drop down list, the selected index must be > 0  
            if (itemToVerify.selectedIndex == 0) 
              { 
                DDLsCompleted = false;
                //Display the error message under the DDL
                //Find the parent table and then the span which is the location for the error message.
                //Start from the 'select' node and iterate up until we get to 'table'.
                var em = findErrorMessageField(itemToVerify);
                incrementGlobalErrorCount();
                em.style.color = "red";
              }
             break;
       case "radio":
            //For a radio button, one of the group must have been selected
            //Loop round all radio buttons with the same name
            //debugger;
            var RBname = itemToVerify.name;
            var RBcheck = false;
            var parentTable = itemToVerify;  
            
            //If it is ok for none of the radio buttons to be selected, set RBcheck to 'true', regardless.
            //MustBeCompleted attribute it at the table level as opposed to the individual button level.
            while (parentTable.nodeName != "TABLE")
            {
                parentTable = parentTable.parentNode;
            }
            
            //If the radio button is compulsory, nothing more to do.
            if (parentTable.getAttribute("MustBeCompleted") == "No") RBcheck = true;
            
            //This piece of code checks that the second radio button for the T&C form has been
            //selected. 
            var TandCRadio = parentTable.getAttribute("TermsAndConditions")
            if (TandCRadio == "Yes")
            {
              if (arrayOfUserInputs[1].checked == false) RBselected = false;
              if (arrayOfUserInputs[1].checked == true) RBcheck = true;
            }
            else
            {              
                if (!RBcheck)
                {
                    var j = 0;
                    do
                    {
                        if (arrayOfUserInputs[i+j].checked == true) RBcheck = true;
                        j++;
                        //Don't want to fall off the end of the array
                        if (i+j == arrayOfUserInputs.length) break;
                    } while (arrayOfUserInputs[i+j].name == RBname)
                }
            }
            
            if (!RBcheck)
              {
                //Display the error message under the radio buttons
                //Look for the table containing the radio buttons and error message field
                //debugger;
                var em = findErrorMessageField(itemToVerify);
                incrementGlobalErrorCount();
                //Show the error message by changing the colour of the text from white to red
                
                em.style.color = "red";
                RBselected = false;               
              }
              
            //Have gone round inner loop of radio buttons, increment main loop index, i, by the number of radio buttons,
            //then subtract one because i will be incremented by one by virtue of the main loop.
            i=i+j-1;
            break;
         }
     }
  }
   
  //debugger;
  if (!(DDLsCompleted && RBselected && CBselected && textBoxCompleted && textareaCompleted && AllImagesSelected && datePeriodCorrect))
    {
      //If an alert has been issued for too few boxes ticked, don't show the PageError field, otherwise do show it.
      if (!turnOffGlobalErrors)
        {
        showPageError("",false);
        }
      else
        {
        turnOffGlobalErrors = false;
        }
      return false;  
    }
  else
    {
      globalErrorCount=0;
      return true;
    }
}

//FUNCTION to remove any error message when a date period DDL is clicked on
function checkErrorDatePeriod(DDL_ID)
{
//debugger;
var EL_ID;
EL_ID = findErrorMessageField(DDL_ID);
if (EL_ID != undefined) 
  { 
  EL_ID.style.color = "white";
  //alert("In checkErrorDatePeriod, globalErrorCount is " + globalErrorCount);
  decrementGlobalErrorCount();
  }
}

//FUNCTION to check whether an end date is later than a start date
function checkDatePeriod(startDayDDL_ID, endDayDDL_ID)
{
var i=0;
var startDay;
var startMonth;
var startYear;
var endDay;
var endMonth;
var endYear;
var startDate;
var endDate;
startDay = startDayDDL_ID.value;
startMonth = startDayDDL_ID.nextSibling.value;
startYear = startDayDDL_ID.nextSibling.nextSibling.value;
endDay = endDayDDL_ID.value;
endMonth = endDayDDL_ID.nextSibling.value;
endYear = endDayDDL_ID.nextSibling.nextSibling.value;
//debugger;
startDate = new Date(startYear,startMonth - 1,startDay);
endDate = new Date(endYear,endMonth - 1,endDay);
 
return (endDate > startDate);
}

//FUNCTION to check that either the checkbox has been ticked or that the text box has valid input
function checkConfirmBoxAndText(checkBox_ID,textBox_ID)
{
//debugger;
var userString = textBox_ID.value;
var alphaRegEx = /^[\sa-zA-Z0-9\-\'\.\;,!\|\+\$\?\(\)\/]*$/;
  
if (checkBox_ID.checked == false)
  {
  if (alphaRegEx.test(userString) && userString != "")
         //Allow spaces, letters, numbers, hyphens, forward slashes and apostrophes.
         {
            return true;
         }
  else return false;
  }
else //the box could be ticked and there could be a comment so check for validity (an empty comment is ok as the box has been checked)
  {
  if (alphaRegEx.test(userString) || userString == "")
         //Allow spaces, letters, numbers, hyphens, forward slashes and apostrophes.
         {
            return true;
         }
  else return false;
  }
}

//FUNCTION to see if all inputs on the 'invite user' page have been completed.
//If so, re-enable the continue button. Inputs are text boxes (inc. email addresses) and a DDL.
//First email text box must match the second.
function testInviteUserComplete(imgContinue_ID)
{
//debugger;
//Pick out all the elements that the user must complete; DDLs, radion buttons etc.
  
  var arrayOfInputs = new Array();
  var arrayOfUserInputs = new Array();
  var DDLsCompleted = true;
  var textBoxCompleted = true;
  var emailAddressesMatch = false;
  var globalErrorMessage = "";
  var searchRE = /radio|checkbox|text/;
  var emailRegEx = /^([0-9a-zA-Z]+[-._+&!#%=?'])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$/;
  var nameRegEx = /^[a-zA-Z\-\'\.\;\,\/]+( [a-zA-Z\-\'\.\;\,\/]+)*$/;
  var pageValid = true;
  
  arrayOfInputs = document.getElementsByTagName("input");
  //First look for radio buttons, checkboxes and text boxes.
  for (var i=0;i<arrayOfInputs.length;i++)
    {
         if (searchRE.test(arrayOfInputs[i].type)) arrayOfUserInputs.push(arrayOfInputs[i]);
    } 
       
 arrayOfInputs = document.getElementsByTagName("select");
  //Now look for any DDLs.
  for (var i=0;i<arrayOfInputs.length;i++)
    {
       if (arrayOfInputs[i].getAttribute("MustBeCompleted") == "No")
       {
         //do nothing
       }
       else
       {
         arrayOfUserInputs.push(arrayOfInputs[i]); 
       }
    } 
    
  //This variable will keep track of which email field we are on.
  var FirstEmailField = "";   
 
  //Go through the list of user inputs that have been collected and validate each appropriately.
  for (var i=0;i<arrayOfUserInputs.length;i++)
    {
    //debugger;
    var itemToVerify = arrayOfUserInputs[i];
       
    switch(itemToVerify.type)
       {
       case "text":
            //For a text box, check the MustBeCompleted attribute. If set to 'Yes', the box must not be empty and must 
            //conform to a regular expression
            //debugger;
            var userString = itemToVerify.value;
            var mustBeCompleted = itemToVerify.getAttribute("MustBeCompleted")
            var emailAddress = itemToVerify.getAttribute("EmailAddress")
                        
            if ((mustBeCompleted == "No") && (userString == "")) break;
             
            if (emailAddress == "Yes") 
            {
                if (emailRegEx.test(userString))
                //Check for a valid email address
                {
                  if (FirstEmailField == "")
                  { //Dealing with the first email field
                    FirstEmailField = userString;
                  }
                  else
                  { //Dealing with the second email field, see if they match
                    if (FirstEmailField != userString)
                    {
                       //debugger;
                       incrementGlobalErrorCount();
                       incrementGlobalErrorCount();
                       em = findErrorMessageField(itemToVerify);
                       em.style.color = "red";
                       emailAddressesMatch = false;
                       globalErrorMessage = "Email addresses do not match";
                    }
                    else
                    { //Two email fields match
                       emailAddressesMatch = true;
                    }
                  }
                }
                else
                { //Invalid email address found in either field
                  var em = findErrorMessageField(itemToVerify);
                  incrementGlobalErrorCount();
                  incrementGlobalErrorCount();
                  em.style.color = "red";
                  textBoxCompleted = false;
                  globalErrorMessage = "Invalid email address";
                }
             }
             else
             {
                if (nameRegEx.test(userString))
                //Allow letters, hyphens, forward slashes and apostrophes. Also optional space and then the pattern multiple times again (e.g. Mary Jane)
                {
                  //do nothing
                }
                else
                {
                  var em = findErrorMessageField(itemToVerify);
                  //Increment the globalErrorCount twice, see note in checkForErrorSTB.
                  incrementGlobalErrorCount();
                  incrementGlobalErrorCount();
                  em.style.color = "red";
                  textBoxCompleted = false;
                  globalErrorMessage = "Invalid text";
                }
             } 
             break;
       case "select-one":
            //For a drop down list, the selected index must be > 0  
            if (itemToVerify.selectedIndex == 0) 
              { 
                DDLsCompleted = false;
                //Display the error message under the DDL
                //Increment the globalErrorCount twice, see note in checkForErrorSTB.
                var em = findErrorMessageField(itemToVerify);
                incrementGlobalErrorCount();
                incrementGlobalErrorCount();
                em.style.color = "red";
                globalErrorMessage = "Please select an option from the drop down list";
              }
             break;
     
         }
     }
   
  //debugger;
  if (!(DDLsCompleted && textBoxCompleted && emailAddressesMatch))
    {
      //If an alert has been issued for too few boxes ticked, don't show the PageError field, otherwise do show it.
      if (!turnOffGlobalErrors)
        {
        showPageError(globalErrorMessage,false);
        }
      else
        {
        turnOffGlobalErrors = false;
        }
      return false;  
    }
  else
    {
      globalErrorCount=0;
      return true;
    }
}

function decrementGlobalErrorCount()
{
var errorField;
//debugger;

if (globalErrorCount > 0) globalErrorCount -= 1;
if (globalErrorCount == 0) 
  {
  //debugger;
  errorField=document.getElementsByClassName("JavaErrorMessage");
  if (errorField.length != 0) errorField[0].style.color = "white";
  }
}

function incrementGlobalErrorCount()
{  
//debugger;  
  globalErrorCount += 1;
}

function showPageError(errorMessage,messageFixed) // messageFixed is a boolean, if true, want to always display the same message, regardless of count (CPD log)
{
//debugger;
var errorField;

errorField=document.getElementsByClassName("JavaErrorMessage");
if (errorField.length != 0) //If there is not a global error field, do nothing
{
    errorField[0].style.color = "red";
    if (errorMessage != "")
    {
       //If there has been more than one error (actually 2, see checkForErrorSTB), output a generic message. Otherwise as errors get corrected,
       //the error message displayed may not make sense any more.
       if ((globalErrorCount > 2) && !(messageFixed)) errorMessage = "Please correct errors on the page";
       errorField[0].innerHTML = errorMessage;
    }
}
}


//Function to test whether one image has been selected from an image list
function testImageSelected(ImageList)
{
//debugger;
var thisImageSelected;

for (var k=0;k<ImageList.length;k++)
{
  if (ImageList[k].lastChild.getAttribute("isselected") == "false")
  {
    thisImageSelected = false;
  }
  else
  {
    thisImageSelected = true;
    return true;
  }
}
//No images have been selected
return false;
}


//This function is for the 'top 5' part of the Fun and Games section. Each time an image is clicked,
//toggle it and check that it isn't the 6th.
function ImageListToggleAndMax5(Image_ID,myValue,HiddenField_ID)
{
//debugger;
var imageList;
var index;
var count=0;

//An image can always be deselected so first check if we are toggling from Selected to Unselected
if (Image_ID.getAttribute("IsSelected") == "true")
{
  mouseoverOn = Image_ID.getAttribute("current");
  if (mouseoverOn != "")
   {
     Image_ID.setAttribute("src", mouseoverOn);
     Image_ID.setAttribute("current","");
   }
  currentURL = Image_ID.getAttribute("src");
  alternativeURL = Image_ID.getAttribute("AlternativeImage");
  Image_ID.setAttribute("src",alternativeURL);
  Image_ID.setAttribute("AlternativeImage",currentURL); 
  Image_ID.setAttribute("IsSelected","false");
  HiddenField_ID.value=0;
}
else  //Selecting an image
{
  //Check whether too many images have been clicked on
  imageList = document.getElementsByTagName("img");
  for (var index=0;index<imageList.length;index++)
   {
     if (imageList[index].getAttribute("IsSelected") == "true") count++;
   }
 
 
  if (count < 5)
  {
    //Toggle the image that was clicked and the IsSelected flag.
    //First reverse any mouseover.
    mouseoverOn = Image_ID.getAttribute("current");
    if (mouseoverOn != "")
     {
       Image_ID.setAttribute("src", mouseoverOn);
       Image_ID.setAttribute("current","");
     }
    currentURL = Image_ID.getAttribute("src");
    alternativeURL = Image_ID.getAttribute("AlternativeImage");
    Image_ID.setAttribute("src",alternativeURL);
    Image_ID.setAttribute("AlternativeImage",currentURL);
    currentStatus = Image_ID.getAttribute("IsSelected");
    currentStatus == "false" ? currentStatus = "true" : currentStatus = "false";
    Image_ID.setAttribute("IsSelected",currentStatus);
    HiddenField_ID.value=1;
  }
  else
  {
    alert("Please select no more than 5 features");
  }
}
}

//FUNCTION which will be called when a check box in the 'Top 5' question is ticked.
//It must stop the user from checking more than 5 boxes.
function CheckBoxListMax5(CB_ID,index)
{
//debugger;
  var arrayOfInputs = new Array();
  var arrayOfCBs = new Array();
  
  //Pick out all the inputs and then refine to get just the check boxes.
  arrayOfInputs = document.getElementsByTagName("input");
  
  for(var i=0;i<arrayOfInputs.length;i++)
    {
       if ((arrayOfInputs[i].type == "checkbox") && (arrayOfInputs[i].offsetParent.className == "Top5Checkbox"))
        {
          arrayOfCBs.push(arrayOfInputs[i]);
        }  
    } 
             
  //Each time a box is ticked, check that it isn't the 6th.
  //Index will be 0 for first item in array
  toomany = max5checksArray(arrayOfCBs, index);

}


//FUNCTION to check the Technology Page to ensure that at least one item (or 'other') has been selected.
function checkTechnologyPage(arrayOfInputs)
{
//debugger;
var selectionMade = false;
var imageSelected = false;
var arrayImageQuestions = new Array();
var alphaRegEx = /^[a-zA-Z0-9\-\'\.\;\,\/]+( [a-zA-Z0-9\-\'\.\;\,\/]+)*$/;

for (var i=0;i<arrayOfInputs.length;i++)
    {
       if (arrayOfInputs[i].childNodes[0].className == "HorizontalListItems")
          {
           //add the image list to the array of inputs to be verified
           arrayImageQuestions.push(arrayOfInputs[i].childNodes[0].childNodes);
          }
       else
          {
           //found 'other' text box
           var userString = arrayOfInputs[i].firstChild.value;
           if (userString != "")
              {
                if (alphaRegEx.test(userString))
                  {
                   selectionMade = true;
                   //Know we have a valid entry in the 'other' text box so don't bother verifying the image list questions
                   return true;
                  }
              }
          }
    }

for (var j=0;j<arrayImageQuestions.length;j++)
    {
       imageSelected = testImageSelected(arrayImageQuestions[j]);
       if (imageSelected) 
          {
           selectionMade = true;
           break;
          }
     }
if (selectionMade)
    {
       return true;
    }
else
    {
       alert("Please select the technologies you have used recently or specify your own `other` technology");
       return false;
    }    
}

function checkCPDLogConfirmation(checkBox)
{
//debugger;

var CBcheck = true;

    CBcheck = checkConfirmBoxAndText(checkBox,checkBox.parentNode.nextSibling.childNodes[1]);
    
if (CBcheck)
    {
         return true;
    }
else
    {
        var targetElement = checkBox;
        var labelField;
        // Find the 'Confirmation' label so we can show an error
        while (targetElement.className != "PanelConfirmationEntry")
        {
           targetElement = targetElement.parentNode;
        }
        labelField = targetElement.previousSibling;
        labelField.style.color = "red";
        labelField.style.textDecoration = "underline";
        //labelField.style.fontWeight = "bold";
        labelField.title = "Please either tick the checkbox or provide an explanatory comment.";
        //alert("Please confirm all log entries by either selecting the box or writing a comment");
        return false;
    }
}

function checkCPDLogEntry()
{
var arrayOfInputs = new Array();
var arrayTextBoxes = new Array();
var arrayCheckBoxes = new Array();
var errorInCPD = false;

var numericRegEx = /^[.0-9]*$/;
//spaces, letters, numbers punctuation
var alphaRegEx = /^[\sa-zA-Z0-9\-\'\.\;,!\|\+\$\?\(\)\/]*$/;  

var searchTextRE = /text/;
var searchCheckboxRE = /checkbox/;

arrayOfInputs = document.getElementsByTagName("input");
//Filter out the checkboxes and text boxes.
for (var i=0;i<arrayOfInputs.length;i++)
    {
         if (searchTextRE.test(arrayOfInputs[i].type)) arrayTextBoxes.push(arrayOfInputs[i]);
         if (searchCheckboxRE.test(arrayOfInputs[i].type)) arrayCheckBoxes.push(arrayOfInputs[i]);
    }
    
for (var i=0;i<arrayTextBoxes.length;i++)
    {
         //debugger;
         var itemToVerify = arrayTextBoxes[i];
         if (itemToVerify.disabled == true) break;
         var numericField = itemToVerify.getAttribute("CPDLogNumeric");
         var userString = itemToVerify.value;
         var labelField;  //Show an error by making the label red/bold/underlined
         var targetElement = itemToVerify;
         if (numericField == "Yes")
         {
             if (numericRegEx.test(userString))
                {
                   //do nothing
                }
             else
                {
                while (targetElement.className != "FieldPanel")
                    {
                        targetElement = targetElement.parentNode;
                    }
                //The childNodes containing the FieldLabelPanel is a different node in IE6 :(
                for (j=0; targetElement.childNodes.length; j++)
                    {
                        labelField = targetElement.childNodes[j];
                        if (labelField.className == "FieldLabelPanel") break;
                    }
                labelField.style.color = "red";
                labelField.style.textDecoration = "underline";
                //labelField.style.fontWeight = "bold";
                labelField.title = "This field must have numeric input";
                incrementGlobalErrorCount();
                incrementGlobalErrorCount();
                errorInCPD = true;
                /*alert("Duration and Credit fields must be numeric");*/
                } 
         }  
         else
         {
             //alphanumeric field
            if (alphaRegEx.test(userString))
                 {
                    //do nothing
                 }
             else
                 { 
                 while (!((targetElement.className == "FieldPanel") || (targetElement.className == "TextEntryPanel")))
                    {
                        targetElement = targetElement.parentNode;
                    }
                 //The childNodes containing the FieldLabelPanel is a different node in IE6 :(
                for (j=0; targetElement.childNodes.length; j++)
                    {
                        labelField = targetElement.childNodes[j];
                        if ((labelField.className == "TextEntryLabelPanel") || (labelField.className == "FieldLabelPanel")) break;
                    }
                 labelField.style.color = "red";
                 labelField.style.textDecoration = "underline";
                 //labelField.style.fontWeight = "bold";
                 labelField.title = "This field must have alphanumeric input, please remove braces and angled brackets.";
                 incrementGlobalErrorCount();
                 incrementGlobalErrorCount();
                 //alert("Please remove invalid characters from input");
                 errorInCPD = true;
                 }
         }    
    }
if (errorInCPD)
{
    showPageError("Please review page errors by hovering your mouse over the red field labels",true);
    return false;
}
return true;
}
   
//FUNCTION to remove any error message that might be displayed for a text box in a CPD log question
function checkForErrorCPD(CPD_ID)
{
//debugger;

    var targetElement = CPD_ID;
    var labelField;
    //Find the error message for the text field
    while (!((targetElement.className == "FieldPanel") || (targetElement.className == "TextEntryPanel")))
             {
                targetElement = targetElement.parentNode;
             }
    //errorField = targetElement.childNodes[3]; (This was the original asterisk field)
    //errorField.style.color = "#FDFDE8";
    //The childNodes containing the FieldLabelPanel is a different node in IE6 :(
    for (j=0; targetElement.childNodes.length; j++)
            {
               labelField = targetElement.childNodes[j];
               if ((labelField.className == "TextEntryLabelPanel") || (labelField.className == "FieldLabelPanel")) break;
            }
    labelField.style.color = "#555555";
    labelField.style.textDecoration = "";
    //labelField.style.fontWeight = "";
    labelField.title = "";
    
    //alert("In checkForErrorCPD, globalErrorCount is " + globalErrorCount);
    decrementGlobalErrorCount();
    
} 


//FUNCTION to check the Thank You page. In order to invite other participants, the user must complete their own first and
//last names. These are then concatenated and put in the hidden field of each email question for use in the invitation
//email.
function checkEmailInvitationPage()
{
//debugger;

var arrayOfInputs = new Array();
var arrayTextBoxes = new Array();
var arrayCheckBoxes = new Array();
var arrayHiddenFields = new Array();

var pageValid = false;
var requestedInfo = false;
var ownEmailProvided = false;
var madeNominations = false;
var nameValid = false;
var emailValid = false;

var searchTextRE = /text/;
var searchCheckboxRE = /checkbox/;
var searchHiddenRE = /hidden/;
//var emailRegEx = /^([a-zA-Z0-9])+([\.\+a-zA-Z0-9_-])*@([a-zA-Z0-9])+(\.[a-zA-Z0-9_-]+)+$/;
var emailRegEx = /^([0-9a-zA-Z]+[-._+&!#%=?'])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$/;
//Allow trailing spaces in names as it's easy to add these accidentally!
var nameRegEx = /^[a-zA-Z\-\'\.]+([a-zA-Z\-\'\.\ ]+)*$/;

arrayOfInputs = document.getElementsByTagName("input");
//Filter out the checkboxes and text boxes.
for (var i=0;i<arrayOfInputs.length;i++)
    {
         if (searchTextRE.test(arrayOfInputs[i].type)) arrayTextBoxes.push(arrayOfInputs[i]);
         if (searchCheckboxRE.test(arrayOfInputs[i].type)) arrayCheckBoxes.push(arrayOfInputs[i]);
         if (searchHiddenRE.test(arrayOfInputs[i].type)) 
            {
               //Look for the hidden fields that are part of the question, not ViewState etc.
               if (arrayOfInputs[i].parentNode.className == "QInputArea") arrayHiddenFields.push(arrayOfInputs[i]);
            }
    }
    
//First and Family names are in first two elements of arrayTextBoxes, user's email address in the third.
var firstName = arrayTextBoxes[0].value;
var familyName = arrayTextBoxes[1].value;
var emailAddress = arrayTextBoxes[2].value;
var fullName = "";

if ((nameRegEx.test(firstName)) && (nameRegEx.test(familyName)))
    {
       fullName = firstName + " " + familyName;
    }
    
if ((arrayCheckBoxes[0].checked) || (arrayCheckBoxes[1].checked))
    {
       requestedInfo = true;
    }
    
if (emailRegEx.test(emailAddress))
    { 
       ownEmailProvided = true;
    }

if (requestedInfo && !(ownEmailProvided))
    {
        alert("Please supply a valid email address so we can send you the information you have requested");
        return false;
    }
    
var count = 0;
for (var i=4; i<13; i=i+2)
    {
    if (arrayTextBoxes[i].value != (null || ""))
        {
           nameValid = nameRegEx.test(arrayTextBoxes[i-1].value);
           emailValid = emailRegEx.test(arrayTextBoxes[i].value);
           if (nameValid && emailValid)
             {
               if (fullName != "")
                 {
                   arrayHiddenFields[count].value = fullName;
                 }
               else
                 {
                   arrayHiddenFields[count].value = null;
                   alert("Please supply your First and Family names if you wish to invite other participants.");
                   return false;
                 }
             }
           else //name or email invalid
             {
                var index=convertCount(count);
                if (emailValid)
                   {
                     alert("Please supply a valid name for the " + index + " person you are inviting");
                     return false;
                   }
                else if (nameValid)
                   {
                     alert("Please supply a valid email address for the " + index + " person you are inviting");
                     return false;
                   }
                else 
                   {
                     alert("Please supply a valid email address and name for the " + index + " person you are inviting");
                     return false;
                   }
             }
         }
         count++;
    }
return true;       
}

//FUNCTION to convert between a count and a position
function convertCount(index)
{
var result = null;
switch (index) 
 {
  case 0: result = 'first'; break;
  case 1: result = 'second'; break;
  case 2: result = 'third'; break;
  case 3: result = 'fourth'; break;
  case 4: result = 'fifth'; break;
  default: result = 'unknown';
 }
return result;
}



//Function that will be called when 'continue' is pressed for the 'Top 5' question.
//Only allow 5 boxes to be checked.
function verifyTop5CheckBox(CBTop5Array)
{
//debugger;
var lengthCBArray = CBTop5Array.length
var i = 0;
var countChecked = 0;

for (var i=0; i<lengthCBArray; i++)
  {
    if (CBTop5Array[i].checked) countChecked++;
    if (countChecked > 5)
       {
         alert("Please select no more than 5 boxes");
         turnOffGlobalErrors = true;
         return false;
       }
  }
return true;
}

//Function that will be called when 'continue' is pressed for the 'no more than 3' question.
function verifyRestrictedCheckBox(CBArray,Limit)
{
//debugger;
var lengthCBArray = CBArray.length
var i = 0;
var countChecked = 0;

for (var i=0; i<lengthCBArray; i++)
  {
   if (CBArray[i].checked) countChecked++;
   if (countChecked > Limit)
       {
         alert("Please select no more than " + Limit + " boxes");
         turnOffGlobalErrors = true;
         return false;
       }
   }
return true;
}

//FUNCTION to show an alert message if a particular item in a DDL has been selected
function onChangeDDL(DDL_ID)
{
var itemSelected = DDL_ID.selectedIndex;
if (itemSelected == DDL_ID.getAttribute("ItemWithAlert")) alert(DDL_ID.getAttribute("AlertMessage"));
}

//FUNCTION to remove any error message that might be displayed for the drop down list
function checkForErrorDDL(DDL_ID)
{
//debugger;
//Because this function is attached to both the onfocus and onclick events, need to add
    //2 to globalErrorCount when there is an error which will then get decremented by 2 when
    //this function is called twice.
var EL_ID;
EL_ID = findErrorMessageField(DDL_ID);

if (DDL_ID.selectedIndex != 0)
   {
     EL_ID.style.color = "white";
     //alert("In checkForErrorDDL, globalErrorCount is " + globalErrorCount);
     decrementGlobalErrorCount();
   }
}


function checkForErrorRB(RB_ID, NumButtons)
{
//debugger;

var EL_ID;
var k;
var arrayOfButtons = RB_ID.getElementsByTagName("input")
var RBchecked = false;

//Find the error message for the text field
EL_ID = findErrorMessageField(RB_ID);    
  
for (var k=0;k<arrayOfButtons.length;k++)
 {
   if (arrayOfButtons[k].checked) 
      {
        RBchecked = true;
      }
 }
 if (RBchecked)
   {
    EL_ID.style.color = "white";
    decrementGlobalErrorCount();
   }
}

function checkForErrorCB(CB_ID)
{
//debugger;

var EL_ID;
var k;
var arrayOfBoxes = CB_ID.getElementsByTagName("input")
var CBchecked = false;

//Find the error message for the text field
EL_ID = findErrorMessageField(CB_ID);    
  
for (var k=0;k<arrayOfBoxes.length;k++)
 {
   if (arrayOfBoxes[k].checked) 
      {
        CBchecked = true;
      }
 }
 if (CBchecked)
   {
    EL_ID.style.color = "white";
    decrementGlobalErrorCount();
   }
}

//For a Radio Button list with an 'other' text box, a click must both check whether to expose/hide the 'other' text box
//and check whether any visible error message should be hidden.
function combinedClickRB(RB_ID, TextBox_ID, NumButtons)
{
//debugger;
checkForErrorRB(RB_ID, NumButtons);
hideshowRBOther(RB_ID, TextBox_ID, NumButtons);
}

//If a check box list has a maximum number of boxes that can be selected, deselect the last checked box in the list.
//Don't know the index of the item which was clicked last as the check box list wasn't generated dynamically.
function checkMaximumClickedCB(CBarray,MaxNumber)
{
//debugger;
var arrayOfBoxes = CBarray.getElementsByTagName("input")
var count = 0;

for (var i=0; i<arrayOfBoxes.length; i++)
  {
    if (arrayOfBoxes[i].checked) count++;
    if (count > MaxNumber) 
       {
         alert("Please select no more than " + MaxNumber + " boxes");
         arrayOfBoxes[i].checked = false;
         break;
       }
  }
}

//For a Check Box list with an 'other' text box, a click must both check whether to expose/hide the 'other' text box
//and check whether any visible error message should be hidden. Also whether the maximum number of clicks has been reached.
function combinedClickCB(CB_ID, TextBox_ID, MaxNumber)
{
//debugger;
checkForErrorCB(CB_ID);
hideshowCBOther(CB_ID, TextBox_ID);
if (MaxNumber > 0) checkMaximumClickedCB(CB_ID,MaxNumber);
}

//For a Drop Down Lise list with an 'other' text box, a click must both check whether to expose/hide the 'other' text box
//and check whether any visible error message should be hidden. 
function combinedClickDDL(DDL_ID, TextBox_ID)
{
//debugger;
checkForErrorDDL(DDL_ID);
hideshowDDLOther(DDL_ID, TextBox_ID);
}

//Clear any error message associated with a 'confirm' check box. Message will also be cleared if something
//is typed into the accompanying text box.
function onclickConfirm(CH_ID)
{
    //debugger;
    var EL_ID;
    EL_ID = findErrorMessageField(CH_ID);
    EL_ID.style.color = "white";
    decrementGlobalErrorCount();
}

//Clear any error message associated with a 'confirm' check box that is part of a CPD log. Message will also be cleared if something
//is typed into the accompanying text box.
function onclickConfirmCPD(CB_ID)
{
    //debugger;
    var targetElement = CB_ID;
    var labelField;
    // Find the 'Confirmation' label so we can clear the error
    while (targetElement.className != "PanelConfirmationEntry")
        {
           targetElement = targetElement.parentNode;
        }
    labelField = targetElement.previousSibling;
    labelField.style.color = "#555555";
    labelField.style.textDecoration = "";
    //labelField.style.fontWeight = "";
    labelField.title = "";
    decrementGlobalErrorCount();
}

//FUNCTION to remove any error message that might be displayed for a short text box
function checkForErrorSTB(STB_ID)
{
//debugger;

    var EL_ID;
    //Find the error message for the text field
    //Because this function is attached to both the onfocus and onclick events, need to add
    //2 to globalErrorCount when there is an error which will then get decremented by 2 when
    //this function is called twice.
    EL_ID = findErrorMessageField(STB_ID);
    
    EL_ID.style.color = "white";
    //alert("In checkForErrorSTB, globalErrorCount is " + globalErrorCount);
    decrementGlobalErrorCount();
    
}

//FUNCTION to remove any error message that might be displayed for a User Picture
//Fired when you click on the Browse button
function checkForErrorUserPicture(BrowseButton_ID)
{
//debugger;

    var EL_ID;
    //Find the error message for the User Picture field
    EL_ID = findErrorMessageField(BrowseButton_ID);
    
    EL_ID.style.color = "white";
    decrementGlobalErrorCount();
    
}

//FUNCTION to remove any error message that might be displayed for a User Picture
function checkForFileName(Submit_ID)
{
//debugger;

    var FileUploadValue;
    //See if the file upload control has a file name
    FileUploadValue = Submit_ID.previousSibling.value
    if (FileUploadValue == "") 
       {   
        //Find the error message for the UserPicture field
        EL_ID = findErrorMessageField(Submit_ID);   
        EL_ID.style.color = "red";
        decrementGlobalErrorCount();
        return false;
        }
    else
        {
        return true;
        }   
}

//FUNCTION to remove any error message that might be displayed for an open text box
function checkForErrorOTB(OTB_ID)
{
//debugger;

 var errorMessage = "PLEASE remove any of the following characters from your input: < > { }";
 var EL_ID;
 
 EL_ID = findErrorMessageField(OTB_ID);
 
 EL_ID.style.color = "white";  
 decrementGlobalErrorCount();  
 
}

function checkForReturn(LinkButton_ID,e)
{

if (window.event)
      last_key = window.event.keyCode;  //IE
else last_key = e.which     //Firefox

if (last_key == 13) 
 {
 //debugger;
   if (LinkButton_ID && typeof(LinkButton_ID.click) == 'undefined') 
   {
        LinkButton_ID.click = function()
        { 
           var result = true;
           if (LinkButton_ID.onclick) result = LinkButton_ID.onclick();
           if (typeof(result) == 'undefined' || result) 
           {
               eval(LinkButton_ID.href);
           }
        }
    }
 }
else 
 {
       return true
  }; 
}
    
//Function to pad a string to the left with the specified character to the specified length
function padLeft(str, pad, count) 
{
while(str.length<count)
str=pad+str;
return str;
}

//Function to pad a string to the left with the specified character to the specified length
function padLeft(str, pad, count) 
{
while(str.length<count)
str=pad+str;
return str;
}

//Function to make images match HiddenPattern after page reload (the value of the image list won't have been saved at this point
//in the database so the HiddenPattern and the images will be out of sync.

function matchHiddenPattern(Image_ID, HiddenPattern_ID, NumImageButtons,FirstItemLabel)
{
//debugger;
var binaryArray;
var imageList;
var index=0;
var currentURL;
var alternativeURL;


//HiddenPattern_ID.value is a string containing a number. Convert to an integer then 
//into a binary string. Then pad out binaryArray with zeroes on the left until it is the
//same length as NumImageButtons
//E.g. If the question has 5 buttons, "7" would become "00111". 

//If HiddenPattern is 0, nothing to do. Also, only need to go through the pattern once for each question so
//test whether our image is the first item in the list (as flagged by FirstItemLabel (from ConfigData). If not, return immediately.
if ((HiddenPattern_ID.value == 0) || (Image_ID.parentNode.id != FirstItemLabel)) return;

binaryArray = (parseInt(HiddenPattern_ID.value,10).toString(2));
binaryArray = padLeft(binaryArray, "0", NumImageButtons);

imageList = Image_ID.parentNode.parentNode.childNodes;

for (var index=0;index<imageList.length;index++)
{
  // If the image's 'IsSelected' value matches the corresponding bit in HiddenPattern, nothing to do.
  // Otherwise, flip the image.
  if ((binaryArray[index] == "1") && (imageList[index].lastChild.getAttribute("IsSelected") == "false"))
      {
       //select the image
       currentURL = imageList[index].lastChild.getAttribute("src");
       alternativeURL = imageList[index].lastChild.getAttribute("AlternativeImage");
       imageList[index].lastChild.setAttribute("src",alternativeURL);
       imageList[index].lastChild.setAttribute("AlternativeImage",currentURL);
       currentStatus = imageList[index].lastChild.getAttribute("IsSelected");
       currentStatus == "false" ? currentStatus = "true" : currentStatus = "false";
       imageList[index].lastChild.setAttribute("IsSelected",currentStatus);
      }
}
}

//Function to make images match HiddenPattern after page reload (the value of the image list won't have been saved at this point
//in the database so the HiddenPattern and the images will be out of sync. This is for questions where the image list only
//has one item.

function matchHiddenFlag(Image_ID, HiddenPattern_ID)
{
//debugger;
var binaryArray;
var imageList;
var index=0;
var currentURL;
var alternativeURL;


//HiddenPattern_ID.value is either 1 or 0

if (HiddenPattern_ID.value == 0) return;

if ((HiddenPattern_ID.value == 1) && (Image_ID.getAttribute("IsSelected") == "false"))
      {
       //select the image
       currentURL = Image_ID.getAttribute("src");
       alternativeURL = Image_ID.getAttribute("AlternativeImage");
       Image_ID.setAttribute("src",alternativeURL);
       Image_ID.setAttribute("AlternativeImage",currentURL);
       currentStatus = Image_ID.getAttribute("IsSelected");
       currentStatus == "false" ? currentStatus = "true" : currentStatus = "false";
       Image_ID.setAttribute("IsSelected",currentStatus);
      }
}

//Function deselectImage - deselect a previously selected image. Find the image to deselect
//from the given ImageIndex (first find the list of images that Image_ID is part of).
function deselectImage(Image_ID, ImageIndex)
{
//debugger;
var imageToDeselect;
var currentURL;
var alternativeURL;
var currentStatus;

imageToDeselect=Image_ID.parentNode.parentNode.childNodes[ImageIndex].lastChild;
//Toggle the image that is being displayed and the value of IsSelected
currentURL = imageToDeselect.getAttribute("src");
alternativeURL = imageToDeselect.getAttribute("AlternativeImage");
imageToDeselect.setAttribute("src",alternativeURL);
imageToDeselect.setAttribute("AlternativeImage",currentURL);
currentStatus = imageToDeselect.getAttribute("IsSelected");
currentStatus == "false" ? currentStatus = "true" : currentStatus = "false";
imageToDeselect.setAttribute("IsSelected",currentStatus);
}


//Function to toggle the URL for an image
function toggleImage(Label_ID, Image_ID, HiddenPattern_ID, ImageIndex, NumImageButtons, OneOnly)
{
//debugger;

var currentURL;
var alternativeURL;
var tempString;
var binaryArray;
var imageAlreadySelected;
var selectOneOnly = OneOnly == 1 ? true : false;
var currentStatus;


//HiddenPattern_ID.value is a string containing a number. Convert to an integer then 
//into a binary string. Then pad out binaryArray with zeroes on the left until it is the
//same length as NumImageButtons
//E.g. If the question has 5 buttons, "7" would become "00111". 


binaryArray = (parseInt(HiddenPattern_ID.value,10).toString(2));
binaryArray = padLeft(binaryArray, "0", NumImageButtons);

imageAlreadySelected = binaryArray.indexOf("1");  //Look for a one in the array, shows that something has been selected

if (selectOneOnly && (imageAlreadySelected != -1) && (imageAlreadySelected != ImageIndex))
{
   //Toggle the image for the item that is being deselected
   deselectImage(Image_ID,imageAlreadySelected);
   //Clear the previous entry in binaryArray
   binaryArray = binaryArray.replace(/1/,"0");     
}

//Toggle the value in binaryArray for the Image Item that has been clicked
if (binaryArray.charAt(ImageIndex) == "1")
{
   tempString = binaryArray.slice(ImageIndex) //Get the end of the string, the first char of tempString is the one to replace.
   binaryArray = binaryArray.slice(0,ImageIndex) //First part of string
   binaryArray = binaryArray + "0" + tempString.slice(1) //Join first part to last part, replacing the first char. of last part
}
else
{
   tempString = binaryArray.slice(ImageIndex) //Get the end of the string, the first char of tempString is the one to replace.
   binaryArray = binaryArray.slice(0,ImageIndex) //First part of string
   binaryArray = binaryArray + "1" + tempString.slice(1) //Join first part to last part, replacing the first char. of last part
}

//Toggle the image that is being displayed and the IsSelected flag.
//First reverse any mouseover.
mouseoverOn = Image_ID.getAttribute("current");
if (mouseoverOn != "")
{
   Image_ID.setAttribute("src", mouseoverOn);
   Image_ID.setAttribute("current","");
}
currentURL = Image_ID.getAttribute("src");
alternativeURL = Image_ID.getAttribute("AlternativeImage");
Image_ID.setAttribute("src",alternativeURL);
Image_ID.setAttribute("AlternativeImage",currentURL);
currentStatus = Image_ID.getAttribute("IsSelected");
currentStatus == "false" ? currentStatus = "true" : currentStatus = "false";
Image_ID.setAttribute("IsSelected",currentStatus);


//Convert the binaryArray back to a string containing a decimal integer
binaryArray = (parseInt(binaryArray,2));
HiddenPattern_ID.value = binaryArray.toString();

//debugger;
//If at least one image has been selected, remove any error asterisk that might be present
if (binaryArray > 0)
{ 
  var em = findErrorMessageField(Image_ID);
  if (typeof em != "undefined") 
    { 
      em.style.color="white";
      decrementGlobalErrorCount();
    }
}
}

//FUNCTION to change the image displayed on mouseover event
function mouseoverImage(Image_ID)
{
//debugger;
var currentImage = Image_ID.getAttribute("src");
Image_ID.setAttribute("current",currentImage);
var mouseoverImage = Image_ID.getAttribute("MouseoverImage");
Image_ID.setAttribute("src",mouseoverImage);
}

function mouseoutImage(Image_ID)
{
//debugger;
var resetImage = Image_ID.getAttribute("current");
if (resetImage != "") Image_ID.setAttribute("src",resetImage);
}


//FUNCTIONS for Period question
//=============================
function DayChanged(DayCtrlID,MonthCtrlID,YearCtrlID) {
//debugger;
var months = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
//Clear any error that may have been set
checkErrorDatePeriod(DayCtrlID);
DateSelected = new Date(YearCtrlID.value, MonthCtrlID.value - 1, DayCtrlID.value);
dsmonth = months[DateSelected.getMonth()];
dsday = DateSelected.getDate();
dsyear = DateSelected.getFullYear();
DateString = dsday + " " + dsmonth + " " + dsyear;
}


function MonthChanged(MonthCtrlID,YearCtrlID,DayCtrlID) {
//debugger;
//Clear any error that may have been set
checkErrorDatePeriod(MonthCtrlID);
var dayselected = DayCtrlID.value;

// Months are set up in DDL to be from 1 to 12 rather than from 0 to 11. This means
// that timeA is actually the first day of the following month. Subtract one day
// (86400000 milliseconds) to get actual month required and then get the number
// of days in that month.

timeA = new Date(YearCtrlID.value, MonthCtrlID.value,1);
timeDifference = timeA - 86400000;
timeB = new Date(timeDifference);
var daysInMonth = timeB.getDate();

// If the user has selected a day which doesn't exist for the month and year chosen, recreate the 
// 'day' DDL
if (dayselected > daysInMonth) 
{
    // Clear the 'day' DDL
    for (var i = 0; i < DayCtrlID.length; i++) {
    DayCtrlID.options[i] = null;
        }
    // Repopulate the 'day' DDL
    for (var i = 0; i < daysInMonth; i++) {
    DayCtrlID.options[i] = new Option(i+1,i+1);  // new Option(text,value,default,selected)
        }
    // Set the day to the last day in the month
    DayCtrlID.options[daysInMonth - 1].selected = true;    
    dayselected = daysInMonth;
}

// If the day DDL has been shortened (e.g. user switched from the last day in Jan to the last
// day in Feb), it may need to be increased if the user then switches back to a month
// with more days in it. 
if (DayCtrlID.length != daysInMonth)
{
    // Clear the 'day' DDL
    for (var i = 0; i < DayCtrlID.length; i++) {
    DayCtrlID.options[i] = null;
        }
    // Repopulate the 'day' DDL
    for (var i = 0; i < daysInMonth; i++) {
    DayCtrlID.options[i] = new Option(i+1,i+1);
        }
        
    // Set the selected day again
    DayCtrlID.options[dayselected - 1].selected = true;    
}

}

function YearChanged(YearCtrlID,DayCtrlID,MonthCtrlID) {
// debugger;
//Clear any error that may have been set
checkErrorDatePeriod(YearCtrlID);
var dayselected = DayCtrlID.value;

// Months are set up in DDL to be from 1 to 12 rather than from 0 to 11. This means
// that timeA is actually the first day of the following month. Subtract one day
// (86400000 milliseconds) to get actual month required and then get the number
// of days in that month.

timeA = new Date(YearCtrlID.value, MonthCtrlID.value,1);
timeDifference = timeA - 86400000;
timeB = new Date(timeDifference);
var daysInMonth = timeB.getDate();

// If the user has selected a day which doesn't exist for the month and year chosen, recreate the 
// 'day' DDL
if (dayselected > daysInMonth) 
{
    // Clear the 'day' DDL
    for (var i = 0; i < DayCtrlID.length; i++) {
    DayCtrlID.options[i] = null;
        }
    // Repopulate the 'day' DDL
    for (var i = 0; i < daysInMonth; i++) {
    DayCtrlID.options[i] = new Option(i+1,i+1);
        }
    // Set the day to the last day in the month
    DayCtrlID.options[daysInMonth - 1].selected = true;  
    dayselected = daysInMonth;   
}

// If the day DDL has been shortened (e.g. user switched from the last day in Jan to the last
// day in Feb), it may need to be increased if the user then switches back to a month
// with more days in it. 
if (DayCtrlID.length != daysInMonth)
{
    // Clear the 'day' DDL
    for (var i = 0; i < DayCtrlID.length; i++) {
    DayCtrlID.options[i] = null;
        }
    // Repopulate the 'day' DDL
    for (var i = 0; i < daysInMonth; i++) {
    DayCtrlID.options[i] = new Option(i+1,i+1);
        }
        
    // Set the selected day again
    DayCtrlID.options[dayselected - 1].selected = true;  
}
}

function onclickHistory() {
//debugger;
history.go(-1);
}

function onclickAlertConfirm(ProfileCtrlID) {
//debugger;
var profileName = ProfileCtrlID.href.substring(ProfileCtrlID.href.lastIndexOf("=")+1);
var answer = confirm("Are you sure you wish to initiate a new " + profileName + " profile? If you click on 'ok', a task will be created for your contribution; click on 'Refresh Panel' to make your profile visible in the 'My Profiles' panel.");
return answer;
}

