// PrestoConn.js
var maxcons = 30;
var httpcons = new Array();

function conn(nome, div, url){
	this.conn = false;
	this.nome = nome;
	this.div = div;
	this.url = url;
	this.onload = undefined;
	this.oncancel = undefined;	
	
	
	this.clean = function(){
		this.conn = false;
		this.nome = '';
		this.div = '';
		this.url = '';
		this.onload = undefined;
		this.oncancel = undefined;		
		}
}

for(i=0;i<maxcons;i++){
	httpcons[i]=new conn('','','');
}

function getPrestoHttp() {
	var xmlHttp=false;
	/* v v v RM (7/Jul/2010) v v v */
	if (window.XMLHttpRequest) {
		xmlHttp = new XMLHttpRequest()
		if(xmlHttp.overrideMimeType) {
			xmlHttp.overrideMimeType('text/html; charset=iso-8859-1');
		}
	} else if (window.ActiveXObject) { 
		try {
			xmlHttp = new ActiveXObject("Msxml2.xmlHttp");
		} catch (e) {
			try {
				xmlHttp = new ActiveXObject("Microsoft.xmlHttp");
			} catch (E) {
				xmlHttp = false;
			}
		}
	}
	/* ^ ^ ^ RM ^ ^ ^ */
	return xmlHttp;
}



function createPresto(nome, url, div){
	res = false;
 	url = limpaAmp(url);
 	/* v v v RM (7/Jul/2010) v v v */
	//var indice = findPresto( '' );
	var indice = findPresto(nome, true);
	
	if(indice>=0 && indice < maxcons ){
		httpcons[indice].nome = nome;
		httpcons[indice].div = div;
		httpcons[indice].url = url;
		if( !httpcons[indice].conn ) {
			httpcons[indice].conn = getPrestoHttp();
		}
		res=true;
	}else{
		res=false;
	}
	/* ^ ^ ^ RM ^ ^ ^ */
	return res;
}

function findPresto(nome, isCreateCall) {
	var res = -1;
	var firstFree = -1;
	for(i=0; i < maxcons && (res==-1); i++){
		/*
		if( nome == '' && httpcons[i].nome == '' && httpcons[i].conn == false ){
			res = i;
		} else if( httpcons[i].nome == nome && (httpcons[i].conn && httpcons[i].conn.readyState == 0) ){
		*/
		if(isCreateCall && firstFree < 0 && httpcons[i].nome == '' && httpcons[i].conn == false){
			firstFree = i;
		} else if(httpcons[i].nome == nome){// && (httpcons[i].conn && httpcons[i].conn.readyState == 0)){
			res = i;
		}
	}
	if(isCreateCall && res < 0 && firstFree >= 0){
		res = firstFree;
	}
	return res;
}

processUpdateResponse = function(myPresto, i){
	if(myPresto.conn.readyState == 4) {
		var content = document.getElementById(myPresto.div);
		if( content != undefined ) {
			var response;
			var shortName = getShortName( myPresto.div );
			if( myPresto.conn.status == 200 ) {
				response = myPresto.conn.responseText;
			
				/* Adiciona o conteúdo HTML recebido */
				content.innerHTML = response;
				/*
				debugPresto = document.getElementById(shortName+'_debugPresto');
				if( debugPresto != undefined ) {
					debugPresto.innerHTML = debugPresto.innerHTML +" <br/><span>"+ i +", " + myPresto.div +", "+ myPresto.onload +"<span>";
				} else {
					content.innerHTML ="<a href=\"#\" id='"+ shortName +"_debugPresto' class='debugPresto'><span>"
								+ i +", " + myPresto.div +"</span></a>" + content.innerHTML;
				}
				*/
			
				if( window.parent.resizeCaller ){
					window.parent.resizeCaller();
				}
				
				/* Adiciona o conteúdo JS recebido ao cabeçalho da página, executando-o */
				var head = document.getElementsByTagName('head').item(0);
				
				var scripts = content.getElementsByTagName('script');
				if( scripts != undefined ) {
					for( j = 0 ; j < scripts.length ; j++ ){
						s = scripts[j].innerHTML;
						if( s.length >0 ){
							script = document.createElement('script');
							script.text = s;  
							script.type = 'text/javascript';
							script.defer = true;
							void(head.appendChild(script));
						}
					}
				}
				
				if(myPresto.onload != undefined) {
					try {
						eval(myPresto.onload);
					} catch(e){}
				}
			}
			else if( myPresto.conn.status == 0 ) {
				response = "<div id=\""+ shortName +"_infoPresto\" class=\"infoPresto\" onclick=\"javascript: this.parentNode.removeChild(this);\">"
						+ "<span class=\"error\">Chamada ajax cancelada (" + myPresto.conn.status + ": " + myPresto.conn.statusText + ", " + myPresto.nome + ").</span>"
						+ "</div>";
						
				var infoPresto = document.getElementById( shortName+'_infoPresto');
				if( infoPresto != undefined ) {
					infoPresto.parentNode.removeChild(infoPresto);
				}
				content.innerHTML = response + content.innerHTML;

				if(myPresto.oncancel != undefined){
					try {
						eval(myPresto.oncancel);
					} catch(e){}
				}
			} else {
				response = "<div id=\""+ shortName +"_infoPresto\" class=\"infoPresto\" onclick=\"javascript: this.parentNode.removeChild(this);\">"
						+ "<span class=\"error\">Ocorreu uma falha de comunicação com o servidor (" + myPresto.conn.status + ": " + myPresto.conn.statusText + ", " + myPresto.nome + ").</span>"
						+ "</div>";
						
				var infoPresto = document.getElementById( shortName+'_infoPresto');
				if( infoPresto != undefined ) {
					infoPresto.parentNode.removeChild(infoPresto);
				}
				content.innerHTML = response + content.innerHTML;
				
				if(myPresto.onCallError != undefined) {
					try {
						eval(myPresto.onCallError+'("'+ myPresto.conn.status +'")');
					} catch(e){}
				}
			}
		}
		
		myPresto.clean();
	}
}
/* ^ ^ ^ RM ^ ^ ^ */

function setPrestoOnload(nome, onload) {
	var i = findPresto( nome );
	//alert(i+"-"+onload+" - "+ onload.substr(0,4));
	if( i >= 0 && onload.substr(0,4) != 'aaa(' ){
		httpcons[i].onload = onload;
	}
}

function setPrestoOnCancel(nome, oncancel) {
	var i = findPresto( nome );
	if(i>= 0){
		httpcons[i].oncancel = oncancel;
	}
}

function setPrestoOnCallError(nome, onCallError) {
	var i = findPresto(nome);
	if(i >= 0){
		httpcons[i].onCallError = onCallError;
	}
}



function callServer( nome, id,postparam) {
	var i = findPresto( nome );
	if( i >= 0 ){
		try{
			var container = document.getElementById(httpcons[i].div)
			var shortName = getShortName(httpcons[i].div);
			var infoPresto = document.getElementById(shortName + '_infoPresto');
			if(infoPresto != undefined){
				infoPresto.parentNode.removeChild(infoPresto);
			}
			var infoMsg = "<div name=\"prestodivloader\" id=\""+ shortName +"_infoPresto\" class=\"infoPresto\">"
						+ "<div class=\"container mynetLinhaSelBold\"><span class=\"loading\">A obter dados...</span></div></div>";
			container.innerHTML = infoMsg + container.innerHTML;
						
		}catch(e){}
		
		if( typeof id != 'undefined' ){
			httpcons[i].url += id;
		}
		var url = httpcons[i].url;
		/* v v v RM (7/Jul/2010) v v v */
		url += "&token=" + (new Date().getTime());
		/* ^ ^ ^ RM ^ ^ ^ */
		
		var submitType="";
		if (postparam==null){
			submitType="GET";
		}else{
			submitType="POST";
		}
		httpcons[i].conn.open(submitType, url, true);
		/* v v v RM (7/Jul/2010) v v v */
		httpcons[i].conn.onreadystatechange = function(){ processUpdateResponse(httpcons[i], i) };
		//httpcons[i].conn.onabort = function(){ processAbort(httpcons[i], i) };
		/* ^ ^ ^ RM ^ ^ ^ */
		if (postparam==null){
			httpcons[i].conn.send(null);
		}else{
			httpcons[i].conn.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			httpcons[i].conn.setRequestHeader("Content-length", postparam.length);
////			httpcons[i].conn.setRequestHeader("Connection", "close");	//FIX: Linha comentada. Corrige o erro Status 12030
			httpcons[i].conn.send(postparam);					
		}

		
	}
}

getShortName = function( name ) {
	var shortName = name;
	if( name.lastIndexOf('_') > 0 ) {
		shortName = name.substr( 0, name.lastIndexOf('_') );
	}
	return shortName
}

function cancelPresto(nome){
	var i = findPresto( nome );
	if( i >= 0 ){
		try{
			myPresto=httpcons[i];
			httpcons[i].conn.abort();
		}catch(e){}
	}else{
		alert("Cancelamento ajax não executado. Chamada não encontrada.");
	}
}
/*Verifica se existem chamadas ativas*/
function existemChamadasActivas(){
	res=false;
	for(i=0; i < maxcons; i++){
		myPresto=httpcons[i];
		if (myPresto!=null){
			if (myPresto.conn){
				if (myPresto.conn.readyState==1 || myPresto.conn.readyState==2 || myPresto.conn.readyState==3){
					res=true;
					break;					
				}
			}
		}
	}
	return res;
}
