/**
 * @author Diego Haas Sanches
 */
var geocoder;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var initialized = false;
var changeListener;
var markers = new Array();
var directionsDisplayOptions = {
	draggable: true
	// suppressMarkers: true
};
/** Variável para guardar coordenadas iniciais e finais **/
var _coordinates = {
	start: {
		lat: null,
		lng: null
	}, 
	end: {
		lat: null,
		lng: null
	}
};
var partida = null;

function initialize() {
	if (typeof(map) == 'undefined') {
		geocoder = new google.maps.Geocoder();
	 	directionsDisplay = new google.maps.DirectionsRenderer(directionsDisplayOptions);
	 	
		var latlng = new google.maps.LatLng(-25.5307489, -49.195815400000015);
	    var myOptions = {
	    	zoom: 12,
	      	center: latlng,
	      	mapTypeId: google.maps.MapTypeId.ROADMAP
	    };
	    map = new google.maps.Map(document.getElementById("map_canvas"),
	        myOptions);
	    directionsDisplay.setMap(map);
	} else {
		var myOptions = {
	    	zoom: map.zoom,
	      	center: map.center,
	      	mapTypeId: map.mapTypeId
	    };
	    
	    var currentDirections = directionsDisplay.getDirections();
	    
	    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	    directionsDisplay.setMap(map);
	    	
		show(currentDirections);
	}
}

function calcRoute(start, end) {
	var request = {
		origin: start,
		destination: end,
		travelMode: google.maps.TravelMode.DRIVING
	};
	
	directionsService.route(request, function(result, status) {
		// console.log(status)
		// Encontrou resultados
		if (status == google.maps.DirectionsStatus.OK) {
			if (typeof(isMobile) != 'undefined' && isMobile) {
				$('#main').hide(); $('#chamar_taxi').show();
			} else {
				$('#buscar_taxi').hide(); $('#chamar_taxi').show();
			}
			$('#formLateral span.sem_rota_erro').hide();
			
			if ($('#chamar_taxi #map_canvas').size() > 0)
				initialize();
				
			show(result);
			directionsDisplay.setDirections(result);
			
			changeListener = google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
				var currentDirections = directionsDisplay.getDirections();
				show(currentDirections);
			});
			
			
		}
		// Não encontrou nenhum resultado
		else if (status == google.maps.DirectionsStatus.ZERO_RESULTS || status == google.maps.DirectionsStatus.NOT_FOUND) {
			$('#formLateral span.sem_rota_erro').show();
		}
	});
}


function show(result){
	if (typeof(result) == 'undefined')
		return false;
		
	var distancia = result.routes[0].legs[0].distance.value;
	var tempo = result.routes[0].legs[0].duration.value;
	
	with (result.routes[0].legs[0]) {
		// Armazenar Coordenadas
		_coordinates.start.lat = start_location.lat();
		_coordinates.start.lng = start_location.lng();
		_coordinates.end.lat = end_location.lat();
		_coordinates.end.lng = end_location.lng();
		
		// Verificar primeiro se origem é de São José dos Pinhais
		verificarCidade('São José dos Pinhais', [start_location], function (isCidade) {
			// Se for de São José dos Pinhais, buscar pelo destino
			if (isCidade) {
				verificarCidade('São José dos Pinhais', [end_location], function (isCidade) {
					var hours = new Date().getHours();
					var bandeira = 0;
					if (isCidade) {
						if (hours >= 6 && hours < 20)
							bandeira = 1;
						else
							bandeira = 2;
					} else {
						if (hours >= 6 && hours < 20)
							bandeira = 3;
						else
							bandeira = 4;
					}
					if (typeof(isMobile) != 'undefined' && isMobile) {
						// console.log('isMobile!');
						
						$('#valor_estimado #valor_estimado_middle').showValor(calcCorrida(distancia, tempo, bandeira), null, bandeira);
					} else {
						$('#formLateral #chamar_taxi #bandeiras .bandeira').hide().each(function() {
							/*var bandeira = parseInt($(this).attr('bandeira'));
							var outraBandeira = parseInt($(this).attr('outra_bandeira'));
							var hour_start = parseInt($(this).attr('hour_start'));
							var hour_end = parseInt($(this).attr('hour_end'));
							var is_sjp = $(this).attr('is_sjp');*/
							//var hours = new Date().getHours();
							
							/*if (hour_end < hour_start) {
								hour_end += 24;
								if (hours < hour_start)
									hours += 24;
							}*/
							switch(bandeira) {
								case 1:
									outraBandeira = 2;
									break;
								case 2:
									outraBandeira = 1;
									break;
								case 3:
									outraBandeira = 4;
									break;
								case 4:
									outraBandeira = 3;
									break;
							}
							
							
							// Se hora atual é maior ou igual hora inicial e menor que hora final e se estão na mesma cidade
							//if ((hours >= hour_start && hours < hour_end) && (isCidade == is_sjp)) {
								$(this).show().showValor(calcCorrida(distancia, tempo, bandeira), calcCorrida(distancia, tempo, outraBandeira), bandeira);
							//}
						});
					}
					
					
				});
				
				getFrota(start_location.lat(), start_location.lng());
				
			} else {
				alert('Origem não é de São José dos Pinhais');
			}
		});
		
		
	}
}

$.fn.showValor = function (valor, outroValor, bandeira) {
	switch (bandeira) {
		case 1:
		case 3:
			outro_horario = 'Das 20h às 8h';
			break;
		case 2:
		case 4:
			outro_horario = 'Das 8h às 20h';
			break;
	}
	var valorStr = (valor+'').split('.');
	$('#chamar_taxi .valor_real').html(valorStr[0]);
	$('#chamar_taxi .valor_centavo').html(',' + valorStr[1]);
	if (typeof(outroValor) != 'undefined' && outroValor != null) {
		$('#bandeiras .outra_bandeira_info .valor').html(outroValor.replace('.', ','));
		$('#bandeiras .outra_bandeira_info .horario_info').html(outro_horario);
	}
	$('#bandeiras').show();
	$(this).show();
}

/**
 * @description Verifica se coordenadas se situam em determinada cidade
 * @param String cidade Nome da cidade
 * @param Array coords Lista de coordenadas
 * @param function callback(isCidade) callback que recebe um parâmetro boolean para identificar se é a mesma cidade para ser executado após cada ajax
 */
// TODO implementar escolha de resultado em vez de sempre escolher o primeiro
function verificarCidade(cidade, coords, callback){
	for (var i in coords) {
		var isCidade = false;
		var request;
		
		if (typeof(coords[i]) == 'string') {
			request = {address: coords[i]};
		} 
		else if (typeof(coords[i]) == 'object') {
			request = {location: coords[i]};
		}
		else if (typeof(coords[i]) == 'undefined') {
			return;
		}
		
		geocoder.geocode(request, function (results, status) {
			if (status == google.maps.GeocoderStatus.OK) {				
				for (var component in results[0].address_components) {
					if (results[0].address_components[component].long_name == cidade || results[0].address_components[component].short_name == cidade)
						isCidade = true;
				}
			}
			
			if (typeof(callback) == 'function') {
				callback(isCidade);
			}
		});
	}
}


function codeAddress(address) {
	if (typeof(address) == 'undefined') {
		alert('Informe um endereço');
		return false;
	}
	if (!/[0-9]+/.test(address)) {
		if (!confirm("Parece que você não informou o número.\n Deseja continuar mesmo assim?")) {
			return false;
		}
	}
		
	geocoder.geocode({'address': address}, function (results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			map.setCenter(results[0].geometry.location);
			var marker = new google.maps.Marker({
				map: map,
				position: results[0].geometry.location
			});
			
		} else {
			alert("Geocode was not successful for the following reason: " + status);
		}
	});
	
	
}

function buscarTaxi(e) {
	// console.log('Buscar Taxi!');
	e.preventDefault();
	var aonde = partida = $.trim($('#inp_aonde').val());
	var para = $.trim($('#inp_para').val());
	
	if (!/São José dos Pinhais/.test(aonde))
		aonde += ', São José dos Pinhais - PR';
	
	verificarCidade('São José dos Pinhais', [aonde], function(isCidade) {
		if (isCidade) {
			if (para == "" || para == $('#inp_para').attr('placeholder')) {
				// Marcar ponto partida
				geocoder.geocode({address: partida}, function(results, status) {
					if (status == google.maps.GeocoderStatus.OK) {
						map.setCenter(results[0].geometry.location);
						var marker = new google.maps.Marker({
						    map: map, 
						    position: results[0].geometry.location
						});
						if (typeof(isMobile) != 'undefined' && isMobile) {
							$('#chamar_taxi #chamar_panel').hide();
							$('#main').hide(); $('#chamar_taxi').show();
						} else {
							$('#buscar_taxi').hide(); $('#chamar_taxi').show();
						}
						$('#formLateral span.sem_rota_erro').hide();

						if ($('#chamar_taxi #map_canvas').size() > 0)
							initialize();
						
						getFrota(results[0].geometry.location.lat(), results[0].geometry.location.lng());
						_coordinates.start.lat = results[0].geometry.location.lat();
						_coordinates.start.lng = results[0].geometry.location.lng();
						
						$('#sem_destino').show();
						
						//show(results[0]);
					} else {
						alert("Geocode was not successful for the following reason: " + status);
					}
				});
			} else {
				calcRoute(aonde, para);
			}
			$('#formLateral span.outra_cidade_erro').hide();
		} else {
			$('#formLateral span.outra_cidade_erro').show();
		}
	});
	
}
  
$(document).ready(function() {
	
	$('#btn_up').click(function(e) {
		e.preventDefault();
		$.expandMap();
	});
	
	if ($('#map_canvas').size() > 0)
		initialize();
	
	$('input#btn_buscar').click(function(e) {
		buscarTaxi(e);
	});
	
	$('#btn_buscar a').click(function(e) {
		buscarTaxi(e);
		
		// initialize();
	});
	
	$('#formLateral #btn_cancelar').click(function() {
		$('#chamar_taxi').hide();
		$('#buscar_taxi').show();
		if (typeof(changeListener) != 'undefined') {
			google.maps.event.removeListener(changeListener);
		}
	});

	// $('#formLateral input[name=aonde], #formLateral input[name=para]').geo_autocomplete(new google.maps.Geocoder, {
	// 		//mapkey: mapKey, 
	// 		selectFirst: false,
	// 		minChars: 3,
	// 		cacheLength: 50,
	// 		width: 300,
	// 		scroll: true,
	// 		scrollHeight: 330,
	// 		maptype: 'terrain',
	// 		mapwidth: 0,
	// 		mapheight: 0,
	// 		geocoder_region: 'Paraná',
	// 		geocoder_address: true,
	// 		geocoder_types: 'locality,political,sublocality,neighborhood'
	// 	}).result(function(_event, _data) {
	// 		 if (_data) alert(typeof(_data));
	//  	});
	
	/**
	 * Autocomplete
	 */
	$('#inp_aonde, #inp_para').each(function() {
			var defaultBounds = new google.maps.LatLngBounds(new google.maps.LatLng(-25.530749,-49.195815));
		
			var input = this;
			var options = {
			  bounds: defaultBounds
			  // types: ['locality,establishment,sublocality,neighborhood']
			};
		
			var autocomplete = new google.maps.places.Autocomplete(input, options);
		});
	
	
	
	
	
	$('#btn_chamar, #btn_chamar_big').click(function() {
		//console.log('Chamar Táxi!');
		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();
			}
		}
	});
});

function calcCorrida(distancia, tempo, bandeira) {
	// Porcentagem do tempo em que o carro permanece parado
	var porcentParado = 5;
	var tempoParado = (tempo * porcentParado) / 100;
	var valorHoraParado = 2400;
	var valor = 0;
	var valorKm = 0;
	var taxaEmbarque = 390;

	switch(bandeira) {
		// Bandeira 1;
		case 1:
			valorKm = 200;
			break;
		// Bandeira 2;
		case 2:
			valorKm = 230;
			break;
		// Bandeira 3;
		case 3:
			valorKm = 286;
			break;
		// Bandeira 4;
		case 4:
			valorKm = 317;
			break;
	}
	
	valor = ((((distancia / 1000) * valorKm) + ((tempoParado / 3600) * valorHoraParado) + taxaEmbarque) / 100).toFixed(2);
		
	return valor;
}

$.expandMap = function () {
	$('#lateral')
		.animate({height: '0px'})
		.find('#lateral_bg_middle').animate({height: '0px'});
		
	$('#map_canvas').animate({
		width: '950px',
		left: '0px'
	}, 700, function() {
		if (!initialized) {
			initialize();
			initialized = true;
		}
	});
}

$.contractMap = function () {
	$('#map_canvas').animate({
		width: '605px',
		left: '345px'
	});
}

function getFrota(latA, lngA) {
	
	if (markers.length > 0)
		for (var marker in markers)
			markers[marker].setMap(null);
		
	markers = new Array();
			
	$.ajax({
		type: 'POST',
		url: webroot + 'ajax/getFrotaKML',
		success: function(data) {
			frota = JSON.parse(data);
			
			for (var i in frota) {
				var radius = 0.025;
				var coordinates = getCoordinates(frota[i]);
				var status = frota[i].styleUrl;
				var location = new google.maps.LatLng(coordinates.latitude, coordinates.longitude, true);
				
				if ((Math.abs(coordinates.latitude - latA) <= radius && Math.abs(coordinates.longitude - lngA) <= radius) && status == '#Free' && checkFiltros(frota[i].description)) {
					markers.push(new google.maps.Marker({
						map: map,
						position: location,
						icon: webroot + 'img/icone_taxi.png'
					}));
					if (markers.length > 1)
						$('#qtd_taxis_info').html("Foram encontrados " + markers.length + " táxis.");
					else if (markers.length == 1)
						$('#qtd_taxis_info').html("Foi encontrado " + markers.length + " táxi.");
					else 
						$('#qtd_taxis_info').html("Não foi encontrado nenhum táxi com essas características.");
				}
			}
		}
	});
}

function getCoordinates(obj) {
	var coordinates = {
		latitude: 0,
		longitude: 0
	};
	
	if (typeof(obj.LookAt) != 'undefined') {
		coordinates = obj.LookAt;
	}
	else if (typeof(obj.Point) != 'undefined') {
		var temp = obj.Point.coordinates.split(',');

		coordinates.longitude = parseFloat(temp[0]);
		coordinates.latitude = parseFloat(temp[1]);
	}
	
	return coordinates;
}


function checkFiltros(description) {
	var filtrosChecked = true;
	var types = description.replace(/\s\+\s/g, ',').split(',');
	
	$('.filtros .marcado').each(function () {
			filtro = $.trim($(this).attr('class').replace('item', '').replace('filtro', '').replace('marcado', '')).toUpperCase();
			if (filtro == 'NAOFUMANTE')
				filtro = "NÃO FUMANTE \\(MOT\\)";
			else if (filtro == 'ARCONDICIONADO')
				filtro = 'AR';
			else if (filtro == 'PET' || filtro == 'PETS')
				filtro = 'ZOO';
			else if (filtro == 'CARTAO')
				filtro = /(VISA|VISA-ELEC|MASTER|MAESTRO|HIPERCARD|DINNERS)/;
				
			// if (description.search(filtro) == -1)
				// filtrosChecked = false;
				
			if (typeof(filtro) == 'string')
				filtro = new RegExp('^' + filtro + '$');
				
			for (var i in types) {
				if (types[i].search(filtro) != -1)
					break;
				else
					if (i == types.length - 1)
						filtrosChecked = false;
			}
	});

	return filtrosChecked;
}

function chamarTaxi() {
	$.ajax({
		type: 'POST',
		data: {
			data: {
				lat: _coordinates.start.lat,
				lng: _coordinates.start.lng,
				partida: partida,
				referencia: $('#txt_referencia').val(),
				filtros: $('#filtros_wrapper').getFiltros()
			}
		},
		url: webroot + 'corridas/chamarTaxi',
		success: function(data) {
			data = JSON.parse(data);
			// console.log(data);
			
			// Mobile
			if (typeof(isMobile) != 'undefined' && isMobile) {
				$('#taxi_a_caminho .msg').html(data.msg);
				$('#chamar_panel .panel #valor_estimado, #chamar_panel #btn_chamar').hide();
				$('#taxi_a_caminho').show();
			}
			// Web
			else {
				$('#taxi_chamado img').hide();
				if (data.status == 'WAIT' || data.status == 'ERROR')
					$('#taxi_chamado #taxi_chamado_erro').show();
				
				else if (data.status == 'OK')
				 	$('#taxi_chamado #taxi_chamado_ok').show();
				
				$('#taxi_chamado .msg').html(data.msg);
				
				$.colorbox({html: $('#taxi_chamado').html()});
				
				$.expandMap();
			}
		}
	});
}

$.fn.getFiltros = function () {
	var filtros = new Array();
	// console.log(filtros);
	// Mobile
	if (typeof(isMobile) != 'undefined' && isMobile) {
		$('.marcado', this).each(function() {
			filtros.push($.trim($(this).attr('class').replace('item', '').replace('marcado', '')).toUpperCase());
		});
	}
	// Web
	else {
		$('.item:visible', this).each(function() {
			filtros.push($.trim($(this).attr('class').replace('item', '').replace('marcado', '')).toUpperCase());
		});
	}
	
	return filtros;
}

