﻿var baseStopIcon = null;
var baseShadowIcon = null;
var map = null;

function createStopMarker(stop, zIndex) {
	var myLatLng = new google.maps.LatLng(stop[1], stop[2]);
	var stopMarker = new google.maps.Marker({
		position: myLatLng,
	    map: map,
	    icon: baseStopIcon,
	    shadow: baseShadowIcon,
	    zIndex: zIndex,
	    title: stop[3]
	});
	
	var contentString = '<b>' + stop[3] + '</b><br /><div id="infobox_details"><img src="/images/ajax-loader.gif" /></div>';
	  
	var infowindow = new google.maps.InfoWindow({
		content: contentString,
	    maxWidth: 200
	});
	  	  
	google.maps.event.addListener(stopMarker, 'click', function() {
		infowindow.open(map, stopMarker);
		$.get('/ajax/stop_details/' + stop[0] + '/', function(data) {
			infowindow.setContent('<b>' + stop[3] + '</b><br />' + data, { maxWidth: 200 });
			screenshotPreview();
		});
	});

	return stopMarker;	  
}

function drawTrip(jsonDATA) { 
	if (jsonDATA.color) {
	    color = jsonDATA.color;
	} else {
		color = "#0000FF";
	}
	
	//poly
	var tripPath = new google.maps.Polyline({
	    path: google.maps.geometry.encoding.decodePath(jsonDATA.points),
	    strokeColor: color,
	    strokeOpacity: 0.8,
	    strokeWeight: 4
	});
	
	var bounds = new google.maps.LatLngBounds();
	
	tripPath.getPath().forEach(function (element, index) {
		bounds.extend(element);
	});
	
	tripPath.setMap(map);
	map.fitBounds(bounds);
	
	//stops
	var stops = jsonDATA.stops;
	for(var i=0; i < stops.length; i++) {
		createStopMarker(stops[i], stops.length - i);
	};
};
	
function downloadAndDrawTrip(trip_id) {
	//remove poly & stops
	if (document.poly) {
		document.map.removeOverlay(document.poly);
	}
	
	if (trip_id) {
		$.ajax({
			url: '/ajax/get_poly/' + trip_id,
			type: 'GET',
			dataType: 'json',
			timeout: 3000,
			tryCount : 0,
			retryLimit : 3,
			success: function(jsonDATA) {
				drawTrip(jsonDATA);
			},
			error : function(xhr, textStatus, errorThrown ) {
				if (textStatus == 'timeout') {
					this.tryCount++;
					if (this.tryCount <= this.retryLimit) {
						//try again
						$.ajax(this);
						return;
					}
					alert('Não foi possível conectar-se ao servidor para baixar esta rota. Por favor, tente recarregar a página.');
					return;
				}
				if (xhr.status == 500) {
					alert('Oops! Houve um erro com o servidor. Desculpe!');
				} else {
					alert('Oops! Ocorreu um erro. Tente mais tarde, por favor.');
				}
			}
		});
	}
};

function createMap() {
	baseStopIcon = new google.maps.MarkerImage("/images/bus_stop.png", 
			new google.maps.Size(32, 37),  //size
			new google.maps.Point(0, 0),   //origin
			new google.maps.Point(16, 16),  //anchor
			new google.maps.Size(20, 20)   //scaledSize
	);
	
	baseShadowIcon = new google.maps.MarkerImage("/images/shadow.png", 
			new google.maps.Size(51, 37),  //size
			new google.maps.Point(0, 0),   //origin
			new google.maps.Point(16, 16),  //anchor
			new google.maps.Size(32, 20)   //scaledSize
	); 
				
	var latlng = new google.maps.LatLng(-23.55258, -46.631579);
	var myOptions = {
	  zoom: 12,
	  center: latlng,
	  mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  
};
					
$(document).ready(function(){
	if ($("#map_canvas").length == 1) {
		createMap();
		if (jsonDATA) {
			drawTrip(jsonDATA);
		} else if (trip_id) {
			downloadAndDrawTrip(trip_id);
		}
	}
});


//autocomplete
$(document).ready(function(){
	if ($("#trips").length == 1) {
		$.ajax({
			  url: "/ajax/autocomplete",
			  dataType: "json",
			  success: 	function(jsonDATA) {
				$("#trips").autocomplete(jsonDATA, {
					matchContains: true,
					formatItem: function(item) {
						return item.text;
					}
				}).result(function(event, item) {
					location.href = item.url;
				});
			  }
		});
	}
});

//screenshot
/*
 * Url preview script 
 * powered by jQuery (http://www.jquery.com)
 * 
 * written by Alen Grakalic (http://cssglobe.com)
 * 
 * for more info visit http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery
 *
 */
 
this.screenshotPreview = function(){	
	/* CONFIG */
		
		xOffset = 10;
		yOffset = 30;
		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result
		
	/* END CONFIG */
	$("a.screenshot").hover(function(e){
		this.t = this.title;
		this.title = "";	
		var c = (this.t != "") ? "<br/>" + this.t : "";
		$("body").append("<p id='screenshot'><img src='"+ this.rel +"' alt='url preview' />"+ c +"</p>");								 
		$("#screenshot")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");						
    },
	function(){
		this.title = this.t;	
		$("#screenshot").remove();
    });	
	$("a.screenshot").mousemove(function(e){
		$("#screenshot")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});			
};

//starting the script on page load
$(document).ready(function(){
	screenshotPreview();
});
