//UTF8 string: ěščřžýáíéů

	var MAX_TYPE_GROUP = 5;
	var MIN_MAP_RESOLUTION = 6;
	var MAX_CUSTOM_MAP_RESOLUTION = 9;
	var MIN_CUSTOM_MAP_RESOLUTION = 5;
	
	// The allowed region which the whole map must be within
	var allowedBounds = new GLatLngBounds(new GLatLng(48.5,12.0), new GLatLng(51.1,18.9));

	var tecky40_vrsek = GetStyle('tecky40_vrsek');
	var tecky40_spodek = GetStyle('tecky40_spodek');
	var zprava = GetStyle('zprava');
	var zprava_cas = 0;
	var zpravashow = true; // show message or not - set to false in Animace after while

	var gAFsRequestNo = 0;
	var gAFsReplyReceived = -1;
	
	// >Constants<
	var HCWIDTH  = 153;
	var HCHEIGHT = 62;
	var MAPWIDTH = parseInt(GetStyle('map_canvas').width);
	var MAPHEIGHT = parseInt(GetStyle('map_canvas').height);

  var gTileServerNext = 0;
  var TILE_SERVERS_COUNT = 3;
  var gTileServers = new Array();
  gTileServers[0] = 'www.e-ubytovani.eu';
  gTileServers[1] = 'www.e-accommodation.eu';
  gTileServers[2] = 'www.e-unterkunft.eu';
//  gTileServers[3] = 'www.e-alloggio.eu';
  		
	// Global variables for our mapping
	var MapInstance = null;
	var custommap = null;
	var AFActiveIcon = null;
	var AFActiveIconBlink = null;
	var AFPassiveIcon = null;
	var AFInfoDiv = GetElement('mapinfo');
	var AFInfoLoadingStyle = GetStyle('mapinfoloading');
	var MapTypeSwitchStyle = GetStyle('maptype_switch');
	var AdvAFsDiv = GetElement('AdvAFsDiv');
	var Markers = new Array();
	Markers[0] = new Array();
	Markers[1] = new Array();
	Markers[2] = new Array();
	Markers[3] = new Array();
	Markers[4] = new Array();
	Markers[5] = new Array();
	Markers[6] = new Array();
	Markers[7] = new Array();
	Markers[8] = new Array();
	Markers[9] = new Array();
	
	var SelectAreaEnabled = false;
	var LastClickedAFID = -1;
	var LastGoogleMapType = G_NORMAL_MAP;
	var loadAFsForAdvTimeout = null;
	

	String.prototype.replaceAll=function(s1, s2)
	{
        return this.replace(new RegExp(s1,"g"), s2);
	}

	if (GMap2) {
		if (GBrowserIsCompatible()) {
			MapInstance = new GMap2(document.getElementById("map_canvas"));

			// Add OSM tiles
			var copyright = new GCopyright(1, new GLatLngBounds(new GLatLng(-90,-180), new GLatLng(90,180)), 0, ""); 
			var copyrightCollection = new GCopyrightCollection('Data'); 
			copyrightCollection.addCopyright(copyright); 

			var tilelayers = []; 
			tilelayers[0] = new GTileLayer(copyrightCollection, 3, 18); 
			tilelayers[0].getTileUrl = function (a, b) {

			// is the request for zoom we support? if not, use google
			if (b < MIN_CUSTOM_MAP_RESOLUTION || b > MAX_CUSTOM_MAP_RESOLUTION) {
				return G_NORMAL_MAP.getTileLayers()[0].getTileUrl(a,b);
			}	
					
			gTileServerNext = (gTileServerNext+1)%TILE_SERVERS_COUNT;
			//return "http://www.beeblog.eu/tmp/map/osmtilecache.php/"+b+"/"+a.x+"/"+a.y+".png";
			//return "http://localhost/e-ubytovani.eu/www/images/map/"+b+"/"+a.x+"_"+a.y+".png";
			return "http://"+gTileServers[gTileServerNext]+"/images/map/"+b+"/"+a.x+"_"+a.y+".png";
			};
			tilelayers[0].isPng = function() { return true;};
			tilelayers[0].getOpacity = function() { return 1.0; };

			custommap = new GMapType(tilelayers, new GMercatorProjection(19), "GoogleCached", {errorMessage:"Error loading cached image."});
			// we use just cached google tiles, so print the same copyright as NORMAL_MAP
			GMapType.prototype.getCopyrights_custom = GMapType.prototype.getCopyrights;
			GMapType.prototype.getCopyrights = function(bounds,zoom) {
				return G_NORMAL_MAP.getCopyrights(bounds,zoom);
			}

			MapInstance.addMapType(custommap); 

			// ====== Restricting the range of Zoom Levels =====
			custommap.getMinimumResolution = function() {return MIN_MAP_RESOLUTION;}
			G_NORMAL_MAP.getMinimumResolution = function() {return MIN_MAP_RESOLUTION;}
			G_SATELLITE_MAP.getMinimumResolution = function() {return MIN_MAP_RESOLUTION;}
			G_HYBRID_MAP.getMinimumResolution = function() {return MIN_MAP_RESOLUTION;}
			G_PHYSICAL_MAP.getMinimumResolution = function() {return MIN_MAP_RESOLUTION;}

			AccMapZoomEnd(7,7); // to enable custommap
			MapInstance.setCenter(new GLatLng(49.87339770318919, 15.479736328125), 7);
			
			// Add controls
			MapInstance.addControl(new GLargeMapControl());
			MapInstance.enableScrollWheelZoom();

			GEvent.addListener(MapInstance, 'zoomend', AccMapZoomEnd);
			GEvent.addListener(MapInstance, 'click', AccMapClicked);
			GEvent.addListener(MapInstance, 'dblclick', AccMapDblClicked);
			GEvent.addListener(MapInstance, 'moveend', AccNewAreaDisplayed);
			GEvent.addListener(MapInstance, 'mouseover', AccMapMouseOver);
			GEvent.addListener(MapInstance, 'mouseout', AccMapMouseOut);
			GEvent.addListener(MapInstance, 'mousemove', AccMapMouseMove);
			GEvent.addListener(MapInstance, 'dragstart', AccMapDragStart);
			//GEvent.addListener(MapInstance, 'move', AccMapMove);
			
			// Prepare other variables
			AFActiveIcon = new GIcon(null,'http://www.e-accommodation.eu/images/tecka_zarizeni_neanim.gif');
			AFActiveIcon.iconSize = new GSize(8, 8);
			AFActiveIcon.iconAnchor = new GPoint(4,4);
			AFActiveIcon.infoWindowAnchor = new GPoint(4,4);

			AFActiveIconBlink = new GIcon(null,'http://www.e-accommodation.eu/images/tecka_zarizeni_anim.gif');
			AFActiveIconBlink.iconSize = new GSize(8, 8);
			AFActiveIconBlink.iconAnchor = new GPoint(4,4);
			AFActiveIconBlink.infoWindowAnchor = new GPoint(4,4);

			AFPassiveIcon = new GIcon(null,'http://www.e-accommodation.eu/images/tecka_zarizeni_neanim_hidden.gif');
			AFPassiveIcon.iconSize = new GSize(8, 8);
			AFPassiveIcon.iconAnchor = new GPoint(4,4);
			AFPassiveIcon.infoWindowAnchor = new GPoint(4,4);
		}
		else {
			alert('browser not compatible with Google Maps');
		}
	}
	else {
		alert('Google map script not imported');
	}

	//----------------------------------------------------
	// Event Listener functions..
	//
	
	function AccMapMove()
	{
		checkBounds();
	}

	// If the map position is out of range, move it back
	function checkBounds()
	{
		// Perform the check and return if OK
		if (allowedBounds.contains(MapInstance.getCenter()))
			return;

		// It`s not OK, so find the nearest allowed point and move there
		var C = MapInstance.getCenter();
		var X = C.lng();
		var Y = C.lat();

		var AmaxX = allowedBounds.getNorthEast().lng();
		var AmaxY = allowedBounds.getNorthEast().lat();
		var AminX = allowedBounds.getSouthWest().lng();
		var AminY = allowedBounds.getSouthWest().lat();

		if (X < AminX) {X = AminX;}
		if (X > AmaxX) {X = AmaxX;}
		if (Y < AminY) {Y = AminY;}
		if (Y > AmaxY) {Y = AmaxY;}
		//alert ("Restricting "+Y+" "+X);
		MapInstance.setCenter(new GLatLng(Y,X));
	}
	
	function AccMapZoomEnd(prev, cur)
	{
		//var cur_map_type = MapInstance.getCurrentMapType();
		if ((cur < MIN_CUSTOM_MAP_RESOLUTION || cur > MAX_CUSTOM_MAP_RESOLUTION ))
		{
			SetMapType(LastGoogleMapType);
		}
		else if ((cur >= MIN_CUSTOM_MAP_RESOLUTION && cur <= MAX_CUSTOM_MAP_RESOLUTION)
			//&& (cur_map_type == G_NORMAL_MAP || cur_map_type == G_SATELLITE_MAP || cur_map_type == G_HYBRID_MAP)
			)
		{
			SetMapType(custommap);
		}
	}
	
	var clickTimeout = null; // Used to separate single click from double click
  var overlay_timeout;
  var latlng_timeout;
  var olLatlng_timeout;
  
	function AccMapClicked(overlay,latlng,olLatlng)
  {
    if (clickTimeout == null)
    {
      possibleDoubleClick = true;
      overlay_timeout = overlay;
      latlng_timeout = latlng;
      olLatlng_timeout = olLatlng;
      clickTimeout = window.setTimeout("mapSingleClick(overlay_timeout,latlng_timeout,olLatlng_timeout);",500);
    }
  }

	function AccMapDblClicked(overlay,latlng)
	{
    window.clearTimeout(clickTimeout);
    clickTimeout = null;
  }
  
  function mapSingleClick(overlay,latlng,olLatlon) {
    clickTimeout = null;
    // Process single click
  
  	// The map or marker has been clicked.
		if (SelectAreaEnabled)
		{
			var point = latlng;
			if (overlay)
				point = overlay.getLatLng();
			
			var p1 = new GPoint(100,100);
			var p2 = new GPoint(100+HCWIDTH/2,100);
			var loc1 = MapInstance.fromContainerPixelToLatLng(p1);
			var loc2 = MapInstance.fromContainerPixelToLatLng(p2);
			var dist = loc1.distanceFrom(loc2);
			
			document.mapform.radius.value = dist;
			document.mapform.lat.value = point.lat();
			document.mapform.lng.value = point.lng();
			document.forms['mapform'].submit();
		}
		else if (overlay)
		{
			if (overlay.getTitle) { AFInfoDiv.innerHTML = "<b>"+overlay.getTitle()+"</b>"; }
			if (overlay.accAFID)
			{
				LastClickedAFID = overlay.accAFID;
				AFInfoLoadingStyle.display='block';
				x_GetAFOverView(overlay.accAFID, cb_GetAFOverView);
			}
		}
  }
   
	
	function cb_GetAFOverView(result)
	{
		AFInfoDiv.innerHTML = result;
		AFInfoLoadingStyle.display = 'none';
	}

	function AccMapMouseOver(point)
	{
		if (SelectAreaEnabled)
			KresliRamecek();
	}
	
	function AccMapMouseOut(point)
	{
		VypniRamecek();
	}
	
	function AccMapMouseMove(point)
	{
		if (SelectAreaEnabled)
		{
			KresliRamecek();
			var pxpoint = MapInstance.fromLatLngToContainerPixel(point);
			var page_xy = GetXYInPage(pxpoint.x,pxpoint.y);
			Animace(pxpoint.x,pxpoint.y,page_xy[0],page_xy[1]);
		}
	}

	function AccMapDragStart()
	{
		VypniRamecek();
	}
	
	// New view of the map, need to reload markers.
	function AccNewAreaDisplayed()
	{
		checkBounds();
		
		var bounds = MapInstance.getBounds();
		var sw = bounds.getSouthWest();
		var ne = bounds.getNorthEast();
		
		var i;
		var groupTypeIDs = "";
		for (i=0; i<=MAX_TYPE_GROUP; i++)
		{
			var checkbox = eval('document.mapform.type'+i);
			if (checkbox.checked)
				groupTypeIDs += i+",";
		}

		var PriceElement = GetElement('price'); 
		var price = PriceElement.options[PriceElement.selectedIndex].value;
		x_GetAFsInMap(++gAFsRequestNo, sw.lng(),sw.lat(),ne.lng(),ne.lat(),groupTypeIDs,groupTypeIDs,price,cb_AccNewAreaDisplayed);
	}
	
	function cb_AccNewAreaDisplayed(result)
	{
		var arr = result.split('<');
		var counts = arr[0].split(';');

		var requestNo = parseInt(counts[2]);
		if (gAFsReplyReceived < requestNo)
			gAFsReplyReceived = requestNo;
			
		if (gAFsRequestNo > gAFsReplyReceived) // not the last response, ignore, wait for current one
			return;

		GetElement('countinfomsgdisp').innerHTML = counts[0];
		GetElement('countinfomsgtot').innerHTML = counts[1];
		
		// info about AF counts
		var countsStyle=GetStyle('countinfomsg');
		if (parseInt(counts[0]) < parseInt(counts[1])) // should be displayed
		{
			if (countsStyle.display == 'none')
				countsStyle.display = 'block';
		}
		else
		{
			if (countsStyle.display == 'block')
				countsStyle.display = 'none';
		}
		
		var maxPrice = parseFloat(document.mapform.price.value);
		
		// markers
		var i;
		for (i = 1; i <= parseInt(counts[0]); i++)
		{
			var qi = arr[i].split('>');
			var hash=markerHash(qi[0]);
			var id = parseInt(qi[0]);
			
			var active = false;
			var checkbox = eval('document.mapform.type'+qi[4]);
			var price = parseFloat(qi[5]);
			// make active only if the type is selected and price is below selected
			if (checkbox && checkbox.checked && (maxPrice == 0 || price <= maxPrice))
				active = true;
				
			if (markerPresent(hash, id, active))
				continue;

			// marker not currently in the map, create new one
			var marked = qi[6] && qi[6] != '';
			var point = new GLatLng(parseFloat(qi[3]),parseFloat(qi[2]));
			var marker = active ? marked ? new GMarker( point, {icon: AFActiveIconBlink, title:qi[1], zIndexProcess:function(){return 4;} })
								         : new GMarker( point, {icon: AFActiveIcon, title:qi[1], zIndexProcess:function(){return 3;} })
								: new GMarker( point, {icon: AFPassiveIcon, title:qi[1], zIndexProcess:function(){return 2;} });
			marker.accAFID = id;
			marker.accInfo = qi[6].replaceAll('&lt;','<').replaceAll('&gt;','>').replaceAll('&amp;','&');
			marker.accActive = active;
			marker.dirty = true;
			MapInstance.addOverlay(marker);
			
			// should we display the info (for PROFI)
			if (marked && active)
				GEvent.addListener(marker, 'mouseover', showProfiAFInfoBoxInMap );

			// add to our array
			Markers[hash].push(marker);
		}

		// remove markers not in current view
		removeCleanMarkers();
		
		if (loadAFsForAdvTimeout == null) // currently not running
			loadAFsForAdvTimeout = setTimeout(loadAFsForAdv, 200);
	}
	
	// "this" is the GMarker of the appropriate AF
	function showProfiAFInfoBoxInMap()
	{
/*
		var point = MapInstance.fromLatLngToContainerPixel(this.getLatLng());
		var object_info = GetStyle('ObjectInfo');
		object_info.left = (point.x-10)+'px';
		object_info.top = (point.y-10)+'px';
		var obj_html = GetElement('ObjectInfoInner');
		obj_html.innerHTML = this.accInfo;
		object_info.visibility = 'visible';
*/
		AFInfoDiv.innerHTML = "<div style='border: solid; border-width: 1px; background-color: #FAED9C;padding:3px;'>"+this.accInfo+"</div>";
		AFInfoLoadingStyle.display = 'none';
		x_GetAFOverView(this.accAFID, cb_GetAFOverView);
	}
	
	function loadAFsForAdv()
	{
		loadAFsForAdvTimeout = null;
		if (gAFsRequestNo > gAFsReplyReceived)
			return; // will be called again
		
		var center = MapInstance.getCenter();
		var bounds = MapInstance.getBounds();
		var sw = bounds.getSouthWest();
		var ne = bounds.getNorthEast();
		x_GetAFsForAdv(center.lng(), center.lat(), MapInstance.getZoom(), sw.lng(),sw.lat(),ne.lng(),ne.lat(),
			LastClickedAFID, SelectAreaEnabled, cb_loadAFsForAdv);
	}
	
	function cb_loadAFsForAdv(result)
	{
		if (AdvAFsDiv)
			AdvAFsDiv.innerHTML = result;
	}
	
	function markerPresent(hash, id, active)
	{
		var i;
		for (i=0; i<Markers[hash].length; i++)
		{
			if (Markers[hash][i].accAFID == id && Markers[hash][i].accActive == active)
			{
				Markers[hash][i].dirty = true;
				return true;
			}
		}
		return false;
	}
	
	function markerHash(num)
	{
		var arr = num.split('');
		var sum = 0;
		var i;
		for (i = 0; i < arr.length; i++)
			sum += parseInt(arr[i]);
			
		while (sum >= 10)
			sum = sum % 10;
		
		return sum;
	}
	
	function removeCleanMarkers()
	{
		var i,j;
		for (i=0;i<Markers.length;i++)
		{
			var arr=new Array();
			for(j=0;j<Markers[i].length;j++)
			{		
				if (Markers[i][j].dirty)
				{
					arr.push(Markers[i][j]);
					arr[arr.length-1].dirty=false;
				}
				else
				{
					MapInstance.removeOverlay(Markers[i][j]);
				}
			}
			Markers[i]=arr;
		}
	}
	
	
	

function KresliRamecek()
{
	tecky40_vrsek.visibility = 'visible';
	tecky40_spodek.visibility = 'visible';
}

function VypniRamecek()
{
	tecky40_vrsek.visibility = 'hidden';
	tecky40_spodek.visibility = 'hidden';
}

function Animace(divx,divy,pagex,pagey)
{
	if (zprava_cas > 100)
	{
		zpravashow = false;
		zprava.visibility = 'hidden';
	}
	else
	{
		zprava.left = (pagex - 100)+'px';
		zprava.top = (pagey + 60)+'px';
		zprava_cas++;
	}

	tecky40_vrsek.left = (pagex-HCWIDTH/2)+'px';
	tecky40_vrsek.top = (pagey-15-HCHEIGHT)+'px';
	tecky40_spodek.left = (pagex-HCWIDTH/2)+'px';
	tecky40_spodek.top = (pagey+15)+'px';

	tecky40_vrsek.clip  = 'rect('+(HCHEIGHT+15-divy<0?0:HCHEIGHT+15-divy)+'px,'+(HCWIDTH/2+(MAPWIDTH-divx)>HCWIDTH?HCWIDTH:HCWIDTH/2+(MAPWIDTH-divx))+'px,'+HCHEIGHT+'px,'+(HCWIDTH/2-divx<0?0:HCWIDTH/2-divx)+'px)';
	tecky40_spodek.clip = 'rect('+0+'px,'+(HCWIDTH/2+(MAPWIDTH-divx)>HCWIDTH?HCWIDTH:HCWIDTH/2+(MAPWIDTH-divx))+'px,'+(MAPHEIGHT-divy-15>HCHEIGHT?HCHEIGHT:MAPHEIGHT-divy-15)+'px,'+(HCWIDTH/2-divx<0?0:HCWIDTH/2-divx)+'px)';
}


// params: event, skupina_zarizeni, 0: nemenit status checked 1: zmenit protoze se kliklo na popis
function GroupTypeClicked(e,skupinaID,zmenitChecked)
{
	var checkbox = eval('document.mapform.type'+skupinaID);

	if (zmenitChecked == 1)
		checkbox.checked = !checkbox.checked;
		
	// reload the accommodation facilities - the same action as is for new area
	AccNewAreaDisplayed();
}

function PriceChanged(newPrice)
{
	// reload the accommodation facilities - the same action as is for new area
	AccNewAreaDisplayed();
}

function GetXYInPage(map_x, map_y)
{
	var mapbox = GetElement('map_canvas');
	var page = GetElement('whole-page');
	var panel = GetElement('main-panel');
	var area = GetElement('maparea');

	var x = map_x + mapbox.offsetLeft + page.offsetLeft + panel.offsetLeft + area.offsetLeft + 2;
	var y = map_y + mapbox.offsetTop + page.offsetTop + panel.offsetTop + area.offsetTop + 1;
	return new Array(x,y);
}

function SetMapTypeIfGoogleMap(mtype)
{
	switch (MapInstance.getCurrentMapType())
	{
	case G_NORMAL_MAP:
	case G_SATELLITE_MAP:
	case G_HYBRID_MAP:
	case G_PHYSICAL_MAP:
		SetMapType(mtype);
		break;
	}
}

function SetMapType(mtype)
{
	switch (mtype)
	{
	case G_NORMAL_MAP:
	case G_SATELLITE_MAP:
	case G_HYBRID_MAP:
	case G_PHYSICAL_MAP:
		// google map
		LastGoogleMapType = mtype;
		GetStyle('normalmapbutton').display = mtype==G_NORMAL_MAP ? 'none' : 'inline';
		//GetStyle('satellitemapbutton').display = mtype==G_SATELLITE_MAP ? 'none' : 'inline';
		GetStyle('hybridmapbutton').display = mtype==G_HYBRID_MAP ? 'none' : 'inline';
		GetStyle('physicalmapbutton').display = mtype==G_PHYSICAL_MAP ? 'none' : 'inline';
		MapTypeSwitchStyle.visibility='visible';
		break;
	default: // custom map
		MapTypeSwitchStyle.visibility='hidden';
		break;
	}

	MapInstance.setMapType(mtype);
		
	if (x_SelectMapTypeUpdate)
	{
		var mode = "";
		if (mtype == G_SATELLITE_MAP) mode = "SATELLITE";
		else if (mtype == G_HYBRID_MAP) mode = "HYBRID";
		else if (mtype == G_PHYSICAL_MAP) mode = "PHYSICAL";
		else if (mtype == G_NORMAL_MAP) mode = "NORMAL";
		
		if (mode !== "")
		{
			x_SelectMapTypeUpdate(mode, null);
		}
	}
}

