var geocoder = new GClientGeocoder();

function SitOrSquatMapApp(currentLocationIn, isIPhone) {
   	console.log("Creating App");
   	this.isIPhone = isIPhone;
   	this.map = null;
   	this.mapControl = null;
   	this.hovering = false;
   	this.currentLocation = currentLocationIn;
   	this.selectedToiletGroupId = 0;
   	this.tileMode = false;
   	this.initialLoad = true;
   	this.embedded = false;
   	this.embeddedConfigId = 0;
   	console.log("Creating Funcs");
    this.load = function() {
    	console.log("in load");
    	if (GBrowserIsCompatible()) {
    		var agent=navigator.userAgent.toLowerCase();
			var iphone = agent.indexOf('iphone') != -1;
    		
    		//var currentLocation = currentLocationIn;
			app.setTileMode(false);
			
			this.map = new GMap2(document.getElementById("map"));
			this.map.setUIToDefault();
			this.gotoCurrentLocation();
			if (!iphone) {
				//this.mapControl = new GLargeMapControl();
				//this.mapControl = new GSmallMapControl();
				//this.map.addControl(this.mapControl);
			} else {
				
			}
			this.map.enableContinuousZoom();
			
			
			this.mwIcon = new GIcon(G_DEFAULT_ICON);
			this.mwFavIcon = new GIcon(G_DEFAULT_ICON);
		
			//this.mwIcon.image = "/sitorsquat/images/map/markers/marker_unknown.png";
			this.mwIcon.image = "/sitorsquat/images/v3/maps/map_marker_yellow.png";
	        this.mwIcon.iconSize = new GSize(23, 28);
	        this.mwIcon.shadowSize = new GSize(23, 28);
	        this.mwIcon.iconAnchor = new GPoint(10, 26);
	        
	        this.mwFavIcon.image = "/sitorsquat/images/map/markers/marker_favorite.png";
	        this.mwFavIcon.iconSize = new GSize(23, 28);
	        this.mwFavIcon.shadowSize = new GSize(23, 28);
	        this.mwFavIcon.iconAnchor = new GPoint(10, 26);
	        
	        this.mwSelectedIcon = new GIcon(G_DEFAULT_ICON);
	        this.mwSelectedIcon.image = "/sitorsquat/images/v3/maps/map_marker_selected_yellow.png";
	        this.mwSelectedIcon.iconSize = new GSize(38, 47);
	        this.mwSelectedIcon.shadowSize = new GSize(23, 28);
	        this.mwSelectedIcon.iconAnchor = new GPoint(19, 46);
	        
	        this.mwSelectedOpenIcon = new GIcon(G_DEFAULT_ICON);
	        this.mwSelectedOpenIcon.image = "/sitorsquat/images/v3/maps/map_marker_selected_green.png";
	        this.mwSelectedOpenIcon.iconSize = new GSize(38, 47);
	        this.mwSelectedOpenIcon.shadowSize = new GSize(23, 28);
	        this.mwSelectedIcon.iconAnchor = new GPoint(19, 46);
	        
	        this.mwSelectedClosedIcon = new GIcon(G_DEFAULT_ICON);
	        this.mwSelectedClosedIcon.image = "/sitorsquat/images/v3/maps/map_marker_selected_red.png";
	        this.mwSelectedClosedIcon.iconSize = new GSize(38, 47);
	        this.mwSelectedClosedIcon.shadowSize = new GSize(23, 28);
	        this.mwSelectedClosedIcon.iconAnchor = new GPoint(19, 46);
	        
	        
		    this.mwOpenIcon = new GIcon(G_DEFAULT_ICON);
	        this.mwOpenIcon.image = "/sitorsquat/images/v3/maps/map_marker_green.png";
	        this.mwOpenIcon.iconSize = new GSize(23, 28);
	        this.mwOpenIcon.shadowSize = new GSize(23, 28);
	        this.mwOpenIcon.iconAnchor = new GPoint(10, 26);    
		
			this.mwClosedIcon = new GIcon(G_DEFAULT_ICON);
	        this.mwClosedIcon.image = "/sitorsquat/images/v3/maps/map_marker_red.png";
	        this.mwClosedIcon.iconSize = new GSize(23, 28);
	        this.mwClosedIcon.shadowSize = new GSize(23, 28);
	        this.mwClosedIcon.iconAnchor = new GPoint(10, 26);    
		
	        
			// Set up our GMarkerOptions object
			this.markerOptions = { icon: this.mwIcon };
			this.markerFavOptions = { icon: this.mwFavIcon };
			this.markerSelectedOptions = { icon: this.mwSelectedIcon };
			this.markerSelectedOpenOptions = { icon: this.mwSelectedOpenIcon };
			this.markerSelectedClosedOptions = { icon: this.mwSelectedClosedIcon };
			this.markerOpenOptions = { icon: this.mwOpenIcon };
			this.markerClosedOptions = { icon: this.mwClosedIcon };
			
			console.log("Attaching events load");
			this.defaultAttachEvents();
			this.attachEvents();
			
		}
    };
    
    this.moveMap = function(x) {
    	var center = app.map.getCenter();
    	var point = app.map.fromLatLngToContainerPixel(center);
    	point.x += x;
    	app.map.setCenter(app.map.fromContainerPixelToLatLng(point));
    };
    
    this.embeddedSearch = function() {
    	var address = $("addressField").value;
    	app.gotoAddress(address, -1);
    };
    
    this.gotoLocation = function(loc,zoomLevel) {
    	if (loc.lat == 0 || loc.lng == 0) {
        	app.gotoAddress(loc.address, zoomLevel);
        } else {
        	app.map.setCenter(new GLatLng(loc.lat,loc.lng), (zoomLevel == -1) ? app.map.getZoom() : zoomLevel);
        	app.reloadToilets();
        }
    };
    
    this.gotoAddress  = function(address, zoomLevel) {
    	geocoder.getLatLng(
		    address,
		    function(point) {
		      if (!point) {
		        alert(address + " not found");
		      } else {
		      	//alert("Zoom Level = " + zoomLevel);
		      	//console.log("Going to zoom: " + zoomLevel);
		        app.map.setCenter(point, (zoomLevel == -1) ? app.map.getZoom() : zoomLevel);
		       	app.reloadToilets();
		        
		      }
		    }
		  );
    };
    
    this.gotoCurrentLocation = function() {
    	//alert("Going to current location");
    	this.map.setCenter(new GLatLng(this.currentLocation.lat, this.currentLocation.lng), (app.embedded == true && startZoomLevel != null) ? startZoomLevel : 15);
    };
    
    this.click = function(x,y) {
    	
    };
    
    this.moveStart = function() {
    	
    };
    
    this.moveTo = function(x, y) {
    	this.map.panDirection(x / 50,y / 50);
    };
    
    this.moveEnd = function(x, y) {
    	
    };
    
    
    this.zoom = function(dist) {
    	if (dist > 0) {
    		this.map.zoomIn();
    	} else {
    		this.map.zoomOut();
    	}
    };
    
    this.getRealToilet = function(toiletCopy) {
    	for(var i = 0; i < this.toilets.length;i++) {
    		var toilet = this.toilets[i];
    		if (toilet.groupId == toiletCopy.groupId)
    			return toilet;
    	}
    	return null;
    };
    
    this.hideToiletDetails = function() {
    	//console.log("Hiding toilets");
    	if (this.toilets == null)
    		return;
    	for(var i = 0; i < this.toilets.length;i++) {
    		var toilet = this.toilets[i];
			//console.log("Looking at toilet: ", toilet.groupId);
			var overlay = overlayCacheMap["" + toilet.groupId];
			if (overlay != null) {
				//console.log("Removing overlay at toilet: ", toilet.groupId);
				this.map.removeOverlay(overlay);
				overlayCacheMap["" + toilet.groupId] = null;
			}
    	}
    };
    
    
    
    this.showToiletDetails = function(toilet) {
    	//console.log("Showing toilet: ", toilet.groupId);
    	
    	this.hideToiletDetails();
    	
    	var markerPoint = this.map.fromLatLngToContainerPixel(toilet.latlng);
    	var centerPoint = this.map.fromLatLngToContainerPixel(this.map.getCenter());
    	var maxX = centerPoint.x * 2;
		//console.log("Current point: ", markerPoint.x, ",",markerPoint.y);
		//console.log("MaxX = " + maxX)
		
		if (markerPoint.y < 400 || maxX - markerPoint.x < 750 || markerPoint.x -200 < 0) {
			if (markerPoint.y < 400) {
				var ydist = 400 - markerPoint.y;
				centerPoint.y -= ydist;
				//console.log("Removing y dist: " + ydist);
			}
			
			if ((maxX - markerPoint.x) < 750) {
				var xdist = 750 - (maxX - markerPoint.x);
				centerPoint.x += xdist
				//console.log("Removing x dist: " + xdist);
			} else if ( markerPoint.x -200 < 0) {
				var xdist = 200 - markerPoint.x;
				centerPoint.x -= xdist
			}
			//console.log("new x = ", centerPoint.x, " new y = ", centerPoint.y);
			var newLatLng = this.map.fromContainerPixelToLatLng(centerPoint);
			//console.log("new lat = ", newLatLng.lat(), " new lng = ", newLatLng.lng());
			//this.map.setCenter(newLatLng, this.map.getZoom());
			this.map.panTo(newLatLng);
		}
    	
    	var infoOverlay = new SInfoOverlay(toilet);
    	this.map.addOverlay(infoOverlay);
    	overlayCacheMap["" + toilet.groupId] = infoOverlay;
    	
    };
    
    this.removeToiletMarker = function(toilet) {
    	//console.log("Removing listener");
    	//GEvent.removeListener(toilet.listenerHandler);
    	//console.log("Removing marker overlay");
    	this.map.removeOverlay(toilet.overlay);
    	//console.log("Removing info overlay");
    	if (toilet.infoOverlay != null)
    		this.map.removeOverlay(toilet.infoOverlay);
    	//console.log("Removing complete");
    };
    
    this.addToiletMarker = function(toilet) {
    	var latlng = new GLatLng(toilet.latitude,toilet.longitude);
		toilet.latlng = latlng;
		var options = (toilet.selected == true) ? ((toilet.status == 1) ? this.markerSelectedOpenOptions : (toilet.status == 2) ? this.markerSelectedClosedOptions : this.markerSelectedOptions) : (toilet.fav) ? this.markerFavOptions : 
			(toilet.status == 1) ?  this.markerOpenOptions : (toilet.status == 2) ? this.markerClosedOptions : this.markerOptions;
		toilet.overlay = new GMarker(latlng, options);
		toilet.overlay.marker = true;
		
		this.map.addOverlay(toilet.overlay);
		
		
    };
    
    this.clearToilets = function() {
    	if (this.toilets == null)
    		return;
    		
    	for(var i = 0; i < this.toilets.length;i++) {
			var toilet = this.toilets[i];
			this.removeToiletMarker(toilet);
		}
		this.toilets = new Array();
    };
    
    this.clearTiles = function() {
    	if (this.tiles == null)
    		return;
    		
    	for(var i = 0; i < this.tiles.length;i++) {
			var tile = this.tiles[i];
			if (tile.overlay != null) {
				tile.overlay.hide();
				this.map.removeOverlay(tile.overlay);
			}
			
		}
		this.tiles = new Array();
    };
    
    
    this.setTileMode = function(newTileMode) {
    	if (newTileMode != app.tileMode) {
    		this.clearTiles();
    		this.clearToilets();
    		app.map.clearOverlays();
    		//if (newTileMode)
    		if (false)
    			this.dettachEvents();
    		else
    			this.attachEvents();
    	}
    	app.tileMode = newTileMode;
    };
    
    this.setTiles = function(newTiles) {
    	//console.log("Clearing tiles");
    	app.clearTiles();
    	app.map.clearOverlays();
    	//console.log("Cleared tiles");
    	app.tiles = newTiles;
    	//console.log("Tile count = " + newTiles.length);
    	for(var i = 0; i < newTiles.length;i++) {
    		var tile = newTiles[i];
    		if (tile.toiletCount == 0)
    			continue;
    		//console.log("Creating polygon: ", tile);
    		var polygon = new GPolygon([
				new GLatLng(tile.minLat, tile.minLng),
				new GLatLng(tile.minLat, tile.maxLng),
				new GLatLng(tile.maxLat, tile.maxLng),
				new GLatLng(tile.maxLat, tile.minLng),
				new GLatLng(tile.minLat, tile.minLng)], 
				"#f33f00", 2, 0.5, "#ff0000", 0.2);
			
			var topLeft = this.map.fromLatLngToDivPixel(new GLatLng(tile.maxLat, tile.minLng))
			topLeft.y += 50;
			var labelTopLeft = this.map.fromDivPixelToLatLng(topLeft);
			
			polygon.label = new ELabel(labelTopLeft, tile.toiletCount, "mapTileLabel");
			app.map.addOverlay(polygon.label);
			polygon.label.hide();
			GEvent.addListener(polygon,'mouseover', function() {
				this.setFillStyle({color: "#000000",  opacity: 0.7});
				this.setStrokeStyle({color: "#888888", weight: 4, opacity: 0.8});
				this.label.show();
			});
			
			GEvent.addListener(polygon,'click', function(latlng) {
				app.map.removeOverlay(this);
				app.map.setCenter(latlng);
				app.map.zoomIn();
			});
			
			GEvent.addListener(polygon,'mouseout', function() {
				this.setFillStyle({color: "#ff0000",  opacity: 0.2});
				this.setStrokeStyle({color: "#f33f00", weight: 2, opacity: 0.5});
				this.label.hide();
			});
			
			
			tile.overlay = polygon;
			this.map.addOverlay(tile.overlay);
  		
    	}
    };
    
    this.setToilets = function(newToilets, toiletImages, favs, stats, statuses) {
    	//console.log("Toilet count = ", (this.toilets == null) ? 0 : this.toilets.length, " new count = ", newToilets.length);
		for(var i = 0; i < newToilets.length;i++) {
			newToilets[i].image = toiletImages[i];
			newToilets[i].stats = stats[i];
		}
		
		
		if (this.toilets == null)
			this.toilets = new Array();
		
		for(var j = 0; j < newToilets.length;j++) {
			var newToilet = newToilets[j];
			//console.log("Checking toilet: " +newToilet.groupId); 
			newToilet.fav = false;
			newToilet.selected = this.selectedToiletGroupId == newToilet.groupId;
			for(var i = 0; i < favs.length;i++) {
				//console.log("Checking fav: " +favs[i]);
				if (newToilet.groupId == favs[i]) {
					//console.log("Is Fav");
					newToilet.fav = true;
					break;
				}
			}
			
			newToilet.status = statuses[j];
		}
		
		for(var i = 0; i < this.toilets.length;i++) {
			var toilet = this.toilets[i];
			toilet.exists = false;
			for(var j = 0; j < newToilets.length;j++) {
				var newToilet = newToilets[j];
				if (toilet.groupId == newToilet.groupId) {
					toilet.exists = true;
					break;
				}
			}
			
			if (toilet.exists && toilet.fav == newToilet.fav) {
				newToilet.overlay = toilet.overlay;
				newToilet.listenerHandler = toilet.listenerHandler;
				newToilet.latlng = toilet.latlng;
			} else {
				//console.log("Removing toilet overlay ", toilet.groupId);
				this.removeToiletMarker(toilet);
			}
		}
		
		
		this.toilets = newToilets;
		
		
		
		for(var i = 0; i < this.toilets.length;i++) {
			var toilet = this.toilets[i];
			//console.log("Toilet id = ", toilet.groupId);
			if (toilet.overlay == null) {
				this.addToiletMarker(toilet);
			} else {
				//console.log("Toilet ", toilet.groupId, " already has overlay, no reason to add");
			}
		}
		
		
	
    };
    
    this.setLoading = function(loading) {
    	$('mapLoading').style.display = (loading) ? "block" : "none";
    };
    
    this.requestCount = 0;
    
    this.reloadToilets = function() {
    	var bounds = this.map.getBounds()
    	var sw = bounds.getSouthWest();
    	var ne = bounds.getNorthEast();
    	app.requestCount++;
    	var requestCount = app.requestCount;
    	app.ne = ne;
    	var size = this.map.getSize();
    	app.setLoading(true);
    	//console.log("Size = " + size.width + "/" + size.height);
    	new Ajax.Request('/sitorsquat/home/getToilets', {
			method: 'post',
			parameters: {neLat: ne.lat(), neLng: ne.lng(), swLat: sw.lat(), swLng: sw.lng(), width: size.width, height: size.height, zoomLevel: app.map.getZoom(), initialLoad: app.initialLoad, embedded: app.embedded, embeddedConfigId: app.embeddedConfigId},
			onSuccess: function(response) {
					var result = response.responseJSON;
					if (result.resp != null) {
						alert(result.resp);
					} else {
						//if (app.ne != null && (ne.lng() != app.ne.lng() || ne.lat() != app.ne.lat())) {
						if (app.requestCount != requestCount || (app.ne != null && (ne.lng() != app.ne.lng() || ne.lat() != app.ne.lat()))) {
							//alert("Not the most recent reload request");
							//console.log("Not the most rescent result");
							return;
						} 
						
						var toilets = result.toilets;
						var toiletImages = result.toiletImages;
						var toiletStats = result.stats;
						var toiletStatuses = result.statuses;
						var favs = result.favorites;
						app.initialLoad = false;
						if (app.map.getZoom() != result.zoomLevel) {
							//console.log("Current Zoome Level = " + app.map.getZoom() + " Result Zoom Level " + result.zoomLevel);
							app.map.setZoom(result.zoomLevel);
						} else {
							app.setTileMode(result.tileMode);
							if (result.tileMode == true) {
								//console.log("Setting tiles");
								app.setToilets(new Array(), new Array(), new Array(), new Object(), new Array());
								app.setTiles(result.tiles);
								//console.log("Set tiles");
							} else {
								//console.log("Setting toilets");
								app.attachEvents(); 
								app.setToilets(toilets, toiletImages, favs, toiletStats, toiletStatuses);
								//console.log("Set toilets");
							}
							
							app.setLoading(false);
						}
						
					}
					
				}
			});
    	
    };
    
    this.hoverTimer = null;
    this.hoverPoint = null;
    this.hoverToilets = null;
    this.configureHover = function() {
    	var point = app.hoverPoint;
    	var toilets = app.hoverToilets;
    	
    	if (toilets != null && toilets.length > 0) {
			//console.log("Creating overlay");
    	
	    	app.hoverOverlay = new SHoverOverlay(point, toilets);
	    	//console.log("Adding overlay to map");
	    	app.map.addOverlay(app.hoverOverlay);
    	} else {
    		//console.log("No toilets or toilets.length is 0");
    	}
    	//this.hovering = false;
    };
    
    this.zoomEndEvent = function(oldLevel, newLevel) {
		app.popupHide();
		app.reloadToilets();
    };
    
    this.moveEndEvent = function() {
		app.popupHide();
		app.reloadToilets();
    };
    
    this.popupHide = function() {
    	if (app.popupOverlay != null) {
    		//app.map.removeOverlay(app.popupOverlay);
    		app.popupOverlay.remove();
    		app.popupOverlay = null;
    		app.theseToilets = null;
    	}
    };
    
    this.selectToilet = function(groupId) {
    	this.selectedToiletGroupId = groupId;
    	var selectedToilet;
    	for (var i = 0; i < app.toilets.length;i++) {
    		var toilet = app.toilets[i];
    		if (toilet.groupId == groupId && toilet.selected == false) {
    			//console.log("---Selecting toilet");
    			selectedToilet = toilet;
    			toilet.selected = true;
    			app.removeToiletMarker(toilet);
    			app.addToiletMarker(toilet);
    		} else if (toilet.groupId != groupId && toilet.selected == true) {
    			toilet.selected = false;
    			app.removeToiletMarker(toilet);
    			app.addToiletMarker(toilet);
    		}
    	}
    	app.popupHide();
    	if (app.embedded) {
    		//window.open("/sitorsquat/toiletDetailsDirect/" + groupId);
    		$("detailsScreen").style.display = "inline";
    		$("detailsNameField").innerHTML = selectedToilet.locationName;
    		var frame = $("detailsFrame");
    		var currentHeight = $("map").offsetHeight;//getCurrentStyleNumeric($("map"),"height");
    		
    		frame.style.height = (currentHeight - 53) + "px";
    		frame.src = "/sitorsquat/embedded/details?toiletGroupId=" + groupId + "&ratings=" + showRatings + "&websites=" + showWebsites;
    	} else {
    		contentPanelGoto("/sitorsquat/toilet/details?groupId=" + groupId);
    	}
    	
    };
    
    this.gotoSitOrSquatDetails = function() {
    	if (this.selectedToiletGroupId == null || this.selectedToiletGroupId == 0)
    		return;
    	
    	window.open("/sitorsquat/toiletDetailsDirect/" + this.selectedToiletGroupId);
    };
    
    this.hideEmbeddedToiletDetails = function() {
    	$("detailsScreen").style.display = "none";
    };
    
    this.clickEvent = function(overlay,  latlng,  overlaylatlng) {
    	console.log("In click event");
    	if (overlay != null && !overlay.marker) {
    		//console.dir(overlay);
    		console.log("Hiding popup");
    		app.popupHide();
    		
    		//return;
    	}
    	
    	//console.log("Past overlay check");
    	if (app.hoverOverlay != null) {
   			console.log("Hiding hover overlay");
   			app.map.removeOverlay(app.hoverOverlay);
   			app.hoverOverlay = null;
     	}
     	
     	if (app.hoverTimer != null) { 
    		console.log("Clearing Hover Timer");
    		clearTimeout(app.hoverTimer);
    	}
    		
    	if (app.popupOverlay != null) {
    		console.log("Removing popup overlay");
    		//app.map.removeOverlay(app.popupOverlay);
    		app.popupOverlay.remove();
    		app.popupOverlay = null;
    	}
    	
    	var point = app.hoverPoint;
    	var toilets = app.hoverToilets;
    	
    	console.dir(toilets);
    	if (toilets != null && toilets.length > 0) {
			//console.log("Creating overlay");
    		app.popupOverlay = new SPopupOverlay(point, toilets);
	    	app.popupOverlay.redraw(true);
	    	//console.log("Adding overlay to map");
	    	//app.map.addOverlay(app.popupOverlay);
    	} else {
    		//console.log("No toilets or toilets.length is 0");
    	}
    	
     	
    };
    
    this.mouseMoveEvent = function(latlng) {
    	//if (app.popupOverlay != null)
    	//	return;
    		
    	var toilets = app.toilets;
    	if (toilets == null) return;
     	
    	var theseToilets = new Array();
    	var currentPoint = app.map.fromLatLngToContainerPixel(latlng);
     	var boundsNE = new GPoint(currentPoint.x - 15, currentPoint.y - 5);
     	var boundsSW = new GPoint(currentPoint.x + 15, currentPoint.y + 30);
     	
     	
     	for (var i = 0; i < toilets.length;i++) {
     		var toilet = toilets[i];
     		var overlay = toilet.overlay;
     		
     		var latlng = overlay.getLatLng();
     		//var point = app.map.fromLatLngToDivPixel(latlng);
     		var point = app.map.fromLatLngToContainerPixel(latlng);
     		//console.log("PointX = " + point.x + " PointY = " + point.y);
     		
     		
     		//console.log("NEX = " + neCorner.x + " NEY = " + neCorner.y + " SWX = " + swCorner.x + " SWY = " + swCorner.y);
     		if (point.x >= boundsNE.x && point.x <= boundsSW.x && point.y >= boundsNE.y && point.y <= boundsSW.y) {
     			//console.log("Hit " + toilet.locationName);
     			//console.dir(toilet);
     			theseToilets[theseToilets.length] = toilet;
     		} else {
     			//console.log("No hit " + toilet.locationName);
     		}
     		
     	}
     	
     	var toiletsMatch = false;
     	if (app.hoverOverlay != null && app.hoverToilets != null && theseToilets.length == app.hoverToilets.length) {
     		toiletsMatch = true;
     		for (var i = 0; i < theseToilets.length; i++) {
     			var toilet = theseToilets[i];
     			var toilet2 = app.hoverToilets[i];
     			if (toilet.id != toilet2.id) {
     				toiletsMatch = false;
     				break;
     			}
     		}
     	}
     	
     	//if ( {
	     	if (app.hoverOverlay != null && !toiletsMatch && app.popupOverlay == null) {
	   			app.map.removeOverlay(app.hoverOverlay);
	   			app.hoverOverlay = null;
	     	}
	     	
	     	
	    //}	
	    if (app.hoverTimer != null && !toiletsMatch) 
	    	clearTimeout(app.hoverTimer);
     	
     	if (!toiletsMatch && theseToilets.length > 0) {
	     	//console.log("Setting timer, got toilets");
	     	app.hoverPoint = currentPoint;
	     	app.hoverToilets = theseToilets;
	     	//app.configureHover();
	     	if (app.popupOverlay == null)
	     		app.hoverTimer = setTimeout("app.configureHover()", 100);
     	}
     	
     	
     	
     	
     	//app.configureHover(currentPoint, theseToilets);
    };
    
    this
    
    
    this.defaultAttachEvents = function() {
    	GEvent.addListener(this.map, "zoomend", this.zoomEndEvent);
    	GEvent.addListener(this.map, "moveend", this.moveEndEvent);
    };
    
    this.dettachEvents = function() {
    	if (this.mouseMoveListener) GEvent.removeListener(this.mouseMoveListener);
    	if (this.clickListener) GEvent.removeListener(this.clickListener);
    };
    
    this.attachEvents = function() {
    	this.mouseMoveListener = GEvent.addListener(this.map, "mousemove", this.mouseMoveEvent);
		this.clickListener = GEvent.addListener(this.map, "click", this.clickEvent);
    };
    
    this.setCoordinates = function(lat,lng) {
    	app.map.setCenter(new GLatLng(lat, lng), app.map.getZoom());
		app.map.savePosition();
    };
    
    this.setActualLocation = function(address,addressField) {
    	console.log("Sending actual location");
    	new Ajax.Request('/sitorsquat/home/setLocation', {
			method: 'post',
			parameters: {address: address},
			onSuccess: function(response) {
					var result = response.responseJSON;
					if (result.resp != null) {
						alert(result.resp);
					} else {
						console.log("Got location response");
						var currentLocation = result.loc;
						console.log("Checking address field");
						if (addressField)
							addressField.value = result.loc.address;
						console.log("Checking cookie");
						if (app.isIPhone == false)						
							Cookie.set("currentAddress", result.loc.address, 100);
						else
							document.location.href="http://www.sitorsquat.com/sorsiphone?action=setLocation||||address=" + result.loc.address;
						console.log("Moving map");
						app.map.setCenter(new GLatLng(currentLocation.lat, currentLocation.lng), app.map.getZoom());
						app.map.savePosition();
					}
					
				}
			});
    };
    
   	this.setLocation = function() {
   		this.hideToiletDetails();
   	
    	var addressField = document.getElementById("headerFindField");
    	var address = addressField.value;
    	this.setActualLocation(address, addressField);
    	
			  	
    };
    
    this.setCurrentToilet = function(toilet) {
    	this.currentToilet = toilet;
    };
    
    this.getCurrentId = function() {
    	return this.currentToilet.id;
    };
    
    this.getCurrentDescription = function() {
    	return this.currentToilet.description;
    };
    
    this.getCurrentInfo = function() {
    	if (this.currentToilet == null || this.currentToilet.id == -1)
    		return null;
    	else
    		return this.iphoneEncode(this.currentToilet);
    };
    
    this.getCurrentImageInfo = function() {
    	if (this.currentToilet.image == null || this.currentToilet.image.id == -1)
    		return null;
    	else
    		return this.iphoneEncode(this.currentToilet.image);
    };
    
    this.iphoneEncode = function(object) {
    	var encodedString = "";
        for (var name in object)
        {
            try
            {
                if (encodedString != "") {
                	encodedString = encodedString + "||||";
                }
                encodedString = encodedString + name + "=" + object[name];
            }
            catch (exc)
            {
            }
        }
        
        return encodedString;
    };
    
    
    
    
    
}


