var map = null;
var mapView = VEMapStyle.Road;
var mapStyle;
var baseLayer = new VEShapeLayer();
var clusterLayer = new VEShapeLayer();
var zoomLimit = 3;
var zoomLevel = 3;
var startLat = 40.534265;
var startLong = -112.298452;
var map_data = "/_includes/map_data.php";
// size (in pixels) of the grid
var gridSize = 5;
// Limit the number of data descriptions that can be displayed in an infobox
var maxDiscription = 5;

var icons = null;
var autoPanMap = false;
var loadXML = true;
var legendVisible = true;
var map_menu_visible = true;
var legendClosedMargin = "-106px";

function GetMap(){
	if($("#propertyMap")){
		var ffv = 0;
		var ffn = "Firefox/"
		var ffp = navigator.userAgent.indexOf(ffn);
		if (ffp != -1) ffv = parseFloat(navigator.userAgent.substring(ffp + ffn.length));
		// If we're using Firefox 1.5 or above override 
		//the Virtual Earth drawing functions to use SVG
		if (ffv >= 1.5) {
			Msn.Drawing.Graphic.CreateGraphic=function(f,b){
				return new Msn.Drawing.SVGGraphic(f,b);
			}
		}
			
		map = new VEMap('propertyMap');
		map.SetDashboardSize(VEDashboardSize.Small);
		map.LoadMap(new VELatLong(startLat, startLong), zoomLevel , mapView ,false, VEMapMode.Mode2D, false);
		mapStyle = map.GetMapStyle();
		AddMyLayer(VEDataType.GeoRSS);
		
		// Events caught from map changes
		map.AttachEvent("onchangeview", bindMapClicks);
		map.AttachEvent("onresize", bindMapClicks);
		map.AttachEvent("onendzoom", bindMapClicks);
	}
}

function AddMyLayer(type){
	if(loadXML){		
		var veLayerSpec = new VEShapeSourceSpecification(type, map_data, baseLayer);
		map.ImportShapeLayerData(veLayerSpec, onFeedLoad, autoPanMap);
	}
}


function onFeedLoad(feed){
	var numShapes = feed.GetShapeCount();
	for(var i=0; i < numShapes; i++){
		var s = feed.GetShapeByIndex(i);
		s.SetCustomIcon(s.IconId);
	}
	mapZoomLevel = map.GetZoomLevel();
	if(mapZoomLevel > 13){
		map.SetZoomLevel(13);
	}
	bindMapClicks();
}

function bindMapClicks(){
	$(".map_icon_link").each(function(e){
		$(this).bind("click",function(c){
			window.location = "/property-detail/"+$(this).attr("id").replace("map_icon_link_","")+"/";
		});
	});
	$(".map_icon_region_link").each(function(e){
		$(this).bind("click",function(c){
			window.location = "/region-detail/"+$(this).attr("id").replace("map_icon_link_","")+"/";
		});
	});
}

function cluster(){
	// Check to see whether event is due to map style change
	if(mapStyle != map.GetMapStyle()){
		// Store the current map style
		mapStyle = map.GetMapStyle();
		return true;
	}
	
	// Remove all pins from the cluster layer
	clusterLayer.DeleteAllShapes(); 
	
	// Calculate the size, in pixels, of the map 
	var mapView = map.GetMapView();
	var bottomRight = map.LatLongToPixel(mapView.BottomRightLatLong);
	var mapWidth = parseInt(Math.ceil(bottomRight.x));
	var mapHeight = parseInt(Math.ceil(bottomRight.y));
	
	// Break the map up into a grid
	var numXCells = parseInt(Math.ceil(mapWidth / gridSize));
	var numYCells = parseInt(Math.ceil(mapHeight / gridSize));
	
	// Create an array to store all the grid data
	var gridCells = new Array(numXCells*numYCells);
	
	// Initialize the grid array with a structure to store all the data
	for(var i = 0; i < numXCells; i++){
		for(var j = 0; j < numYCells;j++){
			gridCells[i+j*numXCells]={latlong:new VELatLong(0,0), title:"", description:"", length:0};
		}
	}

	// Iterate through the shapes in the base layer
	for(var cnt = 0; cnt < baseLayer.GetShapeCount(); cnt++){
		// Convert the shapes latlong to a pixel location
		var shape = baseLayer.GetShapeByIndex(cnt);
		var latLong = (shape.GetPoints())[0];
		var pixel = map.LatLongToPixel(latLong);
		var xPixel = pixel.x;
		var yPixel = pixel.y;

		// Check to see whether the shape is within the bounds of the viewable map
		if(mapWidth >= xPixel && mapHeight >= yPixel && xPixel >= 0 && yPixel >= 0) {
			// Calculate the grid position on the map of where the shape is located
			var i = Math.floor(xPixel/gridSize);
			var j = Math.floor(yPixel/gridSize);
			
			// Calculate the grid location in the array
			var key = i+j*numXCells;
	
			// Define a standard way to display an individual shape 
			if(gridCells[key].length == 0){
				gridCells[key].latlong = latLong;
				gridCells[key].title = shape.GetTitle();
				gridCells[key].description = shape.GetDescription();
			}
	
			gridCells[key].length++;
	
			// Allow the contents of all the points in a grid to be 
			// displayed in the infobox of the shape if the user is zoomed 
			// into a predefined limt. This is done to prevent massive 
			// amounts of data from being displayed inside of the infobox.
			if(gridCells[key].length > 1 && map.GetZoomLevel() >= zoomLimit){
				if(gridCells[key].length == 2){
					gridCells[key].description = "<br /><strong>" + gridCells[key].title + 
					"</strong><br />" + gridCells[key].description + "<br /><hr />"; 
				}
			
				gridCells[key].title = "There are " + gridCells[key].length + " pins clustered here<br /><hr />";
				gridCells[key].description = gridCells[key].description +
				"<b>" + shape.GetTitle() + "</b><br />" + shape.GetDescription() + "<br /><hr />";
			}
		}
	}

	// Iterate through the clustered data in the grid array
	for(var key = 0; key < gridCells.length; key++){
		gridCells[key] = gridCells[key];
		// Set the default infobox message for clustered points that are zoomed out
		if((gridCells[key].length > 1 && map.GetZoomLevel() < zoomLimit) || gridCells[key].length > maxDiscription) {
			gridCells[key].title = "There are " + gridCells[key].length+ " pins clustered here";
			gridCells[key].description = "";
		}
		
		// Add a shape to the cluster layer
		if(gridCells[key].length > 0) {
			var clusterShape = new VEShape(VEShapeType.Pushpin, gridCells[key].latlong);
			clusterShape.SetTitle(gridCells[key].title);
			clusterShape.SetDescription(gridCells[key].description);
			
			if(gridCells[key].length == 1)
				clusterShape.SetCustomIcon("<img src=\'/_images/salt-pepper.gif\'/>");
			else
				clusterShape.SetCustomIcon("<img src=\'/_images/meat.gif\'/>");
		
			clusterLayer.AddShape(clusterShape);
		}
	}
}

$(document).ready(function(){
		GetMap();
		//customSelects();
	
		$("#avail_unit").bind("change",function(a){
				if($(this).val() == "sf"){
					$("#avail_num_sf").show();
					$("#avail_num_acres").hide();
					$("#avail_num_sf select.avail_num").removeAttr("disabled");
					$("#avail_num_acres select.avail_num").attr("disabled","disabled");
				} else {
					$("#avail_num_sf").hide();
					$("#avail_num_acres").show();
					$("#avail_num_sf select.avail_num").attr("disabled","disabled");
					$("#avail_num_acres select.avail_num").removeAttr("disabled");
				}
			});
	} // end function
); // end ready

function toggleLegend(inAdvMap){
	// over ride for adv map
	if(inAdvMap == 1) legendClosedMargin="-71px";
	
	var legendButton = $("#map_legend_button");
	legendButton.blur();
	if(legendVisible){
		$("#map_legend").animate({
				marginTop:legendClosedMargin
			}, "fast", null, function(){
					legendButton.html("Show Legend");
					legendButton.toggleClass("down");
					legendButton.toggleClass("up");
				});
		legendVisible = false;
	} else {
		$("#map_legend").animate({
				marginTop: "0px"
			}, "fast", null, function(){
					legendButton.html("Hide Legend");
					legendButton.toggleClass("down");
					legendButton.toggleClass("up");
				});
		legendVisible = true;
	}
	
	return false;
}

function toggleMapMenu(){
	var menuButton = $("#toggler");
	menuButton.blur();
	if(map_menu_visible){
		menuButton.addClass("hidden");
		$("#custom_map_search").animate({
				marginLeft:"-198px"
			}, "fast", null, function(){
					map_menu_visible = false;
					$("#custom_map_search_wrap").width("20px");
				});
		$(".fake_select_list:visible").each(function(v){
				$(this).parents(".fake_select").children("a.selected").click();
			});
	} else {
		menuButton.removeClass("hidden");
		$("#custom_map_search_wrap").width("218px");
		$("#custom_map_search").animate({
				marginLeft:"0px"
			}, "fast", null, function(){
					map_menu_visible = true;
				});
	}
	return false;
}

function setMapView(view){
	if(view == "road"){
		map.SetMapStyle(VEMapStyle.Road);
	}
	if(view == "aerial"){
		map.SetMapStyle(VEMapStyle.Aerial);
	}
	if(view == "hybrid"){
		map.SetMapStyle(VEMapStyle.Hybrid);
	}
	$("#map_style_buttons .selected").removeClass("selected");
	$("#map_style_"+view).addClass("selected");
	
	// update session so it sticks across pages
	var params = "action=updateMapView&view="+view;
	var ajax_options = {
		type: "POST",
		url: "/_javascript/fi_ajax.php",
		data: params
	};
	
	$.ajax(ajax_options);
	
	return false;
}


function updateStates(country, stateWrap, fake){
	fake = (fake) ? true : false;
	
	$("#state").attr("disabled","disabled");
	var params = "action=updateStates&country="+$(country).val();
	if(fake){
		params += "&fake";
	}
	var ajax_options = {
		type: "POST",
		url: "/_javascript/fi_ajax.php",
		data: params,
		success: function(r){
			$("#"+stateWrap).html(r);
			if(fake){
				theSelect = $("#state");
				$("a#selected_state").bind("click",function(c){
						$(this).blur();
						if($.browser.msie && $.browser.version < 7){
							$("#map_icon_options .isRelative").removeClass("isRelative");
						}
						if(!($(this).parents("div.fake_select").hasClass("isRelative"))){
							if($.browser.msie && $.browser.version < 7){
								// disable map icons
								hidePopups();
								$("#map_icon_options label").each(function(e){
										$(this).unbind("mouseenter");
									});
							}
							// close all others
							$(".fake_select_list:visible").each(function(f){
									$(this).hide();
									$(this).parents("div.fake_select").removeClass("isRelative");
								});
							// open this one
							$(this).parents("div.fake_select").addClass("isRelative");
							$(this).parents("div.fake_select").children("div.fake_select_list").show();
						} else {
							// close this one
							$(this).parents("div.fake_select").children("div.fake_select_list").hide();
							$(this).parents("div.fake_select").removeClass("isRelative");
							
							if($.browser.msie && $.browser.version < 7){
								// enable map icons
								$("#map_icon_options label").each(function(e){
										$(this).bind("mouseenter",function(e){
											showPopup($(this), $(this).attr("class"));
										});
									});
							}
						}
						return false;
					});
				
				$("#select_state a").bind("click",function(c){
						$(this).parents("div.fake_select").children("a.selected").html($(this).html());
						$("#state").val($(this).attr("rel"));
						if($(this).parents("#countryList").length == 1){
							updateStates($(this).parents("#countryList").children("select"),'stateList', true);
						}
						if($(this).parents("#stateList").length == 1){
							updateCities($(this).parents("#stateList").children("select"),'cityList',true);
						}
						$(this).parents("div.fake_select_list").toggle();
						$(".fake_selected").removeClass("fake_selected");
						$(this).addClass("fake_selected");
						return false;
					});
			}
			updateCities($("#state"), "cityList", fake);
		}
	};
	
	$.ajax(ajax_options);
}

function updateCities(state, cityWrap, fake){
	$("#city").attr("disabled","disabled");
	var params = "action=updateCities&state="+$(state).val()
	if(fake){
		params += "&fake=true";
	}
	var ajax_options = {
		type: "POST",
		url: "/_javascript/fi_ajax.php",
		data: params,
		success: function(r){
			$("#"+cityWrap).html(r);
			if(fake){
				$("a#selected_city").bind("click",function(c){
						$(this).blur();
						if($.browser.msie && $.browser.version < 7){
							$("#map_icon_options .isRelative").removeClass("isRelative");
						}
						if(!($(this).parents("div.fake_select").hasClass("isRelative"))){
							if($.browser.msie && $.browser.version < 7){
								// disable map icons
								hidePopups();
								$("#map_icon_options label").each(function(e){
										$(this).unbind("mouseenter");
									});
							}
							// close all others
							$(".fake_select_list:visible").each(function(f){
									$(this).hide();
									$(this).parents("div.fake_select").removeClass("isRelative");
								});
							// open this one
							$(this).parents("div.fake_select").addClass("isRelative");
							$(this).parents("div.fake_select").children("div.fake_select_list").show();
						} else {
							// close this one
							$(this).parents("div.fake_select").children("div.fake_select_list").hide();
							$(this).parents("div.fake_select").removeClass("isRelative");
							
							if($.browser.msie && $.browser.version < 7){
								// enable map icons
								$("#map_icon_options label").each(function(e){
										$(this).bind("mouseenter",function(e){
											showPopup($(this), $(this).attr("class"));
										});
									});
							}
						}
						return false;
					});
				
				
				$("#select_city a").bind("click",function(c){
					$(this).parents("div.fake_select").children("a.selected").html($(this).html());
					$("#city").val($(this).attr("rel"));
					if($(this).parents("#countryList").length == 1){
						updateStates($(this).parents("#countryList").children("select"),'stateList', true);
					}
					if($(this).parents("#stateList").length == 1){
						updateCities($(this).parents("#stateList").children("select"),'cityList',true);
					}
					$(this).parents("div.fake_select_list").toggle();
					$(".fake_selected").removeClass("fake_selected");
					$(this).addClass("fake_selected");
					return false;
				});
			}
		}
	};
	
	$.ajax(ajax_options);
}



/************************ CUSTOM CSS STYLED SELECT MENUS *************************/

function customSelects(){
	$("#propertyMapSearch select").each(function(e){
		var thisSelect = $(this);
		var newHTML = "<div class=\"fake_select\" id=\"fake_select_"+$(this).attr("id")+"\">\n";
		var firstVal = $(this).children("option:selected").attr("value");
		var firstText = $(this).children("option:selected").html();
		
		newHTML += "<a href=\"#\" class=\"selected first-item\" id=\"selected_"+$(this).attr("id")+"\">"+firstText+"</a>\n";
		newHTML += "<div class=\"fake_select_list\" id=\"select_"+$(this).attr("id")+"\" style=\"display:none;";
		var items = $(this).children("option").length;
		if($.browser.msie && $.browser.version < 7){
			if(items < 8){
				newHTML += "height:"+(items * 16)+"px";
			} else {
				newHTML += "height:120px";
			}
		}
		newHTML += "\">\n";
		newHTML += "<ul>\n";
		
		$(this).children("option").each(function(t){
				newHTML += "<li><a href=\"#\" rel=\""+(($(this).attr("value")) ? $(this).attr("value") : "")+"\"";
				if($(this).attr("value") == firstVal){
					newHTML += " class=\"fake_selected\"";
				}
				newHTML += ">"+$(this).html()+"</a></li>\n";
			});
		
		newHTML += "</ul>\n</div>";
		newHTML += "</div>\n";
		$(this).after(newHTML);
		
		//bind events
		$("a#selected_"+$(this).attr("id")).bind("click",function(c){
				$(this).blur();
				if($.browser.msie && $.browser.version < 7){
					$("#map_icon_options .isRelative").removeClass("isRelative");
				}
				if(!($(this).parents("div.fake_select").hasClass("isRelative"))){
					if($.browser.msie && $.browser.version < 7){
						// disable map icons
						hidePopups();
						$("#map_icon_options label").each(function(e){
								$(this).unbind("mouseenter");
							});
					}
					// close all others
					$(".fake_select_list:visible").each(function(f){
							$(this).hide();
							$(this).parents("div.fake_select").removeClass("isRelative");
						});
					// open this one
					$(this).parents("div.fake_select").addClass("isRelative");
					$(this).parents("div.fake_select").children("div.fake_select_list").show();
				} else {
					// close this one
					$(this).parents("div.fake_select").children("div.fake_select_list").hide();
					$(this).parents("div.fake_select").removeClass("isRelative");
					
					if($.browser.msie && $.browser.version < 7){
						// enable map icons
						$("#map_icon_options label").each(function(e){
								$(this).bind("mouseenter",function(e){
									showPopup($(this), $(this).attr("class"));
								});
							});
					}
				}
				return false;
			});

		$("#select_"+$(this).attr("id")+" a").bind("click",function(c){
				$(this).parents("div.fake_select").children("a.selected").html($(this).html());
				thisSelect.val($(this).attr("rel"));
				if($(this).parents("#countryList").length == 1){
					updateStates($(this).parents("#countryList").children("select"),'stateList', true);
				}
				if($(this).parents("#stateList").length == 1){
					updateCities($(this).parents("#stateList").children("select"),'cityList',true);
				}
				$(this).parents("div.fake_select_list").toggle();
				$(".fake_selected").removeClass("fake_selected");
				$(this).addClass("fake_selected");
				return false;
			});
		$(this).hide();
	});
}


  /*              				    												   */
 /************************ END CUSTOM CSS STYLED SELECT MENUS *************************/
/*									    											 */

