var map;
var bwIcon;
var coreIcon;
var premierIcon;
var coreLeftIcon;
var coreRightIcon;
var premierLeftIcon;
var premierRightIcon;
var UKSOverlay;
var size;
var pStore = 0;
var clusterIcons = [];
var BWIcons = [];
var bounds;
var geoCoderPoint;
var addressStr;
var pushpinMarker;
var startZoom = 9;
var currentZoom = 9;
var geocoderAddress;

// Suchoptionen Umkreissuche
function initializeUmkreissuche() {	
	if ($('umkreismap')) {
		addressStr = '' + $('cityRegionSearchString').value;
		if ($('cityRegionSearchString').value != "") {
			$('uks_ort').value = $('cityRegionSearchString').value
		}
		if (addressStr == '') return;
		
		addressStr = fixForMuenchenFlughafen(addressStr);
		//console.log("addressStr:", addressStr);

		BWCustomIcons();
		BWPushPinIcon();
		
		if (GBrowserIsCompatible()) {
			map = new GMap2(document.getElementById("umkreismap"));
			//map.setMapType(G_SATELLITE_MAP);
			map.setMapType(G_HYBRID_MAP);
			addBWCustomControls();			
			
			// ===== Leeres GLatLngBounds object =====     
			bounds = new GLatLngBounds();
			var geocoder = new GClientGeocoder('','AIzaSyCL3z1lBDFZ4gIGlWd8IZm8NFMo6CftWI4');
			//console.log("geocoder: ", geocoder);
			
			if ($chk(addressStr) && geocoder) {
				geocoder.getLatLng(
					addressStr,
					function (point) {
						if (!point) {
							// alert("Die angegebene Adresse " + addressStr + " konnte nicht gefunden werden.");
						} else {
							// console.log("POINT: ", point);
							geoCoderPoint = point;
							// console.log("geoCoderPointX:", geoCoderPoint.x, "geoCoderPointY:", geoCoderPoint.y);
							// umkreisSucheHookUp();

							// Pushpinmarker setzen
							if(pushpinMarker) {
							map.removeOverlay(pushpinMarker);
							}
							pushpinMarker = new GMarker(point, {icon: pushpinIcon, title: addressStr});			  			
							map.addOverlay(pushpinMarker);

							addAllMarkerArray(); // ToDo: Array mit sämtlichen Markern anzeigen
							if (UKSOverlay) { // Kreis-Overlay entfernen und neu erzeugen
								map.removeOverlay(UKSOverlay);
							}
							map.setCenter(point, 7);
							BWCustomOverlay();
							map.setZoom(9);
						}
					}
				);
			}
			else {
				map.setCenter(new GLatLng(50.109527, 8.663802), 7);
				addAllMarkerArray(); // ToDo: Array mit sämtlichen Markern anzeigen
				if (UKSOverlay) { // Kreis-Overlay entfernen und neu erzeugen
				  	map.removeOverlay(UKSOverlay);
				}
				BWCustomOverlay();	
				map.setZoom(9);				
			}		
			
			// Submit mit RETURN für IE aktivieren
			var crss = $('uks_ort');		
			if (crss) {
				crss.addEvent('keydown', function(evt){
					if (evt.code == 13) {
						slidervalue = 10;
						showAddress($('uks_ort').value, $('uks_adresse').value);
					}
				});
			}
		}
	}
}

// Coverflow Umkreissuche
var initializeCFUmkreissuche = function() {
	/*
	if ($('cf_umkreismap')) {
		if (!initSlider()) return;
		BWCustomIcons();
		BWPushPinIcon();
		if (GBrowserIsCompatible()) {
			map = new GMap2(document.getElementById("cf_umkreismap"));
			// map.setMapType(G_SATELLITE_MAP);
			map.setMapType(G_HYBRID_MAP);
			map.setCenter(new GLatLng(52.5234051, 13.4113999), 7);
			// map.addControl(new GScaleControl());
			addBWCustomControls();
			//addBWMarkers();
			// ===== Leeres GLatLngBounds object =====     
			bounds = new GLatLngBounds();
			addAllMarkerArray();
			BWCustomOverlay();
			map.setZoom(9);
			geocoder = new GClientGeocoder();
		}
	}
	*/
}

// Geocodersuche für Umkreissuche
var showAddress = function(stadt, adresse) {
	var myAddress = "";
	if ($defined(adresse)) {
		myAddress = (adresse == '' || adresse == 'Adresse, Bahnhof, POI, o.ä.' ? '' : adresse);
	}
	
	stadt = (stadt == '' || stadt == 'Stadt' ? '' : stadt);
	addressStr = (myAddress != '' ? myAddress + ', ' : '') + stadt;	 
	if (addressStr == '') return;
	addressStr = fixForMuenchenFlughafen(addressStr);
	//console.log("addressStr:", addressStr);

		var geocoder = new GClientGeocoder();
		if ($chk(addressStr) && geocoder) {
			geocoder.getLatLng(
				addressStr,
				function(point) {
					if (!point) {
						//alert("Die angegebene Adresse " + addressStr + " konnte nicht gefunden werden.");
					} else {
						if (geoCoderPoint.x != point.x || geoCoderPoint.y != point.y) {
							//console.log("geoCoderPointX:", geoCoderPoint.x, "geoCoderPointY:", geoCoderPoint.y);
							//console.log("pointX:", point.x, "pointY:", point.y);
							
							
							geoCoderPoint = point;
							// console.log("geoCoderPointX:", geoCoderPoint.x, "geoCoderPointY:", geoCoderPoint.y);
							umkreisSucheHookUp(10);
							map.setCenter(point, 7);
							// Pushpinmarker setzen
							if(pushpinMarker) {
								map.removeOverlay(pushpinMarker);
							}
							pushpinMarker = new GMarker(point, {icon: pushpinIcon, title: addressStr});
							map.addOverlay(pushpinMarker);
							if (UKSOverlay) { // Kreis-Overlay entfernen und neu erzeugen
								map.removeOverlay(UKSOverlay);
							}
							BWCustomOverlay();
							UKSOverlay.redraw('', 10);
							map.setZoom(9);
							
							initSlider();
						}
						else {
							umkreisSucheHookUp(slidervalue);
						}
					}
				}
			);
		}
		geocoderAddress = addressStr;

		//umkreisSucheHookUp();
}

// Suchoptionen Kartensuche
var initializeKartensuche = function() {
	if ($('optmap')) {
		BWCustomIcons();
		if (GBrowserIsCompatible()) {
			map = new GMap2(document.getElementById("optmap"));
			map.setMapType(G_HYBRID_MAP);
			addBWCustomControls();

			// ===== Leeres GLatLngBounds object =====     
			bounds = new GLatLngBounds();
			addMarkerArray();
			// console.log("BOUNDS: ", bounds);
			
			map.setCenter(bounds.getCenter());
			map.setZoom(map.getBoundsZoomLevel(bounds));
			// map.savePosition();
		}
	}
}	

// Suchoptionen Kartensuche
var initHotelviewGMap = function() {
	if ($('optmap')) {
		BWCustomIcons();
		if (GBrowserIsCompatible()) {
			map = new GMap2(document.getElementById("optmap"));
			addBWCustomControls();
			// ===== Leeres GLatLngBounds object =====     
			bounds = new GLatLngBounds();
			addMarkerArray();
			map.setCenter(bounds.getCenter());
			map.setZoom(15);
		}
	}
}	

// Coverflow Kartensuche
var initializeCFKartensuche = function() {
	if ($('cf_googlemap')) {
		BWCustomIcons();
		BWClusterIcons();
		if (GBrowserIsCompatible()) {
			map = new GMap2(document.getElementById("cf_googlemap"));
			map.setMapType(G_HYBRID_MAP);
			map.setCenter(new GLatLng(51, 10), 5);
			addBWCustomControls();
			addBWClusterMarkers();
		}
	}
}

var BWCustomIcons = function() {
    bwIcon = new GIcon();
    bwIcon.image = '/bw/v3/img/maps/core.png';
    bwIcon.shadow = '/bw/v3/img/maps/bwshadow.png';
    bwIcon.iconSize = new GSize(29, 48);
    bwIcon.shadowSize = new GSize(53, 48);
    bwIcon.iconAnchor = new GPoint(15, 48);
    bwIcon.infoWindowAnchor = new GPoint(15, 48);
    coreIcon = new GIcon(bwIcon);
		BWIcons['coreIcon'] = coreIcon;
    premierIcon = new GIcon(bwIcon);
    premierIcon.image = "/bw/v3/img/maps/premier.png";
		BWIcons['premierIcon'] = premierIcon;
	
		coreLeftIcon = new GIcon(bwIcon);
    coreLeftIcon.image = '/bw/v3/img/maps/core_left.png';
    coreLeftIcon.shadow = '/bw/v3/img/maps/bwshadow_left.png';
    coreLeftIcon.iconSize = new GSize(29, 48);
    coreLeftIcon.shadowSize = new GSize(53, 48);
    coreLeftIcon.iconAnchor = new GPoint(22, 48);
    coreLeftIcon.infoWindowAnchor = new GPoint(15, 48);
    BWIcons['coreLeftIcon'] = coreLeftIcon;
    
    coreRightIcon = new GIcon(bwIcon);
    coreRightIcon.image = '/bw/v3/img/maps/core_right.png';
    coreRightIcon.shadow = '/bw/v3/img/maps/bwshadow_right.png';
    coreRightIcon.iconSize = new GSize(29, 48);
    coreRightIcon.shadowSize = new GSize(53, 48);
    coreRightIcon.iconAnchor = new GPoint(6, 48);
    coreRightIcon.infoWindowAnchor = new GPoint(15, 48);
    BWIcons['coreRightIcon'] = coreRightIcon;
    
    premierLeftIcon = new GIcon(coreLeftIcon);
    premierLeftIcon.image = "/bw/v3/img/maps/premier_left.png";
    BWIcons['premierLeftIcon'] = premierLeftIcon;
		premierRightIcon = new GIcon(coreRightIcon);
    premierRightIcon.image = "/bw/v3/img/maps/premier_right.png";
    BWIcons['premierRightIcon'] = premierRightIcon;
}

var BWPushPinIcon = function() {	
	pushpinIcon = new GIcon();
	pushpinIcon.image = "/bw/v3/img/maps/yellow-pushpin.png";
	pushpinIcon.shadow = "/bw/v3/img/maps/pushpinshadow.png";
	pushpinIcon.iconSize=new GSize(32,32);
	pushpinIcon.shadowSize = new GSize(48,32);
   	pushpinIcon.iconAnchor=new GPoint(24,32);
}

var BWClusterIcons = function() {
	for (var i=1; i<=19; i++) {
		clusterIcons[i] = new GIcon();
		clusterIcons[i].image = "/bw/v3/img/maps/c_" + i + ".png";
		if (i==1) { // small
			clusterIcons[i].iconSize=new GSize(13,13);
			clusterIcons[i].iconAnchor=new GPoint(6,6);
		}
		else {
			if(i<10) { // medium 2 bis 9
				clusterIcons[i].iconSize=new GSize(24,24);
				clusterIcons[i].iconAnchor=new GPoint(12,12);
			}
			else { // large 10 - 19
				clusterIcons[i].iconSize=new GSize(35,34);
				clusterIcons[i].iconAnchor=new GPoint(17,17);
			}
		}
	}
}


var BWCustomOverlay = function() {
	// A Rectangle is a simple overlay that outlines a lat/lng bounds on the
    // map. It has a border of the given weight and color and can optionally
    // have a semi-transparent background color.
    function Rectangle(bounds, opt_weight, opt_color) {
      	this.bounds_ = bounds;
     		this.weight_ = opt_weight || 0;
      	this.color_ = opt_color || "#ffffff";
    }
    Rectangle.prototype = new GOverlay();
    // Creates the DIV representing this rectangle.
    Rectangle.prototype.initialize = function(map) {	
      // console.log(map.getContainer().id);  
	  var mapID = map.getContainer().id;
	  
	  if (mapID == 'cf_umkreismap') {
	  	var src = '/bw/v3/img/maps/umkreis_1308x633.png';
	  }
	  else {
	  	var src = '/bw/v3/img/maps/umkreis_1308x990.png';
	  }
	  
	  var div = new Element('div').setStyles({
		'position' : 'absolute'
	  });
	  
	  var circle = new Element('img', {
		'src' : src
	  }).setStyles({
	  	'width' : '100%',
			'height' : '100%'
	  }).inject(div);
      map.getPane(G_MAP_MAP_PANE).appendChild(div);

      this.map_ = map;
      this.div_ = div;
    }

    // Remove the main DIV from the map pane
    Rectangle.prototype.remove = function() {
      this.div_.parentNode.removeChild(this.div_);
    }

    // Copy our data to a new Rectangle
    Rectangle.prototype.copy = function() {
      return new Rectangle(this.bounds_, this.weight_, this.color_, this.backgroundColor_, this.opacity_);
    }

    // Redraw the rectangle based on the current projection and zoom level
    Rectangle.prototype.redraw = function(force, p) {
		// console.log("FORCE: " + force + " - P: " + p); // force == true bei zoom, false bei verschiebung
		
		if ($defined(p)) {
			pStore = p;
		}

		var factor = map.getZoom() - 6;

      	// Calculate the DIV coordinates of two opposite corners of our bounds to
      	// get the size and position of our rectangle
	  
     var c1 = this.map_.fromLatLngToDivPixel(this.bounds_.getSouthWest()); // Ecke links unten
     var c2 = this.map_.fromLatLngToDivPixel(this.bounds_.getNorthEast()); // Ecke rechts oben
		
		
		if ($defined(size)) {
			var dW = Math.abs(size.x / 10 * (p - 10) * factor);
			var dH = Math.abs(size.y / 10 * (p - 10) * factor);
		}
		else {
			var dW = 0;
			var dH = 0;
		}
      	// Now position our DIV based on the DIV coordinates of our bounds

		if ($defined(p) && !force) { // Größe mit Schieber ändern
			this.div_.style.width = Math.abs(c2.x - c1.x + dW) + "px";
			this.div_.style.height = Math.abs((c2.y - c1.y) - dH) + "px";
			this.div_.style.left = (Math.min(c2.x, c1.x) - this.weight_ - dW/2) + "px";
      this.div_.style.top = (Math.min(c2.y, c1.y) - this.weight_ - dH/2) + "px";
      		
      //console.log("NO FORCE => W: ", this.div_.style.width, " / H: ", this.div_.style.heigh, " / L: ", this.div_.style.left, " / T: ", this.div_.style.top);
		}
		
		else {
			if (force != false && !$defined(p) && pStore == 0) {
				this.div_.style.width = Math.abs(c2.x - c1.x) + "px";
      	this.div_.style.height = Math.abs(c2.y - c1.y) + "px";
				this.div_.style.left = (Math.min(c2.x, c1.x) - this.weight_) + "px";
      	this.div_.style.top = (Math.min(c2.y, c1.y) - this.weight_) + "px";
      	// console.log("WITH FORCE => W: ", this.div_.style.width, " / H: ", this.div_.style.heigh, " / L: ", this.div_.style.left, " / T: ", this.div_.style.top);
			}
			else {
				// do nothing
				// console.log("pStore: ", pStore);
				// console.log("size: ", size);
				// console.log("factor: ", factor);
				if ($defined(size)) {
					var dW = Math.abs(size.x / 10 * (pStore - 10) * factor);
					var dH = Math.abs(size.y / 10 * (pStore - 10) * factor);
				}
				this.div_.style.width = Math.abs(c2.x - c1.x + dW) + "px";
				this.div_.style.height = Math.abs((c2.y - c1.y) - dH) + "px";
				this.div_.style.left = (Math.min(c2.x, c1.x) - this.weight_ - dW/2) + "px";
      	this.div_.style.top = (Math.min(c2.y, c1.y) - this.weight_ - dH/2) + "px";
			}
		}
		
		if(!$defined(size)) {
			size = this.div_.getSize();
		}
		
		//console.log("dW: ", dW, " / dH: ", dH);
		if ($defined(p)) {
			//console.log("KM: " + p + " / CURRENTZOOM: " + currentZoom + " / startZoom: " + startZoom);
			if (p > 0 && p <= 25) {
				if (currentZoom != startZoom) {
					map.setZoom(startZoom);
					currentZoom = startZoom;
				}				
			}
			else if (p > 25 && p <= 44) {
				if (currentZoom != startZoom - 1) {
					map.setZoom(startZoom - 1);
					currentZoom = startZoom - 1;
				}
			}
			else if (p > 44) {
				if (currentZoom != startZoom - 2) {
					map.setZoom(startZoom - 2);
					currentZoom = startZoom - 2;
				}
			}
		}
		
		if (force) { // beim Ein- / Auszoomen
			// Bei Zoomstufe < 7 das Overlay ausblenden
			if (map.getZoom() < 7) {
				this.div_.style.visibility = 'hidden';
			}
			else { // Bei Zoomstufe >= 7 das Overlay wieder einblenden
				if (this.div_.style.visibility == 'hidden') {
					this.div_.style.visibility = 'visible';
				}
			}
		}
  } // ende redraw
	
	UKSOverlay = new Rectangle(map.getBounds());		
	map.addOverlay(UKSOverlay);
}


var addBWCustomControls = function() {
	// Zoom Control
	function BWZoomControl() {}
	BWZoomControl.prototype = new GControl();
	BWZoomControl.prototype.initialize = function(map) {
		var zoomContainer =  new Element("div", { 'id' : 'zoomContainer' });
		
		var zoomInBtn = new Element("a", { 
			'id': 'gm_zoomin',
			'title' : 'Zoom In'
		}).inject(zoomContainer);
	  	GEvent.addDomListener(zoomInBtn, "click", function() {
	    	map.zoomIn();
	  	});
	  	var zoomOutBtn = new Element("a", { 
			'id' : 'gm_zoomout',
			'title' : 'Zoom Out'
		}).inject(zoomContainer);
	  	GEvent.addDomListener(zoomOutBtn, "click", function() {
	    	map.zoomOut();
	  	});
		zoomContainer.inject(map.getContainer());
	  	return zoomContainer;
	}
	BWZoomControl.prototype.getDefaultPosition = function() { // Control positionieren
		// return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(0, 2));
		return new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(4, 4));
	}
	
	// MapType Control
	function BWMapTypeControl() {}
	BWMapTypeControl.prototype = new GControl();
	BWMapTypeControl.prototype.initialize = function(map){
		var mapTypeContainer =  new Element("div", { 'id' : 'mapTypeContainer' });
		
		var satelliteTypeBtn = new Element("a", { 'id': 'gm_satellitetype' }).inject(mapTypeContainer);
		satelliteTypeBtn.addEvent('click', function(evt) {
	    	map.setMapType(G_SATELLITE_MAP);
			deselectAll();
			satelliteTypeBtn.addClass('selected');
	  	});
		
		var normalTypeBtn = new Element("a", { 'id': 'gm_normaltype' }).inject(mapTypeContainer);
		normalTypeBtn.addEvent('click', function(evt) {
	    	map.setMapType(G_NORMAL_MAP);
			deselectAll();
			normalTypeBtn.addClass('selected');
	  	});

		var hybridTypeBtn = new Element("a", { 'id': 'gm_hybridtype' }).inject(mapTypeContainer);
		hybridTypeBtn.addEvent('click', function(evt) {
	    	map.setMapType(G_HYBRID_MAP);
			deselectAll();
			hybridTypeBtn.addClass('selected');
	  	});
		
		var deselectAll = function() {
			$each([satelliteTypeBtn, normalTypeBtn, hybridTypeBtn], function(btn) {
				btn.removeClass('selected');
			});
		}
		
		mapTypeContainer.inject(map.getContainer());
		return mapTypeContainer;
	}
	
	BWMapTypeControl.prototype.getDefaultPosition = function() { // Control positionieren
		// return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(0, 2));
		return new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(4, 4));
	}
	
	map.addControl(new BWZoomControl());
	map.addControl(new BWMapTypeControl());
}


function createMarker(point, icon, html){
	if ($type(icon) == "string") {
		icon = BWIcons[icon];
	}
    markerOptions = {
        icon: icon
    };	
    var marker = new GMarker(point, markerOptions);
    GEvent.addListener(marker, "click", function(){
		// console.log(map);
        map.openInfoWindowHtml(point, html);
    });
    return marker;
}

function createClusterMarker(point, c){
    markerOptions = {
        icon: clusterIcons[c]
    };
    var marker = new GMarker(point, markerOptions);
    GEvent.addListener(marker, "click", function(){
        map.setZoom(9);
		map.setCenter(point);
    });
    return marker;
}

var addMarkerArray = function() {
	hotelArray.each(function(h) {
		var html = '<div id="HI-'+h[0]+'"><div class="infoWindow"><a href="'+h[5]+'" target="_blank" class="hl '+h[4]+'">'+h[7]+'</a><br><p class="adresse">'+h[8]+'</p><a href="'+h[6]+'" class="buchenbtn"><img src="/bw/v3/img/btn/buchen100.gif" alt="Jetzt buchen" style="width:100px;height:30px; float:right;"></a><a href="'+h[5]+'" class="toggle">Details ansehen</a></div></div>';
		//console.log(h[1], h[2], h[3], html);
		if ($chk(h[1]) && $chk(h[2])) {
			var point = new GLatLng(h[1], h[2]);
			var marker = createMarker(point, h[3], html);
			map.addOverlay(marker);
			bounds.extend(point);
		}
	});
};

var addAllMarkerArray = function() {
	allHotelArray.each(function(h) {
		var html = '<div id="HI-'+h[0]+'"><div class="infoWindow"><a href="'+h[5]+'" target="_blank" class="hl '+h[4]+'">'+h[7]+'</a><br><p class="adresse">'+h[8]+'</p><a href="'+h[6]+'" class="buchenbtn"><img src="/bw/v3/img/btn/buchen100.gif" alt="Jetzt buchen" style="width:100px;height:30px; float:right;"></a><a href="'+h[5]+'" class="toggle">Details ansehen</a></div></div>';
		//console.log(h[1], h[2], h[3], html);
		if ($chk(h[1]) && $chk(h[2])) {
			var point = new GLatLng(h[1], h[2]);
			var marker = createMarker(point, h[3], html);
			map.addOverlay(marker);
			bounds.extend(point);
		}
	});
};


var addBWClusterMarkers = function(){
	var mgr = new MarkerManager(map);

	var zoomOut = []; // Zommstufen 0 - 7 Clustermarker für Städte und einzelne Hotels
	var zoomIn = []; // Zoomstufe 8 - 15 einzelne Hotels mmit normalen Markern
	
	allHotelArray.each(function(h){
		var html = '<div id="HI-' + h[0] + '"><div class="infoWindow"><a href="' + h[5] + '" target="_blank" class="' + h[4] + '">' + h[7] + '</a><br><p class="adresse">' + h[8] + '</p><a href="' + h[5] + '" class="toggle">Details ansehen</a><a href="' + h[6] + '" class="buchenbtn"><img src="/bw/v3/img/btn/buchen100.gif" alt="Jetzt buchen"></a></div></div>'
		//console.log(h[1], h[2], h[3], html);
		var point = new GLatLng(h[1], h[2]);
		var marker = createMarker(point, h[3], html);
		zoomIn.push(marker);
	});
	
	clusterArray.each(function(c){
		if ($chk(c[0]) && $chk(c[1])) {
			var point = new GLatLng(c[0], c[1]);
			var marker = createClusterMarker(point, c[2]);
			zoomOut.push(marker);
		}
	});	
	mgr.addMarkers(zoomIn, 8, 15);
	mgr.addMarkers(zoomOut, 0, 7);
	mgr.refresh();
};

var fixForMuenchenFlughafen = function(addressStr) {
  addressStr = addressStr.toLowerCase();
  if (addressStr.indexOf("flughafen") != -1 && (addressStr.indexOf("münchen") != -1 || addressStr.indexOf("muenchen") != -1)) {
    return "Flughafen München";
  }
  else {
    return addressStr;
  }
};



	
