﻿var lastFocusedControlId = "";

function focusHandler(e) {
    e.originalTarget.focus = true;
}

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) {
    lastFocusedControlId = typeof (document.activeElement) === "undefined" ? "" : document.activeElement.id;
}

function focusControl(targetControl) {
    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;
        }
        try {
            setCursorToEnd(targetControl);
            // targetControl.focus();
            if (focusTarget) {
                focusTarget.contentEditable = oldContentEditableSetting;
            }
        }
        catch (err) { }
    }
    else {
        setCursorToEnd(targetControl);
        //targetControl.focus();
    }
}

function pageLoadedHandler(sender, args) {
    if (typeof (lastFocusedControlId) !== "undefined" && lastFocusedControlId != "") {
        var newFocused = $get(lastFocusedControlId);
        if (newFocused) {
            focusControl(newFocused);
        }
    }
}

function setCursorToEnd(targetControl) {

    //var control = document.getElementById(elementId);
    try {
        if (null != targetControl) {
            var pos = targetControl.value.length;
            if (targetControl.setSelectionRange) {
                targetControl.setSelectionRange(pos, pos);
            }
            else if (targetControl.createTextRange) {
                var textRange = targetControl.createTextRange();
                textRange.collapse(true);
                textRange.moveEnd("character", pos);
                textRange.moveStart("character", pos);
                textRange.select();
            }
            targetControl.focus();
        }
    }
    catch (err) { }
}
Sys.Application.add_init(appInit);

