//The i Group, DHTML API.
//Alex Gray, Moonshine Communications (alex@moonshinecorp.com) Feb 2004
/////////////////////////////////////////////////////////////////////

function loadComplete(){window.status = "";}
function hideLoadingScreen()
{
	//window.status = "loading...";
	if (getEl("loadingDiv")) document.body.removeChild(getEl("loadingDiv"))
	xHide(getEl("loadingDiv"));
}
function initPage()
{
	if (browserTestPassed == false)
	{
		return false;
	}
	//Set up the panning image
	initPan();
	//Start the preload function (again)
	//imagePreload();
	//To show the page before the load
	hideLoadingScreen();
	
	// Since we only just opened, reset the array
	openWindowsReset();
	
	//get the details for URL Linking: Functionality lets igroup send out links like:
	// www.theigroup.com.au/index.html?i=spies ... which will scroll over and open
	URL_link = queryString("i")

	if (URL_link == "spies")
	{
		scrollToItem(ispies, 2150, 80);
		openContent('ispies_cooler');
	}
}
//---------------------------------------------------------------------------

// The openWindows array holds all open layers. We should reset this every now and then, just to keep it clean
function openWindowsReset() {
 openWindows = new Array();
 openWindows[0] = ''
}
// Function to show a new (sub-)menu
function openWin(arr, parent) {

eventObj = (window.event)?window.event:window.Event;
	// What level is this menu?
	level = arr[0][3];
	// Close all existing child menus
	closeAll(level);
	// Stop the main image from scrolling whilst there are open menus
	scrollFreeze = true;
	// First, we copy a new element from the existing template
    wT = getEl('menuTemplate').cloneNode(true); 
	wT.id = "menuWin_"+ lastCursorX//+ eval(arr);

	///Get the menu elements - 
	headerTR = wT.getElementsByTagName("tr")[1]
	titleIMG = headerTR.getElementsByTagName("img")[1]
	menuSpacerIMG = wT.getElementsByTagName("img")[1]
	menuContentTR = wT.getElementsByTagName("tr")[3]
	menuTD = menuContentTR.getElementsByTagName("td")[0]

	// By default, it's just blank
	titleIMG.src = siteRoot + 'images/blank.gif';

	// If this is a sub level-menu, remove header
	if (level > 1) {
		xHide(headerTR)
		headerTR.style.display = 'none';
	}
	else if (level == 1)
	{
		titleIMG.src = siteRoot + 'images/titles/' + arr[0][2];
	}

	// Create a new table to contain the menu-items, and set its' attributes

	menuTD.className = 'MenuItemsCell';
	if (level > 1) menuTD.className = 'subMenuItemsCell';

	for (i=1; i<arr.length; i++) {
		
		// Create the menu item link
		menuLink = document.createElement('a');
		menuLink.className = 'menuItem';

		//Get rid of the bottom border if its the last menu-item
		if (i == arr.length-1 && level >1) menuLink.style.borderBottom = "0px solid #FFFFFF"

		
		//Create the Icon Image
		linkIconElement = document.createElement('img');
		linkIconElement.border = 0
		linkIconElement.className = 'linkIcon'
		linkIconElement.src = siteRoot + "images/blank.gif";
		linkIconSrc = ""
		
		// If the new menu-item leads to a submenu, we have to set the mouseover effects
		if (arr[i][2].indexOf('menu') >= 0) {
			menuLink.id = arr[i][1];
			menuLink.href = 'javascript:openWin('+arr[i][1]+')';
			xAddEventListener(menuLink, 'mousemove', mouseOverMenu, false)	
		}
		else if (arr[i][2] == 'external') {
			menuLink.href = 'http://' + arr[i][1];
			menuLink.target = '_blank';
		}
		else if (arr[i][2] == 'internal') {
			menuLink.href = arr[i][1];
			linkIconSrc = siteRoot + "images/icons/paper.gif"
		}
		else if (arr[i][2] == 'attachment') {
			menuLink.href = siteRoot + arr[i][1];
			menuLink.target = '_blank';
			linkIconSrc = siteRoot + "images/icons/pdf_small.gif"
		}
		// If it's a content-link, make it point to the content-function, passing it the new array
		else if (arr[i][2] == 'content') {
			menuLink.href = 'javascript:openContent(\''+arr[i][1]+'\')';
			linkIconSrc = siteRoot + "images/icons/paper.gif"
		}
		else if (arr[i][2] == 'video') {
		
			menuLink.href = 'javascript:openContent(\''+arr[i][1]+'\')';
			linkIconSrc = siteRoot + "images/icons/camera.gif"
		}
		
		//Hack for Opera
		
		// set the source for the icon
		linkIconElement.src = linkIconSrc
		// Add Icon Image to menu 
		if (linkIconSrc != "") menuLink.appendChild(linkIconElement.cloneNode(true))
		//Add the text to the link
		menuLink.appendChild(document.createTextNode(arr[i][0])); 
		
		//The Max-widths are borked in Opera.. (or is it Safari that wrong? either way, all other browsers are OK witout it...)
		//And I couldn't find the JS property for max-width?? I am not proud of this hack BTW..
		if (window.opera) menuLink.className = "menuItemOpera"
	
		// Finally, we can add the link
		menuTD.appendChild(menuLink); 
	}
	
	// Some annoying bug kept ruining our template, so we have to set the width of a spacer-image	
	menuSpacerIMG.style.width = MENU_WIDTH-20;

	// Set the source for the title-image, if it is present in the array
	linkIconElement.src = siteRoot + "images/blank.gif"

	// We add all known information to the array of open windows
	// I don't quite understand why, but when I just put oW.length as array number, it messes up?
	openWindowPos = openWindows.length;
	openWindows[openWindowPos] = new Array()
	openWindows[openWindowPos][0] = wT
	openWindows[openWindowPos][1] = arr[0][0]
	openWindows[openWindowPos][2] = parent
	openWindows[openWindowPos][3] = level

	// Positioning
	// If this is a first level menu-item, it needs to be positioned next to the mouse
	if (level == 1) {
	//check if the function call has more x/y coord arguments
		if (openWin.arguments.length > 3)
		{
			xpos_tmp = determineXwin()/2;
			ypos_tmp = screenOffsetY + openWin.arguments[3];
			
			//Mozilla Hack: since I cant find the width of the viewable document, use SCREEN WIDTH
			if (window.screen.availWidth/2 < determineXwin()/2) xpos_tmp = (window.screen.availWidth/2)  - (wT.offsetWidth/2);
		}
		else
		{
			xpos_tmp = lastCursorX;
			ypos_tmp = lastCursorY;
		}
	}

	// Else, we're gonna check out where the parent element is
	else if (parent) {
		parObj = parent
		// We add 8 to the left to cater for the border-lines
		xpos_tmp = parObj.offsetWidth + 4
		// Take it up 25 pixes for the header-bit
		ypos_tmp = - 12;
		
		if (parObj.offsetParent) {
			// Find out where exactly the parent element is on the page
			while (parObj.offsetParent) {

				ypos_tmp += parObj.offsetTop
				xpos_tmp += parObj.offsetLeft
				parObj = parObj.offsetParent;
			}
		}
		//all browsers seem to have a 3px gap... (probably CSS fix, but this is easier)
		xpos_tmp = xpos_tmp-4
	}
	

	
	wT.style.left = xpos_tmp+"px";
	wT.style.top = ypos_tmp+"px";
	// We add this new layer to the body.
	document.body.appendChild(wT);
	// Alright then... show it to the world!
	xShow(wT)

}


// Function to show sub-menu when mousing over a menu-item calling a submenu
function mouseOverMenu(event) {
if (!event) event = window.event;
if (t) clearTimeout(t)

	// Get the element which called this function (should be the 'close' image)
	origSrcElement = (event.target) ? event.target : event.srcElement;
	currEl = origSrcElement

	// Loop through its' parent elements until you find a div-element. This should be the layer itself
	while (currEl.parentElement) {
		if (currEl.tagName.toLowerCase() == 'div') {
			break;
		}
		currEl = currEl.parentElement;
	}

	if (openWindows[openWindows.length-1][0] == currEl) {
		if (t) clearTimeout(t)
	}

	// Do the next part only if the the item actually is a menuitem (if it has a childmenu)
	if (origSrcElement.id) {
		// Open the submenu, by calling openWin, passing it the submenu-array and what element called it (for positioning)
		openWin(eval(origSrcElement.id), origSrcElement);
		// Keep the 'source' menu-item highlighted
		origSrcElement.style.backgroundColor = "#333300";
	}
}

// Called by the mouseout event on the menu-item pointing to a submenu
function mouseOutMenu(event) {
if (!event) event = window.event
	// Get the element which called this function (should be the 'close' image)
	origSrcElement = (event.target) ? event.target : event.srcElement
	currEl = origSrcElement
	// Loop through its' parent elements until you find a div-element. This should be the layer itself
	while (currEl.parentElement) {
		if (currEl.tagName.toLowerCase() == 'div') {
			break;
		}
		currEl = currEl.parentElement;
	}
	for (i=0; i<openWindows.length; i++) {
		if (openWindows[i][0] == currEl) {
		//needs to wait a little, otherwise you cant get to the submenu
			t = setTimeout('closeAll(openWindows['+i+'][3] + 1)', 50)
			//closeAll(openWindows[i][3] + 1)
		}
	}
}

// Function to open a content window. Since its' beahviour is so different from the menu, it was easier to create a seperate function
function openContent(srcDiv) {
if (srcDiv ==  ""){alert('no content found!');return false}
	// Again, stop the main image from scrolling, just to make sure (it should've been stopped already)
	scrollFreeze = true;

	// Get the div which is passed along
	srcDiv = getEl(srcDiv);
	if (!srcDiv)alert("Content layer not found")
	// Get the content template (no need to clone since we only want one window at a time (?))
    cT = getEl('contentTemplate')
	
	//Remove the content, if any	
	if (getEl('contentCell').childNodes.length > 0) getEl('contentCell').removeChild(getEl('contentCell').firstChild)
	
	// Add a div to the content-cell, and stick the content in there (for scrolling purposes et al)
	contentDiv = srcDiv.cloneNode(true)
	contentDiv.className = 'contentText';

	// Add the new div to the contentcell
	getEl('contentCell').appendChild(contentDiv);

	// Set the same spacer as in the menu to prevent the corners from going haywire
	getEl('ContentSpacer').width = srcDiv.width - 46;

	// If there is a title-image... Go on... set it
	if (srcDiv.img != '') getEl('contentTitleImg').src = siteRoot + srcDiv.getAttribute('img');
	
	// Set the width based on the width as specified in the contentDoc
	cT.style.width = srcDiv.style.width;
	cT.style.height = srcDiv.style.height;
		
	// Add it to the body
	document.body.appendChild(cT);
	// Set the position based on the window-size (position it in middle). This has to be done after it's been _
	//     added to the body, otherwise it doesn't know the width or height for some odd reason (go figure!)
	contentWinTop = (determineYwin() != 0)?(determineYwin() / 2) - (cT.offsetHeight / 2):(cT.offsetHeight / 2);
	//if the top has somehow equated to less than 0, then set it to nill - Damn you Safari
	contentWinTop = (contentWinTop < 0)?0:contentWinTop;
	contentWinLeft = (determineXwin()  / 2) - (cT.offsetWidth / 2);
	//Mozilla Hack: since I cant find the (real) width of the viewable document (moz returns the width of the doc including the stuff out of view (which is actually what the other browsers _should_ return)), use SCREEN WIDTH instead..
	if (window.screen.availWidth/2 < determineXwin()/2) contentWinLeft = (window.screen.availWidth/2) - (cT.offsetWidth/2);
	//Another offset... Safari & Mozilla (both have gecko in UA str) underreports availWidth, especially Safari on Mac)
	if (findUAStr("gecko") > 0) 
	{
		contentWinTop = contentWinTop-60;
		contentWinLeft = contentWinLeft-30;
	}
	
	
	
	


	
	//top-position the content-window
	cT.style.top = contentWinTop+"px";
	//left-position the content-window
	cT.style.left = contentWinLeft+"px";
	
	// Let's make it visible to the audience
	xShow(cT);
}


// Function to show the description belonging to an item on the main image
function openDesc(arr) {
	// There should be only one description at a time. So no need to be cloning etc.

	// Get the description layer
	gT = getEl('descTemplate')
	gT.style.position="absolute"
	//gT.style.display="none"
	// Set the title-image
	getEl('descTitleImg').src = siteRoot + 'images/blank.gif'
	getEl('descTitleImg').src = siteRoot + 'images/titles/'+arr[0][2].toLowerCase();

	// Get the last known mouse position to position the layer
	gT.style.left = (lastCursorX+15) + "px"
	gT.style.top = (lastCursorY-15) + "px"

	// Make it visible
	xShow(gT)
}

// Function to hide the description layer
function closeDesc() {
	xHide(getEl('descTemplate'))
}


// Function to close all (sub-)menus
// The from variable is used for example if you're in the second level, showing a third level, and _
//     moving to another third level. Then all layers from (and including) level 3 should be closed
function closeAll(from) {
scrollFreeze = false

if (!from || from.srcElement || from.target) from = 1;
// Loop though all items in openWindows array higher than 'from'.
	while (openWindows.length > from) {
			// remove the highlighting from the originating menuitem
			if (openWindows[openWindows.length-1][2]) openWindows[openWindows.length-1][2].style.backgroundColor = "#61bab8";
			openWindows[openWindows.length-1][0].style.display = "none";
			document.body.removeChild(openWindows.pop()[0]);
	}
		
}

//scrollToItem(itemArr, posX): used to scroll the page to a given X-coord and opens top level menu
function scrollToItem(itemArr, posX, posY)
{
	closeAll(1)
	scrollfreeze = true
	defaulttravel = 20
	
	//This 'windowResOffset' is used for take into account window size and resolution..
	//It's some kind of magic number I came up with.. 
	// The ScrollTo is off in Mozilla and could do with some more tweaking
	windowResOffset = parseInt((580000 / determineXwin())-280)
	posX = posX  + windowResOffset

	if (posX > panImgWidth)
	{
		posX = posX-panImgWidth
	}
	else if (posX < 0)
	{
		posX = posX+panImgWidth
	}
	panLoc = xLeft(panObject)*(-1)
	//window.status = "panLoc:"+panLoc+" -- posX:"+posX
	xx = 0
	//Keep going until the page is in a 20px range of where it should be.. 
	//Cant be exact as the 'defaulttravel' is more than 1
	while (panLoc < posX-10 || panLoc > posX+10 ) {
	//try to figure out which direction to go.. can be imnproved
		if(panLoc < posX)
		{
			move_E()
		}
		else
		{
			move_W()
		}
		panLoc = xLeft(panObject)*(-1)
		xx +=1
		//Emergency exit!
		if(xx > 1000) break;
	}
	stopmoving()
	//Open and close the description window, to make sure title image is there (?)
	openDesc(itemArr)
	closeDesc()
	//Open the menu
	openWin(itemArr, "", posX, posY)
}

//Make sure the page doesn't scroll when the user is hovering the topnav
function topNavMouseMove(event)
{
if (!event) event = window.event;
if (!event) event = window.Event;
	event.cancelBubble = true;
	stopmoving();
}