dojo.require("dojo.event.common");
dojo.require("dojo.event.browser");
dojo.require("dojo.html.style");

/*
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;
    dojo.addOnLoad(this, "init");
};

HelpLinks.prototype.init = function() {
    if (this._initialized) {
        return;
    }
    this._initialized = true;
    
    var categories = dojo.byId(this.config.categoryId);
    if (!categories || !this.config.categoryClass) {
        return;
    }
    
    dojo.event.connect(categories, "onclick", dojo.lang.hitch(this, this.onclickHandler));
    
    function setupHoverStates(category) {
        dojo.event.connect(category, "onmouseover", dojo.lang.hitch(this, this.onmouseoverHandler));
        dojo.event.connect(category, "onmouseout", dojo.lang.hitch(this, this.onmouseoutHandler));
    }
    dojo.lang.forEach(dojo.html.getElementsByClass(this.config.categoryClass, categories), setupHoverStates, this);
};

HelpLinks.prototype.onclickHandler = function(evt) {
    evt = dojo.event.browser.fixEvent(evt);
    var target = evt.target;
    if (!target) {
        return;
    }
    
    while (target && !dojo.html.hasClass(target, this.config.categoryClass) && target.nodeName != 'body') {
        target = target.parentNode;
    }
    if (!dojo.html.hasClass(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 = dojo.event.browser.fixEvent(evt);
    var target = evt.currentTarget;
    if (!target) {
        return;
    }
    
    while (target && !dojo.html.hasClass(target, this.config.categoryClass) && target.nodeName != 'body') {
        target = target.parentNode;
    }
    if (!dojo.html.hasClass(target, this.config.categoryClass)) {
        return;
    }
    dojo.html.addClass(target, "hover");
}

HelpLinks.prototype.onmouseoutHandler = function(evt) {
    evt = dojo.event.browser.fixEvent(evt);
    var target = evt.currentTarget;
    if (!target) {
        return;
    }
    
    var relatedTarget = evt.relatedTarget;
    while (relatedTarget && relatedTarget != target && relatedTarget.nodeName != 'body') {
        relatedTarget = relatedTarget.parentNode;
    }
    if (relatedTarget == target) {
        return;
    }
    while (target && !dojo.html.hasClass(target, this.config.categoryClass) && target.nodeName != 'body') {
        target = target.parentNode;
    }
    if (!dojo.html.hasClass(target, this.config.categoryClass)) {
        return;
    }
    dojo.html.removeClass(target, "hover");
}