var Map = new Object();
Map.balloonEnabled = true;
Map.balloonOpenEvent = "mouseover";
Map.controlDiv = '';
Map.directionsEnabled = false;
Map.urlParameters = '';
Map.url = '/ajax/getMap.php';
Map.GM;
Map.markers = {};
Map.zoom = 10;
Map.zoomAdjust = 0;
Map.gmarkers = [];
Map.gmarkerCount = 0;
Map.startLat = 33.5;
Map.startLon = -117.74;
Map.GMarkerManager;
Map.markerList = [];
Map.sideBarItems = [];
Map.snapToRoute = false;

//Adds a sidebar item for rendering sidebar later.
Map.addSideBarItem = function(name, id, html, sidebarMarker) {
	var labelID = sidebarMarker ? sidebarMarker : Number(id) + 1;
	Map.sideBarItems[id] = '<div class="mapLink" id="link'+id+'"><span class="label">'+labelID+'</span> <a href="#" on' + Map.balloonOpenEvent + '="javascript:Map.linkClicked(' + id + ')" onClick="">'
           + name + '</a><br>' + html + '</div>';
}

// A function to create the marker and set up the event window
Map.createMarker = function createMarker(point,html,icon) {
	var obj = new Object();

	if (icon && icon.length) {
		var iconObj = new GIcon();
//		var iconWidth = icon[2][0];
//		var iconHeight = icon[2][1];
		var iconWidth = 20;
		var iconHeight = 34;
//		iconObj.image = icon[0];
		iconObj.image = icon;
//		iconObj.iconSize = new GSize(icon[2][0],icon[2][1]);
		iconObj.iconSize = new GSize(iconWidth, iconHeight);
		iconObj.iconAnchor = new GPoint((iconWidth / 2), iconHeight);
		iconObj.infoWindowAnchor = new GPoint((iconWidth / 2),0);
		obj.icon = iconObj;
	}
	var marker = new GMarker(point, obj);
	var linkid = "link"+Map.gmarkerCount;
	if (this.directionsEnabled) {
		html += this.getDirectionsForm(point);
	}
	if (this.balloonEnabled) {
		GEvent.addListener(marker, Map.balloonOpenEvent, function() {
			marker.openInfoWindowHtml(html);
			lastlinkid=linkid;
		});
	}
	// save the info we need to use later for the side_bar
	Map.gmarkers[Map.gmarkerCount] = marker;
	Map.gmarkerCount++;
	return marker;
}

Map.getDirectionsForm = function(point) {
	var ptURL = point.toUrlValue();
	var html = '<div class="directionsForm">' + 
	           '<form action="http://maps.google.com/maps" method="get" onSubmit="Map.submitDirections(this)">' + 
						 'Directions: <input type="radio" name="dir" value="to" checked> <b>To here</b> <input type="radio" name="dir" value="from"> <b>From here</b><br>' + 
						 'Address: <input size="20" type="text" name="saddr" /><br>' + 
						 '<input class="button" type="submit" value="Get Directions" />' + 
						 '<input type="hidden" name="daddr" value="' + ptURL + '" />' + 
						 '</form>'
	           '</div>';
	return html;
}

Map.getGeocode = function(val) {
	var ajax  = new Ajax.Request(
		 this.url,
		 {
				method:     "post",
				parameters: Map.urlParameters,
				onSuccess:  Map.renderMap
		 }   
	);
}

Map.initialize = function(startDiv,mapType,mapOptions) {
	this.GM = new GMap2(document.getElementById(startDiv));
	//Set map type
	if (mapType) {
		this.GM.setMapType(mapType);
	}
	//Handle options
	if (mapOptions != "off") {
		if (!mapOptions) {
			this.GM.enableScrollWheelZoom();
			this.GM.addControl(new GLargeMapControl());
			this.GM.addControl(new GMapTypeControl());
		} else { //Control specific options
			for(i = 0; i < mapOptions.length; i++) {
				switch(mapOptions[i]) {
					case 'enableScrollWheelZoom' :
					  this.GM.enableScrollWheelZoom();
						break;
					case 'largeMapControl' : 
					  this.GM.addControl(new GLargeMapControl());
						break;
					case 'mapTypeControl' :
					  this.GM.addControl(new GMapTypeControl());
						break;
					case 'smallZoomControl' : 
					  this.GM.addControl(new GSmallZoomControl());
						break;
					case 'scaleControl' : 
					  this.GM.addControl(new GScaleControl());
						break;
				}
			}
		}
	}
	this.GM.setCenter(new GLatLng( this.startLat,this.startLon), this.zoom);
	this.GMarkerManager = new GMarkerManager(this.GM);
	if (this.snapToRoute) {
		GEvent.addListener(this.GM, 'click', SnapToRoute.mapClick);
  	GEvent.addListener(this.GM, 'mousemove', SnapToRoute.mouseMove);
		SnapToRoute.load()
	}
}

Map.linkClicked = function(i) {
	GEvent.trigger(Map.markerList[i], this.balloonOpenEvent);
}

Map.loadMarker = function(obj) { //type, latLon, name, html, icon, sidebar_html,iconImg) {
	if (!Map.markers[obj.type]) {
		Map.markers[obj.type] = new Array();
	}

	var dataArray = {};
	dataArray["lat"] = obj.lat;
	dataArray["lon"] = obj.lon;
	dataArray["html"] = obj.html;
	dataArray["icon"] = obj.icon;
	dataArray["name"] = obj.name;
	dataArray["sidebar_html"] = obj.sidebar_html;
	dataArray["iconImg"] = obj.iconImage;
	dataArray["sidebarMarker"] = obj.sidebarMarker;

	Map.markers[obj.type].push(dataArray);
}

Map.renderAllMarkers = function(type) {
	if (Map.markers[type]) {
		var bounds = new GLatLngBounds();
		for(i in Map.markers[type]) {
			var lat = parseFloat(Map.markers[type][i]["lat"]);
			var lon = parseFloat(Map.markers[type][i]["lon"]);
			if (lat && lon) {
				var point = new GLatLng(lat,lon);
				marker = this.createMarker(point, Map.markers[type][i]["html"], Map.markers[type][i]["iconImg"]);
				Map.markerList[i] = marker;
				//Assemble new marker for sidebar.
				Map.addSideBarItem(Map.markers[type][i]["name"], i, Map.markers[type][i]["sidebar_html"], Map.markers[type][i]["sidebarMarker"]);
				bounds.extend(marker.getPoint());
			}
		}
		this.GMarkerManager.addMarkers(Map.markerList, 3);
		this.GMarkerManager.refresh();
		var zoomLevel = Map.GM.getBoundsZoomLevel(bounds) + this.zoomAdjust;
		Map.GM.setZoom(zoomLevel);
	}
}

Map.renderMap = function(result) {
	if (result.responseText.length) { 
		document.getElementById(Map.targetDiv).innerHTML = result.responseText;
	}
}

Map.renderSetCenter = function(result) {
	if (result.responseText.length) {
		var latLon = result.responseText.split(',');
		var lon = latLon[0];
		var lat = latLon[1];
		Map.GM.setCenter(new GLatLng(lat, lon), 13);
	}
}

Map.renderSetMarker = function(result) {
	var list = result.responseText.split('<bubble>');
	var latLon = list[0].split(',');
	var lon = latLon[0];
	var lat = latLon[1];
	var html = list[1];

	var marker = new GMarker(new GLatLng(lat,lon));
	Map.GM.setCenter(new GLatLng(lat,lon),15);
	Map.GM.addOverlay(marker);
	if (html) {
		GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(html);});
		marker.openInfoWindowHtml(html);
	}
}

Map.renderSideBarItems = function(divID) {
	var html = '';
	for(i = 0; i < Map.sideBarItems.length; i++) {
		if (Map.sideBarItems[i]) {
			html += Map.sideBarItems[i];
		}
	}
	var el = null;
	if (el = document.getElementById(divID)) {
		el.innerHTML = html;
	}
}

Map.setCenter = function(val) {
	var urlParameters = "loc=" + encodeURI(val);
	var ajax  = new Ajax.Request(
		 this.url,
		 {
				method:     "post",
				parameters: urlParameters,
				onSuccess:  Map.renderSetCenter
		 } 
	);
}

Map.setMarker = function(val) {
	var urlParameters = "loc=" + encodeURI(val);
	var ajax  = new Ajax.Request(
		 this.url,
		 {
				method:     "post",
				parameters: urlParameters,
				onSuccess:  Map.renderSetMarker
		 } 
	);
}

Map.setMarkerList = function(area, type) {
	if (!type) {
		type = "RLS";
	}
	var urlParameters = "mode=list&loc=" + encodeURI(area) + "&propType=" + type;
	var ajax  = new Ajax.Request(
		 this.url,
		 {
				method:     "post",
				parameters: urlParameters,
				onSuccess:  Map.renderSetMarkerList
		 } 
	);
}

Map.setTargetDiv = function (div) {
	this.targetDiv = div;
}

Map.submitDirections = function (form) {
	var str = '';
	var dir = 'to';
	var pointOne = '';
	var PointTwo = '';
	for(i=0; i < form.dir.length; i++) {
		var radio = form.toFrom[i];
		if (radio.checked) {
			dir = radio.value; 
		}
	}
	form.dir.value = dir;
	form.saddr.value = (dir == "to") ? encodeURI(form.addr.value) : encodeURI(form.daddr.value);
	form.daddr.value = (dir == "to") ? encodeURI(form.ptURL.value) : encodeURI(form.addr.value);
}
