/*
	Class:    	dwAvailabilityChecker
	Author:   	David Walsh
	Website:    http://davidwalsh.name
	Version:  	1.0
	Date:     	09/23/2008
	Built For:  MooTools 1.2.0
	
	SAMPLE USAGE AT BOTTOM OF THIS FILE
	
*/


var dwAvailabilityChecker = new Class({
	
	//implements
	Implements: [Options],

	//options
	options: {
		trigger: 'keyup',
		offset: { x:0, y:0 },
		element: '',
		minLength: 5,
		availableClass: 'available',
		takenClass: 'taken',
		availableImage: '',
		takenImage: '',
		url: 'ajax-username-check.php'
	},
	
	//initialization
	initialize: function(options) {
		//set options
		this.setOptions(options);
		
		//validate it
		this.validate();
	},
	
	//a method that does whatever you want
	validate: function() {
		this.options.element.addEvent(this.options.trigger,function() {
			if(this.options.element.value.length >= this.options.minLength) {
				var othis = this;
				var request = new Request({
					url: othis.options.url,
					method: 'get',
					data: {
						username: othis.options.element.value,
						ajax: 1
					},
					onRequest: function() {
						//remove existing classes
						othis.options.element.removeClass(othis.options.availableClass).removeClass(othis.options.takenClass);
					},
					onComplete: function(response) {
						//add class
						othis.options.element.addClass(response == 1 ? othis.options.availableClass : othis.options.takenClass);
						othis.injectImage(response == 1 ? othis.options.availableImage : othis.options.takenImage);
					}
				}).send();
			}
		}.bind(this));
	},
	
	//adds the image
	injectImage: function(image) {
		
		//figure out its position
		var pos = this.options.element.getCoordinates();
		
		var img = new Element('img',{
			src: image,
			styles: {
				'z-index': 100000,
				'position': 'absolute',
				'top': pos.top + this.options.offset.y,
				'left': pos.left + pos.width + this.options.offset.x
			}
		}).inject(document.body);
		
		
	}
	
});

/* usage 
//once the DOM is ready
window.addEvent('domready', function() {
	var validator = new dwAvailabilityChecker({
		trigger: 'keyup',
		element: $('username'),
		availableImage: 'checkmark.jpg',
		takenImage: 'warning.jpg',
		offset: { x: 4, y: 4 },
		minLength: 4,
		url: 'ajax-username-check.php'
	});
});
*/
