﻿var lastFocusedControlId = "";
var FCKEditorControlId = "";
var FCKEditorControl = "";
var dlgChats = new Array();

function FCKeditor_OnComplete( editorInstance )
{
    editorInstance.Events.AttachEvent( 'OnFocus', FCKeditor_OnFocus ) ;
    editorInstance.Events.AttachEvent( 'OnBlur', FCKeditor_OnBlur ) ;
}

function FCKeditor_OnBlur( editorInstance )
{
    FCKEditorControlId = "";
}

function FCKeditor_OnFocus( editorInstance )
{
    FCKEditorControlId = editorInstance.Name;
}

//*

function focusHandler(e) {
    try{
        if(document.activeElement !== document.body)
            lastFocusedControlId = document.activeElement;
    }catch(ex){}
}

function appInit() {
    if (typeof(window.addEventListener) !== "undefined") {
            window.addEventListener("focus", focusHandler, true);    
    } 
    Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoadedHandler);

}

function focusControl(targetControl) {    
    if(FCKEditorControlId){
        setTimeout("FCKEditorControl=FCKeditorAPI.GetInstance(FCKEditorControlId);if(FCKEditorControl){try{FCKEditorControl.MakeEditable();}catch(e){}FCKEditorControl.Focus();}", 0);
    }else{
        
        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;
        }
        setTimeout("lastFocusedControlId.focus();", 0);
    }
}

function pageLoadedHandler(sender, args) {
    try{
        var dlg;
        for(el in dlgChats){
            dlg = $get(dlgChats[el]);
            dlg.scrollTop = dlg.scrollHeight; 
        }
        if (lastFocusedControlId || FCKEditorControlId) 
                focusControl($get(lastFocusedControlId.id));
    }catch(ex){}
}

Sys.Application.add_init(appInit); 

/**/

