﻿var lastFocusedControl = null;
function focusHandler(e) {
    //document.activeElement = e.originalTarget;
}
function appInit() {
    if (typeof (window.addEventListener) !== "undefined") {
        window.addEventListener("focus", focusHandler, true);
    }
    Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(pageLoadingHandler);
    Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoadedHandler);
}
function pageLoadingHandler(sender, args) {
    lastFocusedControl = typeof (document.activeElement) === "undefined"
								? ""
								: document.activeElement;
}
function focusControl(targetControl, previousControl) {
    try {
        if (Sys.Browser.agent === Sys.Browser.InternetExplorer) {
            var focusTarget = targetControl;
            if (focusTarget && (typeof (focusTarget.contentEditable) !== "undefined")) {
                oldContentEditableSetting = focusTarget.contentEditable;
                focusTarget.contentEditable = false;
            }
            else {
                focusTarget = null;
            }
            targetControl.focus();
            if (focusTarget) {
                focusTarget.contentEditable = oldContentEditableSetting;
            }
        }
        else {
            targetControl.focus();
        }

        if (focusTarget.isContentEditable) {
            //debugger;
            targetControl.value = previousControl.value;
        }
    }
    catch (exc) { /* for now: no errors please ;) */ }
}
function pageLoadedHandler(sender, args) {
    if (typeof (lastFocusedControl) !== "undefined" && lastFocusedControl != null && lastFocusedControl.id != "") {
        var newFocused = $get(lastFocusedControl.id);
        if (newFocused) {
            focusControl(newFocused, lastFocusedControl);
        }
    }
}
Sys.Application.add_init(appInit);
