var debugmode = $.browser.mozilla && false;
var eZGmapsEdit = function (attributeID, options)
{	
	var defaults = {
		ezroot: '',
		zoom: 13,
		detailZoom: 13,
		defaultLat: 0,
		defaultLng: 0
	};
	options = $.extend(defaults, options);
	
	var findByZip = function () {
			
			var zip = parseInt(document.getElementById('ezgmaps_zip_' + attributeID).value),
			    country = document.getElementById('ezgmaps_country_' + attributeID).value;
			
			if (zip < 1000) {
				alert ("Geben Sie eine gültige PLZ ein!");	
			} else {
				$.getJSON(options.ezroot + "googlemaps/getlocationbyzip/" + country + '/' + zip,
					function(data){
						if (data.length == 0) {
							
							$('#ezgmaps_locationselect_' + attributeID).removeSelectOptions(2);
							alert ("Zu dieser PLZ wurde kein Ort gefunden.");
							
						} else {

							$('#ezgmaps_locationselect_' + attributeID).fillSelectBox(data, true, 2);

							//if (document.getElementById('ezgmaps_locationselect_' + attributeID).options.length == 3) {
								
								document.getElementById('ezgmaps_locationselect_' + attributeID).selectedIndex=2;
								selectLocation();
							//}
						}
					  }
				);
			}
	
			return false;
		},
		selectLocation = function() {
			var location = parseInt(document.getElementById('ezgmaps_locationselect_' + attributeID).value);
			if (location > 0) {			
				document.getElementById('ezgmaps_location_' + attributeID).value=location;
				document.getElementById('ezgmaps_locationname_' + attributeID).value = document.getElementById('ezgmaps_locationselect_' + attributeID).options[document.getElementById('ezgmaps_locationselect_' + attributeID).selectedIndex].text;
			} else {
				document.getElementById('ezgmaps_locationname_' + attributeID).value = '';
				document.getElementById('ezgmaps_location_' + attributeID).value=0;
			}
		},
		gmap = false,
		geocoder = false,
		marker = false,
		updateLatLng = function (point) {
			document.getElementById('ezgmaps_latitude_' + attributeID).value=point.lat();
			document.getElementById('ezgmaps_longitude_' + attributeID).value=point.lng();
			
			$('#ezgmaps_latitudetext_' + attributeID).html(point.lat());
			$('#ezgmaps_longitudetext_' + attributeID).html(point.lng());
			
		},
		findAdress = function () {
			if (document.getElementById('ezgmaps_location_' + attributeID).value <= 0) {
				alert('Sie müssen einen Ort auswählen');
				return false;
			}
			
			if ($.trim(document.getElementById('ezgmaps_street1_' + attributeID).value) == '') {
				alert('Sie müssen eine Straße eingeben');
				return false;
			}
			
			var address = document.getElementById('ezgmaps_street1_' + attributeID).value + ", " + document.getElementById('ezgmaps_locationname_' + attributeID).value+ ", " + document.getElementById('ezgmaps_country_' + attributeID).value;
	    	if (geocoder) {
	        	geocoder.getLatLng(
	          		address,
	          			function(point) {
	            			if (!point) {
	              				alert(address + " wurde nicht gefunden.");
	            			} else {
	            				marker.setPoint(point);
								marker.show();
	              				gmap.setCenter(point, options.detailZoom);
	              				updateLatLng(point);
							}
						}
	        	);
			}
		};
	
	
    $('#ezgmaps_zip_' + attributeID).keypress(function (e) {
		if (e.which == 13) {
			findByZip();
		} else if (!(e.which >= 48 && e.which <= 57) && e.which != 8 && e.which!=46 && e.which!=9 && !(e.which >= 37 && e.which <= 40)) {
			return false;
		}
    });
    
	$('#ezgmaps_find_' + attributeID).click(findByZip);
	$('#ezgmaps_locationselect_' + attributeID).change(selectLocation);
	$('#ezgmaps_findaddress_' + attributeID).click(findAdress);
	
	//init google maps
	$(function() {
		if (GBrowserIsCompatible()) {
			var lat=parseFloat(document.getElementById('ezgmaps_latitude_' + attributeID).value),
			    lng=parseFloat(document.getElementById('ezgmaps_longitude_' + attributeID).value);
			    
			gmap = new GMap2(document.getElementById('ezgmaps_map_' + attributeID));    
			gmap.addControl(new GSmallMapControl());
			
			if (lat >0 && lng >0) {
				var startupPoint = new GLatLng(lat, lng);
				gmap.setCenter(startupPoint, options.detailZoom);
			} else {
				var startupPoint = new GLatLng(options.defaultLat, options.defaultLng);
				gmap.setCenter(startupPoint, options.zoom);
			}
			
			gmap.enableScrollWheelZoom();
			gmap.enableContinuousZoom();
			
            marker = new GMarker(startupPoint, {draggable: true});
            gmap.addOverlay(marker);
            
			geocoder = new GClientGeocoder();
			GEvent.addListener(gmap, "click", function(newmarker, point) {
				marker.setPoint(point);
				marker.show();
				updateLatLng(point);
				gmap.panTo(point);
			});
			GEvent.addListener(marker, "dragend", function() {
				var point = marker.getPoint();
				updateLatLng(point);
				gmap.panTo(point);
				
			});
				
			if (lat <=0 || lng <=0) {
				marker.hide();
			}
			  
			
			///prevent page scroll
			//http://esa.ilmari.googlepages.com/scrollzoom.htm
			var wheelevent = function (e) {
				if (!e){
					e = window.event
				}
				if (e.preventDefault){
					e.preventDefault()
				}
				e.returnValue = false;
			}
			GEvent.addDomListener(gmap.getContainer(), "DOMMouseScroll", wheelevent);
			gmap.getContainer().onmousewheel = wheelevent;
			//end - prevent page scroll
	      }
		
	});
};

var eZGmapsView = function (attributeID, lat, lng, options) {
	var defaults = {
		zoom: 13,
		mapTypeControl: false,
		mapOverviewControl: false,
		mapOverviewControlHidden: true,
		mapLargeControl: false,
		mapSize: false,
		
		locationIcon: false
	};
	options = $.extend(defaults, options);
    
    var gmap = null,
    	marker = null;

    $(function(){
        if (GBrowserIsCompatible()) {
        	var point = new GLatLng(lat,lng);
			marker = new GMarker(point, {icon:options.locationIcon, clickable:false});
			  
			if (options.mapSize)
				gmap = new GMap2(document.getElementById('ezgmaps_map_' + attributeID), {'size': options.mapSize});
			else
				gmap = new GMap2(document.getElementById('ezgmaps_map_' + attributeID));
			//gmap.disableDragging();
			gmap.disableDoubleClickZoom();
			gmap.continuousZoomEnabled();
			
			gmap.setCenter(point, options.zoom);
			gmap.addOverlay(marker);
          
          	if (options.mapTypeControl) {
          	 	gmap.addMapType(G_PHYSICAL_MAP);
				var gmapControl = new GHierarchicalMapTypeControl();
				
				gmapControl.clearRelationships();
				gmapControl.addRelationship(G_SATELLITE_MAP, G_HYBRID_MAP, "Hybridmodus", true);
				
				gmap.addControl(gmapControl);
          	}
          	
         	if (options.mapOverviewControl) {
         		gmapoverview = new GOverviewMapControl();
         		gmap.addControl(gmapoverview);
         		
         		if (options.mapOverviewControlHidden)
         			gmapoverview.hide(true);
         	}
         	
         	if (options.mapLargeControl) {
         		gmap.addControl(new GLargeMapControl ());
         	} else {
         		gmap.addControl(new GSmallMapControl());
         	}
        }
    });	
};

var eZGmapsOverview = function (containerID, options) {
	
	var defaults = {
		zoom: 7,
		center: new GLatLng(47.4949,13.3593),
		
		mapTypeControl: true,
		mapOverviewControl: true,
		mapOverviewControlHidden: true,
		mapLargeControl: true,
		
		mapContinuousZoomEnabled: true,
		mapScrollWheelZoom: true,
		mapDisableDoubleClickZoom: true,
		mapDisableDragging: false,
		mapSize: false,
		
		loadDataOnStartup: false,
		startupSearchCriteria: {},
		
		zoomInLoadData: true,
		
		markersIntersect: 0.0001,
		combineLocationsZoomLevel: 10,
		combineRegionsZoomLevel: 7,
		combineProvincesZoomLevel: 0,
		
		infoboxRegionsCountPrefix: '',
		infoboxRegionsCountPostfix: [' Standort',' Standorte'],
		infoboxProvincesCountPrefix: '',
		infoboxProvincesCountPostfix: [' Standort',' Standorte'],
		
		locationIcon: false,
		locationCombinedIcons: false,
		regionIcon: false,
		provinceIcon: false,
		
		preSetMarkers: false,
		postSetMarkers: false,
		
		ezroot: ''
	},
	gmap=false,
	gmapMarkerManager=false;
	
	this.options = $.extend(defaults, options);
	this.resultData = false;
	
	this.loadData = function (searchCriteria) {
		if (debugmode) console.log('function eZGmapsOverview::loadData');
		
		var searchcriteriastr = '';
		
		if (typeof(searchCriteria) == 'object') {
			$.each(searchCriteria, function(i, val) {
				if (typeof(val) == 'object') {
					$.each(val, function(i2, val2) {
						searchcriteriastr += i + '[' + i2 + ']=' + val2 + '&';
					});
				} else
		    		searchcriteriastr += i+ '=' + val + '&';
		    });
		}
		
		$this = this;
		if (this.options.ezroot == '/')
			this.options.ezroot = '';
			
		$.getJSON(this.options.ezroot + "/googlemaps/loaddata/?" + searchcriteriastr, function (data) {
			//remove previous markers
			gmapMarkerManager.clearMarkers();
			
			if (data.locations.length == 0) {
				alert ("Es wurden keine Orte gefunden");
			} else {
				
				if (typeof($this.options.preSetMarker) == 'function')
					$this.options.preSetMarker(data);
				
				$this.setMarker(data);
				
				if (typeof($this.options.postSetMarker) == 'function')
					$this.options.preSetMarker(data);
				
			}
		});	
	};
	
	this.prepareInfoHtml = function (infohtml) {
		if (debugmode) console.log('function eZGmapsOverview::prepareInfoHtml');		
		return infohtml.replace(/{ezroot}/g, $this.options.ezroot+'/');
	}
		
	this.setMarker = function (data) {
		if (debugmode) console.log('function eZGmapsOverview::setMarker');	
		
		var bounds = new GLatLngBounds(),
			combinedLocations = {},
			locationsTemp = data.locations,
			i=0,
			$this=this;

		//intersects
		$.each(data.locations, 
			function(id, glocation) {
				if (!glocation.is_combined) {
					glocation.lat=parseFloat(glocation.lat);
					glocation.lng=parseFloat(glocation.lng);
							
					$.each(data.locations, 
						function(id2, glocation2) {
							if (!glocation2.is_combined) {
								glocation2.lat=parseFloat(glocation2.lat);
								glocation2.lng=parseFloat(glocation2.lng);
								
								if (id != id2) {
									if ((Math.abs(glocation.lat-glocation2.lat) < $this.options.markersIntersect ) && (Math.abs(glocation.lng-glocation2.lng) < $this.options.markersIntersect )) {
										if (typeof (data.locations[id].combinelist)=='undefined') {
											data.locations[id].combinelist = new Array();
											data.locations[id].combinelist_count = 1;
										}
										data.locations[id].combinelist.push(data.locations[id2]);
										data.locations[id2].is_combined=true;
										data.locations[id].combinelist_count ++;
									}
								}
							}
						}
					);
				}
			}
		);
		
		var markers = new Array();
		$.each(data.locations, 
			function(id, glocation) {
				if (!glocation.is_combined) {
					var position = new GLatLng(glocation.lat, glocation.lng),
					    minZoomLevel = 1,
					    marker_id = markers.length;
					    
					if (typeof (glocation.combinelist)=='undefined')
						 var marker = new GMarker(position, {title: glocation.shortname, icon:$this.options.locationIcon});					
					else {
						var name=glocation.shortname, icon = false;
						$.each(glocation.combinelist,
						function(id2,glocation2) {
							name+= ', ' + glocation2.shortname;
						});
						
						if (typeof($this.options.locationCombinedIcons) == 'object') {
							if (typeof($this.options.locationCombinedIcons[glocation.combinelist_count]) == 'object')
								icon = $this.options.locationCombinedIcons[glocation.combinelist_count];
							else
								icon = $this.options.locationIcon;
						} else
							icon = $this.options.locationIcon;
							
						var marker = new GMarker(position, {title: name, icon: icon});		
					}			
					
					marker.link_id = id;
					marker.type = 1;
					markers[marker_id]=marker;
					
					data.locations[id].marker = marker;
					
					if (typeof(data.locations[id].combinelist) == 'object') {
						$.each(data.locations[id].combinelist,
							function(i,glocation) {
								glocation.marker = marker;
								glocation.tab_id = i+2;
							});
					}
				  	bounds.extend(position);
				}
			}
		);
		
		if ($this.options.combineLocationsZoomLevel > 0)
  			minZoomLevel = $this.options.combineLocationsZoomLevel + 1;

		gmapMarkerManager.addMarkers(markers,minZoomLevel);
		
		
		if ($this.options.combineLocationsZoomLevel > 0) {
			markers = new Array();
			$.each(data.regions, 
				function(id, region) {
					var position = new GLatLng((parseFloat(region.maxLat)+parseFloat(region.minLat))/2, (parseFloat(region.maxLng)+parseFloat(region.minLng))/2),
						marker = new GMarker(position, {title: region.name, icon:$this.options.regionIcon}), //,googlemapIcon
						minZoomLevel = 1;
					
					marker.link_id = id;
					marker.type = 2;
				  	
				  	markers[markers.length]=marker;
				}
			);
			
			if ($this.options.combineRegionsZoomLevel > 0)
				minZoomLevel = $this.options.combineRegionsZoomLevel + 1;
			gmapMarkerManager.addMarkers(markers,minZoomLevel,$this.options.combineLocationsZoomLevel);
			
			if ($this.options.combineRegionsZoomLevel > 0) {
				markers = new Array();
				
				$.each(data.provinces, 
					function(id, province) {
						var position = new GLatLng((parseFloat(province.maxLat)+parseFloat(province.minLat))/2, (parseFloat(province.maxLng)+parseFloat(province.minLng))/2),
						marker = new GMarker(position, {title: province.name, icon:$this.options.provinceIcon});
						
						marker.link_id = id;
						marker.type = 3;
						
						markers[markers.length]=marker;
					}
				);
										
				//if ($this.options.combineProvincesZoomLevel > 0)
		  		minZoomLevel = 1;
				gmapMarkerManager.addMarkers(markers,minZoomLevel,$this.options.combineRegionsZoomLevel);
			}
			
			//TODO: combine provinces
		}
		gmapMarkerManager.refresh();
		
		this.resultData = data;
		$this = this;
		
		GEvent.addListener(gmaps, "click", function(marker, point) {
			$this.showHtmlInfoWindow(marker);
		});
		
		if (bounds.isEmpty()) {
			gmaps.returnToSavedPosition();
		} else if ($this.options.zoomInLoadData) {
			gmaps.setZoom(gmaps.getBoundsZoomLevel(bounds));
			gmaps.setCenter(bounds.getCenter());
			gmaps.savePosition();
		}
		
	};
	
	this.showHtmlInfoWindow = function(marker, tab) {
		if (debugmode) console.log('function eZGmapsOverview::showHtmlInfoWindow');	
		
		if (marker && marker.type && marker.link_id) {
			switch (marker.type) {
				case 1:
					if (typeof ($this.resultData.locations[marker.link_id].combinelist)=='undefined') {
						marker.openInfoWindowHtml($this.prepareInfoHtml($this.resultData.locations[marker.link_id].infohtml));
					} else {
						var i=1,
							tabshtml = '<li><a href="#gmaps-tab-' + i + '"><span>' + i + '</span></a></li>',
							html = '<div id="gmaps-tab-'+i+'">' + $this.prepareInfoHtml($this.resultData.locations[marker.link_id].infohtml) + '</div>';
			
						$.each($this.resultData.locations[marker.link_id].combinelist,
							function(id,glocation) {
								i++;
								tabshtml += '<li><a href="#gmaps-tab-'+i+'"><span>' + i + '</span></a></li>';
								html += '<div id="gmaps-tab-'+i+'">' + $this.prepareInfoHtml(glocation.infohtml) + '</div>';
							});
						marker.openInfoWindowHtml('<div id="gmaps-tabs"><ul>' + tabshtml + '</ul>' + html + '</div>');
						$("#gmaps-tabs > ul").tabs((typeof(tab) == 'number' ? tab : null));
					}
					break;
				
				case 2:
					var html='<div class="gmaps-infowindow"><div class="gmaps-infowindow-name">' + $this.resultData.regions[marker.link_id].name + '</div><div class="gmaps-infowindow-count">' + $this.options.infoboxRegionsCountPrefix + $this.resultData.regions[marker.link_id].count + (typeof($this.options.infoboxRegionsCountPostfix)=='object' ?  ($this.resultData.regions[marker.link_id].count == 1 ? $this.options.infoboxRegionsCountPostfix[0]: $this.options.infoboxRegionsCountPostfix[1]) : $this.options.infoboxRegionsCountPostfix) + '</div><div class="gmaps-infowindow-zoomin"><a href="#" id="gmaps-zoomin">Zoomen</a></div></div>';
					marker.openInfoWindowHtml(html);
			
					$("#gmaps-zoomin").click(function() {
						var regionbounds  = new GLatLngBounds( new GLatLng( $this.resultData.regions[marker.link_id].minLat, $this.resultData.regions[marker.link_id].minLng), new GLatLng($this.resultData.regions[marker.link_id].maxLat, $this.resultData.regions[marker.link_id].maxLng));
						gmaps.setZoom(gmaps.getBoundsZoomLevel(regionbounds));
						gmaps.setCenter(regionbounds.getCenter());
						return false;
					});
					break;
					
				case 3:
					var html='<div class="gmaps-infowindow"><div class="gmaps-infowindow-name">' + $this.resultData.provinces[marker.link_id].name + '</div><div class="gmaps-infowindow-count">' + $this.options.infoboxProvincesCountPrefix + $this.resultData.provinces[marker.link_id].count + (typeof($this.options.infoboxProvincesCountPostfix)=='object' ?  ($this.resultData.provinces[marker.link_id].count == 1 ? $this.options.infoboxProvincesCountPostfix[0]: $this.options.infoboxProvincesCountPostfix[1]) : $this.options.infoboxProvincesCountPostfix) + '</div><div class="gmaps-infowindow-zoomin"><a href="#" id="gmaps-zoomin">Zoomen</a></div></div>';
					marker.openInfoWindowHtml(html);					
			
					$("#gmaps-zoomin").click(function() {
						var provonincebounds  = new GLatLngBounds( new GLatLng( $this.resultData.provinces[marker.link_id].minLat, $this.resultData.provinces[marker.link_id].minLng), new GLatLng($this.resultData.provinces[marker.link_id].maxLat, $this.resultData.provinces[marker.link_id].maxLng));
						gmaps.setZoom(gmaps.getBoundsZoomLevel(provonincebounds));
						gmaps.setCenter(provonincebounds.getCenter());
						return false;
					});
					break;
				}
				
			}
	}
	
	$this = this;
	$(function(){
		if (debugmode) console.log('function eZGmapsOverview init');
		
        if (GBrowserIsCompatible()) {
			if ($this.options.mapSize)
				gmaps = new GMap2(document.getElementById(containerID), {'size': $this.options.mapSize});
			else
				gmaps = new GMap2(document.getElementById(containerID));
				
			if ($this.options.mapSize)
				gmaps.disableDragging();
				
			if ($this.options.mapDisableDoubleClickZoom)
				gmaps.disableDoubleClickZoom();
				
			if ($this.options.mapScrollWheelZoom)	 {
				gmaps.enableScrollWheelZoom();
				
				///prevent page scroll
				//http://esa.ilmari.googlepages.com/scrollzoom.htm
				var wheelevent = function (e) {
					if (!e){
						e = window.event
					}
					if (e.preventDefault){
						e.preventDefault()
					}
					e.returnValue = false;
				}
				GEvent.addDomListener(gmaps.getContainer(), "DOMMouseScroll", wheelevent);
				gmaps.getContainer().onmousewheel = wheelevent;
				//end - prevent page scroll
			}
				
			if ($this.options.mapContinuousZoomEnabled)
				gmaps.continuousZoomEnabled();
			
			gmaps.setCenter($this.options.center, $this.options.zoom);
          
          	if ($this.options.mapTypeControl) {
          	 	gmaps.addMapType(G_PHYSICAL_MAP);
				var gmapsControl = new GHierarchicalMapTypeControl();
				
				gmapsControl.clearRelationships();
				gmapsControl.addRelationship(G_SATELLITE_MAP, G_HYBRID_MAP, "Hybridmodus", true);
				
				gmaps.addControl(gmapsControl);
          	}
          	
         	if ($this.options.mapOverviewControl) {
         		gmapsoverview = new GOverviewMapControl();
         		gmaps.addControl(gmapsoverview);
         		
         		if ($this.options.mapOverviewControlHidden)
         			gmapsoverview.hide();
         	}
         	
         	if ($this.options.mapLargeControl) {
         		gmaps.addControl(new GLargeMapControl ());
         	} else {
         		gmaps.addControl(new GSmallMapControl());
         	}
         	
         	if ($this.options.loadDataOnStartup) {
         		$this.loadData(options.startupSearchCriteria);
         	}
         	
         	gmapMarkerManager = new MarkerManager(gmaps);

         	//marker types: 1: position, 2: region, 3: province, 4: country
			GMarker.prototype.type = 1;
			GMarker.prototype.link_id = 0;
        }

    });	
	
};

	
jQuery.fn.removeSelectOptions = function (offset) {
	if (typeof offset == "undefined")
		offset = 0;
	
	this.each(function () {
            var $$ = $(this);
	
			for (var i = this.options.length - 1; i>=offset; i--) {
				this.remove(i);
			}
			this.options.length = offset;
			
			this.disabled = true;
	});
	
	return this;
}

jQuery.fn.fillSelectBox = function ( options, remove, offset )
{
	if (remove == true) {
		$(this).removeSelectOptions(offset);
	}
		
	this.each(function () {
		var $$ = this;
		
		$.each(options, function(index, value) {
			$$.options[$$.options.length] = new Option(value, index, false, false);
		});
		$$.disabled = false;
		
		$$.selectedIndex = 0;
	});
	
	return this;
}


