﻿function sleep(milliSeconds) {
    var startTime = new Date().getTime(); // get the current time
    while (new Date().getTime() < startTime + milliSeconds); // hog cpu
}

namespace("app.random");

app.random.newShortGuid = function randomStringGenerator(charCount) { var S4 = function () { return (((1 + Math.random()) * 0x10000) | 0).toString(16); }; return (S4()); }
app.random.newGuid = function guidGenerator() { var S4 = function () { return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1); }; return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4()); }

namespace("app.ui");

app.ui.elementExists = function (ElementId) {
    var obj = $("#" + ElementId);
    if (obj.length > 0) {
        return true;
    }
    return false;
};

app.ui.setbuttons = function () {
    // enable the buttons
    log.debug("app.ui.setbuttons()");
    $("button, .button").button();
    $("button[data-icon=up]").button({ icons: { primary: 'ui-icon-arrow-1-n' }, text: false });
    $("button[data-icon=down]").button({ icons: { primary: 'ui-icon-arrow-1-s' }, text: false });
    $("button[data-icon=delete]").button({ icons: { primary: 'ui-icon-trash' }, text: false });
    $("button[data-icon=home_no]").button({ icons: { primary: 'ui-icon-home' }, text: false });
    $("button[data-icon=home_yes]").button({ icons: { primary: 'ui-icon-home' }, text: false, disabled: true });
    $("button:contains('Save')").button({ icons: { primary: 'ui-icon-disk' }, text: true });
    $("button:contains('Help')").button({ icons: { primary: 'ui-icon-help' }, text: true });
    $("button:contains('Add')").button({ icons: { primary: 'ui-icon-plus' }, text: true });
    $("button:contains('Refresh')").button({ icons: { primary: 'ui-icon-refresh' }, text: true });
    $("button:contains('Edit')").button({ icons: { primary: 'ui-icon-pencil' }, text: true });
    $("button:contains('Change')").button({ icons: { primary: 'ui-icon-pencil' }, text: true });
    $("button:contains('Delete')").button({ icons: { primary: 'ui-icon-trash' }, text: true });
    $("button:contains('Remove')").button({ icons: { primary: 'ui-icon-trash' }, text: true });
    $("button:contains('Details')").button({ icons: { primary: 'ui-icon-document' }, text: true });
    $("button:contains('Search')").button({ icons: { primary: 'ui-icon-search' }, text: true });
    $("button:contains('Disable')").button({ icons: { primary: 'ui-icon-cancel' }, text: true });
    $("button:contains('Cancel')").button({ icons: { primary: 'ui-icon-close' }, text: true });
    $("button:contains('Enable')").button({ icons: { primary: 'ui-icon-check' }, text: true });
    $("button:contains('Dial')").button({ icons: { primary: 'ui-icon-check' }, text: true });
    $("button:contains('email')").button({ icons: { primary: 'ui-icon-mail-closed' }, text: true });
}

app.ui.settabs = function () {
    // enable the tabs
    log.debug("app.ui.settabs()");
    $(".tabs").tabs();
}

app.ui.popup = function (elementId, title1) {
    $("#" + elementId).dialog({
        modal: true,
        title: title1,
        resizable: true
    });
};

app.ui.pleasewait = function (selector, text) {
    var html1 = "<div style='padding: 8px 8px 8px 8px; vertical-align: middle; font-family: Trebuchet MS; font-size: 14px; font-weight: bold; color: #336699; text-align: center; width: 95%; height: 40px;'>";
    html1 += "<img src='/images/pleasewait1.gif' alt='please wait' style='vertical-align: middle; margin-right: 10px;' />";
    if (text != undefined)
        html1 += text;
    else
        html1 += "Please wait...";
    html1 += "</div>";
    $(selector).html(html1);
};

app.ui.pleasewaitInline = function (selector, text) {
    var html1 = "<div style='padding: 0px; vertical-align: middle; font-weight: bold; color: #336699; display: inline-block;'>";
    html1 += "<img src='/images/pleasewait1.gif' alt='please wait' style='vertical-align: middle; margin-right: 10px;' />";
    html1 += text;
    html1 += "</div>";
    $(selector).html(html1);
};

app.ui.errornotice = function (selector) {
    var html1 = "<div style='padding: 8px 8px 8px 8px; vertical-align: middle; font-family: Trebuchet MS; font-size: 14px; font-weight: bold; color: #336699; text-align: center; width: 95%; height: 40px;'>";
    html1 += "<img src='/images/error_notice.gif' height='32' width='32' alt='please wait' style='vertical-align: middle; margin-right: 10px;' />";
    html1 += "An error has occurred!";
    html1 += "</div>";
    $(selector).html(html1);
};

app.ui.loadcontent = function (selector1, url1) {
    $.ajax({
        beforeSend: function () {
            app.ui.pleasewait(selector1);
        },
        url: url1,
        cache: false,
        success: function (html) {
            $(selector1).html(html);
        },
        timeout: 10000,
        error: function () {
            app.ui.errornotice(selector1);
        }
    });
};

app.ui.initializeTinyTips = function () {
    $(".helptip").each(function (i) {
        // only initialize the tips once
        if ($(this).attr('loaded') == null) {
            var helptipid = $(this).attr("data-helptipid");
            var contents = $("#helptipid_" + helptipid).html();
            $(this).attr('title', contents);
            $(this).attr('loaded', 0);
            $(this).tinyTips('title');
        }
    });
    //$('.helptip').tinyTips('title');
}

var allowUiInitialize = true;

app.ui.reset = function () {
    allowUiInitialize = true;
    app.ui.initialize();
};
app.ui.initialize = function () {
    if (allowUiInitialize) {
        log.debug("Executing 'app.ui.initialize'");
        app.ui.setbuttons();
        app.ui.settabs();
        app.ui.initializeTinyTips();
        app.ui.initializeHelp();
    }
    // set this to false to prevent it from running twice in the same page display
    allowUiInitialize = false;
};

app.ui.initializeHelp = function () {
    $("button.help").live('click', function (event) {
        var helpid = $(this).attr("data-helpid");
        if (helpid != undefined)
            app.ui.ajax.help(helpid);
        else {
            var helpurl = $(this).attr("data-helpurl");
            if (helpurl != undefined)
                app.ui.ajax.helpByUrl(helpurl);
            else
                app.ui.ajax.help('1000000000');
        }
    });
    $(".MenuItemHelp").live('click', function (event) {
        var helpid = $(this).attr("data-helpid");
        app.ui.ajax.help(helpid);
        return false;
    });
    $(".TextHelpLink").live('click', function (event) {
        var helpid = $(this).attr("data-helpid");
        app.ui.ajax.help(helpid);
        return false;
    });
};

app.ui.getalertmessages = function () {

    // Add Organization Url
    var onSuccess = function (msg) {
        try {
            for (var message1 in msg.Data) {
                // get the date/time of the alert
                var date1 = new Date(parseInt(msg.Data[message1].DateTimeSent.substr(6)));
                // get the category of the alert
                if (msg.Data[message1].Category != undefined) {
                    var category1 = msg.Data[message1].Category;
                }
                else {
                    // if no category defined; set default
                    category1 = "info";
                }
                switch (category1) {
                    case "Error":
                    case "error":
                        $.pnotify({
                            pnotify_title: msg.Data[message1].Title,
                            pnotify_type: 'error',
                            pnotify_text: msg.Data[message1].Body + "<br />" + date1.formatDate("MM/dd/yyyy hh:mm t")
                        });
                        break;
                    case "Mail":
                    case "mail":
                        $.pnotify({
                            pnotify_title: msg.Data[message1].Title,
                            pnotify_notice_icon: 'picon picon-mail-unread-new',
                            pnotify_text: msg.Data[message1].Body + "<br />" + date1.formatDate("MM/dd/yyyy hh:mm t")
                        });
                        break;
                    default:
                        $.pnotify({
                            pnotify_title: msg.Data[message1].Title,
                            pnotify_text: msg.Data[message1].Body + "<br />" + date1.formatDate("MM/dd/yyyy hh:mm t")
                        });
                        break;
                }
            }
        }
        catch (err) {
        }
    };
    $.ajax({
        url: "/AlertMessages/ShowNewMessages",
        success: onSuccess
    });
};

// set the interval in which the client polls for alter messages
//setInterval("app.ui.getalertmessages()", 10000);

app.ui.openPrintWindow = function (title1, body1) {
    var thePopup = window.open("", "Print", "menubar=0,location=0,resizable=0,width=0,height=0");
    thePopup.document.writeln('<html>'
    + '<head>'
    + '<title>' + title1 + '</title>'
    + '<script>'
    + 'window.print();'
    + '</' + 'script>'
    + '</head>'
    + '<body onLoad="self.focus()">'
    + body1
    + '</body></html>');
    thePopup.document.close();
    thePopup.close();
}

app.ui.openPrintWindowUrl = function (url) {
    var thePopup = window.open(url, "Print", "menubar=0,location=0,resizable=0,width=0,height=0");
}

app.ui.setDialogOptions = function (elementId, options) {
    $(elementId).closest(".ui-dialog-content").dialog("option", options);
    $(elementId).closest(".ui-dialog-content").dialog("option", { position: "center" });
}
app.ui.enableDialogSuccessOnClose = function (elementId, options) {
    var close = $(elementId).closest(".ui-dialog-content").dialog("option", "close");
    var success = $(elementId).closest(".ui-dialog-content").dialog("option", "success");
    var newClose = function () {
        success(); close();
    }
    $(elementId).closest(".ui-dialog-content").dialog("option", { close: newClose });
}
app.ui.closeDialog = function (elementId, options) {
    $(elementId).closest(".ui-dialog-content").dialog("close");
}

namespace("app.ui.ajax");

app.ui.ajax.dialog = function (url, options) {
    var newElementId = 'div-' + app.random.newShortGuid();
    if (app.ui.elementExists(newElementId) == false)
        $('body').append('<div id="' + newElementId + '"></div>')
    app.ui.pleasewait("#" + newElementId);
    if (options == null)
        options = {};
    options.close = function () { $("#" + newElementId).remove(); };
    options.cache = false;
    options.modal = true;
    $("#" + newElementId).dialog(options);
    $("#" + newElementId).load(url);
};

app.ui.ajax.help = function (id, options) {
    var newElementId = 'div-helpwindow';
    if (app.ui.elementExists(newElementId) == false)
        $('body').append('<div id="' + newElementId + '"></div>')
    else {
        $("#" + newElementId).dialog('close');
        $("#" + newElementId).remove();
        $('body').append('<div id="' + newElementId + '"></div>')
    }
    app.ui.pleasewait("#" + newElementId);
    if (options == null)
        options = {};
    options.close = function () { $("#" + newElementId).remove(); };
    options.cache = false;
    options.modal = true;
    options.title = "Help";
    $("#" + newElementId).dialog(options);
    $("#" + newElementId).load("/help/" + id);
};

app.ui.ajax.helpByUrl = function (url, options) {
    var newElementId = 'div-helpwindow';
    if (app.ui.elementExists(newElementId) == false)
        $('body').append('<div id="' + newElementId + '"></div>')
    else {
        $("#" + newElementId).dialog('close');
        $("#" + newElementId).remove();
        $('body').append('<div id="' + newElementId + '"></div>')
    }
    app.ui.pleasewait("#" + newElementId);
    if (options == null)
        options = {};
    options.close = function () { $("#" + newElementId).remove(); };
    options.cache = false;
    options.modal = true;
    options.title = "Help";
    $("#" + newElementId).dialog(options);
    $("#" + newElementId).load("/help/?url=" + url);
};

app.ui.initializeHelpWindow = function () {

    // define the dialog window properties
    //var windowHeight = 340;
    var windowHeight = null;
    var windowWidth = 560;

    if ($(".help .contents").attr("height") != undefined)
        windowHeight = $(".help .contents").attr("height");
    if ($(".help .contents").attr("width") != undefined)
        windowWidth = $(".help .contents").attr("width");

    var options = { width: windowWidth };
    if (windowHeight != null)
        options.height = windowHeight;
    $("#div-helpwindow").closest(".ui-dialog-content").dialog("option", options);
    $("#div-helpwindow").closest(".ui-dialog-content").dialog("option", { position: "center" });

    $("div.help a").die();
    $("div.help a").live('click', function (event) {
        var url = $(this).attr("href");
        app.ui.ajax.helpbyurl(url);
        return false;
    });

};

app.ui.ajax.helpbyurl = function (url, options) {
    var newElementId = 'div-helpwindow';
    if (app.ui.elementExists(newElementId) == false)
        $('body').append('<div id="' + newElementId + '"></div>')
    else {
        $("#" + newElementId).dialog('close');
        $("#" + newElementId).remove();
        $('body').append('<div id="' + newElementId + '"></div>')
    }
    app.ui.pleasewait("#" + newElementId);
    if (options == null)
        options = {};
    options.close = function () { $("#" + newElementId).remove(); };
    options.cache = false;
    options.modal = true;
    options.title = "Help";
    $("#" + newElementId).dialog(options);
    $("#" + newElementId).load(url);
};

$(".linkArea").live('click', function () {
    $(window.location).attr('href', $(this).attr('data-url'));
});

$(".linkButton").live('click', function () {
    $(window.location).attr('href', $(this).attr('data-url'));
});

$.ajaxSetup({
    success: function () {
        log.debug("Allow 'app.ui.initialize' to execute!");
        allowUiInitialize = true
    }
});
