﻿/// <reference name="MicrosoftAjax.js"/>

Type.registerNamespace("Shopmobbing.Behaviors");

Shopmobbing.Behaviors.Login = function(element) {

    var tagName = element.tagName.toUpperCase();
    if (tagName != 'DIV')
        throw Error.argument('element', 'login must be atatched to the DIV element only!');

    this._id = null;
    this._css = null;
    this._visible = true;
    this._allowRegistration = true;

    this._registrationForm = null;

    //delegates
    this._showLoginFormDelegate = null;
    this._loadRegistrationFormDelegate = null;
    this._loginDelegate = null;
    this._cancelDelegate = null;
    this._bindDomEventsDelegate = null;

    this._loggingInDelegate = null;
    this._loggedInDelegate = null;

    this._userName = null;

    Shopmobbing.Behaviors.Login.initializeBase(this, [element]);
}

Shopmobbing.Behaviors.Login.prototype = {

    get_id: function() {
        return this._id;
    },
    set_id: function(value) {
        this._id = value;
    },

    get_userName: function() {
        if (this._userName == null)
            return $get('ctl00_hfUserName').value;
        else
            return this._userName;
    },
    set_userName: function(value) {
        this._userName = value;
    },

    get_visible: function() {
        return this._visible;
    },
    set_visible: function(value) {
        if (value === true) {
            $(this.get_element()).hide();
        }
        else {
        }
    },

    get_allowRegistration: function() {
        return this._allowRegistration;
    },
    set_allowRegistration: function(value) {
        Sys.UI.DomElement.setVisible($get("lnkRegistration", this.get_element()), value);
        this._allowRegistration = value;
    },

    add_loggingIn: function(handler) {
        this.get_events().addHandler('loggingIn');
    },
    remove_loggingIn: function(handler) {
        this.get_events().removeHandler('loggingIn', handler);
    },

    add_loggedIn: function(handler) {
        if (handler !== null) {
            this.get_events().addHandler('loggedIn', handler);
        }
    },
    remove_loggedIn: function(handler) {
        this.get_events().removeHandler('loggedIn', handler);
    },

    login: function() {
        $(document.body).css("cursor", "wait");
        var me = this;

        var username = $get('txtUserName', this.get_element()).value;
        var password = $get('txtPassword', this.get_element()).value;

        this.set_userName(username);

        var loggingInHandler = this.get_events().getHandler('loggingIn');
        if (loggingInHandler !== null) {
            loggingInHandler(this, Sys.EventArgs.Empty);
        }

        Sys.Services.AuthenticationService.login(username, password, true, null, null,
        function(result, userContext, method) {
            if (result) {
                $(me.get_element()).css("background-color", "green");
                $.modal.close();

                $(document.body).css("cursor", "default");

                var loggedInHandler = me.get_events().getHandler('loggedIn');
                if (loggedInHandler !== null) {
                    loggedInHandler(me, Sys.EventArgs.Empty);
                }
            }
            else {
                $(me.get_element()).css("background-color", "red");
                $(document.body).css("cursor", "default");
            }
        },
        function(result, userContext, method) {
            alert("Error: " + result);
        },
        "UserContext");
    },

    _onRegistered: function(sender, args) {
        var loggedInHandler = this.get_events().getHandler('loggedIn');
        if (loggedInHandler !== null) {
            loggedInHandler(this, Sys.EventArgs.Empty);
        }
    },

    validateLoginPossibility: function() {
        if ($get("txtUserName", this.get_element()).value !== "" && $get("txtPassword", this.get_element()).value !== ""
        && !$("#txtUserName", this.get_element()).hasClass('watermark') && !$("#txtPassword", this.get_element()).hasClass('watermark')) {
            $("#btnLogin", this.get_element()).removeAttr("disabled");
            return true;
        }
        else {
            $("#btnLogin", this.get_element()).attr("disabled", "disabled");
            return false;
        }
    },

    show: function() {
        var me = this;
        var el = me.get_element();

        $(me.get_element()).modal({
            focus: false,
            onShow: function(dialog) {
                $(document).bind('keydown', function(e) {
                    var code = (e.keyCode ? e.keyCode : e.which);
                    if (code == 13) {
                        var p = me._validateLoginPossibility.call();
                        if (p) {
                            me._loginDelegate.call();
                        }
                    }
                });

                $("#txtUserName", el).blur();
                $("#txtUserName", el).removeClass('watermark');
            },
            onClose: function(dialog) {
                $(document).unbind('keydown');
                me._cancelDelegate.call();
            }
        });
    },

    cancel: function() {
        $.modal.close();
        $("input[type='text']", this.get_element()).filter("disabled").val("").css("background-color", "");
        $("input[type='password']", this.get_element()).val("").css("background-color", "");
    },

    loadRegistrationForm: function(showAfterLoading) {
        $(document.body).css("cursor", "wait");
        $.blockUI({ baseZ: 1010 });
        var me = this;

        if (me._registrationForm === null) {
            $("div#registrationFormContainer", this.get_element()).load(userControlsPath + "/htm/RegistrationForm.htm", null, function(responseText, textStatus, xhr) {
                me._registrationForm = $create(Shopmobbing.Controls.Registration,
                {},
                { registered: me._onRegisteredDelegate },
                {},
                $get("registrationForm"));

                Sys.UI.DomElement.setVisibilityMode(me._registrationForm.get_element(), Sys.UI.VisibilityMode.collapse);

                me.cancel();
                me._registrationForm.show();

                $(document.body).css("cursor", "default");
                $.unblockUI();
            });
        }
        else {
            me.cancel();
            me._registrationForm.show();


            $(document.body).css("cursor", "default");
            $.unblockUI();
        }
    },

    bindDomEvents: function() {
        if (this._showLoginFormDelegate === null) {
            this._showLoginFormDelegate = Function.createDelegate(this, this.show);
        }
        if (this._loadRegistrationFormDelegate === null) {
            this._loadRegistrationFormDelegate = Function.createDelegate(this, this.loadRegistrationForm);
        }

        this._loginDelegate = Function.createDelegate(this, this.login);
        this._onRegisteredDelegate = Function.createDelegate(this, this._onRegistered);
        this._cancelDelegate = Function.createDelegate(this, this.cancel);

        this._validateLoginPossibility = Function.createDelegate(this, this.validateLoginPossibility);

        this._loggingInDelegate = Function.createDelegate(this, this._loggingInHandler);
        this._loggedInDelegate = Function.createDelegate(this, this._loggedInHandler);

        $("#txtUserName").live("keyup", {}, this._validateLoginPossibility);
        $("#txtPassword").live("keyup", {}, this._validateLoginPossibility);
        $("#lnkShowLoginForm").bind('click', null, this._showLoginFormDelegate);
        $("#lnkLoadRegistrationForm", this.get_element()).bind('click', null, this._loadRegistrationFormDelegate);

        $addHandler($get("btnLogin", this.get_element()), "click", this._loginDelegate);
    },

    initialize: function() {
        Shopmobbing.Behaviors.Login.callBaseMethod(this, 'initialize');

        if (this._bindDomEventsDelegate === null) {
            this._bindDomEventsDelegate = Function.createDelegate(this, this.bindDomEvents);
        }
        this._bindDomEventsDelegate();

        $('#txtUserName', this.get_element())
            .watermark('user name or email', 'watermark')
        $('#txtPassword', this.get_element())
            .watermark('password', 'watermark');
    },
    dispose: function() {
        if (this._showLoginFormDelegate) {
            $("#lnkShowLoginForm", this.get_element()).unbind('click', this._showLoginFormDelegate);
            delete this._showLoginFormDelegate;
        }
        if (this._loadRegistrationFormDelegate) {
            $("#lnkShowRegistrationForm", this.get_element()).unbind('click', this._loadRegistrationFormDelegate);
            delete this._showLoginFormDelegate;
        }
        if (this._loginDelegate) {
            //TODO: debug. exception is thrown. $get("btnLogin") is null
            //$removeHandler($get("btnLogin", this.get_element()), 'click', this._loginDelegate);
            delete this._loginDelegate;
        }
        $(document).unbind('keydown');
        //        $removeHandler($get("btnCancel", this.get_element()), 'click', this._cancel);

        Shopmobbing.Behaviors.Login.callBaseMethod(this, 'dispose');
    },

    _loggingInHandler: function(event) {
        var handler = this.get_events().getHandler('loggingIn');
        if (handler) {
            handler(this, Sys.EventArgs.Empty);
        }
    },
    _loggedInHandler: function(event) {
        var handler = this.get_events().getHandler('loggedIn');
        if (handler) {
            handler(this, Sys.EventArgs.Empty);
        }
    }
}
Shopmobbing.Behaviors.Login.registerClass('Shopmobbing.Behaviors.Login', Sys.UI.Behavior);

if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();


