// This file provides the scripting for the menu button animations of www.Bit-Kit.com.
// The code includes startup layout, startup appearance, button generation and menu animation.
//
// Code written by Peder Ydalus (peder@bit-kit.com)

// Create the menus dynamically and set their positions
var topMenuItems = new Array("Home", "Products", "Technologies", "Affiliates", "Contact");
var topMenuItemsWidth = new Array(129, 156, 193, 154, 150);
var topMenuItemsXStart = 110;
var topMenuItemsYPos = "50px";
var topMenuItemsFarLeft = "-200px";

var subMenuItemsXStart = topMenuItemsXStart;
var subMenuItemsYPos = "94px";
var subMenuItemsFarLeft = "-255px";

// The items are the items displayed as menus.
// The names are needed since the items are created and named dynamically, and frankly it seemed 
// overkill to remove whitespace with a regexp programatically and dynamically.
var homeMenuItems      = new Array("Recent Work", "Environmental Awareness");
var homeMenuItemsNames = new Array("RecentWork", "EnvironmentalAwareness");

var productMenuItems      = new Array("Switch", "TranSupport", "Interactive AI Robots", "WinDock", "Custom");
var productMenuItemsNames = new Array("Switch", "TranSupport", "InteractiveAIRobots", "WinDock", "Custom");

var technologyMenuItems      = new Array(".Net", "Web", "Artificial Intelligence", "Design", "3D Animation", "Other");
var technologyMenuItemsNames = new Array("DotNet", "Web", "ArtificialIntelligence", "Design", "ThreeDAnimation", "Other");


// DIV on/off specific variables: TODO: CHANGE TO FLASH DIV
var currentShownDIVName = "div" + topMenuItems[0].toString();
var currentShownDIV;
// SPAN on/off specific variables for the submenus. Similar to DIV above
var currentShownHomePane;
var currentShownHomePaneName    = "HomePane";
var currentShownProductPane;
var currentShownProductPaneName    = "ProductsPane";
var currentShownTechnologyPane;
var currentShownTechnologyPaneName = "TechnologyPane";

// Animation-specific variables:
var numAnimSteps = 20; 					// The number of steps the animation will use
var timeoutTime = 10;					// The number of milliseconds the timeout is set to
var currSelectedSubMenuNames = "none";	// The submenu array - or "none"
var currSelectedSubMenuWidth = "none";
var lastSelectedSubMenuNames = "none";	// The submenu array - or "none"
var lastSelectedSubMenuWidth = "none";

var isFirefox = (navigator.userAgent.indexOf("Firefox") >= 0);

// ---------------------------------------------------------------------
// Create the topmost main menu: 
// ---------------------------------------------------------------------

var topMenuItemXPos = topMenuItemsXStart + "px";

for (var i = 0; i < topMenuItems.length; i++) {
	// Some notes on positioning:
	// position.absolute refers to coordinates of the containing element, whereas position.fixed refers to the browser
	// window and will not scroll with the rest of the contents. However, fixed positioning is not supported in 
	// fourth-generation browsers or IE5 or IE6, and should thus be avoided or provide browser-specific code.

	var menuItemText = topMenuItems[i].toString();

	var tagType = "div";
	var tagTypeClass = " class=\"topMainMenu\"";
	var tagTypeStyle = " style=\"left: " + topMenuItemXPos + "; top: " + topMenuItemsYPos + ";\"";
	var tagNameAndId = " name=" + menuItemText + " id=" + menuItemText;

	// Calculate the NEXT x position based on the current + the width of the current:
	topMenuItemXPos = (parseInt(topMenuItemXPos) + topMenuItemsWidth[i]) + "px";

	document.write("<" + tagType + tagTypeClass + tagTypeStyle + tagNameAndId + ">" + 
		"<h1>" + menuItemText + "</h1>" + 
		"<IMG src = \"./images/topMenu2_right.gif\">" +
		"</" + tagType + ">");
}


// **********************************************************************
// *              Create the submenus:                                  *
// **********************************************************************

function createSubmenu(subMenuItems, subMenuItemsNames) {
	var subMenuItemXPos = subMenuItemsFarLeft; 
	for (var i = 0; i < subMenuItems.length; i++) {
		var menuItemText = subMenuItems[i].toString();
		var menuItemName = subMenuItemsNames[i].toString();
		var tagType = "div";
		var tagTypeClass = " class=\"subMenu\"";
		var tagTypeStyle = " style=\"left: " + subMenuItemXPos + "; top: " + subMenuItemsYPos + ";\"";
		var tagNameAndId = " name=" + menuItemName + " id=" + menuItemName;

		// The NEXT x position is calculated based on the current x + the width of the current:
		// Embed the text-part in a h2 tag, and then relative-adjust this and add padding in the CSS to make it the same height as the rest of the menu item
		document.write("<" + tagType + tagTypeClass + tagTypeStyle + tagNameAndId + ">" + 
			"<h2>" + menuItemText + "</" + "h2>" + 
			"<IMG src = \"./images/subMenu4_right.gif\">" +
			"</" + tagType + ">");
	}
}

// ----------------------------
// Create the home submenu:
// ----------------------------
createSubmenu(homeMenuItems, homeMenuItemsNames);

// ----------------------------
// Create the products submenu:
// ----------------------------
createSubmenu(productMenuItems, productMenuItemsNames);

// ------------------------------
// Create the technology submenu:
// ------------------------------
createSubmenu(technologyMenuItems, technologyMenuItemsNames);

// ------------------------------
// Create the submenu animations:
// ------------------------------

var animInIntervalId      = 0;
var animInStepsCompleted  = 0;
var animOutIntervalId     = 0;
var animOutStepsCompleted = 0;
var subMenuItemsIn  = new Array(); // The DOM-nodes, collected by their id's
var subMenuItemsOut = new Array(); // Need to separate these as two animations (in/out) can happen at once

function removeCurrentSubmenu() {
	// Set up the variables needed, then initialize the setInterval-function

	subMenuItemsOut = new Array();		
	var subMenuStepSize = new Array(); 	// The stepsize the individual nodes will be moved to the left each tick

	for (var i = 0; i < currSelectedSubMenuNames.length; i++) {
		subMenuItemsOut[i] = document.getElementById(currSelectedSubMenuNames[i]);
		subMenuStepSize[i] = (parseInt(subMenuItemsOut[i].style.left) - parseInt(subMenuItemsFarLeft)) / numAnimSteps;
	}
	animOutIntervalId = setInterval("removeCurrentSubmenuAnimation(" + subMenuStepSize + ")", timeoutTime);
}

function removeCurrentSubmenuAnimation() {
	// Animates the removal of the submenu items. The passed array is collected in the arguments-array
	if (animOutStepsCompleted >= numAnimSteps) {
		// The animation is completed. Reset the variables, clear the interval and return.
		clearInterval(animOutIntervalId);
		animOutIntervalId = 0;
		animOutStepsCompleted = 0;
		for (var i = 0; i < subMenuItemsOut.length; i++) {
			// Reset the positions to far left
			subMenuItemsOut[i].style.left = subMenuItemsFarLeft;
		}
	}
	else {
		// Move the manu items to the left with their respective amount
		for (var i = 0; i < subMenuItemsOut.length; i++) {
			subMenuItemsOut[i].style.left = (parseInt(subMenuItemsOut[i].style.left) - arguments[i]) + "px";
		}
		animOutStepsCompleted++;
	}
}

function showCurrentSubMenu() {
	// Set up the variables needed, then initialize the setInterval-function

	subMenuItemsIn = new Array();			
	var subMenuStepSize = new Array();		// The stepsize the individual nodes will be moved to the right each tick
	var itemEndPos = subMenuItemsXStart;	// Item final position, calculated by adding the widths for each looping

	for (var i = 0; i < currSelectedSubMenuNames.length; i++) {
		subMenuItemsIn[i] = document.getElementById(currSelectedSubMenuNames[i]);
		subMenuStepSize[i] = (itemEndPos - parseInt(subMenuItemsFarLeft)) / numAnimSteps;
		itemEndPos += subMenuItemsIn[i].offsetWidth;//currSelectedSubMenuWidth[i];
	}
	animInIntervalId = setInterval("showCurrentSubmenuAnimation(" + subMenuStepSize + ")", timeoutTime);
}

function showCurrentSubmenuAnimation() {
	// Animates the introduction of the submenu items. The passed array is collected in the arguments-array
	if (animInStepsCompleted >= numAnimSteps) {
		// The animation is completed. Reset the variables, clear the interval and return.
		clearInterval(animInIntervalId);
		animInIntervalId = 0;
		animInStepsCompleted = 0;
		 
		var finalXPos = subMenuItemsXStart;
		for (var i = 0; i < subMenuItemsIn.length; i++) {
			// Adjust the positions to the correct ones due to possible decimal errors
			subMenuItemsIn[i].style.left = finalXPos.toString() + "px";
			finalXPos += subMenuItemsIn[i].offsetWidth;//currSelectedSubMenuWidth[i];
		}
	}
	else {
		for (var i = 0; i < subMenuItemsIn.length; i++) {
			subMenuItemsIn[i].style.left = (parseInt(subMenuItemsIn[i].style.left) + arguments[i]) + "px";
		}
		animInStepsCompleted++;
	}
}


// *******************************************************************************************
// *              Set the event handlers for the "buttons" (menus and submenus):             *
// *******************************************************************************************

var homeButton = document.getElementById("Home");
homeButton.onmousedown = function() { homeOnMouseDown(); };

   var recentWorkButton = document.getElementById("RecentWork");
	recentWorkButton.onmousedown = function() { subMenuOnMouseDown(recentWorkButton); };

	var environmentalAwarenessButton = document.getElementById("EnvironmentalAwareness");
	environmentalAwarenessButton.onmousedown = function() { subMenuOnMouseDown(environmentalAwarenessButton); };

var productsButton = document.getElementById("Products");
productsButton.onmousedown = function() {productsOnMouseDown()};

   var switchButton = document.getElementById("Switch");
	switchButton.onmousedown = function() { subMenuOnMouseDown(switchButton); };

   var tranSupportButton = document.getElementById("TranSupport");
	tranSupportButton.onmousedown = function() { subMenuOnMouseDown(tranSupportButton); };

   var interactiveAIRobotsButton = document.getElementById("InteractiveAIRobots");
	interactiveAIRobotsButton.onmousedown = function() { subMenuOnMouseDown(interactiveAIRobotsButton); };

   var winDockButton = document.getElementById("WinDock");
	winDockButton.onmousedown = function() { subMenuOnMouseDown(winDockButton); };

   var customButton = document.getElementById("Custom");
	customButton.onmousedown = function() { subMenuOnMouseDown(customButton); };

var technologiesButton = document.getElementById("Technologies");
technologiesButton.onmousedown = function() {technologyOnMouseDown()};

   var dotNetButton = document.getElementById("DotNet");
	dotNetButton.onmousedown = function() { subMenuOnMouseDown(dotNetButton); };

   var webButton = document.getElementById("Web");
	webButton.onmousedown = function() { subMenuOnMouseDown(webButton); };

   var AIButton = document.getElementById("ArtificialIntelligence");
	AIButton.onmousedown = function() { subMenuOnMouseDown(AIButton); };

   var designButton = document.getElementById("Design");
	designButton.onmousedown = function() { subMenuOnMouseDown(designButton); };

   var ThreeDAnimationButton = document.getElementById("ThreeDAnimation");
	ThreeDAnimationButton.onmousedown = function() { subMenuOnMouseDown(ThreeDAnimationButton); };

   var otherButton = document.getElementById("Other");
	otherButton.onmousedown = function() { subMenuOnMouseDown(otherButton); };

var affiliatesButton = document.getElementById("Affiliates");
affiliatesButton.onmousedown = function() { mainMenuOnMouseDown("divAffiliates"); };

var contactButton = document.getElementById("Contact");
contactButton.onmousedown = function() { mainMenuOnMouseDown("divContact"); };


// Attempt to create a onMouseEnter-effect, but this fails as it seems onmouseout() is called
// before onmousemove(), so we get a final call to onmousemove and this must thus be taken care of properly
//technologiesButton.onmousemove = onmouseenter;
//technologiesButton.onmouseout  = onmouseout;


// **********************************************************************
// *              Event Handlers:                                       *
// **********************************************************************

function mainMenuOnMouseDown(divName) {
	// Generic function for menu items Home, Affiliates and Contact. Products and Technologies are special cases because of the submenus.

	// First, remove the current submenu if it's displayed
	if (currSelectedSubMenuNames != "none") removeCurrentSubmenu();

	// Then clear the submenu variables since the mainmenu submenu is empty
	lastSelectedSubMenuNames = "none";
	currSelectedSubMenuNames = "none";
	currSelectedSubMenuWidth = "none";


	// Hide the old DIV and show the new one
	currentShownDIV = document.getElementById(currentShownDIVName);
	currentShownDIV.style.display="none";
	currentShownDIVName = divName;
	currentShownDIV = document.getElementById(currentShownDIVName);
	currentShownDIV.style.display="block";
}

function homeOnMouseDown() {

	// Handle the submenu slide in/out or do nothing about it if the right submenu is displayed:
	if (currSelectedSubMenuNames != homeMenuItemsNames) {

		// First, remove the current submenu if it's displayed
		if (currSelectedSubMenuNames != "none") removeCurrentSubmenu();

		// Then animate sliding in the products submenu by using a setInterval-function
		lastSelectedSubMenuNames = currSelectedSubMenuNames;
		currSelectedSubMenuNames = homeMenuItemsNames;
		//currSelectedSubMenuWidth = productMenuItemsWidth;
		if (lastSelectedSubMenuNames == "none")
			showCurrentSubMenu(); 																// No previous submenu, start at once
		else
			setTimeout("showCurrentSubMenu()", numAnimSteps * timeoutTime + 50); // Adding a little buffer of 50ms

		// Hide the old DIV and show the new one
		currentShownDIV = document.getElementById(currentShownDIVName);
		currentShownDIV.style.display="none";
		currentShownDIVName = "divHome";
		currentShownDIV = document.getElementById(currentShownDIVName);
		currentShownDIV.style.display="block";
	}
	else {
		// The user has pressed the technology button whilst in the technology category. Show the main technology page:
		showCurrentHomePane("HomePane");
	}
}
	
function showCurrentHomePane(paneName) {
	currentShownHomePane = document.getElementById(currentShownHomePaneName);
	currentShownHomePane.style.display = "none"; 

	currentShownHomePaneName = paneName;
	currentShownHomePane = document.getElementById(currentShownHomePaneName);
	currentShownHomePane.style.display = "inline"; 

}

function productsOnMouseDown() {

	// Handle the submenu slide in/out or do nothing about it if the right submenu is displayed:
	if (currSelectedSubMenuNames != productMenuItemsNames) {

		// First, remove the current submenu if it's displayed
		if (currSelectedSubMenuNames != "none") removeCurrentSubmenu();

		// Then animate sliding in the products submenu by using a setInterval-function
		lastSelectedSubMenuNames = currSelectedSubMenuNames;
		currSelectedSubMenuNames = productMenuItemsNames;
		//currSelectedSubMenuWidth = productMenuItemsWidth;
		if (lastSelectedSubMenuNames == "none")
			showCurrentSubMenu(); 																// No previous submenu, start at once
		else
			setTimeout("showCurrentSubMenu()", numAnimSteps * timeoutTime + 50); // Adding a little buffer of 50ms

		// Hide the old DIV and show the new one
		currentShownDIV = document.getElementById(currentShownDIVName);
		currentShownDIV.style.display="none";
		currentShownDIVName = "divProducts";
		currentShownDIV = document.getElementById(currentShownDIVName);
		currentShownDIV.style.display="block";
	}
	else {
		// The user has pressed the technology button whilst in the technology category. Show the main technology page:
		showCurrentProductPane("ProductsPane");
	}
}
	
function showCurrentProductPane(paneName) {
	currentShownProductPane = document.getElementById(currentShownProductPaneName);
	currentShownProductPane.style.display = "none"; 

	currentShownProductPaneName = paneName;
	currentShownProductPane = document.getElementById(currentShownProductPaneName);
	currentShownProductPane.style.display = "inline"; 

}

function technologyOnMouseDown() {

	if (currSelectedSubMenuNames != technologyMenuItemsNames) {

		// First, remove the current submenu if it's displayed
		if (currSelectedSubMenuNames != "none") removeCurrentSubmenu();

		// Then animate sliding in the products submenu by using a setInterval-function
		lastSelectedSubMenuNames = currSelectedSubMenuNames;
		currSelectedSubMenuNames = technologyMenuItemsNames;
		//currSelectedSubMenuWidth = technologyMenuItemsWidth;
		if (lastSelectedSubMenuNames == "none")
			showCurrentSubMenu(); 																// No previous submenu, start at once
		else
			setTimeout("showCurrentSubMenu()", numAnimSteps * timeoutTime + 50); // Adding a little buffer of 50ms

		// Hide the old DIV and show the new one
		currentShownDIV = document.getElementById(currentShownDIVName);
		currentShownDIV.style.display="none";
		currentShownDIVName = "divTechnologies";
		currentShownDIV = document.getElementById(currentShownDIVName);
		currentShownDIV.style.display="block";
	}
	else {
		// The user has pressed the technology button whilst in the technology category. Show the main technology page:
		showCurrentTechnologyPane("TechnologyPane");
	}
}

function showCurrentTechnologyPane(spanName) {
	currentShownTechnologyPane = document.getElementById(currentShownTechnologyPaneName);
	currentShownTechnologyPane.style.display = "none"; 

	currentShownTechnologyPaneName = spanName;
	currentShownTechnologyPane = document.getElementById(currentShownTechnologyPaneName);
	currentShownTechnologyPane.style.display = "inline"; 

}

// -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
function subMenuOnMouseDown(subMenu) {
	// Generic function event added to all submenus. The call will show or hide the content pane in the main window.

	if (arrayContains(technologyMenuItemsNames, subMenu.id)) {
		if (currentShownTechnologyPaneName != subMenu.id) {
			showCurrentTechnologyPane(subMenu.id + "Pane");
		}
	}
	else if (arrayContains(productMenuItemsNames, subMenu.id)) {
		if (currentShownProductPaneName != subMenu.id) {
			showCurrentProductPane(subMenu.id + "Pane");
		}
	}
	else if (arrayContains(homeMenuItemsNames, subMenu.id)) {
		if (currentShownHomePaneName != subMenu.id) {
			showCurrentHomePane(subMenu.id + "Pane");
		}
	}
}

function arrayContains(arr, elt) {
	// Returns true if an array contains the specified element
	for (i = 0; i < arr.length; i++) {
		if (arr[i] == elt) return true;
	}
	return false;
}

