﻿/// <reference name="MicrosoftAjax.js"/>

Type.registerNamespace("Shopmobbing.Controls");

Shopmobbing.Controls.Registration = function(element) {
    Shopmobbing.Controls.Registration.initializeBase(this, [element]);

    this._email = null;
    this._userNameIsAvailable = false;
    this._emailIsAvailable = false;
    this._authenticationServicePath = null;

    this._showRegistrationFormDelegate = null;
    this._registerDelegate = null;
    this._cancelDelegate = null;
    this._validateRegistrationPossibilityDelegate = null;
    this._registeringDelegate = null;
    this._registeredDelegate = null;
    this._checkUserNameAvailabilityDelegate = null;
}

Shopmobbing.Controls.Registration.prototype = {

    get_authenticationServicePath: function() {
        if (this._authenticationServicePath == null) {
            this.set_authenticationServicePath(Sys.Services.AuthenticationService.get_path());
        }
        return this._authenticationServicePath;
    },
    set_authenticationServicePath: function(value) {
        this._authenticationServicePath = value;
    },

    add_registering: function(handler) {
        this.get_events().addHandler('registering', handler);
    },
    remove_registering: function(handler) {
        this.get_events().removeHandler('registering');
    },
    add_registered: function(handler) {
        this.get_events().addHandler('registered', handler);
    },
    remove_registered: function(handler) {
        this.get_events().removeHandler('registered');
    },

    _checkUserNameAvailability: function(eventObject) {

        //        if (eventObject.keyCode == undefined || eventObject.keyCode === 16 || eventObject.keyCode === 17 || eventObject.keyCode === 18) {
        //            return;
        //        }

        username = $("#txtRegistrationUserName", el).val().trim();

        if (username === "") {
            sender._userNameIsAvailable = false;
            return;
        }

        var me = this;
        var el = this.get_element();

        $.ajax({
            type: "POST",
            url: this.get_authenticationServicePath() + '/CheckUserNameAvailability',
            data: "{'userName' : '" + username + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data, textStatus, xhr) {
                var available = data.d;
                if (available === true) {
                    $("#txtRegistrationUserName", el).css('background-color', 'green');
                    me._userNameIsAvailable = true;
                }
                else {
                    $("#txtRegistrationUserName", el).css('background-color', 'red');
                    me._userNameIsAvailable = false;
                }
                me._validateRegistrationPossibilityDelegate.call();
            }
        });
    },

    _checkEmailAvailability: function(eventObject) {

        //        if (eventObject.keyCode == undefined || eventObject.keyCode === 16 || eventObject.keyCode === 17 || eventObject.keyCode === 18) {
        //            return;
        //        }

        email = $("#txtRegistrationEmail", el).val().trim();

        if (email === "") {
            this._userNameIsAvailable = false;
            return;
        }

        var me = this;
        var el = this.get_element();

        if (!this._email.get_isValid()) {
            me._emailIsAvailable = false;
            me._validateRegistrationPossibilityDelegate.call();
        }
        $.ajax({
            type: "POST",
            url: this.get_authenticationServicePath() + '/CheckEmailAvailability',
            data: "{'email' : '" + email + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data, textStatus, xhr) {
                var available = data.d;
                if (available === true) {
                    $("#txtRegistrationEmail", el).css('background-color', 'green');
                    me._emailIsAvailable = true;
                    me._email.set_alreadyExistsInDatabase(false);
                }
                else {
                    $("#txtRegistrationEmail", el).css('background-color', 'red');
                    me._emailIsAvailable = false;
                    me._email.set_alreadyExistsInDatabase(true);
                }
                me._validateRegistrationPossibilityDelegate.call();
            },
            error: function(xhr, textStatus, errorThrown) {
                alert('error!');
            }
        });
    },

    _validateRegistrationPossibility: function() {

        var el = this.get_element();

        //this._checkUserNameAvailabilityDelegate($get("txtRegistrationUserName", el).value);

        if ($("input[type='text']", el).val() !== "" && $("input[type='password']", el).val() !== "" &&
        $("#txtRegistrationPassword", el).val() === $("#txtRegistrationPasswordConfirmation", el).val() &&
        !$("input", el).hasClass('watermark') && this._userNameIsAvailable && this._emailIsAvailable && 
        !this._email.get_alreadyExistsInDatabase()) {
            $("#btnRegister", this.get_element()).removeAttr("disabled");
            return true;
        }
        else {
            $("#btnRegister", this.get_element()).attr("disabled", "disabled");
            return false;
        }
    },

    _register: function() {
        $(document.body).css("cursor", "wait");
        $.blockUI({ baseZ: 1010 });
        var me = this;

        var username = $get('txtRegistrationUserName', this.get_element()).value;
        var email = $get('txtRegistrationEmail', this.get_element()).value;
        var password = $get('txtRegistrationPassword', this.get_element()).value;

        var registrationInfo = new Object();
        registrationInfo.userName = username;
        registrationInfo.email = email;
        registrationInfo.password = password;
        registrationInfo.profileData = new Object();

        var registeringHandler = this.get_events().getHandler('registering');
        if (registeringHandler !== null) {
            registeringHandler(this, Sys.EventArgs.Empty);
        }

        var authenticationServicePath = Sys.Services.AuthenticationService.get_path();

        $.ajax({
            type: "POST",
            url: authenticationServicePath + '/Registration',
            data: Sys.Serialization.JavaScriptSerializer.serialize(registrationInfo),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data, textStatus, xhr) {
                if (data.d === true) {
                    $(me.get_element()).css("background-color", "green");
                    $.modal.close();

                    $(document.body).css("cursor", "default");

                    var registeredHandler = me.get_events().getHandler('registered');
                    if (registeredHandler !== null) {
                        registeredHandler(me, Sys.EventArgs.Empty);
                    }

                }
                else {
                    $(me.get_element()).css("background-color", "red");
                    $(document.body).css("cursor", "default");

                    alert('error while registering!');
                }
                $.unblockUI();
            }
        });
    },

    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 allowed = me._validateRegistrationPossibilityDelegate.call();
                        if (allowed) {
                            me._registerDelegate.call();
                        }
                    }
                });
                $("#txtRegistrationUserName", el).blur();
                $("#txtRegistrationUserName", el).removeClass('watermark');
            },
            onClose: function(dialog) {
                $(document).unbind('keydown');
                me._cancelDelegate.call();
            }
        });
    },

    cancel: function() {
        $("input[type='text']", this.get_element()).filter("disabled").val("").css("background-color", "");
        $("input[type='password']", this.get_element()).val("").css("background-color", "");
        this._validateRegistrationPossibilityDelegate.call();
        $.modal.close();
    },

    initialize: function() {
        Shopmobbing.Controls.Registration.callBaseMethod(this, 'initialize');

        var el = this.get_element();

        if (this._showRegistrationFormDelegate === null) {
            this._showRegistrationFormDelegate = Function.createDelegate(this, this.show);
        }

        this._registerDelegate = Function.createDelegate(this, this._register);
        this._cancelDelegate = Function.createDelegate(this, this.cancel);

        this._validateRegistrationPossibilityDelegate = Function.createDelegate(this, this._validateRegistrationPossibility);
        this._checkUserNameAvailabilityDelegate = Function.createDelegate(this, this._checkUserNameAvailability);
        this._checkEmailAvailabilityDelegate = Function.createDelegate(this, this._checkEmailAvailability);

        this._registeringDelegate = Function.createDelegate(this, this._registeringHandler);
        this._registeredDelegate = Function.createDelegate(this, this._registeredHandler);

        var options1 = {
            callback: this._checkUserNameAvailabilityDelegate,
            wait: 750,
            highlight: true,
            captureLength: 2
        }

        var options2 = {
            callback: this._checkEmailAvailabilityDelegate,
            wait: 750,
            highlight: true,
            captureLength: 2
        }

        $("#txtRegistrationUserName", el).typeWatch(options1);
        $("#txtRegistrationEmail", el).typeWatch(options2);

        //$("input[type='text']", el).bind('keyup', null, this._validateRegistrationPossibilityDelegate);
        $("input[type='password']", el).bind('keyup', null, this._validateRegistrationPossibilityDelegate);

        $("#btnRegister", el).bind('click', null, this._registerDelegate);
        $("#btnCancel", el).bind('click', null, this._cancelDelegate);

        $("#chbGeneratePassword", el).attr('disabled', 'disabled');

        this._email = $create(Shopmobbing.Behaviors.EmailValidator, {}, {}, {}, $get("txtRegistrationEmail", el));

        $('#txtRegistrationEmail', el)
            .watermark('email', 'watermark');
        $('#txtRegistrationUserName', el)
            .watermark('user name', 'watermark');
        $('#txtRegistrationPassword', el)
            .watermark('password', 'watermark');
        $('#txtRegistrationPasswordConfirmation', el)
            .watermark('confirm password', 'watermark');
    },
    dispose: function() {
        if (this._showRegistrationFormDelegate) {
            delete this._showRegistrationFormDelegate;
        }
        if (this._registerDelegate) {
            $("#btnRegister", this.get_element()).unbind('click', this._registerDelegate);
            delete this._registerDelegate;
        }
        if (this._cancelDelegate) {
            $("#btnCancel", this.get_element()).unbind('click', this._cancelDelegate);
            delete this._cancelDelegate;
        }
        if (this._validateRegistrationPossibility) {
            delete this._validateRegistrationPossibility;
        }
        if (this._registeringDelegate) {
            delete this._registeringDelegate;
        }
        if (this._registeredDelegate) {
            delete this._registeredDelegate;
        }

        Shopmobbing.Controls.Registration.callBaseMethod(this, 'dispose');
    },

    _registeringHandler: function(event) {
        var handler = this.get_events().getHandler('registering');
        if (handler) {
            handler(this, Sys.EventArgs.Empty);
        }
    },
    _registeredHandler: function(event) {
        var handler = this.get_events().getHandler('registered');
        if (handler) {
            handler(this, Sys.EventArgs.Empty);
        }
    }
}
Shopmobbing.Controls.Registration.registerClass('Shopmobbing.Controls.Registration', Sys.UI.Control);

if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
