var map;
var mapCase;
var gLocalSearch;
var marker;
var gSelectedResults = [];
var gCurrentResults = [];

var mapShowed = false;
function initialize(){
	var mapObj = document.getElementById("map");
	if (!mapObj) return false;
	
	mapCase = mapObj.getAttribute('rel');
	
	if (GBrowserIsCompatible()){   
		map = new GMap2(mapObj);
	    map.setCenter(new GLatLng(51.165691 ,10.451526 ), 3);

	    map.enableScrollWheelZoom();
	    //gLocalSearch.setRestriction(gLocalSearch.TYPE_KMLONLY_RESULTS);
	    //alert(GlocalSearch.TYPE_KMLONLY_RESULTS)
	    options = {
	    	resultList : GlocalSearch.TYPE_KMLONLY_RESULTS
	    };
		gLocalSearch = new GlocalSearch(options);
		gLocalSearch.setCenterPoint(map);
		gLocalSearch.setSearchCompleteCallback(null, OnLocalSearch);
		gLocalSearch.setResultSetSize(gLocalSearch.LARGE_RESULTSET);
		gLocalSearch.setAddressLookupMode(gLocalSearch.ADDRESS_LOOKUP_DISABLED);
		loadGoogleAdress();
	}
}

function relocateMap(lat,lng,zoom,offset){
	if (map){
		switch(mapCase){
			case 'quick':
				map.setCenter(new GLatLng(lat, lng), 8);
			break;
			default:
				map.setCenter(new GLatLng(lat, eval(lng-offset)), zoom);
			break;
		}

	}
}

var currentState = 'geosearch';
function OnLocalSearch(){
  if (!gLocalSearch.results){
	  return;
  }	
  if (marker){
	  map.removeOverlay(marker);
  }
  if(currentState === 'autocomplete'){
	$('local_search_autocomplete').show();
	$('local_search_autocomplete').innerHTML = '';
	var list = '';
	for(var i = 0; i < gLocalSearch.results.length; i++){
		result = gLocalSearch.results[i];
		
		address = result.streetAddress+' '+result.city+' '+result.region;
		list = list + '<li id="auto'+i+'" onclick="$(\'address\').value = \''+address+'\';"><b>'+result.title+'</b><br />'+address+'</li>';
	}
	$('local_search_autocomplete').innerHTML = '<ul>'+list+'</ul>';
  }
  else{
	  
	  if(gLocalSearch.results[0]){
		var point = new GLatLng(gLocalSearch.results[0].lat,gLocalSearch.results[0].lng);
	  	marker = new GMarker(point,{draggable: true})  
		
		  GEvent.addListener(marker, "dragend", function() {
			  takeCoords();
		  });
		  map.addOverlay(marker);
		  map.setCenter(new GLatLng(gLocalSearch.results[0].lat, gLocalSearch.results[0].lng), 14);  
	  }

  }  
}

function loadGoogleAdress(){
	if (gLocalSearch){
		gLocalSearch.execute(document.getElementById("address").value);
	}		
	return false;	
}

function takeCoords(){
	if (!gLocalSearch.results) return;
	var marker2 = marker.getPoint();

	document.getElementById("address").value = gLocalSearch.results[0].addressLines;
}

Event.observe(window, 'load', initialize);

 