﻿// ----------------------------------------------------------------------------
//  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);
        },

        ajaxUpdate: function (data) {
            NetApplications.Ajax.getText('/common/pages/updatereport?' + data + '&tks=' + new Date().getTime(), true);
        },

        setPod: function (podId, url, interval) {

            try {
                if (eval('fwPod' + podId)) {  // if dialog hasn't been closed

                    $('#fwPod' + podId).html('<div style="padding:20%;text-align:center"><center><img src="' + NetApplications.sharedPath() + 'images/ajax-loader.gif"><br>Loading...</center></div>');

                    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(podId, xmlHttp.responseText, url, interval); xmlHttp = null;
                        }
                    }
                    xmlHttp.open('GET', url, true);
                    xmlHttp.send(null);
                }
            }
            catch (err) {  // upon error, retry operation
                setTimeout("NetApplications.Reporting.setPod(" + podId + ", '" + url + "', " + interval + ")", interval);
            }
        },

        fillPod: function (podId, html, url, interval) {

            $('#fwPod' + podId).empty();
            $('#fwPod' + podId).html(html);
            $('#fwPod' + podId).animate({ opacity: 0.8 }, 150, function () { $('#fwPod' + podId).animate({ opacity: 1 }, 150) });

            if (interval > 0) {
                setTimeout("NetApplications.Reporting.setPod(" + podId + ", '" + url + "', " + interval + ")", interval);
            }
        },

        animatePod: function (podId) {
            $('#fwPod' + podId).animate({ opacity: 0.8 }, 150, function () { $('#fwPod' + podId).animate({ opacity: 1 }, 150) })
        }
    },

    //  ----------  General routines  ----------
    isNumber: function (n) {
        return !isNaN(parseFloat(n)) && isFinite(n);
    },

    validDate: function (date) {

        if (date == undefined) { return true; }

        // regular expressions to match required date format
        var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
        var re2 = /^\d{1,2}\-\d{1,2}\-\d{4}$/;
        var re3 = /^\d{1,2}\/\d{1,2}\/\d{2}$/;
        var re4 = /^\d{1,2}\-\d{1,2}\-\d{2}$/;
        var re5 = /^\d{4}\-\d{1,2}\-\d{1,2}$/;

        if (date != '' && !date.match(re) && !date.match(re2) && !date.match(re3) && !date.match(re4) && !date.match(re5)) {
            return false;
        }
        return true;
    },

    validEmail: function (email) {
        if (email != '' && (email.indexOf('@') <= 0 || email.indexOf('.') <= 0)) {
            return false;
        }
        return true;
    },

    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/";
        }
    },

    closeDialog: function () {
        if (document.getElementById('NADialog')) {
            $('#NADialog').dialog('close');
        }
    },

    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...";
        }

        document.body.style.cursor = 'wait';
        window.location = url;
    },

    selectedValue: function (id) {
        return document.getElementById(id).options[document.getElementById(id).selectedIndex].value;
    },

    showHelp: function (url, title, width, height) {
        NetApplications.showHelpHTML(NetApplications.Ajax.getText(url, false), title, width, height);
    },

    showHelpHTML: function (html, title, width, height) {

        if (!width) {
            width = '600px';
        }

        if (!height) {
            height = '300px';
        }

        if (!title) {
            title = 'Help';
        }

        if (!document.getElementById('NAHelpDialog')) {
            $('body').append('<div style="background-color:#f5f5f5" id="NAHelpDialog" title="Help"></div>')
        }
        else {
            $('#NAHelpDialog').dialog("destroy");
        }

        $('#NAHelpDialog').html(html);
        $('#NAHelpDialog').dialog({ buttons: { "OK": function () { $(this).dialog("close"); } }, modal: false, height: height, width: width, title: '<div class="help-dialog">' + title + '</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("+", " "));
    },

    stripParam: function (key, query) {
        if (!query)
            query = window.location.search;

        var pos2, pos = query.indexOf('?' + key + '='), delim = '?';

        if (pos == -1) {
            delim = '&';
            pos = query.indexOf('&' + key + '=');
        }

        if (pos > -1) {
            pos2 = query.indexOf('&', pos + 1);

            if (pos2 == -1) {
                pos2 = query.indexOf('#', pos + 1);
            }

            if (pos2 == -1) {
                query = query.substr(0, pos);
            }
            else {
                query = query.substr(0, pos) + delim + query.substr(pos2 + 1);
            }
        }

        return query;
    },

    setParam: function (key, value, query, doNotEncode) {

        query = query || window.location.search;

        query = NetApplications.stripParam(key, query);
        var anchor = '';

        if (query.indexOf('#') > -1) {
            anchor = query.substr(query.indexOf('#'));
            query = query.substr(query, query.indexOf('#'));
        }

        if (query.indexOf('?') > -1 || query.indexOf('&') > -1) {
            return query + "&" + key + '=' + (doNotEncode ? value : encodeURI(value)) + anchor;
        }
        else {
            return query + "?" + key + '=' + (doNotEncode ? value : encodeURI(value)) + anchor;
        }
    },

    showLoading: function (containerId, top, left) {
        coords = NetApplications.getCoordinates(document.getElementById(containerId));
        var divTag = document.createElement("div");
        divTag.style.height = '57px'; divTag.style.width = '140px';
        divTag.innerHTML = '<table style="margin-top:10px;margin-left:10px;height:55px"><tr><td class="ajax-loader" style="width:36px"></td>' +
            '<td style="vertical-align:top;padding-top:4px;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) + ';return false;" 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 = m.position;
                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() };
        }
    }
}
