﻿// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Permissive License.
// See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx.
// All other rights reserved.

Type.registerNamespace('GSAjaxControls');

GSAjaxControls.KeepFocusBehavior = function(element) {

    GSAjaxControls.KeepFocusBehavior.initializeBase(this, [element]);

    // Properties
    this._FocusedStateValue = null;

	// Member variables
    this._focusHandler = null;
    this._blurHandler = null;
    
}

GSAjaxControls.KeepFocusBehavior.prototype = {

    initialize : function() {
        GSAjaxControls.KeepFocusBehavior.callBaseMethod(this, 'initialize');

		if (this._FocusedStateValue)
	    {
			//alert(this.get_element());
			this._autofocus(this.get_element());
	    }
	    
        this._focusHandler = Function.createDelegate(this, this._onfocus);
        $addHandler(this.get_element(), 'focus', this._focusHandler);
        
        this._blurHandler = Function.createDelegate(this, this._onblur);
        $addHandler(this.get_element(), 'blur', this._blurHandler);
    },

    dispose : function() {
        if (this._focusHandler) {
            $removeHandler(this.get_element(), "focus", this._focusHandler);
            this._focusHandler = null;
        }
        
        if (this._blurHandler) {
            $removeHandler(this.get_element(), "blur", this._blurHandler);
            this._blurHandler = null;
        }

        GSAjaxControls.KeepFocusBehavior.callBaseMethod(this, 'dispose');
    },

    _onfocus : function() {
		this.set_FocusedState('true');
	},
	
	_onblur : function() {
		this.set_FocusedState('false');
	},
	
	_autofocus : function(focused) {
		if (focused) {
			try {
				focused.focus();
				if (__nonMSDOMBrowser) {
					focused.scrollIntoView(false);
				}
				if (window.__smartNav) {
					window.__smartNav.ae = focused.id;
				}
			}
			catch (e) {
			}
		}
	},

	get_FocusedState : function() {
		return this._FocusedStateValue;
	},

	set_FocusedState : function(value) {
		this._FocusedStateValue = value;
		GSAjaxControls.KeepFocusBehavior.callBaseMethod(this, 'set_ClientState', [ this._FocusedStateValue ]);
        this.raisePropertyChanged('FocusedState');
	}
	
}

GSAjaxControls.KeepFocusBehavior.registerClass('GSAjaxControls.KeepFocusBehavior', AjaxControlToolkit.BehaviorBase);



if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();