// control file for
// retorte.ch koordinator
// a google maps mod
// (c) nico waldispuehl 2008
// version 0.3

// Declare some global variables
var map, marker;
var searchedWithQuery;
var queryFieldInactiveTextColor = "#AAAAAA";
var queryFieldActiveTextColor = "black";

// Define standard stuff
var startZoom = 8;
var startLat = 46.815099;
var startLng = 8.22876;
var startQuery = "";
var standardMapType = G_NORMAL_MAP;
var startMapType = standardMapType;








// Initialization
function load() {
  if (GBrowserIsCompatible()) {
    
    // Create new map object
    map = new GMap2(document.getElementById("map"));

    // Do some configuration
    map.enableScrollWheelZoom();
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    map.addControl(new GScaleControl());
    map.addMapType(G_PHYSICAL_MAP);
    
    searchedWithQuery = false;

    // Check if there are some url parameters
    if(window.location.search != "")
    {
      // Check if the data makes sense
      var urlParams = parseUrlParams(window.location.search);
      
      if(urlParams["pos"])
      {
        var posParams = urlParams["pos"].split(",");
        var latLngParams = swissGridToCoords(posParams[0], posParams[1]);
        
        startLat = latLngParams[0];
        startLng = latLngParams[1];
        
        updateCoords(posParams[0], posParams[1]);
      }
      
      if(urlParams["zoom"])
      {
        startZoom = urlParams["zoom"] * 1;
        
      }
      
      if(urlParams["map"])
      {
        switch (urlParams["map"]) {      
          case "1":
            startMapType = G_NORMAL_MAP;
            break;
            
          case "2":
            startMapType = G_SATELLITE_MAP;
            break;
            
          case "3":
            startMapType = G_HYBRID_MAP;
            break;
            
          case "4":
            startMapType = G_PHYSICAL_MAP;
            break;
             
          default:
            startMapType = standardMapType;
            break;
        }
      }
      
      if(urlParams["query"])
      {
        var query = decodeURI(urlParams["query"]);
        var geoCoder = new GClientGeocoder();
    		geoCoder.getLatLng(query,
    		function(pos)
      		{
      			if(pos)
      			{
      			  map.panTo(pos);
				      marker.setLatLng(pos);
				  
      				var swissGrid = coordsToSwissGrid(pos.lat(),pos.lng());
      				
      				startLat = swissGrid[0];
              startLng = swissGrid[1];
              
              updateQueryfield(query);
      			}
      		}
    		);

        searchedWithQuery = true;
      }
    }

    // Initialize a nice map center
    var initCenter = new GLatLng(startLat, startLng);
    
    map.setCenter(initCenter, startZoom, startMapType);   

    // Create and add a marker
    marker = new GMarker(initCenter);
    map.addOverlay(marker);
    
    // Generate the initial URL Link
		generateUrl();
	}


  // Add a new event listener for mouse clicks
  GEvent.addListener(map, "click", function(overlay, latlng)
    {
  	  var newCenter = latlng;
  		var swissGrid = coordsToSwissGrid(newCenter.lat(),newCenter.lng());	
  		  
  		// If the mouse has been clicked on a certain spot,
  		// the map pans to that position and the marker is set
  		map.panTo(newCenter);
  		marker.setLatLng(newCenter);

      // The according swiss grid coordinates are written into the text fields
  		updateCoords(swissGrid[0],swissGrid[1]);
  		
  		// The search field is grayed out
  		colorOutQueryfield(queryFieldInactiveTextColor);
  		searchedWithQuery = false;
  		
  		// Generate the URL Link
  		generateUrl();
  	}
	);					
		
	// Add a new event listener for zoom events
  GEvent.addListener(map, "zoomend", function()
    {	
  		// Generate the URL Link
  		generateUrl();
  	}
	);
	
  // And another one for map type changes
  GEvent.addListener(map, "maptypechanged", function()
    {	
  		// Generate the URL Link
  		generateUrl();
  	}
	);
	
}

// Checks if someone presses 'enter' in the search field
function handleKeyPress(e,form)
{
	var key = e.key || e.which;
	if(key == 13)
	{
		goQuery(document.search_form.search.value);
		return false;
	}

}

// Let the map pan to a real name position entered in the search field (if it exists)
function goQuery(query)
{
	if(query != "")
	{
		var geoCoder = new GClientGeocoder();
		geoCoder.getLatLng(query,
		function(pos)
		{
			if(pos)
			{
				map.panTo(pos);
				marker.setLatLng(pos);
				
				var swissGrid = coordsToSwissGrid(pos.lat(),pos.lng());
				
				updateCoords(swissGrid[0],swissGrid[1]);
				colorOutQueryfield(queryFieldActiveTextColor);
				generateUrl();
			}
		}
		);
	
	  searchedWithQuery = true;		
	}
	return false;
}

// Let the map pan to some swiss grid coordinates entered in the text fields i.e.
function goCoords(x,y)
{
	if(x != "" && y != "")
	{
		// Sanitize input
		proper_x = x.replace(' ', '');
		proper_y = y.replace(' ', '');
		
		var latlng = swissGridToCoords(proper_x, proper_y);
		
		var newCenter = new GLatLng(latlng[0],latlng[1]);

		map.panTo(newCenter);
		marker.setLatLng(newCenter);
		updateCoords(proper_x, proper_y);
		
		colorOutQueryfield(queryFieldInactiveTextColor);
		searchedWithQuery = false;
		
		generateUrl();
		
		
		
  }
  return false;
}

// After changing the position, this function is called to update the coordinates 
// in the textfields.
function updateCoords(x,y)
{
	document.getElementById("pos_x").value = x;
	document.getElementById("pos_y").value = y;
}

// Fills the query in the queryfield
function updateQueryfield(query)
{
  document.getElementById("search").value = query;
}

function colorOutQueryfield(color)
{
  document.getElementById("search").style.color = color;
}

function getEncQuery()
{
  return encodeURI(document.getElementById("search").value);
}

// Takes the url parameter string and returns an associative array with the parameters
function parseUrlParams(paramString)
{
  // First take away the leading questionmark
  var realParamString = paramString.substring(1, paramString.length);
  
  // After, split around the ampersand for catching the different key-value pairs
  var paramPairs = realParamString.split("&");
  
  // Now transform the paramPairs into an associative array
  var params = new Array();
  for(var i=0; i < paramPairs.length; i++)
  {
    var pair = paramPairs[i].split("=");
  
    params[i] = pair[1];  
    params[pair[0]] = pair[1];  
  }
  return params;
}

// Produces a url to share over the net, url generates the same view and point
function generateUrl()
{
  var realCoords = marker.getLatLng();
  var swissGridCoords = coordsToSwissGrid(realCoords.lat(),realCoords.lng());

  var coordsString = swissGridCoords[0] + "," + swissGridCoords[1];
  var zoom = map.getZoom();
  var mapType = map.getCurrentMapType().getName(true);
  
  var mapId;
  
  switch (mapType.substring(0,3)) 
  {      
    case "Kar":
      mapId = 1;
      break;
      
    case "Sat":
      mapId = 2;
      break;
      
    case "Hyb":
      mapId = 3;
      break;
      
    case "Gel":
      mapId = 4;
      break;
  }
  
  var parameterString = "pos=" + coordsString;
  
  if(searchedWithQuery)
  {
    parameterString = "query=" + getEncQuery();
  }  
  
  parameterString = parameterString + "&zoom=" + zoom;

 
  if(mapType != standardMapType.getName(true))
  {
    parameterString = parameterString + "&map=" + mapId;  
  }
  
  document.getElementById("tools_url").innerHTML = "<a class='options' href='http://map.retorte.ch/?" + parameterString + "'>URL zu dieser Seite!</a>";
}

// Unloads the whole stuff (according to google)
function unload()
{
  GUnload();
}
















