
/**
INCLUINDO A BIBLIOTECA Json
**/
document.write("<script src='"+URL_CORE_JS+"json.js'></script>");

/**
INCLUINDO A BIBLIOTECA PROTOTYPE
**/
document.write("<script src='"+URL_CORE_JS+"prototype.js'></script>");


<!-- FIM FUNCÕES DE AJAX-->
var arrObject = new Array();
var count_ajax_erros = 0; //erros de não existir páginas de requisição de ajax
function createObjRequest(x){
 try {
	arrObject[x] = new ActiveXObject("Microsoft.XMLHTTP");
  }catch(e) {
	 try {
	   arrObject[x]  = new ActiveXObject("Msxml2.XMLHTTP");
	 }
	 catch(ex) {
		try {
		   arrObject[x]  = new XMLHttpRequest();
		}
		catch(exc) {
		   alert("Esse browser não tem recursos para uso de Ajax");
		   arrObject[x] = null;
		}
	 }
  }
}
function getEmptyObjectKey(){
	var key = false;
	for(x=0;x<arrObject.length;x++){
		if(arrObject[x].readyState == 0){
			key = x;
			break;
		}else if(arrObject[x].readyState == 4){
			createObjRequest(x);
			key = x
			break;
		}else{
			key = false;
		}
	}

	if(key === false){
		createObjRequest(arrObject.length);
		return arrObject.length-1;
	}else{
		return key;
	}
}
function getObjectResponseText(arrObjectsKey){
	object = arrObject[arrObjectsKey];
	if(object.readyState == 4 && object.responseText != "" && object.responseText.length > 0 && object.status == 200){
		var text = object.responseText;
		return text;
	}else{
		return '';
	}
}
function getObjectResponseArray(arrObjectsKey){
	
	object = arrObject[arrObjectsKey];
	if(object.readyState == 4 && object.responseText != ' ' && object.responseText != '' && object.status == 200){
		var text_retorno = object.responseText;
		if(!(text_retorno.search(/ajaxHtmlContent/i)>0)){
			var arrReturn = JSON.parse(str_replace('/*CachedResult*/','',text_retorno));
			
			if(arrReturn['ajaxError']){
				alert(arrReturn['ajaxError']['msg']);
				return false;
			}
			return arrReturn;
		}
	}else{
		return false;
	}
}

function getObjectResponseHtml(arrObjectsKey){
	object = arrObject[arrObjectsKey];
	if(object.readyState == 4 && object.responseText != ' ' && object.responseText != '' && object.status == 200){
		texto = object.responseText;
		
		if(!(texto.search(/ajaxHtmlContent/)>0)){
			if(arr = getObjectResponseArray(arrObjectsKey))
				return arr;
			else
				return '';
		}else{
			var arrReturn = texto;
		}
		return arrReturn;

	}else{
		return false;
	}
}

function fnDebugAjax(){

	var strr = '<b>Quantidade de objetos: '+arrObject.length+'<br><br>';

	for(x=0;x<arrObject.length;x++){
		if(arrObject[x].readyState == 1 || arrObject[x].readyState == 2 || arrObject[x].readyState == 3){
			strStatus="<font color='red'>Ocupado</font>";
		//}else if (object.status != 200){
			//strStatus="<font color='red'>ERRO com o arquivo de servidor</font>";
		}else{
			strStatus="<font color='green'>Disponível</font>";
		}
		strr += '<b>'+(x+1)+'-<b>' +strStatus +"<br>";
	}

	$('divDebugObjetos').innerHTML = strr;
	t=setTimeout("fnDebugAjax()",100)

}


function fnAjaxSendHtml(arquivo_php,param_php,func_retorno_js,param_js){

	var cont = getEmptyObjectKey();
	if(obj_aj = arrObject[cont]){
		if(obj_aj && (obj_aj.readyState == 0 || obj_aj.readyState == 0)) {
			DisplayLoading();
			obj_aj.open("POST", URL_ACTION + arquivo_php, true);
			obj_aj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=iso-8859-1");

			obj_aj.onreadystatechange = function (){
				DisplayLoading();
				if(arrObject[cont].readyState == 4){
					if(arrObject[cont].status != 200){
						if(count_ajax_erros < 50){
							count_ajax_erros++;
							fnAjaxSendHtml(arquivo_php,param_php,func_retorno_js,param_js);
						}else{
							count_ajax_erros++;
							alert('Problemas com o arquivo no servidor , favor tente novamente dentro de alguns minutos.');
						}
					}					
					var retorno = getObjectResponseHtml(cont);

					eval(func_retorno_js+"(retorno"+param_js+")");
				}
			}
			obj_aj.send('&ajax=1'+param_php);
		}
	}
}

function fnAjaxSend(arquivo_php,param_php,func_retorno_js,param_js){
	var cont = getEmptyObjectKey();
	if(obj_aj = arrObject[cont]){
		if(obj_aj && (obj_aj.readyState == 0 || obj_aj.readyState == 0)) {
			DisplayLoading(true);
			
			if (arquivo_php.substr(0, 4) != 'http') {
				obj_aj.open("POST", URL_ACTION + arquivo_php, true);
			} else {
				obj_aj.open("POST", arquivo_php, true);
			}
			
			obj_aj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=iso-8859-1");
			obj_aj.onreadystatechange = function (){

				if(arrObject[cont].readyState == 4){
					if(arrObject[cont].status != 200){
						if(count_ajax_erros < 50){
							count_ajax_erros++;
							fnAjaxSend(arquivo_php,param_php,func_retorno_js,param_js);
						}else{
							count_ajax_erros++;
							alert('Problemas com o arquivo no servidor , favor tente novamente dentro de alguns minutos.');
						}
					}else{
						var retorno = getObjectResponseArray(cont);
						
						eval(func_retorno_js+"(retorno"+param_js+")");
					}
					
					DisplayLoading(false);
					
				}
			}
			obj_aj.send('&ajax=1'+param_php);
		}
	}
}

function getError(retorno){
	if(retorno && retorno.length && retorno['ajaxError']){
		alert(retorno['ajaxError']['msg']);
	}
}

function url_decode(str) {
	if(str !== false && str!= "" && str){
		var n, strCode, strDecode = "";
		str = str.replace(/\+/g," ");
		for (n = 0; n < str.length; n++) {
			if (str.charAt(n) == "%") {
				strCode = str.charAt(n + 1) + str.charAt(n + 2);
				strDecode += String.fromCharCode(parseInt(strCode, 16));
				n += 2;
			} else {
				strDecode += str.charAt(n);
			}
		}
		return strDecode;
	}else{
		return "";
	}
}
function setScriptAjax(texto, obj){
	var ini, pos_src, fim, codigo;
	var objScript = null;
	ini = texto.indexOf("<script", 0)
	while (ini!=-1){
		var objScript = document.createElement("script");
		//Busca se tem algum src a partir do inicio do script
		pos_src = texto.indexOf(" src", ini)
		ini = texto.indexOf(">", ini) + 1;

		//Verifica se este e um bloco de script ou include para um arquivo de scripts
		if (pos_src < ini && pos_src >=0){//Se encontrou um "src" dentro da tag script, esta e um include de um arquivo script
			//Marca como sendo o inicio do nome do arquivo para depois do src
			ini = pos_src + 4;
			//Procura pelo ponto do nome da extencao do arquivo e marca para depois dele
			fim = texto.indexOf(".", ini)+4;
			//Pega o nome do arquivo
			codigo = texto.substring(ini,fim);
			//Elimina do nome do arquivo os caracteres que possam ter sido pegos por engano
			codigo = codigo.replace("=","").replace(" ","").replace("\"","").replace("\"","").replace("\"","").replace("\"","").replace(">","");
			// Adiciona o arquivo de script ao objeto que sera adicionado ao documento
			objScript.src = codigo;
		}else{//Se nao encontrou um "src" dentro da tag script, esta e um bloco de codigo script
			// Procura o final do script
			fim = texto.indexOf("</script>", ini);
			// Extrai apenas o script
			codigo = texto.substring(ini,fim);
			// Adiciona o bloco de script ao objeto que sera adicionado ao documento
			objScript.text = codigo;
		}
		//Adiciona o script ao documento
		obj.appendChild(objScript);
		// Procura a proxima tag de <script
		ini = texto.indexOf("<script", fim);

		//Limpa o objeto de script
		objScript = null;
	}
}
function url_encode(str) {
    var hex_chars = "0123456789ABCDEF";
    var noEncode = /^([a-zA-Z0-9\_\-\.])$/;
    var n, strCode, hex1, hex2, strEncode = "";

    for(n = 0; n < str.length; n++) {
        if (noEncode.test(str.charAt(n))) {
            strEncode += str.charAt(n);
        } else {
            strCode = str.charCodeAt(n);
            hex1 = hex_chars.charAt(Math.floor(strCode / 16));
            hex2 = hex_chars.charAt(strCode % 16);
            strEncode += "%" + (hex1 + hex2);
        }
    }
    return strEncode;
}
function zeraOptions(objSelect){
	objSelect.options.length = 1;

	//objSelect.options[0]= new Option('-- Selecione --', '');
	objSelect.focus();
}
function carregandoImg(idImg , mostra){
	if(mostra == 1){
		$(idImg).style.visibility = 'visible';
	}else{
		$(idImg).style.visibility = 'hidden';
	}
}
function carregandoOption(objSelect){
	objSelect.options.length = 0;
	try{
		LANG_carregando = LANG_carregando


	}catch(e){
			alert('Atenção , você deve exportar a variável LANG_carregando no tpl atual.\nEx: \n<script>LANG_carregando = \'{#carregando#}\'</script>');
		LANG_carregando = ''
	}
	objSelect.options[0]= new Option(LANG_carregando+'...', '');
}
function arrayToOptions(array , objSelect , arrayFieldNameToOptionValue , arrayFieldNameToOptionText , selectedValue){
	objSelect.options.length = 1;
	
	if(typeof(array) != 'undefined') {
		for(var x = 0 ; x < array.length; x++){
				eval('objSelect.options[x+1]= new Option(array[x].' + arrayFieldNameToOptionText + ', array[x].' + arrayFieldNameToOptionValue +')');
				if(selectedValue && objSelect.options[x+1].value == selectedValue){
					objSelect.options[x+1].selected = true;
				}

		}
	}
	//objSelect.focus();
}

function arrayToOptionsByKey(array_opcoes , objSelect , selectedValue){
	
	objSelect.options.length = 1;
	if(typeof(array_opcoes) != 'undefined') {
		var y = 0;
		
		array_opcoes.foreach(function (values , key){
				y++;
				objSelect.options[y] = new Option( values , key );
				if(selectedValue && objSelect.options[y].value == selectedValue){
					objSelect.options[y].selected = true;
				}
		});
	}
	//objSelect.focus();
}

function arrayToOptionsZero(array , objSelect , arrayFieldNameToOptionValue , arrayFieldNameToOptionText , selectedValue){
	objSelect.options.length = 0;

	if(typeof(array) != 'undefined') {
		for(var x = 0 ; x < array.length; x++){
				eval('objSelect.options[x]= new Option(array[x].' + arrayFieldNameToOptionText + ', array[x].' + arrayFieldNameToOptionValue +')');
				if(selectedValue && objSelect.options[x].value == selectedValue){
					objSelect.options[x].selected = true;
				}

		}
	}
	//objSelect.focus();
}

function DisplayLoading(){
	var bool = false;
	for(x=0;x<arrObject.length;x++){
		if(arrObject[x].readyState == 1 || arrObject[x].readyState == 2 || arrObject[x].readyState == 3){
			bool = true;
		}
	}
	if(bool){
		if($('DivDefaultLoading')){
		}else{
			var divblock=document.createElement("div")
			divblock.setAttribute("id", "DivDefaultLoading")
			divblock.innerHTML = '<div class="loading-indicator"><img src="'+URL_CORE_IMG+'loading.gif" style="width:16px;height:16px;" align="absmiddle">&#160;Carregando...</div> </div>';
			$('spnTudo').appendChild(divblock);

		}
	}else{
		try{
			$('spnTudo').removeChild($('DivDefaultLoading'));
		}catch(e){}
	}
}

function fnAuxLoading(){
	DisplayLoading();
	t=setTimeout("fnAuxLoading()",1000);
}
fnAuxLoading();
<!-- FIM RETORNO DE AJAX -->


