/**
 * mooproto -- some mootools extensions for transition from Prototype library
 * 		support Prototype AJAX object
 *
 * @author Rich Clingman, Nov 2008
 */

Element.implement({
	hide: function ( what, how ) {
		this.style.display = 'none';
	},
	show: function ( what, how ) {
		this.style.display = this.tagName === 'DIV' ? 'block' : 'inline';
	},
	toggle: function ( what, how ) {
		var display = this.getStyle('display');
		if (display === 'none') {
			this.show();
		} else {
			this.hide();
		}
	},
	enable: function ( what, how ) {
		this.disabled = false;
	},
	disable: function ( what, how ) {
		this.disabled = true;
	}
});

var Ajax = {
	currentRequests: {},
	cancelRequestOfClass: function( ofClass ) {
		if (ofClass && this.currentRequests[ofClass]) { 
			try {
				this.currentRequests[ofClass].cancel(); 
			} catch(e) {}
			try {
				delete this.currentRequests[ofClass];
			} catch(e) {}
		}
	}
};

Ajax.Updater = new Class({
	Extends: Request.HTML,
	onlyLatestOfClass: null,
	initialize: function(div, url, options){
		if (typeof options === 'undefined') {
			options = {};
		}
		if (options.onlyLatestOfClass) {
			if (Ajax.currentRequests[options.onlyLatestOfClass]) {
				Ajax.currentRequests[options.onlyLatestOfClass].cancel();
				delete Ajax.currentRequests[options.onlyLatestOfClass];
			}
			Ajax.currentRequests[options.onlyLatestOfClass] = this;
			this.onlyLatestOfClass = options.onlyLatestOfClass;
		}
		
		// map prototype options to mootools
		options.url = url;
		options.update = div;
		if (options.asynchronous !== undefined) {
			options.async = options.asynchronous;
		}
		if (options.onComplete !== undefined) {
			options.onSuccess = options.onComplete;
		}
		if (options.parameters !== undefined) {
			options.data = options.parameters;
		}
		
		this.parent(options);
		this.send();
	}
});

Ajax.Request = new Class({
	Extends: Request.JSON,
	onlyLatestOfClass: null,
	initialize: function(url, options){
		if (options.onlyLatestOfClass) {
			if (Ajax.currentRequests[options.onlyLatestOfClass]) {
				Ajax.currentRequests[options.onlyLatestOfClass].cancel();
				delete Ajax.currentRequests[options.onlyLatestOfClass];
			}
			Ajax.currentRequests[options.onlyLatestOfClass] = this;
			this.onlyLatestOfClass = options.onlyLatestOfClass;
		}
		
		// map prototype options to mootools
		options.url = url;
		if (options.asynchronous) {
			options.async = options.asynchronous;
		}
		if (options.json) {
			options.data = 'json=' + escape(JSON.encode(request));
		} else if (options.parameters) {
			options.data = options.parameters;
		}
		
		this.parent(options);
		this.send();
	}
});

var $F = function( el ) { return $(el).value; };
