var map;					// GMap2 - the google map
var details = new Array();	// Array - an array containing previous loaded data
var comments = new Array();	// Array - an array containing previous loaded comments
var highlight;				// GMarker - a marker that overlays the currently selected marker
var highlight_id = 0;		// int - the ID of the current marker
var acc = 0;                // int - "anti-cache-counter", prevents caching of AJAX content

// Icons used in this map
var icon_suicide = makeIcon("red");
var icon_unknown = makeIcon("violet");
var icon_accident = makeIcon("blue");

var icon_highlight = makeIcon("yellow");

// int - default latitude/longitude/zoom
var HOME_LAT = 47.24730;
var HOME_LNG = -122.44400;
var HOME_ZOOM = 10;



// This function is triggered by <body onLoad="">
function initialize() {
	
	// If the map couldn't be loaded, display an error message on the map and quit
	if (!GBrowserIsCompatible()) {
		generateMapErrorMessage('Your browser cannot display Google Maps.');
		return;
	}
	
	// Initialize the map
	map = new GMap2(document.getElementById("map"));
	map.setCenter(new GLatLng(HOME_LAT, HOME_LNG), HOME_ZOOM);
	map.addControl(new GLargeMapControl());
	map.addControl(new GScaleControl());
	map.addControl(new GOverviewMapControl());
	map.addControl(new GHierarchicalMapTypeControl());
	
	// Add click behavior to map
	GEvent.addListener(map, "click", user_clickOnMap);
	
	// Ask server to send marker data
	GDownloadUrl("data/markers.txt", whenGivenMarkers);
}


// This function is triggered when the server responses to the client's request for markers
function whenGivenMarkers(data, responseCode) {
	
	// To ensure against HTTP errors that result in null or bad data,
	// always check status code is equal to 200 before processing the data
	if (responseCode == 200) {
		
		// Split up the data
		var rows = data.split("\n");
		
		// Read each row
		for (var i=0; i<rows.length-1; i++) {
			var record = rows[i];
			var data = record.split("\t");
			
			// If the correct number of variables are found
			if (data.length == 5) {
				// 0 = id
				// 1 = name
				// 2 = latituide
				// 3 = longitude
				// 4 = cause
				
				
				// Determine which icon to use for the marker
				var icon = icon_unknown;
				if (data[4] == "Suicide") { icon = icon_suicide; }
				if (data[4] == "Accident") { icon = icon_accident; }
				
				// Create a marker
				var point = new GLatLng(data[2],data[3]);
				var marker = new GMarker(point, {icon: icon})
				marker.id = data[0];
				marker.name = data[1];
				
				// Add the marker to the map
				map.addOverlay(marker);
				
			} // End of "if (data.length == 5)"
			
		} // End of "for (var i=0; i<rows.length-1; i++)"
	} else {
		// Display an error on the map, because the user will be looking at the map.
		// It won't be necessary to display an alert.
		generateMapErrorMessage('Could not get data needed to build map.');
	}
}

// This function is triggered when the user clicks on the map
function user_clickOnMap(marker, point) {
	
	// If the user clicked on a marker, and that marker isn't highlighted...
	if (marker && (marker != highlight)) {
		
		// If the highlight marker hasn't been created, create it and add it to the map right now
		if (!highlight) {
			highlight = new GMarker(new GLatLng(HOME_LAT,HOME_LNG), {icon: icon_highlight});
			map.addOverlay(highlight);
		}
		
		// Move the highlight marker to overlap the current marker, and remember the ID of the marker
		highlight.setLatLng(marker.getLatLng());
		highlight_id = marker.id;
		
		// Update the display
		
		// Clear the form
		document.form1.name.value = "";
		document.form1.comment.value = "";
		
		getDetails(marker.id);
		getComments(marker.id);
	} // End of "if (marker && (marker != highlight))"
	
}

function getDetails(id) {
	
	document.getElementById('ajax_details').innerHTML = 'Getting details of event...';
	document.getElementById('comments1').style.visibility = 'visible';
	
	// If this web application has already downloaded the details of the event...
	if (details[id]) {
		displayDetails(id);
	} else {
		// Ask the server for the details of this event
		GDownloadUrl("data/event/"+id+".txt", whenGivenDetails);
	}
}

function displayDetails(id) {
	if (details[id]) {
		document.getElementById('ajax_details').innerHTML = details[id];
	} else {
		document.getElementById('ajax_details').innerHTML = "Cannot find the details for this event.";
	}
}

function getComments(id) {
	
	document.getElementById('ajax_comments').innerHTML = "Loading comments...";
	document.getElementById('comments2').style.visibility = 'visible';
	
	// If this web application has already downloaded the comments information...
	if (comments[id]) {
		displayComments(id);
	} else {
		// Ask the server for the comments for this event
		GDownloadUrl("data/comment/"+id+".txt", whenGivenComments);
	}
}

function displayComments(id) {
	if (comments[id]) {
		document.getElementById('ajax_comments').innerHTML = comments[id];
	} else {
		document.getElementById('ajax_comments').innerHTML = "Cannot find the comments for this event.";
	}
}


// This function is triggered when the server responses to the client's request for comments
function whenGivenDetails(data, responseCode) {
	
	// To ensure against HTTP errors that result in null or bad data,
	// always check status code is equal to 200 before processing the data
	if (responseCode == 200) {
		
		// Split up the data
		var rows = data.split("\n");
		var id = rows[1];
		var result = '';
		
		// Create some HTML
		result += format("Date:", rows[2]);
		result += format("Location:", rows[3]);
		result += format("City:", rows[4]);
		result += format("Name:", rows[5]);
		result += format("Gender:", rows[6]);
		result += format("Age:", rows[7]);
		result += format("Track Owner:", rows[8]);
		result += format("Train Owner:", rows[9]);
		result += format("Cause of Death:", rows[10]);
		
		// Create some HTML - the rest of the data is from the details field
		var d = rows[11];
		for (var i=12; i<rows.length; i++) {
			d += rows[i];
		}
		result += format2("Details:", d);
	
		// Save event information locally
		details[id] = result;
	}
	displayDetails(id);
}

function whenGivenComments(data, responseCode) {
	
	var id = 0;
	// To ensure against HTTP errors that result in null or bad data,
	// always check status code is equal to 200 before processing the data
	if (responseCode == 200) {
		
		// Split up the data
		var rows = data.split("\n");
		var id = rows.shift();
		data = rows.join("\n");
		id = id.replace(/[^0-9]/,"");
		
		var result = '';
		
		if (id) { comments[id] = data; }
		
	}
	
	if (id) { displayComments(id); }
}

function user_sendingComment() {
	
	var id = highlight_id;
	var name = trim(document.form1.name.value);
	var comment = trim(document.form1.comment.value);
	
	// Validate the data
	var errors = "";
	if (name == "") { errors += "\n- Include your name"; }
	if (comment == "") { errors += "\n- Include a comment"; }
	
	// Stop if the data is incomplete
	if (errors) {
		errors = "Please make sure all the information is filled out:"+errors;
		alert(errors);
		return;
	}
	
	// Send the information
	var post = "";
	post += "name="    + URLEncode(name)    + "&";
	post += "comment=" + URLEncode(comment) + "&";
	post += "id=" + id;
	
	GDownloadUrl("ajax/comment_add.php", whenGivenCommentResults, post, "application/x-www-form-urlencoded");
}

function whenGivenCommentResults(data, responseCode) {
	
	var rows = data.split("\n");
	if (rows.length == 2) {
		var id = rows[0];
		var result = rows[1];
		
		var message = "???";
		switch (result) {
			case "incomplete":
				message = 'One of the fields are incomplete.';
				break;
			case "notfound":
				message = 'An error has occurred.';
				break;
			case "success":
				message = 'Your comment has been received.';
				break;
			case "database":
				message = 'An error has occurred.';
				break;
			default:
				message = 'An error has occurred.';
		}
		
		alert(message);
		
		if (result == "success") {
			document.form1.name.value = "";
			document.form1.comment.value = "";
			return;
		}
		
	}
	
	alert("There was a problem.  We may not have receive your comment.");
	
}








/* Make an icon based on the folder the icon information is in. */
function makeIcon(color) {
	var xMarker = new GIcon();
	xMarker = new GIcon();
	xMarker.image = "markers/"+color+"/marker.png";
	xMarker.iconSize = new GSize(11, 11);
	xMarker.printImage = "markers/"+color+"/markerie.gif";
	xMarker.mozPrintImage = "markers/"+color+"/markerff.gif";
	xMarker.iconAnchor = new GPoint(6, 6);
	return xMarker;
}

/* Trim whitespace before and after text. */
/*        Version December 3, 2006        */
function trim(sString) {
   
   if (sString == null)
      return "";
   
   return sString.replace(/^\s*|\s*$/g,"");
   
}

// Code borrowed from (2008-05-14):
//   http://cass-hacks.com/articles/code/js_url_encode_decode/
function URLEncode (clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
    	output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}










//////////////////////////////////////
//  functions that create HTML code
function format(heading, content) {
	return '<div class="data"><strong>'+heading+'</strong> '+content+'</div>'+"\n";
}

function format2(heading, content) {
	return '<div class="data"><strong>'+heading+'</strong><br />'+content+'</div>'+"\n";
}

function generateMapErrorMessage(error) {
	
	var result = '<div style="height: 200px;"></div>';
	result += '<div class="criticalMapError">';
	result += error;
	result += '</div>';
	
	document.getElementById("map").innerHTML = result;
}
