// Initialisation moved to the onload in the masterpage
//	window.onload=function(){
//	        alert('window.onload');		  
//			window.page=new Page();
//		}
//		window.onunload=function(){
//			window.page.destroy();
//		}
/* -----------------------------------------------------------------
// Main page object
----------------------------------------------------------------- */

Page = function() {
    //alert('page()');		  
	if (!this.hasSupport()) return;
	this.menu = new Navigation("primary-navigation");
	
}

Page.prototype.destroy = function() {
	if(!this.hasSupport()) return;
	this.menu.destroy();
}

Page.prototype.hasSupport = function() { // block MSIE5.0x/Win, MSIE5.x/Mac
	var ua = navigator.userAgent;
	if((ua.indexOf("MSIE 5.0") != -1 && ua.indexOf("Windows") != -1) 
			|| (ua.indexOf("MSIE 5.2") != -1 && ua.indexOf("Mac") != -1) 
			|| !document.getElementsByTagName 
			|| !document.getElementById) { 
		return false; 
	} else { 
		return true; 
	}
}

/* -----------------------------------------------------------------
// Page helpers/methods/properties/...
----------------------------------------------------------------- */

// Dynamic classname handling for objects
addClass = function(obj, cName) { 
	if (obj) {
		removeClass(obj,cName); 
		return obj.className += (obj.className.length > 0 ? " " : "") + cName; 
	}
}
removeClass = function(obj, cName) {
	if (obj) {
		return obj.className = obj.className.replace(new RegExp("^" + cName+"\\b\\s*|\\s*\\b" + cName+"\\b",'g'),''); 
	}
}

// Function to fetch objects by classname
getElementsByClassName = function(cName, baseElement) {
	var results = new Array;
	var objs = document.getElementsByTagName("*").length > 0 ? baseElement.getElementsByTagName("*") : baseElement.all;
	if(!objs) objs = baseElement.all;
	for(var i = 0; i < objs.length; i++){
		if(objs[i].className.match(cName)) results[results.length] = objs[i]
	}
	return results;
}

Object.prototype.method = function(method) {
	var context = this;
	return function(){
		method.apply(context, arguments);
	}
}

setCookie = function(name, value, expires, path, domain, secure){
	document.cookie = name + "=" + escape(value) + 
		((expires) ? ";expires=" + expires.toGMTString() : "") + 
		((path) ? ";path=" + path : "") + 
		((domain) ? ";domain=" + domain : "") + 
		((secure) ? ";secure" : "");
}

getCookie = function(name){
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
      if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

// Functions to calculate the position of objects
calculateLeft = function(object) {
	if (object) return object.offsetLeft + calculateLeft(object.offsetParent); 
	else return 0;
}
calculateTop = function(object) {
	if (object) return object.offsetTop + calculateTop(object.offsetParent); 
	else return 0;
}

// Tickle the browser to display correctly
tickle = function(){
	addClass(document.getElementsByTagName("body")[0], "tickle");
}

// Function to add event listeners
// This function breaks sharepoint compatibillity (naming conflict perhaps?)
/*
addEvent = function(obj, evType, fn, ieonly) { 
	if (obj.addEventListener && !ieonly){ // Mozilla & others
		obj.addEventListener(evType, fn, false); 
		return true; 
	} else if (obj.attachEvent){ // IE
		var r = obj.attachEvent("on"+evType, fn); 
		return r; 
	} else { 
		return false; 
	} 
}
*/


/* the class object */

Navigation = function (nodeID) {

	// Navigation Settings
	this.menuInitItemHeight = 31; // Height (px) of closed menu
	this.menuItemHeight = 24; // Height (px) of li's
	this.menuPadding = 25; // Extra height padding (px)
	this.menuLoginFormHeight = 7; // OBSOLETE!
	this.fuseDelay = 400; // timeout (ms) before opening navigation
	this.expandLeftLimit = 4; // Number of top-level items before submenus fold the other way
	
	this.locationUri = location.href; // URI to highlight
	this.nToplevelItems = 0; // Counter for top-level items
	
	var navigation = this;
	var selectedItem = null;
	
	this.rootNode = document.getElementById(nodeID);
	this.state = this.CLOSED;
	
	if(document.all){ // shim for IE
		var iframeID = "primary-iframe";
		this.iframe = document.createElement("iframe");
		this.iframe.id=iframeID;
		this.iframe.frameBorder=0;
		this.iframe.scrolling = "no";
		this.iframe.src = "about:blank";
		this.rootNode.appendChild(this.iframe);
	};
	
	// Navigation behaviors
	var closeMenu = function (e) {
		if (e) e.stopPropagation(); else window.event.cancelBubble = true;
		var destination = (e) ? e.relatedTarget : window.event.toElement;
		if(!destination) return;
		if (destination.tagName != "INPUT") // firefox bug ?
			navigation.changeState(navigation.LOSTMOUSE, destination, this.menuitem);
		if (this.menuitem || !navigation.isChild(destination)) removeClass(navigation.selectedItem, "selected");
	};
	var openMenu = function (e) {
		if (e) e.stopPropagation(); else window.event.cancelBubble = true;
		if (navigation.selectedItem) removeClass(navigation.selectedItem, "selected");
		navigation.selectedItem = this;
		if (navigation.selectedItem.menuitem.submenu || navigation.selectedItem.id == "nav-my-post") addClass(navigation.selectedItem, "selected");
		var destination = (e) ? e.relatedTarget : window.event.toElement;
		if(!destination) return;
		navigation.changeState(navigation.GOTMOUSE, destination, this.menuitem);
	};
	var openSubMenu = function (e) {
		addClass(this, "selected");
		if (e) e.stopPropagation(); else window.event.cancelBubble = true;
		//adjust manupanel
		var destination = (e) ? e.relatedTarget : window.event.toElement;
		if(!destination) return;
		navigation.changeState(navigation.GOTMOUSE, destination, this.menuitem);
	};
	var closeSubMenu = function (e) {
		removeClass(this, "selected");
		if (e) e.stopPropagation(); else window.event.cancelBubble = true;
		// check 4 lost events
		var destination = (e) ? e.relatedTarget : window.event.toElement;
		if(!destination) return;
		if (!navigation.isChild(destination)) navigation.changeState(navigation.LOSTMOUSE, destination, this.menuitem);
	};
	
	// get nodes
	var root = this.rootNode.getElementsByTagName("ul")[0];
	root.onmouseout = closeMenu;
	var lis = root.getElementsByTagName("li");
	
	// shift main panel to the ul
	this.rootNode = root;
	
	// hook up behaviors
	for (var i=0; i < lis.length; i++) {
		if (lis[i].parentNode == root) {
			// level 0 (top-level li's)
			this.nToplevelItems += 1;
			lis[i].onmouseover = openMenu;
			lis[i].menuitem = new Object();
			if (lis[i].getElementsByTagName("li").length > 0) {
				// has submenu
				lis[i].menuitem.submenu = lis[i].getElementsByTagName("ul")[0];
				lis[i].menuitem.height = this.calculateMenuHeight(lis[i].menuitem.submenu);
				// Change submenu expansion
				if (this.nToplevelItems > this.expandLeftLimit) {
					addClass(lis[i].getElementsByTagName("ul")[0], "expand-left");
				};
			}
			else {
				lis[i].menuitem.submenu = null;
				lis[i].menuitem.height = this.menuInitItemHeight;
				if (lis[i].id == "nav-my-post") lis[i].menuitem.height = 160;
			};
			// highlight current item corresponding to URI
			if ( this.locationUri.match(lis[i].getElementsByTagName("a")[0].href) ) {
				addClass(lis[i], "current");
			};
		};
		if (lis[i].parentNode.parentNode.parentNode == root) {
			// level 1
			lis[i].onmouseover = openSubMenu;
			lis[i].onmouseout = closeSubMenu;
			lis[i].menuitem = new Object();
			if (lis[i].getElementsByTagName("li").length > 0) {
				lis[i].menuitem.submenu = lis[i].getElementsByTagName("ul")[0];
				lis[i].menuitem.height =  this.calculateMenuHeight(lis[i].menuitem.submenu);
			}
			else {
				lis[i].menuitem.submenu = null;
				lis[i].menuitem.height = this.menuInitItemHeight;
			};
		};
	};
	// recalculate the height
	for (var i=0; i < lis.length; i++) {
		if (lis[i].parentNode == root && lis[i].getElementsByTagName("li").length > 0) {
			this.recalculateMenuHeight(lis[i].menuitem);
		};
	};
	
};

//Event types
Navigation.prototype.GOTMOUSE  = 0;
Navigation.prototype.LOSTMOUSE = 1;

//States
Navigation.prototype.OPEN      = 0;
Navigation.prototype.CLOSED    = 1;
Navigation.prototype.ANIMATING = 2;
Navigation.prototype.HOT       = 3;

Navigation.prototype.changeState = function (eventType, destination, newItem) {
	if (this.isChild(destination) && !newItem) {
		return;//Ignore event bubbling when open, top item events got newItems, so they fall through
	}
	switch (eventType) {
		case this.GOTMOUSE:
			switch (this.state) {
				case this.HOT:
					this.activeItem = newItem;
				break;
				case this.CLOSED:// Menu will open in half a second unless the fuse is put out
					this.fuse = setTimeout(this.method(this.open), this.fuseDelay);
					this.activeItem = newItem;
					this.state = this.HOT;
				break;
				case this.OPEN:// Switch between main categories
					if (newItem != this.activeItem) {
						this.adjust(newItem);
					}
				break;
				case this.ANIMATING:// Stop and animate to new target
					if (newItem != this.activeItem) {
						this.animator.stop();
						this.adjust(newItem);
					}
				break;
			}
		break;
		case this.LOSTMOUSE:
			switch (this.state) {
				case (this.HOT):// Lost the mouse, cancel menu opening
					clearTimeout(this.fuse);
					this.activeItem = null;
					this.state = this.CLOSED;
				break;
				case (this.OPEN):// Close it
					this.close();
				break;
				case this.ANIMATING:// Stop and animate to closed position
					this.animator.stop();
					this.close();
				break;
			}
		break;
	}
}
Navigation.prototype.open = function () {
	this.state = this.ANIMATING;
	this.animator = new Animator(this.menuInitItemHeight, this.activeItem.height, this.method(this.setHeight), this.method(this.opened));
	this.animator.start();
}
Navigation.prototype.opened = function () {
	this.state = this.OPEN;
	this.animator = null;
}

Navigation.prototype.close = function () {
	this.state = this.ANIMATING;
	this.animator = new Animator(this.currentHeight, this.menuInitItemHeight, this.method(this.setHeight), this.method(this.closed));
	this.animator.start();
}
Navigation.prototype.closed = function () {
	this.state = this.CLOSED;
	this.activeItem = null;
	this.animator = null;
}
Navigation.prototype.adjust = function (newItem) {
	this.state = this.ANIMATING;
	this.activeItem = newItem;
	this.animator = new Animator(this.currentHeight, this.activeItem.height, this.method(this.setHeight), this.method(this.opened));
	this.animator.start();
}
Navigation.prototype.isChild = function (candidate) {
	while (candidate && candidate != this.rootNode.parentNode) {
		if (candidate == this.rootNode) return true;
		try {
			candidate = candidate.parentNode;
		} catch (c) {return false}
	}
	return false;
}
Navigation.prototype.setHeight = function (x) {
	this.currentHeight = x;
	//var height=(x+16)/10;
	//this.rootNode.style.height = height+"em";
	var height= x;
	this.rootNode.style.height = height+"px";
	if(document.all){ // shim for IE
		//this.iframe.style.height = height+"em";
		//this.iframe.style.marginTop = -height+"em";
		this.iframe.style.height = height+"px";
		this.iframe.style.marginTop = -height+"px";
	}
}
Navigation.prototype.calculateMenuHeight = function (list) {
	var total = 0;
	var items = list.getElementsByTagName("a");
	for (var i=0; i < items.length; i++) {
		if (items[i].parentNode.parentNode == list)
			total += this.menuItemHeight;
		else
			total += 0;
	}
	total += this.menuPadding; // Add extra padding
	return total+this.menuItemHeight;
}
Navigation.prototype.recalculateMenuHeight = function (list) {
	var items = list.submenu.getElementsByTagName("li");
	var level1items = 0;
	for (var i=0; i < items.length; i++) {
		if (items[i].parentNode == list.submenu) {
			if ((level1items*this.menuItemHeight) + items[i].menuitem.height > list.height-this.menuItemHeight)
				items[i].menuitem.height = (level1items*this.menuItemHeight) + items[i].menuitem.height;
			else
				items[i].menuitem.height = list.height;
			level1items += 1;
		}
	}
}
Navigation.prototype.destroy = function() {
	// Remove closures
	this.rootNode.onmouseout=null;
	var lis = this.rootNode.getElementsByTagName("li");
	for (var i = 0; i < lis.length; i++) {
		lis[i].onmouseover = lis[i].onmouseout = null;
	}
}
