// JavaScript Document
if (navigator.cookieEnabled == 0) {
  alert("Seu browser não tem cookies habilitado.\n Por favor habilite este recurso para navegar no site corretamente.");
}


 /* Função utilizada para deixar frases e palavras com Cap Init
  * Recebe 4 parametros
  * stringEntrada = string a ser tranformada
  * excL
  *
 */

function capInit(stringEntrada, excL, excU, excN){    
    if(stringEntrada == '' || stringEntrada == null )
        return stringEntrada;
        
    var strSaida="";
    var palavras = stringEntrada.split(" ");
    var i;
   
    for(i = 0; i < palavras.length; i++){        
       if(i > 0){
          strSaida += " " + capInitAux(palavras[i], excL, excU, excN);
       }else{
          strSaida += capInitAux(palavras[i], excL, excU, excN);
       }
    }
                  
    return strSaida;
}

function capInitAux(stringEntrada, excL, excU, excN){
    var i;
    var pos;
    
    //excessoes minusculas
    if(excL){
        var excessoes = ["da", "de", "di", "do", "du", "d'", "para", "ao"];
        for(i = 0; i < excessoes.length; i++){
            if(stringEntrada.toLowerCase() == excessoes[i]){
                return excessoes[i];
            }
        }   
     }
    
    //excessoes maiusculas         
    if(excU){
        var excessoesUpper = ["CEP:","CEP", "AC", "AL", "AP", "AM", "BA", "CE", "DF", "ES", "GO", "MA", "MT", "MS", "MG", "PA", "PB", "PR", "PE", "PI", "RJ", "RN", "RS", "RO", "RR", "SC", "SP", "SE", "TO"];        
        for(i = 0; i < excessoesUpper.length; i++){
            if(stringEntrada.toUpperCase() == excessoesUpper[i]){
                return excessoesUpper[i];
            }
        }    
    }
    
    //formatacao numérica
    if(excN){        
        var re = new RegExp("[^0-9]");
        if(!stringEntrada.match(re)){            
            switch(stringEntrada.length){
                 //CEP
                case 8 : {return  stringEntrada.substring(0, 5) + "-" + stringEntrada.substring(5);}
                //CPF
                case 11 :{ return  stringEntrada.substring(0, 3) + "." + stringEntrada.substring(3, 7) + "." + stringEntrada.substring(7, 10) + "-" + stringEntrada.substring(10) ;}
                //CNPJ             
                case 14 :{ return  stringEntrada.substring(0, 2) + "." + stringEntrada.substring(2, 5) + "." + stringEntrada.substring(5, 9) + "/" + stringEntrada.substring(9, 13) + "-" + stringEntrada.substring(13) ;}
            }
        }
    }   
    
    return stringEntrada.charAt(0).toUpperCase() + stringEntrada.substring(1).toLowerCase();
}

// função informa a posicao no array de um determinado elemento
// retorna -1 se não encontrar
function localizaElemento(paramArray, paramElemento ){

    if(paramArray == undefined || paramArray == "" || paramArray == null || paramArray.length == 0 )
        return -1;
    
    if(paramElemento == undefined || paramElemento == "" || paramElemento == null )
        return -1;
    
    for(i=0; i < paramArray.length; i++){
        if(paramArray[i] == paramElemento)
            return i;        
    }
}
  

//Faz somatorio em serviços opcionais
function somaPasseios(){

    var valor = 0;
    var cont = 1;
    var nomeValor = "valorPasseio" + cont;
    var nomeCheck = "checkbox" + cont;

    var val = document.getElementById(nomeValor);
    var check = document.getElementById(nomeCheck);

    while (val != undefined){
        if(check.checked == true){
           if(val.value != "" && !isNaN(val.value)){
              valor = parseFloat(valor) + parseFloat(val.value);
           }
        }

        var cont = cont + 1;
        var nomeValor = "valorPasseio" + cont;
        var nomeCheck = "checkbox" + cont;

        var val = document.getElementById(nomeValor);
        var check = document.getElementById(nomeCheck);
    }
    
    var objTotal = document.getElementById("totalPasseio");
    if(isNaN(valor)){
       valor = 0;
    }
    objTotal.value = valor;
}
// Retorno o Size da Página
// Editado para o FireFox.
function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

//
// Retorno o Scroll da Página.
// Com Hacks para o IE.
function getPageScroll(){

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}

//Define o div no meio da Página.
function visualizarParm(elemento){
// Os valores de tamanho do objeto no CSS não podem estar como AUTO.
var arrayPageSize = getPageSize();
var arrayPageScroll = getPageScroll();
var objLoadingImage = document.getElementById(elemento);
if (objLoadingImage) {
        //objLoadingImage.style.top = (arrayPageScroll[1] + ((arrayPageSize[3] - 35 - (getStyle(elemento,"height")).replace("px","")) / 2) + 'px'); 
        //objLoadingImage.style.left = (((arrayPageSize[0] - 20 - (getStyle(elemento,"width")).replace("px","")) / 2) + 'px');
        objLoadingImage.style.top = (arrayPageScroll[1] + ((arrayPageSize[3] - (getStyle(elemento,"height")).replace("px","")) / 2) + 'px'); 
        objLoadingImage.style.left = (((arrayPageSize[0]  - (getStyle(elemento,"width")).replace("px","")) / 2) + 'px');
        
        objLoadingImage.style.display = 'block';
}

}

//Esta função retorna valores que estão definido no CSS.
function getStyle(el,styleProp)
{
	var x = document.getElementById(el);
	if (x.currentStyle)
		var y = x.currentStyle[styleProp];
	else if (window.getComputedStyle)
		var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
	return y;
}

function ocultarParm(elemento){
    //document.getElementById(elemento).style.visibility="hidden";
    document.getElementById(elemento).style.display="none";
}

function visualizar(){
    document.getElementById("divBoxAlt").style.display="block";
}

function ocultar(){
    document.getElementById("divBoxAlt").style.display="none";
}

//altera o conteudo de um layer.
function WriteLayer(ID,parentID,sText) {
 if (document.layers) {
   var oLayer;
   if(parentID){
     oLayer = eval('document.' + parentID + '.document.' + ID + '.document');
   }else{
     oLayer = document.layers[ID].document;
   }
   oLayer.open();
   oLayer.write(sText);
   oLayer.close();
 } else if (parseInt(navigator.appVersion)>=5 && navigator.appName=="Netscape") {
   document.getElementById(ID).innerHTML = sText;
 } else if (document.all) 
   document.all[ID].innerHTML = sText;
}

//esconde o id caso esteja sendo mostrado, se estiver escondido mostra-o.
function showHideExibe(id) {
    var obj = document.getElementById(id);
    if(obj.style.display == "none") {
        //obj.style.display = "block";
        show(id);
    } else {
        //obj.style.display = "none";
        hide(id);
    }
}
//
function show(id) {
    var obj = document.getElementById(id);
    if (obj != null) {
        obj.style.display = "block";
    }
}
//
function hide(id) {
    var obj = document.getElementById(id);
    if (obj != null) {
        obj.style.display = "none";
    }
}

function writeHTML(id, content) {
    document.getElementById(id).innerHTML=content;
}
//função utilitária para uso com o dwr ajax.
function objectEval(text) {
    // eval() breaks when we use it to get an object using the { a:42, b:'x' }
    // syntax because it thinks that { and } surround a block and not an object
    // So we wrap it in an array and extract the first element to get around
    // this.
    // This code is only needed for interpreting the parameter input fields,
    // so you can ignore this for normal use.
    // The regex = [start of line][whitespace]{[stuff]}[whitespace][end of line]
    text = text.replace(/\n/g, ' ');
    text = text.replace(/\r/g, ' ');
    if (text.match(/^\s*\{.*\}\s*$/))
    {
      text = '[' + text + '][0]';
    }
    return eval(text);
}


/***********************************************
* Textarea Maxlength script- © Dynamic Drive (www.dynamicdrive.com)
* This notice must stay intact for legal use.
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/

function ismaxlength(obj, msgId){
    var msg = $(msgId);
    var mlength = obj.getAttribute ? parseInt(obj.getAttribute("maxlength")) : "";
    if (obj.getAttribute && obj.value.length > mlength) {
        obj.value = obj.value.substring(0,mlength);
    } else {
	msg.value = mlength - obj.value.length;
    }
}

function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : evt.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
      return false;
    }
    return true;
}
/**************************************
 * FUNÇÕES UTILITÁRIAS PARA COOKIES
 *************************************/
 
 function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function abrePanoramica(name){
  tipo_arquivo = name.substring(name.length-3,name.length);
  //alert("tipo_arquivo = "+ tipo_arquivo);
  if(tipo_arquivo == 'ivp'){
   js_win_config = 'width=640,height=510,top=100,left=100,resizable=yes,scrollbars=no';
  }else{
   js_win_config = 'width=320,height=270,top=100,left=100,resizable=yes,scrollbars=no';
  }
  
  window.open('../_panoramica/panoramica.jsf?link='+ name,'Panoramica',js_win_config);
}

function FormataValor(id,tammax,teclapres) {
        if(window.event) { // Internet Explorer
         var tecla = teclapres.keyCode; 
	}
        else if(teclapres.which) { // Nestcape / firefox
         var tecla = teclapres.which;
        }    

	vr = document.getElementById(id).value;
	vr = vr.toString().replace( "/", "" );
	vr = vr.toString().replace( "/", "" );
	vr = vr.toString().replace( ",", "" );
	vr = vr.toString().replace( ".", "" );
	vr = vr.toString().replace( ".", "" );
	vr = vr.toString().replace( ".", "" );
	vr = vr.toString().replace( ".", "" );
	tam = vr.length;

	if (tam < tammax && tecla != 8){ tam = vr.length + 1; }
	
	if (tecla == 8 ){ tam = tam - 1; }
	
	if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
	if ( tam <= 2 ){
	    document.getElementById(id).value = vr; }
	if ( (tam > 2) && (tam <= 5) ){
	    document.getElementById(id).value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ); }
	if ( (tam >= 6) && (tam <= 8) ){
	    document.getElementById(id).value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ); }
	if ( (tam >= 9) && (tam <= 11) ){
	    document.getElementById(id).value = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ); }
	if ( (tam >= 12) && (tam <= 14) ){
	    document.getElementById(id).value = vr.substr( 0, tam - 11 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ); }
	if ( (tam >= 15) && (tam <= 17) ){
	    document.getElementById(id).value = vr.substr( 0, tam - 14 ) + '.' + vr.substr( tam - 14, 3 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam );}
	}
}


       function trocaImagemDestino(js_url_img, js_alt_img){
         var js_img_url_temp = js_url_img;
         var js_display = " ";
         // alert(js_img_url_temp.length);
         if (js_img_url_temp.substring((js_img_url_temp.length - 3), js_img_url_temp.length) == "swf" || js_img_url_temp.substring((js_img_url_temp.length - 3), js_img_url_temp.length) == "SWF" ){
           js_display = "<p><object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'  codebase='HTTP://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0'  width='605' height='200' VIEWASTEXT> <param name=movie value='";
           js_display =  js_display + js_url_img ;
           js_display =  js_display + "' width='605' height='200'><param name=quality value=high><PARAM NAME=wmode VALUE=transparent><embed src='";
           js_display =  js_display + js_url_img;
           js_display =  js_display + "' width='605' height='200'></embed> </object></p>";
         }
         else{
           js_display = "<img name='fotoBanner' id='fotoBanner' src='" + js_url_img +  "' alt='" + js_alt_img + "' />";
         }
         $("divMainDisplay").innerHTML = js_display;
         $("legendaFoto605x200").innerHTML = js_alt_img;
       }

       function loadFlash(js_url, js_w, js_h){
          document.write('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="' + js_w +  '" height="' + js_h + '">\n');
          document.write('<param name="movie" value="' + js_url + '" />\n');
          document.write('<param name="quality" value="high" />\n');
          document.write('<param name="wmode" value="transparent"/>\n');
          document.write('<embed src="' + js_url + '" wmode="transparent" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="'+ js_w + '" height="' + js_h + '"></embed>\n');
          document.write('</object>\n');
       }
       
       
        /**
         * Limita o tamanho de um textArea.
         * Utilizado nos formulários de Fale Conosco.
         */        
        function limitarTextArea(limite) {
            var corte = limite;
            var mensagem = document.getElementById('frm2:mensagem');
            var charCount = document.getElementById('frm2:charCount'); 
            if (mensagem.value.length > corte) {
                mensagem.value = mensagem.value.substring(0,corte);
            }
            charCount.value = corte - mensagem.value.length;
        }
        
/**
 * Monta Saudação para os usuário logados.
 * Atravès da leitura do cookie de usuário.
 */
 function loadSaudacao(nomeCookie, contexto) {
    var innerHTML = '';
    var nome = ""; 
    nome = readCookie(nomeCookie);
    //tratamento para ler cookie localmente
    if(nome == null || nome == "" || nome == "null" )
		nome = readCookie("$OC4J_ENCODED_" + nomeCookie);   
    nome = decodeURIComponent(nome);
    nome = decodeURIComponent(nome);
    
    //tratamento para substituir '+' por 'espaço'
    var i=0;
    for(i=0; i < nome.length; i++){
    	nome = nome.replace('+',' ');
    }
    
       
    if (nome == null || nome == "" || nome == "null" ) {
        innerHTML += '<a href="'+contexto+'/login.jsf">Olá!, clique e faça seu login</a>';
    } else {
        innerHTML += 'Olá, ';
        innerHTML += nome;
        innerHTML += '<br/>';
        innerHTML += '<a href="'+contexto+'/index.jsf?action=Login.logout">(Clique aqui para desconectar)</a>';
    }
    $("siteTopoSaudacao").innerHTML = innerHTML;
 }        
 
function verifica(){
    if(screen.availWidth > 1024){
                if(document.getElementById('divShop') != undefined){
                    document.getElementById('divShop').style.display = "block";
                }
                if(document.getElementById('divSuperGeral') != undefined){
                    if(document.body.offsetWidth < 1003){
                        document.getElementById('divSuperGeral').className = "divGeral1024";
                    }else{
                        document.getElementById('divSuperGeral').className = "divGeral1024Maior";
                    }
                }
                if(document.getElementById('divTopoBuscaHome') != undefined){
                    document.getElementById('divTopoBuscaHome').style.display = "none";
                }
    }else if(screen.availWidth == 1024){
                if(document.getElementById('divShop') != undefined){
                    document.getElementById('divShop').style.display = "block";
                }
                if(document.getElementById('divSuperGeral') != undefined){
                    document.getElementById('divSuperGeral').className = "divGeral1024";
                }
                if(document.getElementById('divTopoBuscaHome') != undefined){
                    document.getElementById('divTopoBuscaHome').style.display = "none";
                }
    }
    else{
                if(document.getElementById('divSuperGeral') != undefined){
                    document.getElementById('divSuperGeral').className = "divGeral775";
                }
                if(document.getElementById('divTopoBuscaHome') != undefined){
                    document.getElementById('divTopoBuscaHome').style.display = "block";
                }
    }
}

//formata para valor (999.999,00) o conteudo enviado por parametro
function FormataStringParaValor(valor) {

    valorFormatado = "";   
    var vr = "";
    vr = eval(valor.toFixed(2)).toString();
    //se nao tiver casas decimais incluo zeros depois da virgula
    if(vr.lastIndexOf(".") == -1 ){
        vr += ",00"
    }

    vr = vr.replace(",", "");
    vr = vr.replace(".", "");    
    tam = vr.length;



    if ( tam <= 2 ){
        valorFormatado = vr
    }
    if ( (tam > 2) && (tam <= 5) ){
        valorFormatado = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ); }

    if ( (tam >= 6) && (tam <= 8) ){
        valorFormatado = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ); }

    if ( (tam >= 9) && (tam <= 11) ){
        valorFormatado = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ); }

    if ( (tam >= 12) && (tam <= 14) ){
        valorFormatado = vr.substr( 0, tam - 11 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ); }

    if ( (tam >= 15) && (tam <= 17) ){
        valorFormatado = vr.substr( 0, tam - 14 ) + '.' + vr.substr( tam - 14, 3 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam );
    }


    return valorFormatado;
}


 /* 8  - Backspace
    9  - TAB
    35 - End    
    36 - Home
    37 - Seta Esquerda
    38 - Seta Acima
    39 - Seta Direita
    40 - Seta baixo
    45 - Insert
    46 - Delete    
*/
function controleTextArea(obj, event, qtLinhas, qtColunas, qtCaracter){
	//captura a tecla pressionada
	var tecla;			
	if(event && event.which){
		event = event;
		tecla = event.which;
	}
	else{
		event = event;
		tecla = event.keyCode;
	}

	if( (tecla != 8)  && (tecla != 9) && (tecla != 35) &&
	    (tecla != 36) && (tecla != 37) && (tecla != 38) && (tecla != 39) &&
		(tecla != 40) && (tecla != 45) && (tecla != 46) ){
		
		var textLimpo = obj.value.replace(/[\n\r\t]/g,"");
		var countCaracter = textLimpo.length + 1;	
		var text = obj.value.replace(/\s+$/g,"");
		var split = text.split("\n");		
		var countlines = split.length;
		
		//
		var myText = obj.value;
		while(myText.indexOf("\n") != -1){
			myText = myText.substr(myText.indexOf("\n") +1 , myText.length -1);
			
			/*var linha = myText.substr(0, myText.indexOf("\n") -1);
			
			if(linha.length > qtColunas -1){
				alert(linha.length);
				alert(linha);
				return false;
			}*/
		}
				
		//Faz a quebra de linha automatica	
		var resto = myText.length % qtColunas;
		if(resto == "0" && myText.length > "0"){
			obj.value = obj.value + "\n";
		}		
		
				
		//Caso seja inserido nova linha auto ou nao, soma mas um
		if(obj.value.charAt(obj.value.length-1) == "\n"){
			countlines = countlines + 1; 
		}
		
	
		//remover
		//document.getElementById("nomeDestinatario").value = countlines;
		//document.getElementById("emailDestinatario").value = countCaracter;
		

		if(countCaracter >= qtCaracter){
			alert("O número máximo de caracteres foi atingido.");
			return false;   
		}
		
		if((countlines > qtLinhas) || ((countlines == qtLinhas) && (tecla == 13) )){
		
			if(obj.value.charAt(obj.value.length-1) == "\n"){
				obj.value =  obj.value.substr(0 , obj.value.length -1);
			}
		
			alert("O número máximo de linhas foi atingido.");
			return false;   
		}	
	}
  

  /*
	// tratamento para o texto colado
	if((obj.value.length >= qtCaracter) && (window.event.type == 'paste')){
		var texto = obj.value;
		obj.value = "";
		obj.value = texto.slice(0, qtCaracter - 1);
	}*/
}