$(document).ready(function(){
//Galeria Facibox
	 try{
  	$(".imagefaci").fancybox({
	   'transitionIn'  :'elastic',
	   'transitionOut' :'elastic'
		}); 
		 }catch(e){
			 alert(e);
		}

});

function get(id) { 
	try { 
		var a = document.getElementById(id); 
	} catch(e) { 
		alert("Erro encontrado: "+e); 		
	} 
	return 	a;
}

function addFlash (file, width, height, id, wmode, bgcolor) {
	if(!wmode)
		wmode = false;

	var fo = new FlashObject(file, "notify", width, height, "9", bgcolor, true);
	fo.addParam("scale", "noscale");
	fo.addParam("wmode", "opaque");
	fo.useExpressInstall('expressinstall.swf');
	
	if(wmode == 'true')
		fo.addParam("wmode", "transparent");		
	fo.write(id);
}

//Limpa/Preenche os campos
function valueField (event, obj) {
	e = event.type;
	var obj = get(obj);
	
	if(!obj.save)
	{
		obj.save = obj.value;		
	}
	
	if(e=="blur")
	{
		if(obj.value=="")
		{
			obj.value = obj.save;
		}
	}
	else if(e=="focus")
	{
		if(obj.value=="")
		{
			obj.value = obj.save;
		}
		else if(obj.value==obj.save)
		{
			obj.value = "";
		}
	}
}

function abreGaleria (dir, id, atual)
{
	   var width = 640;
	   var height = 550;
	   var left = (screen.width - width)/2;
	   var top = (screen.height - height)/2;;   
	   var galeria = window.open('galeria.php?dir='+dir+'&id='+id+'&atual='+atual,'geleria', 'width='+width+', height='+height+', top='+top+', left='+left+', scrollbars=yes, status=no, toolbar=no, location=no, directories=no, menubar=no, resizable=no, fullscreen=no');
	   galeria.focus();
}
function abreGaleria2 (dir, id, atual)
{
	   var width = 986;
	   var height = 600;
	   var left = (screen.width - width)/2;
	   var top = (screen.height - height)/2;;   
	   var galeria = window.open('galeria2.php?dir='+dir+'&id='+id+'&atual='+atual,'geleria', 'width='+width+', height='+height+', top='+top+', left='+left+', scrollbars=yes, status=no, toolbar=no, location=no, directories=no, menubar=no, resizable=no, fullscreen=no');
	   galeria.focus();
}

function abrePop(src) {
   var width = 782;
   var height = 550;
   var left = (screen.width - width)/2;
   var top = (screen.height - height)/2;;  
   var janela = "";
   var src = src;
   var jan = window.open(src,janela, 'width='+width+', height='+height+', top='+top+', left='+left+', status=no, toolbar=no, location=no, directories=no, menubar=no, resizable=no, fullscreen=no');
   
   if(jan == false) {
   		alert("Desabilite seu bloqueador de popups");
   }
}

function abrePop2(src)
{
   var jan = window.open(src,'_blank');
   
   if(jan == false) {
   		alert("Desabilite seu bloqueador de popups");
   }
}


function validaEmail(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;
    }
}


var campos = Array("email","msg"); //"nome","cidade","estado","telefone",
var nomes = Array("E-mail","Mensagem"); //"Nome","Cidade","Estado","Telefone",
var expres = Array("o","a","o","o","o","a");

function val(i) {
	obj = get(campos[i]);
	if(obj.value=="") {
		get('erro_form').innerHTML = "<span style='color: red;'>"+nomes[i]+" inválid"+expres[i]+"!</span>";
		obj.focus();
		return false;
	}
	
	if(campos[i] == 'email')
	{
		if(!validaEmail(obj.value))
		{
			get('erro_form').innerHTML = "<span style='color: red;'>Este e-mail não esta correto!</span>";
			obj.focus();
			return false;
		}
	}
	
	return true;
}

function validaFormContato2() {
	for(i=0;i<campos.length;i++) {
		if(!val(i)) return false;
	}
	get('erro_form').innerHTML = "<span style='color: silver;'>enviando mensagem...</span>";
	get('form_contato').submit();
}

function abreVideo(id)
{
   var width = 620;
   var height = 616;
   var left = (screen.width - width)/2;
   var top = (screen.height - height)/2;;  
   var janela = "janela01";
   var src = src;
   var jan = window.open('videos.php?idB='+id,janela, 'width='+width+', height='+height+', top='+top+', left='+left+', scrollbars=no, status=no, toolbar=no, location=no, directories=no, menubar=no, resizable=no, fullscreen=no');
   jan.focus();
}

function abreVideo2(str, nome)
{
   var width = 620;
   var height = 400;
   var left = (screen.width - width)/2;
   var top = (screen.height - height)/2;;  
   var janela = "janela01";
   var src = src;
   var jan = window.open('videos2.php?str='+str + '&nome=' + nome ,janela, 'width='+width+', height='+height+', top='+top+', left='+left+', scrollbars=no, status=no, toolbar=no, location=no, directories=no, menubar=no, resizable=no, fullscreen=no');
   jan.focus();
}


function loadPage (pg, local, method)
{
	if(!method)
		method = 'GET';
	
	ajax.method = method;
	
	setTimeout(
		function () {
			ajax.loadContent(pg, local);
		}
	, 1);	
}


function abreCidade (id,sufix) {
	 var ele = document.getElementsByName("dvcidade"+sufix);
	 var obj = ele[ele.length-1];

	 var city = new Ajax();
     loadPage("getCidade.php?codigo="+id+"&sufix="+sufix,obj.id);
}

function abreCidade2 (id,sufix) {
	 var ele = document.getElementsByName("dvcidade2"+sufix);
	 var obj = ele[ele.length-1];

	 var city = new Ajax();
    loadPage("getCidade2.php?codigo="+id+"&sufix="+sufix,obj.id);
}

var counter = 0;
var html = "";

function addCampo () {

	var cont = document.createElement("div");
	cont.innerHTML = html;
	counter++;
	cont.id = "content"+counter;
	
	get("content_campos").appendChild(cont);

}

function remCampo () {
	if(counter >= 0)
	{
		var p = get('content'+counter).parentNode;
		p.removeChild(get('content'+counter));
	 
		counter--;
	}
}

function armazenaHTML () {
	html = get('content'+counter).innerHTML;
}

function FormataValor(id,tammax,teclapres) {
    var s = false;
	
	if(window.event) { // Internet Explorer
		var tecla = teclapres.keyCode; }
	else if(teclapres.which) { // Nestcape / firefox
		var tecla = teclapres.which;
	}
		
	var keychar = String.fromCharCode(tecla);
	
	
	if(!isNaN(parseInt(keychar))) {
		s = true;
	} 
	if(tecla == 8 || tecla == 13 || tecla == 32) {
		s = true;
	}
	
	if(s == true) {
	
		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 );}
		}
	
	}
	
	
	return s;
}

function validaEmail(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;
    }
}


function validaCPF(cpf) {
	
	erro = new String;
	if (cpf.length < 11) 
		erro += "Sao necessarios 11 digitos para verificacao do CPF! \n\n";
	
	
	cpf = cpf.replace(".","");
	cpf = cpf.replace(".","");
	cpf = cpf.replace("-","");
	
	var nonNumbers = /\D/;
	
	if (nonNumbers.test(cpf)) 
		erro += "A verificacao de CPF suporta apenas numeros! \n\n";
	
	if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999"){	
		erro += "Numero de CPF invalido!";
	}
	var a = [];
	var b = new Number;
	var c = 11;
	//
	for (i=0; i<11; i++){
	   a[i] = cpf.charAt(i);

	   if (i < 9) 
		   b += (a[i] * --c);
	}
	//
	if ((x = b % 11) < 2) { 
		a[9] = 0;
	} else { 
		a[9] = 11-x;
	}
	//
	b = 0;
	c = 11;
	//
	for (y=0; y<10; y++) 
		b += (a[y] * c--);
	//
	if ((x = b % 11) < 2) { 
		a[10] = 0; 
	} else { 
		a[10] = 11-x; 
	}
	//
	if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])){
		erro +="Número de CPF Inválido!";
	}
	//
	if (erro.length > 0){
		//alert(erro);
		return false;
	}
	return true;
}

function validaCaso (campo,tipo) {
	var error = "";
	switch(tipo) {
		case "string":
			if(campo.value.length < 2) {
				alert('Campo Incorreto');
				campo.focus();
				return false;
			}			
		break;
		
		case "fone":
			if(campo.value.length < 13) {
				alert('Digite seu telefone corretamente');
				campo.focus();
				return false;
			}							
		break;
		
		case "cpf":
			if(!validaCPF(campo.value)) {
				alert('Digite seu CPF corretamente');
				campo.focus();
				return false;
			}
		
		break;
		
		case "email":		
			if(!validaEmail(campo.value)) {
				alert('Digite seu e-mail corretamente');
				campo.focus();
				return false;
			}		
			
		break;
		
		case "select":
			if(campo.options[campo.selectedIndex].value == 0) {
				alert("Você deve selecionar um item");
				campo.focus();
				return false;				
			}				
				
		break;
		
		case "cep":
			if(campo.value.length < 9) {
				alert('Digite seu CEP corretamente');
				campo.focus();
				return false;
			}							
		break;
		default:
			return false;
		break;
	}
	alert('ok');
	return true;	
}

function valueRadio(name)
{
	var objs = document.getElementsByName(name);
	var aux = false;
	
	for(i=0; i < objs.length; i++)
	{
		if(objs[i].checked == true)
			aux = true;
	}
	
	return aux;
}

function validaForm (obj) {
	var formulario = get("form1");
	
	var camposOb = new Array ("end_imovel","nome","endereco","fone","cpf","estado","cep","email","pai","mae","rg","estado_emissor","num_profi");
	var tipos = new Array("string","string","string","fone","cpf","select","cep","email","string","string","string","string","string");
	
	var val = true;
	
	var a = null;
	
	for(a=0; a < camposOb.length; a++) {
	
		if(!validaCaso(get(camposOb[a]),tipos[a])) {
			val = false;
			break;		
		}	
	
	}
	
	if(val) {
		formulario.submit();
	}
}

function addEvent(obj, evType, fn)
{
    //
    if (obj.addEventListener)
    {
        obj.addEventListener(evType, fn, true);
        return true;
    }
    else if (obj.attachEvent)
    {
        var r = obj.attachEvent("on"+evType, fn);
        return r;
    }
    else
    {
        return false;
    }
}

//Limpa/Preenche os campos
function valueField (event, obj) {
	e = event.type;
	var obj = get(obj);
	
	if(!obj.save)
	{
		obj.save = obj.value;		
	}
	
	if(e=="blur")
	{
		if(obj.value=="")
		{
			obj.value = obj.save;
		}
	}
	else if(e=="focus")
	{
		if(obj.value=="")
		{
			obj.value = obj.save;
		}
		else if(obj.value==obj.save)
		{
			obj.value = "";
		}
	}
}

function validaCamposNewsletter()
{
	var nome  = get('n_nome');
	var email = get('n_email');
	
	if(nome.value == 'SEU NOME' || nome.value == '')
	{
		nome.focus();
		return false;
	}
	
	if(email.value == 'SEU EMAIL' || !validaEmail(email.value))
	{
		email.focus();
		return false;
	}
	
	return true;
}

function validaNewsletter()
{
	if(validaCamposNewsletter())
	{
		loadPage ('add_newsletter.php?nome='+get('n_nome').value+'&email='+get('n_email').value, 'div_newsletter', 'POST');
	}

}

var abas  = new Array();
var menus = new Array();

function setaAba(aba, obj)
{
	get(aba).style.cursor = 'pointer';
	
	obj.push(aba);
	
	get(aba).onclick = function ()
	{
		for(i = 0; i < obj.length; i++)
		{
			get('div_'+obj[i]).style.display = 'none';
			get(obj[i]).style.backgroundColor = 'white';
		}
		get('div_'+aba).style.display = 'block';
		get(aba).style.backgroundColor = '#44a1b0';
	}
}

function abaMenu(aba)
{
	obj = menus;
	
	for(i = 0; i < obj.length; i++)
	{
		get('div_'+obj[i]).style.display = 'none';
		get(obj[i]).style.backgroundColor = 'white';
	}
	get('div_'+aba).style.display = 'block';
	get(aba).style.backgroundColor = '#44a1b0';
}

function montaAbas()
{
	setaAba('aba1', abas);
	setaAba('aba2', abas);
	setaAba('aba3', abas);
	
	setaAba('menu1', menus);
	setaAba('menu2', menus);
	setaAba('menu3', menus);
	setaAba('menu4', menus);
	
	get('aba1').style.backgroundColor = '#44a1b0';
	get('menu1').style.backgroundColor = '#44a1b0';
}

 function findPosX(obj)
  {
    var curleft = 0;
    if(obj.offsetParent)
        while(1)
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
  }

  function findPosY(obj)
  {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
  }

function abreImagem(obj, img)
{
	get('carregador').style.display = 'block';
	get('carregador').style.left = findPosX(obj) + 5 +'px';
	get('carregador').style.top  = findPosY(obj) + 22 + 'px';

	var obj = get('imgGaleria');
	obj.src = img;

	obj.onload = function () {
		get('carregador').style.display = 'none';
	}
}

function ampliaFoto(obj, dir, id)
{
	var atual = obj.src;
	var parts = atual.split('/');

	abreGaleria(dir, id, parts[parts.length-1]);
}

function listaFotos(id, pg)
{
	loadPage('lista_fotos.php?idBanner='+id+'&pg='+pg, 'lista_fotos', 'POST');
}

function mudaPesquisa(obj)
{
	if(obj.value == 'locacao')
	{
		window.open('http://visitacaovirtual.suprisoft.com.br/QuickSearchsim.aspx?sigla=sim&wmodo=L', 'busca_rapida');
	} else {
		window.open('http://visitacao.samiweb.com.br/PesquisaRapidaSite.aspx?id=1', 'busca_rapida');	
	}
}

function trim(str) {
	return str.replace(/^\s+|\s+$/g,"");
}

function send(form_name){
	ajax.assincr = false;
	ajax.method = "POST";
	
	var res = ajax.loadResult(get(form_name).action+'?'+getFields(form_name));

	if(trim(res) == "true"){
		return true;
	}else{
		return false;
	}
}


function validaFormInfos()
{
	var campos = Array('info_nome', 'info_email', 'info_fone', 'info_msg', 'resposta_por');
	var tipos  = Array('string'	  , 'email'		, 'fone'	 , 'string'	 , 'radio');

	for(i=0; i < campos.length; i++)
	{
		if(tipos[i] != 'radio')
		{
			if(get(campos[i]).value.length <= 0)
			{
				alert('Campo Inválido');			
				get(campos[i]).focus();
				return false;
			}
		} else {			
			if(!valueRadio(campos[i]))
			{
				alert('Selecione uma Opção');
				return false;
			}
			else
				break;
		}
	}
	
	if(send('form_mais_info'))
	{
		alert('Dados Enviados com Sucesso');
		clear('form_mais_info');
	} else {
		alert('Erro ao enviar Dados');
	}
}

function validaAgendar()
{

	var campos = Array('ag_nome', 'ag_email', 'ag_telefone', 'dia_visita', 'mes_visita', 'ano_visita', 'horario_visita');
	var tipos  = Array('string'	, 'email'	, 'fone'	   , 'select'	 , 'select'	   , 'select', 	   'select');

	for(i=0; i < campos.length; i++)
	{
		if(tipos[i] != 'select')
		{
			if(get(campos[i]).value.length <= 0)
			{
				alert('Campo Inválido');			
				get(campos[i]).focus();
				return false;
			}
		} else {
			if(get(campos[i]).value == 0)
			{
				alert('Preencha a data e horário da visita corretamente.');
				return false;
			}
			else
				break;
		}
	}
	
	if(send('form_agendar_visita'))
	{
		alert('Dados Enviados com Sucesso');
		clear('form_agendar_visita');
	} else {
		alert('Erro ao enviar Dados');
	}
}

function formLigamos()
{
	if(get('nome').value.length < 1)
	{
		alert('Campo nome inválido');			
		get('nome').focus();
		return false;
	}
	
	if(get('telefone').value.length < 13)
	{
		alert('Campo telefone inválido');			
		get('telefone').focus();
		return false;
	}
	
	if(send('form_ligamos'))
	{
		alert('Dados Enviados com Sucesso');
		clear('form_ligamos');
	} else {
		alert('Erro ao enviar Dados');
	}
}

function filter(func, v){
	switch(func){
		case 'chars':
			v.replace(/\d/g,"") //Remove tudo o que não é Letra
		break;
		
		case 'chasUp':
			v=v.toUpperCase() //Maiúsculas
			v.replace(/\d/g,"") //Remove tudo o que não é Letra ->maiusculas
		break;
		
		case 'charsDown':
			v=v.toLowerCase() //Minusculas
			v.replace(/\d/g,"") //Remove tudo o que não é Letra ->minusculas
		break;
		
		case 'number':
			v.replace(/\D/g,"") //Remove tudo o que não é dígito
		break;
		
		case 'phone':
			//v=v.replace(/\D/g,"") //Remove tudo o que não é dígito
			//v=v.replace(/^(\d\d)(\d)/g,"($1) $2") //Coloca parênteses em volta dos dois primeiros dígitos
			//v=v.replace(/(\d{4})(\d)/,"$1-$2") //Coloca hífen entre o quarto e o quinto dígitos
			v=v.replace(/\D/g,"") //Remove tudo o que não é dígito
			v=v.replace(/^\d\d-(\d)/g,"($1) $2") //Coloca parênteses em volta dos dois primeiros dígitos
			v=v.replace(/(\d{4})(\d)/,"$1-$2") //Coloca hífen entre o quarto e o quinto dígitos
		break;
		
		case 'cpf':
			v=v.replace(/\D/g,"") //Remove tudo o que não é dígito
			v=v.replace(/(\d{3})(\d)/,"$1.$2") //Coloca um ponto entre o terceiro e o quarto dígitos
			v=v.replace(/(\d{3})(\d)/,"$1.$2") //Coloca um ponto entre o terceiro e o quarto dígitos
			//de novo (para o segundo bloco de números)
			v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2") //Coloca um hífen entre o terceiro e o quarto dígitos
		break;
		
		case 'cep':
			v=v.replace(/\D/g,"") //Remove tudo o que não é dígito
			v=v.replace(/^(\d{5})(\d)/,"$1-$2") //Esse é tão fácil que não merece explicações
		break;
		
		case 'cnpj':
			v=v.replace(/\D/g,"") //Remove tudo o que não é dígito
			v=v.replace(/^(\d{2})(\d)/,"$1.$2") //Coloca ponto entre o segundo e o terceiro dígitos
			v=v.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3") //Coloca ponto entre o quinto e o sexto dígitos
			v=v.replace(/\.(\d{3})(\d)/,".$1/$2") //Coloca uma barra entre o oitavo e o nono dígitos
			v=v.replace(/(\d{4})(\d)/,"$1-$2") //Coloca um hífen depois do bloco de quatro dígitos
		break;
		
		case 'romanos':
			v=v.toUpperCase() //Maiúsculas
			v=v.replace(/[^IVXLCDM]/g,"") //Remove tudo o que não for I, V, X, L, C, D ou M
			//Essa é complicada! Copiei daqui: http://www.diveintopython.org/refactoring/refactoring.html
			while(v.replace(/^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/,"")!="")
			v=v.replace(/.$/,"")
		break;
		
		case 'date':
			v=v.replace(/\D/g,"") //Remove tudo o que não é dígito
			v=v.replace(/(\d{2})(\d)/,"$1/$2") //Coloca um ponto entre o segundo e o terceiro dígitos
			v=v.replace(/(\d{2})(\d)/,"$1/$2") //Coloca um ponto entre o quarto e o quinto dígitos
			//v=v.replace(/^[0-3]?\d\/[01]?\d\/(\d{2}|\d{4})$/)
			v=v.replace(/^((0[1-9]|[12]\d)\-(0[1-9]|1[0-2])|30\-(0[13-9]|1[0-2])|31\-(0[13578]|1[02]))\-\d{4}$/)
			//v=v.replace(/^(0[1-9]|[012][0-9]|3[01])/\-(0[1-9]|1[012])/\-([12][0-9]{3})/,"")
		break;
		
		case 'time':
			//v=v.replace(/\D/g,"") //Remove tudo o que não é dígito
			v=v.replace(/(\d{2})(\d)/,"$1:$2") //Coloca dois ponto entre o segundo e o terceiro dígitos
			v=v.replace( (/[012][0-9]:[0-5][0-9]/), "")
			//if v.teste( (/[012][0-9]:[0-5][0-9]/);"certo";"errado")
		break;
	}
	return v;
}

//pega os dados de um form em forma de url
function getFields(f){
	if(get(f)){
		var url = new Array();
		for(i=0 ; i<get(f).elements.length ; i++){
			switch(get(f).elements[i].type){
				case 'submit':
				case 'button':
				case 'textarea':
				case 'password':
				case 'hidden':
					url[i] = get(f).elements[i].name+'='+escape(get(f).elements[i].value);
				case 'text':
					url[i] = get(f).elements[i].name+'='+escape(get(f).elements[i].value);
				break;
				case 'select-one':
					url[i] = get(f).elements[i].name+'='+get(f).elements[i].options[get(f).elements[i].selectedIndex].value;
				break;
				
				case 'radio':
					if(get(f).elements[i].checked==true)
					{
						url[i] = get(f).elements[i].name+'='+get(f).elements[i].value;
					}
				case 'checkbox':
					if(get(f).elements[i].checked == true){
						url[i] = get(f).elements[i].name+'='+get(f).elements[i].value;
					}
				break;
			}
		}

		return(url.join("&"));
	}
}



//tenta limpar todos os campos de um formulario
function clear(f){
	if(get(f)){
		for(i=0 ; i<get(f).elements.length ; i++){
			switch(get(f).elements[i].type){
				case 'textarea':
				case 'password':
				//case 'hidden':
				case 'text':
					get(f).elements[i].value = '';
				break;
				
				case 'select-one':
					get(f).elements[i].selectedIndex=0;
				break;
				
				case 'radio':
				case 'checkbox':
					get(f).elements[i].checked = false;
					//
				break;
			}
		}
	}
}

function subClientes() {
	var obj = get('sub-clientes');
	if(obj.style.display == 'none') {
		obj.style.display = 'block';
	} else {
		obj.style.display = 'none';	
	}
	return false;
}

function menuClientes(disp) {
	var obj = get('sub-clientes');
	obj.style.display = disp;
}

// FORMULARIO ALUGUE SEU IMOVEL

var campos_alugue = Array("nome","endereco","bairro","estado","email","telefone","celular","endereco2","bairro2","estado2","email2","telefone2","celular","tipo","dormitorio","suite","garagem","est","obs");
var nomes_alugue = Array("Nome","Endereço","Bairro","Estado","E-mail","Telefone","Celular","Endereço","Bairro","Estado","E-mail","Telefone","Celular","Tipo","Dormitório","Suite","Garagem","Est. Converv.","obs");
var expres_alugue = Array("o","a","o","o","o","o","o","a","o","o","o","o","o","a","o","o","o","o","o","a","o","o","o","o");

function val_alugue(i) {
	obj = get(campos_alugue[i]);
	if(obj.value=="") 
	{
		get('erro_alugue').innerHTML = "<span style='color: red;'>"+nomes_alugue[i]+" inválid"+expres_alugue[i]+"!</span>";
		obj.focus();
		return false;
	}
	
	if(campos_alugue[i] == 'email')
	{
		if(!validaEmail(obj.value))
		{
			get('erro_alugue').innerHTML = "<span style='color: red;'>Este e-mail não esta correto!</span>";
			obj.focus();
			return false;
		}
	}
	
	return true;
}

function validaFormContato() {
	for(i=0; i < campos_alugue.length;i++) {
		if(!val_alugue(i)) return false;
	}
	get('erro_alugue').innerHTML = "<span style='color: silver;'>enviando mensagem...</span>";
	get('form_alugue').submit();
}

//FORMULARIO AVALIACAO IMOVEL

var campos_a = Array("nome","endereco","bairro","residencial","email","tipo","ndormitorios","metragem","idade","posicao","solar");
var nomes_a = Array("Nome","Endereço","Bairro","Telefone","E-mail","Tipo","Nº Dormitórios","Metragem","Idade","Posicao","Orientação Solar");
var expres_a = Array("o","o","o","o","o","o","o","a","o","o","o");

function val_a(i) {
	obj = get(campos_a[i]);
	if(obj.value=="") 
	{
		get('erro_a').innerHTML = "<span style='color: red;'>"+nomes_a[i]+" inválid"+expres_a[i]+"!</span>";
		obj.focus();
		return false;
	}
	
	if(campos_a[i] == 'email')
	{
		if(!validaEmail(obj.value))
		{
			get('erro_a').innerHTML = "<span style='color: red;'>Este e-mail não esta correto!</span>";
			obj.focus();
			return false;
		}
	}	
	return true;
}

function validaFormAvaliacao() {
	for(i=0; i < campos_a.length;i++) {
		if(!val_a(i)) return false;
	}
	get('erro_a').innerHTML = "<span style='color: silver;'>enviando mensagem...</span>";
	get('form_a').submit();
}

//PROPOSTA ADMINISTRACAO DE CONDOMINIO

var campos_c = Array("condominio","endereco","econ","tipo","condominio2","ap","sindico","adm","endereco_envio","fone_res","fone_cel","fone_com","email");
var nomes_c = Array("Nome condomínio","Endereço","Nº de Econ.","Tipo cond.","Nome Sindico","AP./Sl ...","Sindico","Adm","Endereco para Envio","Fone Res.","Fone Cel.","Fone Com.","E-mail");
var expres_c = Array("o","o","o","o","o","o","o","a","o","o","o","o");

function val_c(i) 
{	
	obj = get(campos_c[i]);

	if(obj.value=="") 
	{
		get('erro_c').innerHTML = "<span style='color: red;'>"+nomes_c[i]+" inválid"+expres_c[i]+"!</span>";
		obj.focus();
		return false;
	}
	
	if(campos_c[i] == 'email')
	{
		if(!validaEmail(obj.value))
		{
			get('erro_c').innerHTML = "<span style='color: red;'>Este e-mail não esta correto!</span>";
			obj.focus();
			return false;
		}
	}	
	return true;
}

function validaFormCondominio() {
	for(i=0; i < campos_c.length;i++) {
		if(!val_c(i)) return false;
	}
	get('erro_c').innerHTML = "<span style='color: silver;'>enviando mensagem...</span>";
	get('form_c').submit();
}

function animMenu(id,size)
{
	obj = "#" + id;
	
	$(obj).hover(
		function()
		{
			$(this).stop().animate({ height: 35}, 300);
		},		
		function()
		{
			$(this).stop().animate({ height: size }, 400);
		}
	);

}

var Utils = {
	
	pop:function(pagina, janela, width, height) {
	   var left = (screen.width - width)/2;
	   var top = (screen.height - height)/2;;   
	   var janela = window.open(pagina,janela, 'width='+width+', height='+height+', top='+top+', left='+left+', scrollbars=yes, status=no, toolbar=no, location=no, directories=no, menubar=no, resizable=no, fullscreen=no');
	   janela.focus();
	},
	
	getPageSize:function() {
		var xScroll, yScroll;
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = window.innerWidth + window.scrollMaxX;
			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
			if(document.documentElement.clientWidth){
				windowWidth = document.documentElement.clientWidth; 
			} else {
				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 = xScroll;		
		} else {
			pageWidth = windowWidth;
		}
		arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
		return arrayPageSize;
	},
	
	getPageScroll:function () {
		var xScroll, yScroll;
		if (self.pageYOffset) {
			yScroll = self.pageYOffset;
			xScroll = self.pageXOffset;
		} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
			yScroll = document.documentElement.scrollTop;
			xScroll = document.documentElement.scrollLeft;
		} else if (document.body) {// all other Explorers
			yScroll = document.body.scrollTop;
			xScroll = document.body.scrollLeft;	
		}
		arrayPageScroll = new Array(xScroll,yScroll);
		return arrayPageScroll;
	},
	
	resizeWindow:function(width, height, mode) {
		var arrPageSizes = Utils.getPageSize();
		var arrPageScroll = Utils.getPageScroll();		
		
		if(!mode) { mode = 'fast'; }
		
		$('#utils-window-content,#utils-window-content-ajax').animate({
			width: width,
			height: height
		}, mode);		
	},
	
	openWindow:function(pagina, params, wWindow, hWindow) {
		if(!params) { params = {}; }
		if(!wWindow) { wWindow = 500; }
		if(!hWindow) { hWindow = 450; }
		
		/* HTML		
		<div id="utils-window">
			<div id="utils-window-background"></div>
			<div id="utils-window-content">
				<div id="utils-window-loading"><img src="images/loading.gif"/></div>
				<div id="utils-window-content-ajax"></div>
			</div>
		</div>
		*/
		
		if($('#utils-window').length > 0) {
			$('#utils-window').remove();
		}		
		$('body').append('<div id="utils-window"><div id="utils-window-background"></div><div id="utils-window-content"><div id="utils-window-content-bg"><div id="utils-window-close"><img src="images/fechar.gif"></div><div id="utils-window-loading"><img src="images/loading.gif"/></div><div id="utils-window-content-ajax"></div></div></div></div>');
		
		var arrPageSizes = Utils.getPageSize();
		$('#utils-window-background').css({
			opacity:'0.5',
			display:'block',
			width: arrPageSizes[0],
			height: arrPageSizes[1]
		});
		
		$('#utils-window-content-ajax').css({
			width: wWindow,
			height: hWindow
		});

		var arrPageScroll = Utils.getPageScroll();		
		var heightContentWindow = $('#utils-window-content').height()/2;
		var widthContentWindow = $('#utils-window-content').width()/2;

		$('#utils-window-content').css({
			top: (arrPageSizes[3]/2 + arrPageScroll[1]) - heightContentWindow,
			left: (arrPageSizes[2]/2 + arrPageScroll[0]) - widthContentWindow
		});

		$('#utils-window-background').fadeIn();
		setTimeout( function() { $('#utils-window-content').fadeIn(); }, 100);
		setTimeout(
			function() {
				$('#utils-window-content-ajax').load(pagina, params, function() {
					$('#utils-window-loading').hide();
					$('#utils-window-content').animate({
						top: (arrPageSizes[3]/2 + arrPageScroll[1]) - hWindow/ 2,
						left: (arrPageSizes[2]/2 + arrPageScroll[0]) - wWindow/2,
						width: wWindow,
						height: hWindow
					}, '', 'swing', function() { $('#utils-window-content-ajax').fadeIn(); });										
				});
			},
		400);
		$('#utils-window-background,#utils-window-close').click(function() { Utils.closeWindow() });
	},
	
	closeWindow:function() {
		$('#utils-window-content').fadeOut('fast');
		setTimeout(function() { $('#utils-window-background').fadeOut('fast'); }, 150);
	}
}

function loadFotos(pg,codigo)
{
	if(!pg)
	{
		pg = 0;	
	}
	
	$.ajax(
	{
	   url: 'galeria.ajax.php',
	   type:'POST',
	   data: { codigo:codigo, pg:pg },
	   dataType: 'html',
	   success: function (data) {		   
		   $('#lancamentos_fotos').html(data);
	   }
	});	
	
	 $('#lancamentos_fotos').show();
	 $('#texto_principal').show();	 
}

function imageGaleria (path,codigo)
{
	$('#imagem_grande').load(function () {
		$(this).fadeIn();
		//$("#loading").hide();
	}).error(function () {
		// notify the user that the image could not be loaded
	}).attr('src', path);
	
	$('#texto_principal').html($('#texto_galeria' + codigo).html());
	
	
	$('#tabela_lancamentos').html('tb_passos2');
	
	$('#atual_lancamentos').html(codigo);
	
}

function changeText(id)
{
	$('#main-text').html($('#' + id).html());
	
}

function changeTitulo(id)
{
	$('#main-titulo').html($('#' + id).html());
}

function loadFotos2(pg,codigo)
{
	if(!pg)
	{
		pg = 0;	
	}
	
	$.ajax(
	{
	   url: 'plantas.ajax.php',
	   type:'POST',
	   data: { codigo:codigo, pg:pg },
	   dataType: 'html',
	   success: function (data) {		   
		   $('#lancamentos_fotos').html(data);
	   }
	});	
	
	$('#lancamentos_fotos').show();
	$('#texto_principal').hide();
}

function imageGaleria2 (path,codigo)
{
	$('#imagem_grande').load(function () {
		$(this).fadeIn();
		//$("#loading").hide();
	}).error(function () {
		// notify the user that the image could not be loaded
	}).attr('src', path);
	
	$('#tabela_lancamentos').html('tb_plantas');
	$('#atual_lancamentos').html(codigo);
}

function openMenu(id,position)
{
	$('#' + id).show();
	
	//$('#' + id).css({'left':'300px'});	
}

function openMenu2(id,position)
{
	$('#' + id).hide();
	
	//$('#' + id).css({'left':'300px'});	
}

function showContent(id,id2,num)
{
	hideAll();
	
	var obj = "#" + id;
	var obj2 = "#" + id2;
	
	$(obj2).show();
	$(obj).show();
}

function hideAll()
{
	$('#scroolContent').hide();	
	$('#info').hide();
	$('#ate').hide();	
	$('#age').hide();	
	$('#lig').hide();
}

function abreGaleriaLancamentos (id)
{
	   var atual = $('#atual_lancamentos').html();
	   var dir = $('#tabela_lancamentos').html();
	   
	   var width = 640;
	   var height = 550;
	   var left = (screen.width - width)/2;
	   var top = (screen.height - height)/2;;   
	   var galeria = window.open('galeriaLancamentos.php?dir='+dir+'&id='+id+'&atual='+atual,'geleria', 'width='+width+', height='+height+', top='+top+', left='+left+', scrollbars=yes, status=no, toolbar=no, location=no, directories=no, menubar=no, resizable=no, fullscreen=no');
	   galeria.focus();
}
