/************************************************************/
/* Transmogrifier script (C)2004 Patrick H. Lauke aka redux */
/* Inspiration and challenge provided by Marcello Cerruti   */
/************************************************************/

/* addEvent handler for IE and other browsers */
function addEvent(elm, evType, fn, useCapture)
// addEvent and removeEvent
// cross-browser event handling for IE5+,  NS6 and Mozilla
// By Scott Andrew
{
 if (elm.addEventListener){
   elm.addEventListener(evType, fn, useCapture);
   return true;
 } else if (elm.attachEvent){
   var r = elm.attachEvent("on"+evType, fn);
   return r;
 }
} 

/* this is the main function...it wraps every span with the right class with the javascript link */
function transmogrify() {
	/* get all span elements */
	elements = document.getElementsByTagName('span');
	/* loop through the array of elements */
	n_elements = elements.length;
	for (i = 0; i < n_elements; i++) {
		/* if the span is of class="menureplace" */
		if (elements[i].className=='menureplace') {
			/* get the span's parent */
			var elementParent = elements[i].parentNode;
			/* get the span's next sibling (must be the submenu/UL) */
			var elementSubmenu = elementParent.getElementsByTagName('ul');
			/* clone the span and all its children (i.e. any content in the span)*/
			var elementCloned = elements[i].cloneNode('TRUE');
			/* create a new unlinked A element */
			var newLink = document.createElement("A");
			/* assign an href attribute to the new A element
			this assumes that javascript-enabled browsers also handle javascript: URLs
			wanted to use addEvent here as well, and have a # as href, but can't add a
			 return false...so the activation of the menu would jump back to start... */
			newLink.href="javascript:trigger('"+elementSubmenu[0].id+"')";
			/* assign a new id to the new A element */
			newLink.id="switcher"+elementSubmenu[0].id;
			/* add the cloned span as a child of the new link */
			newLink.appendChild(elementCloned);
			/* give the new link some style, baby */
			newLink.className='menureplacecollapsed';
			/* replace the original span with the newly create A element (which has the span's clone as child) */
			elementParent.replaceChild(newLink,elements[i]);
			elementSubmenu[0].style.display='none';
		}
	}
}

function trigger(targetSubmenu) {
	var target = document.getElementById('switcher'+targetSubmenu);
	var targetSubmenu = document.getElementById(targetSubmenu);
	if (target.className=='menureplacecollapsed') {
		target.className='menureplaceexpanded';
		targetSubmenu.style.display='block';
	} else {
		target.className='menureplacecollapsed';
		targetSubmenu.style.display='none';
	}	
}

/* let's add the transmogrify function to the onload handler of the page */
addEvent (window,'load',transmogrify)