var Greatimmo = {};

Greatimmo.NumObj = Class.create({
    SEPARATOR: '/',

    initialize: function(elem, carrier) {
        this.firstPart = $(elem + '1');
        this.secondPart = $(elem + '2');
        this.carrier = $(carrier);
        if (!this.carrier) {
            alert("Couldn't initialize carrier field: " + carrier);
        }
        if (!(this.firstPart && this.secondPart)) {
            alert("Couldn't initialize input fields for " + elem);
        }
//        Event.observe($('submit-link'), 'click', this.submit.bindAsEventListener(this));
        Event.observe(this.getForm(), 'submit', this.submit.bindAsEventListener(this));
        Event.observe(this.firstPart, 'keypress', this.filter.bindAsEventListener(this));
        Event.observe(this.secondPart, 'keypress', this.filter.bindAsEventListener(this));
        Event.observe(this.firstPart, 'keyup', this.notifyListeners.bindAsEventListener(this));
        Event.observe(this.secondPart, 'keyup', this.notifyListeners.bindAsEventListener(this));
    },

    callbacks: {
        onActive: function() {
        },

        onInactive: function() {
        }
    },

    notifyListeners: function(event) {
        if ($F(this.firstPart).length == this.firstPart.maxLength) {
            this.secondPart.focus();
            }
        if ($F(this.firstPart).length + $F(this.secondPart).length > this.firstPart.maxLength) {
            this.callbacks.onActive();
        } else {
            this.callbacks.onInactive();
        }
    },

    filter: function(event) {
        var ch = String.fromCharCode(event.charCode ? event.charCode : event.keyCode);
        if (/\r/.test(ch)) {
            Event.stop(event);
            this.submit();
        }
        if(/\w/.test(ch) && !/\d/.test(ch)) {
            Event.stop(event);
        }
    },

    submit: function(event) {
        this.carrier.value = $F(this.firstPart) + this.SEPARATOR + $F(this.secondPart);
        this.getForm().submit();
    },

    getForm: function() {
        return $(this.firstPart.form);
    }
});
