$(document).ready(init);

/* Init */
function init(){
	biggerLink();
	modalMapa();
	configMask();
	verHash();
	verEmpreendimentoDetalhe();
	
	$('.destaque-empreendimento a').click(
		function () {
			window.setTimeout('verHash()', 150);
		}
	);

	//onclick="MostraImprimir(event.clientX, event.clientY)"
	//MostraImprimir(event.clientX, event.clientY)

//	function MostraImprimir(alinhaX, alinhaY)
//	{
//		alert(alinhaX + alinhaY);
//	}
	
	$('select#cidades').change(function() {
		var valor = $(this).val();
		if (valor != "") {
			$('select#bairros').html('<option>Aguarde ...</option>');
			$('select#empreendimentos').html('<option>Aguarde ...</option>');
			var url = caminho + "/empreendimentos";
			$.ajax({
				type: 'POST',
				url: url,
				data: {'metodoAjax': 'getBairros', 'cidade': valor},
				success:  function(html) {
					$('select#bairros').html("<option>Bairro</option>" + html);
				}
			});
			$.ajax({
				type: 'POST',
				url: url,
				data: {'metodoAjax': 'getEmpreendimentosLocal', 'cidade': valor},
				success:  function(html) {
					$('select#empreendimentos').html("<option>Empreendimento</option>" + html);
				}
			});
		}
	});

	$('select#bairros').change(function() {
		var valor = $(this).val();
		if (valor != "") {
			$('select#empreendimentos').html('<option>Aguarde ...</option>');
			var url = caminho + "/empreendimentos";
			$.ajax({
				type: 'POST',
				url: url,
				data: {'metodoAjax': 'getEmpreendimentosLocal', 'bairro': valor},
				success:  function(html) {
					$('select#empreendimentos').html("<option>Empreendimento</option>" + html);
				}
			});
		}
	});

	$('#form-busca a#bt-buscar').click(submitBusca);

}

function submitBusca() {
	var emp = $('#empreendimentos').val();
	if (emp != "Empreendimento") {
		url = caminho + "/empreendimentos/detalhes/" + emp;
		document.location.href = url;
	} else {
		$('#form-busca').submit();
	}
}

function verEmpreendimentoDetalhe() {

	if (!(pagina[0] == 'empreendimentos' && pagina[1] == 'detalhes')) {
		return(false);
	}

	$('#detalhe-img a').click(
		function() {
			var id = $(this).attr('href').replace('#', '');
			$('#detalhe-img a').removeClass('ativo');
			$(this).addClass('ativo');
			$('.wrap-carousel').hide();
			$('#wrap-carousel-' + id).show();
		}
	);
	
	$('#nav-destaques a').click(
		function() {
			$('#nav-destaques a').removeClass('ativo');
			$(this).addClass('ativo');
			$('#tab-content div').hide();
			var id = $(this).attr('href');
			$(id).show();
			return false;
		}
	);
}
function verHash(){
	var hash = window.location.hash;
	
	$('#nav-destaques li').removeClass('ativo');
	
	if (hash == '' || hash == '#') {
		$('#ficha-tecnica').addClass('ativo');
	} else {
		hash = hash.replace('#aba-', '');
		$('#' + hash).addClass('ativo');
	}
}

/**
 * Seta as configurações do carrosel que é usado nos detalhes dos produtos.
 */
function startCarousel(qtd, id){
	$(id).jCarouselLite({
		btnNext: id.replace('#', '#wrap-') + " .carousel-next",
		btnPrev: id.replace('#', '#wrap-') + " .carousel-back",
		visible: 5,
		circular: false,
		start: 0,
		scroll: 1
	});
}

/**
 * Seta as configurações do carrosel que é usado na home.
 */
function startCarouselHome(qtd, id){
	$(id).jCarouselLite({
		btnNext: ".carousel-next",
		btnPrev: ".carousel-back",
		visible: qtd,
		circular: false
	});
}

/**
 * Chama o plugin BiggerLink.
 */
function biggerLink(){
	//$('.carousel ul li').biggerlink();
}

/**
 * Configura o colorbox para abrir o mapa da página de contato
 */
function modalMapa(){
	$('a#openMap').colorbox({
		iframe:true,
		innerWidth:600,
		innerHeight:400
	});
	$('a#mapa-empreendimento').colorbox({
		iframe:true,
		innerWidth:600,
		innerHeight:400
	});
}

/**
 * Configura as mascaras dos formulários
 */
function configMask(){
	$('#telefone').setMask('phone');
}

function contatoErros(campos, erros) {
	var campo = campos.split('|');
	var erro = erros.split ('|');
	for (var i = 0; i < campo.length; i++){
		document.getElementById('erro-' + campo[i]).innerHTML = erro[i];
		document.getElementById('erro-' + campo[i]).style.display = '';
		document.getElementById('asterisco-'+ campo[i]).style.display = '';
	}
}

function contatoOk () {
	document.getElementById("confirmacao-envio").style.display = "";
	document.getElementById("formContato").reset();
	document.getElementById("telefone").value = '';
}
function enviarContato() {		
	var funcao_volta = function (res) {
		eval (res);
		$('#botao-enviar').css('display','');
		$('#loader').css('display','none');
	}
	var dados_adicionais = 'metodoAjax=enviar';
	
	$('.mensagem-erro').css('display','none');
	$('.asterisco-erro').css('display','none');
	$('#botao-enviar').css('display','none');
	$('#loader').css('display','');
	document.getElementById("confirmacao-envio").style.display = "none";
	
	enviaFormulario(null, 'formContato', dados_adicionais, get('formContato').action, funcao_volta, true);
}

function enviarContatoEmpreendimento() {
	var funcao_volta = function (res) {
		eval (res);
		$('#botao-enviar').css('display','');
		$('#loading').css('display','none');
	}
	var dados_adicionais = 'metodoAjax=enviar';
	
	$('.mensagem-erro').css('display','none');
	$('.asterisco-erro').css('display','none');
	$('#botao-enviar').css('display','none');
	$('#loading').css('display','');
	document.getElementById("confirmacao-envio").style.display = "none";
	
	enviaFormulario(null, 'contato-empreendimento', dados_adicionais, get('contato-empreendimento').action, funcao_volta, true);
}
function contatoEmpreendimentoOk () {
	document.getElementById("confirmacao-envio").style.display = "";
	document.getElementById("contato-empreendimento").reset();
	document.getElementById("telefone").value = '';
}
function postaAjax(caminho, dados, volta, sincrona) {
	if (!caminho) alert('Caminho não definido!');
	if (!(caminho, dados, volta)) alert('Parâmetros incorretos na função postaAjax(caminho, dados, volta)\n\ncaminho=' + caminho + '\ndados=' + dados + '\nvolta=' + volta);
	var ajax = criar_ajax();
	if (ajax != null) {
		if (!sincrona) {
			ajax.onreadystatechange = function() {
				if (ajax.readyState == 4) {
					volta(ajax.responseText);
				}
			}
		}
		ajax.open('POST', caminho, !sincrona);
		ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
		ajax.send(dados);
		if (sincrona) {
			volta(ajax.responseText)
		}
	}
}
function enviaFormulario(edicao_id, formulario, dados_adicionais, caminho, volta, sincrona) {
	var f = get(formulario);
	var el;
	var valor;
	var dados;
	if (dados_adicionais) {
		dados = dados_adicionais + '&asc=1';
	} else {
		dados = 'asc=1';
	}
	var arrIds = Array();
	getAllIds(f, arrIds);
	for (var i = 0; i < arrIds.length; i++) {
		el = get(arrIds[i]);
		switch (el.type) {
			case 'select-one':
			case 'hidden':
			case 'text':
			case 'textarea':
			case 'password':
				valor = el.value;
				dados += '&' + el.id + '=' + post_encode(valor);
				break; 
			case 'radio':
				if (el.checked) {
					valor = el.value;
					dados += '&' + el.name + '=' + post_encode(valor);
				}
		}
	}
	
	postaAjax(caminho, dados, volta, sincrona);
}
function getAllIds(el, arrIds) {
	if (el.childNodes.length > 0) {
		for (var i = 0; i < el.childNodes.length; i++) {
			if (el.childNodes[i] && el.childNodes[i].id) {
				arrIds[arrIds.length] = el.childNodes[i].id;
			}
			if (el.childNodes[i].childNodes.length > 0) {
				getAllIds(el.childNodes[i], arrIds);
			}
		}
	}
}	
function criar_ajax(){
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp = new XMLHttpRequest();
	} catch (e) {
		// Internet Explorer
		try {
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				return false;
			}
		}
	}
	return(xmlHttp);
}	
function url_decode(psEncodeString) {
	var lsRegExp = /\+/g;
	return unescape(String(psEncodeString).replace(lsRegExp, " "));
}	
function post_encode(campo) {
	return(campo.replace(/\&/g, '%26'));
}
function get(id) {
	return document.getElementById(id);
}

/*Login Área do Cliente da Home*/
	function limparInput(elemento) {
		if (elemento.value == "Login") {
			elemento.value = "";
		}
		if(elemento.value == "Senha") {
			elemento.value = "";
			elemento.type = "password";						
		}
	}
	
	function colocarValorInput(elemento) {
		if(elemento.value == ""){
			if(elemento.id == "login"){
				elemento.value = "Login";
			}
			else{
				elemento.type = "text";
				elemento.value = "Senha";
			}
		}
	}
	
//////////////////////////////////////////////////////////////
// Funções implementadas durante criação da "área do cliente"

function showResposta(id) {
	
	var pai=document.getElementById("widget-faq");
	var el=document.getElementById("divResp"+id);
	if(el.style.display!="block") {
		el.style.display="block";
	}
	else {
		el.style.display="none";
	}
	
	
}

function baixarBoleto() {
	
	var slct=document.getElementById('slctBoletos');
	window.location=slct.options[slct.selectedIndex].value;
	
}

