/*
 * The web services proxy new-style
 */
function Request(){
	this.requestSeed = Math.floor(Math.random()*10000000001);
}

Request.prototype.chunkedData = ""; // This will store the chunks of data that will be sent to the server
Request.prototype.chunkedIndex = 0; // Counter
Request.prototype.requestSeed = 0; // The seed of the iframes for all the iframes of this request
Request.prototype.requestURL = ""; // URL of the requested service
Request.prototype.result;


Request.prototype.getRequestSeed = function(){
	return this.requestSeed;
}

/*
 * Prepares and chunks the data to be sent
 */
Request.prototype.prepareData = function(data){
	var encodedData = Base64.encode(data);
	var chunks = new Array();
	var chunkLen = 1000;
	var i = 0;
	while( i*chunkLen < encodedData.length){
		chunks[i] = encodedData.substring(i*chunkLen, (i+1)*chunkLen);
		i++;
	}
	return chunks;
}

/*
 * Creates the iframes and sets their src and ids
 */
Request.prototype.createIframe = function(oneId, url){
	var script = document.createElement('script');
	script.type = 'text/javascript';	
	script.src = url;

	script.id = oneId;
	try{
		document.getElementsByTagName("head")[0].appendChild(script);
	}catch(e){
		throw new Exception();
	}
}

/*
 * This function is called in order to create the next iframe
 */
Request.prototype.goOn = function(serverToken){
	
	var oneId= "wsresponse_"+this.requestSeed+"_"+this.chunkedIndex;
	
	// There are no chunks of data to be sent to the server. There is no need to use chunked data sending mechanism.
	if(this.chunkedData[this.chunkedIndex] == undefined){
		var url1 = this.requestURL;//+"?"+chunkedData[chunkedIndex];
	}else if ( this.chunkedData.length < 2){
		// There is only one chunk. There is no need to use chunked data sending mechanism.
		var url1 =  this.requestURL + "/" + this.chunkedData[this.chunkedIndex];
	}else{
		// Data should be sent in chunks to the server
		var url1 = this.requestURL+"/?m="+ this.chunkedData[this.chunkedIndex] + "&t="+ this.chunkedData.length + "&o=" + parseInt(this.chunkedIndex + 1) + "&s=" + this.requestSeed;
	}	
	
	if (serverToken != ""){		
		url1=url1 + "&r=" + serverToken;
	}
	
	this.createIframe(oneId, url1);
	this.chunkedIndex ++;
}

/*
 * makeRequest. Named after the same function in the old-style WSRequest
 *
 */
Request.prototype.makeRequest = function(url, data) {	
	this.chunkedData = this.prepareData(data);
	this.chunkedIndex = 0;
	this.requestURL = url;

	this.goOn("");
}


