function appendScript( url ){
	var head = document.getElementsByTagName( 'head' )[0];
	var oldScript = $( "remoteScript" );
	if( oldScript )
		oldScript = null;
	var remoteScript = document.createElement( "script" );
	remoteScript.src = url;
	remoteScript.type = "text/javascript";
	remoteScript.defer = true;
	remoteScript.id = "remoteScript";
	void( head.appendChild( remoteScript ) );
}

function executeScript( url ) {
	var ajaxExec = new CallAjax( url,{ execute:true, method:'get' } );
	// si no soporta ajax, trato de agregar el script al encabezado
	if( !ajaxExec.request )
		appendScript( url );
}

// objeto que realiza una llamada Ajax creado el 16 de marzo del 2006
// basado en http://www.ajax.com.es/index.php?title=XMLHttpRequest y en moo.ajax
var CallAjax = Class.create();
CallAjax.prototype = {
	initialize: function( url, options ) {
		this.execute = options.execute || false; // si es verdadero evaluo la respuesta
		this.parameters = options.parameters || null;
		this.method = options.method ? options.method.toLowerCase() : 'post';
		this.onComplete = options.onComplete || null;
		this.update = $( options.update ) || null;
		this.request = false;
		this.url = url;
		this.createRequest();
		if(this.request) {
			this.request.open(this.method, this.url, true);
			this.request.onreadystatechange = this.requestChange.bind( this );
			if ( this.method == 'post' ){
				this.request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
				if (this.request.overrideMimeType)
					this.request.setRequestHeader('Connection', 'close');
				this.request.send( this.createQuery() );
			} else {
				this.request.send( "" );
			}	
		}
	},
	requestChange: function(){
		if( this.request.readyState == 4 ) {
			if( this.request.status == 200 ){
				if (this.onComplete) 
					setTimeout(function(){this.onComplete(this.request);}.bind( this ), 10);
				if (this.update)
					setTimeout(function(){this.update.innerHTML = this.request.responseText;}.bind( this ), 10);
				if ( this.execute )
					setTimeout(function(){ eval( this.request.responseText ); }.bind( this ), 10);
					
				this.request.onreadystatechange = function(){};
			} else {
				alert("There was a problem retrieving the XML data:\n" +this.request.statusText);
			}
		}
	},
	createRequest: function(){
		// Para mozilla y safari
		if( window.XMLHttpRequest ) {
			this.request = new XMLHttpRequest();
		// Para IE
		} else if(window.ActiveXObject) {
			try {
				this.request = new ActiveXObject("Msxml2.XMLHTTP");
			} catch(e) {
				try {
					this.request = new ActiveXObject("Microsoft.XMLHTTP");
				} catch(e) {}
			}
		}
	},
	getRequest: function(){
		return this.request;
	},
	createQuery: function(){
		var keys = [];
		for( var key in this.parameters  )
			keys[keys.length] = key + "=" + encodeURIComponent( this.parameters[key] );
		return keys.join( '&' );
	}
}
