////////////////////////////////////////////////////////////////////////////////
// Funções "AJAX"  v.2                                                        //
// Breno Damas M. Ribeiro                                                     //
// M.M. Informática - Desenvolvimento Web                                     //
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
// Browser
MSIE=document.all?true:false;
OPERA=(navigator.userAgent.toUpperCase().indexOf('OPERA')>=0);

////////////////////////////////////////////////////////////////////////////////
//Globais
pronto=true;
semajax='/browser_antigo.asp';

atualiza='{}reload:';
js_eval='javascript:';
html_cmd='{}innerHTML:';
HTMLCarregando='Trabalhando... ({total} tarefas em execução)';
oCarrega=null;
sCampos='hidden,text,textarea,';
UltimoFormEnviado='';

function criaLoadDiv(t,m) {
	oCarrega=AdicionaTag('div','tudo','id="divCarregaAjax"');
	if(oCarrega!=null) {
		with (oCarrega.style) {
			visibility='hidden';
			display='none';
			backgroundColor='#FFB';
			padding='1px';
			border='1px solid #DD9';
			position='absolute';
			top='20px';
			right='20px';
			zIndex='999';
		}
		oCarrega.innerHTML='Não há tarefas em execução...';
		pronto=true;
	} else if(m>0) {
		pronto=false;
		setTimeout('criaLoadDiv('+t+','+(--m)+')',t);
	} else {
		if(!confirm('Problemas ao criar elementos de inteface...\nClique OK e tente atualizar a página ou Cancelar para ver uma lista de navegadores sugeridos...'))	location.href='/browser_antigo.asp';
	}
}

function MostraCarregando(id) {
/*	if(HTMLCarregando.length==0) {
		aux='';
		for(i=(fila.length+filab.length)%100;i>=0;--i) aux+='*';
		txLoad=aux;
	} else {
		txLoad=HTMLCarregando.replace('{total}',fila.length+filab.length);
	}

	if(oCarrega==null && (id.indexOf(atualiza)!=0 && id.indexOf(js_eval)!=0)) {
		document.getElementById(id).innerHTML=txLoad;
	} else if(oCarrega!=null) {
		if(fila.length<=0) {
			with (oCarrega.style) {
				visibility='hidden';
				display='none';
			}
		} else {
			with (oCarrega.style) {
				visibility='visible';
				display='block';
			}
		}
		oCarrega.innerHTML=txLoad;
	}*/
}
//criaLoadDiv(100,100);

fila=new Array();
//filab=new Array();
UltimaTarefa=new Array(2);

function criaXMLHTTP() {var r; try {r=new XMLHttpRequest();} catch(e) {try {r=new ActiveXObject("Msxml2.XMLHTTP");} catch(e) {try {r=new ActiveXObject("Microsoft.XMLHTTP");} catch(e) {r=null;}}} return r;}
var xmlhttp=criaXMLHTTP();
if(xmlhttp==null) {
	xmlhttp = false;
	window.location.href=semajax;
} else {
}

bdEmpty=0
bdInt=2
bdLong=3
bdFloat=4
bdDouble=5
bdMoeda=6
bdData=7
bdBool=11
bdByte=16
bdTexto=202
bdMemo=203

//document.cookie='cookieteste=true; path=/';

////////////////////////////////////////////////////////////////////////////////
//Funções de primeiro plano (resultados visíveis ao usuário)
// para chamar uma nova tarefa ao concluir esta, id=atualiza+'id;url'
// terceiro parametro opcional, indica se tarefa deve ser executada em
// background, ou seja, sem exibir progresso da fila...
function EnfileraTarefa(id,url) {
	bk=false;
	if(arguments.length>2) bk=arguments[2];
	fila.push([id,url,bk]);

	if(!bk) MostraCarregando(id);

	if(fila.length==1) RequisitaDados();
}

function RequisitaDados() {
	if(xmlhttp) {
		if(fila.length>0 && pronto) {
			pronto=false;
			xmlhttp.open("GET",CacheMSIE(fila[0][1]),true);
			xmlhttp.onreadystatechange=function () {
				if (xmlhttp.readyState==4) {//alert(fila[0][0]);
					if(xmlhttp.status==200) {
						retorno=xmlhttp.responseText;
						// unescape(xmlhttp.responseText.replace(/\+/g," "));
					} else {
						retorno=xmlhttp.status+' '+xmlhttp.statusText;
					}
		
					x=fila.shift();
					UltimaTarefa=x;
					if(!x[2]) MostraCarregando(x[0]);
					cmd=new String(x[0]);
					if(cmd.indexOf(js_eval)==0) cmd=js_eval;
					else if(cmd.indexOf(atualiza)==0) cmd=atualiza;
					else cmd=html_cmd;
			//		alert(cmd+'~'+x[0]);
					switch(cmd) {
					case js_eval:
						if(xmlhttp.status==200) {
							eval(retorno);
							if(x[0].length>js_eval.length) eval(x[0].substr(js_eval.length));
						} else {
							alert(retorno);
			//				if(xmlhttp.status==122) alert(UltimaTarefa.toString());
						}
						break;
					case atualiza:
						erro=parseInt(retorno,10);
						if(!erro) {
							id=x[0].substring(atualiza.length,x[0].indexOf(";"));
							url=x[0].substr(x[0].indexOf(";")+1);
							//if(confirm('id:'+id+'\nurl:'+url+'\nx[0]:'+x[0]))
							EnfileraTarefa(id,url);
						} else {
							alert('Erro: '+erro);
						}
						break;
					default:
						var oC=document.getElementById(x[0]);
						if(oC!=null) oC.innerHTML=retorno;
					}
					pronto=true;
					if(fila.length>0) RequisitaDados();
					//else LivreB();
				}
			}
			xmlhttp.send(null);
		} else if(fila.length>0) {
			setTimeout('RequisitaDados();',100);
		}// else alert(fila.length+'>'+pronto+'Erro na execução do script!\nEste alert não deveria aparecer...\nEnvie mensagem para: web@mminformatica.com.br');
	} else	window.location.href=semajax;
}



////////////////////////////////////////////////////////////////////////////////
function AdicionaTag(tag,idpai,atr) {
	if(!(document.createElement&&document.getElementById&&document.appendChild)) {
		alert('Seu browser possui algumas restrições inconvenientes...\nSiga as instruções da página seguinte, para atualizá-lo ou migrar para outro...');
		window.location.href=semajax;
		return null;
	}
	atr+=' ';
	atr=atr.replace('\t',' ')
	while(atr.indexOf('  ')>=0) atr=atr.replace('  ',' ');
	if(MSIE && !OPERA) {
		var el=document.createElement('<'+tag+' '+atr+'>');
	} else {
		var el=document.createElement(tag);
		if(atr.length>0) {
			if(!el.setAttribute) {
				alert('Seu browser possui algumas restrições inconvenientes...\nSiga as instruções da página seguinte, para atualizá-lo ou migrar para outro...');
				window.location.href=semajax;
				return;
			}
			var ia='="', fa='" ';
			while(atr.length>0) {
				pos=atr.indexOf(ia);
				if(pos>0) {
					aa=atr.substring(0,pos);
					atr=atr.substr(pos+ia.length);
					pos=atr.indexOf(fa);
					if(pos>0) {
						vl=atr.substring(0,pos);
						atr=atr.substr(pos+fa.length);
					} else if(pos==0) {
						vl='';
						atr=atr.substr(fa.length);
					} else {
						vl=atr;
						atr='';
					}
				} else atr='';
				el.setAttribute(aa,vl);
			}
		}
	}
	var pai=document.getElementById(idpai);
	if(pai!=null)
		pai.appendChild(el);
	else el=pai;
	return el;
}

function RemovePorId(id) {
	if(!document.getElementById) {
		alert('Seu browser possui algumas restrições inconvenientes...\nSiga as instruções da página seguinte, para atualizá-lo ou migrar para outro...');
		window.location.href=semajax;
		return;
	}
	el=document.getElementById(id);
	if(el==null) return null;
	if(!(el.removeChild&&el.parentNode)) {
		alert('Seu browser possui algumas restrições inconvenientes...\nSiga as instruções da página seguinte, para atualizá-lo ou migrar para outro...');
		window.location.href=semajax;
		return;
	}
	return el.parentNode.removeChild(el);
}




////////////////////////////////////////////////////////////////////////////////
// Utilidades
function strHex(num) {
	var str=''
	while(num>0) {
		alg=num%16;
		if(alg>9) {
			alg='ABCDEF'.charAt(alg-10);
		}
		str=alg+str+'';
		num=Math.floor(num/16);
	}
	return str;
}
function URLEncode(sS) {
	var r=''
	for(var i=0;i<sS.length;++i) {
		cod=sS.charCodeAt(i);
		if(cod>160 || cod==35 || cod==38 || cod==43) {
			r+='%'+strHex(cod);
		} else {
			try {
				r+=encodeURI(sS.charAt(i));
			} catch(e) {
				try {
					r+=escape(sS.charAt(i));
				} catch(e) {
					r+=sS.charAt(i);
				}
			}
		}
	}
	return r;
}



////////////////////////////////////////////////////////////////////////////////
// Bugs do IE
function CacheMSIE(sURL) {
	if(navigator.userAgent.indexOf('MSIE')>=0) {
		if(sURL.indexOf('?')<0) {
			sURL+='?';
		} else {
			sURL+='&';
		}
		return sURL+'cid='+encodeURI(Math.random()).replace('.','');
	} else return sURL;
}



