var map;
var route;
var actualRoute1;
var actualRoute2;
var actualRoute3;
var actualRoute4;
var actualRoute5;
var actualRoute6;
var POIs = [];
var marker = [];
var baseIcon;
var icon13;
var mapControl;
var mapScale;
var polyline1;
var polyline2;
var polyline3;
var polyline4;
var polyline5;
var polyline6;
var linesArray;

function initialize() {

	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("gmap"));
		map.setCenter(new GLatLng(-26, 134), 5);
		mapControl = new GLargeMapControl()
		mapScale = new GScaleControl();
		
		route = new GDirections(map);
		actualRoute1 = new GDirections();
		actualRoute2 = new GDirections();
		actualRoute3 = new GDirections();
		actualRoute4 = new GDirections();
		actualRoute5 = new GDirections();
		actualRoute6 = new GDirections();
		GEvent.addListener(actualRoute1, "load", actualRoute1Loaded);
		GEvent.addListener(actualRoute2, "load", actualRoute2Loaded);
		GEvent.addListener(actualRoute3, "load", actualRoute3Loaded);
		GEvent.addListener(actualRoute4, "load", actualRoute4Loaded);
		GEvent.addListener(actualRoute5, "load", actualRoute5Loaded);
		GEvent.addListener(actualRoute6, "load", actualRoute6Loaded);


		baseIcon = new GIcon();
		baseIcon.iconSize=new GSize(32,32);
		baseIcon.shadowSize=new GSize(56,32);
		baseIcon.iconAnchor=new GPoint(16,32);
		baseIcon.infoWindowAnchor=new GPoint(16,0);

		icon13 = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal2/icon13.png", null, "http://maps.google.com/mapfiles/kml/pal2/icon27s.png");

		// add dragable marker to south pole
		var dragMarker = new GMarker(new GLatLng(-66.93006025862445, 140.44921875), {	draggable: true	});
		GEvent.addListener(dragMarker, "dragstart", function() { map.closeInfoWindow(); });
		GEvent.addListener(dragMarker, "dragend", function() { dragMarker.openInfoWindowHtml("drag me, if you can..<br>"+String(dragMarker.getLatLng())); });
		map.addOverlay(dragMarker);

		var mtbRace = new GGeoXml("http://blog.lfalke.de/gmaps/24hrace.kml");
		map.addOverlay(mtbRace);
		addPOI();

//		Great Barrier Reef Polygon
//		var point=[];
//		var poly=[];
//		var line;
//
//		point.push(new GLatLng(-17.350638, 145.986328));
//		point.push(new GLatLng(-14.689881, 145.151367));
//		point.push(new GLatLng(-13.880746, 143.876953));
//		point.push(new GLatLng(-9.665738, 142.646484));
//		point.push(new GLatLng(-13.154376, 144.799805));
//		point.push(new GLatLng(-13.923404, 145.942383));
//		point.push(new GLatLng(-17.811456, 147.348633));
//		point.push(new GLatLng(-19.186678, 149.941406));
//		point.push(new GLatLng(-21.861499, 152.622070));
//		point.push(new GLatLng(-21.902278, 151.127930));
//		point.push(new GLatLng(-20.427013, 149.458008));
//		point.push(new GLatLng(-19.020577, 147.128906));
//		point.push(new GLatLng(-17.350638, 145.986328));
//
//
//		poly.length=0;
//
//		for(var i=0; i<13; i++)
//		{
//			poly.push(point[i]);
//		}
//		line = new GPolygon(poly,'#FF0000', 3, 1,'#FF0000',0.2);
//		map.addOverlay(line);
//		map.openInfoWindow(new GLatLng(-19.186678, 149.941406), document.createTextNode("Great Barrier Reef"));
	}
}

/**
 * create the markers
 */
function populateMap(points)
{
	for (var i=0; i < points.length; i++) {
		var label = points[i].title;
		points[i].marker = new GMarker(points[i],{
			title: label
		});
		POIs.push(points[i].marker);
		map.addOverlay(points[i].marker);
		createInfoWindow(points[i]);
	}
}

/**
 * A general helper function for creating html elements. <div> as default element type
 * @author Esa 2008
 * used for infowindows and sidebar
 */
function createElem(opt_className, opt_html, opt_tagName) {
	var tag = opt_tagName||"div";
	var elem = document.createElement(tag);
	if (opt_html) elem.innerHTML = opt_html;
	if (opt_className) elem.className = opt_className;
	return elem;
}

/**
 * create infowindow
 */
function createInfoWindow(point){
	var iwNode = createElem("gmap-iw");

	iwNode.appendChild(createElem("gmap-iw-title", point.title));
	iwNode.appendChild(createElem("gmap-iw-text", point.text));

	point.marker.bindInfoWindow(iwNode,{
		maxWidth:300
	});
}

/**
 * parseCsv()
 * @return an array of GLatLng() objects
 * @author Esa 2008
 * modifed by lf
 */
String.prototype.parseCsv = function(opt_options)
{
	var results = [];
	var lines = this.split("\n");
	for (var i=0; i<lines.length; i++)
	{
		var lineArray = lines[i].split("##");
		var lat = parseFloat(lineArray[0]);
		var lng = parseFloat(lineArray[1]);
		var point = new GLatLng(lat,lng);

		if(!isNaN(lat+lng))
		{
			if(typeof lineArray[2] != 'undefined')	point.title = String(lineArray[2]);
			else																		point.title = '';
			if(typeof lineArray[3] != 'undefined')	point.text  = String(lineArray[3]);
			else																		point.text  = '';
			results.push(point);
		}
	}
	return results;
}

function addPOI()
{
	GDownloadUrl("http://blog.lfalke.de/gmaps/getMarker.php", function(material){ populateMap(material.parseCsv(material)); });
}

function removePOI()
{
	for(var i = 0; i < POIs.length; i++)
		map.removeOverlay(POIs[i]);
	POIs = [];
}

function addActualRoute()
{
	if(actualRoute1.getStatus().code != 200)
		GDownloadUrl("http://blog.lfalke.de/gmaps/getActualRoute.php", function(material) {
			linesArray = getWaypoints(material);
			
			/*alert(linesArray[0].join(" # ") + "\n\n" + 
					linesArray[1].join(" # ") + "\n\n" + 
					linesArray[2].join(" # ") + "\n\n" + 
					linesArray[3].join(" # "));
			*/
			actualRoute1.loadFromWaypoints(linesArray[0], { getPolyline:true });
		});
	else
	{
		if(actualRoute1.getStatus().code == 200)		map.addOverlay(actualRoute1.getPolyline());
		if(actualRoute2.getStatus().code == 200)		map.addOverlay(actualRoute2.getPolyline());
		if(actualRoute3.getStatus().code == 200)		map.addOverlay(actualRoute3.getPolyline());
		if(actualRoute4.getStatus().code == 200)		map.addOverlay(actualRoute4.getPolyline());
		if(actualRoute5.getStatus().code == 200)		map.addOverlay(actualRoute5.getPolyline());
		if(actualRoute6.getStatus().code == 200)		map.addOverlay(actualRoute6.getPolyline());
	}
}

function actualRoute1Loaded()
{
	polyline1 = actualRoute1.getPolyline();
	polyline1.setStrokeStyle({color: '#FF0000', weight: 3, opacity: 0.65 });
	map.addOverlay(polyline1);
	
	if(linesArray.length > 1)
		actualRoute2.loadFromWaypoints(linesArray[1], { getPolyline:true });
}

function actualRoute2Loaded()
{
	polyline2 = actualRoute2.getPolyline();
	polyline2.setStrokeStyle({color: '#FF0000', weight: 3, opacity: 0.65 });
	map.addOverlay(polyline2);
	
	if(linesArray.length > 2)
		actualRoute3.loadFromWaypoints(linesArray[2], { getPolyline:true });
}

function actualRoute3Loaded()
{
	polyline3 = actualRoute3.getPolyline();
	polyline3.setStrokeStyle({color: '#FF0000', weight: 3, opacity: 0.65 });
	map.addOverlay(polyline3);
	
	if(linesArray.length > 3)
		actualRoute4.loadFromWaypoints(linesArray[3], { getPolyline:true });
}

function actualRoute4Loaded()
{
	polyline4 = actualRoute4.getPolyline();
	polyline4.setStrokeStyle({color: '#FF0000', weight: 3, opacity: 0.65 });
	map.addOverlay(polyline4);
	
	if(linesArray.length > 4)
		actualRoute5.loadFromWaypoints(linesArray[4], { getPolyline:true });
}

function actualRoute5Loaded()
{
	polyline5 = actualRoute5.getPolyline();
	polyline5.setStrokeStyle({color: '#FF0000', weight: 3, opacity: 0.65 });
	map.addOverlay(polyline5);
	
	if(linesArray.length > 5)
		actualRoute6.loadFromWaypoints(linesArray[5], { getPolyline:true });
}

function actualRoute6Loaded()
{
	polyline6 = actualRoute6.getPolyline();
	polyline6.setStrokeStyle({color: '#FF0000', weight: 3, opacity: 0.65 });
	map.addOverlay(polyline6);
}

function removeActualRoute()
{
	if(actualRoute1.getStatus().code == 200)		map.removeOverlay(actualRoute1.getPolyline());
	if(actualRoute2.getStatus().code == 200)		map.removeOverlay(actualRoute2.getPolyline());
	if(actualRoute3.getStatus().code == 200)		map.removeOverlay(actualRoute3.getPolyline());
	if(actualRoute4.getStatus().code == 200)		map.removeOverlay(actualRoute4.getPolyline());
	if(actualRoute5.getStatus().code == 200)		map.removeOverlay(actualRoute5.getPolyline());
	if(actualRoute6.getStatus().code == 200)		map.removeOverlay(actualRoute6.getPolyline());
}

function addRoute()
{
	if(route.getStatus().code == 500)
		GDownloadUrl("http://blog.lfalke.de/gmaps/getRoute.php", function(material) {
			lines = material.split("\n");
			lines.pop();
			route.loadFromWaypoints(lines, { preserveViewport: true });
		});
	else
	{
		map.addOverlay(route.getPolyline());
		for(i = 0; i < route.getNumGeocodes(); i++)
			map.addOverlay(route.getMarker(i));
	}
}

function removeRoute()
{
	map.removeOverlay(route.getPolyline());
	for(i = 0; i < route.getNumGeocodes(); i++)
		map.removeOverlay(route.getMarker(i));
}

function getWaypoints(material)
{
	lines = material.split("\n");
	lines.pop();
	
	var linesArray = [];
	for(i = 1; i < lines.length; i += 10)
	{
		linesArray.push(lines.slice(i-1,i+10));
	}

	return linesArray;
}


function addMarker(lat, lng, title)
{
	showMap(null);
	(function(){
		var m = new GMarker(new GLatLng(lat, lng), icon13);
		var found = -1;

		for(i=0; i<marker.length && found == -1; i++)
			if(marker[i].getLatLng().equals(m.getLatLng()))
				found = i;
		
		if(found == -1)
		{
			m.bindInfoWindow(title);
			map.addOverlay(m);
			m.openInfoWindow(title);
			marker.push(m);
		}
		else
			marker[found].openInfoWindow(title);

	}).delay(800);
}



function toggleMap(x)
{
	var morph = new Fx.Morph($(x));

	if($(x).hasClass("mapbuttonActive"))
	{
		morph.start('.mapbuttonInactive').chain(function() { $(x).removeClass('mapbuttonActive'); $(x).addClass('mapbuttonInactive'); });
		if(x == 'poi')
			removePOI();
		else if(x == 'route')
			removeRoute();
		else if(x == 'actualRoute')
			removeActualRoute();
	}
	else
	{
		morph.start('.mapbuttonActive').chain(function() { $(x).removeClass('mapbuttonInactive'); $(x).addClass('mapbuttonActive'); });
		if(x == 'poi')
			addPOI();
		else if(x == 'route')
			addRoute();
		else if(x == 'actualRoute')
			addActualRoute();
	}
}



function hideall()
{
	var arr = new Array('poi', 'route', 'actualRoute', 'posts');

	for(i=0; i<arr.length; i++)
	{
		if($(arr[i]).hasClass('mapbuttonActive'))
		{
			var x = arr[i];
			var morph = new Fx.Morph($(x));
			morph.start('.mapbuttonInactive').chain(function() { $(x).removeClass('mapbuttonActive'); $(x).addClass('mapbuttonInactive'); });
		}
	}
	map.clearOverlays();
	marker = [];
}
