// This js attaches glossary popups to each of the terms defined below.
(function($) {

    var HIGHLIGHT_TERMS = {
        "\\svikrell" : "Vikrell&amp;reg;",
        "\\scleancoat" : "CleanCoat&amp;reg;"
    };

    // Sitewide glossary popups
    $(document).ready(function() {
        // Form a regular expression to find the terms to highlight
        var regexStr = "";
        for (var key in HIGHLIGHT_TERMS) {
            if (regexStr.length > 0) {
                regexStr = regexStr + "|";
            }
            regexStr = regexStr + "(" + key +  ")";
        }
        var regex = new RegExp(regexStr, "gi");

        // Find all the text nodes in the document and replace the glossary terms into highlighted terms
        // Text nodes are nodeType = 3
        $("p, li").contents().filter(function() {return this.nodeType == 3}).each(function() {
            var text = this.nodeValue;
            var parent = this.parentNode;
            var nodeChildren = [];

            var prevIndex = 0;
            var match = regex.exec(text);
            while (match != null) {
                var matchTerm = match[0];
                var index = regex.lastIndex - matchTerm.length;

                var termKey = null;
                var count = 1;
                for (var value in HIGHLIGHT_TERMS) {
                    if (match[count] != null && $.trim(match[count]).length > 0) {
                        termKey = HIGHLIGHT_TERMS[value];
                        break;
                    }
                    count = count + 1;
                }

                var prevText = text.substring(prevIndex, index);
                if (matchTerm.match("^\\s")) {
                    prevText =  prevText + " ";
                }
                nodeChildren.push(document.createTextNode(prevText));
                nodeChildren.push($('<span class="glossaryTermPopup" rel="' + termKey + '">' + matchTerm + '</span>').get(0))
                if (matchTerm.match("\\s$")) {
                    nodeChildren.push(document.createTextNode(" "));
                }

                regex.lastIndex = prevIndex = index + matchTerm.length;
                match = regex.exec(text);
                break;
            }
            nodeChildren.push(document.createTextNode(text.substring(prevIndex)));
            $(this).replaceWith(nodeChildren);
        });

        $(".glossaryTermPopup").live("mouseover", function() {
            var term = $(this).attr("rel");
            if (!term || term.length == 0) {
                term = $(this).attr("title");
            }
            if (!term || term.length == 0) {
                term = $(this).text();
            }
            if (term && term.length > 0) {
                Sterling.openGlossaryTermPopup(term, this);
            }
            return false;
        });
        $(".glossaryTermPopup").live("mouseout", function() {
            Sterling.closeGlossaryTermPopup();
            return false;
        });
    });

    var origContent;
    var isOpen = false;
    Sterling.openGlossaryTermPopup = function(term, anchorElem) {
        origContent = $("#overlay #overlay-content").clone(true);
        $("#overlay #overlay-content").empty();

        var position = function() {
            var position = $(anchorElem).position();
            if ($("#overlay").height() + position.top > $(window).height() + $(window).scrollTop() - 40) {
                $("#overlay").css("top", (position.top - $("#overlay").height()) + "px");
            } else {
                $("#overlay").css("top", (position.top + 15) + "px");
            }
            if ($("#overlay").width() + position.left > $("#main").width() + 150) {
                $("#overlay").css("left", (position.left - $("#overlay").width() + $(anchorElem).width()) + "px");
            } else {
                $("#overlay").css("left", (position.left + 15) + "px");
            }
            //$("#overlay").css("left", (position.left + 15) + "px");
        }

        // Get the glossary data
        $.ajax({
            type : 'GET',
            dataType : 'json',
            url : '/ajax/glossary-ajax',
            data : { term : term },
            success : function(data) {
                if (data.length == 0) {
                    $("#overlay #overlay-content #overlay-definition").empty().html('<strong>Error</strong><p>Could not retrieve the definition for this term</p>');
                    return;
                }
                for (var key in data) {
                    var definition = data[key];
                    $("#overlay #overlay-content #overlay-definition").empty().html('<strong>' + key + '</strong><p>' + definition + '</p>');
                    break;
                }
                position();
            },
            error : function() {
                $("#overlay #overlay-content #overlay-definition").empty().html('<strong>Error</strong><p>Could not retrieve the definition for this term</p>');
                position();
            }
        });

        // Setup the overlay
        $("#overlay #overlay-content").addClass("glossary-overlay");
        $("#overlay #overlay-content").html('<div id="overlay-definition"><img src="/common/images/loading.gif"/></div>');
        //$("#overlay #overlay-content").append('<img style="top:0px;" width="48" height="11" border="0" alt="Close Definition" class="glossary-close" src="/common/images/btn-glossary-close.png"/>');

        $("img.glossary-close").click(function() {
            Sterling.closeGlossaryTermPopup();
            return false;
        });
        $(document).bind("click.closeGlossary", function(event) {
            if ($(event.target).parents("#overlay").size() == 0) {
                Sterling.closeGlossaryTermPopup();
                return false;
            }
        });
        /*
         $("#overlay-content #printDefinitionButton").click(function() {
         popPrintWindowForSingleDefinition();
         return false;
         });
         */

        $("#overlay").show();
        position();
        isOpen = true;
    }

    Sterling.closeGlossaryTermPopup = function() {
        if (isOpen) {
            $("#overlay").hide();
            $("#overlay #overlay-content").replaceWith(origContent);
            $(document).unbind("click.closeGlossary");
            isOpen = false;
        }
    }
})(jQuery);

