var xmlhttp = null;
// Conexão via XmlHttp
try {
    xmlhttp = new XMLHttpRequest();
} catch(e) {
    try {
	xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(ee) {
	try {
	    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	} catch(eee) {
	    xmlhttp = false;
	}
    }
}
	
function mostraConteudo(url, div, msgAguarde, msgErro) {
    // Seleciona objeto
    obj_div = document.getElementById(div);
    // Verifica se existe xmlhttp
    if (xmlhttp) {
	if(xmlhttp.readyState != 1){
	    xmlhttp.open("GET", url, true);
	    xmlhttp.onreadystatechange = function() {
		// Verifica estado da requisição
		if (xmlhttp.readyState == 1) {
		    obj_div.innerHTML = msgAguarde;
		} else if (xmlhttp.readyState == 4) {
		    // Verifica status da requisição
		    if (xmlhttp.status == 200) {
			obj_div.innerHTML = xmlhttp.responseText;
		    } else {
			obj_div.innerHTML = msgErro;
		    }
		}
	    }
	}
    }
    xmlhttp.send(null);
}

/**
* Função utilizada para popular select
* Os Dados devem ser retornados em formato JSON
* @var url Url completa do script contendo dados a serem populados
* @id_select Nome do identificar do select a ser populado
* @msgAguarde mensagem de aguarde
* @msgErro mensagem de erro caso ocorra algum
* @msgEscolha nome do primeiro item (sem valor) geralmente "Escolha..."
*/
function formSelect(url, id_select, msgAguarde, msgErro, msgEscolha) {
	// Seleciona objeto
	obj_select = document.getElementById(id_select);
   	// Verifica se existe xmlhttp
   	if (xmlhttp) {
		xmlhttp.open("GET", url, true);
		xmlhttp.onreadystatechange = function() {
		   	// Verifica estado da requisição
		    if (xmlhttp.readyState == 1) {
		    	obj_select.options[0] = new Option(msgAguarde, "");
		    } else if (xmlhttp.readyState == 4) {
		    	// Verifica status da requisição
				if (xmlhttp.status == 200) {
					while (obj_select.options.length>0) obj_select.options[0] = null;
		    		obj_select.options[0] = new Option(msgEscolha, "");
		    		// Transforma resultado JSON em Javascript
		            var _resultados = eval(xmlhttp.responseText);
		            // Popula o select com a lista de fóruns obtidos
		            for (var i=0; i<_resultados.length; i++) {
		                //_resultados[i] = unescape(_resultados[i]);
		                obj_select.options[obj_select.options.length] = new Option(unescape(_resultados[i+1].replace(/\+/g, " ")),unescape(_resultados[i].replace(/\+/g, " ")));
		                i++;
		            }
				} else {
					obj_select.options[0] = new Option(msgErro, "");
				}
			}
		}
   	}
   	xmlhttp.send(null);
}

function abrePopup(url,titulo,largura,altura,scrollbars){
    window.open(url,titulo,'toolbar=0,location=0,status=0,menubar=0,scrollbars='+scrollbars+',width='+largura+',height='+altura+',resizable=0');
}

function mostraDivBlock(divId){
    objDiv = document.getElementById(divId).style;
    objDiv.display = 'block';
}

function escondeDiv(divId){
    objDiv = document.getElementById(divId).style;
    objDiv.display = 'none';
}

function getRefToDiv(divID,oDoc) {
    if( !oDoc ) {oDoc = document;}
    if( document.layers ) {
	if( oDoc.layers[divID] ) {
	    return oDoc.layers[divID];
	}
	//repeatedly run through all child layers
	for( var x = 0, y; !y && x < oDoc.layers.length; x++ ) {
	    //on success, return that layer, else return nothing
	    y = getRefToDiv(divID,oDoc.layers[x].document);
	}
	return y;
    }
    if( document.getElementById ) {
	return document.getElementById(divID);
    }
    if( document.all ) {
	return document.all[divID];
    }
    return false;
}


function escondelayer(layer) {
    myReference = getRefToDiv(layer);
    if (myReference.style) //DOM & proprietary DOM
	myReference.style.visibility = 'hidden';
    else //Netscape
	myReference.visibility = 'hide';
}

function exibelayer(layer) {
    myReference = getRefToDiv(layer);
    if (myReference.style) //DOM & proprietary DOM
	myReference.style.visibility = 'visible';
    else //Netscape
	myReference.visibility = 'show';
}

String.prototype.replaceAll = function(de, para){
    var str = this;
    var pos = str.indexOf(de);
    while (pos > -1){
		str = str.replace(de, para);
		pos = str.indexOf(de);
	}
    return (str);
}

function preparaBuscaAvancada (documento) {
    document.getElementById('baQ').value = document.getElementById('baBusca').value;
    if (document.getElementById('baBuscaNegada').value) document.getElementById('baQ').value += ' -'+document.getElementById('baBuscaNegada').value;
    if (document.getElementById('baEvento').value) document.getElementById('baQ').value += ' evento:'+document.getElementById('baEvento').value;
    if (document.getElementById('baPessoa').value) document.getElementById('baQ').value += ' pessoa:'+document.getElementById('baPessoa').value;
    if (document.getElementById('baFotografo').value) document.getElementById('baQ').value += ' fotografo:'+document.getElementById('baFotografo').value;
    if (document.getElementById('baEditoria').value) document.getElementById('baQ').value += ' editoria:'+document.getElementById('baEditoria').value;
    if (document.getElementById('baSubeditoria').value) document.getElementById('baQ').value += ' subeditoria:'+document.getElementById('baSubeditoria').value;
    document.documento.submit();
}

//calcula tamanho de dois blocos e deixa o primeiro do mesmo tamanho que o segundo
//e aplica a diferenca do terceiro parametro
function ajustaAlturaBlocos(idPrimeiro,idSegundo,dif){
        //prim = $('.'+idPrimeiro);
        //seg = $('.'+idSegundo);
        //tamanhoPrim = prim.clientHeight;
        //tamanhoSeg = seg.clientHeight;
        //tamanhoPrim = $('.'+idPrimeiro).height();
        tamanhoSeg = $('.'+idSegundo).height();
        $('.'+idPrimeiro).height((parseInt(tamanhoSeg) + parseInt(dif)) + 'px');
        //alert((parseInt(tamanhoSeg) + parseInt(dif)));
}

// limita o tamanho de um campo textarea e mostra a qtd que falta
function limitText(idCampo, idContador, qtdLimite) {
    if (document.getElementById(idCampo).value.length > qtdLimite) {
    	document.getElementById(idCampo).value = document.getElementById(idCampo).value.substring(0, qtdLimite);
    } else {
    	document.getElementById(idContador).innerHTML = qtdLimite - document.getElementById(idCampo).value.length;
    }
}

function replace(valor, de, para){
    return valor.replaceAll(de, para);
}
