// simple browser detector
function BrowserDetectorClass()
{
	this.constInternetExplorer = 0;
	this.constOpera = 1;
	this.constNetscape = 2;
	this.constFirefox = 3;

	this.browser = this.constInternetExplorer;

    if (navigator.userAgent.indexOf("Opera") >= 0) this.browser = this.constOpera;
    else if (navigator.userAgent.indexOf("Firefox") >= 0) this.browser = this.constFirefox;
    else if (navigator.userAgent.indexOf("Netscape") >= 0) this.browser = this.constNetscape;
    //else browser = constInternetExplorer;
}

//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

function MenuDropdownItem(id, parentId, title, url, url2, behaviour, childrenCountToRender, renderFlag, itemStyleClass, level, childrenCountToRenderPopup)
{
    this.id = id;
    this.parentId = parentId;
    this.title = title;
    this.url = url;
    this.url2 = url2;
    this.behaviour = behaviour;
    this.childrenCountToRender = childrenCountToRender;
    this.renderFlag = renderFlag;
    this.itemStyleClass = itemStyleClass;
    this.level = level;
    this.childrenCountToRenderPopup = childrenCountToRenderPopup;

    //refer to Menu Item definition in src
    this.BEHAVIOUR_HOME_PAGE = 0;                // I want to show the home page of this section
    this.BEHAVIOUR_URL = 1;                      // I want to show the url on it
    this.BEHAVIOUR_HOME_PAGE_URL_WINDOW = 2;     // I want to show the home page and the url in a new browser window
    this.BEHAVIOUR_URL_WINDOW = 3;               // I want to show the url in a new browser window
    this.BEHAVIOUR_FOLDING = 4;                  // Folding only
}

//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

//Usage:
//var m = new MenuDropdown({params});
//m.addItem(params);
//m.init();
function MenuDropdown(
    name,
    dynamicContainerId,
    width,
    itemImgEmptySrc,
    itemImgCollapseSrc,
    itemIdPrefixDivider,
    itemIdPrefixAnchor,
    itemIdPrefixImg,
    stylePrefixPage,
    stylePrefixSection,
    stylePrefixSelected,
    stylePrefixHighlighted,
    itemDividerStyleClass,
    itemIdPrefixPopup,
    popupInitOnDemandFlag,
    imagePos,
    showFolderImage,
	lastLevel
	)
{
    this.debugFlag = false;

    this.name = name;
    this.dynamicContainerId = dynamicContainerId;
    this.items = Array();
    this.itemsMap = Object();
    this.itemChildren = Object();
    this.width = (width != null ? width : 200);
    this.imagePos = (imagePos != null ? imagePos : "right");
    this.showFolderImage = (showFolderImage != null ? showFolderImage : false);
	this.lastLevel = lastLevel;

    this.popupTimer = null;
    this.openedPopups = Array();
    this.openedPopupsMap = Object();

    //refer to Menu Tag definition in src
    this.ITEM_IMG_EMPTY_SRC = (itemImgEmptySrc != null ? itemImgEmptySrc : "./images/1.gif");
    this.ITEM_IMG_COLLAPSE_SRC = (itemImgCollapseSrc != null ? itemImgCollapseSrc : "./images/collapse.gif");
    this.ITEM_ID_DIVIDER_PREFIX = (itemIdPrefixDivider != null ? itemIdPrefixDivider : "d");
    this.ITEM_ID_ANCHOR_PREFIX = (itemIdPrefixAnchor != null ? itemIdPrefixAnchor : "a");
    this.ITEM_ID_IMG_PREFIX = (itemIdPrefixImg != null ? itemIdPrefixImg : "i");
    this.ITEM_STYLE_PREFIX_PAGE = (stylePrefixPage != null ? stylePrefixPage : "p");
    this.ITEM_STYLE_PREFIX_SECTION = (stylePrefixSection != null ? stylePrefixSection : "s");
    this.ITEM_STYLE_PREFIX_SELECTED = (stylePrefixSelected != null ? stylePrefixSelected : "x"); //unnecessary
    this.ITEM_STYLE_PREFIX_HIGHLIGHTED = (stylePrefixHighlighted != null ? stylePrefixHighlighted : "r");
    this.ITEM_DIVIDER_STYLE_CLASS = (itemDividerStyleClass != null ? itemDividerStyleClass : "menuSeparator");

    //const
    this.TIMER_HIDE_ALL_VALUE = 1000; //1000ms = 1 sec
    this.ITEM_ID_PREFIX_POPUP = (itemIdPrefixPopup != null ? itemIdPrefixPopup : "p");

    //additional vars
    this.popupInitOnDemandFlag = (popupInitOnDemandFlag != null ? popupInitOnDemandFlag : false);
    //var browserDetector = new BrowserDetectorClass();
    //if (browserDetector.browser == browserDetector.constInternetExplorer) this.popupInitOnDemandFlag = true;

    //debug
    var dynamicContainer = document.getElementById(this.dynamicContainerId);

    if (dynamicContainer != null && this.debugFlag)
    {
        var code = "<DIV id=\"debugDiv\" style=\"position:absolute; background-color:white; border:black 1px solid; left:600; top:100; width:400; height:400; z-index:99;\"></DIV>";
        dynamicContainer.innerHTML += code;
        alert("MenuDropdown: debug mode.");
    }
}

MenuDropdown.prototype.addItem = function(id, parentId, title, url, url2, behaviour, childrenCountToRender, renderFlag, itemStyleClass, level, childrenCountToRenderPopup)
{
    if (this.name != null)
    {
        var item = new MenuDropdownItem(id, parentId, title, url, url2, behaviour, childrenCountToRender, renderFlag, itemStyleClass, level, childrenCountToRenderPopup);

        this.itemsMap[id] = item;
        this.items[this.items.length] = id;

        if (this.itemChildren[parentId] == null) this.itemChildren[parentId] = Array();
        this.itemChildren[parentId][this.itemChildren[parentId].length] = item;

        this._setItemProcessThroughJs(item);
    }
}

MenuDropdown.prototype._setItemProcessThroughJs = function(item)
{
    if (item != null)
    {
        //anchor
        var a = document.getElementById(this.ITEM_ID_ANCHOR_PREFIX + item.id);

        if (a != null) a.innerHTML = item.title;

        //image
        var i = document.getElementById(this.ITEM_ID_IMG_PREFIX + item.id);

        if (i != null)
        {
            var imageSrc = this.ITEM_IMG_EMPTY_SRC;

            if (item.childrenCountToRender > 0)
				{
					if (item.level < this.lastLevel)
					{
						imageSrc = this.ITEM_IMG_COLLAPSE_SRC;
					}
				}

            i.innerHTML = "<IMG src=\"" + imageSrc + "\" border=\"0\" hspace=\"1\" vspace=\"1\">";
        }

        //tr
        var tr = document.getElementById(item.id);

        if (tr != null)
        {
            tr.menu = this;
            tr.onmouseover = function() {this.menu._iMI(this, item.id, 0);};
            tr.onmouseout = function() {this.menu._iMO(this, item.id, 0);};
            tr.onclick = function() {this.menu._iC(this, item.id, 0);};
        }

        //status += item.id + status;
    }
}

MenuDropdown.prototype.init = function()
{
    if (!this.popupInitOnDemandFlag && this.name != null)
    {
        for (var i = 0; i < this.items.length; i++)
        //for (var i = 0; i < 19 && i < this.items.length; i++)
        {
            this._createPopup(this.items[i]);
        }
    }
}

//itemMouseOver (In)
MenuDropdown.prototype._iMI = function(caller, itemId, callLevel)
{
    //this.debugStr("in-" + itemId);
    var item = this.itemsMap[itemId];

    if (item != null)
    {
        this._dropTimer();

        if (callLevel == null)
        {
            var activeId = this.openedPopups[this.openedPopups.length-1];

            if (activeId != null)
            {
                if (activeId != item.parentId)
                {
                    var active = this.itemsMap[activeId];

                    if (active.parentId == itemId)
                    {
                        this._hidePopupTree(activeId);
                    }
                    else
                    {
                        this._hidePopupTree(item.parentId, false);
                    }
                }
            }
        }
        else
        {
            this._hideAllPopups();
        }

        this._itemHighlight(itemId, true, callLevel);

        this._showPopup(caller, itemId);
    }
}

//itemMouseOut (Out)
MenuDropdown.prototype._iMO = function(caller, itemId, callLevel)
{
    //this.debugStr("<B>OUT</B>-" + itemId);
    // hide selection
    this._itemHighlight(itemId, false, callLevel);

    this._setTimer();
}

MenuDropdown.prototype._itemHighlight = function(itemId, highlightFlag, callLevel)
{
    var obj = null;

    //first: find popup item
    if (callLevel == null)
    {
        obj = document.getElementById(this.ITEM_ID_PREFIX_POPUP + this.ITEM_ID_PREFIX_POPUP + itemId);
    }

    if (obj == null)
    {
        //else: find item of root
        obj = document.getElementById(itemId);
    }

    if (obj != null)
    {
        if (highlightFlag)
        {
            var highlightPrefix = this.ITEM_STYLE_PREFIX_HIGHLIGHTED;

            if (this.ITEM_STYLE_PREFIX_HIGHLIGHTED + this._getItemStyleClass(itemId) != obj.className)
            {
                obj.storedClassName = obj.className;
                obj.className = this.ITEM_STYLE_PREFIX_HIGHLIGHTED + this._getItemStyleClass(itemId);
            }
        }
        else
        {
            if (obj.storedClassName != null) obj.className = obj.storedClassName;
        }
    }
}

//itemClick
MenuDropdown.prototype._iC = function(caller, itemId, level)
{
	var item = this.itemsMap[itemId];

    if (item != null)
    {
        var newWindowUrl = "";
        var documentLocationUrl = "";

        if (item.behaviour == item.BEHAVIOUR_HOME_PAGE)
        {
            documentLocationUrl = item.url;
        }
        else if (item.behaviour == item.BEHAVIOUR_URL)
        {
            documentLocationUrl = item.url2;
        }
        else if (item.behaviour == item.BEHAVIOUR_HOME_PAGE_URL_WINDOW)
        {
            //automatically processed
        }
        else if (item.behaviour == item.BEHAVIOUR_URL_WINDOW)
        {
            newWindowUrl = item.url2;
        }
        else if (item.behaviour == item.BEHAVIOUR_FOLDING)
        {
            if (level == 0)
            {
                var children = this.itemChildren[item.id];

				if (typeof(children) != "undefined")
				{
					for (var i = 0; i < children.length; i++)
					{
						var childId = children[i].id;
						var childObj = document.getElementById(childId);

						if (childObj != null)
						{
							if (childObj.style.display == "none") childObj.style.display = "";
							else childObj.style.display = "none";
						}

						var childDivObj = document.getElementById(this.ITEM_ID_DIVIDER_PREFIX + childId);

						if (childDivObj != null)
						{
							if (childDivObj.style.display == "none") childDivObj.style.display = "";
							else childDivObj.style.display = "none";
						}
					}
				}
			}
        }

        if (newWindowUrl != "") window.open(newWindowUrl, '');
        if (documentLocationUrl != "") document.location = documentLocationUrl;
    }
}

MenuDropdown.prototype._setTimer = function()
{
    this.popupTimer = setTimeout(this.name + '._executeOnTimer()', this.TIMER_HIDE_ALL_VALUE);
}

MenuDropdown.prototype._dropTimer = function()
{
    clearTimeout(this.popupTimer);
}

MenuDropdown.prototype._executeOnTimer = function()
{
    this._hideAllPopups();
}

MenuDropdown.prototype._hideAllPopups = function()
{
    this._hidePopupTree("");
}

MenuDropdown.prototype._hidePopupTree = function(itemId, includedFlag)
{
    includedFlag = (includedFlag != null ? includedFlag : true);
    var exitFlag = (this.openedPopups.length == 0);
    var hideFlag;

    while (!exitFlag)
    {
        var activeId = this.openedPopups[this.openedPopups.length-1];
        hideFlag = true;

        if (activeId == itemId)
        {
            exitFlag = true;
            hideFlag = includedFlag;
        }

        if (hideFlag)
        {
            this._hidePopup(activeId);
            this.openedPopups.length -= 1;
            this.openedPopupsMap[itemId] = null;
        }

        if (this.openedPopups.length == 0) exitFlag = true;
    }
}

MenuDropdown.prototype._hidePopup = function(itemId)
{
    var obj = document.getElementById(this.ITEM_ID_PREFIX_POPUP + itemId);

    if (obj != null)
    {
        obj.style.display = "none";
    }
}

MenuDropdown.prototype._showPopup = function(caller, itemId)
{
    //this.debugStr("showPopup:1:" + itemId);
    if (this.openedPopups[this.openedPopups.length - 1] != itemId)
    //if (this.openedPopupsMap[itemId] == null)
    {
        var obj = document.getElementById(this.ITEM_ID_PREFIX_POPUP + itemId);
        //this.debugStr("showPopup:obj1" + obj);

        if (this.popupInitOnDemandFlag && obj == null)
        {
            this._createPopup(itemId);

            obj = document.getElementById(this.ITEM_ID_PREFIX_POPUP + itemId);
            //this.debugStr("showPopup:obj2" + obj);
        }

        if (obj != null)
        {
            //this.debugStr("showPopup:obj3:" + obj);

            //position
            if (caller != null)
            {
                //this.debugStr(caller.offsetWidth + ":" + getElementXPos(caller) + ":" + getElementYPos(caller) + "<HR>");

                obj.style.left = caller.offsetWidth + getElementXPos(caller);
                obj.style.top = getElementYPos(caller);
            }

            //visibility
            //alert(obj.className);
            obj.style.display = "";
        }

        this.openedPopups[this.openedPopups.length] = itemId;
        this.openedPopupsMap[itemId] = 1;
    }
}

MenuDropdown.prototype._getItemStyleClass = function(itemId)
{
    var itemStyleClass = this.ITEM_STYLE_PREFIX_PAGE;
    var item = this.itemsMap[itemId];

    if (item != null)
    {
        itemStyleClass = item.itemStyleClass;
    }

    return(itemStyleClass);
}

MenuDropdown.prototype._createPopup = function(itemId)
{
    //this.debugStr("createPopup:" + itemId);
    var children = this.itemChildren[itemId];
    if (children == null) children = Array();

    var item = this.itemsMap[itemId];

//    if (children.length > 0 && this.container != null && item.childrenCountToRender > 0)
	var dynamicContainer = document.getElementById(this.dynamicContainerId);

    if (dynamicContainer != null && item.childrenCountToRenderPopup > 0)
    {
        //this.debugStr("createPopup:start:"+childrenIds.length);
        var code = "";

        //div has id = "p" + itemId
        //item has id = "p" + "p" + itemId
        //because root menu has all(!!!) items with id = itemId, but some of them are hidden

        code += "<DIV id=\""+this.ITEM_ID_PREFIX_POPUP+itemId+"\" style=\"position:absolute; display:none;\">";
        //code += "<DIV id=\""+this.ITEM_ID_PREFIX_POPUP+itemId+"\" class=\"positionAbsolute invisible\">";
        code += "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" width=\""+this.width+"\">";

        for (var i = 0; i < children.length; i++)
        {
            //this.debugStr("createPopup:child:"+i);
            var child = children[i];

            if (child != null)
            {
                if (child.renderFlag)
                {
                    var itemChildren = this.itemChildren[child.id];
                    if (itemChildren == null) itemChildren = Array();
                    var imageSrc = this.ITEM_IMG_EMPTY_SRC;
                    var itemStyleClass = this._getItemStyleClass(child.id);

                    if (itemChildren.length > 0)
                    {
                        if (child.childrenCountToRender > 0)
							{
								if (child.level < this.lastLevel)
								{
									imageSrc = this.ITEM_IMG_COLLAPSE_SRC;
								}
							}

					}

                    code += "<TR id=\""+this.ITEM_ID_PREFIX_POPUP+this.ITEM_ID_PREFIX_POPUP+child.id+"\" ";
                    code += " onmouseover=\""+this.name+"._iMI(this, '"+child.id+"', null)\" ";
                    code += " onmouseout=\""+this.name+"._iMO(this, '"+child.id+"', null)\" ";
                    code += " onclick=\""+this.name + "._iC(this, '"+child.id+"', null)\" ";
                    code += " class=\"" + itemStyleClass + "\" ";
                    //code += " class=\"" + itemStyleClass + " cursorPointer\" ";
                    code += " style=\"cursor: pointer;\" ";
                    code += ">";

                    if (this.showFolderImage && this.imagePos == 'left')
                    {
                    	code += this._renderFolderImage(imageSrc);
                    }

                    code += "<TD>";
                    code += child.title;
                    code += "</TD>";

					//Folder Image
                    if (this.showFolderImage && this.imagePos == 'right')
                    {
                    	code += this._renderFolderImage(imageSrc);
                    }

                    code += "</TR>";

                    code += "<TR class=\""+this.ITEM_DIVIDER_STYLE_CLASS+"\"><TD colspan=\"2\" height=\"1\">";
                    code += "</TD></TR>\n";
                }
            }
        }

        code += "</TABLE>";
        code += "</DIV>";

        dynamicContainer = document.getElementById(this.dynamicContainerId);
        dynamicContainer.innerHTML += code;

        var obj = document.getElementById(this.ITEM_ID_PREFIX_POPUP+itemId);
    }
}

MenuDropdown.prototype._renderFolderImage = function(imageSrc)
{
	var resultBuffer = "";

	resultBuffer += "<TD valign=\"top\" height=\"16\" width=\"16\">";
	resultBuffer += "<DIV align=\"center\">";
	resultBuffer += "<IMG src=\"" + imageSrc + "\" border=\"0\" hspace=\"1\" vspace=\"1\">";
	resultBuffer += "</DIV>";
	resultBuffer += "</TD>";

	return resultBuffer;
}

MenuDropdown.prototype.debugStr = function(str)
{
    var obj = document.getElementById("debugDiv");

    if (obj != null)
    {
        obj.innerHTML = str + " " + obj.innerHTML;
    }
}

//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

function getElementXPos(elementRef)
 {
  var x = elementRef.offsetLeft;

  try
  {
      var parentRef = elementRef.offsetParent;

      while (parentRef != null)
       {
        x += parentRef.offsetLeft;
        parentRef = parentRef.offsetParent;
       }
  }
    catch(e)
    {
    }

  return x;
 }

function getElementYPos(elementRef)
 {
  var y = elementRef.offsetTop;

  try
  {
      var parentRef = elementRef.offsetParent;

      while (parentRef != null)
       {
        y += parentRef.offsetTop;
        parentRef = parentRef.offsetParent;
       }
  }
  catch(e)
  {
  }

  return y;
 }


