//! ClientScript.debug.js
//

(function() {

Type.registerNamespace('ClientScript');

////////////////////////////////////////////////////////////////////////////////
// ClientManager

ClientManager = function ClientManager() {
    /// <field name="_listeners" type="Array" static="true">
    /// </field>
    /// <field name="_uniqueIdCounter" type="Number" integer="true" static="true">
    /// </field>
    /// <field name="_options" type="Object" static="true">
    /// </field>
    /// <field name="_fb" type="FB" static="true">
    /// </field>
    /// <field name="_facebookPermissionsGranted" type="Array" elementType="String" static="true">
    /// </field>
    /// <field name="_createUpdateAccount" type="Boolean" static="true">
    /// </field>
    /// <field name="_onWaitingForServer" type="Action" static="true">
    /// </field>
    /// <field name="_onWaitingForServerComplete" type="Action" static="true">
    /// </field>
}
ClientManager.registerListener = function ClientManager$registerListener(listener) {
    /// <param name="listener" type="System.Action`2">
    /// </param>
    if (listener == null) {
        return;
    }
    ClientManager._listeners.add(listener);
}
ClientManager.deregisterListener = function ClientManager$deregisterListener(listener) {
    /// <param name="listener" type="System.Action`2">
    /// </param>
    if (listener == null) {
        return;
    }
    ClientManager._listeners.remove(listener);
}
ClientManager.postMessage = function ClientManager$postMessage(msg, data) {
    /// <param name="msg" type="String">
    /// </param>
    /// <param name="data" type="Object">
    /// </param>
    if (String.isNullOrEmpty(msg)) {
        return;
    }
    var $enum1 = ss.IEnumerator.getEnumerator(ClientManager._listeners);
    while ($enum1.moveNext()) {
        var listener = $enum1.current;
        listener(msg, data || null);
    }
}
ClientManager.generateUniqueElementId = function ClientManager$generateUniqueElementId(prefix) {
    /// <param name="prefix" type="String">
    /// </param>
    /// <returns type="String"></returns>
    var uniqueId = String.concat(prefix, ClientManager._uniqueIdCounter.toString());
    ClientManager._uniqueIdCounter++;
    return uniqueId;
}
ClientManager._initFacebookApi = function ClientManager$_initFacebookApi() {
    if (ClientManager._fb != null) {
        return;
    }
    ClientManager._fb = MdSc.Client.Sh.U._facebook.getFB();
    var initOptions = {};
    initOptions.appId = ClientManager._options.FacebookAppId;
    initOptions.status = true;
    initOptions.xfbml = true;
    initOptions.cookie = true;
    initOptions.logging = true;
    initOptions.oauth = true;
    if (!!window.location.port.length) {
        initOptions.channelUrl = window.location.protocol + '//' + window.location.hostname + ':' + window.location.port + '/channel.html';
    }
    else {
        initOptions.channelUrl = window.location.protocol + '//' + window.location.hostname + '/channel.html';
    }
    ClientManager._fb.init(initOptions);
}
ClientManager.attemptFacebookLoginClientOnly = function ClientManager$attemptFacebookLoginClientOnly(onResult) {
    /// <param name="onResult" type="System.Action`1">
    /// </param>
    ClientManager._fb.login(function(r) {
        if (onResult != null) {
            onResult(r);
        }
    });
}
ClientManager.acquireFacebookPermissions = function ClientManager$acquireFacebookPermissions(scope, onResult) {
    /// <param name="scope" type="String">
    /// </param>
    /// <param name="onResult" type="System.Action`1">
    /// </param>
    var options = {};
    options.scope = scope;
    ClientManager._fb.login(function(r) {
        if (onResult != null) {
            onResult(r);
        }
    }, options);
}
ClientManager.attemptFacebookLogin = function ClientManager$attemptFacebookLogin(createUpdateAccount, onWaitingForServer, onWaitingForServerComplete) {
    /// <param name="createUpdateAccount" type="Boolean">
    /// </param>
    /// <param name="onWaitingForServer" type="Action">
    /// </param>
    /// <param name="onWaitingForServerComplete" type="Action">
    /// </param>
    if (ss.isValue(createUpdateAccount)) {
        ClientManager._createUpdateAccount = createUpdateAccount;
    }
    if (ss.isValue(onWaitingForServer)) {
        ClientManager._onWaitingForServer = onWaitingForServer;
    }
    else {
        ClientManager._onWaitingForServer = null;
    }
    if (ss.isValue(onWaitingForServerComplete)) {
        ClientManager._onWaitingForServerComplete = onWaitingForServerComplete;
    }
    else {
        ClientManager._onWaitingForServerComplete = null;
    }
    var options = {};
    options.scope = 'email,user_location,user_about_me';
    ClientManager._fb.login(function(lr) {
        ClientManager._onFbLogin(lr);
    }, options);
}
ClientManager.logoutFacebook = function ClientManager$logoutFacebook(redirectToLogoutPage) {
    /// <param name="redirectToLogoutPage" type="Boolean">
    /// </param>
    var fnRedirect = function() {
        if (redirectToLogoutPage) {
            window.location.href = '/Account/LogOff';
        }
    };
    ClientManager._fb.logout(fnRedirect);
    if (redirectToLogoutPage) {
        window.setTimeout(fnRedirect, 2000);
    }
}
ClientManager._onFbLogin = function ClientManager$_onFbLogin(response) {
    /// <param name="response" type="LoginResponse">
    /// </param>
    ClientManager._onFbAuthLogin(response);
}
ClientManager._onFbGetLoginStatus = function ClientManager$_onFbGetLoginStatus(response) {
    /// <param name="response" type="LoginResponse">
    /// </param>
    ClientManager._onFbAuthLogin(response);
}
ClientManager._onFbAuthLogin = function ClientManager$_onFbAuthLogin(response) {
    /// <param name="response" type="Object">
    /// </param>
    var loginResponse = response;
    if (loginResponse.status !== 'connected') {
        return;
    }
    if (ClientManager._createUpdateAccount) {
        if (ClientManager._onWaitingForServer != null) {
            ClientManager._onWaitingForServer();
        }
        ClientManager._createUpdateAccount = false;
        window.setTimeout(function() {
            ClientManager._requestFacebookMe(function(user) {
                if (user != null) {
                    ClientManager._createOrUpdateUserAccount(user);
                }
            });
        }, 10 * 1);
    }
}
ClientManager._requestFacebookMe = function ClientManager$_requestFacebookMe(onData) {
    /// <param name="onData" type="System.Action`1">
    /// </param>
    ClientManager._fb.api('/me', function(response) {
        if (response == null) {
            onData(null);
            return;
        }
        else {
            var fbUser = response;
            if (ss.isNullOrUndefined(fbUser.id)) {
                onData(null);
                return;
            }
            else {
                onData(fbUser);
                return;
            }
        }
    });
}
ClientManager._createOrUpdateUserAccount = function ClientManager$_createOrUpdateUserAccount(fbUser) {
    /// <param name="fbUser" type="UserObject">
    /// </param>
    $.post('/Account/LogonFacebook', { fbUser: JSON.stringify(fbUser) }, function(o) {
        if (Type.canCast(o, String)) {
            ClientManager._fb.logout(function() {
            });
            alert(o);
            if (ClientManager._onWaitingForServerComplete != null) {
                ClientManager._onWaitingForServerComplete();
            }
        }
        else if (Type.canCast(o, Boolean)) {
            var success = o;
            if (success) {
                window.location.href = '/Member';
            }
            else {
                ClientManager._fb.logout(function() {
                });
            }
        }
    });
}
ClientManager.publishStoryOnFacebook = function ClientManager$publishStoryOnFacebook(storyUrl, storyTitle, description, resultHandler) {
    /// <param name="storyUrl" type="String">
    /// </param>
    /// <param name="storyTitle" type="String">
    /// </param>
    /// <param name="description" type="String">
    /// </param>
    /// <param name="resultHandler" type="System.Action`1">
    /// </param>
    if (storyUrl.startsWith('/')) {
        storyUrl = 'http://' + window.location.host + storyUrl;
    }
    var options = {};
    options.method = 'feed';
    options.name = storyTitle;
    options.link = storyUrl;
    options.description = description || '';
    if (options.description.length > 250) {
        options.description = options.description.substr(0, 245) + '...';
    }
    ClientManager._fb.ui(options, function(obj) {
        if (resultHandler == null) {
            return;
        }
        if (obj != null && obj['post_id'] != null) {
            resultHandler(true);
        }
        else {
            resultHandler(false);
        }
    });
}
ClientManager.urlStory = function ClientManager$urlStory(userAppKey, storyId, storyTitle) {
    /// <param name="userAppKey" type="String">
    /// </param>
    /// <param name="storyId" type="Number" integer="true">
    /// </param>
    /// <param name="storyTitle" type="String">
    /// </param>
    /// <returns type="String"></returns>
    return String.format('/{0}/{1}/{2}', userAppKey, storyId, encodeURIComponent(storyTitle));
}


Type.registerNamespace('FacebookSS.GraphApi');

////////////////////////////////////////////////////////////////////////////////
// FacebookSS.GraphApi.UIOptionsPermissionsRequest

FacebookSS.GraphApi.UIOptionsPermissionsRequest = function FacebookSS_GraphApi_UIOptionsPermissionsRequest(permissions) {
    /// <param name="permissions" type="String">
    /// </param>
    /// <field name="perms" type="String">
    /// </field>
    FacebookSS.GraphApi.UIOptionsPermissionsRequest.initializeBase(this);
    this.method = 'permissions.request';
    this.display = 'popup';
    this.perms = permissions;
}
FacebookSS.GraphApi.UIOptionsPermissionsRequest.prototype = {
    perms: null
}


Type.registerNamespace('ClientScript.UI');

////////////////////////////////////////////////////////////////////////////////
// ClientScript.UI.ConfirmRemove

ClientScript.UI.ConfirmRemove = function ClientScript_UI_ConfirmRemove(userSelectionHandler) {
    /// <param name="userSelectionHandler" type="System.Action`1">
    /// </param>
    /// <field name="_jqMbNo" type="jQueryObject">
    /// </field>
    /// <field name="_jqMbYes" type="jQueryObject">
    /// </field>
    /// <field name="_jqMbNoButton" type="jQueryObject">
    /// </field>
    /// <field name="_jqMbYesButton" type="jQueryObject">
    /// </field>
    /// <field name="_text" type="jQueryObject">
    /// </field>
    /// <field name="_userSelectionHandler$1" type="System.Action`1">
    /// </field>
    /// <field name="template" type="String">
    /// </field>
    ClientScript.UI.ConfirmRemove.initializeBase(this);
    this._userSelectionHandler$1 = userSelectionHandler;
    this._jqMbNo.click(ss.Delegate.create(this, this._onMbNoKeyPress$1));
    this._jqMbYes.click(ss.Delegate.create(this, this._onMbYesKeyPress$1));
    this._jqMbNoButton.mouseover(ss.Delegate.create(this, this._onMbNoButtonMouseOver$1));
    this._jqMbNoButton.mouseout(ss.Delegate.create(this, this._onMbNoButtonMouseOut$1));
    this._jqMbYesButton.mouseover(ss.Delegate.create(this, this._onMbYesButtonMouseOver$1));
    this._jqMbYesButton.mouseout(ss.Delegate.create(this, this._onMbYesButtonMouseOut$1));
}
ClientScript.UI.ConfirmRemove.show = function ClientScript_UI_ConfirmRemove$show(userSelectionHandler, text) {
    /// <param name="userSelectionHandler" type="System.Action`1">
    /// </param>
    /// <param name="text" type="String">
    /// </param>
    var myConfirmRemove = new ClientScript.UI.ConfirmRemove(userSelectionHandler);
    if (ss.isValue(text)) {
        var textEncoded = text.htmlEncode();
        textEncoded = textEncoded.replaceAll('[[', '<span>');
        textEncoded = textEncoded.replaceAll(']]', '</span>');
        myConfirmRemove._text.html(textEncoded);
    }
    myConfirmRemove.get_rootElement().appendTo('body');
    myConfirmRemove.get_rootElement().css({ width: '100%', position: 'absolute', top: '30%', left: '0%' });
    myConfirmRemove.get_rootElement().fadeIn('fast');
}
ClientScript.UI.ConfirmRemove.prototype = {
    _jqMbNo: null,
    _jqMbYes: null,
    _jqMbNoButton: null,
    _jqMbYesButton: null,
    _text: null,
    _userSelectionHandler$1: null,
    
    _onMbYesKeyPress$1: function ClientScript_UI_ConfirmRemove$_onMbYesKeyPress$1(e) {
        /// <param name="e" type="jQueryEvent">
        /// </param>
        this._userSelectionHandler$1(true);
        this.get_rootElement().detach();
    },
    
    _onMbNoKeyPress$1: function ClientScript_UI_ConfirmRemove$_onMbNoKeyPress$1(e) {
        /// <param name="e" type="jQueryEvent">
        /// </param>
        this._userSelectionHandler$1(false);
        this.get_rootElement().detach();
    },
    
    _onMbNoButtonMouseOver$1: function ClientScript_UI_ConfirmRemove$_onMbNoButtonMouseOver$1(e) {
        /// <param name="e" type="jQueryEvent">
        /// </param>
        if (this._jqMbNoButton.attr('src').indexOf('-off') >= 0) {
            this._jqMbNoButton.attr({ src: this._jqMbNoButton.attr('src').replaceAll('-off', '-on') });
        }
    },
    
    _onMbNoButtonMouseOut$1: function ClientScript_UI_ConfirmRemove$_onMbNoButtonMouseOut$1(e) {
        /// <param name="e" type="jQueryEvent">
        /// </param>
        if (this._jqMbNoButton.attr('src').indexOf('-on') >= 0) {
            this._jqMbNoButton.attr({ src: this._jqMbNoButton.attr('src').replaceAll('-on', '-off') });
        }
    },
    
    _onMbYesButtonMouseOver$1: function ClientScript_UI_ConfirmRemove$_onMbYesButtonMouseOver$1(e) {
        /// <param name="e" type="jQueryEvent">
        /// </param>
        if (this._jqMbYesButton.attr('src').indexOf('-off') >= 0) {
            this._jqMbYesButton.attr({ src: this._jqMbYesButton.attr('src').replaceAll('-off', '-on') });
        }
    },
    
    _onMbYesButtonMouseOut$1: function ClientScript_UI_ConfirmRemove$_onMbYesButtonMouseOut$1(e) {
        /// <param name="e" type="jQueryEvent">
        /// </param>
        if (this._jqMbYesButton.attr('src').indexOf('-on') >= 0) {
            this._jqMbYesButton.attr({ src: this._jqMbYesButton.attr('src').replaceAll('-on', '-off') });
        }
    },
    
    template: "\r\n\r\n<style>\r\n.modalBox {width:508px; height:245px; background:url(/Content/Images/Confirm/bgModalStatic.png) no-repeat; text-align:center;z-index:101;}\r\n\t.modalBox img {border:0; outline:none;}\r\n\t.modalBox .mbContent {font:26px Arial, Helvetica, sans-serif; color:#474644; padding:76px 20px 0 20px; margin:0;}\r\n\t\t.modalBox .mbContent span {color:#d03f14;}\r\n\t.modalBox .mbBtns {padding:18px 0 0;}\r\n\t\t.modalBox .mbNo {margin-right:13px;}\r\n\t\t.modalBox .mbYes {margin-left:13px;}\r\n</style>\r\n<div style='display:none;z-index:101;'>\r\n<div class='modalBox'>\r\n\t<div class='mbContent'>\r\n\t\t<div xid='text'><span>Remove</span> from list?</div>\r\n\t\t<div class='mbBtns'>\r\n\t\t\t<a href='javascript:;' xid='mbNo'><img src='/Content/Images/Confirm/btnNoCancel-off.png' alt='Cancel' class='mbNo mbBtn' xid='mbNoButton' /></a><a href='javascript:;' xid='mbYes'><img src='/Content/Images/Confirm/btnYesRemove-off.png' alt='Remove' class='mbYes mbBtn' xid='mbYesButton' /></a>\r\n\t\t</div>\r\n\t</div>\r\n</div><!--end .modalBox-->\r\n</div>\r\n\r\n"
}


Type.registerNamespace('MdSc.Client.Sh.U');

////////////////////////////////////////////////////////////////////////////////
// MdSc.Client.Sh.U._facebook

MdSc.Client.Sh.U._facebook = function MdSc_Client_Sh_U__facebook() {
}
MdSc.Client.Sh.U._facebook.getFB = function MdSc_Client_Sh_U__facebook$getFB(win) {
    /// <param name="win" type="WindowInstance">
    /// </param>
    /// <returns type="FB"></returns>
    if (ss.isNullOrUndefined(win)) {
        win = window.self;
    }
    var fb = (win.FB || null);
    if (ss.isNullOrUndefined(fb)) {
        throw new Error('Error detecting Facebook API.');
    }
    return fb;
}
MdSc.Client.Sh.U._facebook.parsePermissions = function MdSc_Client_Sh_U__facebook$parsePermissions(permissions) {
    /// <param name="permissions" type="Object">
    /// </param>
    /// <returns type="Array" elementType="String"></returns>
    var permissionsAsObject = null;
    if (Type.canCast(permissions, String)) {
        var permissionsAsString = permissions;
        if (permissionsAsString.startsWith('[') || permissionsAsString.startsWith('{')) {
            permissionsAsObject = JSON.parse(permissionsAsString);
        }
        else {
            if (permissionsAsString.indexOf(',') !== -1) {
                return permissionsAsString.split(',');
            }
            else if (permissionsAsString.indexOf(';') !== -1) {
                return permissionsAsString.split(';');
            }
            else if (!!(permissionsAsString = permissionsAsString.trim()).length) {
                return [ permissionsAsString ];
            }
            else {
                return [];
            }
        }
    }
    else {
        permissionsAsObject = permissions;
    }
    if (permissionsAsObject == null) {
        throw new Error('uknown permissions format');
    }
    var permissionsAsDictionary = permissionsAsObject;
    var extendedPermissions = permissionsAsDictionary['extended'];
    return extendedPermissions;
}


Type.registerNamespace('SharpUI');

////////////////////////////////////////////////////////////////////////////////
// SharpUI.Position

SharpUI.Position = function() { 
    /// <field name="unspecified" type="Number" integer="true" static="true">
    /// </field>
    /// <field name="absolute" type="Number" integer="true" static="true">
    /// </field>
    /// <field name="relative" type="Number" integer="true" static="true">
    /// </field>
    /// <field name="fixed" type="Number" integer="true" static="true">
    /// </field>
};
SharpUI.Position.prototype = {
    unspecified: 0, 
    absolute: 1, 
    relative: 2, 
    fixed: 3
}
SharpUI.Position.registerEnum('SharpUI.Position', false);


////////////////////////////////////////////////////////////////////////////////
// SharpUI.MouseCaptureState

SharpUI.MouseCaptureState = function() { 
    /// <field name="begin" type="Number" integer="true" static="true">
    /// </field>
    /// <field name="move" type="Number" integer="true" static="true">
    /// </field>
    /// <field name="end" type="Number" integer="true" static="true">
    /// </field>
};
SharpUI.MouseCaptureState.prototype = {
    begin: 0, 
    move: 1, 
    end: 2
}
SharpUI.MouseCaptureState.registerEnum('SharpUI.MouseCaptureState', false);


////////////////////////////////////////////////////////////////////////////////
// SharpUI.VerticalAlignment

SharpUI.VerticalAlignment = function() { 
    /// <field name="top" type="Number" integer="true" static="true">
    /// </field>
    /// <field name="center" type="Number" integer="true" static="true">
    /// </field>
    /// <field name="bottom" type="Number" integer="true" static="true">
    /// </field>
    /// <field name="stretch" type="Number" integer="true" static="true">
    /// </field>
};
SharpUI.VerticalAlignment.prototype = {
    top: 0, 
    center: 1, 
    bottom: 2, 
    stretch: 3
}
SharpUI.VerticalAlignment.registerEnum('SharpUI.VerticalAlignment', false);


////////////////////////////////////////////////////////////////////////////////
// SharpUI.HorizontalAlignment

SharpUI.HorizontalAlignment = function() { 
    /// <field name="left" type="Number" integer="true" static="true">
    /// </field>
    /// <field name="center" type="Number" integer="true" static="true">
    /// </field>
    /// <field name="right" type="Number" integer="true" static="true">
    /// </field>
    /// <field name="stretch" type="Number" integer="true" static="true">
    /// </field>
};
SharpUI.HorizontalAlignment.prototype = {
    left: 0, 
    center: 1, 
    right: 2, 
    stretch: 3
}
SharpUI.HorizontalAlignment.registerEnum('SharpUI.HorizontalAlignment', false);


////////////////////////////////////////////////////////////////////////////////
// SharpUI.TemplateControl

SharpUI.TemplateControl = function SharpUI_TemplateControl(oTemplate) {
    /// <param name="oTemplate" type="Object">
    /// </param>
    /// <field name="_attributeNameLocalId" type="String" static="true">
    /// </field>
    /// <field name="_attributeNameControlClass" type="String" static="true">
    /// </field>
    /// <field name="_dataNameControl" type="String" static="true">
    /// </field>
    /// <field name="cssClassNameControl" type="String" static="true">
    /// </field>
    /// <field name="cssClassNameControlUnadded" type="String" static="true">
    /// </field>
    /// <field name="_idPrefixAutoRewrite" type="String" static="true">
    /// </field>
    /// <field name="_cssClassNamePrefixAutoRewrite" type="String" static="true">
    /// </field>
    /// <field name="_jqRootElement" type="jQueryObject">
    /// </field>
    /// <field name="_strInstanceId" type="String">
    /// </field>
    /// <field name="_bStaticConstructionFinished" type="Boolean" static="true">
    /// </field>
    /// <field name="_hash_templateCache" type="Object" static="true">
    /// Cache of html templates for each known type.
    /// </field>
    /// <field name="_hash_processedCss" type="Object" static="true">
    /// </field>
    /// <field name="_documentTreeCheckInterval" type="Number" integer="true" static="true">
    /// </field>
    /// <field name="__addedToDocument" type="EventHandler">
    /// </field>
    /// <field name="__removedFromDocument" type="EventHandler">
    /// </field>
    /// <field name="__presented" type="EventHandler">
    /// </field>
    /// <field name="_bPresented" type="Boolean">
    /// </field>
    /// <field name="_iCheckParentIntervalId" type="Number" integer="true" static="true">
    /// </field>
    /// <field name="_hash_strControlIdsKnownInDocument" type="Object" static="true">
    /// </field>
    /// <field name="_hash_cachedTypeNameResolves" type="Object" static="true">
    /// </field>
    /// <field name="_iAutoIdGeneratorCounter" type="Number" integer="true" static="true">
    /// </field>
    /// <field name="_iInstanceIdGeneratorCounter" type="Number" integer="true" static="true">
    /// </field>
    /// <field name="_hash_oNamedChildElements" type="Object">
    /// </field>
    /// <field name="_hash_oNamedChildControls" type="Object">
    /// </field>
    /// <field name="_hash_rewrittenGroupNames" type="Object">
    /// </field>
    /// <field name="_hash_controlFieldMappingByControl" type="Object" static="true">
    /// Each entry KVP is a type=&gt;Dictionary. each inner dictionary is a xid(string)=&gt;field(string).
    /// </field>
    /// <field name="_mouseCaptureHandler" type="SharpUI.MouseCaptureHandler" static="true">
    /// </field>
    /// <field name="_jqMouseCaptureGlassBarrier" type="jQueryObject" static="true">
    /// </field>
    /// <field name="_layoutPosition" type="SharpUI.Position">
    /// </field>
    this._layoutPosition = SharpUI.Position.unspecified;
    if (!SharpUI.TemplateControl._bStaticConstructionFinished) {
        SharpUI.TemplateControl._staticConstructor();
    }
    this._strInstanceId = SharpUI.TemplateControl._generateNewInstanceId();
    var strTemplate;
    if (ss.isNullOrUndefined(oTemplate)) {
        strTemplate = SharpUI.TemplateControl._findTemplate(this);
        if (String.isNullOrEmpty(strTemplate)) {
            throw new Error(Type.getInstanceType(this).get_fullName() + ' is missing a Template member and no template was provided.');
        }
    }
    else {
        if (Type.canCast(oTemplate, String)) {
            strTemplate = oTemplate;
        }
        else {
            var jqTemplate = $(oTemplate);
            strTemplate = '<' + jqTemplate[0].tagName + '>' + jqTemplate.html() + '</' + jqTemplate[0].tagName + '>';
        }
    }
    this._hash_oNamedChildControls = {};
    this._hash_oNamedChildElements = {};
    var jqHead = $('head');
    if (ss.isNullOrUndefined(strTemplate)) {
        strTemplate = this.template;
    }
    if (String.isNullOrEmpty(strTemplate)) {
        throw new Error(Type.getInstanceType(this).get_fullName() + ' is missing a Template member.');
    }
    var newId = SharpUI.TemplateControl._generateNewAutoId();
    var numOtherControlsWithId = $('#' + newId).length;
    if (!!numOtherControlsWithId) {
        throw new Error('Auto generated id conflict.');
    }
    var jqContent = $(strTemplate.replaceAll('`', '"'));
    var strStyleRules = '';
    jqContent.filter('style').each(function(i, e) {
        var jqElement = $(e);
        strStyleRules += jqElement.html();
        jqElement.remove();
    });
    jqContent = jqContent.not('style').remove();
    if (!String.isNullOrEmpty(jqContent.attr('id'))) {
        throw new Error("Global ID's not permitted. Element with ID \"" + jqContent.attr('id') + '" found.');
    }
    jqContent.removeAttr('id');
    this._jqRootElement = jqContent;
    this._jqRootElement.data(SharpUI.TemplateControl._dataNameControl, this);
    jqContent.find('*[' + SharpUI.TemplateControl._attributeNameLocalId + ']').each(ss.Delegate.create(this, function(i, e) {
        var jqElement = $(e);
        if (!String.isNullOrEmpty(jqElement.attr(SharpUI.TemplateControl._attributeNameControlClass))) {
            return;
        }
        var strLocalId = SharpUI.TemplateControl._getLocalId(jqElement);
        if (strLocalId == null) {
            return;
        }
        this._hash_oNamedChildElements[strLocalId] = jqElement;
        if (!String.isNullOrEmpty(jqElement.attr('id'))) {
            throw new Error("Global ID's not permitted. Element with ID \"" + jqElement.attr('id') + '" found.');
        }
        jqElement.removeAttr('id');
    }));
    var currentType = Type.getInstanceType(this);
    var currentTopLevelNamespace = currentType.get_fullName().substr(0, currentType.get_fullName().indexOf('.'));
    this._jqRootElement.addClass(SharpUI.TemplateControl.cssClassNameControl);
    this._jqRootElement.addClass(SharpUI.TemplateControl.cssClassNameControlUnadded);
    jqContent.find('div[' + SharpUI.TemplateControl._attributeNameControlClass + ']').each(ss.Delegate.create(this, function(index, element) {
        var jqElement = $(element);
        var strChildTypeName = jqElement.attr(SharpUI.TemplateControl._attributeNameControlClass);
        var strChildTypeNameResolved = SharpUI.TemplateControl._resolveTypeName(strChildTypeName, currentTopLevelNamespace);
        var oChildType = Type.getType(strChildTypeNameResolved);
        if (ss.isNullOrUndefined(oChildType)) {
            throw new Error('Could not locate type "' + (strChildTypeNameResolved || strChildTypeName) + '"');
        }
        var childControl = Type.safeCast(new oChildType(null), SharpUI.TemplateControl);
        var strLocalId = SharpUI.TemplateControl._getLocalId(jqElement) || SharpUI.TemplateControl._generateNewAutoId();
        if (strLocalId != null) {
            this._hash_oNamedChildControls[strLocalId] = childControl;
        }
        var strClass = jqElement.attr('class');
        var strStyle = jqElement.attr('style');
        if (!String.isNullOrEmpty(strClass)) {
            var strClassFromTemplate = childControl.get_rootElement().attr('class') || '';
            childControl.get_rootElement().attr('class', strClassFromTemplate + ' ' + strClass);
        }
        if (!String.isNullOrEmpty(strStyle)) {
            var strStyleFromTemplate = childControl.get_rootElement().attr('style') || '';
            childControl.get_rootElement().attr('style', strStyleFromTemplate + ' ' + strStyle);
        }
        for (var i = 0, m = jqElement[0].attributes.length; i < m; ++i) {
            var a = jqElement[0].attributes[i];
            if ($.browser.version === '7.0' && $.browser.msie && !a.specified) {
                continue;
            }
            var attributeName = a.name.toLowerCase();
            switch (attributeName) {
                case 'id':
                case 'xid':
                case 'class':
                case 'style':
                case 'control':
                    break;
                default:
                    childControl.get_rootElement().attr(a.name, a.value);
                    break;
            }
        }
        jqElement.removeAttr('id').after(childControl.get_rootElement()).remove();
        if (strLocalId != null) {
            childControl.get_rootElement().attr('xid', strLocalId);
        }
        childControl.get_rootElement().attr('control', jqElement.attr(SharpUI.TemplateControl._attributeNameControlClass));
        var jqChildContent = jqElement.find('>*');
        if (jqChildContent.length > 0) {
            childControl.processChildContent(jqChildContent);
        }
    }));
    var jqRadioInputs = this._jqRootElement.find('input[type=radio]');
    var hash_rewrittenGroupNames = {};
    jqRadioInputs.each(function(index, element) {
        var jqRadio = $(element);
        var strGroupName = jqRadio.attr('name');
        if (String.isNullOrEmpty(strGroupName)) {
            return;
        }
        var strNewGroupName;
        if (Object.keyExists(hash_rewrittenGroupNames, strGroupName)) {
            strNewGroupName = hash_rewrittenGroupNames[strGroupName];
        }
        else {
            hash_rewrittenGroupNames[strGroupName] = strNewGroupName = SharpUI.TemplateControl._generateNewAutoId();
        }
        jqRadio.attr('name', strNewGroupName);
        if (String.isNullOrEmpty(jqRadio.attr('id'))) {
            jqRadio.attr('id', SharpUI.TemplateControl._generateNewAutoId());
        }
    });
    this._hash_rewrittenGroupNames = hash_rewrittenGroupNames;
    var jqLabels = this._jqRootElement.find('label[for]');
    jqLabels.each(ss.Delegate.create(this, function(index, element) {
        if (this._bPresented) {
        }
        var jqLabelElement = $(element);
        var strForId = jqLabelElement.attr('for');
        var jqTargetElement = this.tryGetElement(strForId);
        if (jqTargetElement == null) {
            return;
        }
        var strTargetElementNewId = jqTargetElement.attr('id');
        if (String.isNullOrEmpty(strTargetElementNewId)) {
            jqTargetElement.attr('id', strTargetElementNewId = SharpUI.TemplateControl._generateNewAutoId());
        }
        jqLabelElement.attr('for', strTargetElementNewId);
        return;
    }));
    if (!!strStyleRules.length) {
        SharpUI.TemplateControl._processCss(this, strStyleRules);
    }
    this._autoFillMemberFields();
    SharpUI.AdvancedLayout.autoEnable(this._jqRootElement);
}
SharpUI.TemplateControl._staticConstructor = function SharpUI_TemplateControl$_staticConstructor() {
    if (SharpUI.TemplateControl._bStaticConstructionFinished) {
        throw new Error('Static construction already finished.');
    }
    SharpUI.TemplateControl._initDocumentDetection();
    SharpUI.TemplateControl._initDocumentMouseTracking();
    SharpUI.TemplateControl._bStaticConstructionFinished = true;
}
SharpUI.TemplateControl._findTemplate = function SharpUI_TemplateControl$_findTemplate(templateControl) {
    /// <summary>
    /// For the given template control, retrieve its html template.
    /// </summary>
    /// <param name="templateControl" type="SharpUI.TemplateControl">
    /// </param>
    /// <returns type="String"></returns>
    var templateTypeName = Type.getInstanceType(templateControl).get_fullName();
    if (!Object.keyExists(SharpUI.TemplateControl._hash_templateCache, templateTypeName)) {
        var strTemplate = templateControl.template;
        if (!String.isNullOrEmpty(strTemplate)) {
            SharpUI.TemplateControl._hash_templateCache[templateTypeName] = strTemplate;
        }
        else {
            var $dict1 = templateControl;
            for (var $key2 in $dict1) {
                var kvp = { key: $key2, value: $dict1[$key2] };
                if (!(Type.canCast(kvp.value, String))) {
                    continue;
                }
                if (!kvp.key.startsWith('$')) {
                    continue;
                }
                var strTmp = (kvp.value).trim();
                if (strTmp.startsWith('<')) {
                    SharpUI.TemplateControl._hash_templateCache[templateTypeName] = kvp.value;
                }
            }
        }
    }
    return (SharpUI.TemplateControl._hash_templateCache[templateTypeName] || null);
}
SharpUI.TemplateControl._fromRootElement = function SharpUI_TemplateControl$_fromRootElement(elem) {
    /// <summary>
    /// Helper method. Retrieves the TemplateControl instance from its jQuery root element.
    /// </summary>
    /// <param name="elem" type="Object">
    /// </param>
    /// <returns type="SharpUI.TemplateControl"></returns>
    if (elem == null) {
        throw new Error('Element null.');
    }
    var jqElem = $(elem);
    var tc = Type.safeCast(jqElem.data(SharpUI.TemplateControl._dataNameControl), SharpUI.TemplateControl);
    if (tc == null) {
        throw new Error('Provided element is not the root of a Template Control.');
    }
    return tc;
}
SharpUI.TemplateControl._processCss = function SharpUI_TemplateControl$_processCss(rootControl, strRawCss) {
    /// <param name="rootControl" type="SharpUI.TemplateControl">
    /// </param>
    /// <param name="strRawCss" type="String">
    /// </param>
    var strControlType = Type.getInstanceType(rootControl).get_fullName();
    var bIsNewStyleSet = false;
    var hash_xidsToCssClasses = SharpUI.TemplateControl._hash_processedCss[strControlType] || null;
    if (hash_xidsToCssClasses == null) {
        hash_xidsToCssClasses = {};
        bIsNewStyleSet = true;
    }
    if (bIsNewStyleSet) {
        var strProcessedCss = strRawCss.replace(new RegExp('#[a-zA-Z]\\w*', 'g'), function(s) {
            var sSub = s.substr(1);
            if (sSub === 'this') {
                hash_xidsToCssClasses[sSub] = hash_xidsToCssClasses[sSub] || SharpUI.TemplateControl._generateNewAutoCssClass();
                return '.' + hash_xidsToCssClasses[sSub] + '/* ' + s + ' */';
            }
            var jqElement = rootControl._hash_oNamedChildElements[sSub] || null;
            if (jqElement != null) {
                hash_xidsToCssClasses[sSub] = hash_xidsToCssClasses[sSub] || SharpUI.TemplateControl._generateNewAutoCssClass();
                return '.' + hash_xidsToCssClasses[sSub] + '/* ' + s + ' */';
            }
            var oControl = rootControl._hash_oNamedChildControls[sSub] || null;
            if (oControl != null) {
                hash_xidsToCssClasses[sSub] = hash_xidsToCssClasses[sSub] || SharpUI.TemplateControl._generateNewAutoCssClass();
                return '.' + hash_xidsToCssClasses[sSub] + '/* ' + s + ' */';
            }
            return s;
        });
        var jqStyle;
        if ($.browser.msie) {
            jqStyle = $('<style type="text/css">' + strProcessedCss + '</style>');
        }
        else {
            jqStyle = $('<style type="text/css"></style>');
            jqStyle.html(strProcessedCss);
        }
        $('head').append(jqStyle);
        SharpUI.TemplateControl._hash_processedCss[strControlType] = hash_xidsToCssClasses;
    }
    var $dict1 = hash_xidsToCssClasses;
    for (var $key2 in $dict1) {
        var kvp = { key: $key2, value: $dict1[$key2] };
        var key = kvp.key;
        if (key === 'this') {
            rootControl._jqRootElement.addClass(kvp.value);
            continue;
        }
        var jqElement = rootControl._hash_oNamedChildElements[key] || null;
        if (jqElement != null) {
            jqElement.addClass(kvp.value);
            continue;
        }
        var oControl = rootControl._hash_oNamedChildControls[key] || null;
        if (oControl != null) {
            oControl.get_rootElement().addClass(kvp.value);
            continue;
        }
        throw new Error('CSS rule found for no corresponding element/control.');
    }
}
SharpUI.TemplateControl._initDocumentDetection = function SharpUI_TemplateControl$_initDocumentDetection() {
    if (!SharpUI.TemplateControl._iCheckParentIntervalId) {
        SharpUI.TemplateControl._iCheckParentIntervalId = window.setInterval(SharpUI.TemplateControl._onIntervalCheckParent, SharpUI.TemplateControl._documentTreeCheckInterval);
    }
}
SharpUI.TemplateControl._onIntervalCheckParent = function SharpUI_TemplateControl$_onIntervalCheckParent() {
    var arr_controlsToNotifyAdded = [];
    var $dict1 = SharpUI.TemplateControl._hash_strControlIdsKnownInDocument;
    for (var $key2 in $dict1) {
        var kvp = { key: $key2, value: $dict1[$key2] };
        var strInstanceId = kvp.key;
        var control = kvp.value;
        if (!control.get__isInDocument()) {
            delete SharpUI.TemplateControl._hash_strControlIdsKnownInDocument[strInstanceId];
            control._notifyRemovedFromDocument();
            control.get_rootElement().addClass(SharpUI.TemplateControl.cssClassNameControlUnadded);
        }
        if (!control._bPresented && control.__presented != null) {
            if (control.get_rootElement().is(':visible')) {
                control._notifyPresented();
                control._bPresented = true;
            }
        }
    }
    var hash_strControlsFound = {};
    var newControls = $('.' + SharpUI.TemplateControl.cssClassNameControlUnadded);
    newControls.each(function(i, e) {
        var rootElement = $(e);
        var control = rootElement.data(SharpUI.TemplateControl._dataNameControl);
        if (control == null) {
            throw new Error('Control root element missing Control data. Did you use jQuery empty() or remove() by mistake?');
        }
        var strInstanceId = control._strInstanceId;
        if (String.isNullOrEmpty(strInstanceId.trim())) {
            throw new Error('Found control with empty instance id.');
        }
        hash_strControlsFound[strInstanceId] = null;
        if (!Object.keyExists(SharpUI.TemplateControl._hash_strControlIdsKnownInDocument, strInstanceId)) {
            SharpUI.TemplateControl._hash_strControlIdsKnownInDocument[strInstanceId] = control;
            arr_controlsToNotifyAdded.add(control);
            rootElement.removeClass(SharpUI.TemplateControl.cssClassNameControlUnadded);
        }
    });
    for (var i = arr_controlsToNotifyAdded.length - 1; i >= 0; --i) {
        var controlToNotify = arr_controlsToNotifyAdded[i];
        controlToNotify._notifyAddedToDocument();
    }
    arr_controlsToNotifyAdded.clear();
}
SharpUI.TemplateControl._resolveTypeName = function SharpUI_TemplateControl$_resolveTypeName(strShortName, startingNamespace) {
    /// <param name="strShortName" type="String">
    /// </param>
    /// <param name="startingNamespace" type="String">
    /// </param>
    /// <returns type="String"></returns>
    if (ss.isNullOrUndefined(startingNamespace)) {
        throw new Error('Missing starting namespace.');
    }
    if (Object.keyExists(SharpUI.TemplateControl._hash_cachedTypeNameResolves, strShortName)) {
        return SharpUI.TemplateControl._hash_cachedTypeNameResolves[strShortName];
    }
    var strResolvedTypeName = startingNamespace + '.' + strShortName;
    if (Type.getType(strResolvedTypeName) != null) {
        return (SharpUI.TemplateControl._hash_cachedTypeNameResolves[strShortName] = strResolvedTypeName);
    }
    strResolvedTypeName = startingNamespace + '.' + '_' + strShortName.substr(0, 1).toLowerCase() + strShortName.substr(1);
    if (Type.getType(strResolvedTypeName) != null) {
        return (SharpUI.TemplateControl._hash_cachedTypeNameResolves[strShortName] = strResolvedTypeName);
    }
    var d = Type.getType(startingNamespace);
    var $dict1 = d;
    for (var $key2 in $dict1) {
        var kvp = { key: $key2, value: $dict1[$key2] };
        if (!Type.isNamespace(kvp.value)) {
            continue;
        }
        var namespaceName = kvp.value.getName();
        strResolvedTypeName = SharpUI.TemplateControl._resolveTypeName(strShortName, namespaceName);
        if (strResolvedTypeName != null) {
            return (SharpUI.TemplateControl._hash_cachedTypeNameResolves[strShortName] = strResolvedTypeName);
        }
    }
    return null;
}
SharpUI.TemplateControl._generateNewAutoId = function SharpUI_TemplateControl$_generateNewAutoId() {
    /// <returns type="String"></returns>
    return SharpUI.TemplateControl._idPrefixAutoRewrite + SharpUI.TemplateControl._iAutoIdGeneratorCounter++;
}
SharpUI.TemplateControl._generateNewAutoCssClass = function SharpUI_TemplateControl$_generateNewAutoCssClass() {
    /// <returns type="String"></returns>
    return SharpUI.TemplateControl._cssClassNamePrefixAutoRewrite + SharpUI.TemplateControl._iAutoIdGeneratorCounter++;
}
SharpUI.TemplateControl._getLocalId = function SharpUI_TemplateControl$_getLocalId(jqElement) {
    /// <param name="jqElement" type="jQueryObject">
    /// </param>
    /// <returns type="String"></returns>
    var strLocalId = jqElement.attr(SharpUI.TemplateControl._attributeNameLocalId);
    if (String.isNullOrEmpty(strLocalId)) {
        return null;
    }
    strLocalId = strLocalId.trim();
    if (!strLocalId.length) {
        return null;
    }
    return strLocalId;
}
SharpUI.TemplateControl._generateNewInstanceId = function SharpUI_TemplateControl$_generateNewInstanceId() {
    /// <returns type="String"></returns>
    return (SharpUI.TemplateControl._iInstanceIdGeneratorCounter++).toString();
}
SharpUI.TemplateControl._initDocumentMouseTracking = function SharpUI_TemplateControl$_initDocumentMouseTracking() {
    var jqDocument = $(window.document);
    var jqBarrier = $('<div></div>');
    jqBarrier.css({ position: 'fixed', left: '0px', top: '0px', width: '100%', height: '100%', 'z-index': '500' });
    jqBarrier.hide();
    SharpUI.TemplateControl._jqMouseCaptureGlassBarrier = jqBarrier;
    jqDocument.append(jqBarrier);
    jqDocument.mousemove(SharpUI.TemplateControl._onMouseMoveDocument);
    jqDocument.mousedown(SharpUI.TemplateControl._onMouseDownDocument);
    jqDocument.mouseup(SharpUI.TemplateControl._onMouseUpDocument);
}
SharpUI.TemplateControl._onMouseDownDocument = function SharpUI_TemplateControl$_onMouseDownDocument(e) {
    /// <param name="e" type="jQueryEvent">
    /// </param>
}
SharpUI.TemplateControl._onMouseMoveDocument = function SharpUI_TemplateControl$_onMouseMoveDocument(e) {
    /// <param name="e" type="jQueryEvent">
    /// </param>
    if (SharpUI.TemplateControl._mouseCaptureHandler == null) {
        return;
    }
    SharpUI.TemplateControl._mouseCaptureHandler(SharpUI.MouseCaptureState.move, SharpUI.TemplateControl._makeJQueryPosition(e.pageX, e.pageY));
    e.preventDefault();
    e.stopPropagation();
}
SharpUI.TemplateControl._onMouseUpDocument = function SharpUI_TemplateControl$_onMouseUpDocument(e) {
    /// <param name="e" type="jQueryEvent">
    /// </param>
    if (SharpUI.TemplateControl._mouseCaptureHandler == null) {
        return;
    }
    SharpUI.TemplateControl._mouseCaptureHandler(SharpUI.MouseCaptureState.end, SharpUI.TemplateControl._makeJQueryPosition(e.pageX, e.pageY));
    SharpUI.TemplateControl._mouseCaptureHandler = null;
    e.preventDefault();
    e.stopPropagation();
    SharpUI.TemplateControl._jqMouseCaptureGlassBarrier.hide();
}
SharpUI.TemplateControl._makeJQueryPosition = function SharpUI_TemplateControl$_makeJQueryPosition(left, top) {
    /// <param name="left" type="Number">
    /// </param>
    /// <param name="top" type="Number">
    /// </param>
    /// <returns type="jQueryPosition"></returns>
    return { left: left, top: top };
}
SharpUI.TemplateControl.prototype = {
    _jqRootElement: null,
    
    get_rootElement: function SharpUI_TemplateControl$get_rootElement() {
        /// <value type="jQueryObject"></value>
        return this._jqRootElement;
    },
    
    _strInstanceId: null,
    
    processChildContent: function SharpUI_TemplateControl$processChildContent(jqChildContent) {
        /// <summary>
        /// If this control instance had content placed inside its declaration,
        /// this method is called with said content.
        /// </summary>
        /// <param name="jqChildContent" type="jQueryObject">
        /// </param>
    },
    
    add_addedToDocument: function SharpUI_TemplateControl$add_addedToDocument(value) {
        /// <param name="value" type="Function" />
        this.__addedToDocument = ss.Delegate.combine(this.__addedToDocument, value);
    },
    remove_addedToDocument: function SharpUI_TemplateControl$remove_addedToDocument(value) {
        /// <param name="value" type="Function" />
        this.__addedToDocument = ss.Delegate.remove(this.__addedToDocument, value);
    },
    
    __addedToDocument: null,
    
    add_removedFromDocument: function SharpUI_TemplateControl$add_removedFromDocument(value) {
        /// <param name="value" type="Function" />
        this.__removedFromDocument = ss.Delegate.combine(this.__removedFromDocument, value);
    },
    remove_removedFromDocument: function SharpUI_TemplateControl$remove_removedFromDocument(value) {
        /// <param name="value" type="Function" />
        this.__removedFromDocument = ss.Delegate.remove(this.__removedFromDocument, value);
    },
    
    __removedFromDocument: null,
    
    add_presented: function SharpUI_TemplateControl$add_presented(value) {
        /// <param name="value" type="Function" />
        this.__presented = ss.Delegate.combine(this.__presented, value);
    },
    remove_presented: function SharpUI_TemplateControl$remove_presented(value) {
        /// <param name="value" type="Function" />
        this.__presented = ss.Delegate.remove(this.__presented, value);
    },
    
    __presented: null,
    _bPresented: false,
    
    _notifyAddedToDocument: function SharpUI_TemplateControl$_notifyAddedToDocument() {
        if (this.__addedToDocument != null) {
            this.__addedToDocument(this, null);
        }
    },
    
    _notifyRemovedFromDocument: function SharpUI_TemplateControl$_notifyRemovedFromDocument() {
        if (this.__removedFromDocument != null) {
            this.__removedFromDocument(this, null);
        }
    },
    
    _notifyPresented: function SharpUI_TemplateControl$_notifyPresented() {
        if (this.__presented != null) {
            this.__presented(this, null);
        }
    },
    
    get_documentBody: function SharpUI_TemplateControl$get_documentBody() {
        /// <value type="jQueryObject"></value>
        if (this.get__isInDocument()) {
            return $(window.document.body);
        }
        else {
            return null;
        }
    },
    
    get__isInDocument: function SharpUI_TemplateControl$get__isInDocument() {
        /// <value type="Boolean"></value>
        var e = this.get_rootElement()[0];
        while (true) {
            e = e.parentNode;
            if (e == null) {
                return false;
            }
            if (e.nodeType === 9) {
                return true;
            }
        }
    },
    
    _hash_oNamedChildElements: null,
    
    getElement: function SharpUI_TemplateControl$getElement(strId) {
        /// <param name="strId" type="String">
        /// </param>
        /// <returns type="jQueryObject"></returns>
        var o = this._hash_oNamedChildElements[strId];
        if (ss.isNullOrUndefined(o)) {
            throw new Error('Element by id "' + strId + '" not found.');
        }
        return o;
    },
    
    tryGetElement: function SharpUI_TemplateControl$tryGetElement(strId) {
        /// <param name="strId" type="String">
        /// </param>
        /// <returns type="jQueryObject"></returns>
        var o = this._hash_oNamedChildElements[strId];
        return o || null;
    },
    
    _hash_oNamedChildControls: null,
    
    getControl: function SharpUI_TemplateControl$getControl(strId) {
        /// <param name="strId" type="String">
        /// </param>
        /// <returns type="SharpUI.TemplateControl"></returns>
        var o = this._hash_oNamedChildControls[strId];
        if (ss.isNullOrUndefined(o)) {
            throw new Error('Control by id "' + strId + '" not found.');
        }
        return o;
    },
    
    _hash_rewrittenGroupNames: null,
    
    getGroup: function SharpUI_TemplateControl$getGroup(formFieldGroupname) {
        /// <param name="formFieldGroupname" type="String">
        /// </param>
        /// <returns type="jQueryObject"></returns>
        var rewrittenName = this._hash_rewrittenGroupNames[formFieldGroupname];
        if (ss.isNullOrUndefined(rewrittenName)) {
            throw new Error('Group by name "' + formFieldGroupname + '" not found.');
        }
        return this.get_rootElement().find('*[name=' + rewrittenName + ']');
    },
    
    _autoFillMemberFields: function SharpUI_TemplateControl$_autoFillMemberFields() {
        var typeNameThis = Type.getInstanceType(this).get_fullName();
        if (!Object.keyExists(SharpUI.TemplateControl._hash_controlFieldMappingByControl, typeNameThis)) {
            var newMapping = {};
            var thisAsDictionary = this;
            var $dict1 = this._hash_oNamedChildElements;
            for (var $key2 in $dict1) {
                var kvpElement = { key: $key2, value: $dict1[$key2] };
                var loopCount = 0;
                var strFieldNameTemp = null;
                while (loopCount >= 0) {
                    switch (loopCount) {
                        case 0:
                            strFieldNameTemp = '_' + kvpElement.key;
                            break;
                        case 1:
                            strFieldNameTemp = '_jq' + kvpElement.key;
                            break;
                        case 2:
                            if (kvpElement.key.length <= 1) {
                                loopCount = -10;
                                break;
                            }
                            strFieldNameTemp = '_' + kvpElement.key.substr(0, 1).toLowerCase() + kvpElement.key.substr(1);
                            break;
                        case 3:
                            strFieldNameTemp = '_jq' + kvpElement.key.substr(0, 1).toUpperCase() + kvpElement.key.substr(1);
                            break;
                        default:
                            loopCount = -10;
                            break;
                    }
                    var $dict3 = thisAsDictionary;
                    for (var $key4 in $dict3) {
                        var kvpField = { key: $key4, value: $dict3[$key4] };
                        if (kvpField.key.startsWith(strFieldNameTemp) && Math.abs(kvpField.key.length - strFieldNameTemp.length) <= 2) {
                            if (kvpField.value == null) {
                                newMapping[kvpElement.key] = kvpField.key;
                                loopCount = -10;
                            }
                        }
                    }
                    ++loopCount;
                }
            }
            var $dict5 = this._hash_oNamedChildControls;
            for (var $key6 in $dict5) {
                var kvpControl = { key: $key6, value: $dict5[$key6] };
                var loopCount = 0;
                var strFieldNameTemp = null;
                while (loopCount >= 0) {
                    switch (loopCount) {
                        case 0:
                            strFieldNameTemp = '_' + kvpControl.key;
                            break;
                        case 1:
                            strFieldNameTemp = '_o' + kvpControl.key;
                            break;
                        case 2:
                            if (kvpControl.key.length <= 1) {
                                loopCount = -10;
                                break;
                            }
                            strFieldNameTemp = '_' + kvpControl.key.substr(0, 1).toLowerCase() + kvpControl.key.substr(1);
                            break;
                        case 3:
                            strFieldNameTemp = '_o' + kvpControl.key.substr(0, 1).toUpperCase() + kvpControl.key.substr(1);
                            break;
                        default:
                            loopCount = -10;
                            break;
                    }
                    var $dict7 = thisAsDictionary;
                    for (var $key8 in $dict7) {
                        var kvpField = { key: $key8, value: $dict7[$key8] };
                        if (kvpField.key.startsWith(strFieldNameTemp) && Math.abs(kvpField.key.length - strFieldNameTemp.length) <= 2) {
                            if (kvpField.value == null) {
                                newMapping[kvpControl.key] = kvpField.key;
                                loopCount = -10;
                            }
                        }
                    }
                    ++loopCount;
                }
            }
            SharpUI.TemplateControl._hash_controlFieldMappingByControl[typeNameThis] = newMapping;
        }
        var mapping = SharpUI.TemplateControl._hash_controlFieldMappingByControl[typeNameThis];
        var $dict9 = this._hash_oNamedChildElements;
        for (var $key10 in $dict9) {
            var kvp = { key: $key10, value: $dict9[$key10] };
            if (Object.keyExists(mapping, kvp.key)) {
                this[mapping[kvp.key]] = kvp.value;
            }
        }
        var $dict11 = this._hash_oNamedChildControls;
        for (var $key12 in $dict11) {
            var kvp = { key: $key12, value: $dict11[$key12] };
            if (Object.keyExists(mapping, kvp.key)) {
                this[mapping[kvp.key]] = kvp.value;
            }
        }
    },
    
    get_actualWidth: function SharpUI_TemplateControl$get_actualWidth() {
        /// <value type="Number"></value>
        if (!this.get__isInDocument()) {
            throw new Error('Control not added to document yet.');
        }
        return this.get_rootElement().outerWidth(false);
    },
    
    get_actualHeight: function SharpUI_TemplateControl$get_actualHeight() {
        /// <value type="Number"></value>
        if (!this.get__isInDocument()) {
            throw new Error('Control not added to document yet.');
        }
        return this.get_rootElement().outerHeight(false);
    },
    
    get_percentWidth: function SharpUI_TemplateControl$get_percentWidth() {
        /// <value type="Number"></value>
        throw new Error('Getter not supported.');
    },
    set_percentWidth: function SharpUI_TemplateControl$set_percentWidth(value) {
        /// <value type="Number"></value>
        this.get_rootElement().width(Math.round(value).toString() + '%');
        return value;
    },
    
    get_percentHeight: function SharpUI_TemplateControl$get_percentHeight() {
        /// <value type="Number"></value>
        throw new Error('Getter not supported.');
    },
    set_percentHeight: function SharpUI_TemplateControl$set_percentHeight(value) {
        /// <value type="Number"></value>
        this.get_rootElement().height(Math.round(value).toString() + '%');
        return value;
    },
    
    get_pixelWidth: function SharpUI_TemplateControl$get_pixelWidth() {
        /// <value type="Number"></value>
        throw new Error('Getter not supported.');
    },
    set_pixelWidth: function SharpUI_TemplateControl$set_pixelWidth(value) {
        /// <value type="Number"></value>
        this.get_rootElement().width(Math.round(value).toString() + 'px');
        return value;
    },
    
    get_pixelHeight: function SharpUI_TemplateControl$get_pixelHeight() {
        /// <value type="Number"></value>
        throw new Error('Getter not supported.');
    },
    set_pixelHeight: function SharpUI_TemplateControl$set_pixelHeight(value) {
        /// <value type="Number"></value>
        this.get_rootElement().height(Math.round(value).toString() + 'px');
        return value;
    },
    
    get_pixelLeft: function SharpUI_TemplateControl$get_pixelLeft() {
        /// <value type="Number"></value>
        throw new Error('Getter not supported.');
    },
    set_pixelLeft: function SharpUI_TemplateControl$set_pixelLeft(value) {
        /// <value type="Number"></value>
        this.get_rootElement().css('left', Math.round(value).toString() + 'px');
        return value;
    },
    
    get_pixelTop: function SharpUI_TemplateControl$get_pixelTop() {
        /// <value type="Number"></value>
        throw new Error('Getter not supported.');
    },
    set_pixelTop: function SharpUI_TemplateControl$set_pixelTop(value) {
        /// <value type="Number"></value>
        this.get_rootElement().css('top', Math.round(value).toString() + 'px');
        return value;
    },
    
    _captureMouse: function SharpUI_TemplateControl$_captureMouse(mouseEvent, h, cssMouseCursor) {
        /// <param name="mouseEvent" type="jQueryEvent">
        /// </param>
        /// <param name="h" type="SharpUI.MouseCaptureHandler">
        /// </param>
        /// <param name="cssMouseCursor" type="String">
        /// </param>
        cssMouseCursor = cssMouseCursor || null;
        if (SharpUI.TemplateControl._mouseCaptureHandler != null) {
            throw new Error('Mouse already being captured.');
        }
        if (h == null || mouseEvent == null) {
            throw new Error('Argument(s) were null.');
        }
        if (mouseEvent.type !== 'mousedown' && mouseEvent.type !== 'mousemove') {
            throw new Error("Event must be a 'mousedown' or 'mousemove' type.");
        }
        var pos = SharpUI.TemplateControl._makeJQueryPosition(mouseEvent.pageX, mouseEvent.pageY);
        h(SharpUI.MouseCaptureState.begin, pos);
        SharpUI.TemplateControl._mouseCaptureHandler = h;
        SharpUI.TemplateControl._jqMouseCaptureGlassBarrier.css('cursor', cssMouseCursor || '');
        SharpUI.TemplateControl._jqMouseCaptureGlassBarrier.show();
    },
    
    get_zIndex: function SharpUI_TemplateControl$get_zIndex() {
        /// <value type="Number" integer="true"></value>
        var zIndex;
        try {
            zIndex = Math.round(parseFloat(this.get_rootElement().css('z-index')));
        }
        catch ($e1) {
            zIndex = 0;
        }
        return zIndex;
    },
    set_zIndex: function SharpUI_TemplateControl$set_zIndex(value) {
        /// <value type="Number" integer="true"></value>
        this.get_rootElement().css('z-index', value.toString());
        return value;
    },
    
    get_layoutPosition: function SharpUI_TemplateControl$get_layoutPosition() {
        /// <value type="SharpUI.Position"></value>
        return this._layoutPosition;
    },
    set_layoutPosition: function SharpUI_TemplateControl$set_layoutPosition(value) {
        /// <value type="SharpUI.Position"></value>
        var cssValue;
        switch (value) {
            case SharpUI.Position.unspecified:
            default:
                cssValue = '';
                break;
            case SharpUI.Position.absolute:
                cssValue = 'absolute';
                break;
            case SharpUI.Position.relative:
                cssValue = 'relative';
                break;
            case SharpUI.Position.fixed:
                cssValue = 'fixed';
                break;
        }
        this.get_rootElement().css('position', cssValue);
        this._layoutPosition = value;
        return value;
    }
}


////////////////////////////////////////////////////////////////////////////////
// SharpUI.Thickness

SharpUI.Thickness = function SharpUI_Thickness(top, right, bottom, left) {
    /// <param name="top" type="Number">
    /// </param>
    /// <param name="right" type="Number">
    /// </param>
    /// <param name="bottom" type="Number">
    /// </param>
    /// <param name="left" type="Number">
    /// </param>
    /// <field name="bottom" type="Number">
    /// </field>
    /// <field name="left" type="Number">
    /// </field>
    /// <field name="top" type="Number">
    /// </field>
    /// <field name="right" type="Number">
    /// </field>
    if (ss.isUndefined(top)) {
        top = 0;
    }
    if (ss.isUndefined(right)) {
        right = 0;
    }
    if (ss.isUndefined(bottom)) {
        bottom = 0;
    }
    if (ss.isUndefined(left)) {
        left = 0;
    }
    this.top = top;
    this.right = right;
    this.bottom = bottom;
    this.left = left;
}
SharpUI.Thickness.prototype = {
    bottom: 0,
    left: 0,
    top: 0,
    right: 0
}


////////////////////////////////////////////////////////////////////////////////
// SharpUI.AdvancedLayout

SharpUI.AdvancedLayout = function SharpUI_AdvancedLayout() {
    /// <field name="cssClassNameAdvancedLayout" type="String" static="true">
    /// </field>
    /// <field name="_layoutEnforcementInterval" type="Number" integer="true" static="true">
    /// </field>
    /// <field name="attributeNamePrefix" type="String" static="true">
    /// </field>
    /// <field name="_attributeNamePrefixEscaped" type="String" static="true">
    /// </field>
    /// <field name="_dataNameLayoutState" type="String" static="true">
    /// </field>
    /// <field name="_layoutEnforcementTimerId" type="Number" integer="true" static="true">
    /// </field>
    /// <field name="_frameDetector" type="jQueryObject" static="true">
    /// </field>
}
SharpUI.AdvancedLayout._initLayoutEnforcement = function SharpUI_AdvancedLayout$_initLayoutEnforcement() {
    SharpUI.AdvancedLayout._frameDetector = $('<span></span');
    SharpUI.AdvancedLayout._frameDetector.css({ position: 'absolute', height: '0px', width: '0px', margin: '0px', padding: '0px', border: 'none', display: 'block' });
    if (!SharpUI.AdvancedLayout._layoutEnforcementTimerId) {
        SharpUI.AdvancedLayout._layoutEnforcementTimerId = window.setInterval(SharpUI.AdvancedLayout._onLayoutEnforcement, SharpUI.AdvancedLayout._layoutEnforcementInterval);
    }
}
SharpUI.AdvancedLayout._onLayoutEnforcement = function SharpUI_AdvancedLayout$_onLayoutEnforcement() {
    var controlsInDocument = $('.' + SharpUI.AdvancedLayout.cssClassNameAdvancedLayout);
    for (var i = 0, m = controlsInDocument.length; i < m; ++i) {
        SharpUI.AdvancedLayout._updateLayout($(controlsInDocument[i]));
    }
}
SharpUI.AdvancedLayout._updateLayout = function SharpUI_AdvancedLayout$_updateLayout(element) {
    /// <param name="element" type="jQueryObject">
    /// </param>
    SharpUI.AdvancedLayout._measure(element);
    SharpUI.AdvancedLayout._arrange(element);
}
SharpUI.AdvancedLayout._measure = function SharpUI_AdvancedLayout$_measure(element) {
    /// <param name="element" type="jQueryObject">
    /// </param>
}
SharpUI.AdvancedLayout._arrange = function SharpUI_AdvancedLayout$_arrange(element) {
    /// <param name="element" type="jQueryObject">
    /// </param>
    if (!element.is('.' + SharpUI.AdvancedLayout.cssClassNameAdvancedLayout)) {
        throw new Error('Element not marked for advanced layout.');
    }
    var elementState = element.data(SharpUI.AdvancedLayout._dataNameLayoutState);
    if (elementState == null) {
        element.data(SharpUI.AdvancedLayout._dataNameLayoutState, elementState = SharpUI.AdvancedLayout._parseAdvancedLayout(element));
    }
    var parent = element.parent();
    var offsetParent = element.offsetParent();
    if (!offsetParent.length || !parent.length) {
        return;
    }
    var parentIsOffsetParent = offsetParent[0] === parent[0];
    if (!parentIsOffsetParent && element.is(':visible')) {
        throw new Error('Parent must use position:absolute|fixed|relative;.');
    }
    if (!parentIsOffsetParent) {
        return;
    }
    var parentDimensions = null;
    parentDimensions = SharpUI.AdvancedLayout._getDimensionsAndPadding(parent);
    var contentStartInOffsetSpaceX, contentStartInOffsetSpaceY;
    if (parentIsOffsetParent) {
        contentStartInOffsetSpaceX = 0;
        contentStartInOffsetSpaceY = 0;
    }
    else {
        parent.prepend(SharpUI.AdvancedLayout._frameDetector);
        var parentContentFrameInDocumentSpace = SharpUI.AdvancedLayout._frameDetector.offset();
        var offsetParentFrameInDocumentSpace = offsetParent.offset();
        if (parentContentFrameInDocumentSpace != null && offsetParentFrameInDocumentSpace != null) {
            contentStartInOffsetSpaceX = parentContentFrameInDocumentSpace.left - offsetParentFrameInDocumentSpace.left - parentDimensions.paddingLeft;
            contentStartInOffsetSpaceY = parentContentFrameInDocumentSpace.top - offsetParentFrameInDocumentSpace.top - parentDimensions.paddingTop;
        }
        else {
            var contentStartInOffsetSpace = SharpUI.AdvancedLayout._frameDetector.position();
            if (contentStartInOffsetSpace != null) {
                contentStartInOffsetSpaceX = contentStartInOffsetSpace.left - parentDimensions.paddingLeft;
                contentStartInOffsetSpaceY = contentStartInOffsetSpace.top - parentDimensions.paddingTop;
            }
            else {
                contentStartInOffsetSpaceX = 0;
                contentStartInOffsetSpaceY = 0;
            }
        }
        SharpUI.AdvancedLayout._frameDetector.remove();
    }
    var topBoundary = contentStartInOffsetSpaceY + parentDimensions.paddingTop + elementState.margin.top;
    var bottomBoundary = contentStartInOffsetSpaceY + parentDimensions.clientHeight - parentDimensions.paddingBottom - elementState.margin.bottom;
    var leftBoundary = contentStartInOffsetSpaceX + parentDimensions.paddingLeft + elementState.margin.left;
    var rightBoundary = contentStartInOffsetSpaceX + parentDimensions.clientWidth - parentDimensions.paddingRight - elementState.margin.right;
    var top = 0;
    var left = 0;
    var width = 0;
    var height = 0;
    switch (elementState.verticalAlignment) {
        case SharpUI.VerticalAlignment.top:
            height = Math.round(elementState.height - elementState.padding.top - elementState.padding.bottom);
            top = Math.round(topBoundary);
            break;
        case SharpUI.VerticalAlignment.center:
            height = Math.round(elementState.height - elementState.padding.top - elementState.padding.bottom);
            top = Math.round(topBoundary * 0.5 + bottomBoundary * 0.5 - height * 0.5);
            break;
        case SharpUI.VerticalAlignment.bottom:
            height = Math.round(elementState.height - elementState.padding.top - elementState.padding.bottom);
            top = Math.round(contentStartInOffsetSpaceY + parentDimensions.clientHeight - parentDimensions.paddingBottom - elementState.margin.bottom - elementState.height);
            break;
        case SharpUI.VerticalAlignment.stretch:
            height = Math.round(bottomBoundary - topBoundary - elementState.padding.top - elementState.padding.bottom);
            top = Math.round(topBoundary);
            break;
    }
    switch (elementState.horizontalAlignment) {
        case SharpUI.HorizontalAlignment.left:
            width = Math.round(elementState.width - elementState.padding.left - elementState.padding.right);
            left = Math.round(leftBoundary);
            break;
        case SharpUI.HorizontalAlignment.center:
            width = Math.round(elementState.width - elementState.padding.left - elementState.padding.right);
            left = Math.round(leftBoundary * 0.5 + rightBoundary * 0.5 - width * 0.5);
            break;
        case SharpUI.HorizontalAlignment.right:
            width = Math.round(elementState.width - elementState.padding.left - elementState.padding.right);
            left = Math.round(contentStartInOffsetSpaceX + parentDimensions.clientWidth - parentDimensions.paddingRight - elementState.margin.right - elementState.width);
            break;
        case SharpUI.HorizontalAlignment.stretch:
            width = Math.round(rightBoundary - leftBoundary - elementState.padding.left - elementState.padding.right);
            left = Math.round(leftBoundary);
            break;
    }
    if (width <= 0) {
        width = 0;
    }
    if (height <= 0) {
        height = 0;
    }
    element.css({ position: 'absolute', top: top, left: left, width: width, height: height, 'padding-top': elementState.padding.top, 'padding-right': elementState.padding.right, 'padding-bottom': elementState.padding.bottom, 'padding-left': elementState.padding.left });
}
SharpUI.AdvancedLayout._getDimensionsAndPadding = function SharpUI_AdvancedLayout$_getDimensionsAndPadding(element) {
    /// <param name="element" type="jQueryObject">
    /// </param>
    /// <returns type="Object"></returns>
    var d = {};
    if ((typeof(window.getComputedStyle) === 'function')) {
        var computedStyle = window.getComputedStyle(element[0]);
        if (('width' in computedStyle)) {
            d.clientWidth = Number.parse(computedStyle.width);
            d.clientHeight = Number.parse(computedStyle.height);
            d.paddingTop = Number.parse(computedStyle.paddingTop);
            d.paddingRight = Number.parse(computedStyle.paddingRight);
            d.paddingBottom = Number.parse(computedStyle.paddingBottom);
            d.paddingLeft = Number.parse(computedStyle.paddingLeft);
        }
        else {
            d.clientWidth = Number.parse(computedStyle.getPropertyValue('width'));
            d.clientHeight = Number.parse(computedStyle.getPropertyValue('height'));
            d.paddingTop = Number.parse(computedStyle.getPropertyValue('padding-top'));
            d.paddingRight = Number.parse(computedStyle.getPropertyValue('padding-right'));
            d.paddingBottom = Number.parse(computedStyle.getPropertyValue('padding-bottom'));
            d.paddingLeft = Number.parse(computedStyle.getPropertyValue('padding-left'));
        }
        d.clientWidth += d.paddingLeft + d.paddingRight;
        d.clientHeight += d.paddingTop + d.paddingBottom;
        return d;
    }
    else {
        d.clientWidth = element.innerWidth();
        d.clientHeight = element.innerHeight();
        d.paddingTop = Number.parse(element.css('padding-top'));
        d.paddingRight = Number.parse(element.css('padding-right'));
        d.paddingBottom = Number.parse(element.css('padding-bottom'));
        d.paddingLeft = Number.parse(element.css('padding-left'));
        return d;
    }
}
SharpUI.AdvancedLayout._parseAdvancedLayout = function SharpUI_AdvancedLayout$_parseAdvancedLayout(element) {
    /// <param name="element" type="jQueryObject">
    /// </param>
    /// <returns type="Object"></returns>
    var marginTop, marginRight, marginBottom, marginLeft;
    var margin = element.attr(SharpUI.AdvancedLayout.attributeNamePrefix + 'margin');
    if (!String.isNullOrEmpty(margin)) {
        var split = margin.trim().split(' ');
        marginTop = parseFloat(split[0]);
        marginRight = parseFloat(split[1]);
        marginBottom = parseFloat(split[2]);
        marginLeft = parseFloat(split[3]);
    }
    else {
        marginTop = 0;
        marginRight = 0;
        marginBottom = 0;
        marginLeft = 0;
    }
    var paddingTop, paddingRight, paddingBottom, paddingLeft;
    var padding = element.attr(SharpUI.AdvancedLayout.attributeNamePrefix + 'padding');
    if (!String.isNullOrEmpty(padding)) {
        var split = padding.trim().split(' ');
        paddingTop = parseFloat(split[0]);
        paddingRight = parseFloat(split[1]);
        paddingBottom = parseFloat(split[2]);
        paddingLeft = parseFloat(split[3]);
    }
    else {
        paddingTop = 0;
        paddingRight = 0;
        paddingBottom = 0;
        paddingLeft = 0;
    }
    var advancedWidth, advancedHeight;
    var width = element.attr(SharpUI.AdvancedLayout.attributeNamePrefix + 'width');
    var height = element.attr(SharpUI.AdvancedLayout.attributeNamePrefix + 'height');
    if (String.isNullOrEmpty(width)) {
        advancedWidth = Number.NaN;
    }
    else {
        advancedWidth = Number.parse(width);
    }
    if (String.isNullOrEmpty(height)) {
        advancedHeight = Number.NaN;
    }
    else {
        advancedHeight = Number.parse(height);
    }
    var verticalAlignment;
    switch (element.attr(SharpUI.AdvancedLayout.attributeNamePrefix + 'vertical-alignment')) {
        case 'top':
        case 'Top':
            verticalAlignment = SharpUI.VerticalAlignment.top;
            break;
        case 'center':
        case 'Center':
            verticalAlignment = SharpUI.VerticalAlignment.center;
            break;
        case 'bottom':
        case 'Bottom':
            verticalAlignment = SharpUI.VerticalAlignment.bottom;
            break;
        case 'stretch':
        case 'Stretch':
        default:
            verticalAlignment = SharpUI.VerticalAlignment.stretch;
            break;
    }
    var horizontalAlignment;
    switch (element.attr(SharpUI.AdvancedLayout.attributeNamePrefix + 'horizontal-alignment')) {
        case 'left':
        case 'Left':
            horizontalAlignment = SharpUI.HorizontalAlignment.left;
            break;
        case 'center':
        case 'Center':
            horizontalAlignment = SharpUI.HorizontalAlignment.center;
            break;
        case 'right':
        case 'Right':
            horizontalAlignment = SharpUI.HorizontalAlignment.right;
            break;
        case 'stretch':
        case 'Stretch':
        default:
            horizontalAlignment = SharpUI.HorizontalAlignment.stretch;
            break;
    }
    if (verticalAlignment !== SharpUI.VerticalAlignment.stretch && isNaN(advancedHeight)) {
        verticalAlignment = SharpUI.VerticalAlignment.stretch;
    }
    if (horizontalAlignment !== SharpUI.HorizontalAlignment.stretch && isNaN(advancedWidth)) {
        horizontalAlignment = SharpUI.HorizontalAlignment.stretch;
    }
    var state = {};
    state.margin = new SharpUI.Thickness();
    state.padding = new SharpUI.Thickness();
    state.height = advancedHeight;
    state.width = advancedWidth;
    state.verticalAlignment = verticalAlignment;
    state.horizontalAlignment = horizontalAlignment;
    state.margin.top = marginTop;
    state.margin.right = marginRight;
    state.margin.bottom = marginBottom;
    state.margin.left = marginLeft;
    state.padding.top = paddingTop;
    state.padding.right = paddingRight;
    state.padding.bottom = paddingBottom;
    state.padding.left = paddingLeft;
    return state;
}
SharpUI.AdvancedLayout._getElementFromObject = function SharpUI_AdvancedLayout$_getElementFromObject(e) {
    /// <param name="e" type="Object">
    /// </param>
    /// <returns type="jQueryObject"></returns>
    var elementAsJq;
    var tc = Type.safeCast(e, SharpUI.TemplateControl);
    if (tc != null) {
        elementAsJq = tc.get_rootElement();
    }
    else {
        elementAsJq = $(e);
    }
    return elementAsJq;
}
SharpUI.AdvancedLayout.autoEnable = function SharpUI_AdvancedLayout$autoEnable(elementSubtree) {
    /// <param name="elementSubtree" type="Object">
    /// </param>
    var jqRoot = $(elementSubtree);
    var advancedLayoutSelector;
    var checkAttributesDirectly;
    if ($.browser.msie && parseFloat($.browser.version) < 9) {
        checkAttributesDirectly = true;
        advancedLayoutSelector = '*[control!=]:not(.' + SharpUI.AdvancedLayout.cssClassNameAdvancedLayout + ')';
    }
    else {
        checkAttributesDirectly = false;
        advancedLayoutSelector = '*[' + SharpUI.AdvancedLayout._attributeNamePrefixEscaped + 'horizontal-alignment][control!=]:not(.' + SharpUI.AdvancedLayout.cssClassNameAdvancedLayout + '), ' + '*[' + SharpUI.AdvancedLayout._attributeNamePrefixEscaped + 'vertical-alignment][control!=]:not(.' + SharpUI.AdvancedLayout.cssClassNameAdvancedLayout + '), ' + '*[' + SharpUI.AdvancedLayout._attributeNamePrefixEscaped + 'margin][control!=]:not(.' + SharpUI.AdvancedLayout.cssClassNameAdvancedLayout + '), ';
    }
    var fnEnableAdvancedLayout;
    if (checkAttributesDirectly) {
        fnEnableAdvancedLayout = function(i, e) {
            var hasAdvancedAttribute = false;
            try {
                hasAdvancedAttribute = (hasAdvancedAttribute | e.getAttribute(SharpUI.AdvancedLayout.attributeNamePrefix + 'horizontal-alignment') != null) === 1;
            }
            catch ($e1) {
            }
            try {
                hasAdvancedAttribute = (hasAdvancedAttribute | e.getAttribute(SharpUI.AdvancedLayout.attributeNamePrefix + 'vertical-alignment') != null) === 1;
            }
            catch ($e2) {
            }
            try {
                hasAdvancedAttribute = (hasAdvancedAttribute | e.getAttribute(SharpUI.AdvancedLayout.attributeNamePrefix + 'margin') != null) === 1;
            }
            catch ($e3) {
            }
            if (hasAdvancedAttribute) {
                SharpUI.AdvancedLayout.setAdvancedLayout(e, true);
            }
        };
    }
    else {
        fnEnableAdvancedLayout = function(i, e) {
            SharpUI.AdvancedLayout.setAdvancedLayout(e, true);
        };
    }
    jqRoot.find(advancedLayoutSelector).each(fnEnableAdvancedLayout);
    if (checkAttributesDirectly) {
        if (!String.isNullOrEmpty(jqRoot.attr(SharpUI.AdvancedLayout.attributeNamePrefix + 'horizontal-alignment')) || !String.isNullOrEmpty(jqRoot.attr(SharpUI.AdvancedLayout.attributeNamePrefix + 'vertical-alignment')) || !String.isNullOrEmpty(jqRoot.attr(SharpUI.AdvancedLayout.attributeNamePrefix + 'margin'))) {
            SharpUI.AdvancedLayout.setAdvancedLayout(jqRoot, true);
        }
    }
    else {
        if (jqRoot.is(advancedLayoutSelector)) {
            fnEnableAdvancedLayout(-1, jqRoot[0]);
        }
    }
}
SharpUI.AdvancedLayout.setAdvancedLayout = function SharpUI_AdvancedLayout$setAdvancedLayout(e, enabled) {
    /// <param name="e" type="Object">
    /// </param>
    /// <param name="enabled" type="Boolean">
    /// </param>
    var elementAsJq = SharpUI.AdvancedLayout._getElementFromObject(e);
    if (enabled) {
        elementAsJq.addClass(SharpUI.AdvancedLayout.cssClassNameAdvancedLayout);
    }
    else {
        elementAsJq.remove(SharpUI.AdvancedLayout.cssClassNameAdvancedLayout);
    }
}
SharpUI.AdvancedLayout.setMargin = function SharpUI_AdvancedLayout$setMargin(e, margin) {
    /// <param name="e" type="Object">
    /// </param>
    /// <param name="margin" type="SharpUI.Thickness">
    /// </param>
    var elementAsJq = SharpUI.AdvancedLayout._getElementFromObject(e);
    elementAsJq.attr(SharpUI.AdvancedLayout.attributeNamePrefix + 'margin', Math.round(margin.top) + ' ' + Math.round(margin.right) + ' ' + Math.round(margin.bottom) + ' ' + Math.round(margin.left));
    elementAsJq.data(SharpUI.AdvancedLayout._dataNameLayoutState, SharpUI.AdvancedLayout._parseAdvancedLayout(elementAsJq));
}
SharpUI.AdvancedLayout.setHeight = function SharpUI_AdvancedLayout$setHeight(e, height) {
    /// <param name="e" type="Object">
    /// </param>
    /// <param name="height" type="Number">
    /// </param>
    var elementAsJq = SharpUI.AdvancedLayout._getElementFromObject(e);
    elementAsJq.attr(SharpUI.AdvancedLayout.attributeNamePrefix + 'height', Math.round(height).toString());
    elementAsJq.data(SharpUI.AdvancedLayout._dataNameLayoutState, SharpUI.AdvancedLayout._parseAdvancedLayout(elementAsJq));
}


ClientManager.registerClass('ClientManager');
FacebookSS.GraphApi.UIOptionsPermissionsRequest.registerClass('FacebookSS.GraphApi.UIOptionsPermissionsRequest', Object);
SharpUI.TemplateControl.registerClass('SharpUI.TemplateControl');
ClientScript.UI.ConfirmRemove.registerClass('ClientScript.UI.ConfirmRemove', SharpUI.TemplateControl);
MdSc.Client.Sh.U._facebook.registerClass('MdSc.Client.Sh.U._facebook');
SharpUI.Thickness.registerClass('SharpUI.Thickness');
SharpUI.AdvancedLayout.registerClass('SharpUI.AdvancedLayout');
ClientManager._listeners = [];
ClientManager._uniqueIdCounter = 1;
ClientManager._options = null;
ClientManager._fb = null;
ClientManager._facebookPermissionsGranted = null;
ClientManager._createUpdateAccount = false;
ClientManager._onWaitingForServer = null;
ClientManager._onWaitingForServerComplete = null;
(function () {
    try {
        if (!('ClientManager' in window)) {
            window.ClientManager = ClientManager;
        }
    }
    catch ($e1) {
    }
    ClientManager._options = window.clientManagerOptions;
    if (ss.isNullOrUndefined(ClientManager._options)) {
        ClientManager._options = {};
    }
    if (!String.isNullOrEmpty(ClientManager._options.FacebookAppId)) {
        ClientManager._initFacebookApi();
    }
})();
SharpUI.TemplateControl._attributeNameLocalId = 'xid';
SharpUI.TemplateControl._attributeNameControlClass = 'control';
SharpUI.TemplateControl._dataNameControl = 'templateControl';
SharpUI.TemplateControl.cssClassNameControl = 'templateControl';
SharpUI.TemplateControl.cssClassNameControlUnadded = 'templateControlUnadded';
SharpUI.TemplateControl._idPrefixAutoRewrite = 'auto_';
SharpUI.TemplateControl._cssClassNamePrefixAutoRewrite = 'css_auto_';
SharpUI.TemplateControl._bStaticConstructionFinished = false;
SharpUI.TemplateControl._hash_templateCache = {};
SharpUI.TemplateControl._hash_processedCss = {};
SharpUI.TemplateControl._documentTreeCheckInterval = 200;
SharpUI.TemplateControl._iCheckParentIntervalId = 0;
SharpUI.TemplateControl._hash_strControlIdsKnownInDocument = {};
SharpUI.TemplateControl._hash_cachedTypeNameResolves = {};
SharpUI.TemplateControl._iAutoIdGeneratorCounter = 0;
SharpUI.TemplateControl._iInstanceIdGeneratorCounter = 1;
SharpUI.TemplateControl._hash_controlFieldMappingByControl = {};
SharpUI.TemplateControl._mouseCaptureHandler = null;
SharpUI.TemplateControl._jqMouseCaptureGlassBarrier = null;
SharpUI.AdvancedLayout.cssClassNameAdvancedLayout = 'advancedLayout';
SharpUI.AdvancedLayout._layoutEnforcementInterval = 500;
SharpUI.AdvancedLayout.attributeNamePrefix = 'al:';
SharpUI.AdvancedLayout._attributeNamePrefixEscaped = SharpUI.AdvancedLayout.attributeNamePrefix.replaceAll(':', '\\:');
SharpUI.AdvancedLayout._dataNameLayoutState = '__als';
SharpUI.AdvancedLayout._layoutEnforcementTimerId = 0;
SharpUI.AdvancedLayout._frameDetector = null;
(function () {
    SharpUI.AdvancedLayout._initLayoutEnforcement();
})();
})();

//! This script was generated using Script# v0.7.0.0

