/*
Copyright (c) 2006 Author
Author: Anil Sharma for the book "Real-World AJAX: Secrets of the Masters"

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions
of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

/**
*
*
*  Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
*  file except in compliance with the License. You may obtain a copy of the License at
*
*         http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software distributed under the
*  License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
*  either express or implied. See the License for the specific language governing permissions
*  and limitations under the License.
**/


function AjaxEngine() {
   
   this.currentRequest = null;
   this.nextRequest = new Array();
   this.timeoutHandler = null;
  
}

AjaxEngine.prototype.sendRequest = function(currentRequest, callback) {
    var queryString = "";
    queryString = this._createQueryString(currentRequest);
    new Ajax.Request(currentRequest.requestURL,
    this._requestOptions(queryString, currentRequest.getXMLDoc(), callback));
}


AjaxEngine.prototype.handleTimedOut = function() {
    
    // request timed out
    if (this.currentRequest != null) {
        this.currentRequest.requestTimedOut(this.currentRequest);
        this.currentRequest = null;
    }
    this.processNextRequest();
    
}

AjaxEngine.prototype.processRequest = function(dsRequest) {
    if (this.currentRequest != null) {
        this.nextRequest.push(dsRequest);
        return;
    }
    this.currentRequest = dsRequest;
    var self = this;
    
    
    self.onreadystatechange = function(response) {
        self.oncomplete(response);
    }
    
    this.timeoutHandler = setTimeout( this.handleTimedOut.bind(this), 10000 );
    ajaxEngine.sendRequest(this.currentRequest, self.onreadystatechange);
    
}

AjaxEngine.prototype.processNextRequest = function() {
    if (this.nextRequest.length != 0) {
        
        this.currentRequest = this.nextRequest.shift();
        var self = this;
        
        self.onreadystatechange = function(response) {
        self.oncomplete(response);
        }
        this.timeoutHandler = setTimeout( this.handleTimedOut.bind(this), 10000 );
        ajaxEngine.sendRequest(this.currentRequest, self.onreadystatechange);
        
    }
}

AjaxEngine.prototype.oncomplete = function(response) {
    try {
        clearTimeout( this.timeoutHandler );
        var request = this.currentRequest;
        
        if (response.status != 200) {
        if (request.requestFailed) {
            request.requestFailed(request, response);
        }
        return;
        }
        
        
        if (request.requestCompleted) {
        request.requestCompleted(response);
        }
        
        this.currentRequest = null;
        
    }
    catch (ex) {
        alert("Error in processing Ajax Result\n" + ex.name + " - " + ex.message);
    }
    finally {
        this.currentRequest = null;
    }
    
    this.processNextRequest();
    
},

AjaxEngine.prototype._requestOptions = function(queryString, xmlDoc, callback) {
    var self = this;
    
    var requestHeaders = ['X-RWA-Version', '1.0' ];
    var sendMethod = "post"
    if ( !xmlDoc )
        sendMethod = "get";
    
    return { requestHeaders: requestHeaders,
        parameters:     queryString,
        postBody:       xmlDoc,
        method:         sendMethod,
        onComplete:     callback,
    asynchronous: true };
    
}

AjaxEngine.prototype._createQueryString = function( currentRequest ) {
    
    var queries = currentRequest.queries;
    var queryString = ""
    if (queries && queries.length > 0) {
        for ( var i = 0 ; i < queries.length ; i++ ) {
        if ( i > 0 ) {
            queryString += "&";
        }
        var q = queries[i];
        
        if ( q.name != undefined && q.value != undefined ) {
            queryString += q.name +  "=" + escape(q.value);
        }
        }
    }
    
    s = currentRequest.getServiceInvokeXML();
    if (s != null) {
        if (queryString != "") {
        queryString += "&";
        }
        queryString += "service_spec=" + s;
    }
    
    
    return queryString;
}


function DataRequest(requestURL, requestCompleted, requestFailed,
   requestTimedOut, xmlDoc) {
   
   this.requestURL = requestURL;
   this.requestCompleted = requestCompleted;
   this.requestFailed = requestFailed;
   this.xmlDoc = xmlDoc;
   if (requestTimedOut) {
      this.requestTimedOut = requestTimedOut;
      } else {
      this.requestTimedOut = this._requestTimedOut;
   }
   this.queries = new Array();
   this.serviceParameters = new Array();
}

DataRequest.prototype.addQuery = function(name, value) {
    if (name && value) {
        var q = new Object();
        q.name = name;
        q.value = value;
        this.queries.push(q);
    }
}

DataRequest.prototype.setServiceSpec = function(serviceName, methodName) {
    this.serviceName = serviceName;
    this.methodName = methodName;
}

DataRequest.prototype.addParameter = function(name, value) {
    if (name && value) {
        var p = new Object();
        p.name = name;
        p.value = value;
        this.serviceParameters.push(p);
    }
},

DataRequest.prototype.getServiceInvokeXML = function() {
    var s = null;
    if (this.serviceName && this.methodName) {
        s = "<service name=\"" + this.serviceName + "\"><method name=\"" + this.methodName + "\">";
        for (var i=0; i<this.serviceParameters.length; i++) {
        var p = this.serviceParameters[i];
        s += "<parameter name=\"" + p.name + "\"" + " value=\"" + p.value + "\"/>"
        }
        s += "</method></service>";
    }
    return s;
}

DataRequest.prototype.getXMLDoc = function() {
    return this.xmlDoc;
},

DataRequest.prototype._requestTimedOut = function(request) {
    showError("Request timed out, url: " + this.requestURL);
}

var ajaxEngine = new AjaxEngine();
