function swapI(obj,focus){
	if(focus){
		if(obj.value == obj.attributes["label"].value){
			obj.value = "";
		}
	} else {
		if(obj.value.trim() == ""){
			obj.value = obj.attributes["label"].value;
		}
	}
}
function swapP(obj,focus){
	if(focus){
		var pass = document.getElementById(obj.attributes["parent"].value);
		if(pass){
			obj.innerHTML = "";
			pass.focus();
		}
	} else {
		if(obj.value == ""){
			var div = document.getElementById("div"+obj.id);
			if(div){
				div.innerHTML = obj.attributes["label"].value;
			}
		}
	}
}
function swapM(menu,show){
	var m = $('#div_'+menu);
	if(m){
		if(show){
			tmp_width = m.parent().width();
			if(menu == 'contato'){
				tmp_width += 30;
				m.css('margin-left','-15px');
			}
			tmp_width = tmp_width+'px';
			m.find('table.submenu').each(function (){
				$(this).css('width',tmp_width);
			});
			m.css('display','');
		} else {
			m.css('display','none');
		}
	}
}
function nossostelefones(){
	var p = new Popup(422,296);
	p.template = 2;
	p.overflow = 'hidden';
	p.open('../../inc/structure/nossostelefones.html');
}
//function moveBanner(action) {
//	clearTimeout(banner);
//
//	$$('div_banner_'+indicebanner).style.marginTop = '-50000px';
//	if (action == 'next') {
//		indicebanner++;
//		if (totalbanner <= indicebanner) {
//			indicebanner = 0;
//		}
//	} else {
//		indicebanner--;
//		if (indicebanner < 0) {
//			indicebanner = totalbanner-1;
//		}
//	}
//	$$('div_banner_'+indicebanner).style.marginTop = '0px';
//
//	banner = setTimeout("moveBanner('next')",7000);
//}
function loadCampo(tmp_idSelecionando,tmp_idcampo,tmp_rotina){
	resetSelect(tmp_idcampo);
	var a = new Ajax();
	a.onLoad = function(){
		//alert(this.html);
		var str = this.html;
		var campo = document.getElementById(tmp_idcampo);
		var arr = str.split("###");//separa por registro
		var arraux = new Array();

		if (str != '') {
			for(var x = 0; x < arr.length; x++){
				arraux = arr[x].split("...");

				addOption(campo,arraux[1],arraux[0]);
				if (arraux[0] == '') {
					campo.options[x+2].style.fontWeight = 'bold';
				}
			}
			campo.disabled = '';
		} else {
			addOption(campo,'Nenhum item encontrado','');
			campo.disabled = true;
		}
		$('#'+tmp_idcampo).msDropDown();
	}
	a.get('../../inc/routines/routines.php?action='+tmp_rotina+'&id_selecionado='+tmp_idSelecionando);
}
function resetSelect(tmp_idcmapo){
	var campo = document.getElementById(tmp_idcmapo);
	if(campo){
		var dis = campo.disabled;
		campo.disabled = '';
		for(var x=campo.length-1;x>=2;x--){
			campo.remove(x);
		}
		campo.disabled = dis;
	}
}
function addOption(obj_select,tmp_text,tmp_value){
	var option = document.createElement('option');
	option.value = tmp_value;
	option.text = tmp_text;

	try {//outros navegadores
		obj_select.add(option,null);
	} catch(ex) {//para IE
		obj_select.add(option);
	}
}
function loadImoveisHome(tmp_routine){
	var div = $$('div_imoveis_home');
	var tmp_id = $$('Loja_CMB0').value;
	if(div){
		div.innerHTML = '<div style="height:'+div.offsetHeight+'px;"><i>Carregando...</i></div>';
		var a = new Ajax();
		a.onLoad = function(){
			var div = $$('div_imoveis_home');
			if(div){
				div.innerHTML = this.html;
			}
		}
		a.get('../../inc/routines/routines.php?action='+tmp_routine+'&tmp_id='+tmp_id);
	}
}
function loadLancamentos(){
	loadImoveisHome('loadLancamentos');
	$$('tit_lancamentos').className = 'titulo';
	$$('tit_prontosparamorar').className = 'titTop_hover';
}
function loadProntosParaMorar(){
	loadImoveisHome('loadProntosParaMorar');
	$$('tit_lancamentos').className = 'titulo_hover';
	$$('tit_prontosparamorar').className = 'titTop';
}
function ligamosVoce(){
	var p = new Popup(347,272);
	p.template = 2;
	p.overflow = 'hidden';
	p.open('../../inc/structure/ligamosparavoce.php');
}

function contatoemail(tmp_codigo){
	var p = new Popup(440,245);
	p.template = 2;
	p.overflow = 'hidden';
	p.open('../../inc/structure/enviarporemail.php?tmp_codigo='+tmp_codigo);
}

function sendLigamos(){
	if(f.send('frmLigamos',true)){
		var a = new Ajax();
		a.onLoad = function() {
			this.runJS(this.html);
		}
		a.sendForm('frmLigamos');
	}
}
function sendPorEmail(){
	if(f.send('frmPorEmail',true)){
		var a = new Ajax();
		a.onLoad = function() {
			this.runJS(this.html);
		}
		a.sendForm('frmPorEmail');
	}
}
function getTipos(){
	var total = $$('detalhe_totaltipo').value;
	total++;total--;

	for(var x=0;x<total;x++){
		if($$('detalhe_tipo'+x).checked){
			return 'true';
		}
	}
	return '';
}
function getInfraestrutura(){
	var total = $$('detalhe_caracttotal').value;
	total++;total--;

	for(var x=0;x<total;x++){
		if($$('detalhe_caract'+x).checked){
			return 'true';
		}
	}
	return '';
}
function buscaDetalhada(tmp_buscar){
	if(tmp_buscar){
		var ok = false;
		var msg = 'Faço ao menos um filtro antes de fazer a busca.';
		var codigo = $$('Código _TXT0');
		var tipo = getTipos();
		var cidade = $$('Cidade2_CMB0');
		var bairro = $$('Bairro2_CMB0');
		var dormitorios = $$('Dormitório2_CMB0');
		var banheiros = $$('Banheiro_CMB0');
		var garagem = $$('Garagem2_CMB0');
		var valorDe = $$('De2_CMB0');
		var valorAte = $$('Até2_CMB0');
		var areaDe = $$('De3_CMB0');
		var areaAte = $$('Até3_CMB0');
		var infraestrutura = getInfraestrutura();

		if((codigo.value != '') && (codigo.value != codigo.defaultValue)){
			ok = true;
		}
		if(tipo != ''){
			ok = true;
		}
		if(cidade.value != ''){
			ok = true;
		}
		if(bairro.value != ''){
			ok = true;
		}
		if(dormitorios.value != ''){
			ok = true;
		}
		if(banheiros.value != ''){
			ok = true;
		}
		if(garagem.value != ''){
			ok = true;
		}
		if(valorDe.value != ''){
			ok = true;
		}
		if(valorAte.value != ''){
			ok = true;
		}
		if(areaDe.value != ''){
			ok = true;
		}
		if(areaAte.value != ''){
			ok = true;
		}
		if(infraestrutura != ''){
			ok = true;
		}

		if(valorAte.selectedIndex < valorDe.selectedIndex){
			msg = 'Selecione os valores corretamente.';
			valorDe.focus();
			ok = false;
		}
		if(areaAte.selectedIndex < areaDe.selectedIndex){
			msg = 'Selecione a área corretamente.';
			areaDe.focus();
			ok = false;
		}

		if(ok){
			f.send('frmBuscaDetalhe');
		} else {
			alert(msg);
			codigo.focus();
		}
	} else {
		var p = new Popup(710,550);
		p.template = 2;
		p.overflow = '';
		p.position = 'fixed';
		p.open('../../inc/structure/buscadetalhe.php');
	}
}
function buscaTopo(){
	var ok = false;
	var msg = 'Faço ao menos um filtro antes de fazer a busca.';
	var codigo = $$('Código_TXT0');
	var tipo = $$('Tipo_CMB0');
	var cidade = $$('Cidade_CMB0');
	var bairro = $$('Bairro_CMB0');
	var dormitorios = $$('Dormitório_CMB0');
	var garagem = $$('Garagem_CMB0');
	var valorDe = $$('De_CMB0');
	var valorAte = $$('Até_CMB0');
	if((codigo.value != '') && (codigo.value != codigo.defaultValue)){
		ok = true;
	}
	if(tipo.value != ''){
		ok = true;
	}
	if(cidade.value != ''){
		ok = true;
	}
	if(bairro.value != ''){
		ok = true;
	}
	if(dormitorios.value != ''){
		ok = true;
	}
	if(garagem.value != ''){
		ok = true;
	}
	if(valorDe.value != ''){
		ok = true;
	}
	if(valorAte.value != ''){
		ok = true;
	}
	if(valorAte.selectedIndex < valorDe.selectedIndex){
		msg = 'Selecione os valores corretamente.';
		valorDe.focus();
		ok = false;
	}

	if(ok){
		if($$('frm_buscaLateral')){
			f.send('frm_buscaLateral');
		} else if($$('frm_buscaTopo')){
			f.send('frm_buscaTopo');
		}
	} else {
		alert(msg);
		codigo.focus();
	}
}
//verifica se já não está atualizando
var addingSelecao = false;
function addSelecao(tmp_codigo){
	$$('addSelecao').checked = true;
	$$('delSelecao').checked = true;
	if(!(addingSelecao)){
		addingSelecao = true;
		var a = new Ajax();
		a.onLoad = function() {
			with(parent){
				addingSelecao = false;
				$$('span_addSelecao').style.display = 'none';
				$$('span_delSelecao').style.display = 'block';
				//alert("Item adicionado com sucesso.\nPara visualizar sua lista clique em minha seleção.");
				$$('adicionadoPromptBox').style.display = 'block';
			}
		}
		a.get('../../inc/routines/routines.php?action=addSelecao&tmp_codigo='+tmp_codigo);
	} else {
		alert('Por favor aguarde a conclusão do processo...');
	}
}
function addSelecao2(obj_id, tmp_codigo){
	$$(obj_id).innerHTML = 'Adicionando...';
	var a = new Ajax();
	a.onLoad = function() {
		with(parent){
			$$(obj_id).innerHTML = '<a href="javascript: delSelecao2(\'adddel'+tmp_codigo+'\', \''+tmp_codigo+'\');">Excluir da minha seleção</a>';
		}
	}
	a.get('../../inc/routines/routines.php?action=addSelecao2&tmp_codigo='+tmp_codigo);
}
function delSelecao2(obj_id, tmp_codigo){
	$$(obj_id).innerHTML = 'Excluindo...';
	var a = new Ajax();
	a.onLoad = function() {
		with(parent){
			$$(obj_id).innerHTML = '<a href="javascript: addSelecao2(\'adddel'+tmp_codigo+'\', \''+tmp_codigo+'\');">Adicionar a minha seleção</a>';
		}
	}
	a.get('../../inc/routines/routines.php?action=delSelecao2&tmp_codigo='+tmp_codigo);
}
var dellingSelecao = false;
function delSelecao(tmp_codigo){
	$$('addSelecao').checked = false;
	$$('delSelecao').checked = false;
	if(!(dellingSelecao)){
		dellingSelecao = true;
		var a = new Ajax();
		a.onLoad = function() {
			with(parent){
				dellingSelecao = false;
				$$('span_addSelecao').style.display = 'block';
				$$('span_delSelecao').style.display = 'none';
			}
		}
		a.get('../../inc/routines/routines.php?action=delSelecao&tmp_codigo='+tmp_codigo);
	} else {
		alert('Por favor aguarde a conclusão do processo...');
	}
}
function pop(tmp_src,tmp_w,tmp_h){
	var p = new Popup(tmp_w,tmp_h);
	p.template = 1;
	p.overflow = 'hidden';
	p.position = 'fixed';
	p.open(tmp_src);
}
function loadAtual(tmp_id){
	if(tmp_id == ''){
		alert('Por favor, selecione uma cidade válida.');
	} else {
		window.location = '../home/?selectedLoja='+tmp_id;
		// if($$('tit_lancamentos').className == 'titulo'){//lancamentos selecionado
			// loadLancamentos();
		// } else {
			// loadProntosParaMorar();
		// }
	}
}
function openMe(obj){
	if(obj.className.indexOf('disable') == -1){
		//abre, não está desabilitado
		var inner = $$(obj.id+'_inner');
		if(inner.style.display == 'none'){
			inner.style.display = 'block';
		}
		else {
			 inner.style.display = 'none';
		}
	}
}
function loadBairro(tmp_idSelecionando,tmp_idcampo,tmp_rotina, onLoad){
	var campo = $$(tmp_idcampo);

	if(isMobile) {
		/* campo.style.height = '150px'; */
	}
	else {
		campo.className = 'select disable';
	}

	/* Clearing previous content */
	var inner = $$(tmp_idcampo+'_inner');
	if(inner) { /*it's not specified fro mobile version*/
		inner.innerHTML = '';
		inner.style.display = 'none';
	} else { /* mobile version has options */
		if(campo.options) {
			campo.options.length = 2;
		}
	}

	var total = $$(tmp_idcampo+'_total');
	total.value = 0;

	var a = new Ajax();
	a.onLoad = function(){
		// console.log(this.html);
		var str = this.html;
		var arr = str.split("###");//separa por registro
		var arraux = new Array();

		if (str != '') {
			for(var x = 0; x < arr.length; x++)
			{
				arraux = arr[x].split("...");
				// console.log("Adding:" + arraux[1] + " - " + arraux[0]);
				addOptionBairro(tmp_idcampo, arraux[1], arraux[0]);
			}
			changeDisplayBarrioSelect(campo, true);
		} else {
			addOptionBairro(tmp_idcampo,'Nenhum item encontrado','');
			changeDisplayBarrioSelect(campo, false);
		}

		var total = $$(tmp_idcampo+'_total').value;

		if(inner) { // not used in mobile version
			if(total < 7){
				inner.style.height = 'auto';
			} else {
				inner.style.height = '157px';
			}
			inner.style.display = 'block';
		}
                
                if(onLoad != undefined){                    
                    onLoad()
                }
	};  
	a.get('../../inc/routines/routines.php?action='+tmp_rotina+'&id_selecionado='+tmp_idSelecionando);        
}


function loadBairro_face(tmp_idSelecionando,tmp_idcampo,tmp_rotina){
	var campo = $$(tmp_idcampo);

	isMobile = null;
		
		campo.className = 'select disable';

	/* Clearing previous content */
	var inner = $$(tmp_idcampo+'_inner');
	if(inner) { /*it's not specified fro mobile version*/
		inner.innerHTML = '';
		inner.style.display = 'none';
	} else { /* mobile version has options */
		if(campo.options) {
			campo.options.length = 2;
		}
	}

	var total = $$(tmp_idcampo+'_total');
	total.value = 0;

	var a = new Ajax();
	a.onLoad = function(){
		// console.log(this.html);
		var str = this.html;
		var arr = str.split("###");//separa por registro
		var arraux = new Array();

		if (str != '') {
			for(var x = 0; x < arr.length; x++)
			{
				arraux = arr[x].split("...");
				// console.log("Adding:" + arraux[1] + " - " + arraux[0]);
				addOptionBairro(tmp_idcampo, arraux[1], arraux[0]);
			}
			changeDisplayBarrioSelect(campo, true);
		} else {
			addOptionBairro(tmp_idcampo,'Nenhum item encontrado','');
			changeDisplayBarrioSelect(campo, false);
		}

		var total = $$(tmp_idcampo+'_total').value;

		if(inner) { // not used in mobile version
			if(total < 7){
				inner.style.height = 'auto';
			} else {
				inner.style.height = '157px';
			}
			inner.style.display = 'block';
		}

	};
	a.get('../site/inc/routines/routines.php?action='+tmp_rotina+'&id_selecionado='+tmp_idSelecionando);
}



function addOptionBairro(id_select,tmp_text,tmp_value){
	var select = $$(id_select);
	var total = $$(id_select+'_total').value;
	total++;total--;

	if(isMobile) {
		addOptionBarrioMobileBrowser(select, tmp_text, tmp_value);
	} else {
		addOptionBarrioNormalBrowser(select, id_select, total, tmp_text, tmp_value);
	}

	total++;
	$$(id_select+'_total').value = total;
}

/**
 * Adding option of new Barrio for normal browsers that would not need to have the combo box for selection and all the JS stuff is good for them.
 */
function addOptionBarrioNormalBrowser(select, id_select, total, tmp_text, tmp_value) {
	var span = document.createElement('span');

	span.className = 'option';
	span.innerHTML = '<input type="checkbox" id="'+id_select+total+'" name="'+select.attributes['name'].value+total+'" value="'+tmp_value+'" /><label for="'+id_select+total+'" style="">'+tmp_text+'</label>';
	$$(id_select+'_inner').appendChild(span);
}

/**
 * The method provide adding barrio properties to the normal combo box that is supposed to be got as id in parameter.
 */
function addOptionBarrioMobileBrowser(select, tmp_text, tmp_value) {
	// var option = new Option(tmp_text, tmp_value);
	// select.add(option);
	select.options[select.length] = new Option(tmp_text, tmp_value);
}

/**
 * Changes displaying of selection box (combo box) of the barrios.
 * @param boolean isDisplay  the property says whether that could be displayed (true) or hidden/disabled (false)
 * @param dom element  element that will be changed
 */
function changeDisplayBarrioSelect(element, isDisplay) {
	if(isMobile) {
		if(isDisplay) {
			element.multiple = true;
			element.disabled = false;
		} else {
			element.multiple = false;
			element.disabled = true;
		}
	} else {
		if(isDisplay) {
			element.className = 'select';
		} else {
			element.className = 'select disable';
		}
	}
}

function selectCombo(value, field){
            
    var combo = $('#'+field+'_child').find('a');
    var titulo = $('#'+field+'_titletext');
    var qnt = combo.length;
    var name = $('#'+field+' option[value="'+value+'"]').attr('alt');
            
    var i, campoatual;
            
            
    combo.removeClass('selected');
    for(i = 0; i < qnt; i++){
        campoatual = combo.find('span').eq(i).attr('alt');
        if(campoatual == name){
            combo.eq(i).addClass('selected');
        }
    }
    titulo.find('.ddTitleText').html(name);
    titulo.find('img').attr('src', name);
    $('#'+field+' option[alt="'+name+'"]').attr('selected', true);            
} 
