$(document).ready(function() 
{ 
	var mapDivs = $('body').find('div.google_map_container');
	if(mapDivs.length > 0) 
	{
		gmapFactory = new GmapFactory(mapDivs);
	}
});

GmapFactory = function GmapFactory(divs) 
{
	var mapContainer = [];
	
	for (var i = 0; i < divs.length; i++) 
	{
		mapContainer[i] = new GmapManager(divs[i]);
	}
}

GmapManager = function GmapManager(div) 
{
	this.div = div;
	this.postcode = this.getPostCode();
	this.mapType = this.getMapType();
	this.zoom = this.getZoomLevel();
	this.map;
	this.localSearch = new GlocalSearch();
	this.icon = new GIcon();
	this.icon.image = "http://www.google.com/mapfiles/marker.png";
	this.icon.shadow = "http://www.google.com/mapfiles/shadow50.png";
	this.icon.iconSize = new GSize(20, 34);
	this.icon.shadowSize = new GSize(37, 34);
	this.icon.iconAnchor = new GPoint(10, 34);
	
	this.createNewMap();
	this.usePointFromPostcodefunction();
}

GmapManager.prototype.getPostCode = function() 
{
	return $(this.div).find('input#google_map_post_code').val();
}

GmapManager.prototype.getMapType = function() 
{
	return $(this.div).find('input#google_map_post_type').val();
}

GmapManager.prototype.getZoomLevel = function() 
{
	var zoom = 15; //default
	
	if($(this.div).find('input#google_map_zoom_level').size() > 0) {
	
		val = parseInt($(this.div).find('input#google_map_zoom_level').val());
		
		if(!isNaN(val)) {
			zoom = val;
		}
	}
	
	return zoom;
}

GmapManager.prototype.createNewMap = function() 
{
	if (GBrowserIsCompatible()) {
		this.map = new GMap2(this.div);
		this.map.addControl(new GLargeMapControl());
		this.map.addControl(new GMapTypeControl());
	}
}

GmapManager.prototype.usePointFromPostcodefunction = function() 
{
	this.localSearch.setSearchCompleteCallback(this, 
		function() 
		{
			if (this.localSearch.results[0])
			{		
				var resultLat = this.localSearch.results[0].lat;
				var resultLng = this.localSearch.results[0].lng;
				var point = new GLatLng(resultLat,resultLng);
				this.placeMarkerAtPoint(point);
			}
			else
			{
				alert("Postcode not found!");
			}
		}
	);	
		
	this.localSearch.execute(this.postcode + ", UK");
}

GmapManager.prototype.placeMarkerAtPoint = function (point)
{
	var marker = new GMarker(point,this.icon);
	this.map.addOverlay(marker);
	this.setCenterToPoint(point);
}

GmapManager.prototype.setCenterToPoint = function (point)
{
	switch (this.mapType) 
	{
		case 'NORMAL':
			this.map.setCenter(point, this.zoom, G_NORMAL_MAP);
			break;
			
		case 'SATELLITE':
			this.map.setCenter(point, this.zoom, G_SATELLITE_MAP);
			break;
			
		case 'HYBRID':
			this.map.setCenter(point, this.zoom, G_HYBRID_MAP);
			break;
			
		default:
			this.map.setCenter(point, this.zoom, G_HYBRID_MAP);
			break;
	}
}
