/* Methods for invoking server side calls.
 */
if (typeof calhoun == "undefined") calhoun = {}

calhoun.ajax={};

calhoun.ajax.indicatorId = null
calhoun.ajax.indicatorCount = 0

/**
 *  Gives the ajax module the id of an element which should be made visible
 *  while ajax calls are processing.
 */
calhoun.ajax.initializeIndicator = function(indicatorId) {
   calhoun.ajax.indicatorId = indicatorId
   YAHOO.util.Dom.setStyle(indicatorId, 'display', 'none');
}

calhoun.ajax.showIndicator = function() {
   if (calhoun.ajax.indicatorId == null) return;
   var timeoutCallback = function() {
      if (calhoun.ajax.indicatorCount > 0) {
	   YAHOO.util.Dom.setStyle(calhoun.ajax.indicatorId, 'display', 'block');
      }
   }
   setTimeout(timeoutCallback,500)
   calhoun.ajax.indicatorCount++
}

calhoun.ajax.hideIndicator = function() {
   if (calhoun.ajax.indicatorId == null) return;
   calhoun.ajax.indicatorCount--
   if (calhoun.ajax.indicatorCount == 0) {
      YAHOO.util.Dom.setStyle(calhoun.ajax.indicatorId, 'display', 'none');
   }
}


calhoun.ajax.generateUrl = function(url, params, type) {
    return calhoun.ajax._generateUrl(url, params, type).url;
}

calhoun.ajax._generateUrl = function(url, params, type) {
    if (type == null) type = "GET";
	var sb = [url];
	var data = [];
	for(var i=0;i<params.length;i++) {
		var p = params[i];
		if (p == null) {
			data.push("&sp=X");
		} else {
			data.push("&sp=S");
			data.push(encodeURIComponent(p));
		}
	}
	var resp = new Object();
	resp.url = url;
	resp.data = data.join("");
	if (type == "GET") {
	    data.unshift(url);
	    resp.url = data.join("");
	}
	return resp;
}

calhoun.ajax.invokeCallable = function (contFn, url, params, context, type) {
    if (type == null) type = "GET";
    var urlData = calhoun.ajax._generateUrl(url, params, type);
    var fullUrl = urlData.url;
	
	// add an extra parameter which is unique each time 
	// to prevent caching in IE
	fullUrl += "&timestamp="+(new Date().getTime());

    YAHOO.log("fullUrl = " + fullUrl)

    var notifyObj = {
        success: function(resp) {
           calhoun.ajax.hideIndicator()
            var x;
            try {
                x = eval("("+resp.responseText+")");
            } catch (e) {
               alert("Could not deserialize result: "+e.message);
                contFn(null);
                return;
            }
            
            // now call with the deserialized object
            try {
                if (context != null)
                    context[contFn](x);
                else
                    contFn(x);
            } catch (e) {
               alert("exception handling result: "+e.message);
            }
        },
       failure: function() {
          calhoun.ajax.hideIndicator()
            try {
                if (context != null)
                    context[contFn](null);
                else
                    contFn(null);
            } catch (e) {
               alert("exception handling failure: "+e.message);
            }
        }
    }
    
   calhoun.ajax.showIndicator()
   if (type == "GET") return YAHOO.util.Connect.asyncRequest("GET", fullUrl, notifyObj, null);
   else return YAHOO.util.Connect.asyncRequest("POST", fullUrl, notifyObj, urlData.data);
}

calhoun.ajax.doQuery = function(oCallbackFn, sQuery, oParent) {
    var isXML = (this.responseType == YAHOO.widget.DS_XHR.TYPE_XML);
    var sUri = this.scriptURI+"&"+this.scriptQueryParam+"=S"+sQuery;
    if(this.scriptQueryAppend.length > 0) {
        sUri += "&" + this.scriptQueryAppend;
    }
    var oResponse = null;
    var oSelf = this;

    /*
     * Sets up ajax request callback
     *
     * @param {object} oReq          HTTPXMLRequest object
     * @private
     */
    var responseSuccess = function(oResp) {
        // Response ID does not match last made request ID.
        if(!oSelf._oConn || (oResp.tId != oSelf._oConn.tId)) {
            oSelf.dataErrorEvent.fire(oSelf, oParent, sQuery, YAHOO.widget.DataSource.ERROR_DATANULL);
            return;
        }

        if(!isXML) {
            oResp = oResp.responseText;
        }
        else {
            oResp = oResp.responseXML;
        }
        if(oResp === null) {
            oSelf.dataErrorEvent.fire(oSelf, oParent, sQuery, YAHOO.widget.DataSource.ERROR_DATANULL);
            return;
        }

        var aResults = oSelf.parseResponse(sQuery, oResp, oParent);
        var resultObj = {};
        resultObj.query = decodeURIComponent(sQuery);
        resultObj.results = aResults;
        if(aResults === null) {
            oSelf.dataErrorEvent.fire(oSelf, oParent, sQuery, YAHOO.widget.DataSource.ERROR_DATAPARSE);
            aResults = [];
        }
        else {
            oSelf.getResultsEvent.fire(oSelf, oParent, sQuery, aResults);
            oSelf._addCacheElem(resultObj);
        }
        oCallbackFn(sQuery, aResults, oParent);
    };

    var responseFailure = function(oResp) {
        oSelf.dataErrorEvent.fire(oSelf, oParent, sQuery, YAHOO.widget.DS_XHR.ERROR_DATAXHR);
        return;
    };
			
	var oCallback = {
        success:responseSuccess,
        failure:responseFailure
    };
			
    if(!isNaN(this.connTimeout) && this.connTimeout > 0) {
        oCallback.timeout = this.connTimeout;
    }

    if(this._oConn) {
        this.connMgr.abort(this._oConn);
    }

    oSelf._oConn = this.connMgr.asyncRequest("GET", sUri, oCallback, null);
};


