﻿/// Helper method that checks for an element and if it doesn't exist
/// it appends it to the body. Allow for portability of this document.
function initElement(id)
{
    if (jQuery("#" + id).length == 0)
        jQuery('body').append("<div id='" + id + "'/>");
}

/// Helper method that initializes a dialog box.
function initDialog(id, title, width, minwidth)
{
    if (!jQuery("#" + id).is(":data(dialog)"))
    {
        jQuery("#" + id).dialog({
            "autoOpen": false,
            "draggable": true,
            "title": title,
            "width": (width == null) ? 700 : width,
            "minWidth": (minwidth == null) ? 300 : minwidth,
            "resizable": true,
            "modal": true
        });
    }
}

function getMsgbox()
{
    var msgbox = jQuery('#msgbox');
    if (msgbox.length == 0)
    {
        jQuery("body").append('<div id="msgbox" class="ui-widget" />');
        msgbox = jQuery("#msgbox");
    }
    else
    {
        msgbox.html('');
    }
    //    msgbox.css("zIndex", "10000");
    msgbox.css("width", "500px");
    msgbox.css("padding", "10px");

    msgbox.css("left", "50%");

    if (jQuery.browser.msie)
    {
        msgbox.css("position", "absolute");
        msgbox.css("top", (jQuery("body").scrollTop() + 75) + "px");
    }
    else
    {
        msgbox.css("position", "fixed");
        msgbox.css("top", "75px");
    }
    msgbox.css("margin-left", "-250px");

    msgbox.off("click");
    msgbox.jqm({ overlay: 40, modal: false });
    //$(msgbox).jqmAddClose($(msgbox));
    msgbox.jqmShow();
    return msgbox;
}

function getLoading()
{
    var loadingbox = jQuery('#loadingbox');
    if (loadingbox.length == 0)
    {
        jQuery("body").append('<div id="loadingbox" style="z-index: 100000; position: absolute; left: 45%; top: 45%; margin: 0 auto; padding: 1em 0.25em; background-color: #EEEEEE; border: 1px solid #505050; width: 10%; text-align: center;" />');
        loadingbox = jQuery('#loadingbox');
    }
    if (loadingbox.html() == '') loadingbox.html('<img src="/images/ajax-loader.gif" style="border: 0;" alt="Loading..." /> <span style="font-size: 16px; font-weight: bold; vertical-align: middle; font-variant: small-caps;">Loading...</span>');
    return loadingbox;
}

/*
* A function to be called if the request fails.
* The function is passed three arguments: The XMLHttpRequest object, a string describing the type of error that occurred and an optional exception object,
* if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".
*/
function showError(event, xhr, ajaxSettings, errorThrown)
{
    var msgbox = getMsgbox();
    var errormsg = jQuery('<div class="ui-state-error ui-corner-all" style="padding: 0pt 1em;" />');
    switch (xhr.status)
    {
        case 404:
            errormsg.append('<p>The page you\'re looking for was not found.</p>');
            break;
        case 500:
            errormsg.append("<p><span class=\"ui-icon ui-icon-alert\" style=\"float: left; margin-right: 0.3em;\"/><strong>Error:</strong></p><p>There seems to be a problem with the page you were just trying to access. An error report has been generated and will be reviewed.</p>");
            break;
        default:
            errormsg.append("<p><span class=\"ui-icon ui-icon-alert\" style=\"float: left; margin-right: 0.3em;\"/><strong>Error:</strong></p><p>An error occurred in application processing.<br /><a href=\"javascript:void(0); // Show Details\" onclick=\"jQuery(this).hide(); jQuery('#errordetails').show();\">Show Details</a></p>");
            break;
    }
    if (xhr.statusText == "error")
    {
        try
        {
            var err = eval("(" + xhr.responseText + ")");
            errormsg.append(jQuery('<pre id="errordetails" style="display: none;">' + err.Message + '</pre>'));
        } catch (e)
        {
            if (errorThrown == "")
            {
                errorThrown = "No details available.";
            }
            errormsg.append(jQuery('<pre id="errordetails" style="display: none;">' + errorThrown + '</pre>'));
        }
    }
    if (xhr.statusText == "timeout")
    {
        errormsg.append('<p id="errordetails" style="display: none;">The AJAX request timed out.</p>');
    }
    if (xhr.statusText == "parsererror")
    {
        errormsg.append('<p id="errordetails" style="display: none;">Malformed response:<br /><pre>' + xhr.responseText + '</pre></p>');
    }
    errormsg.append('<p style="text-align: right;"><a href="javascript:void(0);" onclick="jQuery(\'#msgbox\').jqmHide();">[ Close ]</a></p>');
    msgbox.append(errormsg);
}

// Shows a message of the specified type and with the 
// specified message. The types are Info, Success, Error, and Failure
function showMessage(type, value)
{
    var msgbox = getMsgbox();
    msgbox.on("click", function() { jQuery("#msgbox").jqmHide() });
    var msg;
    switch (type)
    {
        case "Info":
        case "Success":
            msg = jQuery('<div class="ui-state-highlight ui-corner-all" style="padding: 0 0.7em;" />');
            msg.append('<p><span class="ui-icon ui-icon-info" style="float: left; margin-right: 0.3em;"/><strong>' + type + '</strong></p>');
            break;
        case "Error":
        case "Failure":
        default:
            msg = jQuery('<div class="ui-state-error ui-corner-all" style="padding: 0 0.7em;" />');
            msg.append('<p><span class="ui-icon ui-icon-alert" style="float: left; margin-right: 0.3em;"/><strong>' + type + '</strong></p>');
            break;
    }
    msg.append("<p>" + value + "</p>");
    msg.append('<p style="padding: 0; margin: 0;"><span style="float: right; font-size: 8pt; font-family: sans-serif;">(Click anywhere to close this popup)</span>&nbsp;</p>');
    msgbox.append(msg);
}

var _responsehandler;

function ajax_setup()
{
    if (window["ResponseHandler"] == undefined)
    {
        jQuery.getScript("/scripts/responsehandler.js");
    }
    _responsehandler = new ResponseHandler.response(showMessage)
    jQuery.ajaxSetup({
        dataType: "xml",
        timeout: 60000, //60 seconds
        type: "POST",
        traditional: true //shallow serialization because webservices do not support extended serialization of arrays (from=1&from=5 works but from[]=1&from[]=5 does not on WebMethods)
    });
    jQuery(document).ajaxError(showError);
    jQuery(document).ajaxSuccess(function(event, xhr, ajaxOpt) { _responsehandler.handler(xhr.responseXML); });
    //add ajax loading gif
    jQuery(document).ajaxSend(function() { getLoading().show(); });
    jQuery(document).ajaxComplete(function() { getLoading().hide(); });

    //add model popup stuff
    if (typeof loadjqm != "undefined")
    {
        loadjqm();
        jQuery.jqm.params.overlayClass = "ui-widget-overlay";
        jQuery.jqm.params.modal = true;
    }
}

jQuery(function()
{
    ajax_setup();
    if (jQuery.isFunction(window["pageload"])) window["pageload"]();
});

