Ajax.ScriptRequest = Class.create();

Ajax.ScriptRequest.prototype = {

	setOptions: function(options){
		
		this.options = {parameters: {}};
		Object.extend(this.options, options || {});
	    if (typeof this.options.parameters == 'string') {
			this.options.parameters = this.options.parameters.toQueryParams();
		}		
	},
	
	initialize: function(url, options){

		this.url = url;
		this.setOptions(options);

		Object.extend(this.options, options || {});
	    switch (typeof this.options.parameters) {
			case 'string': 		this.options.parameters = this.options.parameters.toQueryParams(); break;
			case 'undefined': 	this.options.parameters = {}; break;
		}

		this.id = Ajax.ScriptRequest.count ++;

		if (this.options.callbackName){
			
			this.options.parameters[this.options.callbackName] = "Ajax.ScriptRequest._q" + this.id;
			Ajax.ScriptRequest["_q" + this.id] = this.respond.bind(this);
			if (Ajax && Ajax.Responders){ Ajax.Responders.dispatch('onCreate', this, this.transport); }		
		}

		this.request(); 
	},
	
	respond: function(response){
		
		try {
			if (this.options.onResponse){
				this.options.onResponse(response);
			}
			this.clear();
			if (Ajax && Ajax.Responders){ Ajax.Responders.dispatch('onComplete', this, this.transport);	}
		} catch(e){
			this.dispatchException(e);
		}				
	},
	
	request: function(){
		
		var params = Hash.toQueryString(this.options.parameters);
		this.url = this.url + (params ? (this.url.include('?') ? '&' : '?') + params : '');
		
		try {
			this.transport = document.createElement('script');
			this.transport.type ='text/javascript';
			this.transport.src = this.url;
			
			if (this.options.onCreate) {
				this.options.onCreate(this.transport);
			}
			Ajax.Responders.dispatch('onCreate', this, this.transport);
			
		} catch(e){
			this.dispatchException(e);
		}
		
		document.getElementsByTagName('head')[0].appendChild(this.transport);
	},
	
	dispatchException: function(exception) {
		(this.options.onException || Prototype.emptyFunction)(this, exception);
		Ajax.Responders.dispatch('onException', this, exception);
	},
	
	clear: function(){
		this.transport.parentNode.removeChild(this.transport);
	}
};

Ajax.ScriptRequest.count = 0;
Ajax.ScriptRequest.extend = function(extension){
	var klass = Class.create();
	klass.prototype = Object.extend(new Ajax.ScriptRequest(), extension);
	return klass;		
}