/*
 * Licensed Materials - Property of IBM
 *
 * Copyright IBM Corporation 2008. All Rights Reserved.
 *
 * U.S. Government Users Restricted Rights - Use, duplication or
 * disclosure restricted by GSA DP Schedule Contract with IBM Corp.
 */

var DEPLOY_ON_PHP = true;
	  
new egl.egl.jsrt.ServiceRT();

if (DEPLOY_ON_PHP) {
	egl.egl.jsrt.$ServiceRT.doInvokeInternal = function( /*HttpRequest*/ request, 
	    							   /*String*/ serviceCallTypeIn,
	                                   /*function*/ callback, 
	                                   /*function*/ errCallback,                     
	                                   /*boolean*/ asynchronous) {
		var serviceCallType = serviceCallTypeIn;     //copy the value
	    var requestString = egl.egl.core.$ServiceLib.convertToJSON(request);
	    egl.egl.core.$ServiceLib.callBackResponse.originalRequest = requestString;
	    var xhr = egl.newXMLHttpRequest();
	    var beginTime = new Date().getTime();
	    var response = new egl.egl.core.HttpResponse();
	    var proxyURL = '/' + egl.contextRoot + '/' + this.eze$$proxyURL;
	    
	    if (egl.debugg) {
	        if (proxyURL.indexOf("?") == -1) {
	        	proxyURL += "?contextKey=" + egl.getContextKey();
	        }
	        else {
	        	proxyURL += "&contextKey=" + egl.getContextKey();
	        }
	    }
	    
	    xhr.onreadystatechange = function(){
	        //4 - the response is complete; you can get the server's response and use it
	        if (xhr.readyState == 4) {
	        	var eglExp = null;
	            try {                    
	            	egl.enter("Response for " + request.uri, { eze$$typename: "RUI Runtime" });
	                if (xhr.status >= 200 && xhr.status <= 299){
	                    var json;
	                    try {
	                    	egl.enter("Parse JSON ("+xhr.responseText.length+" bytes) from "+ request.uri, { eze$$typename: "RUI Runtime" });
	                    	json = egl.egl.core.$ServiceLib.convertFromJSON(xhr.responseText);
	                    }
	                    finally {
	                    	egl.leave();
	                    }
	                    if (json == null) {
	                    	json = xhr.responseText;
	                    }
	                    if (json != null) {
	                        response = json;
	                        try {
	                        	response.body = response.body.replace(/&quot;/g, '"');
	                        }
	                        catch (e) {
	           	              	response.body = xhr.responseText;
	        				}
	                        // egl.println("body="+response.body);
	                        try {
	                        	egl.enter("Handling callback for " + request.uri, { eze$$typename: "RUI Runtime" });
	                        	egl.egl.jsrt.$ServiceRT.runCallback(callback, response, request.uri, beginTime);
	                        }
	                        finally {
	                        	egl.leave();
	                        }
	                    }
	                    else {
	                    	response.status = xhr.status;
	                    	response.statusMessage = xhr.statusMessage;
	                    	eglExp = egl.createServiceInvocationException(
	                        		"CRRUI3659E",
	                        		[xhr.responseText],
	                        		egl.egl.jsrt.$ServiceRT.getExceptionSource(serviceCallType),
	                        		xhr.status,
	                        		xhr.statusMessage);
	                    }
	                }
	                else {
	                	//things failed on the proxy, need to report error to errorCallback                    	
	                    response.status = xhr.status || 404;
	                    response.statusMessage = xhr.statusText;     
	                    
	                	//var exp = null;
	                	try{
	                		eglExp = egl.egl.jsrt.$ServiceRT.createExceptionFromJsonRPCError(xhr.responseText, serviceCallType);                    		
	                	}
	                	catch(jsonError){
	                		//the xhr.responseText is either not in a json format 
	                		//or the parsed json object isn't a JSONRPCError object
	                		//error parsing JSONRPCError
	                		if(response.status == 404){
	                			eglExp = egl.createServiceInvocationException(
	                					"CRRUI3657E",
	                					[proxyURL],
	                					egl.egl.jsrt.$ServiceRT.getExceptionSource(serviceCallType),
		                				response.status,
		                				response.statusMessage,
		                				xhr.responseText);
	                		}
	                		else{	
	                			eglExp = egl.createServiceInvocationException(
		                				"CRRUI3658E", 
		                				[proxyURL, request.uri],
		                				egl.egl.jsrt.$ServiceRT.getExceptionSource(serviceCallType),
		                				response.status,
		                				response.statusMessage,
		                				xhr.responseText);
	                		}
	                	}
	                }                    
	            }
	            catch(e) {
	            	eglExp = egl.createServiceInvocationException(
	            			"CRRUI3660E "+e.message,
	            			[request.uri, e.message],
	            			egl.egl.jsrt.$ServiceRT.getExceptionSource(serviceCallType),
	            			xhr.status,
	            			xhr.statusMessage,
	            			xhr.responseText);
	            }
	            finally {
	            	egl.leave();
	            }
	            
	            if(eglExp != null)
	            	egl.egl.jsrt.$ServiceRT.runErrorCallback(errCallback, eglExp, response);
	        }
	    }
	    xhr.open( 'POST', '___proxy.php?url='+encodeURIComponent(request.uri), asynchronous );
	    xhr.setRequestHeader('Content-Length', requestString.length);
	    xhr.setRequestHeader('Content-Type', 'application/jsonrequest;charset=UTF-8');
	
	    xhr.send( requestString );
	};
}