var WIO_GMAP = 
{
	mapDivId          : 'wio-gmap-div-map',
	map               : null,
	marker            : null,
	defaultMarkerZoom : 17,
	objectsMarkers    : [],
	objectsToPlace    : [],
	firstZoomObjectId : null,
	idCellTableBegin  : 'wio-gmap-cell-',
	classCellSelected : 'wio-gmap-cell-selected',
	idAddress         : 'search-wio-gmap-search-input',
	idHelpBox         : 'search-wio-gmap-helpbox', 
	defCursor	      : 'pointer',
	moveCursor		  : 'move',
	idCancelB         : 'search-wio-gmap-controls-cancel',
	idStartSearch     : 'search-wio-gmap-controls-start-search', 
	placeEvent        : null,
	idFirstBlock      : 'search-wio-gmap-first-block',
	idLat             : 'search-wio-gmap-input-lat',
	idLong            : 'search-wio-gmap-input-long',
	idActionField     : 'search-wio-gmap-action',
	idForm            : 'search-wio-gmap-form',
	idDirections      : 'wio-gmap-div-directions',
	idDirectionsPlace : 'wio-gmap-div-directions-place',
	directionsPlaceImage   : '',
	directionsPlaceImageId : 'wio-gmap-image-loading-directions',
	
	idSecondBlock     : 'search-wio-gmap-second-block',
	
	ME_ON_THE_MAP     : '',
	
	customUserIcon    : null,
	baseIcon          : null,
	
	circle            : null,
	circleColor       : '#ff8000',
	
	direactionsColor  : '#ff8333',
	
	geoCoderZoom      : 16,
	
	gdir              :  null,
	locale            : "en_US",
	
	initMap: function()
	{
		var _d  = document.getElementById(this.mapDivId);
		if( _d )
		{
			if (GBrowserIsCompatible()) 
			{
				this.map = new GMap2( _d );
				this.map.setCenter(new GLatLng(37.4419, -122.1419), 1);	
				this.map.setUIToDefault();
				this.placeMarkers();
			}
		}
		this.initBaseIcon();
	},
	
	initBaseIcon: function()
	{
		this.baseIcon = new GIcon();
		this.baseIcon.shadow = "images/shadow50.png";
		this.baseIcon.iconSize = new GSize( 18, 34);
		this.baseIcon.shadowSize = new GSize( 37, 34 );
		this.baseIcon.iconAnchor = new GPoint( 9, 34 );
		this.baseIcon.infoWindowAnchor = new GPoint( 9, 2 );
		this.baseIcon.infoShadowAnchor = new GPoint( 18, 25 );
	},
	
	placeMarkers: function()
	{
		for(var u=0; this.objectsToPlace.length >u; u++)
		{
			var obj = this.objectsToPlace[u];
			this.placeMarker(obj.lat, obj._long, obj.hint, obj._id, obj._address);
		}	
		if(this.firstZoomObjectId)
		{
			this.zoomOnMarker(this.firstZoomObjectId, true);
		}
	},
	
	placeMarker: function(lat, _long, hint, _id, _address)
	{
		var point   = new GLatLng(lat, _long);
		var marker  = new GMarker(point);
		this.map.addOverlay(marker);
		
		marker.hint     = hint;
		marker._address = _address;
		GEvent.addListener( marker, 'click', this._onclickEvent );
		this.objectsMarkers[_id] = marker;
	},	
	
	_onclickEvent: function()
	{
		var marker = this;
		if( marker )
		{
			var tab1 = new GInfoWindowTab("", '<div id="wio-gmap-hint" style="height:100px;">' +  this.hint  + '<br>' + this._address +  '</div>' );
			var infoTabs = [ tab1 ];
			marker.openInfoWindowTabs( infoTabs );
		}
	},
	
	zoomOnMarker: function(_id, _skip)
	{
		//if(_id == this.firstZoomObjectId && !_skip) return;
		var _m = this.objectsMarkers[_id];
		if(_m)
		{
			var point = _m.getLatLng();
			this.map.setCenter(point, this.defaultMarkerZoom);
		}
		this.colorCell(_id);	
	},
	
	colorCell: function(_id)
	{
		var oldCell = document.getElementById(this.idCellTableBegin + this.firstZoomObjectId);
		if(oldCell)
		{
			oldCell.className = 'first odd';
		}
		var cell = document.getElementById(this.idCellTableBegin + _id);
		if(cell)
		{
			cell.className    = this.classCellSelected;
		}	
		this.firstZoomObjectId = _id;
	},
	
	eraseData: function()
	{
		this.updateValues();
		this.cancelClickEvent();
		var address = $(this.idAddress);
		if(address)
		{
			address.value = '';
		}	
	},
	
	submitErase: function()
	{
		var field = $(this.idActionField);
		if(field)
		{
			field.value = 'erase';
			var form = $(this.idForm);
			if(form)
			{
				form.submit();
			}
		}	
	},
	
	cancelSearch: function(_do_submit_erase)
	{
		if(_do_submit_erase)
		{
			this.submitErase();
			return;
		}
		var cancel = $(this.idCancelB);
		if(cancel)
		{
			cancel.style.display = 'none';
		}
		var start = $(this.idStartSearch);
		if(start)
		{
			start.style.display = 'block';
		}
		var firstb = $(this.idFirstBlock);
		if(firstb)
		{
			firstb.style.display = 'none';
		}
		var helpBox = $(this.idHelpBox);
		if(helpBox)
		{
			helpBox.style.display = 'none';
		}
		this.hideSecondBlock();
		this.eraseData();
		if(this.marker)this.map.removeOverlay(this.marker);
	},
	
	startSearch: function()
	{
		var cancel = $(this.idCancelB);
		if(cancel)
		{
			cancel.style.display = 'block';
		}
		var start = $(this.idStartSearch);
		if(start)
		{
			start.style.display = 'none';
		}
		var firstb = $(this.idFirstBlock);
		if(firstb)
		{
			firstb.style.display = 'block';
		}
	},
	
	showOnMap: function(EMPTY_ADDRESS_TEXT, NOT_FOUND_TEXT)
	{
		var addressEl = document.getElementById(this.idAddress);
		if(!addressEl) return;
		var geocoder  = new GClientGeocoder();
		var address   = addressEl.value;
		if(address == '')
		{
			alert( EMPTY_ADDRESS_TEXT );
			return;
		}
		function showAddress(address) 
		{
			geocoder.getLatLng
			(
				address,
				function(point) 
				{
					if (!point) 
					{
						alert(address + ' ' + NOT_FOUND_TEXT);
					} 
					else 
					{
						WIO_GMAP.map.setCenter(point, WIO_GMAP.geoCoderZoom);
						$(WIO_GMAP.idLat).value = '';
						WIO_GMAP.hideSecondBlock();
						if(WIO_GMAP.marker){WIO_GMAP.map.removeOverlay(WIO_GMAP.marker); WIO_GMAP.marker = false;};
						if(WIO_GMAP.circle)WIO_GMAP.circle.remove();
					}
				}
			);
	    }
	    this.showHelpBox();
		this.startClickEvent();    
		return showAddress(address);
	},
	
	__onclickEvent: function(overlay, point)
	{
		if(!overlay)
		{
			WIO_GMAP.placeMarkerOnMap(point);
		}
	},
	
	showSecondBlock: function()
	{
		var block = $(this.idSecondBlock);
		if(block)
		{
			if(block.style.display != 'block')
			{
				block.style.display = 'block';	
			}
		}
	},
	
	hideSecondBlock: function()
	{
		var block = $(this.idSecondBlock);
		if(block)
		{
			if(block.style.display != 'none')
			{
				block.style.display = 'none';	
			}
		}
	},
	
	placeDefMarker: function(_lat, _long, radius, _show_circle, _is_km)
	{
		if(!_lat || !_long || _long == '' || _lat == '') return;
		var point    = new GLatLng(_lat, _long);
		this.circle  = new CircleOverlay(point, radius, this.circleColor, 1, 1,  this.circleColor, 0.35, 60, this.map, true, _is_km);
		//this.map.addOverlay(this.circle);
		if(!_show_circle) this.hideCircle();
		this.placeMarkerOnMap(point);
		this.map.setCenter(point, this.circle.zoom);
		this.defaultMarkerZoom = this.circle.zoom;
	},
	
	clickShowCircleCheckbox: function(_show)
	{
		if(_show) this.showCircle();
		else this.hideCircle();
	},
	
	hideCircle: function()
	{
		if(this.circle) this.circle.hide();	
	},
	
	showCircle: function()
	{
		if(this.circle) this.circle.show();
	},
	
	placeMarkerOnMap: function(point)
	{
		if(!this.marker)
		{
			var icon    = new GIcon( this.baseIcon, this.customUserIcon );
			this.marker = new GMarker(point, {icon : icon, title: this.ME_ON_THE_MAP});
			this.marker.hint     = this.ME_ON_THE_MAP;
			this.marker._address = '';
			this.map.addOverlay(this.marker);
			GEvent.addListener( this.marker, 'click', this._onclickEvent );
		}
		else
		{
			this.marker.setLatLng(point);
		}
		this.showSecondBlock();
		this.updateValues(point);
	},
	
	updateValues: function(point)
	{
		var lat   = document.getElementById(this.idLat);
		var _long = document.getElementById(this.idLong);

		lat.value   = point ? point.lat() : '';
		_long.value = point ? point.lng() : '';
	},
	
	startClickEvent: function()
	{
		this.setDraggableCursor();
		this.cancelClickEvent();
		this.placeEvent    = GEvent.addListener( this.map, 'click', this.__onclickEvent );
	},
	
	cancelClickEvent: function()
	{
		if(WIO_GMAP.placeEvent)
		{
			GEvent.removeListener( this.placeEvent );
		}
	},
	
	showHelpBox: function()
	{
		var box = $(this.idHelpBox);
		if(box) box.style.display = 'block';
	},
	
	hideHelpBox: function()
	{
		var box = $(this.idHelpBox);
		if(box) box.style.display = 'none';
	},
	
	showDirections: function(marker_id)
	{
		this.clearDirection();
		var lat_from  = $(this.idLat).value;
		var long_from = $(this.idLong).value;
		var obj_to    = this.objectsMarkers[marker_id];
		if(lat_from != '' && long_from != '' && obj_to != '')
		{
			var arr     = [];
			arr.push([lat_from, long_from]);
			var coorObj = obj_to.getLatLng();
			arr.push(coorObj);
			this.gdir = new GDirections(this.map, $(this.idDirectionsPlace));
			$(this.idDirectionsPlace).innerHTML = '<img src="'+this.directionsPlaceImage+'" id="'+this.directionsPlaceImageId+'"></img>';
			$(this.idDirections).style.display  = 'block';
	        GEvent.addListener(this.gdir, "load", this.onGDirectionsLoad);
	        GEvent.addListener(this.gdir, "error", this.handleErrorsGDir);
	
	        this.setDirections(arr, this.locale);
	        this.colorCell(marker_id);
		}
	},
	
	setDirections: function(arr, _lang)
	{
		this.gdir.loadFromWaypoints(arr,
                { "locale": _lang });

	},
	
	onGDirectionsLoad: function()
	{
		$(WIO_GMAP.directionsPlaceImageId).parentNode.removeChild($(WIO_GMAP.directionsPlaceImageId));
		//var route = this.gdir.
	},
	
	handleErrorsGDir: function()
	{
		if (WIO_GMAP.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: " + WIO_GMAP.gdir.getStatus().code);
	   else if (WIO_GMAP.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: " + WIO_GMAP.gdir.getStatus().code);
	   
	   else if (WIO_GMAP.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: " + WIO_GMAP.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 (WIO_GMAP.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 (WIO_GMAP.gdir.getStatus().code == G_GEO_BAD_REQUEST)
	     alert("A directions request could not be successfully parsed.\n Error code: " + WIO_GMAP.gdir.getStatus().code);
	    
	   else alert("An unknown error occurred.");
	
	},
	
	clearDirection: function()
	{
		if(WIO_GMAP.gdir)
		{
			WIO_GMAP.gdir.clear();
		}	
		$(WIO_GMAP.idDirections).style.display = 'none';
	},
	
	setDefaultCursor: function()
	{
		this.map.getDragObject().setDraggableCursor( WIO_GMAP.defCursor );
	},

	setDraggableCursor: function()
	{
		this.map.getDragObject().setDraggableCursor( 'url("' + WIO_GMAP.cursorUrl + '"),' + WIO_GMAP.moveCursor );
	},
	
	formOnSubmit: function()
	{
		var el   = $(this.idSecondBlock);
		var val  = $(this.idLat).value
		if(el && val != '')
		{
			if(el.style.display == 'none')
			{
				return false;
			}
			else
			{
				return true;
			}
		}
		return false;
	}
}
