// (1) coloca target _blank nos links onde tem rel external (serve para validar site no W3C)
// (2) formata Campo CNPJ
// (3) formata Telefone
// (4) formata CEP
// (5) valida CNPJ
// (6) verifica se o CAPS LOCK do usuário está ligado
// (7) seleciona TODAS as CIDADES de acordo com o ESTADO
// (8) seleciona as CIDADES cadastradas no BANCO DE DADOS de acordo com o ESTADO
// (9) seleciona TODOS os BAIRROS de acordo com a CIDADE
// (10) seleciona os BAIRROS cadastradas no BANCO DE DADOS de acordo com a CIDADE
// (11) 
// (12) seleciona bairro na pesquisa simples e avançada
// (13) ativa menu selecionada
// (14) ativa ABA selecionada
// (15) esconde e mostra conteúdo da DIV
// (16) verifica dominio se está disponivel
// (17) conta clique após usuário clica em cima da logo da imobiliária
// (18) verifica se o login já existe ao criar um novo usuário para o FLEXImob
// (19) no cadastro de imobiliária verifica se existe PASTA para o pré domínio
// (20) no cadastro verifica se pré-domínio está disponível no BD de imobiliária
// (21) insere novo voto na enquete
// (22) 
// (23) verifica se algum input do tipo RADIO está selecionado
// (24) máscara
// (25) remove caracter ESPAÇO
// (26) bloqueia caracter ESPAÇO

// (1) coloca target _blank nos links onde tem rel external (serve para validar site no W3C)
function externalLinks() {
 if (!document.getElementsByTagName) return;
 var anchors = document.getElementsByTagName("a");
 for (var i=0; i<anchors.length; i++) {
   var anchor = anchors[i];
   if (anchor.getAttribute("href") &&
       anchor.getAttribute("rel") == "external")
     anchor.target = "_blank";
 }
}

// (2) formata Campo CNPJ
function FormataCNPJ(Campo, teclapres)
{

   if(window.event){
    var tecla = teclapres.keyCode;
   }else  tecla = teclapres.which;

   var vr = new String(Campo.value);
   vr = vr.replace(".", "");
   vr = vr.replace(".", "");
   vr = vr.replace("/", "");
   vr = vr.replace("-", "");

   tam = vr.length + 1;

  
   if (tecla != 9 && tecla != 8){
      if (tam > 2 && tam < 6)
         Campo.value = vr.substr(0, 2) + '.' + vr.substr(2, tam);
      if (tam >= 6 && tam < 9)
         Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,tam-5);
      if (tam >= 9 && tam < 13)
         Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,tam-8);
      if (tam >= 13 && tam < 15)
         Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,4)+ '-' + vr.substr(12,tam-12);
      }
}

// (3) formata Telefone
function FormataFone(Campo, teclapres)
{

   if(window.event){
    var tecla = teclapres.keyCode;
   }else  tecla = teclapres.which;

   var vr = new String(Campo.value);
   vr = vr.replace(".", "");
   vr = vr.replace(".", "");
   vr = vr.replace("/", "");
   vr = vr.replace("-", "");

   tam = vr.length + 1;

  
   if (tecla != 9 && tecla != 8){
      if (tam > 4 )
         Campo.value = vr.substr(0, 4) + '-' + vr.substr(4,tam-4);
      }
}

// (4) formata CEP
function FormataCEP(Campo, teclapres)
{

   if(window.event){
    var tecla = teclapres.keyCode;
   }else  tecla = teclapres.which;

   var vr = new String(Campo.value);
   vr = vr.replace(".", "");
   vr = vr.replace(".", "");
   vr = vr.replace("/", "");
   vr = vr.replace("-", "");

   tam = vr.length + 1;

  
   if (tecla != 9 && tecla != 8){
      if (tam > 2 ) 
         Campo.value = vr.substr(0, 2) + '.' + vr.substr(2,tam);
      if (tam > 6 )
         Campo.value = vr.substr(0, 2) + '.' + vr.substr(2, 3) + '-' + vr.substr(5,tam-5);
   }
}

// (5) valida CNPJ
function validaCNPJ() 
{
	CNPJ = document.getElementById('ecnpj').value;
	erro = new String;
	if (CNPJ.length < 18) erro += "CNPJ inválido! \n\n";
	if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
		if (erro.length == 0) erro += "CNPJ inválido! \n\n";
	}
	//substituir os caracteres que nao sao numeros
	if(document.layers && parseInt(navigator.appVersion) == 4){
		x = CNPJ.substring(0,2);
		x += CNPJ.substring(3,6);
		x += CNPJ.substring(7,10);
		x += CNPJ.substring(11,15);
		x += CNPJ.substring(16,18);
		CNPJ = x;
	} else {
		CNPJ = CNPJ.replace(".","");
		CNPJ = CNPJ.replace(".","");
		CNPJ = CNPJ.replace("-","");
		CNPJ = CNPJ.replace("/","");
	}
	var nonNumbers = /\D/;
	if (nonNumbers.test(CNPJ)) erro += "A verificacao de CNPJ suporta apenas numeros! \n\n";
		var a = [];
		var b = new Number;
		var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
		for (i=0; i<12; i++){
		a[i] = CNPJ.charAt(i);
		b += a[i] * c[i+1];
	}
	if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
		b = 0;
		for (y=0; y<13; y++) {
		b += (a[y] * c[y]);
	}
	if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
	if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
		erro +="CNPJ - Digito verificador com problema!";
	}
	if (erro.length > 0){
		alert(erro);
		return false;
	} else {
		return true;
	}
}

// (6) verifica se o CAPS LOCK DO USUÁRIO ESTÁ LIGADO
function checar_caps_lock(ev)
{
    var e = ev || window.event;
    codigo_tecla = e.keyCode?e.keyCode:e.which;
    tecla_shift = e.shiftKey?e.shiftKey:((codigo_tecla == 16)?true:false);
    if(((codigo_tecla >= 65 && codigo_tecla <= 90) && !tecla_shift) || ((codigo_tecla >= 97 && codigo_tecla <= 122) && tecla_shift)) {
        document.getElementById('aviso_caps_lock').style.visibility = 'visible';
            }
    else {
        document.getElementById('aviso_caps_lock').style.visibility = 'hidden';
    }
}

// (7) seleciona TODAS as cidades de acordo com o estado
function selecionaCidadeCompleto(sigla)
{
	if(sigla)
	{
		// inicia o ajax
		var ajax = criaAJAX(); 
	
		//aponta arquivo
		ajax.open("GET", "selecionaCidadesCompleto.php?vsigla="+ sigla, true); 
		
		ajax.onreadystatechange = function(){
			
			if(ajax.readyState == 1) {
			
				document.getElementById('mostraCidades').innerHTML = '<select name="ecidade" class="form_field" id="ecidade"><option value="0">Carregando...</option></select>';
			
			}
			// Quando estiver tudo pronto.
			if(ajax.readyState == 4)
			{ 
				if(ajax.status == 200){
					
					document.getElementById('mostraCidades').innerHTML = ajax.responseText;
				} else alert("erro")
			
			} 
	
		}
		//submete dados ao servidor
		ajax.send(null); 
	}

}

// (8) seleciona as cidades cadastradas no BD de acordo com o estado
function selecionaCidade(sigla)
{
	if(sigla)
	{
		// inicia o ajax
		var ajax = criaAJAX(); 
	
		//aponta arquivo
		ajax.open("GET", "selecionaCidades.php?vsigla="+ sigla, true); 
		
		ajax.onreadystatechange = function(){
			
			if(ajax.readyState == 1) {
			
				document.getElementById('mostraCidades').innerHTML = '<select name="ecidade" class="form_field" id="ecidade"><option value="0">Carregando...</option></select>';
			
			}
			// Quando estiver tudo pronto.
			if(ajax.readyState == 4)
			{ 
				if(ajax.status == 200){
					
					document.getElementById('mostraCidades').innerHTML = ajax.responseText;
				} else alert("erro")
			
			} 
	
		}
		//submete dados ao servidor
		ajax.send(null); 
	}

}


// (15) esconde e mostra conteúdo da DIV
function escondeElemento(id) { document.getElementById(id).style.display = 'none'; }
function mostraElemento(id) { document.getElementById(id).style.display = 'block'; }


// (18) verifica se o login já existe ao criar um novo usuário para o FLEXImob
function verificaLogin(login)
{
		
	if(login)
	{
		// inicia o ajax
		var ajax = criaAJAX(); 
	
		//aponta arquivo
		ajax.open("GET", "verificaLogin.php?vlogin="+ login, true); 
		
		ajax.onreadystatechange = function(){
			
			if(ajax.readyState == 1) {
			
				document.getElementById('mostraLogin').innerHTML = '&nbsp; &nbsp; Carregando...';
			
			}
			// Quando estiver tudo pronto.
			if(ajax.readyState == 4)
			{ 
				if(ajax.status == 200){
					
					document.getElementById('mostraLogin').innerHTML = ajax.responseText;
					
				} else alert("erro")
			
			} 
	
		}
		//submete dados ao servidor
		ajax.send(null); 
	}

}



// (20) no cadastro verifica se pré-domínio está disponível no BD de imobiliária
function verificaPreDominio(preDominio)
{
		
	if(preDominio)
	{
		// inicia o ajax
		var ajax = criaAJAX(); 
	
		//aponta arquivo
		ajax.open("GET", "verificaPreDominio.php?vdominio="+ preDominio, true); 
		
		ajax.onreadystatechange = function(){
			
			if(ajax.readyState == 1) {
			
				document.getElementById('mostraPreDominio').innerHTML = '&nbsp; &nbsp; Carregando...';
			
			}
			// Quando estiver tudo pronto.
			if(ajax.readyState == 4)
			{ 
				if(ajax.status == 200){
					
					document.getElementById('mostraPreDominio').innerHTML = ajax.responseText;
					
				} else alert("erro");
			
			} 
	
		}
		//submete dados ao servidor
		ajax.send(null); 
	}

}




// (25) remove caracter ESPAÇO
function removeEspacos(valor){
var valorSemEspacos="";

var tamanho = valor.length;
	for (i = 0; i<30;i++){
		if(valor.substr(i,1)==" "){
		}else{
		valorSemEspacos = valorSemEspacos + valor.substr(i,1);
		}
	}
return valorSemEspacos;
}

// (26) bloqueia caracter ESPAÇO
function bloqueiaEspaco(tecla, elemento){
	
	keyascii = tecla.keyCode;
	
	if (keyascii == 32){	
		elemento.value = elemento.value.replace(" " ,"");
		alert("Não é permitido usar espaço no login! Por favor, preencha corretamente.");
	}
}






$(document).ready(function(){
						   
	$('#irTop').click(function(){$('#top').ScrollTo(1000);return false});
		
}); //close doc ready



//////////////////// scroll by jquery ////////////////////////////////////////////////////////////////////////////
jQuery.getPos = function (e)
{
	var l = 0;
	var t  = 0;
	var w = jQuery.intval(jQuery.css(e,'width'));
	var h = jQuery.intval(jQuery.css(e,'height'));
	var wb = e.offsetWidth;
	var hb = e.offsetHeight;
	while (e.offsetParent){
		l += e.offsetLeft + (e.currentStyle?jQuery.intval(e.currentStyle.borderLeftWidth):0);
		t += e.offsetTop  + (e.currentStyle?jQuery.intval(e.currentStyle.borderTopWidth):0);
		e = e.offsetParent;
	}
	l += e.offsetLeft + (e.currentStyle?jQuery.intval(e.currentStyle.borderLeftWidth):0);
	t  += e.offsetTop  + (e.currentStyle?jQuery.intval(e.currentStyle.borderTopWidth):0);
	return {x:l, y:t, w:w, h:h, wb:wb, hb:hb};
};
jQuery.getClient = function(e)
{
	if (e) {
		w = e.clientWidth;
		h = e.clientHeight;
	} else {
		w = (window.innerWidth) ? window.innerWidth : (document.documentElement && document.documentElement.clientWidth) ? document.documentElement.clientWidth : document.body.offsetWidth;
		h = (window.innerHeight) ? window.innerHeight : (document.documentElement && document.documentElement.clientHeight) ? document.documentElement.clientHeight : document.body.offsetHeight;
	}
	return {w:w,h:h};
};
jQuery.getScroll = function (e) 
{
	if (e) {
		t = e.scrollTop;
		l = e.scrollLeft;
		w = e.scrollWidth;
		h = e.scrollHeight;
	} else  {
		if (document.documentElement && document.documentElement.scrollTop) {
			t = document.documentElement.scrollTop;
			l = document.documentElement.scrollLeft;
			w = document.documentElement.scrollWidth;
			h = document.documentElement.scrollHeight;
		} else if (document.body) {
			t = document.body.scrollTop;
			l = document.body.scrollLeft;
			w = document.body.scrollWidth;
			h = document.body.scrollHeight;
		}
	}
	return { t: t, l: l, w: w, h: h };
};

jQuery.intval = function (v)
{
	v = parseInt(v);
	return isNaN(v) ? 0 : v;
};

jQuery.fn.ScrollTo = function(s) {
	o = jQuery.speed(s);
	return this.each(function(){
		new jQuery.fx.ScrollTo(this, o);
	});
};

jQuery.fx.ScrollTo = function (e, o)
{
	var z = this;
	z.o = o;
	z.e = e;
	z.p = jQuery.getPos(e);
	z.s = jQuery.getScroll();
	z.clear = function(){clearInterval(z.timer);z.timer=null};
	z.t=(new Date).getTime();
	z.step = function(){
		var t = (new Date).getTime();
		var p = (t - z.t) / z.o.duration;
		if (t >= z.o.duration+z.t) {
			z.clear();
			setTimeout(function(){z.scroll(z.p.y, z.p.x)},13);
		} else {
			st = ((-Math.cos(p*Math.PI)/2) + 0.5) * (z.p.y-z.s.t) + z.s.t;
			sl = ((-Math.cos(p*Math.PI)/2) + 0.5) * (z.p.x-z.s.l) + z.s.l;
			z.scroll(st, sl);
		}
	};
	z.scroll = function (t, l){window.scrollTo(l, t)};
	z.timer=setInterval(function(){z.step();},13);
};

