var DropDown = Class.create();
Object.extend(DropDown.prototype, {
    initialize:	function(element, navId, subId, options) {
        this.element = $(element);
        options = options || {};
        this._navId  = navId;
        this._subId  = subId;
        this._navRegEx = new RegExp(navId);
        this._subRegEx = new RegExp(subId);
        Element.cleanWhitespace(this.element);
        for (var i=0; i<this.element.childNodes.length; i++) {
            var link = this.element.childNodes[i];
            if (link.tagName.toUpperCase() == 'A' && link.id.indexOf(navId) != -1) {
                var id = link.id.replace(this._navRegEx, '');
                Event.observe(link, 'mouseover', this.menuOver.bindAsEventListener(this));
                Event.observe(link, 'mouseout', this.menuOut.bindAsEventListener(this));
                Event.observe(subId + id, 'mouseover', this.menuOver.bindAsEventListener(this));
                Event.observe(subId + id, 'mouseout', this.menuOut.bindAsEventListener(this));
                Element.hide(subId + id);
                if (options.positionLeft) {
                    Position.clone(link, subId + id, { setHeight: false, setWidth: false, setTop: false });
                }
            }
        }
        this._current = null;
    },
    menuOver: function (event) {
        var id = this.getId(Event.element(event));
        if (this._current != id) {
            if (this._appearEffect) {
                this._appearEffect.cancel();
            }
            this._appearEffect = Effect.Appear(this._subId + id, { duration: 0.5 });
            this._current = id;
        }
    },
    menuOut: function (event) {
        var id = this.getId(Event.element(event));
        if (this._current == id) {
            setTimeout(function () { this.collapse(id); }.bind(this), 300);
            this._current = null;
        }
    },
    collapse: function (id) {
        if (id && this._current != id) {
            if (this._fadeEffect) {
                this._fadeEffect.cancel();
                Element.hide(this._fadeEffect.element);
            }
            this._fadeEffect = Effect.Fade(this._subId + id, { duration: 0.5 });
        }
    },
    getId: function (element) {
        while (element.tagName.toUpperCase() != 'BODY' && ! element.id.match(this._navRegEx) && ! element.id.match(this._subRegEx)) {
            element = element.parentNode;
        }
        return element.id.replace(this._navRegEx, '').replace(this._subRegEx, '');
    }
});

