var stops = [];

function getActiveStop() {
	for (var i = 0; i < stops.length; ++i) {
		if (stops[i].isActive()) {
			return stops[i];
		}
	}
	return null;
}

function daysBetween(date1, date2) {
    // The number of milliseconds in one day
    var ONE_DAY = 1000 * 60 * 60 * 24

    // Convert both dates to milliseconds
    var date1_ms = date1.getTime()
    var date2_ms = date2.getTime()

    // Calculate the difference in milliseconds
    var difference_ms = Math.abs(date1_ms - date2_ms)
    
    // Convert back to days and return
    return Math.round(difference_ms/ONE_DAY)
}

function Stop(xml_node) {
	this.next = null;
	this.previous = null;

	this.name = xml_node.name;
	this.days = xml_node.days;
	
	var regex = /(\d+).(\d+).(\d+)/;
	var result = regex.exec(xml_node.from);
	if (result != null) {
		this.from = new Date(result[3], result[2] - 1, result[1]);
	} else {
		this.from = null;
	}
	this.description = xml_node.description[0].Text;
	this.blog_entries = xml_node.blog[0].entry;

	//-- Marker --//
	var position = new GLatLng(
			xml_node.position[0].latitude,
			xml_node.position[0].longitude);
	
	var opts = {
		title: xml_node.number,
		icon: MapIconMaker.createMarkerIcon({width: 32, height: 32, primaryColor: "#3121FF"})
	};

	this.marker = new GMarker(position, opts);
	
	// HINT strange - but works. Find out if ther is no other way or if this is the way to go (-> closures)
	var me = this;
	GEvent.addListener(this.marker, "click", 
			function() {
				me.setActive();
			});
	//--\ Marker \--//
	
	this.active = false;
	
	this.setActive = function() {
		var active = getActiveStop();
		if (active != null) {
			active.setInactive();
		}
		
		var active_style = {color: "#ff0000",
				ocupacity: 0.8,
				weight: 6};

		this.marker.openInfoWindowHtml(this.getDescription());
		if (this.movement != null) {
			this.movement.setStrokeStyle(active_style);
		}
		
		this.active = true;
	}
	
	this.setInactive = function () {
		var default_style = {color: "#0000ff",
							ocupacity: 0.8,
							weight: 6};
		
		this.marker.closeInfoWindow();
		if (this.movement != null) {
			this.movement.setStrokeStyle(default_style);
		}
		
		this.active = false;
	}
	
	this.isActive = function() {
		return this.active;
	}
	
	//-- Description --//
	this.getDescription = function() {
		var description = '<div class="infoWindow">' +
							'<h1>' + this.name + "</h1>";

		description += '<div class="smallInfo">';
		if (this.days == 1) {
			description += '<span class="days">' + this.days + ' Tag</span>';
		} else if (this.days == '?') {
			if (this.from != null) {
				var diff = daysBetween(this.from, new Date());
				description += '<span class="days">' + diff + ' Tage bis jetzt...</span>';
			} else {
				description += '<span class="days">' + this.days + ' Tage bis jetzt...</span>';
			}
		} else {
			description += '<span class="days">' + this.days + ' Tage</span>';
		}
		
		if (this.movement != null) {
			description += '<span class="distance">' + Math.ceil(this.movement.getLength() / 1000) + 'km</span>';
		}
		description += '</div>';
							
		if (this.description != '') {
			description += '<p class="description">' + this.description + '</p>';
		}
							
		if (this.blog_entries != null) {
			description += '<h2>Blog-Eintr&auml;ge</h2>' +
							'<ul>';
			
			for (var i = 0; i < this.blog_entries.length; i++) {
				description += '<li><a target="_new" href="' + this.blog_entries[i].url + '">' +
						this.blog_entries[i].title + '</a></li>';
			}
				
			description += '</ul>' +
							'<p>';
		}
		
		if (this.previous != null) {
			description += '<a href="#" class="back" onclick="getActiveStop().previous.setActive(); return false;">&lt;&lt; Zur&uuml;ck</a>';
		}
		if (this.next != null) {
			description += '<a href="#" class="foreward" onclick="getActiveStop().next.setActive(); return false;">Vor &gt;&gt;</a>';
		}
		
		description += '</p>';
		
		return description;
	}
	//--\ Description \--//
	
	//-- Movement --//
	if (xml_node.movement[0].points[0].Text != "") {
		var movement = new GPolyline.fromEncoded({
				color: "#0000ff",
				ocupacity: 0.8,
				weight: 6,
				points: xml_node.movement[0].points[0].Text,
				levels: xml_node.movement[0].levels[0].Text,
				zoomFactor: 32,
				numLevels: 4
				});
		
		this.movement = movement;
	} else {
		this.movement = null;
	}
	//--\ Movement \--//
}

function init() {
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById("map"));
		map.setCenter(new GLatLng(-26.35249785815401, 136.58203125), 4);

		map.addMapType(G_PHYSICAL_MAP);
		map.setMapType(G_PHYSICAL_MAP);
		
		map.addControl(new ExtLargeMapControl());
		map.addControl(new GMapTypeControl());
		
		map.enableScrollWheelZoom();
		map.enableContinuousZoom();

		GDownloadUrl("trip.xml?fuckingcache=" + Math.random(), 
				function(data, status) {
					if (status != 200) {
						alert("Unable to load xml data :-(");
						return;
					}
					
					var trip = XMLObjectifier.xmlToJSON(data);
					
					for (var i = 0; i < trip.stop.length; i++) {
						var stop = new Stop(trip.stop[i]);
						stops.push(stop);
						
						if (i != 0) {
							stops[i - 1].next = stop;
							stop.previous = stops[i - 1];
						}
						
						map.addOverlay(stop.marker);

						if (stop.movement != null) {
							map.addOverlay(stop.movement);
						}
					}
				}
		);
	}
}
