/**
*   CtXMLHttpRequest
*
*   Javscript class for handling XMLHttpRequests in CorePublish
*
*
*   @author Arve Skjørestad, august 2004
*/
/**
*  class CorePublishSubMenu
*
*
*/
function CtXMLHttpRequest() {
	
    if (window.XMLHttpRequest) { // Moz
      req = new XMLHttpRequest();
      this.browsertype = "moz";
    }
    else { // MSIE
      req = new ActiveXObject("Microsoft.XMLHTTP");
      this.browsertype = "ie";
    }

    this.reqobject = req; 
    this.onreadystatechangefunctionname = "void();";

}

/**
 * Sets the function that will be called when the xmlhttp object
 * changes state. It is very important that this function is called on the proper way: <br>
 * xmlHttp.setOnreadystatechange('functionname()'); or xmlHttp.setOnreadystatechange('functionname');
 * will NOT work. <br>
 * Use:<br>
 * xmlHttp.setOnreadystatechange(functionname); // function name NOT as a string
 * <p>
 * Advanced use:<br>
 * If you are going to call several async calls using the same callbackhandler, you 
 * will probably need a way to tell which instance/call that called your callbackhandler. This 
 * is not easy to do, but here is a workaround: <br>
 * Your callbackhandler needs to take the xmlHttpobject as the first argument, like e.g.: <br>
 * <code>function myCallBackHandler(xmlHttpObject) {} </code> <br>
 * When setting the callbackhandler, you need to do something like this:<br>
 * <code>
 * xmlObj = new CtXMLHttpRequest();
 * xmlObj.setOnreadystatechange(function () { myCallBackHandler(xmlObj); }) ;
 * </code>
 * <br>
 * The callbackhandler, myCallBackHandler(), will then be called with the belonging XMLHttpobject
 * as the first argument, and you then know which object is calling you.
 * 
 * @param functionname function to call when the readystate changes.
 */
CtXMLHttpRequest.prototype.SetOnreadystatechange = function(functionname) {
    this.reqobject.onreadystatechange = functionname;
}



/**
 *  opens the http connection
 * 
 *  @param method GET or POST
 *  @param url the url to open 
 *  @param asyncFlag set to TRUE to run asynchronously, FALSE otherwise. Always use TRUE!
 *  @param username[optional] username if url requires logon
 *  @param password[optional] password if url requires logon
 */
CtXMLHttpRequest.prototype.open = function(method, url, asyncFlag, username, password) {
    //alert("calling this.reqobject.open with method " + method + ", url " + url );

    if (this.browsertype == "ie") {
        var rand =  Math.random(1000);
        url += "&ie_nocache_random_param"+ rand + "=" + rand;  
    }
    //alert(url);

    this.reqobject.open(method, url, asyncFlag, username, password);
}

/**
 *  opens a CorePublish/CPLIB XMLHttpService - expects to talk to a CpXMLHttpRequestManager
 *  on the serverside. 
 * 
 *  @param url the url to the CpXMLHttpRequestManager (including "filename.php" at the end but without "?")
 *  @param service the name of the service to open
 *  @param parameters array containing additional parameters to the service. use 'parametername' => value style arrays
 *  @param responseFormat which format to retrive the result in, 'text' or 'xml'.
 */
CtXMLHttpRequest.prototype.openCorePublishService = function(url, service, responseFormat, parameters ) {

    var finalurl = url + "?service=" + service + "&responseformat=" + responseFormat;

    if (parameters) {
        for(var key in parameters) {
            finalurl += "&"+key+"="+parameters[key];
        }
    }
    this.open("GET", finalurl, true);
    this.send();
}

/**
 *  Sends the request. 
 * 
 *  @param data the data to post. Set to null if not used.
 */
CtXMLHttpRequest.prototype.send = function(data) {
    this.reqobject.send(data);
}

/**
 *  Returns the ready state for this object. <p>
 *  0 = uninitialized<br>
 *  1 = loading<br>
 *  2 = loaded<br>
 *  3 = interactive<br>
 *  4 = complete<br>
 * 
 *  @return int the ready state
 */
CtXMLHttpRequest.prototype.getReadyState = function() {
    return this.reqobject.readyState;
}

/**
 * returns whether the request is ready to be processes. 
 * if true is returned, this means that the request is ready 
 * to be processed and has no errors
 * 
 */
CtXMLHttpRequest.prototype.isReadyToProcess = function() {
    
    if (this.reqobject.readyState == 4 && this.hasError() == false) {
        return true;
    } else {
        return false;
    }
    
}

/**
 * returns whether the request has errors
 * If the request has errors, you can normally 
 * call the getErrorString() to get the error message
 * Note that this function will always return true until 
 * the ready state is 4, meaning the request is finished.
 * 
 */
CtXMLHttpRequest.prototype.hasError = function() {
    if ( this.getStatus() != 200 && this.getReadyState() == 4) {
        return true;
    } else {
        return false;
    }
}

CtXMLHttpRequest.prototype.getErrorString = function() {
    if ( this.hasError() == false) {
        return "";
    } else {
        switch (this.getStatus()) {
        case "404":
            // we need to handle this special, otherwise 
            // the responsetext will be set to the html output
            // from the error page
            return "the page requested could not be found. Check the url to the service";
            break;
        case "500":
        default:
            return "An internal service error occured.";

            break;
        }
    }
}

/**
 *  Returns the http statuscode
 *  e.g:<br>
 *  404 page not found<br>
 *  200 ok <br>
 *  Please note that status is not always available in IE during 
 *  processing, therefore "200" may be returned until
 *  the isreadytoprocess() method returns true. 
 * 
 */
CtXMLHttpRequest.prototype.getStatus = function() {
    try {
        return this.reqobject.status;
    } catch (e) {
        // status is not always available in IE during 
        // processing, therefore return 200 ok until
        // it is finished. 
        return 200;
    }
}


/**
 *  Returns the http status as a string 
 * 
 * 
 */
CtXMLHttpRequest.prototype.getStatusText = function() {
    return this.reqobject.statusText;
}


/**
 *  returns the response from the request as a text string
 * 
 * 
 */
CtXMLHttpRequest.prototype.getResponseText = function() {
    return this.reqobject.responseText;
}

/**
 *  returns the response from the request as a XML document
 * 
 * 
 */
CtXMLHttpRequest.prototype.getResponseXML = function() {
    return this.reqobject.responseXML;
}

/**
 *  Aborts the current async request
 * 
 * 
 */
CtXMLHttpRequest.prototype.abort = function() {
    return this.reqobject.abort;
}


/**
 * Returns all response headers as a string
 * 
 * 
 * 
 */
CtXMLHttpRequest.prototype.getAllResponseHeaders = function() {
    return this.reqobject.getAllResponseHeaders();
}

/**
 * Returns the specified response header as a string
 * 
 * 
 * 
 */
CtXMLHttpRequest.prototype.getResponseheader = function(headerLabel) {
    return this.reqobject.getResponseheader(headerLabel);
}

/**
 * Sets a specific http request header.
 * 
 * 
 * 
 */
CtXMLHttpRequest.prototype.setRequestHeader = function(label, value) {
    return this.reqobject.setRequestHeader(label, value);
}

    
    


