/*
	
	CRAcademy
	Javascripts
	
*/

	var usingIE = (document.all && document.getElementById);	// Flag to indicate use of IE

	// Scrolling variables
	var scrollContentID = 'stories_content';
	var scrollSpeed = 1;
	var scrollOffset = 20;
	
	var scrollInterval;			// The timeout for the next scroll event
	var scrolling = false;		// Flag to indicate whether or not scrolling is in progress
	var scrollContentHeight;	// The height of the content being scrolled - used to detect when the content has left the frame and needs reseting

	var contentNode;
	var contentCopy;
	var frameNode;
	var scrollTop = 0;

	// STOP SCROLL	
	function stopScroll(event)
	{
		//debug('stopScroll');
	
		clearInterval(scrollInterval);
		scrolling = false;
		
	// Prevent the event from bubbling up to parent element
		if(!event) var event = window.event;
		event.cancelBubble = true;							// IE
		if(event.stopPropagation) event.stopPropagation();	// W3C compliant
	// Prevent the event from being fired again
		if(event && event.returnValue) event.returnValue = null;
	}
	
	// START SCROLL
	function startScroll(event)
	{
		//debug('startScroll');
	
		if(!scrolling)
		{
			if(!contentNode || !contentCopy || !frameNode)
			{
				// Get the content node
				contentNode = document.getElementById(scrollContentID);
				frameNode = contentNode.parentNode;
				
				// Set up the inital top
				if(contentNode.style.marginTop == '')
					contentNode.style.marginTop = '0px';
				
				// Find the height of the content and the frame
				scrollContentHeight = contentNode.offsetHeight;
				var scrollFrameHeight = frameNode.offsetHeight;
				frameNode.style.height = scrollFrameHeight + 'px';
				
				frameNode.onmouseover = stopScroll;
				frameNode.onmouseout = startScroll;
				
				// Duplicate the content
				// This way when it scrolls off the top another copy appears straight away
				contentCopy = contentNode.cloneNode(true);
				contentCopy.id = scrollContentID+'_copy';
				
				if(!usingIE)
				{
					contentNode.style.border=  '1px solid white';
					contentCopy.style.border = '1px solid white';
				}
				
				frameNode.appendChild(contentCopy);
			}
			
			// Set the scrolling flag
			scrolling = true;
			
			// Start the recursive function
			scrollInterval = setInterval("scrollDown()",50);
		}
		
	// Prevent the event from bubbling up to parent element
		if(!event) var event = window.event;
		if(event)
		{
			event.cancelBubble = true;							// IE
			if(event.stopPropagation) event.stopPropagation();	// W3C compliant
			if(event.returnValue) event.returnValue = null;
		}
	}
	
	// SCROLL DOWN
	// Recursive scrolling function
	function scrollDown()
	{	
		//var top = parseInt(contentNode.style.marginTop);
		if(scrollTop < -scrollContentHeight)
		{
			////debug('Looping...', false);
			contentNode.id = scrollContentID+'_copy';
			contentCopy.id = scrollContentID;
			
			frameNode.removeChild(contentNode);
			frameNode.appendChild(contentNode);
			scrollTop += scrollContentHeight + scrollOffset;
			
			contentNode.style.marginTop = '0px';
			contentNode = contentCopy;
			contentCopy = document.getElementById(scrollContentID+'_copy');
		}
		scrollTop -= scrollSpeed;
		contentNode.style.marginTop = scrollTop + "px";
		
		////debug('scrollDown ('+contentNode.style.marginTop+', '+contentCopy.style.marginTop+')');
	}
	
	
	
	
	
	


/*
	VARIABLES
	- Timeout IDs and operations, to hide an L1 menu before the timeout fires simply eval() tabOperations[i] and then clearTimeout(tabTimeouts[i])
	- Browser flags
*/
	var tabTimeouts = new Array();		// Timeout IDs for L1 menu hiding
	var tabOperations = new Array();	// Timeout operations for L1 menu hiding
	var menuTimeouts = new Array();		// Timeout IDs for L2 menu hiding
	var menuOperations = new Array();	// Timeout operations for L2 menu hiding


/*
	HIDE A TAB
	- Sets the tabs className
	- Sets the classNames of the tab's children
	- Argument is the index of the desired tab in the childNodes array of #mainmenu
	- Exists for the benefit of Safari, which is rubbish
*/
	function hideTab(id)
	{
		//debug('hideTab');
	
	// Find the tab we want
		var node = document.getElementById(id);
	
	// If we can't find it, there's nothing we can do
		if(!node)
			return;
	
	// Set the classname of the tab we're hiding
		node.className = node.className.replace(' hover', '');
		
	// Set the classnames of the tab's children so they don't retain their
	// current state the next time the menu is displayed
		var children = node.getElementsByTagName('LI');
		for(var i = 0, child; child = children[i]; i++)
		{
			if(child.className == 'hover')
				child.className = '';
			else
				child.className = child.className.replace(' hover', '');
		}
	}


/*
	CLEAR TIMEOUTS
	- Manually fires any timeouts that haven't automatically run yet
	- Clears the timeouts so they don't run again later
*/
	function clearTimeouts()
	{
		//debug('clearTimeouts');
	
	// L2 and 3 menus
		for(var i = 0; i < menuOperations.length; i++)
		{
			if(menuOperations[i])
			{
				//eval(menuOperations[i]);
				document.getElementById(menuOperations[i]).className = 'parent';
				clearTimeout(menuTimeouts[i]);
				menuOperations[i] = null;
				menuTimeouts[i] = null;
			}
		}
	
	// L1 menus
		for(var i = 0; i < tabOperations.length; i++)
		{
			if(tabOperations[i])
			{
				//eval(tabOperations[i]);
				var node = document.getElementById(tabOperations[i]);
				node.className = (node.className == 'hover') ?
					node.className = '' :
					node.className = node.className.replace(' hover', '');
				
				clearTimeout(tabTimeouts[i]);
				tabOperations[i] = null;
				tabTimeouts[i] = null;
			}
		}
	}


/*
	GENERAL MOUSE OVER
	- Add ' hover' to the class name
*/
	function mouseOver(event)
	{
		//debug('mouseOver');
	
	// hide other visible menus and show this one
		clearTimeouts();
		this.className += ' hover';
		
	// Prevent the event from being fired again
		if(event && event.returnValue) event.returnValue = null;
	}


/*
	GENERAL MOUSE OUT
	- Remove 'hover' from the class name
*/	
	function mouseOut(event)
	{	
		//debug('mouseOut');
		
		var operation;
		if(this.className == 'parent hover')
		{
			var index = parseInt(this.id.substring(8));
			var operation = "document.getElementById('"+this.id+"').className = 'parent';";
			menuTimeouts[index] = setTimeout(operation, 500);
			menuOperations[index] = this.id;// operation;	
		}
		else if(this.className == 'hover')
			this.className = '';
		else
			this.className = this.className.replace(' hover', '');
			
	// Prevent the event from being fired again		
		if(event && event.returnValue) event.returnValue = null;
	}
	
	
/*
	GENERAL ON CLICK
	- Sets the window location to the URL of the first A child element of the sender
*/	
	function onClick(event)
	{
		//debug('onClick');
	
		var link = this.getElementsByTagName('A')[0];
		if(link)
			window.location = link.href;
	
	// Prevent the event from bubbling up to parent element and redirecting to the wrong page
		if(!event) var event = window.event;
		event.cancelBubble = true;							// IE
		if(event.stopPropagation) event.stopPropagation();	// W3C compliant
	}

	
/*
	MOUSE OVER LEVEL 1 TABS
	- Clears the timeout and hides any L1 menus that are already being displayed
	- Displays the menu that the mouse is over
*/
	function tabMouseOver(event)
	{	
		//debug('tabMouseOver');
	
	// Explicitly hide visible tabs
	// This is done for the sake of Safari, which won't hide the tabs just using the
	// clear timeouts mechanism when the mouse moves from an L3 menu to an L1 tab
		if(!usingIE)
		{
			var navRoot = document.getElementById('mainmenu');
			for(var i = 0, node; node = navRoot.childNodes[i]; i++)
			{
				if(node.tagName == 'LI' && node != this)
					hideTab(node.id);
			}
		}
	
	// Clear timeouts
		clearTimeouts();

	// Display the menu that the mouse if over
		this.className += ' hover';
		
	// Prevent the event from being fired again
		if(!event) var event = window.event;
		if(event)
		{
			event.cancelBubble = true;							// IE
			if(event.stopPropagation) event.stopPropagation();	// W3C compliant
			if(event.returnValue) event.returnValue = null;
		}
		//if(event && event.returnValue) event.returnValue = null;
	}

	
/*
	MOUSE OUT OF LEVEL 1 TABS
	- Builds an appropriate expression to hide the tab
	- Sets a half second timeout to execute the expression
*/
	function tabMouseOut(event)
	{
		//debug('tabMouseOut');
	// Find index of tab
		var index = parseInt(this.id.substring(8));
	
	// Build the expression to hide the menu later
		var operation = "document.getElementById('"+this.id+"').className";
		if(this.className == 'hover')
			operation = operation+" = '';";
		else
			operation = operation+" = "+operation+".replace(' hover', '');";
		
	// Set the timeout to hide the menu in half a seconds time
		tabTimeouts[index] = setTimeout(operation, 500);
		tabOperations[index] = this.id;
		
	// Prevent the event from being fired again
		if(event && event.returnValue) event.returnValue = null;
	}

	
/*
	MOUSE DOWN (primarily for register button)
	- Appends ' down' to the class name
*/
	function mouseDown()
	{
		//debug('mouseDown');
	
		this.className += ' down';
	}

	
/*
	MOUSE UP (primarily for register button)
	- Removed 'down' from the class name
*/
	function mouseUp()
	{
		//debug('mouseUp');
	
		if(this.className == 'down')
			this.className = '';
		else
			this.className = this.className.replace(' down', '');
	}


/*
	INIT TABS MENU
	- Set the mousein and mouseout functions of the LIs in the menu
*/	
	function initMenu()
	{
		//debug('initMenu');
	
	// Get the navigation root
		var navRoot = document.getElementById('mainmenu');

	// Set up item IDs
		var allItems = navRoot.getElementsByTagName('LI');
		for(var i = 0, item; item = allItems[i]; i++)
			item.id = 'MenuItem'+i;
		
	// Loop through children of mainmenu to set up L1 menus
		for(var i = 0, node; node = navRoot.childNodes[i]; i++)
		{
			//var node = navRoot.childNodes[i];
			if(node.tagName == 'LI')
			{
				node.onmouseover = tabMouseOver;
				node.onmouseout = tabMouseOut;
				
			// Set up submenus
				var subItems = node.getElementsByTagName('LI');
				for(var j = 0, subItem; subItem = subItems[j]; j++)
				{
					subItem.onmouseover = mouseOver;
					subItem.onmouseout = mouseOut;
					subItem.onclick = onClick;
				}
			}
		}
	}

/*
	INIT REGISTER BUTTON
	- Set the mouse in, out, up and down functions for the register button
*/	
	function initRegButton()
	{
		//debug('initRegButton');
		
		var regButton = document.getElementById('registerbutton');
		regButton.onmouseover = mouseOver;
		regButton.onmouseout = mouseOut;
		//regButton.onmousedown = mouseDown;
		//regButton.onmouseup = mouseUp;
	}


/*
	PRELOAD IMAGES
	- Preload the menu top and bottom images
	- Preload the register button mouse over and mouse down images
*/	
	function preloadImages()
	{
		//debug('preloadImages');
	
		var imageURLs = new Array();
		//imageURLs[ 0] = 'images/menu_bottom_pink_small.gif';
		//imageURLs[ 1] = 'images/menu_bottom_blue_small.gif';
		//imageURLs[ 2] = 'images/menu_bottom_green_small.gif';
		imageURLs[ 0] = 'images/register_button_hover.gif';
		
		var preload = new Array();
		for(i = 0; i < imageURLs.length; i++)
		{
			preload[i] = new Image();
			preload[i].src = imageURLs[i];
		}
	}


/*
	INIT LINKS
	- Finds all links with rel="external" and sets their target to _blank
	- This gets round the problem of target not being a valid XHTML attribute but still being a valid DOM attribute
*/
	function initLinks()
	{
		//debug('initLinks');
	
		var links = document.getElementsByTagName('A');
		for(var i = 0, link; link = links[i]; i++)
		{
			if(link.getAttribute('rel') == 'external')
				link.setAttribute('target', '_blank');
		}
	}

/*
	INITIALISATION
	- Run the init functions when the window loads
*/	
	window.onload = function()
	{
		initMenu();
		//initRegButton();
		initLinks();
		preloadImages();
		//startScroll();
	}


/*
	SEND TO FRIEND
	- Opens the "send to friend" window
*/
	function sendToFriend(rootUrl)
	{
		var url = window.location;
		var title = document.title;
		rootUrl = (!rootUrl) ? '' : rootUrl;
	
  		var width = 500;
  		var height = 550;
  		var left = (screen.width - width) / 2;
  		var top = (screen.height - height) / 2;
	
		window.open(rootUrl+'sendtofriend.php?url='+escape(url)+'&title='+escape(title), 'sendtofriend', 'status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=0,height='+height+',width='+width+',top='+top+',left='+left);
	}


/*
	DEBUGGING
	- Debug function for testing only
	- Logs to console in Safari (DISABLED)
	- Creates a div and outputs to that in other browsers
*/
	function debug(string, clear)
	{
		//if(window.console) 
		//	window.console.log(string);
		//else
		{
			var d = document.getElementById('debug');
			if(d && clear)
			{
				while(d.firstChild)
					d.removeChild(d.firstChild);
			}
			if(!d)
			{
				d = document.createElement('DIV');
				d.id = 'debug';
				d.style.background = 'white';
				d.style.border = '1px solid black';
				document.getElementsByTagName('BODY')[0].appendChild(d);
			}
			d.insertBefore(document.createTextNode(string), d.firstChild);
			if(!clear) d.insertBefore(document.createElement('BR'), d.firstChild);
		}
	}