﻿/// <reference name="MicrosoftAjax.debug.js" />
/// <reference path="Web.MembershipResources.js" />

Type.registerNamespace("Web");

Web.Membership = function() {
    Web.Membership.initializeBase(this);
    this._membershipBar = null;
    this._intervalId = null;
}

Web.Membership.prototype = {
    initialize: function() {
        Web.Membership.callBaseMethod(this, 'initialize');
        this._loginButtonClickHandler = Function.createDelegate(this, this._loginButtonClick);
        this._loginDialogMouseOverHandler = Function.createDelegate(this, this._loginDialogMouseOver);
        this._loginDialogMouseOutHandler = Function.createDelegate(this, this._loginDialogMouseOut);
        this._login_CompletedHandler = Function.createDelegate(this, this._login_Completed);
        this._method_FailureHandler = Function.createDelegate(this, this._method_Failure);
        this._textBoxKeyPressHandler = Function.createDelegate(this, this._textBoxKeyPress);
    },
    dispose: function() {
        if (this._loginButton) $clearHandlers(this._loginButton);
        if (this._loginDialog) $clearHandlers(this._loginDialog);
        if (this._userName) $clearHandlers(this._userName);
        if (this._password) $clearHandlers(this._password);
        Web.Membership.callBaseMethod(this, 'dispose');
    },
    get_membershipBar: function() {
        return this._membershipBar;
    },
    get_isLoginDialogVisible: function() {
        return this._isLoginDialogVisible;
    },
    set_isLoginDialogVisible: function(value) {
        this._isLoginDialogVisible = value;
    },
    get_displayRememberMe: function() {
        return this._displayRememberMe != false;
    },
    set_displayRememberMe: function(value) {
        this._displayRememberMe = value;
    },
    get_rememberMeSet: function() {
        return this._rememberMeSet == true;
    },
    set_rememberMeSet: function(value) {
        this._rememberMeSet = value;
    },
    get_displayPasswordRecovery: function() {
        return this._displayPasswordRecovery != false;
    },
    set_displayPasswordRecovery: function(value) {
        this._displayPasswordRecovery = value;
    },
    get_displaySignUp: function() {
        return this._displaySignUp != false;
    },
    set_displaySignUp: function(value) {
        this._displaySignUp = value;
    },
    get_displayMyAccount: function() {
        return this._displayMyAccount;
    },
    set_displayMyAccount: function(value) {
        this._displayMyAccount = value;
    },
    get_displayHelp: function() {
        return this._displayHelp;
    },
    set_displayHelp: function(value) {
        this._displayHelp = value;
    },
    get_baseUrl: function() {
        return this._baseUrl;
    },
    set_baseUrl: function(value) {
        this._baseUrl = value;
    },
    get_servicePath: function() {
        return this._servicePath;
    },
    set_servicePath: function(value) {
        this._servicePath = value;
    },
    get_welcome: function() {
        return this._welcome;
    },
    set_welcome: function(value) {
        this._welcome = value;
    },
    showLoginDialog: function() {
        this.hideLoginDialog();
    },
    hideLoginDialog: function() {
        if (this._intevalId) {
            window.clearInterval(this._intervalId);
            this._intervalId = null;
        }
    },
    changeLoginDialogVisibility: function(visible, delay) {
        if (this._intevalId) {
            window.clearInterval(this._intevalId);
            this._intevalId = null;
        }
        if (delay)
            this._intevalId = window.setInterval(String.format('$find("{0}").changeLoginDialogVisibility({1})', this.get_id(), visible), delay);
        else {
            if (visible != this.get_isLoginDialogVisible()) {
                var loginControls = $get('LoginControlsRow', this._membershipBar);
                if (loginControls) {
                    if (visible)
                        Sys.UI.DomElement.removeCssClass(this._loginDialog, 'LoginDialogCollapsed');
                    else
                        Sys.UI.DomElement.addCssClass(this._loginDialog, 'LoginDialogCollapsed');
                    Sys.UI.DomElement.setVisible(loginControls, visible);
                }
                if (visible && !(document.activeElement && document.activeElement.id == 'Password')) this._userName.focus();
                this.set_isLoginDialogVisible(visible);
            }
        }
    },
    updated: function() {
        Web.Membership.callBaseMethod(this, 'updated');
        if (!Web.Membership._instance) Web.Membership._instance = this;
        var bar = document.createElement('div');
        bar.className = 'MembershipBarPlaceholder';
        document.body.insertBefore(bar, document.body.childNodes[0]);
        this._membershipBar = $get('Membership_Login');
        var loggedIn = Sys.Services.AuthenticationService.get_isLoggedIn();
        if (!this._membershipBar) {
            this._membershipBar = document.createElement('div');
            if (document.body.childNodes.length > 0)
                document.body.insertBefore(this._membershipBar, document.body.childNodes[0]);
            else
                document.body.appendChild(this._membershipBar);
            var sb = new Sys.StringBuilder();
            this._membershipBar.id = 'Membership_Login';
            this._membershipBar.className = 'MembershipBar';
            if (this.get_displayHelp())
                sb.append(String.format('<div style="float:right;padding-top:5px;padding-right:4px;" class="HelpLink"> | <a href="#" onclick="$find(&quot;{0}&quot;).help();return false;">{1}</a></div>', this.get_id(), Web.MembershipResources.Bar.HelpLink));
            if (!loggedIn)
                sb.append(String.format(
                    '<table id="LoginDialog" cellpadding="0" class="LoginDialog">' +
                    '<tr><td id="Anchor"><a href="#" onfocus="$find(&quot;{0}&quot;).changeLoginDialogVisibility(true);return false">{1}</a>{2}</td></tr>' +
                    '<tr id="LoginControlsRow"><td id="LoginControls"><table>' +
                    '<tr><td align="right">{3}</td><td><input type="text" id="UserName" size="20" value="" /></td></tr>' +
                    '<tr><td align="right">{4}</td><td><input type="password" id="Password" size="20" /></td></tr>' +
                    (this.get_displayRememberMe() ? String.format('<tr><td align="right" colspan="2"><input type="checkbox" id="RememberMe"{0}/><label for="RememberMe">{1}</label></td></tr>', this.get_rememberMeSet() ? ' checked="checked"' : '', Web.MembershipResources.Bar.RememberMe) : '') +
                    (this.get_displayPasswordRecovery() ? '<tr><td>&nbsp;</td><td align="right"><a href="#" onclick="$find(&quot;{0}&quot).passwordRecovery();return false;" id="PasswordRecovery">{6}</a></td></tr>' : '') +
                    (this.get_displaySignUp() ? '<tr><td>&nbsp;</td><td align="right"><a href="#" onclick="$find(&quot;{0}&quot).signUp();return false;" id="SignUp">{7}</a></td></tr>' : '') +
                    '<tr><td>&nbsp;</td><td align="right"><button id="Login">{5}</button></td></tr>' +
                    '</table></td></tr></table>', this.get_id(), Web.MembershipResources.Bar.LoginLink, Web.MembershipResources.Bar.LoginText,
                    Web.MembershipResources.Bar.UserName, Web.MembershipResources.Bar.Password, Web.MembershipResources.Bar.LoginButton,
                    Web.MembershipResources.Bar.ForgotPassword, Web.MembershipResources.Bar.SignUp));
            else
                sb.append(String.format(
                    '<table id="LoginDialog" cellpadding="0" class="LoginDialog LoginDialogCollapsed"><tr><td>' +
                    (this.get_welcome() ? this.get_welcome() + ' | ' : '') +
                    (this.get_displayMyAccount() ? '<a id="MyAccount" href="#" onclick="$find(&quot;{0}&quot;).myAccount();return false;">{1}</a> | ' : '') +
                    '<a href="#" onclick="$find(&quot;{0}&quot;).logout();return false;">{2}</a>' +
                    '</td></tr></table>', this.get_id(), Web.MembershipResources.Bar.MyAccount, Web.MembershipResources.Bar.LogoutLink));
            this._membershipBar.innerHTML = sb.toString();
        }
        //document.body.style.marginTop = '0px';
        document.body.style.paddingTop = '0px';
        if (!loggedIn) {
            this._loginDialog = $get('LoginDialog', this._membershipBar);
            this._loginDialog.style.width = this._loginDialog.offsetWidth + 'px';
            if ($get('LoginControlsRow', this._loginDialog))
                $addHandlers(this._loginDialog, { 'mouseover': this._loginDialogMouseOverHandler, 'mouseout': this._loginDialogMouseOutHandler }, this);
            this._loginButton = $get('Login', this._membershipBar);
            if (this._loginButton) $addHandler(this._loginButton, 'click', this._loginButtonClickHandler);
            this._userName = $get('UserName', this._membershipBar);
            if (this._userName) $addHandler(this._userName, 'keypress', this._textBoxKeyPressHandler);
            this._password = $get('Password', this._membershipBar);
            if (this._password) $addHandler(this._password, 'keypress', this._textBoxKeyPressHandler);
            this._rememberMe = $get('RememberMe', this._membershipBar);
            this.changeLoginDialogVisibility(window.location.href.match(/\?ReturnUrl=(.+)$/) != null);
        }
    },
    _login_Completed: function(validCredentials) {
        if (!validCredentials) {
            alert(Web.MembershipResources.Messages.InvalidUserNameAndPassword);
            this.changeLoginDialogVisibility(true);
            this._userName.focus();
        }
        else {
            var returnUrl = window.location.href.match(/\?ReturnUrl=(.+)$/);
            var anchoredHref = window.location.href.match(/^(.+?)#.*$/);
            window.location.href = returnUrl ? unescape(returnUrl[1]) : (anchoredHref ? anchoredHref[1] : window.location.href);
        }
    },
    _method_Failure: function(error, userContext, methodName) {
        alert(String.format('Method {0} has failed. {1}', methodName, error.get_message()));
    },
    _loginButtonClick: function(e) {
        this.login();
    },
    _loginDialogMouseOver: function(e) {
        this.changeLoginDialogVisibility(true, 50);
    },
    _loginDialogMouseOut: function(e) {
        this.changeLoginDialogVisibility(false, 500);
    },
    _textBoxKeyPress: function(e) {
        if (e.charCode == Sys.UI.Key.enter) {
            e.preventDefault();
            this.login();
        }
        if (e.charCode == Sys.UI.Key.esc) {
            e.preventDefault();
            this.set_isLoginDialogVisible(true);
            this.changeLoginDialogVisibility(false);
        }
    },
    login: function() {
        if (this._userName && this._password) {
            var isBlank = /^\s*$/;
            if (isBlank.exec(this._userName.value)) {
                alert(Web.MembershipResources.Messages.BlankUserName);
                this.set_isLoginDialogVisible(false);
                this._userName.focus();
                return;
            }
            if (isBlank.exec(this._password.value)) {
                this.set_isLoginDialogVisible(false);
                alert(Web.MembershipResources.Messages.BlankPassword);
                this.set_isLoginDialogVisible(false);
                this._password.focus();
                return;
            }
            Sys.Services.AuthenticationService.login(this._userName.value, this._password.value, this._rememberMe != null && this._rememberMe.checked, null, null, this._login_CompletedHandler, this._method_FailureHandler, null);
        }
        else
            alert('UserName and/or Password elements are not found in the Memership_Login');
    },
    logout: function() {
        Sys.Services.AuthenticationService.logout(null, null, null, null);
    },
    signUp: function() {
        Web.DataView.showModal($get('SignUp', this.get_membershipBar()), 'aspnet_Membership', 'signUpForm', 'New', 'signUpForm', this.get_baseUrl(), this.get_servicePath());
    },
    passwordRecovery: function() {
        Web.DataView.showModal($get('PasswordRecovery', this.get_membershipBar()), 'aspnet_Membership', 'passwordRequestForm', 'New', 'passwordRequestForm', this.get_baseUrl(), this.get_servicePath());
    },
    myAccount: function() {
        Web.DataView.showModal($get('MyAccount', this.get_membershipBar()), 'aspnet_Membership', 'myAccountForm', 'Edit', 'myAccountForm', this.get_baseUrl(), this.get_servicePath());
    },
    help: function(fullScreen) {
        var path = window.location.pathname;
        var helpPath = this.get_baseUrl() == './' ? path.substr(path.lastIndexOf('/'), 100) : '';
        if (helpPath.length == 0) {
            var baseSegments = this.get_baseUrl().split(/\//);
            var pathSegments = path.split(/\//);
            if (baseSegments[baseSegments.length - 1] == '')
                Array.removeAt(baseSegments, baseSegments.length - 1);
            if (pathSegments[pathSegments.length - 1] == '')
                Array.removeAt(pathSegments, pathSegments.length - 1);
            if (pathSegments[0] == '')
                Array.removeAt(pathSegments, 0);
            var levelsUp = baseSegments.length;
            if (pathSegments[pathSegments.length - 1].indexOf('.') == -1)
                levelsUp--;
            for (var i = pathSegments.length - levelsUp - 1; i < pathSegments.length; i++)
                helpPath += '/' + pathSegments[i];
        }
        var helpUrl = String.format('{0}help{1}', this.get_baseUrl(), helpPath);
        if (fullScreen) {
            window.open(helpUrl);
            this.help();
            return;
        }
        if (!this._helpBar) {
            this._helpDiv = document.createElement('div');
            document.body.appendChild(this._helpDiv);
            this._helpDiv.className = 'HelpBar';
            this._helpDiv.innerHTML = String.format('<div class="Title">{1}</div><iframe id="help" frameBorder="0"></iframe><div class="Buttons"><button onclick="$find(&quot;{0}&quot;).help()">{2}</button><button onclick="$find(&quot;{0}&quot;).help(true)">{3}</button></div>',
                this.get_id(), Web.MembershipResources.Bar.HelpLink, Web.MembershipResources.Bar.HelpCloseButton, Web.MembershipResources.Bar.HelpFullScreenButton);
            this._helpFrame = $get('help', this._helpDiv);
            this._helpBar = $create(AjaxControlToolkit.AlwaysVisibleControlBehavior, { HorizontalSide: AjaxControlToolkit.HorizontalSide.Right, VerticalSide: AjaxControlToolkit.VerticalSide.Top, HorizontalOffset: 15, VerticalOffset: 30 }, null, null, this._helpDiv);
            Sys.UI.DomElement.setVisible(this._helpDiv, false);
        }
        Sys.UI.DomElement.setVisible(this._helpDiv, !Sys.UI.DomElement.getVisible(this._helpDiv));
        if (Sys.UI.DomElement.getVisible(this._helpDiv)) {
            if (this._helpFrame.src == '')
                this._helpFrame.src = helpUrl;
            this._helpBar._reposition();
        }
    }
}
Web.Membership.registerClass('Web.Membership', Sys.Component);

if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

