//verifica o browser
ns = (document.layers)? true:false;
ie = (document.all)? true:false;

var DivNameLoad='idCarregando'; /* identificação da DIV de loading */

function makeRequest(){
		
	var http_request = false;

    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/xml');
        }
    } else if (window.ActiveXObject) { // IE
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }
    
    if (!http_request) {
        return false;
    }
    
    return http_request;
}//fim da function


function ajaxRespost(DivID, URLparam, StrParam){
    
    var xmlhttp=makeRequest();
	var metodo='GET';
	
	if(!StrParam){StrParam=null;}	
    else{metodo='POST';}
    
    if(xmlhttp===false){
        alert('Giving up :( Cannot create an XMLHTTP instance');
        return false;
    }
    
    /*  */ 
    //showLoad();
    
    xmlhttp.open(metodo,URLparam, true);
    xmlhttp.onreadystatechange = function(){
	    
	    if (xmlhttp.readyState == 4 && xmlhttp.status==200) {
			// --- carrega o objt  --- //
	        //$(DivID).innerHTML = xmlhttp.responseText;
			$tid(DivID).innerHTML = xmlhttp.responseText;
			
			
	        
	       /*  */
	       //removeLoad();
	    }//fim do if
	}//fim da function onreadystatechange
	
	xmlhttp.setRequestHeader('Content-type' , 'application/x-www-form-urlencoded');
	xmlhttp.send(StrParam);
}//fim da function 


function ajaxRespostValue(DivID,URLparam,intParam,StrParam){
    
    var xmlhttp=makeRequest();
	var metodo='GET';

	if(!StrParam){StrParam=null;}	
    else{metodo='POST';}
    
    if(xmlhttp===false){
        alert('Giving up :( Cannot create an XMLHTTP instance');
        return false;
    }
    
    xmlhttp.open(metodo,URLparam, true);
    xmlhttp.onreadystatechange = function(){
	    if (xmlhttp.readyState == 4 && xmlhttp.status==200) {
			// --- carraga o objt
	        if(!intParam) {$(DivID).value = num2money(xmlhttp.responseText);}
	        else {$(DivID).value = xmlhttp.responseText;}
	    }//fim do if
	}//fim da function onreadystatechange
	
	xmlhttp.setRequestHeader('Content-type' , 'application/x-www-form-urlencoded');
  	xmlhttp.send(StrParam);
}//fim da function 

/* *********************************************************************
 * baseado no novo script de Bernardo Rufino  
 * ********************************************************************/
//Ajax=onnavigate("Ajax",function(data){ ajaxRespost('conteudo',data);})


/* ******************************************************************
 *  
 * ******************************************************************/
function limpar_div(ID,Valuehtml){
  var InnerTxt=' ';	

	if(Valuehtml){
		var InnerTxt=Valuehtml;
	}	
	if($(ID)){$(ID).innerHTML=InnerTxt;}
	
}

function EnterSubmit(event){
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    alert(keyCode);
    if ( keyCode == 13 ) {
       $('validateuser').submit();
    }
}


/* ******************************************************************
 * Imprime o conteudo de uma DIV 
 * ******************************************************************/
function enviaMail(DivID){
	
	if(!$('bnNomeRemetente').value){
		alert('Nome do remetente deve ser informado!');
		return false;
	}
	
	if(!checkMail($('bnEmailRemetente').value)){
		alert('Email do remetente deve ser informado ou não é válido!');
		return false;
	}

	if(!checkMail($('bnEmailDestinatario').value)){
		alert('Email do destinatário deve ser informado ou não é válido!');
		return false;
	}
	
	$('bnDivMsg').value=$(DivID).innerHTML;
	
	submit('sendmailto','includes/sendmail.php',document.frmSend);
	
	alert('email enviado!');
	limpar_div('sendmailto');
	
}//fim do function

/* ******************************************************************
 * Valida email 
 * ******************************************************************/
function checkMail(mail){
    var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);
    if(typeof(mail) == "string"){
        if(er.test(mail)){ return true; }
    }else if(typeof(mail) == "object"){
        if(er.test(mail.value)){
                    return true;
                }
    }else{
        return false;
        }
}

/* ************************************************************
 * fucao seleciona todos
 * ***********************************************************/
function CheckAll() {
	var val; 
	val = document.frm.checkall.checked; 
	dml = document.frm; 
	len = dml.elements.length; 
	var i=0;
	for(i=0;i<len;i++){
		dml.elements[i].checked=val;
	}
}

/** Cria uma div de loading como "Carregando ..." **/ 
function showLoad(){
	var body = $tag('body')[0];
	var div = document.createElement('div');
	div.setAttribute("id",DivNameLoad);
	body.appendChild(div);
	$(DivNameLoad).innerHTML="Carregando informações, por favor aguarde ...";
};

/** Remove a div de loading **/ 
function removeLoad() {
	var body = $tag('body')[0];
	var div = $(DivNameLoad);
	if (div){
		body.removeChild(div);
	}
};

function serialize(nv){
	var nv=function(e){
		if(e.name){
			return encodeURIComponent(e.name)+'='+encodeURIComponent(e.value);
		}else{ return '';}
	};
	var i=collect($tag('input'),function(i){
		if((i.type!='radio' && i.type!='checkbox') || i.checked) return nv(i);
	});
	var s=collect($tag('select'),nv);
	var t=collect($tag('textarea'),nv);
	return i.concat(s).concat(t).join('&');
};

/* fim da function serialize */ 
function submit(id,url,frm){
	ajaxRespost(id, url, serialize(frm));
};

function collect(a,f){
	var n=[];
	for (var i=0;i<a.length;i++){
		var v=f(a[i]);
		if(v!=null)n.push(v);
	}
	return n;
};

function $tag(e){
	if(typeof e=='string') {
		e=document.getElementsByTagName(e);
	}
	return e;
};

function $n(e){
	if(typeof e=='string') {
		e=document.getElementsByName(e);
	}
	return e;
};

function $tid(e){
	if(typeof e=='string') {
		e=document.getElementById(e);
	}
	return e;
};

 /*
########################################################################################
Formulários de Contato 
Funções javascript
########################################################################################
*/
function form_valido(err){
	var err = '';
	var er = /^[\w-]+(\.[\w-]+)*@(([A-Za-z\d][A-Za-z\d-]{0,61}[A-Za-z\d]\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
	var Teler = /^[(]{1}?([0-9]{2}[)]?)?[0-9]{3,4}\-?[0-9]{4}$/
	
	if(!document.getElementById('nome').value || document.getElementById('nome').value.length < 3 || !document.getElementById('nome').value.match(/^[a-zA-Z ]+$/)){		
		err += "- Nome: inválido \n";
	}	
	
	email = document.getElementById('correl').value;
	email_valid = er.exec(email);
	if(email.indexOf('@badesul.com.br')>-1 || !email_valid || !email){
		err += "- E-mail: não preenchido ou inválido. \n ";
	}
	
	fone = document.getElementById('fone').value;
	tel_valid = Teler.exec(fone);
	if(!tel_valid){
		err += "- Telefone: não preenchido ou inválido. \n";
	}
	
	if(!document.getElementById('cidade').value){
		err += "- Município: não preenchido. \n"
	}
	if(document.getElementById('assunto').selectedIndex <= 0){		
		err += "- Assunto: não selecionado. \n";
	}
	if(!document.getElementById('mensagem').value){
		err += "- Mensagem: não preenchida. \n"	
	}
	else if(document.getElementById('mensagem').value.length < 10){
		err += "- Favor preecher o campo Mensagem com no minímo de 10 caracteres. \n"	
	}
	return err;
}

function enviar(){				
 var valor, nome; 
 var input = new Array();  
 parametros = ''; 
 var erro  = form_valido(); 
  if(!erro){
	for(i=0;i< document.frmContato.length-2;i++){
		 valor = document.frmContato.elements[i].value;
		 nome = document.frmContato.elements[i].name;	 
		 input[i] = nome+'='+valor;		
	}	
	for(i=0;i< input.length;i++){
		parametros +=  input[i]+'&';
	}
	
		tam = parametros.length;
		parametros = parametros.slice(0,tam-1);		
		ajaxRespost('formulario','includes/resposta.php?'+parametros);
	}else{
		alert(erro);
	}	
}

 /*
########################################################################################
 :: Rede Fomento ::
Funções javascript
########################################################################################
*/
function abrePopUp(){
 	window.open("badesul/rede_fomento_caixars.htm","","width=580,height=480,scrollbars=1,resizable=1");
}

function abrePopUpConsultor(){
 	window.open("badesul/papelConsultor.htm","","width=580,height=480,scrollbars=1,resizable=1");
}
function mudaSelect(){
	var cod = document.getElementById('corede').value;	
	ajaxRespost('municip','includes/redefomento_aux.php?cod='+cod);
}

function redirMapa(cod){	
 		window.open("https://www1.badesul.com.br/crf/Consulta_Rede.asp?parm=0000000000"+cod);
}

function algumaSelecao(){	
	cod = document.getElementById('corede').value;
	num = document.getElementById('municipio').value;
	tipo = document.getElementById('tipo').value;

	if(cod!="00" || mun!="000000" || tipo!="00")
		window.open("https://www1.badesul.com.br/crf/Consulta_Rede.asp?parm="+cod+""+mun+""+tipo+"00");
	else
		alert("Favor selecionar itens para a pesquisa.");	
}

function switchMenu(obj) {
var el = document.getElementById(obj);
	
	 //firefox  el.previousElementSibling.previousElementSibling.firstChild.innerHTML;
	 //ie = el.previousSibling.previousSibling.firstChild.innerHTML
	 
	 var browser = navigator.appName;
		
	 if(browser == 'Netscape'){
		objS = el.previousElementSibling.previousElementSibling.firstChild;
	 }else{
		objS = el.previousSibling.previousSibling.firstChild
	 }
		
	 	
	if(objS.innerHTML == '-'){
		objS.innerHTML = '+';
	}else{
		objS.innerHTML = '-';
	}
	   
	
	if ( el.style.display != 'none' ) {
		el.style.display = 'none';		
	}
	else {
		el.style.display = '';
	}			
	
}

function sendURL(){
	if(arguments[1]) arguments[1] = document.getElementById(arguments[1]).value;
	window.parent.location = "index.php?"+arguments[0]+arguments[1];	
}
function buscar(){
	window.parent.location = "index.php?pg=39&busca="+document.getElementById('busca').value+'&item='+document.getElementById('item').value;
}



/* #################################################################
	Funções para destacar frases quando efetuado uma pesquisa
################################################################### */


function doHighlight(bodyText, searchTerm, highlightStartTag, highlightEndTag) 
{
  // defina aqui o padrão para highlightStartTag e highlightEndTag, caso não seja passado como parametro.
  if ((!highlightStartTag) || (!highlightEndTag)) {
    highlightStartTag = "<font style='color:black; background-color:yellow;'>";
    highlightEndTag = "</font>";
  }
  
  // find all occurences of the search term in the given text,
  // and add some "highlight" tags to them (we're not using a
  // regular expression search, because we want to filter out
  // matches that occur within HTML tags and script blocks, so
  // we have to do a little extra validation)
  var newText = "";
  var i = -1;
  var lcSearchTerm = searchTerm.toLowerCase();
  var lcBodyText = bodyText.toLowerCase();
    
  while (bodyText.length > 0) {
    i = lcBodyText.indexOf(lcSearchTerm, i+1);
    if (i < 0) {
      newText += bodyText;
      bodyText = "";
    } else {
      // skip anything inside an HTML tag
      if (bodyText.lastIndexOf(">", i) >= bodyText.lastIndexOf("<", i)) {
        // skip anything inside a <script> block
        if (lcBodyText.lastIndexOf("/script>", i) >= lcBodyText.lastIndexOf("<script", i)) {
          newText += bodyText.substring(0, i) + highlightStartTag + bodyText.substr(i, searchTerm.length) + highlightEndTag;
          bodyText = bodyText.substr(i + searchTerm.length);
          lcBodyText = bodyText.toLowerCase();
          i = -1;
        }
      }
    }
  }
  
  return newText;
}

/*	
	idObj = elemento html
	searchTerm = texto para procura
	treatAsPhrase = true para frase
	warnOnFailure = true para alertar caso o elemento html não seja encontrado
	textColor = cor da fonte 
	bgColor = cor de fundo
*/
function highlightSearchTerms(idObj,searchText, treatAsPhrase, warnOnFailure, textColor, bgColor){
  
  // se treatAsPhrase é true, então procura pela frase, caso contrário divide e procura pelas palavras individualmente
  
  if (treatAsPhrase) {
    searchArray = [searchText];
  } else {
    searchArray = searchText.split(" ");
  }
  
  // testa se o elemento html existe
  //if (!document.body || typeof(document.body.innerHTML) == "undefined") {
  if (!document.getElementById(idObj) || typeof(document.getElementById(idObj).innerHTML) == "undefined") {    
	if (warnOnFailure){
      alert("Sorry, for some reason the text of this page is unavailable. Searching will not work.");
    }
    return false;
  }
  
	// edite aqui a formatação da marcação
    highlightStartTag = "<font style='color:" + textColor + "; background-color:" + bgColor + ";'>";
	highlightEndTag = "</font>"; 
  
  //var bodyText = document.body.innerHTML;
  var bodyText = document.getElementById(idObj).innerHTML;
  for (var i = 0; i < searchArray.length; i++) {
    bodyText = doHighlight(bodyText, searchArray[i], highlightStartTag, highlightEndTag);
  }
  
  //document.body.innerHTML = bodyText;
  document.getElementById(idObj).innerHTML = bodyText;
  return true;
}



		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 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 expires = "";
		  document.cookie = name+"="+value+expires+"; path=/";
		}




