document.write("<script src='"+URL_CORE_JS+"json.js'></script>");
var arrObject=new Array();var count_ajax_erros=0;
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 = object.responseText;
		if(!(text.search(/ajaxHtmlContent/i)>0)){
			var arrReturn = JSON.parse(text);
			if(arrReturn['ajaxError']){
				if(arrReturn['ajaxError']['msg'])
					alert(arrReturn['ajaxError']['msg']);
				if(arrReturn['ajaxError']['jsFunction'])
					eval(arrReturn['ajaxError']['jsFunction']);
				
				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 false;
			}
		}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);
					if(retorno != false){						
						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);
			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 (){
				
				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.');
						}
					}

					var retorno = getObjectResponseArray(cont);
					if(retorno != false){
						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 setEntidadeHTML(tipconversao, texto){
    var eHTML1 = new Array("&Aacute;","&Eacute;","&Iacute;","&Oacute;","&Uacute;","&Agrave;","&Egrave;","&Igrave;","&Ograve;","&Ugrave;","&Atilde;","&Otilde;","&Acirc;","&Ecirc;","&Icirc;","&Ocirc;","&Ucirc;","&aacute;","&eacute;","&iacute;","&oacute;","&uacute;","&agrave;","&egrave;","&igrave;","&ograve;","&ugrave;","&atilde;","&otilde;","&acirc;","&ecirc;","&icirc;","&ocirc;","&ucirc;","&ccedil;","&Ccedil;","&amp;","&nbsp;","&lt;","&gt;","&deg;","&ordf;");
    var eHTML2 = new Array("Á","É","Í","Ó","Ú","À","È","Ì","Ò","Ù","Ã","Õ","Â","Ê","Î","Ô","Û","á","é","í","ó","ú","à","è","ì","ò","ù","ã","õ","â","ê","î","ô","û","ç","Ç","&","&nbsp;","<",">","º","ª");

    for(i=0; i< eHTML1.length; i++){
        switch(tipconversao){
            case 1:
                charFind = eHTML1[i];
                charReplace = eHTML2[i];
                break;
            case 2:
                charFind = eHTML2[i];
                charReplace = eHTML1[i];
                break;
            default:
                alert('Você não definiu o tipo da conversão na função setEntidadeHTML.');
                return false;
                break;
        }
        texto = texto.replace(eval('/'+charFind+'/g'), charReplace);
    }

    return texto;
}

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 arrayToOptions(array , objSelect , arrayFieldNameToOptionValue , arrayFieldNameToOptionText , selectedValue){
	objSelect.options.length = 1;
	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 arrayToOptionsZero(array , objSelect , arrayFieldNameToOptionValue , arrayFieldNameToOptionText , selectedValue){
	objSelect.options.length = 0;
	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_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();
	setTimeout("fnAuxLoading()",1000);
}
fnAuxLoading();
