/*
 * Returns the form that contains the control with the given id.
 */
function getFormForId(id) {
        return document.getElementById(id).form;
}

/*
 * Opens a new page in the right frame.
 * It also shows the loading screen during loading
 */
function openPage(href) {
    target = isFramed() ? parent.admin_content : this;
    openPageIn(href, target);
}

/*
 * Opens a new page in the given target frame.
 * It also shows the loading screen during loading
 */
function openPageIn(href, target) {
    loadingOn();
    target.location = href;
}

/*
 * Sets the current displayed context help.
 * It only works if framed.
 */
function setContextHelp(contextHelp) {
    try {
        top.body.menu.setInternalContextHelp(contextHelp);
    } catch(e) {}
}

/*
 * Sets the default context help.
 * It only works if framed.
 */
function setContext(defaultContext) {
    if (defaultContext) {
        top.defContextHelp = defaultContext;
    }
    setContextHelp();
}

/*
 * Returns the default context help.
 * It only works if framed.
 */
function getContext() {
    return top.defContextHelp;
}

/*
 * Sets the active item in the menu frame.
 * It only works if framed.
 */
function setActiveItemByName(name) {
    try {
        return parent.admin_menu.setActiveItem(name);
    } catch (e) {
        return false;
    }
}

/*
 * Mouse event handler for item groups.
 */
function mouseGroupEvent(group, open) {
    if (open) {
       group.className = 'navTitleOver';
    } else {
       group.className = 'navTitle';
    }
}

function bodyLoad() {
			document.getElementById('loaderContainerH').height = document.body.offsetHeight;
			document.getElementById("loaderContainerH").style.display = "none";
}

function bodyUnload(mensagem) {
			if (mensagem != "") {
						top.body.menu.document.getElementById("conteudoCarregando").innerHTML=mensagem;
			}
	
			document.getElementById("loaderContainerH").style.display = "block";
}

function showMenuVoltar() {
        	if (window.innerHeight) {
        	// Mozilla
        		winWidth = window.innerWidth;
        	} else if (document.documentElement && document.documentElement.clientHeight) {
        	// IE 6 "strict" mode
        		winWidth = document.documentElement.clientWidth;
        	} else if (document.body && document.body.clientWidth) {
        	// IE 5, IE 6 "relaxed" mode
        		winWidth = document.body.clientWidth;
        	}

			divVoltar = document.getElementById("menuVoltar");
			divVoltar.style.left = winWidth - 240 + "px";
			divVoltar.style.display = "block";
}

function hideMenuVoltar() {
			document.getElementById("menuVoltar").style.display = "none";
}

/*
 * Submits a form, showing the loading screen during loading.
 */
function submitForm(theForm) {
    loadingOn();
    theForm.submit();
    return true;
}

function simpleSubmit(theForm) {
    document.theForm.submit();
}

/*
 * Checks is we are working in the admin-view framed environment.
 */
function isFramed() {
    return parent.admin_content && parent.admin_menu;
}

/*
 * Resize iframe (max height)
 */
function maximizeIframe(iframeName, topo) {
				obj_iframe = top.body.menu.document.getElementById(iframeName);
				obj_iframe.height = top.body.menu.document.body.offsetHeight - topo;
			
				if (iframeName == "iframe_menu") {
					  changeSizeMenu(obj_iframe.height);
				}
}

/*
 * Return pos Top of object
 */
function findPosY(objeto) {
		var curtop = 0;

		if (objeto) {
						if (objeto.offsetParent) {
							  while (objeto.offsetParent) {
							  	  curtop += objeto.offsetTop;
								    objeto = objeto.offsetParent;
							  }
						}
						else if (objeto.y) {
							  curtop += objeto.y;
						}	
						return curtop;
		}
}

var preimages = new Array()

function preload() {

	for (i=0; i < preload.arguments.length; i++){

		preimages[i] = new Image()

		preimages[i].src = preload.arguments[i]

	}

}

/*
 * Tela de administrador
 */

function telaAdminAjustaPesquisaHierarquiaFrame(obj) {
	if(window.screen.width <= 835) { 
		obj.style.height = "480";
		obj.style.width = "200";
	} else {
		obj.style.height = "480";
		obj.style.width = "250";
	}    
}

function telaAdminAjustaPesquisaHierarquiaDiv(obj) {
	if(window.screen.width <= 835) { 
		obj.style.height = "455";
		obj.style.width = "100%";
	} else {
		obj.style.height = "455";
		obj.style.width = "100%";
	}    
}

function telaAdminAjustaListaFrame(obj) {
	if(window.screen.width <= 835) { 
		obj.style.height = "225";
		obj.style.width = "330";
	} else {
		obj.style.height = "225";
		obj.style.width = "500";
	}    
}

function telaAdminAjustaListaDiv(obj) {
	if(window.screen.width <= 835) { 
		obj.style.height = "180";
		obj.style.width = "100%";
	} else {
		obj.style.height = "180";
		obj.style.width = "100%";
	}    
}

function telaAdminAjustaPesquisaFrame(obj) {
	if(window.screen.width <= 835) { 
		obj.style.height = "255";
		obj.style.width = "330";
	} else {
		obj.style.height = "255";
		obj.style.width = "500";
	}    
}

function telaAdminAjustaPesquisaDiv(obj) {
	if(window.screen.width <= 835) { 
		obj.style.height = "210";
		obj.style.width = "100%";
	} else {
		obj.style.height = "210";
		obj.style.width = "100%";
	}    
}



function telaPerfilAjustaPesquisaFrame(obj) {
	if(window.screen.width <= 835) { 
		obj.style.height = "185";
		obj.style.width = "540";
	} else {
		obj.style.height = "275";
		obj.style.width = "750";
	}    
}

function telaPerfilAjustaPesquisaDiv(obj) {
	if(window.screen.width <= 835) { 
		obj.style.height = "140";
		obj.style.width = "100%";
	} else {
		obj.style.height = "230";
		obj.style.width = "100%";
	}    
}



/*
 * Tela de administrador com frame(nao iframe)
 */

function telaAdminAjustaHierarquiaPerfil(objDiv) {
	if(window.screen.width <= 835) { 
		objDiv.style.width = "98%";
		objDiv.style.height = "170";
	} else {
		objDiv.style.width = "98%";
		objDiv.style.height = "220";
	}    
}

function ajustaAlturaIframe(iframeID, variacao) {
        	if (window.innerHeight) {
        	// Mozilla
        		winHeight = window.innerHeight;
        	} else if (document.documentElement && document.documentElement.clientHeight) {
        	// IE 6 "strict" mode
        		winHeight = document.documentElement.clientHeight;
        	} else if (document.body && document.body.clientHeight) {
        	// IE 5, IE 6 "relaxed" mode
        		winHeight = document.body.clientHeight;
        	}
	
	
       if (document.all && document.getElementById) {
          					document.getElementById(iframeID).style.height = winHeight + variacao + "px";
       }
       else if (navigator.appName == "Microsoft Internet Explorer") {
          					document.getElementById(iframeID).height = winHeight+ variacao + "px";
	   }          
       else if (document.getElementById) {
	  						document.getElementById(iframeID).style.height = winHeight + variacao + "px";
       } 
}

//Faz mouseover no displaytag :)
function highlightTableRows(tableId) {
    var previousClass = null;
    var table = document.getElementById(tableId);
    if (table == null)
    	return false;
    var tbody = table.getElementsByTagName("tbody")[0];
    var rows = tbody.getElementsByTagName("tr");
    
    // procura a primeira coluna que tenha link em todas as linhas
    for (i=0; i < rows.length; i++) {
        rows[i].onmouseover = function() { previousClass=this.className;this.className+=' over' };
        rows[i].onmouseout = function() { this.className=previousClass };
    	var cells = rows[i].getElementsByTagName("td");
    	
    	for (j=0; j < cells.length; j++) { //loop em todas as colunas dessa linha
    		if (cells[j].getElementsByTagName("a").length > 0) {
    			rows[i].onclick = function(evt) {   
  					//verifica se o click foi dado em uma TD			
  					var srcElement;
				  	if (evt && evt.target) {
				    	srcElement = evt.target;
				    	if (srcElement.nodeType == 3) {
				     		srcElement = srcElement.parentNode;
				    	}
				  	}
				  	else if (window.event) {
				   		srcElement = window.event.srcElement;
				  	}
				 	tagName = srcElement.tagName.toLowerCase();
				  	if (tagName != 'td') {return;}
    			    	
    			    //--se chegou aqui, ? porque clicou em uma TD, ent?o executa o link				
    				var link = this.getElementsByTagName("a")[0];
    			
    				if (link.onclick) { //olha se o link da a??o est? no onclick ou no href
    					 call=link.getAttribute("onclick");
               	     	 // this will not work for links with onclick handlers that return false
               	     	 eval(call);
               		} else {
               	    	 location.href = link.getAttribute("href");
              		}
              		this.style.cursor="wait";
    			} //if do onclick
    			
   				break; //achou o link, pula para a pr?xima linha
    		} //if
    	} //for
    } //for
}

// Fun??es para ser usadas com <select>
//Add an item to a list
function addToList(listField, newText, newValue) {
   if ( ( newValue == "" ) || ( newText == "" ) ) {
      //alert("You cannot add blank values!");
   } else {
      var len = listField.length++; // Increase the size of list and return the size
      listField.options[len].value = newValue;
      listField.options[len].text = newText;
      listField.selectedIndex = len; // Highlight the one just entered (shows the user that it was entered)
   } // Ends the check to see if the value entered on the form is empty
}

//Remove the selected element from a list
function removeFromList(listField) {
   if ( listField.length == -1) {  // If the list is empty
      //alert("There are no values which can be removed!");
   } else {
      var selected = listField.selectedIndex;
      if (selected == -1) {
         //alert("You must select an entry to be removed!");
      } else {  // Build arrays with the text and values to remain
         var replaceTextArray = new Array(listField.length-1);
         var replaceValueArray = new Array(listField.length-1);
         for (var i = 0; i < listField.length; i++) {
            // Put everything except the selected one into the array
            if ( i < selected) { replaceTextArray[i] = listField.options[i].text; }
            if ( i > selected ) { replaceTextArray[i-1] = listField.options[i].text; }
            if ( i < selected) { replaceValueArray[i] = listField.options[i].value; }
            if ( i > selected ) { replaceValueArray[i-1] = listField.options[i].value; }
         }
         listField.length = replaceTextArray.length;  // Shorten the input list
         for (i = 0; i < replaceTextArray.length; i++) { // Put the array back into the list
            listField.options[i].value = replaceValueArray[i];
            listField.options[i].text = replaceTextArray[i];
         }
      } // Ends the check to make sure something was selected
   } // Ends the check for there being none in the list
}

//Move up the selected option
function moveUpList(listField) {
   if ( listField.length == -1) {  // If the list is empty
      //alert("There are no values which can be moved!");
   } else {
      var selected = listField.selectedIndex;
      if (selected == -1) {
         //alert("You must select an entry to be moved!");
      } else {  // Something is selected 
         if ( listField.length == 0 ) {  // If there's only one in the list
            //alert("There is only one entry!\nThe one entry will remain in place.");
         } else {  // There's more than one in the list, rearrange the list order
            if ( selected == 0 ) {
               //alert("The first entry in the list cannot be moved up.");
            } else {
               // Get the text/value of the one directly above the hightlighted entry as
               // well as the highlighted entry; then flip them
               var moveText1 = listField[selected-1].text;
               var moveText2 = listField[selected].text;
               var moveValue1 = listField[selected-1].value;
               var moveValue2 = listField[selected].value;
               listField[selected].text = moveText1;
               listField[selected].value = moveValue1;
               listField[selected-1].text = moveText2;
               listField[selected-1].value = moveValue2;
               listField.selectedIndex = selected-1; // Select the one that was selected before
            }  // Ends the check for selecting one which can be moved
         }  // Ends the check for there only being one in the list to begin with
      }  // Ends the check for there being something selected
   }  // Ends the check for there being none in the list
}

//Move down the selected option
function moveDownList(listField) {
   if ( listField.length == -1) {  // If the list is empty
      //alert("There are no values which can be moved!");
   } else {
      var selected = listField.selectedIndex;
      if (selected == -1) {
         //alert("You must select an entry to be moved!");
      } else {  // Something is selected 
         if ( listField.length == 0 ) {  // If there's only one in the list
            //alert("There is only one entry!\nThe one entry will remain in place.");
         } else {  // There's more than one in the list, rearrange the list order
            if ( selected == listField.length-1 ) {
               //alert("The last entry in the list cannot be moved down.");
            } else {
               // Get the text/value of the one directly below the hightlighted entry as
               // well as the highlighted entry; then flip them
               var moveText1 = listField[selected+1].text;
               var moveText2 = listField[selected].text;
               var moveValue1 = listField[selected+1].value;
               var moveValue2 = listField[selected].value;
               listField[selected].text = moveText1;
               listField[selected].value = moveValue1;
               listField[selected+1].text = moveText2;
               listField[selected+1].value = moveValue2;
               listField.selectedIndex = selected+1; // Select the one that was selected before
            }  // Ends the check for selecting one which can be moved
         }  // Ends the check for there only being one in the list to begin with
      }  // Ends the check for there being something selected
   }  // Ends the check for there being none in the list
}

/*
 * Sets the current folder locate
 */
function setDisplayFolderLocate(text) {
	tamanhoConteudo = top.head.document.body.offsetWidth;
	//se est? em resolu??o 800x600 tem que diminuir a descri??o
	if (tamanhoConteudo <= 800 && text.length > 63) {
		text = "..."+text.substr(text.length-63);
	}
	
	container = top.head.document.getElementById('folderLocate');
	container.innerHTML = text;
}

function refreshConteudo() {
	document.location.href = urlRefresh;
}

/*
 * Mostra ou esconde o menu
 */
function escondeMenu() {
	if (top.body.document.body.cols == "215,*") {		
		top.body.document.body.cols='0%,100%';
		top.head.document.getElementById("div_fechar_menu").innerHTML = "<img src=\""+contextoBackoffice+"/images/but_fechar_menu2.gif\" width=\"17\" height=\"26\" border=\"0\" alt=\"fechar o menu\">";
		top.head.document.getElementById("div_abrir_menu").innerHTML = "<a href=\"javascript:;\" onclick=\"escondeMenu()\"><img src=\""+contextoBackoffice+"/images/but_abrir_menu.gif\" width=\"17\" height=\"26\" border=\"0\" alt=\"abrir o menu\"></a>";
	}
	else if (top.body.document.body.cols == "0%,100%") {
		top.body.document.body.cols='215,*';
		top.head.document.getElementById("div_fechar_menu").innerHTML = "<a href=\"javascript:;\" onclick=\"escondeMenu()\"><img src=\""+contextoBackoffice+"/images/but_fechar_menu.gif\" width=\"17\" height=\"26\" border=\"0\" alt=\"fechar o menu\"></a>";
		top.head.document.getElementById("div_abrir_menu").innerHTML = "<img src=\""+contextoBackoffice+"/images/but_abrir_menu2.gif\" width=\"17\" height=\"26\" border=\"0\" alt=\"abrir o menu\">";
	}
}

function mudarEstadoDivHide(node,div_id){

	obj = document.getElementById(div_id);

	if (obj.style.display == 'none') {
		obj.style.display = 'block';
		node.childNodes.item(0).src = getImgDirectoryDiv(node.childNodes.item(0).src) + "minus.gif";
	}else {
		obj.style.display = 'none';
		node.childNodes.item(0).src = getImgDirectoryDiv(node.childNodes.item(0).src) + "plus.gif";
	}
}

function getImgDirectoryDiv(source) {
    return source.substring(0, source.lastIndexOf('/') + 1);
}

// Pega a tecla digitada
function pegaTecla(evento) {
	if(navigator.appName == "Microsoft Internet Explorer") {
		eventChooser = event.keyCode;
	} else {
		eventChooser = evento.which;
	}

	return eventChooser;
}

//valida o tipo de tecla pressionada se o campo for do tipo texto
function validarTeclaCampo(codigoTecla, objetoCampo) {
	if ((objetoCampo.getAttribute("readonly") != null || objetoCampo.getAttribute("readonly") != undefined) && objetoCampo.getAttribute("readonly") != false) {
		return false;
	}
	else if ((objetoCampo.type == 'text' || objetoCampo.type == 'textarea') && !( (codigoTecla >= 48 && codigoTecla <= 125) || codigoTecla == 8 || codigoTecla == 32) ) {
		return false;
	}
	else {
		return true;
	}
}

var janelaPreview;
function abrirPopUpPreview(url) {
	janelaPreview = window.open(url,'popupPreview','left=20,top=20,width=795,height=450,toolbar=0,resizable=1');
	janelaPreview.focus();
}

function openNewWindow(url, target, width, height,status, scroll) {

	window.open(url, target, 'width=' + width + ', height=' + height + ', status=' + status + ', scrollbars=' +scroll + ', resizable=no,top='+((window.screen.height/2)-(height/2))+',left='+((window.screen.width/2)-(width/2)));
}

function openNewWindowDefault(url, target) {
	openNewWindow(url, target, 800, 600);
}

//exibe a ajuda para cada campo do formul?rio
function exibirAjuda(nomeFormulario, objCampo) {
	keyAjuda = nomeFormulario + '.' + objCampo.name + '.ajuda';

	setContextHelp(property[keyAjuda]);
}

function getScrolling() {
    var x = 0; var y = 0;
    if (document.body && document.body.scrollLeft && !isNaN(document.body.scrollLeft)) {
        x = document.body.scrollLeft;
    } else if (window.pageXOffset && !isNaN(window.pageXOffset)) {
        x = window.pageXOffset;
    }
    if (document.body && document.body.scrollTop && !isNaN(document.body.scrollTop)) {
        y = document.body.scrollTop;
    } else if (window.pageYOffset && !isNaN(window.pageYOffset)) {
        y = window.pageYOffset;
    }
    return x + "," + y;
}
function manterLinhaSelecionada(tableId, idRowSelecionado) {
    var table = document.getElementById(tableId);
    if (table == null)
    	return false;
    var tbody = table.getElementsByTagName("tbody")[0];
    var rows = tbody.getElementsByTagName("tr");
    
    // da um loop em todas as linhas procurando o idRow que tenha o idRowSelecionado
    for (i=0; i < rows.length; i++) {

    	var cells = rows[i].getElementsByTagName("td");
    	if (cells[0].getElementsByTagName("idRow").length > 0) {
    		idRow = cells[0].getElementsByTagName("idRow")[0];
    		
    		if (idRow.getAttribute("id") == idRowSelecionado) {
    			rows[i].className+=' over';
    		}
    	} 	
    }
}
function mudarEstadoImgEDivHide(img_id, div_id) {
	obj_div = document.getElementById(div_id);
	obj_img = document.getElementById(img_id);

	if (obj_div.style.display == 'none') {
		obj_div.style.display = 'block';
		obj_img.src = getImgDirectoryDiv(obj_img.src) + "minus.gif";
	}else {
		obj_div.style.display = 'none';
		obj_img.src = getImgDirectoryDiv(obj_img.src) + "plus.gif";
	}
}





function alterar(url){
		document.location.href=url;
}

function incluir(url){
		window.location=url;
}

function submitExcluir(){
	if(confirm('Excluir o(s) Registro(s) Selecionado(s)')){
		document.forms[0].submit();
	}
}

function voltar(){
	window.history.back();
}

function verificaQtd(tamanho,input,qtd,e) {
  	var campo = input;
  	var qtde = qtd;
  	var str = "";
  	var contEnter = 0;
	
	for (i=0; i<campo.value.length; i++) {
		str = campo.value[i];
		if (str == '\n')
		contEnter++;
	}
	if ( ((campo.value.length) + contEnter) >= tamanho) {
		campo.value = campo.value.substring(0,tamanho-contEnter);
		tamanho = 0;
	}else {	
		tamanho = (tamanho - campo.value.length) - (contEnter);    
	}
	
    /*try {
		if (e.keyCode) key = e.keyCode;
		else if (e.which) key = e.which;
	    if ( key == 13) {
		     tamanho = tamanho - 3;
	    }
    }
    catch (e) {}*/
    qtde.value = tamanho;
}


// Permite digitar apenas numeros
function ENumero(tecla)
{
  var digito = pegaTecla(tecla);
  if (((digito) > 47) && ((digito) < 58))
      return true ;
   else 
      return caracterControle(digito); 
}

// Pega a tecla digitada
function pegaTecla(evento) {
	if(navigator.appName == "Microsoft Internet Explorer") {
		eventChooser = event.keyCode;
	} else {
		eventChooser = evento.which;
	}

	return eventChooser;
}

function ENumeroLetra(tecla)
{
  var digito = pegaTecla(tecla);
  if ( (digito>47 && digito<58) || (digito>64 && digito<91) || (digito>96 && digito<123))
      return true ;
   else 
      return caracterControle(digito); 
}

//valida o tipo de tecla pressionada se o campo for do tipo texto
function validarTeclaCampo(codigoTecla, objetoCampo) {
	if ((objetoCampo.getAttribute("readonly") != null || objetoCampo.getAttribute("readonly") != undefined) && objetoCampo.getAttribute("readonly") != false) {
		return false;
	}
	else if ((objetoCampo.type == 'text' || objetoCampo.type == 'textarea') && !( ( ((codigoTecla >= 48 && codigoTecla <= 111) || (codigoTecla >= 124 && codigoTecla <= 200)) && codigoTecla != 144 && codigoTecla != 145) || codigoTecla == 8 || codigoTecla == 32) ) {
		return false;
	}
	else {
		return true;
	}
}

function caracterControle(digito){
  if (digito == 0 || digito == 8 || digito == 13)
    return true;
  else
    return false;
}

// Permite digitar apenas numeros e virgula
function EDecimal(tecla)
{
  var digito = pegaTecla(tecla);
  if ((((digito) > 47) && ((digito) < 58)) || (digito == 44) )
      return true ;
   else 
      return caracterControle(digito); 
}

// Formata moeda
// onkeypress="return formataMoeda(this,event);" onkeydown="backSpaceMoeda(this,event);"
function formataMoeda(ConteudoCampo,tecla)
{
 var digito = pegaTecla(tecla);
	if ((ConteudoCampo.value.length >= ConteudoCampo.maxLength && ConteudoCampo.maxLength != -1)&&!caracterControle(digito)) {
		return false;
	}
	if (((digito) > 47) && ((digito) < 58))
	{
	   NumDig = ConteudoCampo.value;
	   TamDig = NumDig.length;
	   Contador = 0;
	   if (TamDig > 1)
	      {numer = "";
	      for (i = TamDig; (i >= 0); i--){
	          if ((parseInt(NumDig.substr(i,1))>=0) && (parseInt(NumDig.substr(i, 1))<=9))
	            {
	             Contador++;
	             if ((Contador == 2) && ((TamDig -i) < 4))
	              {numer = ","+numer;
	               Contador = 0;
	               }
	             else if (Contador == 3)
	              {//numer = "."+numer;
	               Contador = 0;
	              }
	             numer = NumDig.substr(i, 1)+numer;
	            }
	           }
	      ConteudoCampo.value = numer;
	      };
	   if (TamDig >= 2){
 	   NumDig = ConteudoCampo.value;
	   	if (parseInt(NumDig.substr(0,1)) == 0 && NumDig.substr(1,1) != 44) {
	   		NumDig = NumDig.substr(2,NumDig.length-1);
	   	}
	   }   
	   return(true);
	}
	else return caracterControle(digito);
}
// usa em conjunto com FormataMoeda
function backSpaceMoeda(dado,tecla)
{
   var digito = pegaTecla(tecla);
   NumDig = dado.value;
   TamDig = NumDig.length;
   //TamDig--;
   Contador = 0;
   if ((TamDig >= 0) && (digito == 8))
    { numer = "";
      for (i = TamDig; (i >= 0); i--){
          if ((NumDig.substr(i, 1) == '-') || ((parseInt(NumDig.substr(i,1))>=0) && (parseInt(NumDig.substr(i, 1))<=9)))
            {
             Contador++;
			 //alert(NumDig.substr(i, 1) + " Contador " + Contador+ " numer "+ numer+ " TamDig " +TamDig + " i " + i );
             if ((Contador == 4) && ((TamDig -i) < 5))
              {
              	numer = ","+numer;
               Contador = 0;
               }
             else if ((Contador == 3) && ((numer.length) > 4))  
              {
              	//numer = "."+numer;
               Contador = 0;
              }
             numer = NumDig.substr(i, 1)+numer;
			
            }
			}
			if (numer == "000") 
			    numer="";		
			if ((numer.length) == 3 )
			    numer= "0," + numer;

		if (numer.indexOf('-') > 0){
			numer = numer.replace('-','') + '0';			
		}
		dado.value = numer;
      };
    return true;
}
