// JavaScript Document
// Places Browse By Map Class
//VARIABLE DECLARATIONS
var CITY_DEFAULT="Marquette";
var PLACE_TITLE_MAX_LENGTH=70;
var map;
var custommap
var markerManager;
var MapSettings = new Object();
var selectedPlaceId = "";
var selectedPlaceTitle = "";
var lastPlaceCount = 0;
var MaxPlaces = 150;
var colExistingMarkers;
var icoTemplate;
//var mapBounds = new GLatLngBounds(new GLatLng(44.9981,-90.4285),new GLatLng(48.012,-83.4367));
//MINOR FUNCTIONS

function mouseOverMarker(i)
{
	//Simulates a mouse over action on the map when the mouse is over the sidebar
	GEvent.trigger(gmarkers[i],"mouseover");
}
function mouseOutMarker(i)
{
	//Simulates a mouse over action on the map when the mouse is over the sidebar
	GEvent.trigger(gmarkers[i],"mouseout");
	document.getElementById("message_bar").innerHTML = '&nbsp;';
}
function myclick(i)
{
	GEvent.trigger(gmarkers[i],"click");
}
function Dictionary()
  {
	  this.count=0;
	  this.Obj=new Object();
	  this.exists=Dictionary_exists;
	  this.add=Dictionary_add;
	  this.getVal=Dictionary_getVal;
	  }
function Dictionary_exists(sKey)
  {
	  return(this.Obj[sKey])?true:false;
	  }
function Dictionary_add(sKey,aVal)
  {
	  var K=String(sKey);
	  if(this.exists(K))
	    return false;
	  this.Obj[K]=aVal;
	  this.count++;
	  return true;
	  }
function Dictionary_getVal(sKey)
  {
	  var K=String(sKey);
	  return this.Obj[K];
	  }
function SetIcons()
  {
	  icoTemplate=new GIcon();
	  icoTemplate.iconSize=new GSize(16,16);
	  icoTemplate.iconAnchor=new GPoint(8,16);
	  icoTemplate.infoWindowAnchor=new GPoint(17,0);
	  icoTemplate.transparent="/images/markers/Transparent.png";
	  icoTemplate.imageMap=[0,18,1,11,4,6,8,3,15,0,22,0,30,5,34,12,35,18,34,22,32,27,29,31,24,33,21,35,17,42,13,34,9,33,3,28,1,24];
	  }

//MAJOR FUNCTIONS

function createMarker(point,name,id,category,iconFileName)
{
	var markerIcon;
	markerIcon = new GIcon(icoTemplate,"/images/markers/"+iconFileName);
	//var markerIcon = new GIcon(G_DEFAULT_ICON);
	baseIcon = '/images/markers/'+iconFileName;
	selectedIcon = '/images/markers/selected-'+iconFileName;
	//markerIcon.image = 'http://maps.google.com/mapfiles/ms/icons/red-dot.png';
	markerIcon.image = baseIcon;
	if (category == 21)
	  {
		markerIcon.iconSize = new GSize(32, 32);
	    //markerIcon.shadow = '/images/markers/shadow-'+iconFileName;
  	    //markerIcon.shadowSize = new GSize(36, 24);  
	  }
	else
	  {
		markerIcon.iconSize = new GSize(20, 20);
	    markerIcon.shadow = '/images/markers/shadow-'+iconFileName;
  	    markerIcon.shadowSize = new GSize(30, 20);  
	  }
	
	markerOptions = { icon:markerIcon };
	var marker = new GMarker(point,markerIcon);
    // === Store the category and name info as a marker properties ===
    marker.mycategory = category;                                 
    marker.myname = name;
    GEvent.addListener(marker, "click", function() {selectedPlaceTitle = name;
													selectedPlaceId = id;
													ShowMarker(marker,id);});
	
    GEvent.addListener(marker, "mouseover", function() { marker.setImage('/images/markers/selected-'+iconFileName);
														 document.getElementById('placetitle').innerHTML = name;});
    GEvent.addListener(marker, "mouseout", function() { marker.setImage('/images/markers/'+iconFileName);
														document.getElementById('placetitle').innerHTML = selectedPlaceTitle;});
	GEvent.addListener(marker,'infowindowclose',function()
														   {
															   if(id==selectedPlaceId)
															   {
																   //$("#"+selectedTrailId).removeClass("trailSelected");
																   document.getElementById('placetitle').innerHTML='';
																   selectedPlaceId='';
																   selectedPlaceTitle='';
																   }});
	return marker;
}

function PopulatePlaces()
  {
	  var placeCount=0;
	  var mapId = 0;
	  var center=map.getCenter();
	  var bounds=map.getBounds();
	  var sw=bounds.getSouthWest();
	  var ne=bounds.getNorthEast();
	  var minLat=sw.lat();
	  var maxLat=ne.lat();
	  var minLon=sw.lng();
	  var maxLon=ne.lng();
	  var url='/Maps/KML/markers.cfm?minlat=' + minLat + '&minlon=' + minLon + '&maxlat=' + maxLat + '&maxlon=' + maxLon + '&mapId=' + MapSettings.placeFilter;
	  GDownloadUrl(url,function(data,response)
					     {
							 ClearInfo();
							 var xml=GXml.parse(data);
							 var markers=xml.documentElement.getElementsByTagName("marker");
							 placeCount=markers.length;
							 if(placeCount==0)
					   	      {
								  //SetStatus("There are 0 trails to display.");
								  //SetInstructions("To see trails on the map, use the <strong>- zoom</strong> navigation, located at the top left corner of the map.");
								  //ShowZoomAlert();
								  document.getElementById("status").innerHTML = "There are 0 places to that matched your filter";
								  lastPlaceCount=0;
								  //DisplayNumTrails(trailCount);
								  }
							 else if(placeCount<=MaxPlaces)
							   {
								   var url='/Maps/KML/markers.cfm?minlat=' + minLat + '&minlon=' + minLon + '&maxlat=' + maxLat + '&maxlon=' + maxLon + '&mapId=' + MapSettings.placeFilter;
								   //DisplayNumTrails(trailCount);
								   document.getElementById("zoommessage").innerHTML = '';
								   document.getElementById("status").innerHTML = '<span class="HeadingText">There are ' + placeCount + ' places in this area</span>';
								   getMarkers(url);
								   //ClearStatus();
								   if(lastPlaceCount>MaxPlaces)
								     {
										 markerManager.refresh();
										 }
								   lastPlaceCount=placeCount;
								  }
							 else
							   {
								   //DisplayNumTrails(0);
								   //SetStatus("We have "+placeCount+" trails in this area.");
								   //SetInstructions("To see trails on the map, use the <strong>+ zoom</strong> navigation, located at the top left corner of the map.");
								   //ShowZoomAlert();
								   document.getElementById("status").innerHTML = '<span class="HeadingText">There are <b>' + placeCount + '</b> places to in this area.</span>';
								   document.getElementById("zoommessage").innerHTML = '<span style="font-family:Arial, helvetica, sans serif;font-size:13px;">To see places on the map, use the + zoom navigation, located at the top left corner of the map, or unselect the types of places to be viewed on the map from the list below.</span>';
								   setTimeout('map.clearOverlays()',10);
								   lastPlaceCount=placeCount;
								   }});
	  MapSettings.lat=center.lat();
	  MapSettings.lon=center.lng();
	  MapSettings.zoom=map.getZoom();
	  updateSessionVars();
	  //document.getElementById("CenterPoint").innerHTML=MapSettings.lat+" x "+MapSettings.lon;
	  //document.getElementById("ZoomLevel").innerHTML=MapSettings.zoom;
	  //document.getElementById("existingTrailsLength").innerHTML=colExistingMarkers.count+" || gmarkerManagerCount: "+markerManager.getMarkerCount(1);
	  //document.getElementById("URL").innerHTML='<a href=\"http://www.dev.trails.com'+url+'\" target=\"_blank\">'+url+'</a>';document.getElementById("lat-spread").innerHTML=maxLat-minLat;
	  //document.getElementById("lon-spread").innerHTML=maxLon-minLon;
}


function Place()
  {
	  this.name='';
	  this.id='';
	  this.lat='';
	  this.lon='';
	  this.category='';
	  this.address='';
	  this.icon='';
	  //this.length='';
	  this.marker='';
	  }

function getMarkers(url)
  {
	  GDownloadUrl(url,function(data,responseCode)
								{
									var xml=GXml.parse(data);
									var markers=xml.documentElement.getElementsByTagName("marker");
									var arrViewablePlaces=Array();
									for(var i=0;i<markers.length;i++)
									{
										var place = new Place();
										place.id=markers[i].getAttribute("id");
										place.name=markers[i].getAttribute("name");
										place.category=markers[i].getAttribute("category");
										place.address=markers[i].getAttribute("address");
										place.icon=markers[i].getAttribute("icon");
										place.lat=parseFloat(markers[i].getAttribute("lat"));
										place.lon=parseFloat(markers[i].getAttribute("lng"));
										//trail.length=parseFloat(markers[i].getAttribute("length"));
										if(!colExistingMarkers.exists(place.id))
										  {
											  var point=new GLatLng(parseFloat(place.lat),parseFloat(place.lon));
											  //var marker=CreateMarker(point,place.name,place.id,place.iconFileName);
											  var html = '<b>'+place.name+'</b><br>'+place.address;
											  var marker=createMarker(point,place.name,place.id,place.category,place.icon)
											  place.marker=marker;
											  colExistingMarkers.add(place.id,marker);
											  markerManager.addMarker(marker,1);
											  }
										else
										  {
											  place.marker=colExistingMarkers.getVal(place.id);
											  }
										arrViewablePlaces.push(place);
									}
								    //arrViewableTrails.sort(sortFunction);
									for(i=0;i<arrViewablePlaces.length;i++)
									{
										CreateListEntry(arrViewablePlaces[i].name,arrViewablePlaces[i].id,arrViewablePlaces[i].category,i+1,arrViewablePlaces[i].icon,arrViewablePlaces[i].marker);
									}
								    //$(".trailSelected").next().addClass("selectedSibling");
								});
	  }

function loadPlaceMap()
{
	
	
	if (GBrowserIsCompatible())
	{
		
	    //Sys.Application.add_navigate(pageNavigate);
		map=new GMap2(document.getElementById("map"));
		map.addControl(new GScaleControl());
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		map.addControl(new GOverviewMapControl());
		map.addMapType(G_PHYSICAL_MAP);
		markerManager=new GMarkerManager(map);
		colExistingMarkers=new Dictionary();
	  if(window.location.href.indexOf('?')>0)
		{
			RestorePageState();
			}
	  else
	    map.setCenter(new GLatLng(MapSettings.lat,MapSettings.lon),MapSettings.zoom);
	  GEvent.addListener(map,"moveend",PopulatePlaces);
	  SetIcons();
	  PopulatePlaces();
	}
}
function RestorePageState()
{
	var strParams=window.location.href.substr(window.location.href.indexOf('?')+1,window.location.href.length);
	var arrParams=strParams.split("&");
	var lat,lon,zoom,mapType,placeFilter;
	if(arrParams.length!=5)
	{}
	else
	{
	    lat=arrParams[0].substr(arrParams[0].indexOf('=')+1,arrParams[0].length);
	    lon=arrParams[1].substr(arrParams[1].indexOf('=')+1,arrParams[1].length);
	    zoom=arrParams[2].substr(arrParams[2].indexOf('=')+1,arrParams[2].length);
	    mapType=arrParams[3].substr(arrParams[3].indexOf('=')+1,arrParams[3].length);
	    placeFilter=arrParams[4].substr(arrParams[4].indexOf('=')+1,arrParams[4].length);
	    ApplyMapSettings(lat,lon,zoom,mapType,placeFilter);
	}
}
function ApplyMapSettings(lat,lon,zoom,mapType,placeFilter)
{
	map.setCenter(new GLatLng(parseFloat(lat),parseFloat(lon)));
	map.setZoom(parseFloat(zoom));
	//SetMapType(mapType);
	//if(activityFilter.indexOf(',')>0)
	//{
		//document.getElementById(ddlActivityListID).selectedIndex=document.getElementById(ddlActivityListID).length;
		//}
	//else
	//{
		//for(var i=0;i<document.getElementById(ddlActivityListID).length;i++)
		//{
			//if(activityFilter==document.getElementById(ddlActivityListID).options[i].value)
			//{
				//document.getElementById(ddlActivityListID).selectedIndex=i;
				//}
			//}
		//}
	}
function CreateListEntry(title,id,category,listNumber,iconFileName,marker)
{
	var ol=document.getElementById("info");
	var li=document.createElement("li");
	var href=document.createElement("a");
	var span=document.createElement("span");
	var listTitle;
	var len
	listTitle=title
	span.appendChild(document.createTextNode(listTitle));
	href.appendChild(span);
	href.setAttribute("href","javascript:void(0);");
    href.onmouseover=function() {
		 							document.getElementById('placetitle').innerHTML = title;
									marker.setImage('/images/markers/selected-'+iconFileName);
	 								};
	href.onmouseout=function() {
									marker.setImage('/images/markers/'+iconFileName);
									document.getElementById('placetitle').innerHTML = selectedPlaceTitle;
									};
	href.onclick=function() {		selectedPlaceId = id;
									selectedPlaceTitle = title;
									setTimeout(function(){ShowMarker(marker,id);},1);
									};
	
	                         /*{
								 if(title.length>TRAIL_TITLE_MAX_LENGTH)
								 {
									 document.getElementById('trailTitle').innerHTML=title.substr(0,TRAIL_TITLE_MAX_LENGTH)+'...';
								 }
								 else
								 {
									 document.getElementById('trailTitle').innerHTML=title;
								 }
								 marker.setImage("/images/browseByMap/map-icons/"+iconFileName+"_on.png");};
								 href.onmouseout=function(){
									 if(selectedTrailTitle.length>TRAIL_TITLE_MAX_LENGTH)
									 {
										 document.getElementById('trailTitle').innerHTML=selectedTrailTitle.substr(0,TRAIL_TITLE_MAX_LENGTH)+'...';
										 }
									else
									{
										document.getElementById('trailTitle').innerHTML=selectedTrailTitle;
										}
									marker.setImage("/images/browseByMap/map-icons/"+iconFileName+".png");
									};
								href.onclick=function()
								{
									$("#"+selectedTrailId).removeClass("trailSelected");
									$("#"+id).addClass("trailSelected");
									if(title.length>TRAIL_TITLE_MAX_LENGTH)
									{
										document.getElementById('trailTitle').innerHTML=title.substr(0,TRAIL_TITLE_MAX_LENGTH)+'...';
										}
									else
									{
										document.getElementById('trailTitle').innerHTML=title;
										}
									selectedTrailId=id;
									selectedTrailTitle=title;
									AddHistoryPoint(id,marker.getLatLng().lat(),marker.getLatLng().lng(),MapSettings.zoom,MapSettings.mapType,MapSettings.activityFilter,title);
									setTimeout(function()
														{
															ShowMarker(marker,id);
															},1)
									};*/
	li.setAttribute("id",id);
	li.appendChild(href);
	ol.appendChild(li);
	/*if(listNumber==1)
	{
		$("#"+id).addClass("first");
		}
	if(id==selectedTrailId)
	{
		$("#"+id).addClass("trailSelected");
		}*/
}
function loadMapFilters()
{
	//var p = document.getElementById("mapid").value;
	document.forms[0].lat.value = MapSettings.lat;
	document.forms[0].lon.value = MapSettings.lon;
	document.forms[0].zoom.value = MapSettings.zoom;
	document.forms[0].maptype.value = MapSettings.mapType;
	//window.location.href='?lat=' + MapSettings.lat + '&lon=' + MapSettings.lon + '&zoom=' + MapSettings.zoom + '&maptype=' + MapSettings.mapType + '&mapid=' + p;
	
	return true;
}
function updateSessionVars()
{
	var ajaxurl = 'UpdateSessionVars.cfm?lat=' + MapSettings.lat + '&lon=' + MapSettings.lon + '&zoom=' + MapSettings.zoom + '&maptype=' + MapSettings.mapType;
	ajaxpage(ajaxurl,'session_update');
}
function ClearInfo(){document.getElementById("info").innerHTML="";}

function ShowMarker(marker,id)
{
	marker.openInfoWindowHtml("<div style='display:block;height:225px;width:300px;' id='bbmInfoWindow'><iframe width='300' height='225' scrolling='yes' src='infowindow.cfm?id="+id+"' frameborder='0' marginheight='0' marginwidth='0' id='trailBalloonFrame'></iframe></div>");
}

function loadTrailMap()
{
	var myCopyright = new GCopyrightCollection("COPY");
	myCopyright.addCopyright(new GCopyright('Demo', new GLatLngBounds(new GLatLng(-90,-180), new GLatLng(90,180)),0,'&copy;2007 Google'));
	
	//var tilelayer = new GTileLayer(myCopyright);
	//tilelayer.getTileUrl = getTileUrlSSide
	//tilelayer.isPng = function() {return true;};
	//tilelayer.getOpacity = function() {return 1.0; };
	var GMapTypeOptions = new Object();
    GMapTypeOptions.minResolution = 7;//9;
    GMapTypeOptions.maxResolution = 12;
	var tilelayers = new Array();
    tilelayers[0] = G_NORMAL_MAP.getTileLayers()[0];
    tilelayers[1] = new GTileLayer(myCopyright, 5, 12);
    tilelayers[1].getTileUrl = GetTileUrlSSide
    tilelayers[1].getOpacity = function () {return 1.0;};//of the non transparent part
    tilelayers[1].isPng = function() {return true;};
	
	custommap = new GMapType(tilelayers, new GMercatorProjection(22), "Snowmobile Trails",GMapTypeOptions);
	map.addMapType(custommap);
	map.removeControl(GSmallMapControl)
	//var myTileLayer = new GTileLayer(tilelayers);
	//map.addOverlay(myTileLayer);
}

function GetTileUrlSSide (a,b)
{
	//alert(b + "_" + a.y + "_" + a.x);
    //return "http://www.sledgps.com/sgmt.php?t=" + b + "_" + a.y + "_" + a.x;
	return "sgmt.cfm?t=" + b + "_" + a.y + "_" + a.x;
}
