var MENUDIV_ID = "dhtmlgoodies_menu";
var SUBMENU_CLASS = 'dhtmlgoodies_subMenu';
var menuItems;
var slideSpeed_out = 10;	// Steps to move sub menu at a time ( higher = faster)
var slideSpeed_in = 10;
var delayMenuClose = 150;	// Microseconds from mouseout to close of menu
var slideTimeout_out = 25;	// Microseconds between slide steps ( lower = faster)
var slideTimeout_in = 10;	// Microseconds between slide steps ( lower = faster)
var xOffsetSubMenu = 0; 	// Offset x-position of sub menu items - use negative value if you want the sub menu to overlap main menu

/* Don't change anything below here */

var indeces = new Array();
indeces[0] = 0;
var isMSIE = navigator.userAgent.indexOf('MSIE')>=0?true:false;
var browserVersion = parseInt(navigator.userAgent.replace(/.*?MSIE ([0-9]+?)[^0-9].*/g,'$1'));
if(!browserVersion)browserVersion=1;

function mouseOn(obj) {
	var mi = findNode(getSearchIdFromObj(obj));
	if (mi) mi.mouseOn();
}

function mouseOff(obj) {
	var mi = findNode(getSearchIdFromObj(obj));
	if (mi) mi.mouseOff();
}

function getSearchIdFromObj(obj) {
	// pull the postfix off the A link or LI tag id and return the menu item ID
	var objId = obj.id;
	var idx = objId.indexOf('_');
	if (idx>=0) {
		return "MenuItem" + objId.substring(idx);
	}
	return null;
}

function slideChildMenu(aId) {
	var mi = findNode(aId);
	if (mi) mi.slideChildMenu();
}

function findNode(searchId) {
	var result;
	for (var no=0;no<menuItems.length;no++) {
		result = menuItems[no].findNode(searchId);
		if (result) return result;
	}
	return null;
}

function getNextIndex(lvl) {
	var result = 0;
	if (indeces.length<=lvl) {
		indeces[lvl] = 1;
	} else {
		result = indeces[lvl];
		indeces[lvl]++;
	}
	return result;
}

function MenuItem(divref, ulref, liref, lvlnum, parentref) {
	this.parent = parentref;
	this.div = divref;
	this.ul = ulref;
	this.width = this.ul.offsetWidth;
	// this.left = div.style.left.replace(/[^0-9]/g,'');
	this.li = liref;
	this.alink = this.li.getElementsByTagName('A')[0];
	this.lvl = lvlnum;
	this.idx = getNextIndex(this.lvl);
	this.children;
	this.subUL = this.li.getElementsByTagName('UL')[0];
	this.children;
	this.isMouseOnMe = false;
	// note: if !isOpen && !isClosed then I am animating a slide
	this.isChildMenuOpen = false;
	this.isChildMenuClosed = true;

	// Constructor
	// if a node does not have an A tag but it's children do then we need
	// null out this node's alink field...
	if (this.alink) {
		if (this.alink.parentNode!=this.li) this.alink = null;
	}
	if (this.subUL) {
		this.children = new Array();
		var subLI = this.subUL.getElementsByTagName('LI')[0];
		while(subLI) {
			if(subLI.tagName && subLI.tagName.toLowerCase()=='li') {
				this.children[this.children.length] = new MenuItem(null, this.subUL, subLI, this.lvl + 1, this);
			}
			subLI = subLI.nextSibling;
		}
	}

	this.getPostfix = function() {
		return '_' + this.idx + '_' + this.lvl;
	}
	
	this.getId = function() {
		return "MenuItem" + this.getPostfix();
	}

	this.hasChildren = function() {
		return (this.children!=null);
	}

	this.getTopPos = function() {
		var origDisp = this.div.style.display;
		this.div.style.display = "";
		var obj = this.li;
		var result = obj.offsetTop;
		while((obj = obj.offsetParent) != null) result += obj.offsetTop;
		this.div.style.display = origDisp;
		return result;
	}

	this.getLeftPos = function() {
		var origDisp = this.div.style.display;
		this.div.style.display = "";
		var obj = this.li;
		var result = obj.offsetLeft;
		while((obj = obj.offsetParent) != null) result += obj.offsetLeft;
		this.div.style.display = origDisp;
		return result;
	}

	this.renderNode = function() {
		// set node properties
		this.li.id = "menuItemLI" + this.getPostfix();
		this.ul.style.position = "relative";
		if (this.alink) {
			this.alink.id = "menuItemA" + this.getPostfix();
			this.alink.onmouseover = function() {mouseOn(this);};
			this.alink.onmouseout = function() {mouseOff(this);};
		} else {
			this.li.onmouseover = function() {mouseOn(this);};
			this.li.onmouseout = function() {mouseOff(this);};
		}

		// set sub-menu nodes
		if (this.hasChildren()) {
			var mi = this.children[0];
			var subdiv = document.createElement('DIV');
			subdiv.className=SUBMENU_CLASS;
			document.body.appendChild(subdiv);
			subdiv.id = "menuItemDIV" + mi.getPostfix();
			this.subUL.id = "menuItemUL" + mi.getPostfix();
			subdiv.appendChild(this.subUL);
			subdiv.style.left = this.getLeftPos() + this.width + xOffsetSubMenu + 'px';
			subdiv.style.top = this.getTopPos() + 'px';
			subdiv.style.visibility = "hidden";
			subdiv.style.display = "none";
			subdiv.style.zindex = "1000";
			for (var no=0;no<this.children.length;no++) {
				var mi = this.children[no];
				mi.div = subdiv;
				mi.renderNode();
			}
		}
		return this.li;
	}

	this.findNode = function(searchId) {
		var result;
		if (this.getId() == searchId) {
			result = this;
		} else {
			if (this.hasChildren()) {
				for (var no=0;no<this.children.length;no++) {
					var mi = this.children[no];
					result = mi.findNode(searchId);
					if (result!=null) break;
				}
			}
		}
		return result;
	}

	this.mouseOn = function() {
		this.isMouseOnMe = true;
		if (this.hasChildren() && this.isChildMenuClosed) {
			this.initiateChildMenuOpen();
		}
	}

	this.mouseOff = function() {
		this.isMouseOnMe = false;
		if (this.hasChildren() && !this.isChildMenuClosed) {
			this.initiateChildMenuClose();
		} else if (this.parent) {
			this.parent.mouseOff();
		}
	}

	this.isMouseOnChild = function() {
		if (this.isMouseOnMe) return true;
		if (this.hasChildren()) {
			for (var no=0;no<this.children.length;no++) {
				if (this.children[no].isMouseOnChild()) return true;
			}
		}
		return false;
	}

	this.initiateChildMenuOpen = function() {
		this.isChildMenuClosed = false;
		var childDiv = this.children[0].div;
		childDiv.style.width = "0px";
		childDiv.style.visibility = "visible";
		childDiv.style.display = "";
		this.slideChildMenu();
	}

	this.initiateChildMenuClose = function() {
		this.isChildMenuOpen = false;
		// we have to wait to close the menu
		// allow the mouse to navigate over the child menu
		setTimeout("slideChildMenu('" + this.getId() + "')", delayMenuClose);
	}

	this.slideChildMenu = function() {
		var divref = this.children[0].div;
		var ulref = this.children[0].ul;
		var maxwidth = this.children[0].width;
		var nextWidth;
		if (this.isMouseOnMe  || this.isMouseOnChild()) {
			nextWidth = divref.offsetWidth + slideSpeed_out;
			if (nextWidth >= maxwidth) {
				this.finishOpeningChild(divref, ulref, maxwidth);
			} else {
				ulref.style.left = nextWidth - maxwidth + "px";
				divref.style.width = nextWidth + "px";
				setTimeout("slideChildMenu('" + this.getId() + "')", slideTimeout_out);
			}
		} else {
			nextWidth = divref.offsetWidth - slideSpeed_in;
			if (nextWidth <= 0) {
				this.finishClosingChild(divref, ulref, maxwidth);
			} else {
				ulref.style.left = nextWidth - maxwidth + "px";
				divref.style.width = nextWidth + "px";
				setTimeout("slideChildMenu('" + this.getId() + "')", slideTimeout_out);
			}
		}
	}

	this.finishOpeningChild = function(divref, ulref, maxwidth) {
		this.isChildMenuOpen = true;
		this.isChildMenuClosed = false;
		ulref.style.left = "0px";
		divref.style.width = maxwidth + "px";
	}

	this.finishClosingChild = function(divref, ulref, maxwidth) {
		this.isChildMenuOpen = false;
		this.isChildMenuClosed = true;
		divref.style.visibility = "hidden";
		divref.style.display = "none";
		divref.style.width = maxwidth + "px";
		if (this.parent) this.parent.mouseOff();
	}

}

function collectMenuNodes(menuObj) {
     if (!menuObj) return null;

     var results = new Array();
     var menuUL = menuObj.getElementsByTagName('UL')[0];
     var menuLI = menuUL.getElementsByTagName('LI')[0];
     while(menuLI) {
        if(menuLI.tagName && menuLI.tagName.toLowerCase()=='li') {
              results[results.length] = new MenuItem(menuObj, menuUL, menuLI, 0, null);
        }
        menuLI = menuLI.nextSibling;
     }
     return results;
}

function initMenu() {
	var mainDiv = document.getElementById(MENUDIV_ID);
	menuItems = collectMenuNodes(mainDiv);
	if (menuItems) {
		for (var no=0;no<menuItems.length;no++) {
			var mi = menuItems[no];
			mi.renderNode();
		}
		mainDiv.style.visibility = 'visible';
	}
	// window.onresize = resetPosition;
}

window.onload = initMenu;

var loadingImage = 'loading.gif';		
var closeButton = 'close.gif';		

function getPageScroll(){

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}

function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

function pause(numberMillis) {
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while (true) {
		now = new Date();
		if (now.getTime() > exitTime)
			return;
	}
}

function getKey(e){
	if (e == null) { // ie
		keycode = event.keyCode;
	} else { // mozilla
		keycode = e.which;
	}
	key = String.fromCharCode(keycode).toLowerCase();
	
	if(key == 'x'){ hideLightbox(); }
}


function listenKey () {	document.onkeypress = getKey; }
	
function showLightbox(objLink)
{
	// prep objects
	var objOverlay = document.getElementById('overlay');
	var objLightbox = document.getElementById('lightbox');
	var objCaption = document.getElementById('lightboxCaption');
	var objImage = document.getElementById('lightboxImage');
	var objLoadingImage = document.getElementById('loadingImage');
	var objLightboxDetails = document.getElementById('lightboxDetails');

	
	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();

	// center loadingImage if it exists
	if (objLoadingImage) {
		objLoadingImage.style.top = (arrayPageScroll[1] + ((arrayPageSize[3] - 35 - objLoadingImage.height) / 2) + 'px');
		objLoadingImage.style.left = (((arrayPageSize[0] - 20 - objLoadingImage.width) / 2) + 'px');
		objLoadingImage.style.display = 'block';
	}

	// set height of Overlay to take up whole page and show
	objOverlay.style.height = (arrayPageSize[1] + 'px');
	objOverlay.style.display = 'block';

	// preload image
	imgPreload = new Image();

	imgPreload.onload=function(){
		objImage.src = objLink.href;

		// center lightbox and make sure that the top and left values are not negative
		// and the image placed outside the viewport
		var lightboxTop = arrayPageScroll[1] + ((arrayPageSize[3] - 35 - imgPreload.height) / 2);
		var lightboxLeft = ((arrayPageSize[0] - 20 - imgPreload.width) / 2);
		
		objLightbox.style.top = (lightboxTop < 0) ? "0px" : lightboxTop + "px";
		objLightbox.style.left = (lightboxLeft < 0) ? "0px" : lightboxLeft + "px";


		objLightboxDetails.style.width = imgPreload.width + 'px';
		
		if(objLink.getAttribute('title')){
			objCaption.style.display = 'block';
			//objCaption.style.width = imgPreload.width + 'px';
			objCaption.innerHTML = objLink.getAttribute('title');
		} else {
			objCaption.style.display = 'none';
		}
		
		if (navigator.appVersion.indexOf("MSIE")!=-1){
			pause(250);
		} 

		if (objLoadingImage) {	objLoadingImage.style.display = 'none'; }

		selects = document.getElementsByTagName("select");
        for (i = 0; i != selects.length; i++) {
                selects[i].style.visibility = "hidden";
        }

	
		objLightbox.style.display = 'block';

		arrayPageSize = getPageSize();
		objOverlay.style.height = (arrayPageSize[1] + 'px');
		
		// Check for 'x' keypress
		listenKey();

		return false;
	}

	imgPreload.src = objLink.href;
	
}

function hideLightbox()
{
	// get objects
	objOverlay = document.getElementById('overlay');
	objLightbox = document.getElementById('lightbox');

	// hide lightbox and overlay
	objOverlay.style.display = 'none';
	objLightbox.style.display = 'none';

	// make select boxes visible
	selects = document.getElementsByTagName("select");
    for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "visible";
	}

	// disable keypress listener
	document.onkeypress = '';
}

function initLightbox()
{
	
	if (!document.getElementsByTagName){ return; }
	var anchors = document.getElementsByTagName("a");

	// loop through all anchor tags
	for (var i=0; i<anchors.length; i++){
		var anchor = anchors[i];

		if (anchor.getAttribute("href") && (anchor.getAttribute("rel") == "lightbox")){
			anchor.onclick = function () {showLightbox(this); return false;}
		}
	}

	var objBody = document.getElementsByTagName("body").item(0);
	
	// create overlay div and hardcode some functional styles (aesthetic styles are in CSS file)
	var objOverlay = document.createElement("div");
	objOverlay.setAttribute('id','overlay');
	objOverlay.onclick = function () {hideLightbox(); return false;}
	objOverlay.style.display = 'none';
	objOverlay.style.position = 'absolute';
	objOverlay.style.top = '0';
	objOverlay.style.left = '0';
	objOverlay.style.zIndex = '90';
 	objOverlay.style.width = '100%';
	objBody.insertBefore(objOverlay, objBody.firstChild);
	
	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();

	// preload and create loader image
	var imgPreloader = new Image();
	
	// if loader image found, create link to hide lightbox and create loadingimage
	imgPreloader.onload=function(){

		var objLoadingImageLink = document.createElement("a");
		objLoadingImageLink.setAttribute('href','#');
		objLoadingImageLink.onclick = function () {hideLightbox(); return false;}
		objOverlay.appendChild(objLoadingImageLink);
		
		var objLoadingImage = document.createElement("img");
		objLoadingImage.src = loadingImage;
		objLoadingImage.setAttribute('id','loadingImage');
		objLoadingImage.style.position = 'absolute';
		objLoadingImage.style.zIndex = '150';
		objLoadingImageLink.appendChild(objLoadingImage);

		imgPreloader.onload=function(){};	//	clear onLoad, as IE will flip out w/animated gifs

		return false;
	}

	imgPreloader.src = loadingImage;

	// create lightbox div, same note about styles as above
	var objLightbox = document.createElement("div");
	objLightbox.setAttribute('id','lightbox');
	objLightbox.style.display = 'none';
	objLightbox.style.position = 'absolute';
	objLightbox.style.zIndex = '100';	
	objBody.insertBefore(objLightbox, objOverlay.nextSibling);
	
	// create link
	var objLink = document.createElement("a");
	objLink.setAttribute('href','#');
	objLink.setAttribute('title','Clicca per chiudere');
	objLink.onclick = function () {hideLightbox(); return false;}
	objLightbox.appendChild(objLink);

	// preload and create close button image
	var imgPreloadCloseButton = new Image();

	// if close button image found, 
	imgPreloadCloseButton.onload=function(){

		var objCloseButton = document.createElement("img");
		objCloseButton.src = closeButton;
		objCloseButton.setAttribute('id','closeButton');
		objCloseButton.style.position = 'absolute';
		objCloseButton.style.zIndex = '200';
		objLink.appendChild(objCloseButton);

		return false;
	}

	imgPreloadCloseButton.src = closeButton;

	// create image
	var objImage = document.createElement("img");
	objImage.setAttribute('id','lightboxImage');
	objLink.appendChild(objImage);
	
	// create details div, a container for the caption and keyboard message
	var objLightboxDetails = document.createElement("div");
	objLightboxDetails.setAttribute('id','lightboxDetails');
	objLightbox.appendChild(objLightboxDetails);

	// create caption
	var objCaption = document.createElement("div");
	objCaption.setAttribute('id','lightboxCaption');
	objCaption.style.display = 'none';
	objLightboxDetails.appendChild(objCaption);

	// create keyboard message
	var objKeyboardMsg = document.createElement("div");
	objKeyboardMsg.setAttribute('id','keyboardMsg');
	objLightboxDetails.appendChild(objKeyboardMsg);


}

function addLoadEvent(func)
{	
	var oldonload = window.onload;
	if (typeof window.onload != 'function'){
    	window.onload = func;
	} else {
		window.onload = function(){
		oldonload();
		func();
		}
	}

}



addLoadEvent(initLightbox);	// run initLightbox onLoad