﻿//Initialise on page loaded
function initialise()
{
    //Set up async wait screen
    var prm = getPRM();

    prm.add_initializeRequest(beginWaitScreen);
    prm.add_endRequest(endWaitScreen);

    setUpInlineHelp();
    setUpDummyFormSubmit();
}

var waitScreenTimer;
var waitScreenDelay = 100;

//Prepare to show async wait screen
function beginWaitScreen(sender, args)
{
    if (args && args._postBackElement) {
        var postBackElement = $(args._postBackElement);
        if (postBackElement.hasClass("noWait") || postBackElement.parents(".noWait").length) return;
    }

    waitScreenTimer = setTimeout(function () { showWaitScreen(args); }, waitScreenDelay)
}

//Prepare to hide async wait screen
function endWaitScreen(sender, args)
{
    clearTimeout(waitScreenTimer);
    hideWaitScreen();
}

//Shows the async wait screen
function showWaitScreen(args)
{
    $("div.popUpBackground").removeClass("popUpBackground").addClass("popUpBackgroundClear");

    var waitScreen = $find('mpeWaitScreenBehaviour');
    if (waitScreen) waitScreen.show();
}

//Hides the async wait screen
function hideWaitScreen()
{
    $("div.popUpBackgroundClear").removeClass("popUpBackgroundClear").addClass("popUpBackground");

    var waitScreen = $find('mpeWaitScreenBehaviour');
    if (waitScreen) waitScreen.hide();
}

//Forces modal popup to reposition itself in the center
function resetModalPopUp(behaviourID)
{
    $find(behaviourID)._layout();
}

//Select and focus on a control
function selectAndFocusControl(controlID)
{
    setTimeout(function ()
    {
        var control = document.getElementById(controlID);
        if (control) {
            if (control.select) control.select();
            if (control.focus) control.focus();
        }
    }, 250);
}

//Copy text to clipboard
function copyToClipboard(url)
{
    try {
        var txtHoldText = document.getElementById('txtHoldText');
        txtHoldText.innerText = url.replace(/ /gi, "%20");

        var copied = txtHoldText.createTextRange();
        copied.execCommand("Copy");

        alert('The following link has been copied to the clipboard:\n\n' + txtHoldText.innerText);
    }
    catch (err) {
        alert('Sorry, the copying of the link to the clipboard has failed.\n\nPlease select and copy from below instead:\n\n' + txtHoldText.innerText);
    }
}

//Object to show a hovering tooltip
var toolTip = function ()
{
    var xOffset = 15;
    var yOffset = -15;
    var divToolTip;

    return {
        show: function (text)
        {
            // Create tooltip element if it does not exist already
            if (divToolTip == null) {
                divToolTip = document.createElement('div');
                divToolTip.className = 'tooltip';

                document.getElementById('divToolTipContainer').appendChild(divToolTip);
                document.onmousemove = this.pos;
            }

            // Populate & show tooltip
            divToolTip.innerHTML = text;
            divToolTip.style.display = 'block';
        },
        pos: function (e)
        {
            var l = document.all ? event.clientX + document.documentElement.scrollLeft : e.pageX;
            var t = document.all ? event.clientY + document.documentElement.scrollTop : e.pageY;

            // Move tooltip relative to the mouse pointer
            if (divToolTip) {
                divToolTip.style.left = (l + xOffset) + 'px';
                divToolTip.style.top = (t + yOffset) + 'px';
            }
        },
        hide: function ()
        {
            // Hide the tooltip
            if (divToolTip) divToolTip.style.display = 'none';
        }
    };
} ();

//Shows an alert popup
function showAlert(message)
{
    setTimeout(function () { alert(message); }, 250);
}

//Creates XmlHttp request object
function getXMLHttp()
{
    var xmlHttp = false;

    try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); }
    catch (err1) {
        try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); }
        catch (err2) { xmlHttp = false; }
    }
    // Mozilla...
    if (!xmlHttp && typeof XMLHttpRequest != 'undefined') xmlHttp = new XMLHttpRequest();

    return xmlHttp;
}

//Gets an instance of the Page Request Manager
function getPRM()
{
    return Sys.WebForms.PageRequestManager.getInstance();
}

//Checks whether the specified Update Panel is being created/updated
function isPanelUpdating(panelID, args)
{
    if (args) {
        var panelsCreated = args.get_panelsCreated();
        for (var i = 0; i < panelsCreated.length; i++) {
            if (panelID == panelsCreated[i].id) return true;
        }

        var panelsUpdated = args.get_panelsUpdated();
        for (var i = 0; i < panelsUpdated.length; i++) {
            if (panelID == panelsUpdated[i].id) return true;
        }
    }
    return false;
}

//Ensure active tab state is saved
function activeTabChanged(sender, args)
{
    sender.get_clientStateField().value = sender.saveClientState();
}

//Sets up the mouse in/out events for any inline help
function setUpInlineHelp()
{
    $("span.inlineHelp > img").live("mouseenter", function ()
    {
        $(this).next().css("display", "inline");
    });
    $("span.inlineHelp > img").live("mouseleave", function ()
    {
        $(this).next().css("display", "none");
    });
}

//Sets up the submitting of any dummy forms
function setUpDummyFormSubmit()
{
    $("div.dummyForm input[type=submit], div.dummyForm input[type=image]").live("click", function (e)
    {
        var dummyForm = $(this).closest("div.dummyForm");
        var htmlForm = $("<form target='_blank'></form>");
        var formAttr = ['action', 'accept', 'accept-charset', 'enctype', 'method', 'name', 'target'];

        $.each($(formAttr), function (i)
        {
            if (dummyForm.attr(formAttr[i]) != "undefined") {
                htmlForm.attr(formAttr[i], dummyForm.attr(formAttr[i]));
            }
        });

        $("input, select, textarea, button", dummyForm).each(function ()
        {
            var thisElement = $(this);
            var clone = thisElement.clone();

            if (clone.get(0).tagName == "SELECT") {
                clone.val(thisElement.val());
            }

            clone.appendTo(htmlForm);
        });

        htmlForm.appendTo("body");

        try { htmlForm.submit(); }
        catch (err) { } //Do nothing...

        htmlForm.remove();

        return false;
    });
}
