var icons = new Object();
icons['cafes'] = new GIcon(G_DEFAULT_ICON);
icons['cafes'].image = '/images/map/marker_hellgruen.png';

icons['restaurants-und-gaststaetten'] = new GIcon(G_DEFAULT_ICON);
icons['restaurants-und-gaststaetten'].image = '/images/map/marker_blau.png';

icons['bars'] = new GIcon(G_DEFAULT_ICON);
icons['bars'].image = '/images/map/marker_orange.png';

icons['hotels'] = new GIcon(G_DEFAULT_ICON);
icons['hotels'].image = '/images/map/marker_hellrot.png';

icons['apotheken'] = new GIcon(G_DEFAULT_ICON);
icons['apotheken'].image = '/images/map/marker_rosa.png';

icons['apotheke'] = new GIcon(G_DEFAULT_ICON);
icons['apotheke'].image = '/images/map/marker_rosa.png';

icons['aerzte-fuer-allgemeinmedizin'] = new GIcon(G_DEFAULT_ICON);
icons['aerzte-fuer-allgemeinmedizin'].image = '/images/map/marker_hellblau.png';

icons['zahnaerzte'] = new GIcon(G_DEFAULT_ICON);
icons['zahnaerzte'].image = '/images/map/marker_braun.png';

icons['zahnarzt'] = new GIcon(G_DEFAULT_ICON);
icons['zahnarzt'].image = '/images/map/marker_braun.png';

icons['reisebuero'] = new GIcon(G_DEFAULT_ICON);
icons['reisebuero'].image = '/images/map/marker_gelb.png';

icons['reisebuero'] = new GIcon(G_DEFAULT_ICON);
icons['reisebuero'].image = '/images/map/marker_gelb.png';

icons['rechtsanwaelte'] = new GIcon(G_DEFAULT_ICON);
icons['rechtsanwaelte'].image = '/images/map/marker_rot.png';

icons['steuerberater'] = new GIcon(G_DEFAULT_ICON);
icons['steuerberater'].image = '/images/map/marker_gruen.png';

var icon_uni = new GIcon(G_DEFAULT_ICON);
icon_uni.image = '/images/map/marker_uni.png';
icon_uni.iconSize = new GSize(16,16);
icon_uni.iconAnchor = new GPoint(0,8);

icon_uni.shadow = '';

var iconsBase = new Object();
iconsBase['cafes'] = new GIcon(G_DEFAULT_ICON);
iconsBase['cafes'].image = '/images/map/marker_uni_hellgruen.png';


iconsBase['restaurants-und-gaststaetten'] = new GIcon(G_DEFAULT_ICON);
iconsBase['restaurants-und-gaststaetten'].image = '/images/map/marker_uni_blau.png';

iconsBase['bars'] = new GIcon(G_DEFAULT_ICON);
iconsBase['bars'].image = '/images/map/marker_uni_orange.png';

iconsBase['hotels'] = new GIcon(G_DEFAULT_ICON);
iconsBase['hotels'].image = '/images/map/marker_uni_hellrot.png';

iconsBase['apotheken'] = new GIcon(G_DEFAULT_ICON);
iconsBase['apotheken'].image = '/images/map/marker_uni_rosa.png';

iconsBase['apotheke'] = new GIcon(G_DEFAULT_ICON);
iconsBase['apotheke'].image = '/images/map/marker_uni_rosa.png';

iconsBase['aerzte-fuer-allgemeinmedizin'] = new GIcon(G_DEFAULT_ICON);
iconsBase['aerzte-fuer-allgemeinmedizin'].image = '/images/map/marker_uni_hellblau.png';

iconsBase['zahnaerzte'] = new GIcon(G_DEFAULT_ICON);
iconsBase['zahnaerzte'].image = '/images/map/marker_uni_braun.png';

iconsBase['zahnarzt'] = new GIcon(G_DEFAULT_ICON);
iconsBase['zahnarzt'].image = '/images/map/marker_uni_braun.png';

iconsBase['reisebuero'] = new GIcon(G_DEFAULT_ICON);
iconsBase['reisebuero'].image = '/images/map/marker_uni_gelb.png';

iconsBase['rechtsanwaelte'] = new GIcon(G_DEFAULT_ICON);
iconsBase['rechtsanwaelte'].image = '/images/map/marker_uni_rot.png';

iconsBase['steuerberater'] = new GIcon(G_DEFAULT_ICON);
iconsBase['steuerberater'].image = '/images/map/marker_uni_gruen.png';

$.each(iconsBase,function() {
	this.iconSize = new GSize(16,16);
	this.iconAnchor = new GPoint(0,8);
	this.shadow = '';	
});

var categories = new Array();

var entries = new Object();
var entriesList = new Array();
var latlngbounds = new GLatLngBounds( );
		
/**
 * The core entry handler class. This class provides all functionality to display the entries on the map.
 */
function BBEntry() {
	this.id = "";
	this.title = "";
	this.street = "";
	this.housenumber = "";
	this.zip = "";
	this.city = "";
	this.phone = "";
	this.fax = "";
	this.lat = 0.0;
	this.lng = 0.0;
	this.icon = new GIcon(G_DEFAULT_ICON);
	this.categories = new Array();
	this.paid = false;
	this.marker = null;
	this.distance = null;
	return {
		addToMap : function(map) {
			if (this.lat == 0 || isNaN(this.lat)) {
				var geocoder = new GClientGeocoder();
				var entry = this;
				geocoder.getLatLng(this.street+ ' ' + this.housenumber + ', '+this.zip+' '+this.city, function(latlng) {
					entry.marker = new GMarker(latlng, entry.icon);
					entry.marker.title = entry.title;
					entry.lat = latlng.lat();
					entry.lng = latlng.lng();
					entry.createInfoWindow(map);
					map.addOverlay(entry.marker);
					if (entries.length == 0) {
						/*Hauptkarte*/
						//map.setCenter(latlng, 7);/*12 Zoomfaktor Kartenanzeige*/
					} else if (entries.length == 1) {
						/*Einzelansicht*/
    					latlngbounds.extend( latlng );
  						map.setCenter( latlngbounds.getCenter( ), 13 );/*15 Zoomfaktor Kartenanzeige*/
  					} else {
  						/*kleine Karten Liste*/
    					latlngbounds.extend( latlng );
    					//map.setCenter( latlngbounds.getCenter( ), 7 );
    					map.setCenter( latlngbounds.getCenter( ), Math.min(map.getBoundsZoomLevel( latlngbounds ), 13) );
  					}					
				});
			} else {
				
				var latlng = new GLatLng(this.lat,this.lng);
				this.marker = new GMarker(latlng, this.icon);
				this.createInfoWindow(map);
				map.addOverlay(this.marker);
			}			
		},
		
		createInfoWindow: function(map) {
			if (this.link) {
				var title = "<a href='"+this.link+"'><strong>"+this.title+' '+this.surname+' '+this.name+"</strong></a><br/>";
			} else {
				var title = this.title+' '+this.surname+' '+this.name+"<br/>";
			}
			var fax = "";
			if (this.fax.search(/[0-9]+/) != -1) {
				fax = "Fax: "+this.fax+"<br/><br/>";
			}
				
			this.marker.bindInfoWindowHtml(
				title
				+this.street+' '+this.housenumber+"<br/>"
				+this.zip+" "+this.city+"<br/>"
				+"Tel: "+this.phone+"<br/>"
				+fax
				+"<a class='zoom' href='javascript:map.savePosition();map.setCenter(new GLatLng("+this.lat+","+this.lng+"),14);'>Heranzoomen</a>",
				{ maxWidth: 180}
			);				
		},
		
		addToList: function(list) {
			var distance = '<span class="route">Routenplaner</span>';
			if (this.distance != null) {
				distance = '<span class="distance">'+ Math.round(this.distance/100)/10+''+' km</span>'+distance;
			}
			var image = "<img align='left' src='"+this.icon.image+"'/>";
			var name = '<a href="#">'+this.title+'</a>';
			var address = '<address>'+this.street+ ' ' + this.housenumber + ', '+this.zip+' '+this.city+'<br/>'+this.phone+'</address>';
			var category = '';
			$('<li id="entry'+this.id+'" >'+distance+'<div class="cb"></div>'+name+address+category+'</li>').appendTo(list);
			
			$('#entry'+this.id).mouseover(function() {
				$(this).css('background-color','#e6e6e6')
			});			
			$('#entry'+this.id).mouseout(function() {
				$(this).css('background-color','#f3f3f3')
			});	
		},

		removeFromList: function() {
			$('#entry'+this.id).remove();
		}
		
	};
	
} 
	
/**
 * Starts a search for entries and displays them on the map
 * @param word The search string
 * @param start Start index of the result set
 * @param amount Amount of entries to be retrieved
 * @param lat Latitude of the center
 * @param lng Longitude of the center
 * @param distance Radius from the center 
 */
  
function searchEntries(word, start, amount, lat, lng, distance) {
	$.ajax({
		type		: 'GET',
		url			: 'xml/testdata'+word+start+'.xml', 
		data		: {word:[word],amount:[amount],geox:[lng],geoy:[lat],start:[start],distance:[distance]}, 
		dataType	: "xml",
		success		: function (data) {
	   		$.each(searchedEntries, function(index, entry) {
	   			map.removeOverlay(entry.marker);
	   			entry.removeFromList();
	   		});
	   		searchedEntries = new Array();
			$("entry",data).each(function() {
				var entry = new BBEntry();
				entry.id = $("id", this).text();
				entry.lat = $("geoy", this).text();
				entry.lng = $("geox", this).text();
				entry.title = $("title", this).text();
				entry.name = $("name:first", this).text();
				entry.surname = $("surname", this).text();
				entry.link = $("link", this).text();				
				entry.street = $("street", this).text();
				entry.housenumber = $("housenumber", this).text();
				entry.zip = $("zip", this).text();
				entry.city = $("city", this).text();
				entry.phone = $("phone", this).text();
				entry.fax = $("fax", this).text();
				if (distance) {
					var start = new GLatLng(lat, lng);
					entry.distance = start.distanceFrom(new GLatLng(entry.lat,entry.lng));
				}
				searchedEntries.push(entry);
				
			});
			
			displayEntries(start,amount);
			total = $('entries',data).attr('totalAmount');
			var where = "";
			if ($('#where').val()) {
				where = '/'+$('#where').val();
			}
			$('#resultText').text(total+' Treffer zu '+word+where);

			if (total > start+amount) {
				$('#next').css('display','block');
			} else {
				$('#next').css('display','none');
			}
			
			
		},
		error		: function(xml,msg,error) {
			//alert('Die Daten konnten nicht geladen werden');
		}				 
	});	
}
	
/**
 * Displays entries in the result list and the map. The markers are changed to non nmbered makrers if the entry is not displayed in the list.
 * All entries are displayed on the map
 */
function displayEntries(start, amount) {
	map.clearOverlays();
	var number = 1;
	for (var i = 0; i < searchedEntries.length; i++) { 
		searchedEntries[i].removeFromList();
		if (i >= start && i < start+entriesPerPage) {
			searchedEntries[i].icon = new GIcon(G_DEFAULT_ICON);
			searchedEntries[i].icon.image = '/images/map/numbered/marker'+number+'.png';
			searchedEntries[i].addToList($('#resultList'));
			number++;
		} else {
			searchedEntries[i].icon = icon_uni;
		}
		searchedEntries[i].addToMap(map);
	}
}
	
/**
 * Retrieves a category from the server and displays all entries on the map
 * @param id ID of the category
 * @param display Flag whether the category is displayed or shall be removed
 * @param specialIcon An Index to the icon array to override the default icon 
 */
function displayCategory(id, obj, display, specialIcon, ignore, startlat, startlng, endlat, endlng) {

   	if (display) {
   		if (!startlat) {
			var bounds = map.getBounds();
			var sw = bounds.getSouthWest();
			var ne = bounds.getNorthEast();
			var startlat = sw.lat();
			var startlng = ne.lng();
			var endlat = ne.lat();
			var endlng = sw.lng();
   		}
		$.ajax({
			type		: 'GET',
			url			: '/cat_xml.php', 
			data		: {id:[id],xml:['true'],page:[1],range:[10],startlat:[startlat],startlng:[startlng],endlat:[endlat],endlng:[endlng]}, 
			dataType	: "xml",
			success		: function (data) {
				entries[id] = new Array();
				$("entry",data).each(function() {
					
					var entry = new BBEntry();
					entry.id = $("id", this).text();
					entry.lat = $("geoy", this).text();
					entry.lng = $("geox", this).text();
					entry.title = $("title", this).text();
					entry.name = $("name:first", this).text();
					entry.surname = $("surname", this).text();
					entry.link = $("link", this).text();
					entry.street = $("street", this).text();
					entry.housenumber = $("housenumber", this).text();				
					entry.zip = $("zip", this).text();
					entry.city = $("city", this).text();
					entry.phone = $("phone", this).text();
					entry.fax = $("fax", this).text();
					entry.paid = $("paid", this).text();
					if (specialIcon) {
						if (entry.paid == 'false') {
							entry.icon = iconsBase[id];
						} else {
							entry.icon = icons[id];
						}

					}
					if (ignore != entry.id) {
						entry.addToMap(map);
						entries[id].push(entry);
					}

				})
				
			},
			error		: function(xml,msg,error) {
				//alert('Die Daten konnten nicht geladen werden');
			}				 
		});
   	} else {
   		$.each(entries[id], function(index, entry) {
   			map.removeOverlay(entry.marker);
   		});

   		entries[id] = new Array();
   	}
}

/**
 * Decode utf8 encoded text
 */
function decode_utf8(utftext) { 
	var plaintext = ""; var i=0; var c=c1=c2=0;
	while(i<utftext.length) {
	    c = utftext.charCodeAt(i);
	    if (c<128) {
	         plaintext += String.fromCharCode(c);
	          i++;}
	     else if((c>191) && (c<224)) {
	        c2 = utftext.charCodeAt(i+1);
	         plaintext += String.fromCharCode(((c&31)<<6) | (c2&63));
	         i+=2;}
	      else {
	         c2 = utftext.charCodeAt(i+1); c3 = utftext.charCodeAt(i+2);
	        plaintext += String.fromCharCode(((c&15)<<12) | ((c2&63)<<6) | (c3&63));
	       i+=3;}
	     }
	  return plaintext;
}  