/*
Config is of the form:
{
     categoryId: "id of the help topic categories",
     categoryClass: "CSS class of the help topic element"
}
*/
HelpLinks = function(config) {
    this.config = config;
    Event.onDomReady(this.init.bind(this));
};

HelpLinks.prototype.init = function() {
    if (this._initialized) {
        return;
    }
    this._initialized = true;
    
    var categories = $(this.config.categoryId);
    if (!categories || !this.config.categoryClass) {
        return;
    }
    
    Event.observe(categories, 'click', this.onclickHandler.bind(this));
    
    function setupHoverStates(category) {
        Event.observe(category, 'mouseover', this.onmouseoverHandler.bind(this));
        Event.observe(category, 'mouseout', this.onmouseoutHandler.bind(this));
    }
    Element.queryAll(categories, '.'+this.config.categoryClass).forEach(setupHoverStates, this);
};

HelpLinks.prototype.onclickHandler = function(evt) {
    evt = Event.fixEvent(evt);
    var target = evt.target;
    if (!target) {
        return;
    }
    
    while (target && !Element.hasClassName(target, this.config.categoryClass) && target.nodeName != 'body') {
        target = target.parentNode;
    }
    if (!Element.hasClassName(target, this.config.categoryClass)) {
        return;
    }
    var link = target.getElementsByTagName('a');
    if (link && link.length > 0) {
        window.location = link[0].href;
    }
}

HelpLinks.prototype.onmouseoverHandler = function(evt) {
    evt = Event.fixEvent(evt);
    var target = evt.currentTarget;
    if (!target) {
        return;
    }
    
    while (target && !Element.hasClassName(target, this.config.categoryClass) && target.nodeName != 'body') {
        target = target.parentNode;
    }
    if (!Element.hasClassName(target, this.config.categoryClass)) {
        return;
    }
    Element.addClassName(target, "hover");
}

HelpLinks.prototype.onmouseoutHandler = function(evt) {
    evt = Event.fixEvent(evt);
    var target = evt.currentTarget;
    if (!target || !target.nodeName || !Element || !Element.hasClass || !this.config || !this.config.categoryClass) {
        return;
    }
    
    var relatedTarget = evt.relatedTarget;
    while (relatedTarget && relatedTarget != target && relatedTarget.nodeName != 'body') {
        relatedTarget = relatedTarget.parentNode;
    }
    if (relatedTarget == target) {
        return;
    }
    while (target && !Element.hasClassName(target, this.config.categoryClass) && target.nodeName != 'body') {
        target = target.parentNode;
    }
    if (!Element.hasClassName(target, this.config.categoryClass)) {
        return;
    }
    Element.removeClassName(target, "hover");
}
