/*******************************************************************************
 * Licensed Materials - Property of IBM
 * (c) Copyright IBM Corporation 2005-2008. All Rights Reserved.
 * 
 * Note to U.S. Government Users Restricted Rights:
 * Use, duplication or disclosure restricted by GSA ADP Schedule
 * Contract with IBM Corp.
 *******************************************************************************/
(function() {

dojo.provide("jazz.NavBar");

dojo.require("dijit._Widget");
dojo.require("dijit._Templated");
dojo.require("dijit.Menu");

dojo.declare("jazz.NavBar", [dijit._Widget, dijit._Templated], {

	templateString: "<div class=\"jazz-NavBar\"><div class=\"navbarItem home\"><a class=\"homeLink navbarItem\" href=\"http://jazz.net/\" dojoAttachPoint=\"home\"><span></span>Home</a></div></div>",
	
	options: null,
	optionsUrl: "/servlet/GlobalNav/",
	dynamicPages: null,
	menuClass: "jazznet-HoverMenu-menu",
	
	postCreate: function(){
		dojo.addClass(this.domNode, "jazz-NavBar-loading");
		if (this.options) {
			// we already have the xml, parse it and display widget.
			try {
				if (dojo.isIE) {
					xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
					xmlDoc.async="false";
					xmlDoc.loadXML(this.options);
				} else {
					parser=new DOMParser();
					xmlDoc=parser.parseFromString(this.options,"text/xml");
				}
			} catch (e) {
				this.getMenuOptions(this.optionsUrl);
			}
			this.handleMenuResponse(xmlDoc);
		} else {
			// fetch the XML asynchronously
			this.getMenuOptions(this.optionsUrl);
		}
	},
	getMenuOptions: function( optionsUrl ){
		var dfd = dojo.xhrGet({
			url: optionsUrl,
			handleAs: "xml"
		});
		dfd.addCallback(dojo.hitch(this, this.handleMenuResponse));
	},
	handleMenuResponse: function(response){
		try {
			var dynamicPages = this.dynamicPages;
			var path = window.location.pathname;
			path = path.split("/")[1];
			if (path === "") {
				dojo.addClass(this.home, "selected");
			}
			this.sections = response.getElementsByTagName("section");
			var group = document.createDocumentFragment();
			dojo.forEach(this.sections, function(section){
				var pages = new Array();
				var sectionName = section.getElementsByTagName('sectionLabel');
				var sectionLink = section.getElementsByTagName('sectionLink');
				if (sectionName.length == 1) {
					var anchor = document.createElement("a");
					anchor.className = "navbarItem";
					anchor.href = sectionLink[0].childNodes[0].nodeValue;
					anchor.appendChild(document.createTextNode(sectionName[0].childNodes[0].nodeValue));
					if (path === sectionLink[0].childNodes[0].nodeValue.split("/")[1]) 
						dojo.addClass(anchor, "selected");
					
					if (section.getElementsByTagName("pages").length == 1) {
						dojo.forEach(section.getElementsByTagName("page"), function(page){
							var label = page.getElementsByTagName('label')[0].childNodes[0].nodeValue;
							var data = {label: label};
							if (label == "__separator__") {
								data.separator = true;
							} else {
								data.href = page.getElementsByTagName('href')[0].childNodes[0].nodeValue;
							}
							pages.push(data);
						});
					}
					if (dynamicPages && dynamicPages.section[0].sectionName) {
						for (var i = 0; i < dynamicPages.section.length; i++) {
							if (dynamicPages.section[i].sectionName === sectionName[0].childNodes[0].nodeValue) {
								for (var j = 0; j < dynamicPages.section[i].pages.length; j++) {
									pages.push(dynamicPages.section[i].pages[j]);
								}
							}
						}
					}
					if (pages.length > 0) {
						var hoverDiv = document.createElement("A");
						new jazz.HoverMenu({
							pages: pages,
							align: "left",
							menuProvider: dojo.hitch(this, this._menuProvider),
							around: anchor,
							menuClass: this.menuClass,
							cacheMenu: true
						}, anchor);
						anchor.appendChild(hoverDiv);
					} else {
						dojo.addClass(anchor, "navbar-no-menu")
					}
				}
				group.appendChild(anchor);
			}, this);
			
			if (this.domNode.childNodes > 0){
				this.domNode.innerHTML = "";
				this.domNode.appendChild(group);
			}
			else
				this.domNode.appendChild(group);
		} catch(e) {
			displayExceptionInfo(e);
		} finally {
			dojo.removeClass(this.domNode, "jazz-NavBar-loading");
		}
	},
	_menuProvider: function(hoverMenu){
		if (hoverMenu._menu) { //cached
			hoverMenu._menu.domNode.style.top = "";
			return hoverMenu._menu;
		}
		var pages = hoverMenu.pages;
		var menu = new dijit.Menu();
		dojo.addClass(menu.domNode, "jazznet-navbar-menu");
		if (pages) {
			var item;
			for (var i = 0; i < pages.length; i++) {
				if (pages[i].separator) {
					menu.addChild(new dijit.MenuSeparator({}));
				} else {
					item = new dijit.MenuItem({
						label: "<a href=\""+pages[i].href+"\">"+pages[i].label+"</a>",
						onClick: dojo.hitch(window, function(href){ location.href = href; }, pages[i].href)
					});
					if (pages[i].label.substring(0,1)==" ") {
						dojo.addClass(item.domNode, "indent");
					}
					menu.addChild(item);
				}
			}
		}
		hoverMenu._menu = menu;  //cache the menu
		return menu;
	}
});

dojo.provide("jazz.HoverMenu");

var _currentOpen = null;
var _currentOver = null;
dojo.declare("jazz.HoverMenu", [dijit._Widget], {
	
	align: "left",
	around: null,
	menuProvider: null,
	showCaret: true,
	buttonMenuOpenClass: "menu-open",
	menuClass: "",
	href: "",
	cacheMenu: false,
	stopClick: false,
	openDelay: 300,
	closeDelay: 800,
	closeBufferPx: 10,
	
	_menuOpen: false,

	postCreate: function() {
		dojo.addClass(this.domNode, "jazznet-HoverMenu");
		this.connect(this.domNode, "onmouseover", this._onMouseOver);
		this.connect(this.domNode, "onclick", this._onClick);
		this.connect(this.domNode, "onkeypress", this._handleKeypress);
		if (this.showCaret) {
			var caret = document.createElement("img");
			caret.className = "caret";
			caret.src = document.location.protocol+"//jazz.net/_scripts/graphics/HoverMenu/navbar-arrow.gif";
			this.domNode.appendChild(caret);
			if (!this.stopClick) {
				this.connect(caret, "onclick", this._onCaretClick);
			}
		} 
		if (!this.around) {
			this.around = this.domNode;
		}
	},
	_onMouseOver: function(event) {
		dojo.stopEvent(event);
		if (_currentOpen) {
			if (_currentOpen == this) {
				return; // menu is already open.
			}
			dojo.hitch(_currentOpen, _currentOpen._killMenu)(false);
			this._openMenu();
		} else if (!this._overTimeout) {
			_currentOver = this;
			this._overTimeout = setTimeout(dojo.hitch(this,this._deferredOpen),this.openDelay);
		}
		if (!this._mouseMoveEvent) 
			this._mouseMoveEvent = this.connect(dojo.doc, "onmousemove", this._mouseMove);		
	},
	_mouseMove: function(event) {
		var stayOpen = false;
		if (this._menuOpen) {
			var pc = dojo.coords(this._currentMenu.domNode),
				mouseX = event.clientX,
				mouseY = event.clientY,
				BUFFER = this.closeBufferPx
			if (pc.x - BUFFER <= mouseX && pc.x + pc.w + BUFFER >= mouseX && pc.y - BUFFER <= mouseY && pc.y + pc.h + BUFFER >= mouseY) {
				stayOpen = true;
			}
		}
		if ((this._menuOpen && stayOpen) || dojo.isDescendant(event.target, this.around)) {
			//stay open
			clearTimeout(this._killMenuTimeout);
			this._killMenuTimeout = null;
			return;	
		} else {
			//close
			if (this._menuOpen) {
				var canDismiss = this._currentMenu.canDismiss;
				if (canDismiss && canDismiss() === false) {
					//the popup doesn't want to be dismissed yet.
					return;
				}
				// wait delay and kill popup.
				if (!this._killMenuTimeout) {
					this._killMenuTimeout = setTimeout(dojo.hitch(this,this._deferredKill), this.closeDelay);	
				}
			} else {
				this.disconnect(this._mouseMoveEvent);
				this._mouseMoveEvent = null;
				clearTimeout(this._overTimeout);
				this._overTimeout = null;
			}
		}		
	},
	_deferredKill: function() {
		this.disconnect(this._mouseMoveEvent);
		this._mouseMoveEvent = null;
		this._killMenu();
	},
	_onCaretClick: function(event) {
		this._onClick(event, true);
	},
	_onClick: function(event, caretClick) {
		if (this.stopClick || caretClick) {
			dojo.stopEvent(event);
		} else {
			this._killMenu(false);
			clearTimeout(this._overTimeout);
			this._overTimeout = null;
			return;
		}
		_currentOver = this;
		this.disconnect(this._mouseMoveEvent);
		this._mouseMoveEvent = null;
		this._openMenu(event);
	},
	_deferredOpen: function(event) {
		clearTimeout(this._overTimeout);
		this._overTimeout = null;
		if (_currentOver && _currentOver != this) {
			// the timeout fired here, but the mouse is over another menu
			dojo.hitch(_currentOver, _currentOver._openMenu)(event); // open the other menu
		} else {
			this._openMenu(event);
		}
		_currentOver = null;
	},
	_openMenu: function(event) {
		if (this._menuOpen) {
			dojo.hitch(this._currentMenu, this._currentMenu.onOpen)();
			return;
		}
		if (this._currentMenu) {
			var menu = this._currentMenu;  //there's a menu from last time. Re-use it.
		} else {
			try {
				menu = this.menuProvider(this);	
			} catch(e) {
				console.error(e);
			}
			if (!menu) return;
			this._currentMenu = menu;
			dojo.addClass(menu.domNode, "jazz-app-HoverMenu-menu");
			dojo.addClass(menu.domNode, this.menuClass);
		}
		var exec = dojo.hitch(this, this._killMenu);
		this.domNode.focus();
		dijit.popup.open({
			popup: menu, 
			parent: this, 
			around: this.around, 
			orient: (this.align == "right") ? {"BR":"TR"}: {"BL":"TL"}, 
			onExecute: exec,
			onCancel: exec
		});
		menu.domNode.style.top = "";	//hack for dojo 1.2 (navbar in RTC 2.0.0.2)
		this._menuOpen = true;
		_currentOpen = this;
		dojo.addClass(this.around,this.buttonMenuOpenClass);
		this._bodyClickEvent = this.connect(document.body, "onclick", this._bodyClick);
		if (menu.startup) menu.startup();
	},
	_bodyClick: function(event){
		if (dojo.isDescendant(event.target, this.around) || dojo.isDescendant(event.target, this._currentMenu.domNode)) {
			return;
		}
		this._killMenu(false);
	},
	// private functions
	_killMenu: function(focus) {
		if (this._currentMenu && this._menuOpen) {
			dijit.popup.close(this._currentMenu);
			this._currentMenu.onClose&&this._currentMenu.onClose();
			this._menuOpen = false;
			if (!this.cacheMenu && this._currentMenu && this._currentMenu.destroyRecursive) {
				this._currentMenu.destroyRecursive();
				this._currentMenu = null;
			}
			dojo.removeClass(this.around, this.buttonMenuOpenClass);
			this.disconnect(this._mouseMoveEvent);
			this.disconnect(this._bodyClickEvent);
			clearTimeout(this._killMenuTimeout);
			clearTimeout(this._overTimeout);
			this._bodyClickEvent = null;
			this._mouseMoveEvent = null;
			this._killMenuTimeout = null;
			this._overTimeout = null;
			_currentOpen = null;
			if (focus === false) return;
			dijit.focus(this.around);
		}
	},
	_handleKeypress: function(e) {
		var k = dojo.keys;
		switch (e.charOrCode) {
			case k.UP_ARROW:
			case k.DOWN_ARROW:
			case k.SPACE:
				if (!this._menuOpen) this._openMenu();
				e.preventDefault();
				break;
		}
		switch (e.charOrCode) {
			case k.UP_ARROW:
				this._currentMenu.focus("end");
				break;
			case k.DOWN_ARROW:
				this._currentMenu.focus("start");
				break;
			case k.TAB:
				if (this._menuOpen) {
					this._currentMenu.focus();
					e.preventDefault();
				}
				break;
				
		}
	}
});
dojo.mixin(jazz.HoverMenu, {
	closeAll: function() {
		if (_currentOpen) dojo.hitch(_currentOpen,_currentOpen._killMenu)();
	}
});

dojo.provide("jazz.theme.AboveBannerWidget");

dojo.declare("jazz.theme.AboveBannerWidget", jazz.NavBar, {
	menuClass: "jazznet-HoverMenu-menu jazznet-HoverMenu-menu-product jazz-ui-Menu",
	isSandboxSetup: false,
	isSandbox: false,
	postCreate: function() {
		var href = document.location.href;
		if (href.indexOf("/sandbox/setup/") >= 0) {
			this.isSandboxSetup = true;
		} else if (href.indexOf("/sandbox/") >= 0) {
			this.isSandbox = true;
		}
		dojo.addClass(this.domNode, "jazz-NavBar-product");
		if (!this.isSandboxSetup) {
			var img = document.createElement("img");
			img.src = document.location.protocol+"//jazz.net/_scripts/graphics/NavBar/jazz-navbar-small.png";
			this.home.insertBefore(img,this.home.firstChild);
			if (this.isSandbox) {
				var div = document.createElement("div");
				div.className = "sandbox-nav";
				div.innerHTML = "<a href='https://jazz.net/sandbox/setup/web'>Sandbox Home</a> <a href='http://jazz.net/forums'>Forums</a> <a href='http://www.ibm.com/software/awdtools/rtc/'>Buy @ IBM.com</a> <a href='https://jazz.net/downloads/rational-team-concert/latest'>Download</a>";
				this.domNode.insertBefore(div,this.domNode.firstChild);
			}
		}
		dojo.require("dojox.analytics.Urchin");
		var tracker = new dojox.analytics.Urchin({ 
			acct:"UA-10864409-1",
			_isFirst: true,
			GAonLoad: function() {
				if (this._isFirst) {
					var obj = dojo.getObject("net.jazz.ajax.internal.events.viewPage");
					if (obj) dojo.subscribe(obj, this, "GAonLoad");
					delete this._isFirst;
				}
				var url = location.href;
				var index = url.indexOf("jazz.net/");
				if (index >= 0)	url = url.substring(index+8);
				this.trackPageView(url);
			}
		});
		this.inherited(arguments);
	}
});
})();