// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

/* Antes de utilizar o Application:
 *
 * 1. Verificar se a(s) função(ões) que se deseja implementar já não existe no
 * prototype.
 * 
 * 2. Verificar se essa(s) função(ões) será global ou se será usada em casos
 * específicos, para decidir se será incluída no Application, se precisará de
 * um arquivo javascript a parte, ou se poderá ser incluída diretamente no html.
 * 
 * */

if(typeof LightboxOptions != 'undefined'){
  LightboxOptions.fileLoadingImage = '/images/default/loading.gif';
  LightboxOptions.fileBottomNavCloseImage = '/images/default/closelabel.gif';
}

var Browser = {
	detect: function() {
    var UA = navigator.userAgent;
   	this.isKHTML = /Konqueror|Safari|KHTML/.test(UA);
		this.isGecko = (/Gecko/.test(UA) && !this.isKHTML);
		this.isOpera = /Opera/.test(UA);
		this.isMSIE  = (/MSIE/.test(UA) && !this.isOpera);
		this.isMSIE7 = this.isMSIE && !(/MSIE 6\./.test(UA) && !this.isOpera);
    //Adicionado por Quickfast ------------------------------------------------/
		this.isMSIE6 = (/MSIE 6\./.test(UA) && !this.isOpera &&
      !(/MSIE 7\./.test(UA)) && !(/MSIE 8\./.test(UA)));
    // ------------------------------------------------------------------------/
	}
}
Browser.detect();

function isNumberKey(evt) {
  var charCode = (evt.which) ? evt.which : event.keyCode
  if (charCode > 31 && (charCode < 48 || charCode > 57))
    return false;
    return true;
}	
	
function popupscroll(url, largura, altura){
   var nWind; 
   nWind = window.open(url, '_blank',
     'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=no, width='+largura+',height='+altura);
}
function popup(url, largura, altura){
   window.open(url,'popup','width='+largura+',height='+altura+',toolbar=no,location=no,status=no,resizable=no,scrolling=auto,top=0,left=0');
}
function showlightbox2(page, width, height){
	Vcentro = (document.body.clientHeight / 2) - (height / 2) + document.body.scrollTop;
	Hcentro = (document.body.clientWidth / 2) - (width / 2);
	document.getElementById('lightbox_googlemaps').className = 'lightboxshow';	
	document.getElementById('boxConteudo').style.visibility = '';	
	document.getElementById('boxConteudo').style.display='block';
	document.getElementById('boxConteudo').style.top = Vcentro;
	document.getElementById('boxConteudo').style.left = Hcentro;
	document.getElementById('boxConteudo').style.width = width;
	document.getElementById('boxConteudo').style.height = height;	
	document.getElementById('iframePage').width = width;
	document.getElementById('iframePage').height = height;
	document.getElementById('iframePage').src = page;	
}
function HideLightBox(){
	Vcentro = 0;
	Hcentro = 0;
	document.getElementById('lightbox_googlemaps').className = 'lightboxhide';	
	document.getElementById('boxConteudo').style.visibility = 'hidden';
	document.getElementById('iframePage').width = 0;
	document.getElementById('iframePage').height = 0;
	document.getElementById('iframePage').src = '';
}

/////ALTERNAR ENTRE BLOCOS/////////////////////////////////////////////////
var
	numeroblocos;
function changeblock(bloco){
	nblocos = new Array(numeroblocos+1);
	for (i=1; i<=numeroblocos; i++){
		nblocos[i] = "none";
	}
	nblocos[bloco] = "block";
	for (i=1; i<=numeroblocos; i++){
		document.getElementById("block_id"+i).style.display = nblocos[i];
	}
}

///// COMBO_LIST_CHECK_BOX /////////////////////////////////////////////////
var ComboListCheckBox = Class.create({
  initialize: function(id){
    this.id = id;
    this.valores = new Array();
    document.observe('mousedown',function(e){
      var elemento = Event.element(e);
      if(!elemento.descendantOf(id) && $$('#'+id+' .clcb_caixa')[0].visible()){
        $$('#'+id+' .clcb_caixa')[0].hide();
        $$('#'+id+' input[type=checkbox]').each(function(i){ i.checked = false; });
        if(eval(id).valores.size() != 0){
          eval(id).valores.each(function(i){
            $$('#'+id+' input[type=checkbox][value='+i+']')[0].checked = true;
          });
        }
      }
    });
  },
  alternar: function(){
    $$('#'+this.id+' .clcb_caixa')[0].toggle();
  },
  setValue: function(){
    var id = this.id;
    var valores = this.valores;
    valores.clear();
    $$('#'+id+' .clcb_caixa input[type=checkbox]').each(function(i){
      if(i.checked) valores.push(i.value);
    });
  },
  value: function(){
    var id = this.id;
    var valores = new Array;
    this.valores.each(function(item){
      valores.push('pesquisar['+id+'][]='+item);
    });
    return valores.join('&');
  }
});

///// MÁSCARAS //////////////////////////////////////
function mascara(mask,campo){
  var numero = $(campo).value.match(/\d/g);
  var n = 0, i = 0, valor = '';
  mask = mask.toArray();
  if(numero){
    while(numero[n] && i < mask.length){
      if(mask[i] == 'x'){
        valor = valor + numero[n];
        n++;
      } else {
        valor = valor + mask[i];
      }
      i++;
    }
  }
  $(campo).value = valor;
}

///// ANEXOS /////////////////////////////////////////////////
function arquivo_anexar(bloco, authenticity_token){

  var hidden_frame = document.createElement('iframe');
  hidden_frame.id = "hidden_frame";
  hidden_frame.name = "hidden_frame";
  hidden_frame.width = "0";
  hidden_frame.height = "0";
  hidden_frame.scrolling = "no";
  hidden_frame.setStyle({border:"0px"});
  document.body.appendChild(hidden_frame);

  var at = document.createElement('input');
  at.type = 'hidden';
  at.name = 'authenticity_token';
  at.value = authenticity_token;

  var form = document.createElement('form');
  form.id = "form_anexar";
  form.style.display = "none";
  form.action = '/imovels/arquivo_anexar';
  form.method = 'post';
  form.enctype = 'multipart/form-data';
  form.target = 'hidden_frame';
  form.appendChild(at);
  document.body.appendChild(form);

  var arquivo = $$("#"+bloco+" input")[0];
  arquivo.hide();
  arquivo.id = "arquivo";
  arquivo.name = "arquivo";

  var carregando = $$("#"+bloco+" img")[0];
  carregando.show();

  var novo_campo = document.createElement('input');
  novo_campo.type = 'file';
  novo_campo.setStyle({display:"none"});

  var anexo_bloco = document.createElement('input');
  anexo_bloco.type = "hidden";
  anexo_bloco.value = bloco;
  anexo_bloco.name = "anexo_bloco";
  anexo_bloco.id = "anexo_bloco";

  form.insert(arquivo);
  form.insert(anexo_bloco);
  $(bloco).insert({top:novo_campo});

  form.submit();

}

// Abas      =>  classe das abas.
// blocos    =>  classe dos blocos que irão alternar.
// posicacao =>  posicao da aba e do bloco.
function alternar_aba(abas,blocos,posicao){
  abas = $$("."+abas);
	blocos = $$("."+blocos);
	posicao -= 1;
  abas.without(abas[posicao]).each(function(i){
		if(i.hasClassName('aba_ativa')){
			i.removeClassName('aba_ativa');
			abas[posicao].addClassName('aba_ativa');
		}
	});
	blocos.without(blocos[posicao]).each(function(i){
	  if(i.visible()){
			i.fade({duration:0.1});
			blocos[posicao].appear({delay:0.05});
		}
	});
}

function apresentacao(){
	var itens = $$('.apresentacoes_itens');
	var links = $$('#apresentacao_seletor a');
	var slide, posicao;
	itens.each(function(item){
		if(item.visible()){
			slide = item;
			posicao = itens.indexOf(item);
		}
	});
	slide.fade();
	links[posicao].removeClassName('aba_ativa');
	if(itens.last() != slide){
		slide.next().appear();
		links[posicao].next().addClassName('aba_ativa');
	} else {
		itens.first().appear();
		links.first().addClassName('aba_ativa');
	}
}

function apresentacoes_play(){
	apresentacoes = new PeriodicalExecuter(function(){apresentacao()}, 7);
}

// Função para adicionar aos favoritos.
// Por enquanto funcina apenas em Firefox e IE.
function favoritosAdicionar(url, title){
  if (window.sidebar) window.sidebar.addPanel(title, url,"");
  else if (document.all) window.external.AddFavorite(url, title);
  else alert('O seu browser não suporta esta função.\n\n' +
    'Verifique qual o atalho utilizado para adicionar esta página aos ' +
    'seus favoritos.');
}

// Função para mostrar as horas. Atualiza um elemento de meio em meio segundo com a hora atual.
// O id do elemento a ser atualizado pode ser passado como parâmetro, mas, caso não se especifique,
// a função irá atualizar o elemento cujo id seja "relogio".
function horaAtual(id){
  if(id == undefined) id = 'relogio';
  var d = new Date();
  var h = d.getHours(), m = d.getMinutes(), s = d.getSeconds();
  if(m < 10) m = '0' + m;
  if(s < 10) s = '0' + s;
  var horas = h+':'+m+':'+s;
  $(id).update(horas);
  horaAtual.delay(0.5);
}

// Função que retorna  a data atual em português.
function dataAtual(){
  var d = new Date();
  var meses = ['janeiro', 'fevereiro', 'março', 'abril', 'maio', 'junho',
    'julho', 'agosto', 'setembro', 'outubro', 'novembro', 'dezembro'];
  return d.getUTCDate()+' de '+meses[d.getMonth()]+' de '+d.getFullYear();
}