

function login(options)
{
    this.settings = {};
    $.extend(this.settings, this.defaults, options);

    if (!this.settings['popup'].length)
        throw new Error('Popup not found.');

    var obj = this;
    
    jQuery(document).bind(
        this.settings['event'],
        this.settings['shortcut'],
        function (event) {obj.showPopup.apply(obj, new Array(event))}
    );

    this.settings['submitButton'].click(function(event){
        obj.submitFormHandler.call(obj);
        event.stopPropagation( );
        event.preventDefault( );
        return false;
    });
}

login.prototype = {
    defaults : {
        'popup'    : null,  // само окно
        'form'     : null,  // форма с логином и паролем
        'errors'   : null,  // контейнер для отображения ошибок
        'succeed'   : null,  // контейнер, отображаемый при успешном логине
        'succeed-name' : null, // контейнер для имени.

        'event'    : 'keyup',
        'shortcut' : "ctrl+shift+l",
        'loginUrl' : "",
        
        'submitButton' : null,
        'overlay':{
            'color': '#FFF',
            'loadSpeed': 200,
            'opacity': 0.9
        }
    },
    settings : null,

    submitFormHandler : function()
    {
        this.hideErrors()
            .disableForm();

        var send = {
          "email" : this.settings["popup"].find("input[name=email]").val(),
          "password" : this.settings["popup"].find("input[name=password]").val()
        };
        
        var obj = this;
        $.post(
            this.settings["loginUrl"],
            send,
            function (data, success) {
                obj.submitFormCallback.apply(obj, new Array(data, success));
            },
            'json'
        );
    },

    /**
     * Функция обратного вызова для логина.
     */
    submitFormCallback : function (data, status)
    {
        // если нажали Esc, пока происходила отправка данных
        // и получение ответа.
        if (this.settings['popup'].is(":hidden"))
        {
            this.enableForm()
                .hideErrors();
            return;
        }

        if (data.errors)
        {
            this.showErrors(data.errors)
                .enableForm();
        } else {
            var name = null;
            if (data.identity !== undefined)
                name = data.identity;
                
            this.hideErrors()
                .hideForm()
                .showSucceed(name);
           setTimeout("location.reload(true)", 500);
        }
    },

    /**
     * Показываем ошибки
     */
    showErrors : function(errors)
    {
        if (null !== this.settings['errors'])
        {
            var ul = $("<ul></ul>");
            for (var field in errors)
                for (var error in errors[field])
                    ul.append("<li>" + errors[field][error] + "</li>");
            this.settings['errors'].empty().append(ul);

            if (this.settings['errors'].is(":hidden"))
                this.settings['errors'].slideDown();
        }

        this.settings['popup']
            .animate({"left": "+=5px"},  {"duration":"fast"})
            .animate({"left": "-=10px"}, {"duration":"fast"})
            .animate({"left": "+=10px"}, {"duration":"fast"})
            .animate({"left": "-=10px"}, {"duration":"fast"})
            .animate({"left": "+=5px"},  {"duration":"fast"});

       return this;
    },

    // скрываем контейнер с ошибками
    hideErrors : function()
    {
        if (null === this.settings['errors'])
            return this;
        
        this.settings['errors']
            .empty()
            .slideUp();
        return this;
    },

    /**
     * отключаем все инпуты в форме
     */
    disableForm : function()
    {
        if (null == this.settings['form'])
            return this;
        
        this.settings['form'].find('input').attr('disabled', 'disabled');
        this.settings['form'].find('button').attr('disabled', 'disabled');
        return this;
    },

    /**
     * Включаем все инпуты в форме
     */
    enableForm : function()
    {
      if (null == this.settings['form'])
            return this;

      this.settings['form'].find('input').removeAttr('disabled');
      this.settings['form'].find('button').removeAttr('disabled');
      return this;
    },

    /**
     * Скрываем форму
     */
    hideForm : function()
    {
        if (null == this.settings['form'])
            return this;
        
        this.settings['form'].slideUp();
        return this;
    },

    /**
     * Показывем приветствие для вошедшего пользователя.
     */
    showSucceed : function(name)
    {
        if (null !== this.settings['succeed'])
        {
            if (undefined !== name
                && null !== this.settings['succeed-name'])
                this.settings['succeed-name'].html(name);
            
            this.settings['succeed'].slideDown();
        }

        return this;

    },

    /**
     * Показываем модальное окно для входа
     */
    showPopup : function(event)
    {
        var obj = this;
        
        triggers = this.settings['popup'].overlay({
            // some expose tweaks suitable for modal dialogs
            expose: this.settings.overlay,
            closeOnClick: false,
            api: true
        }).load();

        event.stopPropagation( );
        event.preventDefault( );
        return false;
    }
}
