﻿M2 = this.M2 || {};
M2.Help = M2.Help || {};

(function() {
    var textCache = {};
    var helpTooltip;

    function getHelpTooltip() {
        if (!helpTooltip) helpTooltip = new M2.Lightbox({ width: 250 });
        return helpTooltip;
    }

    M2.Help.edit = function(key) {
        jQuery.fn.colorbox({ iframe: true, href: M2.Help.serviceLocation + '?h=' + encodeURIComponent(key), width: '500', height: '400', open: true });
        delete textCache[key];
        getHelpTooltip().hide();
        return false;
    };

    function getEditHtml(key) {
        return '<br /><a href="javascript:void(0);" onclick="return M2.Help.edit(unescape(\'' + escape(key) + '\'));"><img src="' + M2.Help.editIcon + '" style="border:0" /></a>';
    }

    M2.Help.activate = function(item, e, key, edit) {
        if (tooltip && tooltip.isVisible() && tooltip.getItem() == item) {
            tooltip.hide();
            return false;
        }

        var text = M2.Help.getText(key);

        var helpText = text.text;

        if (helpText == null && edit) {
            M2.Help.edit(key);
            return false;
        }

        if (edit) {
            helpText += getEditHtml(key);
        }

        if (text && text.type == 'Tooltip') {
            var tooltip = getHelpTooltip();

            tooltip.setHtml(helpText);
            tooltip.show(item);

        } else if (text && text.type == 'Popup') {
            jQuery.fn.colorbox({ html: helpText, width: '400', height: '400', open: true });
        }

        return false;
    };


    M2.Help.getText = function(key) {
        if (textCache[key]) return textCache[key];

        if (window.XMLHttpRequest) {
            var req = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            var req = new ActiveXObject('MSXML2.XMLHTTP.3.0')
        }
        if (req) {
            var url = M2.Help.serviceLocation + '?j=' + encodeURIComponent(key);
            req.open('POST', url, false);
            req.send();
            return textCache[key] = eval('(' + req.responseText + ')');
        }
    };


})();