
Sajax = Class.create( {
initialize: function( uri, callback, options ) {
this.callback = callback;
this.options = Object.extend( { timeout: 0 }, options );
var f = "callback" + Math.floor((Math.random() * 10000 ));
eval( f + " = this.response.bind( this );" );
if ( uri.search( /\?/ ) == -1 )
uri += "?";
else
uri += "&";
uri += "callback=" + f;
var tag = new Element("script");
tag.type = "text/javascript";
tag.src = uri;
var head = document.getElementsByTagName("head");
if ( !head || head.length < 1 )
document.body.appendChild( tag );
else
head[0].appendChild( tag );
this.wait();
},
wait: function() {
if ( arguments.length )
this.options.timeout = arguments[0];
if ( this.options.timeout ) {
delete this._do_not_respond;
this._timeout = setTimeout( this.on_timeout.bind( this ), this.options.timeout );
}
},
response: function( data ) {
this.stop_timeout();
if ( !this._do_not_respond ) {
this.callback( this, data );
}
},
on_timeout: function() {
this.stop_timeout();
this._do_not_respond = true;
if ( this.options.on_timeout ) {
this.options.on_timeout( this );
}
},
stop_timeout: function() {
if ( this._timeout ) {
window.clearTimeout( this._timeout );
delete this._timeout;
}
}
} );
