Ajax.ScriptRequest = Class.create();

Ajax.ScriptRequest.prototype = {
	
	initialize: function(url, options){

		this.options = {parameters: {}};
		this.url = url;
		Object.extend(this.options, options || {});
	
	    if (typeof this.options.parameters == 'string') {
			this.options.parameters = this.options.parameters.toQueryParams();
		}		
	
		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] = function(response){
				this.options.onSuccess(response);
				this.clear();
				if (Ajax && Ajax.Responders){ Ajax.Responders.dispatch('onComplete', this, this.transport);	}				
			}.bind(this);
			
			if (Ajax && Ajax.Responders){ Ajax.Responders.dispatch('onCreate', this, this.transport); }		
		}

		this.request(); 
	},
	
	request: function(){
		
		var params = $H(this.options.parameters).toQueryString();
		this.url = this.url + (params ? (this.url.indexOf('?') != -1 ? '&' : '?') + params : '');
		
		this.transport = document.createElement('script');
		this.transport.type ='text/javascript';
		this.transport.src = this.url;
		
		document.getElementsByTagName('head')[0].appendChild(this.transport);
	},
	
	clear: function(){
		
		this.transport.parentNode.removeChild(this.transport);
	}
};

Ajax.ScriptRequest.count = 0;