var propertytype = 'own';
var hometypes = {};
var priceranges = {};
var scroll_per_point = 0;
var markers = [];
var assetlist = [[],[],[],[],[]];
var assetids = ["parks","education","transit","neighborhood","arts"];

var map;
// Create an array to contain the points of our polyline  
polylinePoints = [];

function startMap()
{  
    map.addTypeControl();     
    map.addZoomLong();
    map.removeZoomScale();            
    map.addPanControl();    

    if(gup('lat') != '' && gup('lon') != '')
    {         
	   initMapZoomandCenter(gup('lat'),gup('lon'));

	   if(gup('assettype') != '')
	   {
	   	cat = getAssetCat(gup('assettype'),gup('assettype'));
		marker = new YMarker(new YGeoPoint(parseFloat(gup('lat')),parseFloat(gup('lon'))), createCustomMarkerImage(cat));
		map.addOverlay(marker);
	   }

    }
    else
	    map.drawZoomAndCenter("Baltimore, MD", 6);  
}  

//Initialize Map with Incoming GEOCODE values
function initMapZoomandCenter(lat,lon)
{
	// Create a lat/lon object
	var myPoint = new YGeoPoint(lat,lon); 
  	// Display the map centered on a latitude and longitude 
	map.drawZoomAndCenter(myPoint, 3);		
}

//Get URL Parameters
function gup( name )
{  
	   var regexS = "[\\?&]"+name+"=([^&#]*)";  
	   var regex = new RegExp( regexS );  
	   var tmpURL = window.location.href;  
	   var results = regex.exec( tmpURL );  
	   if( results == null )    return "";  
	   else    return results[1];
}
  
Event.observe(window,"load",function() {
	map = new YMap(document.getElementById('map'));
	startMap();
	
	new Ajax.Request("http://www.livebaltimore.com/NeighborhoodSearch.cfm?action=getoptions&option=HousingPriceRangesRent", { evalJSON: "force", onComplete: function(response) {
		html = '';
		response.responseJSON.OPTIONS.each(function(el) {
			html += '<li><img src="http://www.livebaltimore.com/Common/Images/SevaCM/uncheck.png" alt="" name="' + el.IDCODEVALUE + '" class="price_range checkable" onclick="checkable(this)" /> ' + el.TXCODEDESCRIPTION + '</li>';		
		});
		priceranges.rent = html;
	}});
	
	new Ajax.Request("http://www.livebaltimore.com/NeighborhoodSearch.cfm?action=getoptions&option=HousingPriceRangesOwn", { evalJSON: "force", onComplete: function(response) {
		html = '';
		response.responseJSON.OPTIONS.each(function(el) {
			html += '<li><img src="http://www.livebaltimore.com/Common/Images/SevaCM/uncheck.png" alt="" name="' + el.IDCODEVALUE + '" class="price_range checkable" onclick="checkable(this)" /> ' + el.TXCODEDESCRIPTION + '</li>';		
		});
		priceranges.own = html;
		$("priceranges").innerHTML = priceranges.own;
	}});
	
	new Ajax.Request("http://www.livebaltimore.com/NeighborhoodSearch.cfm?action=getoptions&option=HousingTypesRent", { evalJSON: "force", onComplete: function(response) {
		html = '';
		response.responseJSON.OPTIONS.each(function(el) {
			html += '<li><img src="http://www.livebaltimore.com/Common/Images/SevaCM/uncheck.png" alt="" name="' + el.IDCODEVALUE + '" class="home_type checkable" onclick="checkable(this)" /> ' + el.TXCODEDESCRIPTION + '</li>';
		});
		hometypes.rent = html;
	}});
	
	new Ajax.Request("http://www.livebaltimore.com/NeighborhoodSearch.cfm?action=getoptions&option=HousingTypesOwn", { evalJSON: "force", onComplete: function(response) {
		html = '';
		response.responseJSON.OPTIONS.each(function(el) {
			if (el.TXCODEDESCRIPTION == "Single Family Detached Home")
				el.TXCODEDESCRIPTION = "Single Family Detached";
			html += '<li><img src="http://www.livebaltimore.com/Common/Images/SevaCM/uncheck.png" alt="" name="' + el.IDCODEVALUE + '" class="home_type checkable" onclick="checkable(this)" /> ' + el.TXCODEDESCRIPTION + '</li>';
		});
		hometypes.own = html;
		$("hometypes").innerHTML = hometypes.own;
		$("map_loading").hide();
	}});
	
	$$(".ptype").invoke("observe","click",function(ev) {
		el = ev.element();
		if (el.alt == "") {
			$$(".ptype").each(function(el) { el.src = el.src.gsub("-check","-uncheck"); el.alt = ""; });
			el.src = el.src.gsub("uncheck","check");
			el.alt = "checked";
			if (el.name == "own") {
				$("hometypes").innerHTML = hometypes.own;
				$("priceranges").innerHTML = priceranges.own;
				propertytype = 'own';
			} else {
				$("hometypes").innerHTML = hometypes.rent;
				$("priceranges").innerHTML = priceranges.rent;
				propertytype = 'rent';
			}

			$("map_results").innerHTML = '';
			
			markers.each(function(mlist) {
				if (mlist != undefined) 
					mlist.each(function(m) { 
						map.removeMarker(m.id); 
					}); 
			});
			
		}
	});
	
	$$("#map_pop_up img")[0].observe("click",function(ev) { ev.stop(); $("map_pop_up").hide(); });
	
	new Draggable("map_handle", { constraint: "horizontal", starteffect: function() { }, endeffect: function() { },
		onDrag: function(ev) {
			left = ev.element.style.left.substr(0,ev.element.style.left.length-2);
			scrollResults(left);
		},
		snap: function(x,y) {
			if (x < 0)
				newx = 0;
			else if (x > 590)
				newx = 590;
			else
				newx = x;
			return [newx,y];
    	}
	});
});

function checkable(el) {
	if (el.alt == "checked") {
		el.src = el.src.gsub("check","uncheck");
		el.alt = "";
	} else {
		el.src = el.src.gsub("uncheck","check");
		el.alt = "checked";
	}
	mapSearch();
}

function mapSearch() {
	markers.each(function(mlist) { 
		if (mlist != undefined)
			mlist.each(function(m) { 
				map.removeMarker(m.id); 
			}); 
	});
	assetlist = [[],[],[],[],[]];
	queries = "HousingTypes=";
	$$(".home_type").each(function(el) { if (el.alt == "checked") { queries += el.name + ","; } });
	queries = queries.substr(0,queries.length-1);
	queries += "&PriceRanges=";
	$$(".price_range").each(function(el) { if (el.alt == "checked") { queries += el.name + ","; } });
	queries = queries.substr(0,queries.length-1);
	queries += "&PropertyType=" + propertytype;
	
	new Ajax.Request("http://www.livebaltimore.com/NeighborhoodSearch.cfm?action=SearchByCriteria&option=JSON&idNS=0209E891-1372-1B6A-0D5850CCD4AFEC9C&" + queries, { evalJSON: "force", onComplete: function(response) {
		newresults = "<ul>";

		response.responseJSON.NEIGHBORHOODS.each(function(el) {
			newresults += '<li><img src="http://www.livebaltimore.com/Common/Images/SevaCM/check.png" alt="checked" name="' + el.NEIGHBORHOODID + '" class="checkable" onclick="resultCheckable(this)" /> ' + el.TITLE + '<br />' ;
	
			if(el.NEIGHBORHOODURL != '')
				newresults+= '<a href= "' + el.NEIGHBORHOODURL + '">' + '<img src="http://www.livebaltimore.com/Common/Images/SevaCM/map-read-more.png" alt="" class="map_readmore" />' + '</a>';

			else	
				newresults+='<img src="http://www.livebaltimore.com/Common/Images/SevaCM/map-read-more.png" alt="" class="map_readmore" />'

			newresults+= '<br /><a href="javascript:map.panToLatLon(new YGeoPoint(' + el.LATITUDE + ',' + el.LONGITUDE +'));"><img src="http://www.livebaltimore.com/Common/Images/SevaCM/recenter-map.png" alt="" class="map_recenter" name="' + el.LATITUDE + ',' + el.LONGITUDE + '" /></a></li>';
			geoPoint = new YGeoPoint(el.LATITUDE,el.LONGITUDE);
			marker = new YMarker(geoPoint,createCustomMarkerImage(3));
			YEvent.Capture(marker, EventsList.MouseClick, function(ev) {

				$$("#map_pop_up h3")[0].innerHTML = el.TITLE;				
				$$("#map_pop_up h4")[0].innerHTML = "Neighborhood";
				$$("#map_pop_up p")[0].innerHTML = "";
				$($(ev.thisObj.id).down("img").id).insert( { after: $("map_pop_up") });
				$("map_pop_up").show();
				map.panToLatLon(new YGeoPoint(el.LATITUDE,el.LONGITUDE));
			});	
			map.addOverlay(marker);
			assets = [];
			assets[0] = marker;
			el.ASSETS.each(function(as) {
				geoPoint = new YGeoPoint(as.LATITUDE,as.LONGITUDE);
				cat = getAssetCat(as.MAJORCATEGORY,as.MINORCATEGORY);
				marker = new YMarker(geoPoint, createCustomMarkerImage(cat));
				YEvent.Capture(marker, EventsList.MouseClick, function(ev) {
					$(ev.thisObj.id).style.zIndex = "888";
					$$("#map_pop_up h3")[0].innerHTML = as.NAME;
					$$("#map_pop_up h4")[0].innerHTML = as.MINORCATEGORY;
					$$("#map_pop_up p")[0].innerHTML = as.ADDRESS1 + "<br />" + as.CITY + ", " + as.STATE + " " + as.ZIP;
					if (as.WEBSITE)
						$$("#map_pop_up p")[0].innerHTML += '<br /><a href="' + as.WEBSITE + '">' + as.WEBSITE.sub("http://","") + '</a>';
					$($(ev.thisObj.id).down("img").id).insert( { after: $("map_pop_up") });
					$("map_pop_up").show();
					map.panToLatLon(new YGeoPoint(el.LATITUDE,el.LONGITUDE));
				});
				map.addOverlay(marker);
				assets[assets.length] = marker;

				if (cat != undefined)
					assetlist[cat][assetlist[cat].length] = marker;
				hide = false;
				$$(".asset").each(function(el) {
					if (el.name == cat && el.alt != "checked")
						hide = true;
				});
				if (hide)
					marker.hide();
			});
			markers[el.NEIGHBORHOODID] = assets;
		});

		newresults += "</ul>";
		$("map_results").innerHTML = newresults;
		setTimeout("updateScrollWidth()",500);
	}});
}

function updateScrollWidth() {
	dims = $$("#map_results ul")[0].getDimensions();
	w = dims.width - 700;
	scroll_per_point = w / 590;
	$("map_handle").style.left = "0px";
	$("map_result_constraint").scrollLeft = 0;
	$$(".map_recenter").invoke("observe","click",function(ev) {
		el = ev.element();
		coords = el.getAttribute("name").split(",");
		map.panToLatLon(new YGeoPoint(coords[0],coords[1]));
	});
}

function resultCheckable(el) {
	if (el.alt == "checked") {
	    el.alt = "";
	    el.src = "http://www.livebaltimore.com/Common/Images/SevaCM/uncheck.png";
	    markers[el.name].each(function(m) { m.communityhidden = true; m.hide(); });
	} else {
	    el.alt = "checked";
	    el.src = "http://www.livebaltimore.com/Common/Images/SevaCM/check.png";
	    markers[el.name].each(function(m) {
	    	if (!m.assethidden)
		    	m.unhide();
		    m.communityhidden = false;
	    });
	}
}

function assetCheckable(el) {
	if (el.alt == "checked") {
	    el.alt = "";
	    el.src = el.src.gsub("check","uncheck");
	    assetlist[el.name].each(function(m) { m.assethidden = true; m.hide(); });
	} else {
	    el.alt = "checked";
	    el.src = el.src.gsub("uncheck","check");
	    assetlist[el.name].each(function(m) { m.assethidden = false; if (!m.communityhidden) { m.unhide(); } });
	}
}

function scrollResults(x) {
	$("map_result_constraint").scrollLeft = Math.round(x * scroll_per_point);
}

function createCustomMarkerImage(type) {  
	var myImage = new YImage();
	myImage.src = 'http://www.livebaltimore.com/Common/Images/SevaCM/' + assetids[type] + "-map-icon.png";
	myImage.size = new YSize(63,54);  
	myImage.offsetSmartWindow = new YCoordPoint(0,0);  
	return myImage;   
}

function getAssetCat(type,mtype) {
	if (mtype == "Parks and Recreation")
		return 0;
	if (mtype == "Educational Resources")
		return 1;
	if (type == "Public Transit")
		return 2;
	if (type == "Neighborhood")
		return 3;
	if (mtype == "Arts and Culture")
		return 4;
}