/**
 * /public_html/javascript/request_handler.js
 *
 * @author    Ahmed Chafik (admin@achafik.com)
 * @copyright aChafik 2007
 * @version   Define("Id: request_handler.js,v 1.00 2007/10/07 17:35:37 Ahmed")
 * <script>
 */

function request_handler( async ) {
    // Should connections be asynchronous?
    this.async = async ? true : false;
}

// Initializes the XML handler
request_handler.prototype.init = function() {
    try {
        this.handler = new XMLHttpRequest();
        return (this.handler.setRequestHeader ? true : false);
    } catch (e) {
        try {
            this.handler = eval("new A" + "ctiv" + "eX" + "Ob" + "ject('Micr" + "osoft.XM" + "LHTTP');");
            return true;
        } catch (e) {
          return false;
        }
    }
}

// Check the system status
request_handler.prototype.ready = function() {
  return !(this.handler.readyState && (this.handler.readyState < 4));
}

// Send data
request_handler.prototype.send = function( url, datastream, handler ) {

    if (!this.handler) {
        // Handler isn't functioning... try initializing it
        if (!this.init())
          return false;
    }

    // If the handler is ready, open the connection and send the data
    if (this.ready()) {

        // Set our handler
        if (typeof handler == 'function')
            this.handler.onreadystatechange = handler;

        this.handler.open('POST', url, this.async);
        this.handler.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        this.handler.send(datastream);

        if (!this.async && this.handler.readyState == 4 && this.handler.status == 200)
          return true;

    } else {
        // Looks like we're busy right now... Why don't you take a timeout and try again later?
        window.setTimeout(function() {
            request_handler.send(url, datastream, handler);
        }, 300);
    }

  return false;
}

request_handler = new request_handler(true);