var tiempoMostrar = 500;
var tiempoOcultar = 250;
var cercadorRutes = false;


$(document).ready(function(){

	
	$("label").inFieldLabels();
	$("input").attr("autocomplete","off");
	
	$('#slider').crossSlide({ sleep: 4, fade: 1 }, [
		{ src: '/img/home01.jpg' },
		{ src: '/img/home02.jpg' },
		{ src: '/img/home03.jpg' }
	]);

	ocultar($("div.homeProductesDesplegat"));
	
	$("a.tancarCapaInfo").click(function(){
		ocultar($(this).parent().parent());
	});
	
	$("a.menuInfo").click(function(){
		ocultarCercador();
		idInfo = "info" + $(this).attr("id");
		
		if(!$("#" + idInfo).is(":visible")){
			$(this).addClass("active");
			//Ocultamos todas las capas del menu visibles
			ocultar($("div.homeProductesDesplegat:visible"));
			//Ponemos la capa a mostrar al origen de la animacion
			$("#" + idInfo).animate({
				opacity: 0,
				top: 280
			}, 1);
			$("#" + idInfo).show();
			//Animamos la capa
			$("#" + idInfo).animate({
				opacity: 1,
				top : 250
			}, tiempoMostrar, function(){
				
			});
		}
	});
	
	/*
	$("#menuSobre").click(function(){
		if(!$("#contenidoSobre").is(":visible")){
			$("#contenidoSobre").animate({
				opacity: 1
			}, tiempoMostrar);
			$("#contenidoSobre").show();
		}else{
			$("#contenidoSobre").animate({
				opacity: 0
			}, tiempoOcultar);
			$("#contenidoSobre").hide();
		}
	});
	*/
	
	$("#btnCercador").click(function(){
		ocultar($("div.homeProductesDesplegat"));
		
		if(!cercadorRutes){			
			$("#cercadorRutes").animate({
				height: 526
			}, tiempoMostrar, function(){
				$("#fletxetaCercador").attr("src", "img/fletxaCercadorOn.gif");
				cercadorRutes = true;				
			});
		}else{	
			ocultarCercador();
			
		}		
	});
	
	
	$("#cercarRutaButton").click(function(){
		$("div.mapaCerca").show();
		$("div.mapaCerca").animate({
			width: '658px'
		}, tiempoMostrar, function(){
		});
		elCamiMesRapid.getRoute();
	});
	
	// inicializaciones para google maps
	elCamiMesRapid.init();
});

var ocultarCercador = function(){
	$("div.mapaCerca").animate({
		width: 1
	}, tiempoOcultar, function(){
		$('div.mapaCerca').hide();
		$("#cercadorRutes").animate({
			height: 45
		}, tiempoOcultar, function(){
			$("#fletxetaCercador").attr("src", "img/fletxaCercadorOff.gif");
			cercadorRutes = false;			
		});
	});
};

function ocultar(items){
	items.animate({
		opacity: 0,
		top: 250			
	}, tiempoOcultar, function(){
		items.hide();
		items.each(function(){
			idInfoButton = ($(this).attr("id").substring(4));
			$("#" + idInfoButton).removeClass("active");
		});
	});
}


var elCamiMesRapid = {
		
		gmap: null,
		directionsService: null,
		trafficLayer: null,
		elCamiMesRapidInstance : null,
		
		init: function() {
			
			elCamiMesRapidInstance = this;
			
			this.directionsService = new google.maps.DirectionsService();
			
	        directionsDisplay = new google.maps.DirectionsRenderer();
	        var myOptions = {
	          zoom: 6,
	          latitude: 40.420088, 
	          longitude:-3.688810
	        };

	        var myOptions = {
                zoom: 6,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                center: new google.maps.LatLng( 40.420088, -3.688810 ),
                provideRouteAlternatives: true,
                unitSystem: google.maps.UnitSystem.METRIC
	        };
	        this.gmap = new google.maps.Map( document.getElementById('mapaContainer'), myOptions );
	        
	        directionsDisplay.setMap(this.gmap);
	        
	        this.trafficLayer = new google.maps.TrafficLayer();
	       
	        //directionsDisplay.setPanel(document.getElementById('directions-panel'));
	        
	        $('#displayTransit').bind('change', function() {
	        	if ( $(this).attr('checked') ) {
	        		elCamiMesRapidInstance.trafficLayer.setMap(elCamiMesRapidInstance.gmap);
	        	}
	        	else {
	        		elCamiMesRapidInstance.trafficLayer.setMap( null );
	        	}
	        });
	        
	        $('#buttonResetForm').bind('click', function() {
	        	$('#elcamimesrapidForm').each (function(){
	        		  this.reset();
	        	});
	        })
		},

		
		getRoute: function() {
			
			$.fancybox.showActivity();
			
			var start = $('#origen_carrer').val() +" "+ $('#origen_ciutat').val() +" "+ $('#origen_pais').val();
			var end = $('#desti_carrer').val() +" "+ $('#desti_ciutat').val() +" "+ $('#desti_pais').val();
			/*
			start = "España barcelona alfons xii, 75";
			end = "España viladecavalls carrer major, 40";
			*/
			
			//start = "Barcelona";
			//end = "Viladecavalls";
			var avoidToolsVar = $('#avoidTolls').attr('checked') == 'checked';
	        var request = {
	          origin: start,
	          destination: end,
	          travelMode: google.maps.DirectionsTravelMode.DRIVING,
	          provideRouteAlternatives: true,
	          avoidTolls: avoidToolsVar
	        };

	        
	        this.directionsService.route(request, function(response, status) {

	        	$.fancybox.hideActivity();
	        	switch (status) {
	        		case google.maps.DirectionsStatus.ZERO_RESULTS:
	        			alert("No resultados");
	        		break;
	        		case google.maps.DirectionsStatus.INVALID_REQUEST:
	        			alert("No resultados");
		        	break;
	        		case google.maps.DirectionsStatus.MAX_WAYPOINTS_EXCEEDED:
	        			alert("Número de resultados excesivamente grande");
		        	break;
	        		case google.maps.DirectionsStatus.NOT_FOUND:
        				alert("No encontrado");
		        	break;
	        		case google.maps.DirectionsStatus.OVER_QUERY_LIMIT:
		        		alert("Over Query Limit");
		        	break;
	        		case google.maps.DirectionsStatus.REQUEST_DENIED:
		        		alert("Petició denegada");
		        	break;
	        		case google.maps.DirectionsStatus.UNKNOWN_ERROR:
		        		alert("Error desconegut");
		        	break;
	        		case google.maps.DirectionsStatus.OK:
			            directionsDisplay.setDirections(response);
			            distancia = response.routes[0].legs[0].distance.text;
			            distancia = distancia.replace('.','|').replace(',','.').replace('|',',');
			            $('#distanceInfoField').val( distancia );
			            
			            var duration = response.routes[0].legs[0].duration.text;
			            $('#durantionInfoField').val( duration );
	        		break;
	        	}
	        });			
		}
};
