// JavaScript Document
window.onload = addHelp;

function addHelp()
{
  var strID, objHelp;

  // Check we're working with a DOM compliant browser
  if (document.getElementById && document.appendChild && document.removeChild)
  {
    if (document.getElementById('formhelp')) {
		var objHelpform = document.getElementById('formhelp');
		
		var objAnchors = objHelpform.getElementsByTagName('a');
		
		// Iterate through all anchors in the form
		for (var iCounter=0; iCounter<objAnchors.length; iCounter++)
		{
		  // Only process anchors that link to the help section
		  if (objAnchors[iCounter].className != 'leave')
		  {
			// Locate the associated help text's container,
			// and hide it
			strID = getIDFromHref(objAnchors[iCounter].href);
			objHelp = document.getElementById(strID);
			if (objHelp) {
			  objHelp.style.display = 'none';
			
			  // Add events to reveal/hide
			  objAnchors[iCounter].onclick = function(event){return expandHelp(this, event);}
			  objAnchors[iCounter].onkeypress = function(event){return expandHelp(this, event);}
			
			  // Move beneath current form field
			  objAnchors[iCounter].parentNode.appendChild(objHelp);
			}
		  }
		}
	}
    if(document.getElementById('helpcontainer')) {
		// Remove the remainder of the old help section
		var objOldnode = document.getElementById('helpcontainer');
		
		objOldnode.parentNode.removeChild(objOldnode);
	
		// Release memory to prevent IE memory leak
		// Thanks to Mark Wubben <http://novemberborn.net/>
		// for highlightint the issue
		objHelpform = null;
		objHelp = null;
		objAnchors = null;
	}
  }
}

// Return the ID of the element from the "href" attribute
function getIDFromHref(strHref)
{
  var iOffset = strHref.indexOf('#') + 1;
  var iEnd = strHref.length;

  return strHref.substring(iOffset, iEnd);
}

function expandHelp(objAnchor, objEvent)
{
  var iKeyCode;

  // If from the keyboard, check the user is
  // activating it rather than tabbing through
  if (objEvent && objEvent.type == 'keypress')
  {
    if (objEvent.keyCode)
      iKeyCode = objEvent.keyCode;
    else if (objEvent.which)
      iKeyCode = objEvent.which;
    
    if (iKeyCode != 13 && iKeyCode != 32)
      return true;
  }

  strID = getIDFromHref(objAnchor.href);
  objHelp = document.getElementById(strID);

  // Toggle on and off
  if (objHelp.style.display == 'none')
    objHelp.style.display = 'block';
  else
    objHelp.style.display = 'none';

  return false;
}