var map;
var gdir;
var geocoder = null;
var addressMarker;

$(document).ready(function() {
	jQuery(window).load(function() {
        	initialize();
			
			if( $.query.get('from') != "" && $.query.get('to') != "" &&  $.query.get('locale') != "") {
				$('#fromAddress').val($.query.get('from'));
				$('#toAddress').val($.query.get('to'));
				setDirections($.query.get('from'), $.query.get('to'), $.query.get('locale'))
			}
			
			// initialize the action value to the current url
			var currentUtl = window.location.href.split("?")[0];
			$('#directions_form').attr("action", currentUtl + "#car-panel-button");
			
     });
	/*$("#toggleHide").click(function(){
			$("#directions-panel").slideToggle("slow");

		//$(this).next().slideUp();
		//$("#public-transit-panel").slideToggle("slow");
		//$(this).toggleClass("panel-active"); return false;
	});*/
	$("#print-icon").click(function(){
				
		var fromAddress = $.query.get('from');
		var toAddress = $.query.get('to');
		var locale = $('#print-icon').attr("locale");
		var currentQuery = $.query.copy();
		//var queryString = $.query.set("fromAddress", fromAddress).set("toAddress", toAddress).set("locale", locale).toString();
		//alert(queryString);
		
		var printWin = window.open("../contact/print_directions.html" + currentQuery, "", "width=760,height=980, scrollbars=1");
		
	});

});

function initialize() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map_canvas"));
		gdir = new GDirections(map, document.getElementById("directions"));
		geocoder = new GClientGeocoder();
		map.setCenter(new GLatLng(47.3587476, 8.5211645), 3);
		map.addControl(new GLargeMapControl());
                map.addControl(new GMapTypeControl());
                map.addControl(new GOverviewMapControl() ); 
	
		GEvent.addListener(gdir, "load", showPrintButton);
		GEvent.addListener(gdir, "error", handleErrors);
		GEvent.addListener(gdir, "addoverlay", onGDirectionsLoad);
		

		/*setDirections("Bubenbergstrasse 11, 8045 Zürich, Switzerland (Comerge)",
				"Bubenbergstrasse 11, 8045 Zürich, Switzerland (Comerge)", "en");*/
		//alert("initializing");
	}
}


function showPrintButton() {
	// if the entered starting point is correct then show the print icon
	if(gdir.getStatus().code == 200){
		$(document).ready(function() {
			$("#print-icon").show();

		});
	}
}

function setDirections(fromAddress, toAddress, locale) {
	/*gdir.load("from: " + fromAddress + " to: " + toAddress, {
		"locale" : locale
	});*/
	
	/*if(locale == "en") {
		alert("here");
		$.query.set('locale', 'en');
	} else if(locale == "de") {
		$.query.set('locale', 'de');
	}*/
	convertLatAndShow(fromAddress, toAddress, locale);
}

function convertLatAndShow(fromaddress, toaddress, locale) {

  geocoder.getLatLng(
    fromaddress,
    function(frompoint) {
      if (!frompoint) {
        alert(fromaddress + " not found");
      } else {
	geocoder.getLatLng(
    	toaddress,
    	function(topoint) {
    	if (!topoint) {
        	alert(toaddress + " not found");
      	} else {
		showDirectionsPanel();
        	gdir.load("from: " + frompoint + " to: " + topoint, {
			"locale" : locale});
	//alert("from: " + frompoint + " to: " + topoint);
      }
    }
  );
      }
    }
  );
	  
}

function showDirectionsPanel() {
	$(document).ready(function() {
		if($("#directions-panel").css("display") == "none")
		{	//alert("none");
			
			
			$("#directions-panel").show();
			map.checkResize();
			map.setCenter(new GLatLng(47.3587476, 8.5211645), 3);
		}
	});
}

function handleErrors() {
	if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS) {
		alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: "
				+ gdir.getStatus().code);
	} else if (gdir.getStatus().code == G_GEO_SERVER_ERROR) {
		alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: "
				+ gdir.getStatus().code);
	} else if (gdir.getStatus().code == G_GEO_MISSING_QUERY) {
		alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: "
				+ gdir.getStatus().code);
	} else if (gdir.getStatus().code == G_GEO_BAD_KEY) {
		alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: "
				+ gdir.getStatus().code);
	} else if (gdir.getStatus().code == G_GEO_BAD_REQUEST) {
		alert("A directions request could not be successfully parsed.\n Error code: "
				+ gdir.getStatus().code);
	} else {
		alert("An unknown error occurred.");
	}

	$(document).ready(function() {
		if($("#print-icon").css("display") != "none")
		{	//alert("none");
			
			
			$("#print-icon").hide();
		}
	});
	return;
	
}

function onGDirectionsLoad() {
	var poly = gdir.getPolyline();
	if (poly.getVertexCount() > 5000) {
		alert("This route has too many vertices");
		return;
	}
	var baseUrl = "http://maps.google.com/staticmap?";

	var params = [];
	var markersArray = [];
	markersArray.push(poly.getVertex(0).toUrlValue(5) + ",greena");
	markersArray.push(poly.getVertex(poly.getVertexCount() - 1).toUrlValue(5)
			+ ",greenb");
	params.push("markers=" + markersArray.join("|"));

	var polyParams = "rgba:0x0000FF80,weight:5|";
	var polyLatLngs = [];
	for ( var j = 0; j < poly.getVertexCount(); j++) {
		polyLatLngs.push(poly.getVertex(j).lat().toFixed(5) + ","
				+ poly.getVertex(j).lng().toFixed(5));
	}
	params.push("path=" + polyParams + polyLatLngs.join("|"));
	params.push("size=300x300");
	params.push("key=ABQIAAAAJfeTBqHtt5kjcApmFu42gBTwYzLkllwS4J2GcJEnHCl6ktTa9RTKJA-X5kn6O2U0WKKxbKIZ8PFD-w");

	baseUrl += params.join("&");

	var extraParams = [];
	extraParams.push("center=" + map.getCenter().lat().toFixed(6) + ","
			+ map.getCenter().lng().toFixed(6));
	extraParams.push("zoom=" + map.getZoom());
	addImg(baseUrl + "&" + extraParams.join("&"), "staticMapOverviewIMG");

	var extraParams = [];
	extraParams.push("center=" + poly.getVertex(0).toUrlValue(5));
	extraParams.push("zoom=" + 15);
	addImg(baseUrl + "&" + extraParams.join("&"), "staticMapStartIMG");

	var extraParams = [];
	extraParams.push("center="
			+ poly.getVertex(poly.getVertexCount() - 1).toUrlValue(5));
	extraParams.push("zoom=" + 15);
	addImg(baseUrl + "&" + extraParams.join("&"), "staticMapEndIMG");
}

function addImg(url, id) {
	var img = document.createElement("img");
	img.src = url;
	document.getElementById(id).innerHTML = "";
	document.getElementById(id).appendChild(img);
}
