var anzecken=36;
var bundeslandaktiv=0;
var aktuelleansicht=0;
var kreisaktiv=0;

var baseIcon = new GIcon(G_DEFAULT_ICON);

var markers=new Array();
var markeranz=0;

var zi = 0;                     // Iterationsstartwert
var suchradius=0.0;
var suchpoint=0.0;

var myMap = null;
var localSearch = null;
var myQueryControl = null;
var supercircle=null;

function createMarker(point, index, mytext) {
  // Create a lettered icon for this point using our icon class
  var letter = String.fromCharCode("A".charCodeAt(0) + index);
  var letteredIcon = new GIcon(baseIcon);
  //letteredIcon.image = "http://www.google.com/mapfiles/marker.png";
  letteredIcon.image = "img/navi"+index+".gif";

  // Set up our GMarkerOptions object
  markerOptions = { icon:letteredIcon };
  var marker = new GMarker(point, markerOptions);
  markers[markeranz]=marker;
  markeranz++;


  GEvent.addListener(marker, "click", function() {
    marker.openInfoWindowHtml(mytext);
  });
  return marker;
}

function lade_ergebnisse()
{
	lade_ergebnisse_seite(0);
}


var aktsort=0;
function sorti(sortnr)
{
	aktsort=sortnr;
	lade_ergebnisse_seite(0);
}

function lade_ergebnisse_seite(pagenr)
{
	$("#ergebnisliste").html("<div style=\"height:519px;text-align:center;\"><div style=\"position:relative;top:200px;\">Lade ...<br><img src=img/ajax-loader.gif></div></div>");

	volltext=$("#inputvolltext").val();
	if(volltext=="Suchbegriff eingeben") volltext="";
	volltext=escape(volltext);

	for(i=0;i<10;i++) {
		st="#sb_"+i;
		if($(st)) {
			if($(st).attr('checked')) volltext=volltext+" "+escape($(st).val());
		}
	}

	blx="";
	if(bundeslandaktiv==1) {
		bundesland=$("#bundesland").val();
		region=$("#regionen").val();
		blx='&region='+region+'&bundesland='+bundesland;
		suchpoint=suchradius=0.0;
	}

	for(y=0;y<markeranz;y++) {
		myMap.removeOverlay(markers[y]);
	}
	martkeranz=0;

	$.ajax({
  url: 'ajaxergebnisse.php',
  cache:false,
  data:'point='+suchpoint+'&radius='+suchradius+'&eignung='+$("#inputeignung").val()+
       '&verpflegung='+$("#inputverpflegung").val()+
       '&preis='+$("#inputpreis").val()+
       '&sortierung='+aktsort+
       '&volltext='+volltext+
       blx+
       '&page='+pagenr+
       '&kapazitaet='+$("#inputkapazitaet").val(),

  success: function(data) {
  	if(document.getElementById('ergebnisliste')) {
  		$("#ergebnisliste").html(data);

  		//myMap.clearOverlays();

			if(aktuelleansicht==1) {	//hausansicht
				if(document.getElementById("hs_1")) {
					showhaus(document.getElementById("hs_1").value);
				}
			}
			firsthaus=0;
  		for(y=1;y<=7;y++) {
  			lonstr="lon_"+y;
  			latstr="lat_"+y;
  			inhaltstr="inhalt_"+y;
  			if(document.getElementById(lonstr)) {
  				if(document.getElementById(latstr)) {

		  			var latlng = new GLatLng(document.getElementById(lonstr).value,document.getElementById(latstr).value);
		  			inhalt=document.getElementById(inhaltstr).value;
		  			myMap.addOverlay(createMarker(latlng, y,inhalt));
		  		}
		  	}
  		}
  		if(aktuelleansicht==1) {
  			refade(1);
  		}
  	}
  },
  error: function (xhr, ajaxOptions, thrownError) {
  	if(document.getElementById('ergebnisliste')) {
  		$("#ergebnisliste").html("FEHLER");
  	}
  }
	});
}

function karte_hol_daten2()
{
	seitenwechsel=0;
	lade_ergebnisse();
}

function displayMap()
{
  myMap = new GMap2(document.getElementById("map"));
  myMap.setCenter(new GLatLng(51.151786,10.415039), 6,G_PHYSICAL_MAP);
  myMap.setUIToDefault();

  myMap.addControl(new GMapTypeControl());
  myQueryControl = new QueryControl(localSearch);
  myMap.addControl(myQueryControl);

  GEvent.addListener(myMap, "click", function(overlay, point) {
		if(point) {
			if(bundeslandaktiv==1) {
				bundeslandaktiv=0;
				$("#bundesland").val(0);
				$("#regionen").html("<option value=\"\">Alle</option");
			}
			var newradius=50000;
	  	if(myQueryControl) {
	  		if(suchradius>0) newradius=suchradius;
	  		myQueryControl.remove(0);
	  	}

			myMap.setZoom(8);
			myMap.setCenter(point);
	  	createCircle(point, newradius);

	  	karte_hol_daten2();
	  }
	});

  karte_hol_daten2();
};

function removecircle()
{
	if(myQueryControl) {
		myQueryControl.remove(0);
	}	
}

var	geocoder = new GClientGeocoder();

function gotoPlacemark(ix) {

	var pMark = gResponse.Placemark[ix];
	var point = new GLatLng(pMark.Point.coordinates[1],	pMark.Point.coordinates[0]);

	myMap.setZoom(9);
	myMap.panTo(point);

	var myrad=20000;
	myQueryControl.remove(0);
	createCircle(point, myrad);
 	karte_hol_daten2();
};


function addAddressToMap(response) {
	if (!response || response.Status.code != 200) {
		switch (response.Status.code) {
			case G_GEO_SUCCESS: break;
			case G_GEO_BAD_REQUEST: alert("Fehler " + response.Status.code + ' - A directions request could not be successfully parsed.'); break;
			case G_GEO_SERVER_ERROR: alert("Fehler " + response.Status.code + ' - A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.'); break;
			case G_GEO_MISSING_QUERY: alert("Fehler " + response.Status.code + ' - The HTTP q parameter was either missing or had no value. For geocoding requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.'); break;
			case G_GEO_MISSING_ADDRESS: alert("Fehler " + response.Status.code + ' - Synonym for G_GEO_MISSING_QUERY.'); break;
			case G_GEO_UNKNOWN_ADDRESS: alert("Fehler " + response.Status.code + ' - Keine passende Adresse gefunden'); break;
			case G_GEO_UNAVAILABLE_ADDRESS: alert("Fehler " + response.Status.code + ' - The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.'); break;
			case G_GEO_UNKNOWN_DIRECTIONS: alert("Fehler " + response.Status.code + ' - The GDirections object could not compute directions between the points mentioned in the query. This is usually because there is no route available between the two points, or because we do not have data for routing in that region.'); break;
			case G_GEO_BAD_KEY: alert("Fehler " + response.Status.code + ' - The given key is either invalid or does not match the domain for which it was given.'); break;
			case G_GEO_TOO_MANY_QUERIES: alert("Fehler " + response.Status.code + ' - The given key has gone over the requests limit in the 24 hour period.'); break;
			default: alert("Unknown Error"  + response.Status.code);
		}
	} else {
		gResponse = response;
		if (response.Placemark.length > 0) {
			if(bundeslandaktiv==1) {
				bundeslandaktiv=0;
				$("#bundesland").val(0);
				$("#regionen").html("<option value=\"\">Alle</option");
			}
			
			if(kreisaktiv==0) {
				var point = new GLatLng(51.151786,10.415039);
				createCircle(point, 20000);
			}

			gotoPlacemark(0);
		}
	}
};

function gcKey(event) {
	if (event.keyCode == 13) {

		//if(bundeslandaktiv==1) {
		//	$("#regionen").html("<option value=\"\">Alle</option");
		//	$("#bundesland").val(0);
		//	bundeslandaktiv=0;
		//	resetmap_to_circle();
		//} else {
		//	resetmap_to_circle();
		//}

		getLocation();
	}
}
function getLocation() {
	var oSearchLocation = document.getElementById('umort');

	if(oSearchLocation.value) {
		geocoder.reset();
		geocoder.getLocations(oSearchLocation.value,addAddressToMap);
	} else {
		alert('Bitte Ort eingeben');
	}
};
  var singleClick = false;
  var queryCenterOptions = new Object();
  var queryLineOptions = new Object();

queryCenterOptions.icon = new GIcon();
queryCenterOptions.icon.image = "img/kreuz.png";
queryCenterOptions.icon.iconSize = new GSize(20,20);
queryCenterOptions.icon.shadowSize = new GSize(0, 0);
queryCenterOptions.icon.iconAnchor = new GPoint(10, 10);
queryCenterOptions.draggable = true;
queryCenterOptions.bouncy = false;

queryLineOptions.icon = new GIcon();
queryLineOptions.icon.image = "img/radius.png";
queryLineOptions.icon.iconSize = new GSize(25,20);
queryLineOptions.icon.shadowSize = new GSize(0, 0);
queryLineOptions.icon.iconAnchor = new GPoint(12, 10);
queryLineOptions.draggable = true;
queryLineOptions.bouncy = false;

function createCircle(point, radius) {
	if(kreisaktiv==1) {
	} else {
		kreisaktiv=1;
	}
  singleClick = false;
  geoQuery = new GeoQuery();
  geoQuery.initializeCircle(radius, point, myMap);
  myQueryControl.addGeoQuery(geoQuery);
  geoQuery.render();
}

function destination(orig, hdng, dist) {
  var R = 6371; // earth's mean radius in km
  var oX, oY;
  var x, y;
  var d = dist/R;  // d = angular distance covered on earth's surface
  hdng = hdng * Math.PI / 180; // degrees to radians
  oX = orig.x * Math.PI / 180;
  oY = orig.y * Math.PI / 180;

  y = Math.asin( Math.sin(oY)*Math.cos(d) + Math.cos(oY)*Math.sin(d)*Math.cos(hdng) );
  x = oX + Math.atan2(Math.sin(hdng)*Math.sin(d)*Math.cos(oY), Math.cos(d)-Math.sin(oY)*Math.sin(y));

  y = y * 180 / Math.PI;
  x = x * 180 / Math.PI;
  return new GLatLng(y, x);
}

function distance(point1, point2) {
  var R = 6371; // earth's mean radius in km
  var lon1 = point1.lng()* Math.PI / 180;
  var lat1 = point1.lat() * Math.PI / 180;
  var lon2 = point2.lng() * Math.PI / 180;
  var lat2 = point2.lat() * Math.PI / 180;

  var deltaLat = lat1 - lat2
  var deltaLon = lon1 - lon2

  var step1 = Math.pow(Math.sin(deltaLat/2), 2) + Math.cos(lat2) * Math.cos(lat1) * Math.pow(Math.sin(deltaLon/2), 2);
  var step2 = 2 * Math.atan2(Math.sqrt(step1), Math.sqrt(1 - step1));
  return step2 * R;
}

function GeoQuery() {

}

GeoQuery.prototype.CIRCLE='circle';

GeoQuery.prototype = new GeoQuery();
GeoQuery.prototype._map;
GeoQuery.prototype._type;
GeoQuery.prototype._radius;
GeoQuery.prototype._dragHandle;
GeoQuery.prototype._centerHandle;
GeoQuery.prototype._polyline;
GeoQuery.prototype._color ;
GeoQuery.prototype._control;
GeoQuery.prototype._points;
GeoQuery.prototype._dragHandlePosition;
GeoQuery.prototype._centerHandlePosition;


GeoQuery.prototype.initializeCircle = function(radius, point, map) {
    this._type = this.CIRCLE;
    this._radius = radius;
    this._map = map;
    this._dragHandlePosition = destination(point, 90, this._radius/1000);

    this._dragHandle = new GMarker(this._dragHandlePosition, queryLineOptions);

    this._centerHandlePosition = point;

    this._centerHandle = new GMarker(this._centerHandlePosition, queryCenterOptions);

    this._color = "#0000FF";
    map.addOverlay(this._dragHandle);
    map.addOverlay(this._centerHandle);

    var myObject = this;
    supercircle=this;

    GEvent.addListener (this._dragHandle, "dragend", function() {
    	myObject.updateCircle(1);
    	karte_hol_daten2();
   	});

    GEvent.addListener (this._dragHandle, "drag", function() {
    	myObject.updateCircle(1);
    });

    GEvent.addListener(this._centerHandle, "dragend", function() {
    	myObject.updateCircle(2);
    	karte_hol_daten2();
    });
    GEvent.addListener(this._centerHandle, "drag", function() {
    	myObject.updateCircle(2);
    });
}

GeoQuery.prototype.updateCircle = function (type) {
    this._map.removeOverlay(this._polyline);
    if (type==1) { // groesse aendern
      this._dragHandlePosition = this._dragHandle.getPoint();
      this._radius = distance(this._centerHandlePosition, this._dragHandlePosition) * 1000;
      this.render();
    } else {		// move
      this._centerHandlePosition = this._centerHandle.getPoint();
      this.render();
      this._dragHandle.setPoint(this.getEast());
    }

    if(document.getElementById('founder')) {
    	document.getElementById('founder').innerHTML = "Radius: "+Math.round(suchradius/1000)+" km";
    }
    if(document.getElementById('founder2')) {
    	document.getElementById('founder2').innerHTML = "Radius: "+Math.round(suchradius/1000)+" km";
    }
}

GeoQuery.prototype.render = function() {
  if (this._type == this.CIRCLE) {

  	suchradius=this._radius;
  	suchpoint=this._centerHandlePosition;

    this._points = [];
    var distance = this._radius/1000;
    for (i=0;i<anzecken;i++) {
      this._points.push(destination(this._centerHandlePosition, i * 360/anzecken, distance) );
    }
    this._points.push(destination(this._centerHandlePosition, 0, distance) );
    //this._polyline = new GPolyline(this._points, this._color, 6);
    this._polyline = new GPolygon(this._points, this._color, 1, 1, this._color, 0.2);
    this._map.addOverlay(this._polyline)
    this._control.render();
  }
}

GeoQuery.prototype.remove = function() {
  this._map.removeOverlay(this._polyline);
  this._map.removeOverlay(this._dragHandle);
  this._map.removeOverlay(this._centerHandle);
}

GeoQuery.prototype.getRadius = function() {
    return this._radius;
}

GeoQuery.prototype.getHTML = function() {
	return "";
}

GeoQuery.prototype.getDistHtml = function() {
	result="";
  return result;
}

GeoQuery.prototype.getNorth = function() {
  return this._points[0];
}

GeoQuery.prototype.getSouth = function() {
  return this._points[(anzecken/2)];
}

GeoQuery.prototype.getEast = function() {
  return this._points[(anzecken/4)];
}

GeoQuery.prototype.getWest = function() {
  return this._points[(anzecken/4*3)];
}
GeoQuery.prototype.getSouthWest = function() {
  return this._points[(28)];
}

function QueryControl (localSearch) {
  this._localSearch = localSearch;
}

QueryControl.prototype = new GControl();
QueryControl.prototype._geoQueries ;
QueryControl.prototype._mainDiv;
QueryControl.prototype._queriesDiv;
QueryControl.prototype._minStar;
QueryControl.prototype._minPrice;
QueryControl.prototype._maxPrice;
QueryControl.prototype._timeout;
QueryControl.prototype._localSearch;

QueryControl.prototype.initialize = function(map) {
  this._mainDiv = document.createElement("div");
  this._mainDiv.id = "GQueryControl";
  titleDiv = document.createElement("div");
  titleDiv.id = "GQueryControlTitle";
  titleDiv.appendChild(document.createTextNode(""));
  this._mainDiv.appendChild(titleDiv);
  this._queriesDiv = document.createElement("div");
  this._queriesDiv.id = "queriesDiv";
  this._mainDiv.appendChild(this._queriesDiv);

  map.getContainer().appendChild(this._mainDiv);
  this._geoQueries = new Array();

  return this._mainDiv;
}

QueryControl.prototype.getDefaultPosition = function() {
  //Return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(80, 50));
}

QueryControl.prototype.addGeoQuery = function(geoQuery) {
  this._geoQueries.push(geoQuery);
  geoQuery._control = this;
  newDiv = document.createElement("div");
  newDiv.innerHTML = geoQuery.getHTML();
  this._queriesDiv.appendChild(newDiv);

}

QueryControl.prototype.render = function() {
}

QueryControl.prototype.query = function() {
	alert('CHECK');
  listMarkers = myQueryControl._localSearch.markers.slice();
  for (i = 0; i < listMarkers.length; i++) {
    marker = listMarkers[i].marker;
    result = listMarkers[i].resultsListItem;
    listImage = marker.getIcon().image;
    inCircle = true;
    for (j = 0; j < myQueryControl._geoQueries.length; j++) {
      geoQuery = myQueryControl._geoQueries[j];
      dist = distance(marker.getLatLng(), geoQuery._centerHandlePosition);
      if (dist > geoQuery._radius / 1000) {
        inCircle = false;
        break;
      }
    }
    if (inCircle) {
      marker.setImage(listImage);
      result.childNodes[1].style.color = '#0000cc';
    } else {
      var re = new RegExp(".*(marker.\.png)");
      marker.setImage(listImage.replace(re, "img/$1"));
      result.childNodes[1].style.color = '#b0b0cc';
    }
  }
}

QueryControl.prototype.remove = function(index) {
	kreisaktiv=0;
	if(this._geoQueries[index]) {
  	this._geoQueries[index].remove();

	  this._queriesDiv.removeChild(this._queriesDiv.childNodes[index]);
  	delete this._geoQueries[index];
  	this._geoQueries.splice(index,1);
  }
  this.render();
}

QueryControl.prototype.getIndex = function(geoQuery) {
  for (i = 0; i < this._geoQueries.length; i++) {
    if (geoQuery == this._geoQueries[i]) {
      return i;
    }
  }
  return -1;
}

