// Really basic javascript menus

/*
var oldOnload = window.onload;
if (oldOnload)
    window.onload = function(e) { registerMenus(e); return oldOnload(e); };
else
    window.onload = registerMenus;
*/

/* Muffin Research ultra-deluxe getElementsByClassName(class, tag, container) {{{ */
/*
Copyright (c) 2006 Stuart Colville
http://muffinresearch.co.uk/archives/2006/04/29/getelementsbyclassname-deluxe-edition/

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/

function getElementsByClassName(strClass, strTag, objContElm) {
    strTag = strTag || "*";
    objContElm = objContElm || document;
    var objColl = (strTag == '*' && document.all) ? document.all : objContElm.getElementsByTagName(strTag);
    var arr = new Array();
    var delim = strClass.indexOf('|') != -1  ? '|' : ' ';
    var arrClass = strClass.split(delim);
    var i, j, k, l, m, n;
    for (i = 0, j = objColl.length; i < j; i++) {
        if (objColl[i].className == undefined) continue;
        var arrObjClass = objColl[i].className.split(' ');
        if (delim == ' ' && arrClass.length > arrObjClass.length) continue;
        var c = 0;
        comparisonLoop:
        for (k = 0, l = arrObjClass.length; k < l; k++) {
            for (m = 0, n = arrClass.length; m < n; m++) {
                if (arrClass[m] == arrObjClass[k]) c++;
                if (( delim == '|' && c == 1) || (delim == ' ' && c == arrClass.length)) {
                    arr.push(objColl[i]);
                    break comparisonLoop;
                }
            }
        }
    }
    return arr;
}

// To cover IE 5 Mac lack of the push method
if (!Array.prototype.push) {
    Array.prototype.push = function(value) {
        this[this.length] = value;
    }
}
/* }}} */

function addClassName(element, className) { /* {{{ */
    if (element.className)
        element.className += ' ' + className;
    else
        element.className = className;
} /* }}} */

function removeClassName(element, className) { /* {{{ */
    var classes = element.className.split(/\s+/);
    var newClassName = '';

    for (var x=0, l=classes.length; x<l; x++) {
        if (classes[x] == className)
            continue;
        if (newClassName != '')
            newClassName += ' ';
        newClassName += classes[x];
    }

    element.className = newClassName;
} /* }}} */

function getStyle(el, style) { /* {{{ */
    if (el.currentStyle)
        return el.currentStyle[style]
    else
        return document.defaultView.getComputedStyle(el, null).getPropertyValue(style)
} /* }}} */

var flyouts = [];
var dropdowns = [];

function registerMenus(e) { /* {{{ */
    if (!e) var e = window.event;

    flyouts = getElementsByClassName('flyout');
    for (var x=0, l=flyouts.length; x<l; x++) {
        flyouts[x] = new basicMenu(flyouts[x], 'flyout');
    }

    dropdowns = getElementsByClassName('dropdown');
    for (var x=0, l=dropdowns.length; x<l; x++)
        dropdowns[x] = new basicMenu(dropdowns[x], 'dropdown');
} /* }}} */

function basicMenu(element, menuType) { /* {{{ */
    this.element = element;
    this.menuType = menuType;

    this.listItems = this.element.getElementsByTagName('li');
    for (var x=0, l=this.listItems.length; x<l; x++)
        this.initListItem(this.listItems[x], menuType);
} /* }}} */

basicMenu.prototype.initListItem = function(item, menuType) { /* {{{ */
    /* Event handlers for menus {{{ */
    var thisMenu = this; /* this is a bit of a hack */
    thisMenu.toClose = null;
    thisMenu.closeTimer = null;

    function closeMenu() {
        thisMenu.toClose.subMenu.style.display = 'none';
        removeClassName(thisMenu.toClose, 'hover');
        thisMenu.toClose = null;
        thisMenu.closeTimer = null;
    }
    this.closeMenu = closeMenu;

    function enterMenu(e) {
        if (!e) var e = window.event;

        for (var x=0, l=flyouts.length; x<l; x++) {
            if (flyouts[x].toClose) {
                clearTimeout(flyouts[x].closeTimer);
                flyouts[x].closeMenu();
            }
        }
        for (var x=0, l=dropdowns.length; x<l; x++) {
            if (dropdowns[x].toClose) {
                clearTimeout(dropdowns[x].closeTimer);
                dropdowns[x].closeMenu();
            }
        }
        item.subMenu.style.display = item.originalDisplay;
        $(item.subMenu).bgiframe();
    }

    /* This takes advantage of the fact that onmouseout events get thrown for
     * the parent menu item both when you leave it, and when you leave its
     * child elements.  That's why the events are tied to the <li> and not the
     * <a> tag. */
    function leaveMenu(e) {
        this.related = (!e ? window.event.toElement : e.relatedTarget);

        if (item.contains(this.related)) {
            /* If you move to the submenu, keep it highlighted */
            if (!item.hasHoverClass) {
                addClassName(item, 'hover');
                item.hasHoverClass = 1;
            }
            return;
        }
        /* If we move anywhere else, we dont' want to keep it highlighted */
        removeClassName(item, 'hover');
        item.hasHoverClass = 0;

        if (thisMenu.toClose) {
            clearTimeout(thisMenu.closeTimer);
            closeMenu();
        }
        thisMenu.toClose = item;
        thisMenu.closeTimer = setTimeout(closeMenu, 300);
    }
    /* }}} */

    // Find if there is a submenu, if not, we don't need to do anything else
    var subMenus = item.getElementsByTagName('ul');
    if (subMenus.length <= 0) {
        // No submenu, do nothing for this item
        item.subMenu = null;
        return false;
    }

    item.subMenu = subMenus[0];
    // Give the submenu a classname so that style sheets can style it
    // differently depending on if javascript is working or not
    addClassName(item.subMenu, 'alive');
    item.originalDisplay = item.subMenu.style.display;
    if (item.originalDisplay == 'none' || item.originalDisplay == '')
        item.originalDisplay = 'block';
    item.subMenu.style.opacity = '0';
    item.subMenu.style.position = 'absolute';
    var itempos = getStyle(item, 'position');
    if (menuType == 'flyout') {
        if (itempos == 'absolute' || itempos == 'relative') {
            item.subMenu.style.left = item.clientWidth + 'px';
            item.subMenu.style.top = '0px';
        } else {
            item.subMenu.style.left = item.offsetLeft + item.clientWidth + 'px';
            item.subMenu.style.top = item.offsetTop + 'px';
        }
    } else if (menuType == 'dropdown') {
        if (itempos == 'absolute' || itempos == 'relative') {
            item.subMenu.style.left = '0px';
            item.subMenu.style.top = item.clientHeight + 'px';
        } else {
            item.subMenu.style.left = item.offsetLeft + 'px';
            item.subMenu.style.top = item.offsetTop + item.clientHeight + 'px';
        }
    }
    item.subMenu.style.display = 'none';
    item.subMenu.style.opacity = '1';

    // Find link element for hovering
    item.link = item.getElementsByTagName('a')[0];

    if (!item.contains)
        item.contains = function(node) {
            if (node == null) { return false; }
            if (node == this) { return true; }
            else { return this.contains(node.parentNode); }
        };
    // Set up event handlers
    item.onmouseover = item.onfocus = item.onactivate   = enterMenu;
    item.onmouseout  = item.onblur  = item.ondeactivate = leaveMenu;

    return true;
} /* }}} */

// TODO:
// - Use IE's onunload to unregister event handlers to be sure we don't leak memory

