﻿
/* UpdatePanel animation scripts */
/* using loadmask to animate panel div */

/* EXAMPLE:
    <script type="text/javascript">
        // all we need to add to create an animation is this
        addPanelToAnimate("animateMe");
    </script>
    <div id="animateMe">
        <fieldset>
            <legend>My Panel</legend>

            <asp:UpdatePanel ID="udpPercelen" runat="server"
                    UpdateMode="Conditional">
                <ContentTemplate>
                        Some Content that will be generated...
                        <asp:Button ID="btnPostBack"
                        Runat="server" Text="Click" />
                </ContentTemplate>
            </asp:UpdatePanel>
        </fieldset>
    </div>
*/


var animatePanels;
var app = null;
try {
    app = Sys.Application;
    app.add_init(ApplicationInit);
} catch (e) {
    console.warn(e);
}

// add handlers
function ApplicationInit(sender) {
    var prm = Sys.WebForms.PageRequestManager.getInstance();

    if (!prm.get_isInAsyncPostBack()) {
        prm.add_beginRequest(BeginRequestHandler);
        prm.add_endRequest(EndRequestHandler);
    }
}

function AddPanelToAnimate(id) {
    if (!animatePanels) {
        animatePanels = new Array();
    }
    animatePanels[animatePanels.length] = id;
}

// show animation mask
function BeginRequestHandler(sender, args) {
    AddLoadmask(args.get_postBackElement());
}

// remove animation maks
function EndRequestHandler(sender, args) {
    var mask = $(".loadmask");
    if (mask) {
        mask.remove();
    }

    var loadMask = $(".loadmask-msg");
    if (loadMask) {
        loadMask.remove();
    }
}

// check if posted controls contains an
// updatepanel from the list and add mask
function AddLoadmask(elem) {
    if (elem) {
        var childs = elem.parentNode.children;
        if (animatePanels) {
            for (i = 0; i < animatePanels.length; i++) {
                // get panel-id
                var pnlID = replaceAll(animatePanels[i], "$", "_");
                // posted element-collection contains panel?
                if (Contains(childs, pnlID)) {
                    $("#" + pnlID).mask("Loading...");
                }
            }
        }
    }
}

// recursive replace
function replaceAll(text, strOld, strNew) {
    while (text.indexOf(strOld) > 0) {
        text = text.replace(strOld, strNew);
    }
    return text;
}

// contains function for array
function Contains(arr, elm) {
    if (arr && elm) {
        for (i = 0; i < arr.length; i++) {
            if (arr[i] == elm) {
                return i;
            }
        }
    }
    return -1;
}
