// A Rectangle is a simple overlay that outlines a lat/lng bounds on the
// map. It has a border of the given weight and color and can optionally
// have a semi-transparent background color.

var style = [
  {
    featureType: "all",
    elementType: "geometry",
    stylers: [
      { saturation: -81 },
      { hue: "#ffaa00" }
    ]
  }
];

var styledMapOptions = {
    map: map,
    name: "Ye-Olde"
  }
      
var yeoldeMapType =  new google.maps.StyledMapType(style,styledMapOptions);
  
var map = new google.maps.Map(document.getElementById("map"), myOptions);
map.mapTypes.set('ye-olde', yeoldeMapType);
map.setMapTypeId('ye-olde');

var myOptions = {
      zoom: 8,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };

var infowindow = new google.maps.InfoWindow({content: "blah"});

var standardIcon = "pics/blue_marker.png";

var TotalMeasure = 0;
var Measure;
var title;
var title_div;

// hash table of markers
var markerHash = new Hash ();
var nonCourseMarkerArray = new Array;

var MarkerArrayLandmarks = null;

var next_sel_image = new Image();
next_sel_image.src="pics/next_sel.gif";
var prev_sel_image = new Image();
prev_sel_image.src="pics/prev_sel.gif";

var next_image = new Image();
next_image.src="pics/next.gif";
var prev_image = new Image();
prev_image.src="pics/prev.gif";

var first_sel_image = new Image();
first_sel_image.src="pics/first_sel.png";
var last_sel_image = new Image();
last_sel_image.src="pics/last_sel.png";

var first_image = new Image();
first_image.src="pics/first.png";
var last_image = new Image();
last_image.src="pics/last.png";

function toggleNonCourseMarkers ()
{
	for (var i = 0; i < nonCourseMarkerArray.length; i++) 
	{
		var currentMarker = nonCourseMarkerArray[i];
		if (currentMarker.map == null)
			currentMarker.setMap (map);
		else
			currentMarker.setMap(null);
	}
}

function centerAndZoom (CenterLat, CenterLng)
{
	var CenterPoint = new google.maps.LatLng (CenterLat, CenterLng);
	map.setCenter(CenterPoint);
	map.setZoom (9);
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/; domain=cannonade.net;";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function HandleClick (id)
{

	if (!markerHash.has(id))
	{
		alert ('Failed to find marker');
		return;
	}

	var marker = markerHash.get(id);

	// trigger the click event for the marke
	google.maps.event.trigger(marker,'click');
}

function HandleOver (id) 
{
	var button = document.getElementById(id);

	if (id == 'next')
		button.src= next_sel_image.src;
	if (id == 'prev')
		button.src= prev_sel_image.src;
	if (id == 'first')
		button.src= first_sel_image.src;
	if (id == 'last')
		button.src= last_sel_image.src;
}

function HandleLeave (id) 
{
	var button = document.getElementById(id);

	if (id == 'next')
		button.src= next_image.src;
	if (id == 'prev')
		button.src= prev_image.src;
	if (id == 'first')
		button.src= first_image.src;
	if (id == 'last')
		button.src= last_image.src;
}

function get_flags (text)
{
	text = text.toLowerCase();
	var result = "<p>";
	for (var i = 0; i < text.length; i++)
	{
		if (text[i] == ' ')
		{
			result = result + "<img height=\"16\" width=\"16\" src=\"pics/space.png\">";
		}

		if ((text[i] >= 'a' && text[i] <= 'z') || (text[i] >= 'A' && text[i] <= 'Z') || (text[i] >= '0' && text[i] <= '9'))
		{
			result = result + "<img height=\"16\" width=\"16\" src=\"pics/" + text[i] + "-flag.png\">";
		}
	}
	result = result + "</p>";
	return result;
}

function fmt_point (point, compass)
{
	// Convert to Degree Minutes Seconds Representation
    PointDeg = Math.floor(point);
    PointMin = Math.floor((point-PointDeg)*60);
    PointSec =  Math.floor((Math.round((((point - PointDeg) - (PointMin/60)) * 60 * 60) * 100) / 100 ) );

	if (PointSec == 60)
	{
		PointMin = PointMin + 1;
		PointSec = 0;
	}

	if (PointMin == 60)
	{
		PointDeg = PointDeg + 1;
		PointMin = 0;
	}

	if (PointMin > 0 && PointSec > 0)
	{
		results = PointDeg + '&deg; ' + PointMin + '\' ' + PointSec + '" ' + compass;
	}
	else if (PointMin > 0)
	{
		results = PointDeg + '&deg; ' + PointMin + '\' ' + compass;
	}
	else
	{
		results = PointDeg + '&deg; ' + compass;
	}

	return results;
}

function fmt_lat (lat)
{
	var results;

	var compass = 'test';

	if (lat >= 0)
	{
		compass = 'East';
	}
	else
	{
		compass = 'West';
	}

	lat = Math.abs (lat);

	return fmt_point (lat , compass);
}

function fmt_lng (lng)
{
	var results;

	var compass = 'test';

	if (lng >= 0)
	{
		compass = 'North';
	}
	else
	{
		compass = 'South';
	}

	lng = Math.abs (lng);

	return fmt_point (lng , compass);
}

function fmt(num, dp) {
  var exp = Math.pow(10, dp);
  return  Math.round(num * exp) / exp;
}

/* Convert degress to radians */
function deg2rad(deg) {
  return deg / (180 / Math.PI);
}

/* Calculate distance between two points */
function point_distance(a, b) {
  var r = 6378700;
  var lat1 = a.lat();
  var lat2 = b.lat();
  var lon1 = a.lng();
  var lon2 = b.lng();
  var dist = r * Math.acos(Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + 
			   Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * 
			   Math.cos(deg2rad(lon1 - lon2)));
  return dist;
}

function load (id)
{
	var str = window.location.search;
	delim = str.indexOf("?");
	if (delim >= 0)
	{
		var keyword = str.substring(delim + 1, str.length);
		var ParamsArray = keyword.split('&');
		if (ParamsArray.length == 1)
		{
			reload (keyword, '');
			return;
		}

		reload (ParamsArray[0], id);
	}
	else
	{
		reload ('Master_and_Commander', '');
	}
} 

function reload (filter_book, id)
{
	var highlight_id = id;
	function createMarkerHTML (point, infoTitle, infoIndex, infoBook, infoCourse, quote, desc, image, image_link, prev_link, next_link, credit, icon_image, icon_shadow, current_book, id) 
	{
		var iwstyle = document.createElement("div");
		iwstyle.setAttribute ('class', 'iwstyle');

		var html = "<div class=\"bookName\">" + current_book + "</div>"

		new_title = "<a href=\"http://www.cannonade.net/map.php?" + infoBook + "&id=" + id + "\">" + infoTitle + "</a>" 

		html = html + new_title + get_flags (infoTitle) + "<p>" + fmt_lng (point.lat()) + " - " + fmt_lat (point.lng()) + "</p>";

		if (credit && credit.length > 0)
		{
			html = html + "<p><a href=\"credits.php\">" + credit + "</a></p>";
		}

		if (quote && quote.length > 0 && desc && desc.length > 0) 
		{
			 html = html + "<p>" + desc + "</p><p style=\"font-style : italic;\">" + quote + "</p>";
		}
		else if (desc && desc.length > 0)
		{
			html = html+ " <p>" + desc + "</p>";
		} else if (quote && quote.length > 0)
		{
			html = html + "<p style=\"font-style : italic;\">" + quote + "</p>";
		}

		if (image && image.length > 0)
		{
			/*
			if (image_link && image_link.length > 0)
				html = html + "<a onclick='Slimbox.open(\""+image_link+"\", \""+infoTitle+"\");return false' rel=\"lightbox\" href=\""+image_link+"\"><img height=\"112\" class=\"iwthumb\" border=\"0\" src=\"" + image + "\"/></a>";
			else
				html = html + "<img height=\"112\" class=\"iwthumb\" border=\"0\" src=\"" + image + "\"/>";
			*/
			html = html + "<img class=\"iwthumb\" height=\"112\" src=\"" + image + "\"/>";
		}

		html = html + "<div class=\"iwnavigate\">";
		html = html + prev_link;
 		html = html + "<img height=\"24\" onClick=\"centerAndZoom("+ point.lat() + ","+ point.lng() +")\" style=\"text-align: center; padding-left:20px; padding-right:20px; cursor: pointer\" src=\"pics/magnify_glass_small.png\">";
		html = html + next_link;
		html = html + "</div>";
			
		iwstyle.innerHTML = html;
		return iwstyle;
	}

	// Creates a marker whose info window displays the given number
	function createMarker(point, infoTitle, infoIndex, infoBook, infoCourse, quote, desc, image, image_link, prev_link, next_link, credit, icon_image, icon_shadow, current_book, id) 
	{
		var marker = new google.maps.Marker({
			position: point,
			map: map,
			title: infoTitle,
			icon: new google.maps.MarkerImage ((icon_image ? icon_image : "pics/blue_marker.png"),
new google.maps.Size(12, 20))});

		// add this marker to the hash
		markerHash.set (id, marker);
		if (infoCourse == "2")
			nonCourseMarkerArray.push(marker);

		var content = createMarkerHTML (point, infoTitle, infoIndex, infoBook, infoCourse, quote, desc, image, image_link, prev_link, next_link, credit, icon_image, icon_shadow, current_book, id); 

		google.maps.event.addListener(marker, 'click', function() {
			infowindow.close ();
			infowindow.setContent(content); 
			infowindow.open(map,marker);
		});

		if (id == highlight_id)
			google.maps.event.trigger(marker,'click');

		//if (id == highlight_id)
		//	setTimeout(function() { HandleClick (id), }, 3000);
	}


	var url = "";
	if (filter_book == "Lissuns")
		url = "xml/" + filter_book + ".php";
	else
		url = "export.php?type=json&map_name=" + filter_book;
	
	var req = new Request({
            method: 'get',
            url: url,
            onRequest: function() { },
            onComplete: function(resp) {

			var response = eval ('('+resp+')');

	if (response)
	{
		var current_book = "";
		var titleElements = response.markers[0];
		if (titleElements)
		{
			Measure = titleElements.Measure;
			TotalMeasure = 0;
			Title = titleElements.Title;
			title_div = document.getElementById("current_text")
				
			title_div.innerHTML = Title;

			var Zoom = titleElements.Zoom;
			var CenterLng = titleElements.CenterLng;
			var CenterLat = titleElements.CenterLat;

			if (Zoom && CenterLat && CenterLng)
			{
				var CenterPoint = new google.maps.LatLng (parseFloat(CenterLat), parseFloat(CenterLng));
				map.setCenter(CenterPoint);
				map.setZoom (parseInt(Zoom));

			}
			else
			{
				map.setCenter( new google.maps.latlng (parseFloat(5) , parseFloat (40)));
				map.setZoom (11);
			}
		}
		else
		{
			document.getElementById("title").innerHTML = "The Voyages of Jack Aubrey and Steven Maturin";
		}

		var polyline_points = new Array;
		var points = new Array(response.markers.length);
		var link_array_course = new Array;
		var link_array_landmarks = new Array;

		for (var i = 1; i < response.markers.length; i++) 
		{
			var current_desc = response.markers[i].desc;
			var current_quote = response.markers[i].quote;
			var current_title = response.markers[i].title;
			var current_course = response.markers[i].course;

			var lng = response.markers[i].lng;
			var lat = response.markers[i].lat;
			var id = response.markers[i].id;

			if ((current_desc && current_desc.length > 0)  || (current_quote && current_quote.length > 0))
			{
				if (current_course == "2")
					link_array_landmarks.push ("onClick=\"HandleClick('"+id+"')\"");
				else
					link_array_course.push ("onClick=\"HandleClick('"+id+"')\"");
			}
		}

		var indexCourse = 0;
		var indexLandmark = 0;

		for (var i = 1; i < response.markers.length; i++) 
		{
			// first tab
			var current_image = response.markers[i].image;
			var current_image_link = response.markers[i].image_link;

			// second tab
			var current_image2 = response.markers[i].image2;
			var current_image_link2 = response.markers[i].image_link2;

			var credit = response.markers[i].credit;
			var current_title = response.markers[i].title;

			// first tab
			var current_desc = response.markers[i].desc;
			var current_quote = response.markers[i].quote;

			// second tab
			var current_desc2 = response.markers[i].desc2;
			var current_quote2 = response.markers[i].quote2;

			var current_icon_image = response.markers[i].icon_image;
			var current_icon_shadow = response.markers[i].icon_shadow;
			var course = response.markers[i].course;
			var color = response.markers[i].color;
			var legend_name = response.markers[i].legend_name;
			var ignore_distance = response.markers[i].ignore_distance;
			var id = response.markers[i].id;

			book = response.markers[i].book;
			if (book && book.length > 0)
				current_book = book;

			points[i] = new google.maps.LatLng(parseFloat(response.markers[i].lat), parseFloat(response.markers[i].lng));

			if (course == null)
			{
				polyline_points.push(points[i]);
			}
			else if (course == "1")
			{
				// start a line
				polyline_points = new Array;
				polyline_points.push(points[i]);
			} else if (course == "0")
			{
				polyline_points.push(points[i]);
				// end a line
				if (polyline_points.length > 0)
				{
					var legend_ul = document.getElementById("legend");
					if (legend_name && legend_name.length > 0)
					{
						var item_div = document.createElement("li");
						var item_link = document.createElement("a");

						item_link.style.color = color;
						// item_div.style.color = "#F7F7F2";
						item_link.setAttribute ('href', "http://www.cannonade.net/map.php?" + filter_book + "&id=" + id);
						item_link.innerHTML += legend_name;

						item_div.appendChild (item_link);
						legend_ul.appendChild (item_div);
					}

					// add the polyline
					var polyline = new google.maps.Polyline({
						  path: polyline_points,
						  strokeColor: color,
						  strokeOpacity: 1.0,
						  strokeWeight: 2
						});
					 
				   polyline.setMap(map);

					if (Measure && Measure == 'true') 
					{
						// increment Measure by the length of the polylines

						var CurrentMeasure = 0;

						for (j = 0; j < polyline_points.length; j++)
						{
							if (!j)
								continue;

							CurrentMeasure = CurrentMeasure + (point_distance (polyline_points[j-1], polyline_points[j]) * 0.000539956803);
						}

						if (ignore_distance != "1" && !isNaN (CurrentMeasure))
							TotalMeasure = TotalMeasure + CurrentMeasure;
						//else
						//	alert (indexCourse);

						title_div.innerHTML = Title + " (" + Math.round(TotalMeasure) + " Nautical Miles)";
					}
				}
			} 
			else if (course == "2")
			{
				// no line
			}

			if ((current_desc && current_desc.length > 0) || 
				(current_quote && current_quote.length > 0) ||
				(current_quote2 && current_quote2.length > 0) ||
				(current_desc2 && current_desc2.length > 0))
			{
				if (!current_title || current_title.length <= 0)
					current_title = filter_book;

				// first
				var prev_link = "<img height=\"25\" src=\"pics/prev_disable.gif\">";
				// last
				var next_link = "<img height=\"25\" src=\"pics/next_disable.gif\">";
				// add the overlay marker (do tabbed marker if specified).
				
				var CurrentMarkerArray;

				var infoIndex;
				var infoTitle;
				var infoCourse;
				var infoBook;

				if (course == "2")
				{
					infoTitle= current_title;
					infoIndex = indexLandmark;
					infoBook = filter_book;
					infoCourse = course;

					if (indexLandmark)
					{
						// prev
						prev_link = "<img height=\"25\" id=\"first\" style=\"cursor:pointer;\" onMouseOver=\"HandleOver('first');\" onmouseout=\"HandleLeave('first');\" style=\"cursor:pointer;\" src=\"pics/first.png\" " + link_array_course [0] + ">" + "<img height=\"25\" id=\"prev\" style=\"cursor:pointer;\" onMouseOver=\"HandleOver('prev');\" onmouseout=\"HandleLeave('prev');\" style=\"cursor:pointer\" src=\"pics/prev.gif\" " + link_array_landmarks [indexLandmark - 1] + ">";
					}

					if (indexLandmark < link_array_landmarks.length - 1)
					{
						// next
						next_link = "<img height=\"25\" id=\"next\" onMouseOver=\"HandleOver('next');\" onmouseout=\"HandleLeave('next');\" style=\"cursor:pointer;\" src=\"pics/next.gif\" " + link_array_landmarks [indexLandmark + 1] + ">" + "<img height=\"25\" id=\"last\" onMouseOver=\"HandleOver('last');\" onmouseout=\"HandleLeave('last');\" style=\"cursor:pointer;\" src=\"pics/last.png\" " + link_array_landmarks [link_array_landmarks.length - 1] + ">";
					}

					if (!indexLandmark)
					{
						// link it to the last course point
						prev_link = "<img height=\"25\" id=\"first\" style=\"cursor:pointer;\" onMouseOver=\"HandleOver('first');\" onmouseout=\"HandleLeave('first');\" style=\"cursor:pointer;\" src=\"pics/first.png\" " + link_array_course [0] + ">" + "<img height=\"25\" id=\"prev\" style=\"cursor:pointer;\" onMouseOver=\"HandleOver('prev');\" onmouseout=\"HandleLeave('prev');\" style=\"cursor:pointer\" src=\"pics/prev.gif\" " + link_array_course [link_array_course.length - 1] + ">";
					}

					CurrentMarkerArray = MarkerArrayLandmarks;
					indexLandmark = indexLandmark + 1;
				}
				else
				{
					infoTitle= current_title;
					infoIndex = indexCourse;
					infoBook = filter_book;
					infoCourse = course;

					if (indexCourse)
					{
						// prev
						prev_link = "<img height=\"25\" id=\"first\" style=\"cursor:pointer;\" onMouseOver=\"HandleOver('first');\" onmouseout=\"HandleLeave('first');\" style=\"cursor:pointer;\" src=\"pics/first.png\" " + link_array_course [0] + ">" + "<img height=\"25\" id=\"prev\" style=\"cursor:pointer;\" onMouseOver=\"HandleOver('prev');\" onmouseout=\"HandleLeave('prev');\" style=\"cursor:pointer\" src=\"pics/prev.gif\" " + link_array_course [indexCourse - 1] + ">";
					}

					if (indexCourse < link_array_course.length - 1)
					{
						// next
						next_link = "<img height=\"25\" id=\"next\" onMouseOver=\"HandleOver('next');\" onmouseout=\"HandleLeave('next');\" style=\"cursor:pointer;\" src=\"pics/next.gif\" " + link_array_course [indexCourse + 1] + ">" + "<img height=\"25\" id=\"last\" onMouseOver=\"HandleOver('last');\" onmouseout=\"HandleLeave('last');\" style=\"cursor:pointer;\" src=\"pics/last.png\" " + link_array_landmarks [link_array_landmarks.length - 1] + ">";
					}

					if (indexCourse == link_array_course.length - 1)
					{
						// link it to the first landmark point
						next_link = "<img height=\"25\" id=\"next\" onMouseOver=\"HandleOver('next');\" onmouseout=\"HandleLeave('next');\" style=\"cursor:pointer;\" src=\"pics/next.gif\" " + link_array_landmarks [0] + ">" + "<img height=\"25\" id=\"last\" onMouseOver=\"HandleOver('last');\" onmouseout=\"HandleLeave('last');\" style=\"cursor:pointer;\" src=\"pics/last.png\" " + link_array_landmarks [link_array_landmarks.length - 1] + ">";
					}

					indexCourse = indexCourse + 1;
				}

				//if ((current_quote2 && current_quote2.length > 0) || (current_desc2 && current_desc2.length > 0))
				// CurrentMarkerArray.push(createTabbedMarker(points[i], infoTitle, infoIndex, infoBook, infoCourse, current_quote, current_quote2, current_desc, current_desc2, current_image, current_image2, current_image_link, current_image_link2, prev_link, next_link,credit, current_icon_image, current_icon_shadow, current_book));
				//else
				createMarker(points[i], infoTitle, infoIndex, infoBook, infoCourse, current_quote, current_desc, current_image, current_image_link, prev_link, next_link,credit, current_icon_image, current_icon_shadow, current_book, id);
			}
		}
	}
	else
	{
	//	window.location = "http://www.cannonade.net/";
		return;
	}

	}}).send(); 
}

