
//Marker lookups
var iconTitleLookup = new Object();
	iconTitleLookup['info'] = 'Information';
	iconTitleLookup['camera'] = 'Picture';
	iconTitleLookup['cycleshop'] = 'Cycle Shop or Hire';
	iconTitleLookup['food'] = 'Place to eat';
	iconTitleLookup['lodging'] = 'Lodging Accommodation';
	iconTitleLookup['picnic'] = 'Picnic Area';
	iconTitleLookup['postoffice'] = 'Post Office';
	iconTitleLookup['restrooms'] = 'Restrooms / Toilets';
	iconTitleLookup['store'] = 'Store / Shop';
	iconTitleLookup['tent'] = 'Campsite';
	iconTitleLookup['viewpoint'] = 'View Point';
	iconTitleLookup['warning'] = 'Warning';
	
var directionMarkerArray = new Array('DIR_N','DIR_NNE','DIR_NE','DIR_ENE','DIR_E','DIR_ESE','DIR_SE','DIR_SSE','DIR_S','DIR_SSW','DIR_SW','DIR_WSW','DIR_W','DIR_WNW','DIR_NW','DIR_NNW');
		
	for (direction in directionMarkerArray)
	{
		iconTitleLookup[directionMarkerArray[direction]] = 'Direction';
	}

function addMarkersToMap(map, markers, versionNumber, routeContainerKey) {
	
	for (var m = 0; m < markers.length; m++) {
		
		var marker = createMarker(new GLatLng(markers[m]["lat"], markers[m]["lng"]), 'test', getViewMarkerHTML(markers[m],versionNumber,routeContainerKey), markers[m]['type']);
		map.addOverlay(marker);
	
	}

}

function getViewMarkerHTML(marker, versionNumber,routeContainerKey) {
	
	var markerKeyLink = "'" + marker.key + "'";
	var iconSize = 30;

	//need to switch type in future
	var html = '<div style="width: 300px">';
	html += "<img style='float: left; margin-right: 5px; margin-bottom: 5px' src='/img/iconSet2/" + iconSize + "/" + marker.type + ".png' />";
	html += '<strong>' + iconTitleLookup[marker.type] + '</strong><br />';
		   
	switch(marker.type)
		{
		case "camera":
		  var imageLink = '/getmarkerimage?routeContainerKey=' + routeContainerKey + '&routeMarkerKey=' + marker.key + '&archiveVersion=' + versionNumber + '&decache=' + Math.floor(Math.random()*1001);
		  html += '<div style="height: 200px; width: 200px;"><img id="imageThumbnail" src="' + imageLink + '" /><br /></div>';
		  break; 
		default:
		   html += '<div><em>' + marker.description + '</em><br /></div>'; 
		}
	html += '</div>';
	return html;
}

function addSegmentsToMap(map, segments, lineStyle) {
	
	var bounds = new GLatLngBounds();
	var lineWeight = ((lineStyle == 'thin') ? 2 : (zoomWidthLookup()[map.getZoom()]-1));
	
	for(var l = 0; l < segments.length; l++) {
		
		//Ternary Condition
		var lineColour = ((lineStyle == 'thin') ? "navy" : segments[l]['colour']);
					
			var maxLatLngPoint = new GLatLng(segments[l]['maxLat'], segments[l]['maxLng']);
			bounds.extend(maxLatLngPoint)
			var minLatLngPoint = new GLatLng(segments[l]['minLat'], segments[l]['minLng']);
			bounds.extend(minLatLngPoint)
			
			var newPolyline = GPolyline.fromEncoded({
			    //color: segments[l]['colour'],
			    color: lineColour,
				weight: lineWeight,
			    //opacity: 0.4,
				opacity: 0.4,
			    points: segments[l]['encodedPoints'],
			    levels: segments[l]['encodedLevels'],
			    zoomFactor: 2,
			    numLevels: 18
				});
			
			map.addOverlay(newPolyline);
			
		}
		
	return bounds;
	
}

function createMarker(point,name,html,type) {
		
		if(type == undefined) 
			{
				type = 'bikeicon';
				var gIcon = new GIcon(G_DEFAULT_ICON);
				gIcon.image = '/img/marker_bikeicon.png';
				gIcon.iconSize = new GSize(30,26);
				gIcon.iconAnchor = new GPoint(7,26);
				gIcon.shadow = '/img/shadow-marker_bikeicon.png';
				gIcon.shadowSize = new GSize(44,26);
			}
		else
			{
				var size = "20";	
				var gIcon = new GIcon(G_DEFAULT_ICON);
				
				gIcon.image = '/img/iconSet2/' + size + '/' + type + '.png';
				gIcon.iconSize = new GSize(20,20);
				gIcon.iconAnchor = new GPoint(0,20);
				
				//Hide shadows for direction markers
				if (type.substring(0,3) == 'DIR')
				{
					gIcon.shadow = '';
				}
				else
				{
					gIcon.shadow = '/img/iconSet2/' + size + '/shadow.png';
					gIcon.shadowSize = new GSize(31,20);
				}
				
			}
		
		var gMarkerOptions = new Object();
		gMarkerOptions.icon = gIcon;
		
		var marker = new GMarker(point, gMarkerOptions);	
			
		GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowHtml(html);
		});
		
		return marker;
	}
	
function checkCookie()
	{
	username=getCookie('username');
	if (username!=null && username!="")
	  {
	  alert('Welcome again '+username+'!');
	  }
	  else 
	  {
	  username=prompt('Please enter your name:',"");
	  if (username!=null && username!="")
	    {
	    setCookie('username',username,365);
	    }
	  }
	}
	

function viewRoute(route, boundsLat, boundsLng, boundsZoom, routeContainerKey) {
	
	map.clearOverlays();
	map.setZoom(boundsZoom);
	var latLng = new GLatLng(boundsLat, boundsLng);
	map.panTo(latLng);
	
	loadSegmentBatch(route,'',1,1);
	
}

function loadSegmentBatch(route,minGeoHash,fetchDetails,fetchTags) {
	
	var maxFetch = 100;
	
	var ajaxRequestObject = {
		url: '/rpc?action=GetRouteSegmentsByIdentifier&arg0=' + encodeURIComponent(JSON.stringify(route)) + '&arg1=' + maxFetch + '&arg2=' + encodeURIComponent(JSON.stringify(minGeoHash)) + '&arg3=' + fetchDetails + '&arg4=' + fetchTags,
		type: 'GET',
		dataType: 'json',
		timeout: 10000,
		error: function(){
			//alert('Error');
		},
		success: function(response){
			
			//sDumper(response);
			
			handleSegmentCallBack(response.content.segmentArray);
			
			if(response.details != '')
			{
				handleDetailsCallBack(response.details);
			}
			
			if(response.tags != '')
			{
				handleTagsCallBack(response.tags);
			}
		
			if(response.content.segmentArray.length == maxFetch)
			{
				var nextGeoHash = response.content.segmentArray[maxFetch-1].geohash;
				//alert(nextGeoHash);
				loadSegmentBatch(route,nextGeoHash,0,0);
				
			}
			else
			{
				//$('#spaceused1').progressBar((progressBarCounter = 100));
				loadMarkerBatch(route,'');
			}
		
		}
	
	};
	
	
	$.ajax(ajaxRequestObject);
	
}


function loadMarkerBatch(route,minGeoHash,routeContainerKey) {
	
	//sDumper(route);
	
	var maxFetch = 100;
	
	//$('#spaceused1').progressBar((progressBarCounter += (29/maxFetch)));
	
	var ajaxRequestObject = {
		url: '/rpc?action=GetRouteMarkersByIdentifier&arg0=' + encodeURIComponent(JSON.stringify(route)) + '&arg1=' + maxFetch + '&arg2=' + encodeURIComponent(JSON.stringify(minGeoHash)),
		type: 'GET',
		dataType: 'json',
		timeout: 10000,
		error: function(){
			//alert('Error');
		},
		success: function(response){
	
			//sDumper(response);
	
			handleMarkerCallBack(response.content.markerArray, routeContainerKey);
		
			if(response.content.markerArray.length == maxFetch)
			{
				var nextGeoHash = response.content.markerArray[maxFetch-1].geohash;
				//alert(nextGeoHash);
				loadMarkerBatch(route,nextGeoHash);
				
			}
			else
			{
				//$('#spaceused1').progressBar((progressBarCounter = 100));
				onRouteLoadingComplete();
				
			}
		
		}
	
	};
	
	$.ajax(ajaxRequestObject);
	
}	

function saveMapSettingsCookie() {
	
	cookie.startLat = map.getCenter().lat();
	cookie.startLng = map.getCenter().lng();
	cookie.startZoom = map.getZoom();
	
	cookie.store(365);
	
}

function saveMapTypeCookie() {
	
	
	for (var i = 0; i < map.getMapTypes().length; i++) {
        if (map.getCurrentMapType() == map.getMapTypes()[i]) {
          cookie.startMapType = i;
        }
      } 
	  
	 cookie.store(365); 
	 
}

function zoomWidthLookup() {
	
	var zoomLineWidth = new Object();
	
	zoomLineWidth[15] = 6;
	zoomLineWidth[14] = 5;
	zoomLineWidth[13] = 5;
	zoomLineWidth[12] = 5;
	zoomLineWidth[11] = 5;
	zoomLineWidth[10] = 5;
	zoomLineWidth[9] = 4;
	zoomLineWidth[8] = 4;
	zoomLineWidth[7] = 3;
	zoomLineWidth[6] = 3;
	zoomLineWidth[5] = 2;
	zoomLineWidth[4] = 2;
	zoomLineWidth[3] = 2;
	
	return zoomLineWidth;
	
}

function GetInfoMarkers() {
	
	if (map.getInfoWindow().isHidden()) {
		
		var boundsBean=	{
		 "NELat" : map.getBounds().getNorthEast().lat(),
		 "NELng" : map.getBounds().getNorthEast().lng(),
		 "SWLat" : map.getBounds().getSouthWest().lat(),
		 "SWLng" : map.getBounds().getSouthWest().lng(),
		 "zoom" : map.getZoom()
	}
	
	var params = new Array('GetRouteInfoPoints');
	params.push(boundsBean);
	
	
		
		
		$.ajax({
			//url: '/rpc',
			//type: 'POST',
			url: '/rpc?action=GetRouteInfoPoints&arg0=' + encodeURIComponent(boundsBean['NELat']) + '&arg1=' + encodeURIComponent(boundsBean['NELng']) +'&arg2=' + encodeURIComponent(boundsBean['SWLat']) +'&arg3=' + encodeURIComponent(boundsBean['SWLng']) + '&arg4=' + boundsBean['zoom'],
			type: 'GET',
			dataType: 'json',
			timeout: 1000,
			error: function(){
				
			
			},
			success: function(response){
				
				//Remove current markers
				for(var m = 0; m < markerArray.length; m++)
				{
					map.removeOverlay(markerArray[m]);	
				}
				
				markerArray = new Array();
	
				var batch = [];
				for (var i = 0; i < response.length; i++) {
					
					var identifier = response[i]["identifier"];
					var boundsLat = response[i]["boundsLat"];
					var boundsLng = response[i]["boundsLng"];
					var boundsZoom = response[i]["boundsZoom"];
					var routeContainerKey = response[i]["routeContainerKey"];
					var routeKeyLink = "javascript:viewRoute('" + identifier + "'," + boundsLat + "," + boundsLng + "," + boundsZoom + ",'" + routeContainerKey + "')";
					
					var html = '<div style="height: 100px; width: 200px">';
					html += '<strong>' + response[i]["name"] + '</strong><br />';
					html += '<br /><a href="' + routeKeyLink + '">Highlight</a>'
					html += '| <a href="/routeinfo/' + identifier + '">Full Details</a>'
					html += '</div>';
						
					var marker = createMarker(new GLatLng(response[i]["lat"], response[i]["lon"]), "Number ", html );
					markerArray.push(marker);
					map.addOverlay(marker);
					
				}
			
			}
		});
		
		
		
		/*
		$.ajax({
			url: '/rpc',
			type: 'POST',
			data: JSON.stringify(params),
			dataType: 'json',
			timeout: 1000,
			error: function(){
				
			
			},
			success: function(response){
				
				//Remove current markers
				for(var m = 0; m < markerArray.length; m++)
				{
					map.removeOverlay(markerArray[m]);	
				}
				
				markerArray = new Array();
	
				var batch = [];
				for (var i = 0; i < response.length; i++) {
					
					var identifier = response[i]["identifier"];
					var boundsLat = response[i]["boundsLat"];
					var boundsLng = response[i]["boundsLng"];
					var boundsZoom = response[i]["boundsZoom"];
					var routeContainerKey = response[i]["routeContainerKey"];
					var routeKeyLink = "javascript:viewRoute('" + identifier + "'," + boundsLat + "," + boundsLng + "," + boundsZoom + ",'" + routeContainerKey + "')";
					
					var html = '<div style="height: 100px; width: 200px">';
					html += '<strong>' + response[i]["name"] + '</strong><br />';
					html += '<br /><a href="' + routeKeyLink + '">Highlight</a>'
					html += '| <a href="/routeinfo/' + identifier + '">Full Details</a>'
					html += '</div>';
						
					var marker = createMarker(new GLatLng(response[i]["lat"], response[i]["lon"]), "Number ", html );
					markerArray.push(marker);
					map.addOverlay(marker);
					
				}
			
			}
		});
		*/
		
	}
	
}



