﻿// JavaScript Document
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//LOADER
function loading(div){	
	if ($("#loader").length == 0){
		$(div).append('<div id="loader"></div><div id="loaderImg"><img  src="img/ajax-loader.gif" alt="" /></div>');
		$("#loader").css('opacity', 0);
		$("#loader").fadeTo("fast",0.2);
	}
}
function fadeloading(){
	$("#loaderImg").remove();
	$("#loader").fadeTo("fast",0);
	$("#loader").remove();	
}
///////////////////////////////////////////////////////////////////////////////////////////////////
//GOOGLE MAPS

var paradas=new Array();
var map ;
var infowindowLevel = 0;
var markers=new Array();
var directionsService ;
var waypoints = [];
var directionsVisible = false;
var renders=new Array();
var quantsPunts=2;
var infowindow;
var colorLinia="";
  var shape = {
      coord: [1, 1, 1, 20, 18, 20, 18 , 1],
      type: 'poly'
  };

function initialize(idLinea) {
    var latlng = new google.maps.LatLng(41.159581,1.107459);
    var myOptions = {
      zoom:14,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
	 var estilo =[ { featureType: "road", elementType: "all", stylers: [ { visibility: "on" }, { hue: "#ff9700" }, { saturation: 82 } ] },{ featureType: "all", elementType: "all", stylers: [ { hue: "#ffc91d" }, { saturation: 97 } ] },{ featureType: "all", elementType: "all", stylers: [ ] } ];
    map = new google.maps.Map(document.getElementById("googleMap"), myOptions);
	var styledMapOptions = {
      map: map,
      name: "ReusTransport"
    }
   var RTMapType =  new google.maps.StyledMapType(estilo,styledMapOptions);
  map.mapTypes.set('ReusTranspor', RTMapType);
  map.setMapTypeId('ReusTranspor');
  pintaIncidencies();
  getParadas(idLinea);
 
}
function getParadas(idLinia){
	var res;var lin;
	
	$.get('./php/parades.php',{"id_linia": idLinia}, function(data) {
	 res=data.split("!!");


	paradas=new Array();
	 for(i=0;i<res.length-1;i++){
		 lin=res[i].split(';');
		 paradas[i] =[lin[1]+"-"+lin[2] ,lin[3],lin[4],i,lin[2]];
	 }
	 setMarkers(map, paradas,idLinia);	
	  if(idLinia!='0'){
		 directionsService= new google.maps.DirectionsService();
		    var quants=parseInt(10);
			var inici=markers[0];
			destruirVista();
			for(j=1;j<res.length;j++){
				renders[j]=new google.maps.DirectionsRenderer({preserveViewport:true,suppressMarkers:true,polylineOptions:{strokeColor:colorLinia}});
				renders[j].setMap(map);
				calcRoute1(inici.getPosition(),markers[j].getPosition(),j);
				inici=markers[j];
			}	 
			
	  }});	
}
function destruirVista(){
	for(i=0;i<renders.length;i++){
		if(renders[j]!=null){
			renders[j].setMap(null);
		}
	}
}
function calcRoute1(origin,destination,indexRender) {
		var mode=google.maps.DirectionsTravelMode.DRIVING;
		var request = {
			origin: origin,
			destination: destination,
			waypoints: waypoints,
			travelMode: mode,
			provideRouteAlternatives :false,
			optimizeWaypoints: false,
			avoidHighways:false,
			avoidTolls: true
		};
		directionsService.route(request, function(response, status) {
		  if (status == google.maps.DirectionsStatus.OK) {
			renders[indexRender].setDirections(response);
		  }
		});
		directionsVisible = true;
  }
function setMarkers(map, locations,idLinia) {
	var strImage="";
 	var image;
	switch(idLinia){
		 case '0':strImage='http://www.reustransport.cat/icoMaps/icoStopAll.png';colorLinia='#000000';break;
		 case '10':strImage='http://www.reustransport.cat/icoMaps/icoStopL10.png';colorLinia='#EB3D00';break;
		 case '11':strImage='http://www.reustransport.cat/icoMaps/icoStopL11.png';colorLinia='#90488A';break;
		 case '20':strImage='http://www.reustransport.cat/icoMaps/icoStopL20.png';colorLinia='#005CA9';break;
		 case '30':strImage='http://www.reustransport.cat/icoMaps/icoStopL30.png';colorLinia='#008463';break;
		 case '31':strImage='http://www.reustransport.cat/icoMaps/icoStopL31.png';colorLinia='#479585';break;
		 case '32':strImage='http://www.reustransport.cat/icoMaps/icoStopL32.png';colorLinia='#006C6C';break;
		 case '33':strImage='http://www.reustransport.cat/icoMaps/icoStopL33.png';colorLinia='#636B6E';break;
		 case '40':strImage='http://www.reustransport.cat/icoMaps/icoStopL40.png';colorLinia='#949494';break;
		 case '41':strImage='http://www.reustransport.cat/icoMaps/icoStopL41.png';colorLinia='#71706E';break;
		 case '42':strImage='http://www.reustransport.cat/icoMaps/icoStopL42.png';colorLinia='#615D5C';break;
		 case '50':strImage='http://www.reustransport.cat/icoMaps/icoStopL50.png';colorLinia='#63402C';break;
		 case '60':strImage='http://www.reustransport.cat/icoMaps/icoStopL60.png';colorLinia='#1DBBEB';break;
		 case '72':strImage='http://www.reustransport.cat/icoMaps/icoStopL72.png';colorLinia='#000000';break;
	}
	 image= new google.maps.MarkerImage(strImage,
      new google.maps.Size(23, 33),
      new google.maps.Point(0,0),
      new google.maps.Point(0, 32));
  var shadow = new google.maps.MarkerImage('http://www.reustransport.cat/icoMaps/shadowStop.png',

      new google.maps.Size(73, 38),
      new google.maps.Point(0,0),
      new google.maps.Point(0, 32));


  for (var i = 0; i <locations.length; i++) {
    var paradaBus = locations[i];
    var myLatLng = new google.maps.LatLng(paradaBus[1], paradaBus[2]);
    var marker = new google.maps.Marker({ 
        position: myLatLng,
        map: map,
        shadow: shadow,
        icon: image,
        shape: shape,
        title: paradaBus[0],
        zIndex: paradaBus[3]
    	});
	var texto = paradaBus[4];
	attachInfowindow(marker, texto); 
	 markers[markers.length]=marker;
  }
}
function attachInfowindow(marker, texto) {
		google.maps.event.addListener(marker, 'click', function() {
		if (infowindow) infowindow.close();
		var desc=marker.getTitle().split('-');
		$.post('./php/tiempoParadas.php',{"parada_id": desc[0],"nomParada":texto}, function(data) {	
		infowindow = new google.maps.InfoWindow( { content: '<p class="nombreParada">'+texto+'<span class="hora">'+hora()+'</span></p>'+data });
			infowindow.setZIndex(++infowindowLevel);
			cerrar();
			infowindow.open(map,marker);
			});	
	  } 
	  );
}
function hora(){
	var ahora = new Date() ;
	var hora=ahora.getHours();
	if (hora<=9){
		hora="0"+hora;
	}	
	var minutos=ahora.getMinutes();
	if (minutos<=9){
		minutos="0"+minutos;
	}
	var sec=ahora.getSeconds();
	if (sec<=9){
		sec="0"+sec;
	}	
	ahora=hora+":"+minutos+":"+sec;
	return ahora;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
//BUSCADOR
function buscaParada(dades){
	$.post('./php/buscadorParades.php',{"busqueda": dades}, function(data) {
		if(data==-1){	
				alert("S' ha de posar un número de parada");
		}else if(data==-2){alert("No coincideix amb cap parada");
		}else{
			
			document.getElementById('result').innerHTML=data;
			$('ul.live_filter').liveFilter('slide');
		}
	});
}

function paradaSeleccionada(id,text){
	var desc;
	var trobat=0;
	if(id!=0){
		for(i=0;i<markers.length;i++){
			desc=markers[i].getTitle().split('-');
			if(desc[0]==id){
				
				trobat=1;
				obreBubbleTrobat(markers[i],desc[1]);
				infowindow.open(map,markers[i]);
			}
		}
		if(trobat==0)alert("La parada buscada no correspon a la linia seleccionada");
	}
}

function obreBubbleTrobat(marker, texto){
	cerrar();
	if (infowindow){infowindow.close();infowindow=null;}
	
	var desc=marker.getTitle().split('-');
		$.post('./php/tiempoParadas.php',{"parada_id": desc[0]}, function(data) {							 
			infowindow = new google.maps.InfoWindow( { content: '<p class="nombreParada">'+texto+'<span class="hora">'+hora()+'</span></p>'+data });
			infowindow.setZIndex(++infowindowLevel);
			
			infowindow.open(map,marker);
			});	
}
//Quita texto deinput al hacer clic
function buscarInput(){
	 $('.filter').click(function() {
		if (this.value == this.defaultValue) {
			this.value = '';
		}
	});
	$('.filter').blur(function() {
		if (this.value == '') {
			this.value = this.defaultValue;
		}
	});	 
}

///////////////////////////////////////////////////////////////////////////////////////////////////
//MENU LINEAS SUPERIOR
function menuLineas(){
	var L0_html=$('#lineaTitol').html();
	
	var class2='L0';
	var html2=L0_html;
	
	var pdf='guiaGeneral';
	
	$('#menuLineas li').click(function() {
		var id= this.id;
		//titulo
		$('#lineaTitol').removeClass().addClass(id);
		var titol= $(this).attr('rel');	
		$('#lineaTitol').html(titol);
		
		//pdf
		$('#pdf_horaris_in').removeClass().addClass(this.id);
		$('#pdf_horaris_in a').each(function() {
			$(this).attr("href", "pdf/"+id+".pdf"); 
		});
		$('#pdf_horaris_in .linia').attr("src", "img/"+id+".jpg"); 
		pdf=id;
		
		class2=id;
		html2=titol;
		
		
		if (id!='guiaGeneral'){
			var prefix ='L';	
			removeMarkers();
			initialize(id.substring( ( prefix.length ) ) );			
		}else{
			removeMarkers();
			initialize('0');		
		}	
		return false;		
    });
	$("#menuLineas li").hover(function (){
		$('#lineaTitol').removeClass().addClass(this.id);
		var titol= $(this).attr('rel');	
		$('#lineaTitol').html(titol);
		
		//pdf
		$('#pdf_horaris_in').removeClass().addClass(this.id);
		$('#pdf_horaris_in .linia').attr("src", "img/"+this.id+".jpg"); 
	 },function () {
		$('#lineaTitol').removeClass().addClass(class2);
		$('#lineaTitol').html(html2);
		
		//pdf
		$('#pdf_horaris_in').removeClass().addClass(pdf);
		$('#pdf_horaris_in .linia').attr("src", "img/"+pdf+".jpg"); 
  	});
}

function removeMarkers(){
	for(i=0;i<markers.length;i++){
		markers[i].setMap(null);
	}
	 markers=new Array();
}


///////////////////////////////////////////////////////////////////////////////////////////////////
//HORARIOS TEORICOS
function horariosTeoricos(id){
	loading("#infoLineas");
	if ($("#googleMapWrap").css('marginRight') == '0px') {
		$("#infoLineas").fadeTo(300,1);
		$("#colIzIndex").animate({ marginRight: 240},600);	
		
		$("#infoLineas").animate({ marginRight: 1},600);
	}
	$.get("php/horariosTeoricos.php", {"id":id}, function(data){$("#horariosTeoricos").html(data);fadeloading();},"html");
	
}
function cerrar(){
	if ($("#colIzIndex").css('marginRight') == '240px') {
		
		$("#colIzIndex").animate({ marginRight: 0},600);	
		$("#infoLineas").animate({ marginRight: -250},600,function () {	
			$("#infoLineas").css({'display':'none'});
		});	
	}
}

///////////////////////////////////////////////////////////////////////////////////////////////////
//INCIDENCIAS MAPA
 function pintaIncidencies(){
	 var image;
	 image= new google.maps.MarkerImage('http://www.reustransport.cat/icoMaps/icoIncidencia.png',
      new google.maps.Size(35, 44));
	 
 
 	var shadow = new google.maps.MarkerImage('http://www.reustransport.cat/icoMaps/shadowIncidencia.png',
      new google.maps.Size(70, 44),
      new google.maps.Point(0,0),
      new google.maps.Point(17, 48));
	
	 $.post('./php/recuperaIncidencies.php',{"id_linia": 'idLinia'}, function(data) {														  
			var dades=data.split('||');
			var subd;var latlon;
			for(i=0;i<dades.length-1;i++){
				subd=dades[i].split('&');
				latlon=subd[1].split(',');
					 var myLatLng = new google.maps.LatLng(latlon[0],latlon[1]);
					var marker = new google.maps.Marker({ 
						position: myLatLng,
						map: map,
						shadow: shadow,
						icon: image,
						shape: shape,
						title: "INCIDENCIA",
						zIndex: 1000
						});
					var texto = subd[0];
						attachInfowindow(marker, texto);
					 markers[markers.length]=marker;
			}
	});
 }
///////////////////////////////////////////////////////////////////////////////////////////////////
//INCIDENCIAS CABECERA
function incidencies(){
	var altoLista=$("#scrollWrap ul").height();
	if (altoLista>200){
		$("#scrollWrap").css({'height':'200px'});		
		CSBfleXcroll('scrollWrap');		
	}
	$("#incidencies_cerrar").hide();
	$("#scrollWrap").hide();
	
	 $('#incidencies_bt').click(function() {
		if ($("#incidencies_wrap").css('width') == '400px') {
			incidencies_cerrar();
		}else{
			incidencies_abrir();
		}
	});
	 
	$("#incidencies_cerrar").click(function() {
		incidencies_cerrar();
	});
	 
}
function incidencies_abrir(){	
		$("#idiomas").animate({'margin-right':'420px'},200);	
		$("#incidencies .titol img").hide();
		$("#incidencies_wrap").css({'width':'400px','text-align':'left'});	
		$("#incidencies").css({'padding':'10px 10px 15px 10px','height':'auto'});	
		$("#incidencies_bt").html('<img src="img/incidencias_cerrar.jpg" alt="Cerrar" />');
		$("#incidencies_cerrar").show();
		$("#scrollWrap").slideDown();		
}
function incidencies_cerrar(){
		$("#idiomas").animate({'margin-right':'130px'},200);
		$("#incidencies .titol img").show();
		$("#incidencies_wrap").css({'width':'120px','text-align':'center'});	
		$("#incidencies").css({'padding':'0px','height':'59px'});
		$("#incidencies_bt").html('<img src="img/incidencias_abrir.jpg" alt="Abrir" />');
		$("#incidencies_cerrar").hide();
		$("#scrollWrap").hide();	
}
///////////////////////////////////////////////////////////////////////////////////////////////////
//READY FUNCTION
 $(document).ready(function(){	
	incidencies();
});
