
// Class to observe field and check validity via JSON resource, assigning css class according to validity
// (JSON resource must return {valid: 0} or {valid: 1})
FieldCheck = Class.create({
    initialize: function( options ){
        //set resonable options which can be overwritten
        this.options = $H({
            id: "user_login",
            listen_to: "blur",
            query: "/account/login_availability.json",
            css_good: "field_good",
            css_bad: "field_bad"
        }).merge(options)

        //watch the dom for loaded status and start the observation
        // Bind the THIS pointer to the function being called as an event listener
        this.begin_observation()
    },
    begin_observation: function(){
        //get the field object once and save it to the options hash
        this.options.set('element', $(this.options.get('id')) )
        if(!this.options.get('element')){ console.log("cant find element"); return;}

        //start the observation
        //Again, chaining functions on an observe, bind THIS as event listener
        this.options.get('element').observe( this.options.get('listen_to'), this.check_field.bindAsEventListener(this))
        this.options.get('element').observe( 'focus', this.remove_field_css.bindAsEventListener(this))
    },
    set_field_status: function(available){
        //clear the css
        this.remove_field_css();

        if (available == '1') {
            this.options.get('element').addClassName(this.options.get('css_good'))
        } else {
            this.options.get('element').addClassName(this.options.get('css_bad'))
        }
    },
    remove_field_css: function(){
        //remove the css class names for both good and bad when we focus on the element
        this.options.get('element').removeClassName(this.options.get('css_good'))
        this.options.get('element').removeClassName(this.options.get('css_bad'))
    },
    check_field: function(e){
        new Ajax.Request(this.options.get('query')+'?id=' + this.options.get('element').value, {
            method:'get',
            onComplete: function(transport){
                var json = transport.responseText.evalJSON();
                this.set_field_status(json.valid);
            }.bind(this) //here, you bind the THIS pointer to the psudo function, but since it's not a browser event, it just has to be bound, but not as event listener
        });
    }
});



SignupForm = Class.create({	
    initialize: function(){
        document.observe("dom:loaded", function(){
            this.fc = new FieldCheck({
                id: 'user_login',
                query: "/account/login_availability.json",
                listen_to: "blur",
                css_good: "available_login",
                css_bad: "unavailable_login"
            });

            // Add More functionality here if necessary

        }.bindAsEventListener(this));
    }
}
)


