var	chave_ant="";
var	desc_ant="";
var	descricao_ant="";
var	canceladrop=false;
var camposFormularioLimpar;

  	// Mouse hover dos botões
function hov(loc,cls){
	if(loc.className)
		loc.className=cls;
}

function editaFormulario( numForm,pNomeVista){
	nomeVista="";
	if (pNomeVista!=undefined){
		nomeVista=pNomeVista;
	}

	dest = "FormEditor?frame=0&chave_fmfor="+numForm;
	dest = dest + "&clickName=sel&nomevista="+nomeVista+"&token="+Math.random();
	var win = window.open(dest,'_modelo',"width=900,height=650,scrollbars=yes,toolbar=no,status=yes,resizable=yes,menubar=no,location=no");
	win.focus();
}

function abrepopup(w,h,dest,winprops){
	if(w==''){w=800;}
	if(h==''){h=600;}
	if(w=='-1'){w=screen.width;}	/*Max*/
	if(h=='-1'){h=screen.height;}	/*Max*/
	uniqid=Math.floor(Math.random()*100);
    var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	if (dest!=''){
     	windim = 'height='+h+',width='+w+',top='+wint+',left='+winl;
		var win = window.open(dest,'popupwin'+uniqid,windim+" ,"+winprops);
		win.focus();
	}else{
		alert("Não foi possivel abrir a ligação. O url não se encontra preenchido");
	}
}

function chamaEditFormParent(numeroForm,nomeVista){
	try {editaFormulario(numeroForm,nomeVista);
	} catch (e) {
		try {window.parent.editaFormulario(numeroForm,nomeVista);
		} catch (e) {alert('Não foi possivel editar o formulário. Contacte o administrador.')}
	}
}


function constroiStringForm(frm){
	elem = frm.elements;
	str= "";
	for( i = 0; i < elem.length ; i++ ){
		elemn = elem[i];
		name=elemn.name;
		if( name.length > 0 ){
			str = str + "&"+name+"=";
			if(elemn.value.lengh==0){
				str = str +"_";
			}else{
				str = str + escape(elemn.value);
			}
		}
	}
	return str;
}

function limpaAmp( org ){
	s = new String(org);
	i = 0;
	while( s.indexOf("&amp;") > 0  && i < 20 ){
		s = s.replace("&amp;","&");
		i++;
	}
	return s;
}

//Remover as variaveis de sessao relativas à dropdown 
function destroiCombo(comboId, comboName, comboChave,comboDesc,mul,formtoken) {

	str='RefreshCombo.asp?tiporesultado=4&comboid='+comboId+'&comboname='+comboName+'&combodesc=' + escape(comboDesc)+'&ismul='+pMul+'&formtoken='+formtoken;
	sucess=createPresto('presto_'+comboId+'_ini',str,comboId+'_cb1' );
	if (!sucess){
		setTimeout("destroiCombo('" + comboId + "', '" + comboName + "', '" + comboChave + "', '" + comboDesc + "', '" + mul + "', '" + formtoken + "');", 200);
	}else{
		callServer('presto_'+comboId+'_ini','');
	}
	
}

function inicializaCombo(comboId,comboName,comboChave,comboDesc,mul,formtoken){
	pMul=0;
	if (mul!=undefined){
		pMul=mul;
	}

	/* v v v RM 29-04-2010 v v v */
	//str='RefreshCombo.asp?tiporesultado=3&comboid='+comboId+'&comboname='+comboName+'&combochave='+comboChave+'&combodesc='+comboDesc+'&ismul='+pMul+'&formtoken='+formtoken;
	str = 'RefreshCombo.asp?tiporesultado=3&comboid=' + comboId + '&comboname=' + comboName + '&combodesc=' + escape(comboDesc) + '&ismul=' + pMul + '&formtoken=' + formtoken;
	chave = document.getElementById(comboId+"_chave").value;
	if( chave != undefined && chave != '') {
		str += '&combochave=' + chave;
	}
	/* ^ ^ ^ ^ ^ ^ */
	cb = document.getElementById(comboId+'_cb1');
	cb.className += " initCombo";
	sucess=createPresto('presto_'+comboId+'_ini',str,comboId+'_cb1' );
	if (!sucess){
		setTimeout("inicializaCombo('" + comboId + "', '" + comboName + "', '" + comboChave + "', '" + comboDesc + "', '" + mul + "', '" + formtoken + "');", 200);
	}else{
		callServer('presto_'+comboId+'_ini','');
	}
}

function setFocusRes(comboId,comboName){
	try{
		testeId = document.getElementById("cbo_"+comboId).id;
		document.getElementById("cbo_"+comboId).focus();
	}catch(e){
		setTimeout("setFocusRes('"+comboId+"','"+comboName+"');",100);
	}
}

function obtemComboPesquisa(comboId,comboName,formtoken){

	document.getElementById(comboId+"_ap").className='mynetDivVisible prestoPlacer';
	str='RefreshCombo.asp?tiporesultado=2&comboid='+comboId+'&comboname='+comboName+'&formtoken='+formtoken;
	chave = document.getElementById(comboId+"_chave").value;
	if( chave != undefined && chave != '') {
		str += '&combochave=' + escape(chave);
	}
	createPresto('presto_'+comboId+'_ap',str,comboId+'_ap');
	callServer('presto_'+comboId+'_ap');
	setFocusRes(comboId,comboName);
	document.getElementById(comboId+"_desc").className='mynetDivHidden';	//Esconde input inicial
}
function setFocusComboPesquisa(comboId,comboName){
	var podeCarregar = false;
	try{
		testeId = document.getElementById(comboId+"_crit").id;
		podeCarregar = true;
	}catch(e){
		setTimeout("setFocusComboPesquisa('"+comboId+"','"+comboName+"');",100);
	}		
	if( podeCarregar ){
		document.getElementById(comboId+"_crit").focus();
	}
}

function obtemComboPesquisaFocus(comboId,comboName,formtoken){

			document.getElementById(comboId+"_ap").className='mynetDivVisible';
			str='RefreshCombo.asp?tiporesultado=2&comboid='+comboId+'&comboname='+comboName+'&formtoken='+formtoken;
			createPresto('presto_'+comboId+'_ap',str,comboId+'_ap');
			callServer('presto_'+comboId+'_ap');
			setFocusComboPesquisa(comboId,comboName);
			document.getElementById(comboId+"_desc").className='mynetDivHidden mynetInput mynetPointerHand';	//Esconde input inicial	
			mostraLimpar(comboId, formtoken);
			
}
function obtemCombo(comboId,comboName,formtoken){/*Obtem os resultados de pesquisa*/
	criterio = escape(document.getElementById(comboId+"_crit").value);
	removeElement(document.getElementById(comboId+"_crit"));
	removeElement(document.getElementById(comboId+"_crit_button"));
	retiraLimpar(comboId);
	str='RefreshCombo.asp?tiporesultado=1&comboid='+comboId+'&comboname='+comboName+'&valor='+criterio+'&formtoken='+formtoken;
	createPresto('presto_'+comboId+'_cbo',str,comboId+'_cbo');
	callServer('presto_'+comboId+'_cbo');
	setFocusRes(comboId,comboName)
}

function removeElement(element){
	try{
		element.parentNode.removeChild(element);
	}catch(e){}
}

function isMultiple(comboId){
	isMul=false;
	if (document.getElementById("mul_"+comboId)!=null){
		isMul=true;
	}	
	return isMul;
}

function devolveItemCombo( comboId ,comboName,formtoken){
		if (!canceladrop){
			cboObj=document.getElementById("cbo_"+comboId);
			index=cboObj.selectedIndex;
			if (index >= 0) {
				text=cboObj.options[index].text;
				chave=cboObj.options[index].value;
				if ((chave !='' || chave !='-1') && chave.length>0){
					if (isMultiple(comboId)){
						poeDadosComboMul( comboId, chave, text);	
					}else{
						poeDadosCombo( comboId, chave, text);	
					}
					enviaValorServidor(comboId ,comboName, chave,formtoken);
				}
			}
			hidePesquisa( comboId ,comboName);
		}
		canceladrop=false;
		setDadosDropAnt("","","");
		retiraLimpar(comboId);
		
	return true;
}	

function devolveItemComboCriterio( comboId ,comboName){
	cboObj=document.getElementById(comboId);
	index=cboObj.selectedIndex
	chave=cboObj.options[index].value;
	enviaValorServidor(comboId ,comboName, chave);
}
function limpaResult( comboId ,comboName,formtoken){

	if (isMultiple(comboId)){

	}else{
		try{
			if(comboId == 'inchaveproc'){
				limpaCamposForm();
			}
			text="[Selecione]";
			chave="";
			poeDadosCombo( comboId, chave, text);
			enviaValorServidor(comboId ,comboName, chave,formtoken);	

			cboObj=document.getElementById("cbo_"+comboId);	//Coloca a dropdown na primeira opção
			cboObj.selectedIndex=0;


		}catch (e){
		}
	}	
	return true;
}

function poeValorCampo(idCampo,valor){
	try{
		document.getElementById(idCampo).value=valor;
	}catch (e){
	}
}


function mostra_wnd_op(comboId ,comboName){
	divObj=document.getElementById("wnd_op_" +comboId);
	divObj.className='mynetDivVisible';
}
function poeDadosCombo( comboId , chave, descricao ){
	document.getElementById(comboId+"_chave").value=chave;
	document.getElementById(comboId+"_desc").value=descricao;
	if (descricao=="[Selecione]"){
		document.getElementById(comboId+"_descricao").value="";
	}else{
		document.getElementById(comboId+"_descricao").value=descricao;
	}
}
function poeDadosComboMul( comboId , chave, descricao ){
      var obj=document.getElementById(comboId+"_chave");
      var chaves=new Array('');
      var chaves=obj.value.split(';');
      nElem=0;
      nElem=chaves.length;

      podeAdicionar=true;
      for (i=0; i<nElem;i++){
            if (chave==chaves[i]){
                  podeAdicionar=false;
            }

      }

      if (podeAdicionar){
            var obj_chave=document.getElementById(comboId+"_chave");
            var obj_descricao=document.getElementById(comboId+"_descricao");
            var obj_desc='[Selecione]';
            pref=';';
            if (obj_chave.value==''){
                  pref='';
            }
            obj_chave.value+=pref+chave;
            obj_desc.value+=pref+descricao;
            obj_descricao.value+=pref+descricao;
      }
      drawList(comboId);
}
function delItem(comboId,index){
	delItemList(index,comboId+"_chave");
	delItemList(index,comboId+"_descricao");
   	drawList(comboId);
}	
function delItemList(index,objId){
	var obj=document.getElementById(objId);
	var mular=new Array();
	var mular=obj.value.split(';');
	res='';
   	nElem=mular.length;
	for (i=index+1; i<nElem;i++){
		mular[i-1]=mular[i]
	}
	mular.length-=1;
   	nElem=mular.length;
	for (i=0; i<nElem;i++){
		if (res==''){
			res+=mular[i];
		}else{
			res+=';'+mular[i];
		}
	}
	obj.value=res;

}
function drawList(comboId){
	trgDiv=document.getElementById("mul_"+comboId);
	var obj=document.getElementById(comboId+"_descricao");
	res='';	
	var mular=new Array('');
	var mular=obj.value.split(';');
	nElem=0;
	if (obj.value==''){mular.length=0;}//FIX: Limpa caixa
   	nElem=mular.length;
	res=res + "<table  border='0' cellpadding='0' cellspacing='0'>";
	for (i=0; i<nElem;i++){
		//res=res+"<tr><td nowrap='nowrap' class='mulent'>" +mular[i]+"</td>" + "<td nowrap='nowrap' width='10'></td>" ;
		res=res+"<tr><td class='mulent'>" +mular[i]+"</td>" + "<td nowrap='nowrap' width='10'></td>" ;
		res=res+"<td width='50' class='mynetPointerSel' onclick=\"delItem('"+comboId+"',"+i+")\" valign='top'>";		
		res=res+"<img class='mynetPointerSel' src='Imagens/Bts/btApagar.jpg' border='0'/>"
		res=res+"</td><tr>";	
	}
	res=res + "</table>";	
	trgDiv.innerHTML='';
	trgDiv.innerHTML = res;	
}

function hidePesquisa( comboId ,comboName){
	obj_desc=document.getElementById(comboId+"_desc");
	document.getElementById(comboId+"_desc").className='mynetDivVisible mynetInput mynetPointerHand';
	document.getElementById(comboId+"_ap").className='mynetDivHidden';
}

function enviaValorServidor(comboId ,comboName,valor,formtoken){
	view='';
	try{
		view=document.getElementById("view").value;
		if (view==undefined || view==null ){
			view='';
		}	
	}catch(ev){}

	
	str='RefreshCombo.asp?tiporesultado=99&view='+view+'&comboid='+comboId+'&comboname='+comboName+'&valor=' + escape(valor)+'&formtoken='+formtoken+"&token="+Math.random();

	createPresto('presto_'+comboId+'_cbor',str,comboId+'_ap');
	callServer('presto_'+comboId+'_cbor');
}

/*
* Limpar o formulário de processos de obras, quando é
* limpa a dropdown de processo de obras. Assume-se que o objeto
* camposFormularioLimpar está devidamente preenchido
*/

function limpaCamposForm(){
	for( i in camposFormularioLimpar ) {
		field = document.getElementById( i );
		if( field != undefined ) {
			field.value="";
			field.disabled = false;
			var pos = i.lastIndexOf("_");
			comboId = i.substr( 0, pos );
			iSufix = i.substr( pos );
			if ( iSufix == '_desc' ){ //é dropdown???
				text="[Selecione]";
				chave="";
				poeDadosCombo( comboId, chave, text);	
			}
		}		
	}

	poeDadosCombo( "intpedreqt", "", "[Selecione]");
}


/* v v v RM (04-04-2010) v v v */
/**
 * Preenche campos de uma página com valores presentes num objeto de transferência.
 *
 * @param returnTO o objeto de transferência.
 */
function povoaCampos(returnTO){

	/*guarda os campos pré-preenchidos para os conseguir limpar, 
	* se necessário.
	*/
	camposFormularioLimpar = returnTO;
	meteFocus = false;
	for( i in returnTO ) {
			field = document.getElementById( i );
			if( field != undefined ) {
				meteFocus = true;
				field.value = returnTO[i];
				if( field.type != 'hidden' ) {
					if( returnTO[i+"__toLock"] != undefined && returnTO[i] != ""
						&& ( (returnTO[i+"__toLock"] == "true" && returnTO[i+"__lockValue"] == undefined)
						|| (returnTO[i+"__lockValue"] != undefined && returnTO[i+"__lockValue"] == returnTO[i]) ) ) {//é para bloquear o campo?
						field.disabled = true;
					} else {
						if( field.disabled != undefined && field.disabled != false ) {
							field.disabled = false;
						} /*
						if( returnTO[i] == "" ) {
							field.value = "[Selecione]";
						}*/
					}
				}
				
				var pos = i.lastIndexOf("_");
				iBase = i.substr( 0, pos );
				iSufix = i.substr( pos );
				if ( iSufix == '_desc' ) {//Se este valor for uma descrição...
					field_descricao = document.getElementById( iBase + "_descricao" );
					if( field_descricao != undefined && returnTO[ iBase +"_descricao" ] == undefined ) {//...se existir um campo do tipo "_descricao" sem que haja valor para ele no objeto de transferência, então preenche-o também.
						field_descricao.value = returnTO[i];
					}
				} else {//Se este valor não for uma descrição... (deve ser uma chave)
					field_desc = document.getElementById( iBase + "_desc" );
					if( field_desc != undefined && returnTO[ iBase +"_desc" ] == undefined ) {//...se existir um campo do tipo "_desc" correspondente sem que haja valor para ele no objeto de transferência, então tem que se forçar a obtenção desse valor.
						if( field_desc.type != 'hidden' ) {
							if( returnTO[i+"__toLock"] != undefined  && returnTO[i] != ""
								&& ( (returnTO[i+"__toLock"] == "true" && returnTO[i+"__lockValue"] == undefined)
								|| (returnTO[i+"__lockValue"] != undefined && returnTO[i+"__lockValue"] == returnTO[i]) ) ) {//é para bloquear o campo?
									field_desc.disabled = true;
							} else {
								if( field_desc.disabled != undefined && field_desc.disabled != false ) {
									field_desc.disabled = false;
								}
								if( returnTO[iBase +"_desc"] == "" ) {
									field.value = "[Selecione]";
								}
							}
						}
						//field_desc.click();
						if(iBase!='innovalegreqt'){ // não alterar o valor do regime
							field_desc.onclick();
						}
					}
				}
			}
	}
	if(meteFocus == true){
		document.getElementById(returnTO["endFocus"]+'_desc').onclick();
	}
	return;		
}
/* ^ ^ ^ ^ ^ ^ */

function enviaMyNet(url){
	var xmlHttp = false;
	xmlHttp = new XMLHttpRequest();
	xmlHttp.open("GET", url, false);
	xmlHttp.send(null);
}


function refreshCache(){
	str='MyNetComando.asp?accao=ignoracache';
	enviaMyNet( str );
	document.location = document.location;
}

function alternaPesquisa( comboId ,comboName, formtoken){
	guardadadosanteriores(comboId ,comboName);
	obj=document.getElementById(comboId+"_ap");
	if (obj.className=='mynetDivHidden'){
		obtemComboPesquisa(comboId,comboName, formtoken);
	}else{
		hidePesquisa(comboId,comboName);
	}
	/* v v v RM 27-05-2010 v v v */
	obj=document.getElementById(comboId+"_ErrorField");
	if( obj != undefined ) {
		obj.parentNode.removeChild(obj);
	}
	/* ^ ^ ^ ^ ^ ^*/
}
function alternaPesquisaFocus(comboId, comboName, formtoken) {
	guardadadosanteriores(comboId, comboName);
	obj=document.getElementById(comboId+"_ap");
	if (obj.className=='mynetDivHidden'){
		obtemComboPesquisaFocus(comboId,comboName, formtoken);
	}else{
		hidePesquisa(comboId,comboName);
	}
}
function isPesquisaOpen( comboId){
	obj=document.getElementById(comboId+"_ap");
	if (obj.className=='mynetDivVisible'){
		return true;
	}else{
		return false;
	}
}
function catchEnterPesquisas(e,numEvento,comboId,comboName,formtoken){
	res=true;
	if(e){
		e = e 
	} else {
		e = window.event
	} 
	if(e.which){ 
		var keycode = e.which
	} else {
		var keycode = e.keyCode 
	}

	if (numEvento==1){				//Input critérios
		switch(keycode){
		case 13:
			criterio = document.getElementById(comboId+"_crit").value;
			obtemCombo(comboId,comboName,formtoken);
			break    
		case 27:hidePesquisa(comboId,comboName);retiraLimpar(comboId);break;
		case 37:hidePesquisa(comboId,comboName);break
		case 39:obtemComboPesquisa(comboId,comboName,formtoken);break					
		case 38:hidePesquisa(comboId,comboName);break
		case 40:obtemComboPesquisa(comboId,comboName,formtoken);break;
		case 46:limpaResult(comboId,comboName,formtoken);hidePesquisa(comboId,comboName);break;
		}
	}else if (numEvento==2){		//Input resultados
		switch(keycode){
		case 13:
				devolveItemCombo( comboId, comboName,formtoken);
				hideToolTip();
				enviaFocusComboDesc( comboId );
				break;
		case 27:/*ESC*/
				cancelaEdicaoDd(comboId,comboName);
				break;
		case 46:limpaResult(comboId,comboName,formtoken);hidePesquisa(comboId,comboName);break	
		}
	}else if (numEvento==3){	//Botão pesquisar critérios
		switch(keycode){
		case 13:obtemCombo(comboId,comboName,formtoken);break    
		case 27:hidePesquisa(comboId,comboName);break
		case 37:hidePesquisa(comboId,comboName);break
		case 39:obtemComboPesquisa(comboId,comboName,formtoken);break					
		case 38:hidePesquisa(comboId,comboName);break
		case 40:obtemComboPesquisa(comboId,comboName,formtoken);break;
		}
	}else if (numEvento==4){	//Botão para devolver resultados
		switch(keycode){
		case 13:
				devolveItemCombo( comboId, comboName,formtoken);
				enviaFocusComboDesc(comboId );
				break;
		case 27:hidePesquisa(comboId,comboName);break
		case 16:
			break;
		case 9:
			if (!e.shiftKey){
				hidePesquisa(comboId,comboName);
			}
			break				
		case 37:hidePesquisa(comboId,comboName);break
		case 39:obtemComboPesquisa(comboId,comboName,formtoken);break					
		case 38:hidePesquisa(comboId,comboName);break
		case 40:obtemComboPesquisa(comboId,comboName,formtoken);break														
		}
	}else if (numEvento==5){	//Input do formulário
		guardadadosanteriores(comboId ,comboName);
		switch(keycode){
		case 27:alternaPesquisa(comboId,comboName,formtoken);break
		case 13:
			if (isPesquisaOpen(comboId)){
				hidePesquisa(comboId,comboName);
			}else{
				obtemComboPesquisa(comboId,comboName,formtoken);
			}
			break
		case 37:hidePesquisa(comboId,comboName);break
		case 39:obtemComboPesquisa(comboId,comboName,formtoken);break					
		case 38:hidePesquisa(comboId,comboName);break
		case 40:obtemComboPesquisa(comboId,comboName,formtoken);break										
		case 37:hidePesquisa(comboId,comboName);break
		case 39:obtemComboPesquisa(comboId,comboName,formtoken);break					
		case 38:hidePesquisa(comboId,comboName);break
		case 40:obtemComboPesquisa(comboId,comboName,formtoken);break
		case 9:break
		case 16:break
		case 46:limpaResult(comboId,comboName,formtoken);break	
		default:obtemComboPesquisa(comboId,comboName,formtoken);			
		}
	}else if (numEvento==6){	//Input do formulário com critérios
		guardadadosanteriores(comboId ,comboName);
		switch(keycode){
		case 27:alternaPesquisaFocus(comboId,comboName,formtoken);break
		case 13:
			if (isPesquisaOpen(comboId)){
				hidePesquisa(comboId,comboName);
			}else{
				obtemComboPesquisaFocus(comboId,comboName,formtoken);
			}
			break
		case 37:hidePesquisa(comboId,comboName);break
		case 39:obtemComboPesquisaFocus(comboId,comboName,formtoken);break					
		case 38:hidePesquisa(comboId,comboName);break
		case 40:obtemComboPesquisaFocus(comboId,comboName,formtoken);break										
		case 37:hidePesquisa(comboId,comboName);break
		case 39:obtemComboPesquisaFocus(comboId,comboName,formtoken);break					
		case 38:hidePesquisa(comboId,comboName);break
		case 40:obtemComboPesquisaFocus(comboId,comboName,formtoken);break
		case 9:break
		case 16:break						
		case 46:limpaResult(comboId,comboName,formtoken);break			
		default:
			//obtemComboPesquisaFocus(comboId,comboName,formtoken);
		}
	}else if (numEvento==7){
		switch(keycode){
		case 13:
			pesquisa('');
			break
		}

	}//End if
	
	if (keycode==13 || keycode == 27){
		res=false;
	}
	return res;
}	

function  selectMenuLista(elementoId){
	parent.mostraMenu();
	menuArvore=parent.menuArvore;
	var n=0;
	var encontrado=false;
	for (n; n<menuArvore.aNodes.length; n++) {
		if (menuArvore.aNodes[n].idMenu==elementoId){
			encontrado = true;
			menuArvore.closeAll(); 
			menuArvore.openTo(menuArvore.aNodes[n].id,true,false);			
	/*
	 * <!-- v v v rmatos (07/08/2009) v v v -->
	 * Itens de menu não circuláveis através do uso do tab
	 * e rmatos (07/08/2009)
	 * Corrigir funcionamento do botão "retroceder" no formulário de registo:
	 */	
			//parent.alteraOpcaosELECT(menuArvore.aNodes[n].url);			
			parent.setIFrameSrc(menuArvore.aNodes[n].url);			
	/*
	 * <!-- ^ ^ ^ rmatos ^ ^ ^ -->
	 */	
		}
	}
	if( ! encontrado ){
		menuArvorefolhas=parent.menuArvorefolhas;
		aux = "";
		for (n=0; n<menuArvorefolhas.aNodes.length; n++) {
			aux += " "+menuArvorefolhas.aNodes[n].idMenu;
			ax=''+elementoId;
			if (menuArvorefolhas.aNodes[n].idMenu==ax){				
				encontrado = true;
				//parent.alteraOpcaosELECT(menuArvorefolhas.aNodes[n].url);			
				parent.setIFrameSrc(menuArvore.aNodes[n].url);			
			}
		}
	}
}
function altdropmul(obj,nomebase,nb){
   	objnb=document.getElementById(nb);
	c=0;
	sz=obj.options.length;
	 for (i=0; i<sz; i++) {
    	objtrg=document.getElementById(nomebase+'_'+obj.options[i].value);
	    if (obj.options[i].selected) {valor='1';c+=1;}
	    else{valor='0';}
   		objtrg.value=valor;
  	}
	if (c>0){objnb.value=c;}else{objnb.value='';}  	
}
function altcheck(obj,nometrg,nb){
    	objnb=document.getElementById(nb);
    	if (objnb.value==''){c=0;}
    	else{c=parseFloat(objnb.value);}
    	objtrg=document.getElementById(nometrg);
	    if (obj.checked){valor='1';c+=1;}
	    else{valor='0';c-=1;}
		if (c>0){objnb.value=c;
		}else{objnb.value='';}
   		objtrg.value=valor;    	
}
function altcheckUnica(obj,nometrg){
    	objtrg=document.getElementById(nometrg);
	    if (obj.checked) {valor='1';}
	    else{valor='-1';}
   		objtrg.value=valor;    	
}
function altradio(nomesrc,nometrg){
		objsrc=document.getElementsByName(nomesrc);
    	objtrg=document.getElementById(nometrg);
    	for(var i = 0; i < objsrc.length; i++) {
			if(objsrc[i].checked) {objtrg.value=objsrc[i].value;}
		}
}

function printPag(){
	print();
}

function wndmin(iddiv){
	target=document.getElementById("ct"+iddiv)
	if (target.className=='mynetDivHidden'){
		target.className='mynetDivVisible';
	}else{
		target.className='mynetDivHidden';
	}		
}

/*
 * function to show or hide elements changeing it's sytle directly
 * (without changing the whole style classes)
 
 * @param element can be string or object
 * @param showHide force "show" or "hide" state or, if "", just toggle it's state
 */
function directToggleShowHideElement( element, showHide ){
	try{
		if( document.getElementById(element) ) {
			element = document.getElementById(element);
		}
		if( typeof element == "object" ) {
			if(showHide != "show" && showHide != "hide"){
				showHide = (element.style.visibility == "hidden" ? "show" : "hide");
			}
			
			if(showHide == "show") {
				element.style.visibility = "visible";
				element.style.display = "block";
			} else if (showHide == "hide") {
				element.style.visibility = "hidden";
				element.style.display = "none";
			}
		}
	}catch(e){
		showHide = "?";
	}
	return showHide;
}

function wndmin_v2(root,uid){
	imgicon=document.getElementById("img_"+uid);
	imgicon.src=root+"Imagens/Bts/btmin.gif";
	target=document.getElementById("cnt_"+uid);
	label=document.getElementById("cnt_label_"+uid);
	
	targetClassNamesArray = target.className.split(" ");
	var i = 0;
	className = "";
	for( ; i < targetClassNamesArray.length ; i++ ) {
		if( targetClassNamesArray[i] == 'mynetDivHidden' || targetClassNamesArray[i] == 'mynetDivVisible' ) {
			className = targetClassNamesArray[i];
			break;
		}
	}
	
	if (className=='mynetDivHidden'){
		targetClassNamesArray[i] = 'mynetDivVisible';
		target.className = targetClassNamesArray.join(" ");
		if (tp==3){label.className='mynetDivHidden';}		
		imgicon.src=root+"Imagens/Bts/btmin.gif";		
	}else if(className=='mynetDivVisible'){
		targetClassNamesArray[i] = 'mynetDivHidden';
		target.className = targetClassNamesArray.join(" ");
		if (tp==3){label.className='mynetDivVisible';}
		imgicon.src=root+"Imagens/Bts/MaxRest.gif";
	}else {
		showHide = directToggleShowHideElement( target, '' );
		if (tp==3){
			directToggleShowHideElement( label, (showHide == 'show'? 'hide' : 'show'));
		}
		imgicon.src=root+"Imagens/Bts/" + (showHide == 'hide'? "MaxRest" : "btmin") + ".gif";
	}
	try {parent.resizeIframe("myframeB");}catch(e){}
}

function URLDecode(pData)
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var encoded = pData;
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
   return plaintext;
}

function altdet(id,objthis){
	divobj=document.getElementById(id);
	if (divobj.className=='mynetDivHidden'){
		divobj.className='mynetDivVisible';
		htm1=objthis.innerHTML;
		objthis.innerHTML=htm1.replace("Ver mais","Esconder");
	}else{
		divobj.className='mynetDivHidden';
		htm1=objthis.innerHTML;
		objthis.innerHTML=htm1.replace("Esconder","Ver mais");
	}
	try {
		parent.resizeIframe("myframeB");
	} catch (e) {}
}
function setDadosDropAnt(pc,pd1,pd2){	
			chave_ant=pc;
			desc_ant=pd1;
			descricao_ant=pd2;
}
function guardadadosanteriores(comboId ,comboName){	
			setDadosDropAnt(document.getElementById(comboId+"_chave").value, document.getElementById(comboId+"_desc").value,document.getElementById(comboId+"_descricao").value);
}
function cancelaEdicaoDd(comboId,comboName){
	document.getElementById(comboId+"_chave").value=chave_ant;
	document.getElementById(comboId+"_desc").value=desc_ant;
	document.getElementById(comboId+"_descricao").value=descricao_ant;
	hidePesquisa(comboId,comboName);
	canceladrop=true;
}
function enviaFocusComboDesc( comboId ){
	try{
		document.getElementById(comboId+"_desc").focus();
	} catch(e)
	{	
	}
	
}
function drawWnd_upload(UID,srvurl){
		titulo='';
		botoes='';
		try {
			if( window.parent.wndInit != undefined ) {
				window.parent.wndInit(UID,botoes,titulo,srvurl,'');
			}
		} catch (e) {
		}
}
function mostraWnd_upload(UID,srvurl){	//Função alterada
	width='450';
	height='220';
	url="MyNetFileSystem.asp?tipo=mydocs&tk="+Math.random();
	try{
		drawWnd_upload(UID,srvurl);
		try {
			if( window.parent.showWnd != undefined ) {
				window.parent.showWnd(UID,url,width,height,'','myframeB');
			}
		} catch (e) {
		}
	}catch(e){
		abrepopup(width,height,url,' scrollbars=yes,toolbar=no,status=no,resizable=yes,menubar=no,location=no');
	}

}

	function showInputToolTip(event, objname, maxlen){
		var maxCaracter=maxlen;
				
		var selectText = objname.value;	
				
		var theDiv = document.getElementById('tooltip'); //Id referente ao tooltip	
		
		if(selectText.length<=maxCaracter){ //verificar se é preciso mostrar o tooltip
			if(theDiv!=null){
				if(theDiv.childNodes[0]!=null){ // se existir um tooltip apaga
					hideToolTip();
				}
			}
			return;
		}	
			
		if(theDiv==null){ // se não existir o div cria	
			createToolTip("tooltip");
			theDiv = document.getElementById('tooltip');
		}
			
		if(theDiv.childNodes[0]!=null){ // se existir um tooltip apaga
			hideToolTip();
		}
		
		if(selectText!=""){	// se o texto for vazio não cria tooltip
			if(theDiv.childNodes[0]!=null)
				theDiv.removeChild(theDiv.childNodes[0]); 
			
			var j = document.createTextNode(selectText);		
			theDiv.appendChild( j );
		}
		else{ // apaga tooltip
			if(theDiv.childNodes[0]!=null) // se existir um tooltip apaga
				hideToolTip();				
		}
	
		//show tooltip
		menuLayers.show('tooltip', event,this.id,1);
	
	}
    
	function showSelectToolTip(event, objname, maxlen){
		var maxCaracter=maxlen;		

		//if(objname.selectedIndex==-1) objname.selectedIndex=0;
		if(objname.selectedIndex==-1) return;
		var selectText = objname.options[objname.selectedIndex].text;	
					
		var theDiv = document.getElementById('tooltip'); //Id referente ao tooltip	
		
//		if(selectText.length<=maxCaracter){ //verificar se é preciso mostrar o tooltip
			if(theDiv!=null){
				if(theDiv.childNodes[0]!=null) // se existir um tooltip apaga
					hideToolTip();
			}
//			return;
//		}
		
		if(theDiv==null){ // se não existir o div cria	
			createToolTip("tooltip");
			theDiv = document.getElementById('tooltip');
		}
			
		if(theDiv.childNodes[0]!=null) // se existir um tooltip apaga
			hideToolTip();
		
		if(selectText!=""){	// se o texto for vazio não cria tooltip
			if(theDiv.childNodes[0]!=null)
				theDiv.removeChild(theDiv.childNodes[0]); 
			
			var j = document.createTextNode(selectText);		
			theDiv.appendChild( j );
		}
		else{ // apaga tooltip
			if(theDiv.childNodes[0]!=null) // se existir um tooltip apaga
				hideToolTip();
		}
	
		//show tooltip
		menuLayers.show('tooltip', event,this.id,1);
	}

	function createToolTip(objname){			
		var newdiv = document.createElement('div');
		newdiv.setAttribute('id',objname);
		newdiv.className = "menupop";
		
		newdiv.style.visibility = 'hidden';
		newdiv.style.width		= '500';

		document.body.appendChild(newdiv);

	}
	
	function hideToolTip(){	
		var theDiv = document.getElementById('tooltip'); //Id referente ao tooltip	
		if (theDiv!=null){
			if (document.getElementById) { // DOM3 = IE5, NS6 
				document.getElementById('tooltip').style.visibility = 'hidden'; 			
			}else { 
				if (document.layers) { // Netscape 4 
					document.theDiv.visibility = 'hidden'; 
				} 
				else { // IE 4 
					document.all.theDiv.style.visibility = 'hidden'; 
				}
			} 
		}
		
	}

function replaceAll(string, token, newtoken) {
	while (string.indexOf(token) != -1) {
 		string = string.replace(token, newtoken);
	}
	return string;
}
/*
function openLoadBar(srvurl){
	try {
		window.parent.wndInit("LOADBAR","","","/"+srvurl,"");
		window.parent.showWnd("LOADBAR","/"+srvurl+"/LoadBar.asp?tipo=0","320","220","");
	} catch (e) {}
}
function closeLoadBar(){
	try {
		window.parent.closeWnd("LOADBAR","0","");
	} catch (e) {}
}
*/

//Retira a imagem que aparece para limpar a dropdown
function retiraLimpar(dropdown)
{
	colunaBotaoLimpar = document.getElementById('colunaLimpar_'+dropdown);
	if(colunaBotaoLimpar)
		colunaBotaoLimpar.innerHTML="";
}

//Adiciona uma imagem a tras da dropdown, que permite limpar o conteudo da dropdown
//Imagem é adicionada se a dropdown tiver algum valor e quando se clica na dropdonw
//colunaLimpar diz respeito ao id de um <td> ni interfaceFormCompile
function mostraLimpar(dropdown, formtoken)
{
	if(document.getElementById(dropdown+'_chave').value != "")
	{
		coluna = document.getElementById('colunaLimpar_'+dropdown);
		coluna.innerHTML = "<div><a href='#' onClick=\"cancelaEdicaoDd('"+dropdown+"','"+dropdown.toLowerCase()+"');limpaResult('"+dropdown+"', '"+dropdown.toLowerCase()+"', '"+formtoken+"');retiraLimpar('"+dropdown+"');setCancelaDropFalse(); return false;\"><img src='Imagens/Bts/btApagarDrop.jpg' alt='Limpar' BORDER='0px'/></a></div>";
		
	}
}

function setCancelaDropFalse()
{
	canceladrop = false;
}

if(!Array.prototype.indexOf){
    Array.prototype.indexOf = function(obj, start){
        for(var i = (start || 0), j = this.length; i < j; i++){
            if(this[i] === obj){return i;}
        }
        return -1;
    }
}


function html_entity_decode(str){    
	try	{
		var  tarea=document.createElement('textarea');
		tarea.innerHTML = str;
		var res = tarea.value;
		//tarea.parentNode.removeChild(tarea);
		return res;
	}catch(e){
		//for IE add <div id="htmlconverter" style="display:none;"></div> to the page
		document.getElementById("htmlconverter").innerHTML = '<textarea id="innerConverter">' + str + '</textarea>';
		var content = document.getElementById("innerConverter").value;
		document.getElementById("htmlconverter").innerHTML = "";
		return content;
	}
}
function hasClass(ele,cls) {
	return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}

function addClass(ele,cls) {
	if (!this.hasClass(ele,cls)) ele.className += " "+cls;
}
function removeClass(ele,cls) {
	if (hasClass(ele,cls)) {
		var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
		ele.className=ele.className.replace(reg,' ');
	}
}

function submeteToMynet(url, div) {

	createPresto('presto_'+div,url,div);
	callServer('presto_'+div);

} 
/*Obtem do URL atual o valor de qualquer parametro. Obtém também parametros existentes no hash. Ex de utilização: http://.../var1=1&var2=2#var3=3&var4=4*/
function getUrlParameter(name){  
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");  
	var regexS = "[\\?&#]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );  
	var results = regex.exec( window.location.href );  
		if( results == null )    
			return "";  
		else    
			return results[1];
}
function getFormParams(formName){
	var formP="";
	
	var cam=document.getElementById(formName); 
	for (var i=0;i<cam.length;i++){ 

		if (cam.elements[i].disabled==false && cam.elements[i].name != '') {
			formP += cam.elements[i].name + '=' + escape(cam.elements[i].value) + '&';
		}
	} 
	return formP
}
function addLoadEvent(func) {   

	var oldonload = window.onload;   
	if (typeof window.onload != 'function') {       
		window.onload = func;   
		}   
	else {       
		window.onload = function() {           
		oldonload();           
		func();       
		}   
	}
}
function isNumeric(val) {
    if (isNaN(parseFloat(val))) {
          return false;
     }
     return true
}

function filtrarElementos(term, _id, cellNr){
	var suche = term.value.toLowerCase();
	var table = document.getElementById(_id);
	var ele;
	var indexinicial;
	var indexfinal;
	for (var r = 0; r < table.rows.length; r++){
		//ele = table.rows[r].cells[cellNr].innerHTML.replace(/<[^>]+>/g,"");
		elemento = table.rows[r].cells[cellNr].innerHTML;
		indexinicial = elemento.indexOf('<li>');
		indexfinal = elemento.indexOf('</li>');
		if(indexinicial < 0) {
			indexinicial = elemento.indexOf('<LI>');
		}
		
		if(indexfinal < 0){
			indexfinal = elemento.indexOf('</LI>');
		}
		
		if(indexinicial >= 0 && indexfinal > 0) {
			ele = elemento.substring(indexinicial + 4, indexfinal);
		} else {
			ele = table.rows[r].cells[cellNr].innerHTML.replace(/<[^>]+>/g,"");
		}

		if (ele.toLowerCase().indexOf(suche)>=0 )
			table.rows[r].style.display = '';
		else table.rows[r].style.display = 'none';
	}
}


