﻿// ----------------------------------------------------------------------------
//  Net Applications common javascript routines used by the framework
// ----------------------------------------------------------------------------

//  Set up namespace and add all functions to namespace to prevent conflicts
NetApplications = {

    //  ----------  Ajax routines  ----------
    Ajax: {
        getRequestObject: function () {
            if (window.XMLHttpRequest) {
                return new XMLHttpRequest()
            }
            else {
                if (window.ActiveXObject) {
                    return new ActiveXObject('MSXML2.XMLHTTP.3.0');
                }
            }
        },

        getText: function (page, async, callbackFunction) {
            var xmlHttp = NetApplications.Ajax.getRequestObject();

            if (xmlHttp.overrideMimeType) { xmlHttp.overrideMimeType('text/plain') }

            if (async) {
                xmlHttp.onreadystatechange = function () {
                    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {

                        if (callbackFunction != null) {
                            callbackFunction(xmlHttp.responseText);
                        }
                    }
                }
            }

            xmlHttp.open('GET', page, async);
            xmlHttp.send(null);

            if (!async) {
                return xmlHttp.responseText
            }
        }
    },

    //  ----------  Reporting routines  ----------
    Reporting: {
        fillReportContainer: function (containerId, url) {
            NetApplications.showLoading(containerId);
            setTimeout('NetApplications.Reporting.fillReportContainer2(\'' + containerId + '\', \'' + NetApplications.setParam('qpajaxupdate', '1', url).replace(' ', '+') + '\')', 10);
        },

        fillReportContainer2: function (containerId, url) {
            $('#' + containerId).load(url);
        },

        setPod: function (containerId, url, interval) {
            try {
                if (eval(containerId)) {  // if dialog hasn't been closed
                    var xmlHttp = NetApplications.Ajax.getRequestObject();

                    if (xmlHttp.overrideMimeType) { xmlHttp.overrideMimeType('text/plain') }

                    xmlHttp.onreadystatechange = function () {
                        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                            NetApplications.Reporting.fillPod(containerId, xmlHttp.responseText, url, interval); xmlHttp = null;
                        }
                    }
                    xmlHttp.open('GET', url, true);
                    xmlHttp.send(null);
                }
            }
            catch (err) {  // upon error, retry operation
                setTimeout("NetApplications.Reporting.setPod('" + containerId + "', '" + url + "', " + interval + ")", interval);
            }
        },

        fillPod: function (containerId, html, url, interval) {
            $('#' + containerId).empty()
            $('#' + containerId).html(html)
            $('#' + containerId).animate({ opacity: 0.8 }, 150, function () { $('#' + containerId).animate({ opacity: 1 }, 150) });
            setTimeout("NetApplications.Reporting.setPod('" + containerId + "', '" + url + "', " + interval + ")", interval);
        },

        animatePod: function (containerId) {
            $('#' + containerId).animate({ opacity: 0.8 }, 150, function () { $('#' + containerId).animate({ opacity: 1 }, 150) })
        }
    },

    //  ----------  General routines  ----------

    sharedPath: function () {
        if (window.location.hostname == 'localhost' || window.location.hostname == '127.0.0.1' || window.location.hostname == '::1') {
            return "http://localhost/shared/";
        }
        else {
            return "/shared/";
        }
    },

    openDialog: function (url, title, modal, width, height) {

        if (!document.getElementById('NADialog')) {
            $('body').append('<div style="background-color:white" id="NADialog" title="' + title + '"></div>')
        }
        else {
            $('#NADialog').dialog("destroy");
        }

        $('#NADialog').html(NetApplications.Ajax.getText(url, false));
        $('#NADialog').dialog({ title: title, width: width, height: height, modal: modal });

    },

    loadPage: function (url, title) {

        if (!title) {
            title = "Loading...";
        }

        if (!document.getElementById('NADialog')) {
            $('body').append('<div style="background-color:white" id="NADialog"></div>')
        }
        else {
            $('#NADialog').dialog("destroy");
        }

        $('#NADialog').html('<center><table style="width:140px;height:36px"><tr><td style="width:36px"><div id="NALoading"></div></td><td style="vertical-align:middle;font-size:14px">&nbsp;&nbsp;&nbsp;' +
            title + '</td></tr></table>');
        $('#NADialog').dialog({ resizable: false, title: "", width: 210, height: 80, modal: false });
        $(".ui-dialog-titlebar").hide();
        $('#NALoading').show();
        window.location = url;
    },

    selectedValue: function (id) {
        return document.getElementById(id).options[document.getElementById(id).selectedIndex].value;
    },

    showHelp: function (url, width) {
        NetApplications.showHelpHTML(NetApplications.Ajax.getText(url, false));
    },

    showHelpHTML: function (html, width) {

        if (!width) {
            width = '600px';
        }

        if (!document.getElementById('NAHelpDialog')) {
            $('body').append('<div style="max-height: 700px; background-color:#f5f5f5" id="NAHelpDialog" title="Help"></div>')
        }
        else {
            $('#NAHelpDialog').dialog("destroy");
        }

        $('#NAHelpDialog').html(html);
        $('#NAHelpDialog').dialog({ modal: true, maxHeight: 700, width: width, title: '<div class="help-dialog"> Help</div>' });
    },

    getCoordinates: function (obj) {
        var newObj = new Object();

        newObj.x = obj.offsetLeft;
        newObj.y = obj.offsetTop;
        newObj.width = obj.offsetWidth;
        newObj.height = obj.offsetHeight;
        theParent = obj.offsetParent;

        while (theParent != null) {
            newObj.y += theParent.offsetTop;
            newObj.x += theParent.offsetLeft;
            theParent = theParent.offsetParent;
        }

        return newObj;
    },

    getParam: function (key, query) {
        if (!query)
            query = window.location.search;
        var re = new RegExp("[?|&]" + key + "=(.*?)&");
        var matches = re.exec(query + "&");
        if (!matches || matches.length < 2)
            return "";
        return decodeURIComponent(matches[1].replace("+", " "));
    },

    setParam: function (key, value, query, doNotEncode) {

        query = query || window.location.search;

        if (query.indexOf('?') > -1) {
            var q = query + "&";
        }
        else {
            var q = query + "?";
        }

        var re = new RegExp("[?|&]" + key + "=.*?&");
        if (!re.test(q))
            q += key + "=" + (doNotEncode ? value : encodeURI(value));
        else
            q = q.replace(re, "&" + key + "=" + (doNotEncode ? value : encodeURIComponent(value)) + "&");
        q = q.fwTrimStart("&").fwTrimEnd("&");
        return q;
    },

    showLoading: function (containerId, top, left) {
        coords = NetApplications.getCoordinates(document.getElementById(containerId));
        var divTag = document.createElement("div");
        divTag.style.height = '55px'; divTag.style.width = '130px';
        divTag.innerHTML = '<table style="padding-top:10px;padding-left:10px;height:35px"><tr><td class="ajax-loader" style="width:36px"></td><td style="vertical-align:middle;font-size:14px">&nbsp;&nbsp;&nbsp;Loading...</td></tr></table>';
        divTag.style.borderWidth = '1px';
        divTag.style.borderColor = 'black';
        divTag.style.borderStyle = 'solid';
        divTag.style.position = 'absolute';
        divTag.style.display = 'block';
        divTag.style.backgroundColor = 'white';

        if (top) {
            divTag.style.top = top + 'px';
        }
        else {
            divTag.style.top = coords.y + parseInt(coords.height / 2 - 25) + 'px';
        }

        if (left) {
            divTag.style.left = left + 'px';
        }
        else {
            divTag.style.left = coords.x + parseInt(coords.width / 2 - 65) + 'px';
        }

        document.getElementById(containerId).appendChild(divTag);
    },

    //  Required function so dialogs can change the URL of the parent
    changeUrl: function (url) {
        document.location = url;
    },

    //  Cross-browser event handler
    attachEvent: function (name, event, fn) {
        var el = document.getElementById(name);

        if (el.addEventListener) {
            el.addEventListener(event, fn, false);
        } else if (el.attachEvent) {
            el.attachEvent('on' + event, fn);
        }
    },

    //  ----------  Lightweight context menus used in the framework (Web.UI.ContextMenu.cs)  ----------

    ContextMenus: {
        activeMenu: '',
        inMenu: false,

        menuMouseOver: function (id) {
            NetApplications.ContextMenus.inMenu = true;
            var m = eval('fwContextMenu_' + id), p = document.getElementById(m.parentElementId);

            if (NetApplications.ContextMenus.activeMenu != '') {
                document.getElementById(NetApplications.ContextMenus.activeMenu).style.display = 'none'
            }
            NetApplications.ContextMenus.activeMenu = m.parentElementId + '_cmenu';

            if (document.getElementById(m.parentElementId + '_cmenu') == null) {
                var divTag = document.createElement("div");
                divTag.id = m.parentElementId + '_cmenu';
                if (m.width) { divTag.style.width = m.width + 'px' };
                divTag.className = "context-menu";
                var h = '';

                var noBottom = '';
                for (var i = 0; i < m.items.length; i++) {
                    if (i == m.items.length - 1) { noBottom = ';border-bottom:none' } else { noBottom = '' }

                    if (m.items[i].href.substr(0, 11) == 'javascript:') {
                        h += '<a onclick="document.getElementById(NetApplications.ContextMenus.activeMenu).style.display=\'none\';' + m.items[i].href.substr(11) + '" style=\"text-decoration:none\" href=\"#\"><div class=context-menu-row style="cursor:pointer' + noBottom + '" onmouseover="this.className=\'context-menu-row-highlighted\'" onmouseout="this.className=\'context-menu-row\'">' +
                  m.items[i].label + '</div></a>';
                    }
                    else {
                        h += '<a onclick="document.getElementById(NetApplications.ContextMenus.activeMenu).style.display=\'none\'" style=\"text-decoration:none\" href=\"' + m.items[i].href + '\"><div class=context-menu-row style="cursor:pointer' + noBottom + '" onmouseover="this.className=\'context-menu-row-highlighted\'" onmouseout="this.className=\'context-menu-row\'">' +
                  m.items[i].label + '</div></a>';
                    }
                }

                divTag.innerHTML = h;
                divTag.style.position = 'absolute';
                divTag.style.display = 'none';
                divTag.onmouseover = function () { NetApplications.ContextMenus.inMenu = true };
                divTag.onmouseout = function () { NetApplications.ContextMenus.menuMouseOut() };
                document.body.appendChild(divTag);
            }
            var e = document.getElementById(m.parentElementId + '_cmenu');
            coords = NetApplications.getCoordinates(p);

            if (m.align != 'left') {
                e.style.left = coords.x + coords.width + parseInt(m.offsetX) + 'px';
            } else {
                e.style.left = coords.x + parseInt(m.offsetX) + 'px';
            }
            e.style.top = coords.y + coords.height + parseInt(m.offsetY) + 'px';
            e.style.display = 'block';
        },

        menuMouseOut: function () {
            NetApplications.ContextMenus.inMenu = false;
            setTimeout('NetApplications.ContextMenus.menuDeactivate()', 250);
        },

        menuDeactivate: function () {
            if (!NetApplications.ContextMenus.inMenu && NetApplications.ContextMenus.activeMenu != "") {
                document.getElementById(NetApplications.ContextMenus.activeMenu).style.display = 'none'
            }
        },

        createContextMenu: function (m) {
            var p = document.getElementById(m.parentElementId);
            eval('fwContextMenu_' + m.parentElementId + '=m');
            p.onmouseover = function () { NetApplications.ContextMenus.menuMouseOver(m.parentElementId) };
            p.onmouseout = function () { NetApplications.ContextMenus.menuMouseOut() };
        }
    }
}

String.prototype.fwTrimEnd = function(c) {
    if (c)        
        return this.replace(new RegExp(c.fwEscapeRegExp() + "*$"), '');
    return this.replace(/\s+$/, '');
}
String.prototype.fwTrimStart = function(c) {
    if (c)
        return this.replace(new RegExp("^" + c.fwEscapeRegExp() + "*"), '');
    return this.replace(/^\s+/, '');
}
String.prototype.fwEscapeRegExp = function() {
    return this.replace(/[.*+?^${}()|[\]\/\\]/g, "\\$0");
};



