var cWindow_UserLogin = {

    processButtonClick: function()
    {
        try {
            var r = Request.create();
            if (r !== null) {

                r.send(URL_AJAX_HANDLER, {'rm': 'user_login',
                                          '__login':  this.dom_user_login.val(),
                                          '__password': this.dom_user_password.val()}, this);
                this.startSend();
                delete(r);
            }
        }
        catch (e) {
            this.handleJSException(e);
        }
    },

    requestCallback: function(result, request_params, exception)
    {
        if (request_params.rm != 'user_login') {
            this.m = cWindow.requestCallback;
            return this.m(result, request_params);
        }

        if (exception) {
            this.finishSend();
            alert('Ошибка сервера. Попробуйте еще раз позже');
            result.exception.handled = true;
        } else {

            if (!result.successful) {
                this.finishSend();

                this.dom_user_login.val('');
                this.dom_user_password.val('');

                var error = this.errors[result.error_code];
                this.changeNotice(error.field, 'error', error.text);

            } else {
                window.location.replace(result.url);
            }
        }
    },

    open: function(el)
    {
        for (var i in this.info) {
            this.changeNotice(i, 'info', this.info[i]);
            this['dom_' + i].val('');
        }

        var offset = $(el).offset();
        this.finishSend();
        this.dom_window_area.show();
        var width = this.dom_form_area.get(0).offsetWidth;
        var width_el = el.offsetWidth;
        this.dom_form_area.css({'top': offset.top + 'px', 'left': (offset.left - width + width_el) + 'px'});
        documentEventDispatcher.addListener(this, ['click']);
    },

    close: function()
    {

        this.dom_window_area.hide();
        documentEventDispatcher.removeListener(this, ['click']);
    },

    listenerEvent: function(e)
    {
        e = jEvent.fixEvent(e);
        if (e.type == 'click' && e.pageX != 0 && e.pageX != 0) {
           var res = this.cursorLocation(e.pageX, e.pageY);
           if (!res) {
               this.close();
           }
        }
    },

    cursorLocation: function(x, y)
    {
        var offset = this.dom_form_area.offset();
        var width = this.dom_form_area.get(0).offsetWidth;
        var height = this.dom_form_area.get(0).offsetHeight;

        if (x < offset.left || x > offset.left + width || y < offset.top || y > offset.top + height) {
            return false;
        } else {
            return true;
        }
    },

    finishSend: function()
    {
		this.dom_button_send.show();
		this.dom_progress_indicator.hide();
    },

    startSend: function()
    {
        this.dom_button_send.hide();
     	this.dom_progress_indicator.show();
    },

    changeNotice: function(field, mode, text) {
        this['dom_' + field + '_notice']
            .removeClass('positive')
            .removeClass('error')
            .removeClass('info')
            .addClass(mode).html(text);
    }
}

function Window_UserLogin(data)
{
    this.pc = Window;
    this.pc(data);

    for (var f in cWindow_UserLogin) {
        this[f] = cWindow_UserLogin[f];
    }

    var _this = this;

    this.errors = {
        'USER_LOGIN_EMPTY': {'field': 'user_login', 'text': 'Не может быть пустым'},
        'USER_AGREEMENT_OVERDUE': {'field': 'user_login', 'text': 'Срок действия договора истёк'},
        'USER_PASSWORD_INVALID': {'field': 'user_password', 'text': 'Пароль неверный'},
        'USER_ACCESS_DENIED': {'field': 'user_login', 'text': 'Доступ возможен только из офиса'},
        'USER_NOT_FOUND': {'field': 'user_login', 'text': 'Договор не найден'},
        'USER_AGREEMENT_PRELIMINARY': {'field': 'user_login', 'text': 'Вход для пред-ого договора невозможен'}
    };

    this.info = {
        'user_login': 'Введите номер вашего договора',
        'user_password': 'Введите пароль, указанный в договоре'
    };

    for (var i in this.info) {
        this['dom_' + i + '_notice'] = $(_(this.name + '_' + i + '_notice'));
        this['dom_' + i] = $(_(this.name + '_' + i))
            .val('')
            .click(function(field) {
               return function() {
                    if (!_this['dom_' + field + '_notice'].hasClass('positive')) {
                        _this.changeNotice(field, 'info', _this.info[field]);
                    }
               }
            }(i));
    }
    this.dom_form_area = $(_(this.name + '_form_area'));
    this.dom_form = $(_(this.name + '_form')).submit(function() {_this.processButtonClick(); return false;});
    this.dom_window_area = $(_(this.name));
    this.dom_button_send = $(_(this.name + '_button_send'));//.click(function() { _this.processButtonClick() });
    this.dom_button_close = $(_(this.name + '_button_close')).click(function() { _this.close() });
    this.dom_button_cancel = $(_(this.name + '_button_cancel')).click(function() { _this.close() });
    this.dom_progress_indicator = $(_(this.name + '_progress_indicator'));
}

