﻿(function($) {
    $.fn.disposable = function(cln) {
        return this.each(function() {
            var el = this;
            if (!el.dispose) {
                el.dispose = cleanup; // will be called by MS for cleanup
                $(window).bind("unload", cleanup);
            }
            function cleanup() {
                if (!el)
                    return;
                $(el).unbind();
                $(window).unbind("unload", cleanup);
                el.clnup = el.dispose = null;
                el = null;
            };
        });
    };

    $.cleanEmptyCache = function() {
        // clean jQuery cache = just remove all items whose contents is empty
        for (var id in $.cache) {
            var empty = true;
            for (var cnt in $.cache[id]) {
                empty = false;
                break;
            }
            if (empty)
                delete $.cache[id];
        }
    };
})(jQuery);


jQuery(function() {
    // If the page doesn't have a ScriptManager, Sys.WebForms won't be defined.  In this case
    // there is no need to do anything.  You can't have an Update Panel without a Script Manager.
    if ( typeof(Sys) == "undefined" ) return;
    if ( typeof(Sys.WebForms) == "undefined" ) return;

    //... fix update panel leaks
    Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(function(mgr, args) {
        $(".disposable", GetUpdatePanels(args)).disposable();
    });

    function GetUpdatePanels(args) {
        var ret = (args && args.get_panelsUpdated) ? args.get_panelsUpdated() : null;
        if (!ret || ret.length == 0) return $(document);
        return $(ret);
    }

    if (Sys && Sys.WebForms && !Sys.WebForms.PageRequestManager.jQueryDestroyTreeOverriden) {
        Sys.WebForms.PageRequestManager.jQueryDestroyTreeOverriden = true;
        var oldFn = Sys.WebForms.PageRequestManager.prototype._destroyTree;
        var depth = 0;
        Sys.WebForms.PageRequestManager.prototype._destroyTree = function(element) {
            depth++;
            oldFn.apply(this, [element]);
            if (--depth == 0) {
                // There is an issue with ModalBox control
                // script errors after ModalBox control had been shown or hidden and empty() function had been executed
                if (element.id.indexOf("upModalBox") == -1) {
                    jQuery(element).empty();
                    $.cleanEmptyCache();
                }
            }
        }
    }
});

