﻿/// 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)
{
    jQuery("#" + id).dialog({
        "autoOpen": false,
        "bgiframe": true,
        "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.show();
    $(msgbox).jqm({ overlay: 30 });
    $(msgbox).jqmAddClose($(msgbox));
    $(msgbox).jqmShow();
    msgbox.click(function() { jQuery(this).fadeOut(500); });
    return msgbox;
}

function getLoading()
{
    var loadingbox = jQuery('#loadingbox');
    if (loadingbox.length == 0)
    {
        jQuery("body").append('<div id="loadingbox" style="z-index: 100000; position: fixed; top: 0px; left: 0px; padding: .25em; background-color: #EEEEEE; border-bottom: 1px solid #505050; border-right: 1px solid #505050;" />');
        loadingbox = jQuery('#loadingbox');
    }
    if (loadingbox.html() == '') loadingbox.html('<img src="/images/ajax-loader.gif" style="border: 0;" alt="Loading..." />');
    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".
* Typically only one of textStatus or errorThrown will have info
*/
function showError(xhr, textStatus, errorThrown)
{
    var msgbox = getMsgbox();
    if (textStatus == "timeout" || textStatus == "error" || textStatus == "parsererror")
    {
        var errormsg = jQuery('<div class="ui-state-error ui-corner-all" style="padding: 0pt 1em;" />');
        msgbox.append(errormsg);
        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(\'a\', this).hide(); jQuery(\'#errordetails\').show();>Show Details</a></p>');
                break;
        }
        if (textStatus == "error")
        {
            try
            {
                var err = eval("(" + xhr.responseText + ")");
                errormsg.append(jQuery('<pre id="errordetails" style="display: none;">' + err.Message + '</pre>'));
            } catch (e) { }
        }
        if (textStatus == "timeout")
        {
            errormsg.append('<p id="errordetails" style="display: none;">The AJAX request timed out.</p>');
        }
        if (textStatus == "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\').fadeOut(500);">[ Close ]</a></p>');
    }
}

// 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();
    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["albt"] == undefined)
    {
        jQuery.getScript("/scripts/albatross.js");
    }
    _responsehandler = new albt.response(showMessage)
    jQuery.ajaxSetup({
        dataType: "xml",
        timeout: 1000000,
        type: "POST",
        error: showError,
        success: function(xml) { _responsehandler.handler(xml); }
    });
    //add ajax loading gif
    jQuery('body').bind("ajaxSend", function() { getLoading().show(); }).bind("ajaxComplete", function() { getLoading().hide(); });

    //add model popup stuff
    loadjqm();
    jQuery.jqm.params.overlayClass = "ui-widget-overlay";
    loadbgiframe();
}

/**jquery modal**/
loadjqm = function()
{
    /*
    * jqModal - Minimalist Modaling with jQuery
    *   (http://dev.iceburg.net/jquery/jqModal/)
    *
    * Copyright (c) 2007,2008 Brice Burgess <bhb@iceburg.net>
    * Dual licensed under the MIT and GPL licenses:
    *   http://www.opensource.org/licenses/mit-license.php
    *   http://www.gnu.org/licenses/gpl.html
    * 
    * $Version: 03/01/2009 +r14
    */
    (function($)
    {
        $.fn.jqm = function(o)
        {
            var p = {
                overlay: 50,
                overlayClass: 'jqmOverlay',
                closeClass: 'jqmClose',
                trigger: '.jqModal',
                ajax: F,
                ajaxText: '',
                target: F,
                modal: F,
                toTop: F,
                onShow: F,
                onHide: F,
                onLoad: F
            };
            return this.each(function()
            {
                if (this._jqm) return H[this._jqm].c = $.extend({}, H[this._jqm].c, o); s++; this._jqm = s;
                H[s] = { c: $.extend(p, $.jqm.params, o), a: F, w: $(this).addClass('jqmID' + s), s: s };
                if (p.trigger) $(this).jqmAddTrigger(p.trigger);
            });
        };

        $.fn.jqmAddClose = function(e) { return hs(this, e, 'jqmHide'); };
        $.fn.jqmAddTrigger = function(e) { return hs(this, e, 'jqmShow'); };
        $.fn.jqmShow = function(t) { return this.each(function() { t = t || window.event; $.jqm.open(this._jqm, t); }); };
        $.fn.jqmHide = function(t) { return this.each(function() { t = t || window.event; $.jqm.close(this._jqm, t) }); };

        $.jqm = {
            hash: {},
            open: function(s, t)
            {
                var h = H[s], c = h.c, cc = '.' + c.closeClass, z = (parseInt(h.w.css('z-index'))), z = (z > 0) ? z : 3000, o = $('<div></div>').css({ height: '100%', width: '100%', position: 'fixed', left: 0, top: 0, 'z-index': z - 1, opacity: c.overlay / 100 }); if (h.a) return F; h.t = t; h.a = true; h.w.css('z-index', z);
                if (c.modal) { if (!A[0]) L('bind'); A.push(s); }
                else if (c.overlay > 0) h.w.jqmAddClose(o);
                else o = F;

                h.o = (o) ? o.addClass(c.overlayClass).prependTo('body') : F;
                if (ie6) { $('html,body').css({ height: '100%', width: '100%' }); if (o) { o = o.css({ position: 'absolute' })[0]; for (var y in { Top: 1, Left: 1 }) o.style.setExpression(y.toLowerCase(), "(_=(document.documentElement.scroll" + y + " || document.body.scroll" + y + "))+'px'"); } }

                if (c.ajax)
                {
                    var r = c.target || h.w, u = c.ajax, r = (typeof r == 'string') ? $(r, h.w) : $(r), u = (u.substr(0, 1) == '@') ? $(t).attr(u.substring(1)) : u;
                    r.html(c.ajaxText).load(u, function() { if (c.onLoad) c.onLoad.call(this, h); if (cc) h.w.jqmAddClose($(cc, h.w)); e(h); });
                }
                else if (cc) h.w.jqmAddClose($(cc, h.w));

                if (c.toTop && h.o) h.w.before('<span id="jqmP' + h.w[0]._jqm + '"></span>').insertAfter(h.o);
                (c.onShow) ? c.onShow(h) : h.w.show(); e(h); return F;
            },
            close: function(s)
            {
                var h = H[s]; if (!h.a) return F; h.a = F;
                if (A[0]) { A.pop(); if (!A[0]) L('unbind'); }
                if (h.c.toTop && h.o) $('#jqmP' + h.w[0]._jqm).after(h.w).remove();
                if (h.c.onHide) h.c.onHide(h); else { h.w.hide(); if (h.o) h.o.remove(); } return F;
            },
            params: {}
        };
        var s = 0, H = $.jqm.hash, A = [], ie6 = $.browser.msie && ($.browser.version == "6.0"), F = false,
i = $('<iframe src="javascript:false;document.write(\'\');" class="jqm"></iframe>').css({ opacity: 0 }),
e = function(h) { if (ie6) if (h.o) h.o.html('<p style="width:100%;height:100%"/>').prepend(i); else if (!$('iframe.jqm', h.w)[0]) h.w.prepend(i); f(h); },
f = function(h) { try { $(':input:visible', h.w)[0].focus(); } catch (_) { } },
L = function(t) { $()[t]("keypress", m)[t]("keydown", m)[t]("mousedown", m); },
m = function(e) { var h = H[A[A.length - 1]], r = (!$(e.target).parents('.jqmID' + h.s)[0]); if (r) f(h); return !r; },
hs = function(w, t, c)
{
    return w.each(function()
    {
        var s = this._jqm; $(t).each(function()
        {
            if (!this[c]) { this[c] = []; $(this).click(function() { for (var i in { jqmShow: 1, jqmHide: 1 }) for (var s in this[i]) if (H[this[i][s]]) H[this[i][s]].w[i](this); return F; }); } this[c].push(s);
        });
    });
};
    })(jQuery)
}

/**bgiframe**/
loadbgiframe = function()
{
    /* Copyright (c) 2006 Brandon Aaron (http://brandonaaron.net)
    * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
    * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
    *
    * $LastChangedDate: 2007-07-21 18:45:56 -0500 (Sat, 21 Jul 2007) $
    * $Rev: 2447 $
    *
    * Version 2.1.1
    */
    (function($) { $.fn.bgIframe = $.fn.bgiframe = function(s) { if ($.browser.msie && /6.0/.test(navigator.userAgent)) { s = $.extend({ top: 'auto', left: 'auto', width: 'auto', height: 'auto', opacity: true, src: 'javascript:false;' }, s || {}); var prop = function(n) { return n && n.constructor == Number ? n + 'px' : n; }, html = '<iframe class="bgiframe"frameborder="0"tabindex="-1"src="' + s.src + '"' + 'style="display:block;position:absolute;z-index:-1;' + (s.opacity !== false ? 'filter:Alpha(Opacity=\'0\');' : '') + 'top:' + (s.top == 'auto' ? 'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')' : prop(s.top)) + ';' + 'left:' + (s.left == 'auto' ? 'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')' : prop(s.left)) + ';' + 'width:' + (s.width == 'auto' ? 'expression(this.parentNode.offsetWidth+\'px\')' : prop(s.width)) + ';' + 'height:' + (s.height == 'auto' ? 'expression(this.parentNode.offsetHeight+\'px\')' : prop(s.height)) + ';' + '"/>'; return this.each(function() { if ($('> iframe.bgiframe', this).length == 0) this.insertBefore(document.createElement(html), this.firstChild); }); } return this; }; })(jQuery);
}

jQuery(function()
{
    ajax_setup();
    if (jQuery.isFunction(window["pageload"])) window["pageload"]();
});
