/**
 * @author Serge
 */
$(function(){
	
	debug = function(msg) { $(".debug").append(msg+"<br>"); }


	// holds layers information
	// makes requests, handles responses to/from server
	mapCtrl = function () {
		
	}
	mapCtrl.prototype = {
		map : null,
		chx : null,
		layers : {},
		areas : {},
		homes : [],
		initCoords : {lat: 26.231895609983, lon: -81.8101651763916, zoom: 12},
		setChecks : function(checksObject) {
			this.chx = checksObject;
		},
		/* requests a bunch of info at once */
		initialRequest : function(data) {
			var beans = data;
			mc = this;
			$.post(document.location.pathname, {info : beans },function(data){
				var responseText = data;
				if (responseText){
					if (responseText.layers && responseText.layers.length) {
						for (var i in responseText.layers) {
							var next = (mc.layers[responseText.layers[i].area_id] && mc.layers[responseText.layers[i].area_id].length) ? mc.layers[responseText.layers[i].area_id].length : 0;
							if (next == 0) {
								mc.layers[responseText.layers[i].area_id] = [];
							}
							mc.layers[responseText.layers[i].area_id][next] = responseText.layers[i];
						}
					}
					if (responseText.homes && responseText.homes.length) {
						for (var i in responseText.homes) {
							if (responseText.homes[i].main) {
								mc.initCoords.lat = responseText.homes[i].lat;
								mc.initCoords.lon = responseText.homes[i].lon;
								mc.initCoords.zoom = parseInt(responseText.homes[i].zoom, 10);
							}
						}
						mc.homes = responseText.homes
					}
					if (responseText.lat && responseText.lon) {
						mc.initCoords.lat = responseText.lat;
						mc.initCoords.lon = responseText.lon;
					}

					mc.drawMap();
					mc.displayHomes();
					for (var i in mc.layers) {
						mc.areas[i] = {icon:responseText.area.icon,
								zoom:parseInt(responseText.area.zoom, 10), 
								lon:parseFloat(responseText.area.lon, 10), 
								lat:parseFloat(responseText.area.lat, 10)};
						mc.prepareLayer(i);
						mc.drawLayer(i);
						mc.chx.updateCheckbox(i);
					}
					//this.prepareLayer();
				}
			}, "json");
		},
		drawMap : function() {
			try {
		        if (GBrowserIsCompatible()) {
		        	this.map = new GMap2(document.getElementById("map_canvas"));
		        	this.map.setMapType(G_NORMAL_MAP);
					this.map.setUIToDefault();
					//this.map.setCenter(new GLatLng(26.1394892360259, 81.8001651763916), 14);
					this.map.setCenter(new GLatLng(this.initCoords.lat, this.initCoords.lon), this.initCoords.zoom);
		        }
			} catch (e) {
				// handling exceptions
				alert("some map error");
			}
		},
		displayHomes : function() {
			for (var i in this.homes) {
				var icon = new GIcon(G_DEFAULT_ICON);
				icon.image = "/img/icons/icon0.png"; 
				markerOptions = { icon:icon };
				if (this.homes[i].lat && this.homes[i].lon) {
					this.homes[i].marker = new GMarker(new GLatLng(this.homes[i].lat, this.homes[i].lon), markerOptions);
					this.map.addOverlay(this.homes[i].marker);
					(function (home) {
						GEvent.addListener(home.marker, "click", function() {
							home.marker.openInfoWindowHtml('<img width="165" height="104" src="/userfiles/homes/' + home.list_image + '">'+
							'<br>' + '<b>' + home.name + '</b>' + '<br>' + home.two_rows_description1 +
							'<br>' + home.two_rows_description2 + '<br>' +
							'<a href="/rental-properties/'+((home.url.length>0)?home.url:'home-'+home.id)+'/">details</a>'
							);
						});
					})(this.homes[i]);
					if (this.homes[i].main) { GEvent.trigger(this.homes[i].marker, "click"); }
				}
			}
		},
		displayLayer : function(id) {
			if (this.layers[id] && this.layers[id].length > 0) {
					this.drawLayer(id);
			} else {
				this.requestData(id);
			}
		},
		drawLayer : function(id) {
			// displaying markers prepared earlier
			for (var i in this.layers[id]) {
				this.map.addOverlay(this.layers[id][i].marker);
			}
			if (this.areas[id].zoom && this.areas[id].lat, this.areas[id].lon) {
				this.map.setCenter(new GLatLng(this.areas[id].lat, this.areas[id].lon), this.areas[id].zoom);
			}
		},
		prepareLayer : function(id) {
			// preparing markers
			for (var i in this.layers[id]){
				var icon = new GIcon(G_DEFAULT_ICON);
				icon.image = "/img/icons/icon"+mc.areas[id].icon+".png"; 
				markerOptions = { icon:icon };
				this.layers[id][i].marker = new GMarker(new GLatLng(this.layers[id][i].lat, this.layers[id][i].lon), markerOptions);
				(function (item) {
					GEvent.addListener(item.marker, "click", function() {
						item.marker.openInfoWindowHtml('<b>'+item.name+'</b><br>'+item.address+'<br>'+item.phone);
					});
				})(this.layers[id][i]);
			}
		},
		/* запрашивает один слой за запрос
		 * разница в том, что если бы мы все время пользовались большой запрашивалкой,
		 * то пришлось бы парсить каждый запрос и узнавать, что из этого уже есть, а чего нет
		 * а в initialRequest мы ничего не проверяем на существование. в его момент у нас ничего нет
		 */ 
		requestData : function(id) {
			mc = this;
			$.getJSON("?layer="+id, function(responseText) {
				if (responseText.layers && responseText.layers.length) {
					mc.layers[id] = [];
					for (var i in responseText.layers) {
						mc.layers[id][mc.layers[id].length] = responseText.layers[i]; }
				}
				mc.areas[id] = {icon:responseText.area.icon,
								zoom:parseInt(responseText.area.zoom, 10), 
								lon:parseFloat(responseText.area.lon, 10), 
								lat:parseFloat(responseText.area.lat, 10)};
				mc.prepareLayer(id);
				mc.drawLayer(id);
			});
		}, 
		hideLayer : function(id) {
			for (var i in this.layers[id]) {
				this.map.removeOverlay(this.layers[id][i].marker);
			}
		}
	};


	// DOES NOT parse query strings
	// handles checkboxes' events
	// updates address box
	function checks() {}
	checks.prototype = {
		mc: null, 
		checkboxes : null,
		rp: [],
		setMapController : function(mapController) {
			this.mc = mapController;
		},
		init : function() {
			//this.checkboxes = $(".legend input[type=checkbox]");
			this.mapChbxEvents();
			this.mc.initialRequest(this.parseHash());
		},
		parseHash : function() {
			params = document.location.hash;
			params = params.substr(params.indexOf("#")+1);
			return (params.length)?params:"empty";
		},
		mapChbxEvents : function() {
			chx = this;
			$(".legend input[type=checkbox]").bind("click", function(e) {
				var id = e.target.value;
				if (e.target.checked) {
					chx.mc.displayLayer(id);
				} else {
					chx.mc.hideLayer(id);
				}
			});
		},
		updateCheckbox : function(id) {
			var chkBox = $("#layer"+id);
			if (chkBox[0].checked) {
				$("#layer"+id).removeAttr("checked");
			} else {
				$("#layer"+id).attr("checked", "checked");
			}
		}
	};
	c = new checks();
	m = new mapCtrl()
	m.setChecks(c);
	c.setMapController(m);
	c.init();
});

