$(document).ready(function(){
	// $('#topo_login .text, #lateral .text').each(function(){
	// 		$(this).val($(this).attr('title'));
	// 	}).focus(function(){
	// 		if($(this).val() == $(this).attr('title')){
	// 			$(this).val('');
	// 		}
	// 	}).blur(function(){
	// 		if($(this).val() == ''){
	// 			$(this).val($(this).attr('title'));
	// 		}
	// 	});
	$('#lateral .filtros input').each(function(){
		$img = $(this).attr('class');
		($(this).attr('checked'))?$(this).addClass('marcado'):'';
		$(this).after('<div class="item"></div>');
		$(this).parent().find('div:last')
			.addClass($(this).attr('class'))
			.text($(this).attr('title'))
			.attr('checkbox', 'input[name="'+$(this).attr('name')+'"]')
			.click(function(){
				$inp = $($(this).attr('checkbox'));
				($inp.attr('checked'))?$inp.removeAttr('checked'):$inp.attr('checked', true);
				if ($(this).hasClass('marcado')) {
					$(this).removeClass('marcado');
					$('#chamar_taxi .item.' + $inp.attr('class')).hide();
				} else {
					$(this).addClass('marcado');
					$('#chamar_taxi .item.' + $inp.attr('class')).show();
					
				}
			})
			.hover(function(){ $(this).addClass('hover'); }, function(){ $(this).removeClass('hover'); })
			.css({'background-image':'url('+webroot+'img/queroumtaxi_botao_'+$img+'.png)'})
	}).hide();
	$('.blocoAchados select').selectStyle();
	$('.webClientes select').selectStyle();
	$('.blocoTrabalhe select').selectStyle();
	// $('#listaNoticias .item:last, #noticiaLateral .blocoLateral .conteudo li:last').css({'background':'none','padding':'0'});
	$sa = 0;
	$('.sobreMini').each(function(){
		if($sa < $(this).height()){
			$sa = $(this).height();
		}
	});
	$('.sobreMini').css({'height':$sa+'px'});
	$c = 0;
	$('#blocosSobre .item').each(function(){
		$c++;
		$classe = 'item'+$c;
		$(this).addClass($classe);
	});
	
	$('#lateral #btn').click(function() {
		$(this).parent().parent()
			.animate({height: '0px'})
			.find('#lateral_bg_middle').animate({height: '0px'});
		
		$.expandMap();
	});
	
	$('#btn_off').click(function() {
		$('#lateral')
			.animate({height: '538px'})
			.find('#lateral_bg_middle').animate({height: '100%'});
			
		$.contractMap();
	});
	
	$('form#WebClienteAddForm').getLatLon();
	
/*	$('#btn_chamar').click(function() {
		if (typeof(webCliente) == 'undefined') {
			alert('Para chamar um taxi, é necessário fazer seu login primeiro.');
			$('#formLogin input:first').focus();
		} else {
			if (confirm('Deseja realmente chamar o taxi?')) {
				chamarTaxi();
			}
		}
	});*/
	$('#formLogin').submit(function(e) {
		// e.preventDefault();
		$.ajax({
			type: 'POST',
			url: webroot + $('#formLogin').attr('action').replace('/radiotaxi/', '').replace('/site/', ''),
			data: {
				usuario: $('#formLogin input[name*=usuario]').val(),
				senha: $('#formLogin input[name*=senha]').val()
			},
			complete: function(data) {
				// console.log(data);
				if (data.responseText) {
					data = JSON.parse(data.responseText);
					webCliente = data;
					$('#topo_login #web-cliente-nome').html(data['WebCliente']['nome']);
					$('#div_login').hide();
					$('#div_logado').show();
				} else {
					alert('Usuário ou senha incorretos.');
				}
					
			}
		});
		return false;
	});
	
	$('#link_logout').click(function(e) {
		// e.preventDefault();
		$.ajax({
			type: 'GET',
			url: webroot + "webClientes/logout",
			complete: function(data) {
				if (data.responseText) {
					$('#div_logado').hide();
					$('#div_login').show();
				} else {
					alert("Ocorreu algo inesperado em sua solicitação. Em breve solucionaremos esse empecilho.");
				}
			}
		});
	});
	
	$('#topo_login input').focusin(function () {
		$('#topo_login').css('background', 'url(' + webroot + '/img/topo_form_current.png)');
	});
	
	$('#topo_login input').focusout(function() {
		$('#topo_login').css('background', 'url(' + webroot + '/img/topo_form.png)');
	});
	
	/*$('#topo_login').mouseover(function() {
		$(this).css('background', 'url(' + webroot + '/img/topo_form_current.png)');
	});
	
	$('#topo_login').mouseout(function() {
		if ($('#topo_login input[type=text]:focus').size() == 0)
			$(this).css('background', 'url(' + webroot + '/img/topo_form.png)');
	});*/
	
	/** Ajusta rodapé **/
	var meio = document.getElementById('meio');
	// alert(meio.offsetHeight);
	// alert($(window).height());
	
	if ($('#footer').offset().top < ($(window).height() - 40)) {
		$('#footer').css('position', 'absolute');
		$('#footer').css('bottom', '0px');
		$('#footer').css('width', '100%');
	}
});

/**
 * @author Diego Haas Sanches
 * @description Através da API do Google Maps, recupera a Latitude e Longitude baseado nos campos de endereco do formulário
 */
$.fn.getLatLon = function() {
	var form = $(this);
	$('input[type=submit]', this).click(function (e) {
		e.preventDefault();
		
		var geocoder = new google.maps.Geocoder();
		var endereco = '';
		var options = {
			inputs: {
				enderecos: ['logradouro', 'numero', 'cidade', 'estado'],
				lat: 'lat',
				lng: 'lon'
			}
		};
		
		for(var input in options.inputs.enderecos) {
			with (options.inputs) {
				if ($('input[name*=' + enderecos[input] + ']').size() > 0 && $('input[name*=' + enderecos[input] + ']').val() != 'undefined') {
					endereco += ' ' + $('input[name*=' + enderecos[input] + ']').val();
				}
			}
			
		}
		
		endereco = $.trim(endereco);
		
		geocoder.geocode({address: endereco}, function(results, stats) {
			if (stats == google.maps.GeocoderStatus.OK) {
				// Latitude	
				var latitude = ('' + results[0].geometry.location.lat()).slice(0, 15);
				$('input[name*=' + options.inputs.lat + ']').val(latitude);
				// Longitude
				var longitude = ('' + results[0].geometry.location.lng()).slice(0, 15);
				$('input[name*=' + options.inputs.lng + ']').val(longitude);
				if (!latitude || !longitude) {
					alert('Não foi possível identificar seu endereço.\nPor gentileza, verifique os dados informados.');
				} else {
					form.submit();
				}
			} else {
				alert('Não foi possível identificar seu endereço.\nPor gentileza, verifique os dados informados.');
			}	
		});
	});
}


