var geocoder = null;
var addressMarker;
var browser = "";
var cacheCoordinates = new Array();
var ie7 = (document.all && !window.opera && window.XMLHttpRequest) ? true : false;

function setMapStyles(){
		var browser = "";
		var overlaySmallMap = document.getElementById("overlaySmallMap");
		if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
			overlaySmallMap.style.left = "250px";
			overlaySmallMap.style.filter = 'alpha(opacity=20)';
			browser = "IE6";
		}else{
			if(ie7){
				overlaySmallMap.style.filter = 'alpha(opacity=18)';
			}else{
				overlaySmallMap.style.opacity  = 0.2;
				overlaySmallMap.style.mozOpacity = 0.2;
				overlaySmallMap.style.khtmlOpacity = 0.2;
				overlaySmallMap.style.filter = 'alpha(opacity=2)';
			}
		}

		return true;
	}

	function openFullScreenMap(targetId,module_name){
		var id = "overlayFullScreenMap";
		var objOverlay = document.getElementById(id);
		var objWrapper = document.getElementById(targetId);
				
		var link = "http://" + window.location.host + "/ajax.php?grandparent=site&m="+module_name+"&a=170";
		new Ajax.Updater(targetId, link, 
		    { evalScripts: true,
			  onLoaded: function () {
				objWrapper.style.display = "block";
		      } 
		    }
		);
		return true;
	}	

	function loadRoute(){
		var directionsPanel = document.getElementById("mapRoute");
		var mapRouteFrom = document.getElementById("mapRouteFrom");
		if(mapRouteFrom.value != ""){
			gdir = new GDirections(map, directionsPanel);
			GEvent.addListener(gdir, "load", onGDirectionsLoad);
			GEvent.addListener(gdir, "error", handleErrors);
			setDirections(mapRouteFrom.value, "" + config['Lat'] + ", " + config['Lng']);
		}
	}

	function setDirections(fromAddress, toAddress) {
		gdir.load("from: " + fromAddress + " to: " + toAddress);
	}

	function handleErrors(){
		if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
			alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
		else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
			alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
		else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
			alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
		//   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
		//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
		else if (gdir.getStatus().code == G_GEO_BAD_KEY)
			alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
		else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
			alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
		else alert("An unknown error occurred.");
	}

	function onGDirectionsLoad(){
		directionsPanel = document.getElementById("mapRoute");
		directionsPanel.innerHTML = "";
		directionsPanel.style.display = "block";
	}
	
	function formatPictureName(inputNumber){
		if(inputNumber > 1000){
			var tmp = new String(inputNumber);
			if(inputNumber < 10000){
				return (tmp.substr(0,2) + "00");
			}
			if(inputNumber > 10000 && inputNumber < 100000){
				return (tmp.substr(0,2) + "000");
			}
			if(inputNumber > 100000){
				return (tmp.substr(0,2) + "0000");
			}
		}
		return inputNumber;
	}
	
	function addAddressesMarkers(map, curLat,curLng,jsonString){
		var jsonCoordinates = jsonString.evalJSON();
		var baseIcon = new GIcon(G_DEFAULT_ICON);
		baseIcon.shadow = "";
		baseIcon.shadowSize = new GSize(0,0);
		
		function createAddressMarker(point, itemId, objAmount, title) {
			var amountForPics = formatPictureName(objAmount);
			baseIcon.image = "http://" + window.location.host + "/resources/userdata/images/pics/img_"+amountForPics+".png";
			if(objAmount > 0 && objAmount < 10){
				baseIcon.iconSize = new GSize(25,17);
				baseIcon.imageMap = [0,0, 25,0, 25,17, 0,17 ];
			}else if(objAmount > 9 && objAmount < 100){
				baseIcon.iconSize = new GSize(29,17);
				baseIcon.imageMap = [0,0, 29,0, 29,17, 0,17 ];
			}else if(objAmount > 99 && objAmount < 1000){
				baseIcon.iconSize = new GSize(36,21);
				baseIcon.imageMap = [0,0, 36,0, 36,21, 0,21 ];
			}else if(objAmount > 999 && objAmount < 10000){
				baseIcon.iconSize = new GSize(57,23);
				baseIcon.imageMap = [0,0, 57,0, 57,23, 0,23 ];
			}else if(objAmount > 9999 && objAmount < 100000){
				baseIcon.iconSize = new GSize(70,22);
				baseIcon.imageMap = [0,0, 70,0, 70,22, 0,22 ];
			}else if(objAmount > 99999){
				baseIcon.iconSize = new GSize(73,23);
				baseIcon.imageMap = [0,0, 73,0, 73,23, 0,23 ];
			}	
			
			markerOptions = { icon:baseIcon, title:title + " (" + objAmount +")"};
			var marker = new GMarker(point, markerOptions);
			if(itemId != undefined && itemId != ''){
				GEvent.addListener(marker, "click", function() {
					map.zoomIn();
					map.setCenter(point, map.getZoom());
				});
			}
			return marker;
		}

		if(jsonCoordinates.coordinates.length > 0){
			for(var i=0; i < jsonCoordinates.coordinates.length; i++){
				if(curLat != jsonCoordinates.coordinates[i].Lat && curLng != jsonCoordinates.coordinates[i].Lng){
					 var latlng = new GLatLng(jsonCoordinates.coordinates[i].Lat,jsonCoordinates.coordinates[i].Lng);
					map.addOverlay(createAddressMarker(latlng, jsonCoordinates.coordinates[i].Id, jsonCoordinates.coordinates[i].Amount, jsonCoordinates.coordinates[i].Title));
				}
			}
		}
		
		return true;
	}
	
	function addAdditionalMarkers(map, curLat,curLng,jsonString){
		var jsonCoordinates = jsonString.evalJSON();
		var baseIcon = new GIcon(G_DEFAULT_ICON);
		baseIcon.image = config['additionalMarkerIcon'];
		baseIcon.iconSize = new GSize(16,16);
		baseIcon.shadow = "";
		baseIcon.shadowSize = new GSize(0,0);

		function createMarker(point, itemId) {
			markerOptions = { icon:baseIcon};
			var marker = new GMarker(point, markerOptions);
			if(itemId != undefined && itemId != ''){
				GEvent.addListener(marker, "mouseover", function() {
					var url = "http://" + window.location.host + "/ajax.php?grandparent=site&m=" + config['sModule'] + "&a=160&id="+itemId;
					new Ajax.Request(url, {
						method: 'post',
						onSuccess: function(transport) {
							var details = transport.responseText.evalJSON();
								var htmlDetails = "";
								var tmpUrl = new String(details.ShortPictureUrl);
								htmlDetails += "<div style='height:100px;'><div style='float:left;'><a href=\"" + "http://" + window.location.host + "/" + details.ItemUrl + "\" title=\"" + details.Title + "\" >";
								htmlDetails += "<img src=\"" + "http://" + window.location.host + "/" + tmpUrl.substr(1) + "\" alt=\"" + details.Title + "\" border=\"0\">";
								htmlDetails += "</a></div><div style='float:left;padding-left:10px;width:200px;'><p><b><a href=\"" + "http://" + window.location.host + "/" + details.ItemUrl + "\" title=\"" + details.Title + "\" >"+details.Title+"</a></b></p>";
								if(details.Content != undefined)
									htmlDetails += "<br/><p>"+details.Content+"</p>";
								
								htmlDetails += "<br/><p>"+details.Price+"</p>";
								htmlDetails += "</div></div>";
								
								marker.openInfoWindowHtml(htmlDetails,{maxWidth:380});
						}
					});
				});
				GEvent.addListener(marker, "click", function() {
					window.location.href =  "http://" + window.location.host + "/" + config['ModuleID'] + "/" + itemId + ".html";
				});
			}
			return marker;
		}

		if(jsonCoordinates.coordinates.length > 0){
			for(var i=0; i < jsonCoordinates.coordinates.length; i++){
				if(curLat != jsonCoordinates.coordinates[i].Lat && curLng != jsonCoordinates.coordinates[i].Lng){
					 var latlng = new GLatLng(jsonCoordinates.coordinates[i].Lat,jsonCoordinates.coordinates[i].Lng);
					map.addOverlay(createMarker(latlng, jsonCoordinates.coordinates[i].Id));
				}
			}
		}
		
		return true;
	}
	
	function addMainObject(myMap,myScale){
		var markerOptions;
		var curLat = config['Lat'];
		var curLng = config['Lng'];
		if(config['mainMarkerIcon'] != undefined && config['mainMarkerIcon'] != ''){
			var baseIcon = new GIcon(G_DEFAULT_ICON);
			baseIcon.image = config['mainMarkerIcon'];
			baseIcon.iconSize = new GSize(24,24);
			baseIcon.shadow = "";
			baseIcon.shadowSize = new GSize(0,0);
			markerOptions = { icon:baseIcon};
		}
		var point = new GLatLng(curLat,curLng);
		if(myScale != -1)
			myMap.setCenter(point, myScale);
		var marker = new GMarker(point,markerOptions);
		return marker;
	}
	
	function load(id, isFullScreenMap) {
		var isRequestSent = false;
		var isAddressesRequestSent = false;
		var curLat = config['Lat'];
		var curLng = config['Lng'];
		var curId = id;
		if(curId == undefined || curId == "")
			curId = "map";

		var curIsFullScreenMap = isFullScreenMap;
		if(curIsFullScreenMap == undefined || curIsFullScreenMap == "")
			curIsFullScreenMap = false;

		if (GBrowserIsCompatible()) {
			map = new GMap2(document.getElementById(curId));
			map.addOverlay(addMainObject(map,13));

			if (curLat == "0.0000000" && curLng == "0.0000000")
				showAddress(config['addressToGeocoding']);
			
			if(curIsFullScreenMap){
				map.addControl(new GLargeMapControl());
				map.addControl(new GOverviewMapControl());
				map.setZoom(14);

				function addAddressesObjects(mapZoom){
					var bounds = map.getBounds();
					var southWest = bounds.getSouthWest();
					var northEast = bounds.getNorthEast();
					var lngSpan = northEast.lng() - southWest.lng();
					var latSpan = northEast.lat() - southWest.lat();

					var url = "http://" + window.location.host + "/ajax.php?grandparent=site&m=accommodation_catalog&a=170&southWestLat="+southWest.lat()+"&southWestLng="+southWest.lng()+"&lngSpan="+lngSpan+"&latSpan="+latSpan+"&mapZoom="+mapZoom+"&child_module="+config['sModule'];
				
					if(!isAddressesRequestSent){
						new Ajax.Request(url, {
							method: 'post',
							onSuccess: function(transport) {
								isAddressesRequestSent = false;
								addAddressesMarkers(map,curLat,curLng,transport.responseText);
							},
							onLoaded: function(transport) {
								isAddressesRequestSent = true;
							}
						});
					}
				}
				
				function addAdditionalObjects(){
					var bounds = map.getBounds();
					var southWest = bounds.getSouthWest();
					var northEast = bounds.getNorthEast();
					var lngSpan = northEast.lng() - southWest.lng();
					var latSpan = northEast.lat() - southWest.lat();

					var url = "http://" + window.location.host + "/ajax.php?grandparent=site&m=" + config['sModule'] + "&a=150&southWestLat="+southWest.lat()+"&southWestLng="+southWest.lng()+"&lngSpan="+lngSpan+"&latSpan="+latSpan;
				
					var cachedResponse = cacheCoordinates[southWest.lat() + ":" + southWest.lng() + ":" + lngSpan + ":" + latSpan];
					if(cachedResponse == '' || cachedResponse == undefined || cachedResponse == null ){
						if(!isRequestSent){
							new Ajax.Request(url, {
								method: 'post',
								onSuccess: function(transport) {
									isRequestSent = false;
									cacheCoordinates[southWest.lat() + ":" + southWest.lng() + ":" + lngSpan + ":" + latSpan] = transport.responseText;
									addAdditionalMarkers(map,curLat,curLng,transport.responseText);
								},
								onLoaded: function(transport) {
									isRequestSent = true;
								}
							});
						}
					}else{
						addAdditionalMarkers(map,curLat,curLng,cachedResponse);
					}
				}
				
				addAdditionalObjects();
				
				GEvent.addListener(map, "moveend", function() {
					var curZoom = map.getZoom();
					// full map - 0 
					// max extension - 17
					if(curZoom > 11 ){
						addAdditionalObjects();
					}else{
						addAddressesObjects(curZoom);
					}
				});
				
				GEvent.addListener(map, "zoomend", function(oldLevel, newLevel) {
					var toClearMap = false;
					if(((oldLevel >= 0 && oldLevel < 6) && (newLevel >= 6)) || ((newLevel >= 0 && newLevel < 6) && (oldLevel >= 6))) toClearMap = true; // if country
					if(((oldLevel >= 6 && oldLevel < 8) && (newLevel >= 8)) || ((newLevel >= 6 && newLevel < 8) && (oldLevel >= 8))) toClearMap = true; // if region
					if(((oldLevel >= 8 && oldLevel < 10) && (newLevel >= 10)) || ((newLevel >= 8 && newLevel < 10) && (oldLevel >= 10))) toClearMap = true; // if sub_region
					if(((oldLevel >= 10 && oldLevel <= 11) && (newLevel > 11)) || ((newLevel >= 10 && newLevel <= 11) && (oldLevel > 11))) toClearMap = true; // if town
					
					if(toClearMap){
						map.clearOverlays();
						map.addOverlay(addMainObject(map,-1));
					}
				});
			}else{
				map.addControl(new GSmallZoomControl());
			}
		}
	}