var myrules = {
	'.username' : function(element) {
		element.onblur = function(){
		    new UsernameChecker(element);
		}
	}
};
Behaviour.register(myrules);

/**
 * Checks to see if the username is taken.
 * Expects the element passed in the constrcutor to have 
 * 3 image siblings, a searching, a taken, and a good image, 
 * in that order.  If the name is ok, shows the valid stuff, 
 * otherwise shows nothing.  
 * 
 * See Register.jsp to see it in action.
 */
var UsernameChecker = Class.create();
UsernameChecker.prototype = {
    initialize: function(element) {
        this.element = element;
        var value = element.value;
        if(value.length == 0) {
    	    return;
    	}
    	
    	var images = $A(this.element.parentNode.getElementsByTagName('img'));
    	images[0].style.display = 'inline';
    	new Ajax.Request(
    	"/trail/register/username/available.mb", 
    	{
    		method: 'get',
    		parameters: "username=" + value + "&userProfilePk.pkValue=" + $F('pkValue'), 
    		onComplete: this.handleResponse.bind(this)
    	});    
    },
    
    handleResponse: function(response) {
        this.element.style.borderWidth = "2px";
        this.element.style.borderStyle = "solid";

    	var images = $A(this.element.parentNode.getElementsByTagName('img'));
        images.each(function(img){
           img.style.display = 'none'; 
        });
        
        if(response.responseText == this.element.value.toLowerCase()) {
            this.element.style.borderColor = "green";
            images[2].style.display = 'inline';
        } else {
            this.element.style.borderColor = "red";
            images[1].style.display = 'inline';
        }
    }
};
