var map;   

	var markerOptionSet = {};
	
window.addEvent('domready', function() {
//	theRoar = new Roar({
//		duration: 5000,
//		position: 'upperRight',
//		margin: {x: 30, y: 20}
//	});
	initializeMap();
});

/*
window.addEvent('unload'), function() {
	GUnload();
}
*/
	
function initializeMap() {
	dbug.enable();
	map = new GMap2(document.getElementById("map_canvas"));
	
	// Limit the range of the map
	// http://groups.google.com/group/Google-Maps-API/browse_thread/thread/b2ed264040355663/98601304973e3414
	// http://econym.googlepages.com/range.htm
	// http://econym.googlepages.com/example_range.htm
	
	// Get the list of map types
	var mt = map.getMapTypes();
	
	// Overwrite the getMinimumResolution() and getMaximumResolution() methods
	for (var i=0; i<mt.length; i++) {
		mt[i].getMinimumResolution = function() {return 14;}
		mt[i].getMaximumResolution = function() {return 18;}
	}
	
	// Display the map, with some controls and set the initial (center) location
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	map.setCenter(new GLatLng(34.506468, -112.226479), 15);
	
	// Add a move listener to restrict the bounds range
	GEvent.addListener(map, "move", function() { checkBounds(); });
	
	// The allowed region which the whole map must be within
	var allowedBounds = new GLatLngBounds(
		new GLatLng(34.46, -112.30), new GLatLng(34.56, -112.21));
	
	// If the map position is out of range, move it back
	function checkBounds() {
		// Perform the check and return if OK
		if (allowedBounds.contains(map.getCenter()))
			return;
		
		// It`s not OK, so find the nearest allowed point and move there
		var C = map.getCenter();
		var X = C.lng();
		var Y = C.lat();
		
		var AmaxX = allowedBounds.getNorthEast().lng();
		var AmaxY = allowedBounds.getNorthEast().lat();
		var AminX = allowedBounds.getSouthWest().lng();
		var AminY = allowedBounds.getSouthWest().lat();
		
		if (X < AminX) {X = AminX;}
		if (X > AmaxX) {X = AmaxX;}
		if (Y < AminY) {Y = AminY;}
		if (Y > AmaxY) {Y = AmaxY;}
		//alert ("Restricting "+Y+" "+X);
		map.setCenter(new GLatLng(Y,X));
	}
	
	//new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(0,-53)));
	new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(0,-41));
	
	
	
	
	new Ajax('reportAdmin/AJAX.php?a=loadReportTypeLegend', {
		method: 'post',
		evalScripts: true,
		onComplete: function() {
		}
	}).request();
	
	
	var reportFormHTML;
	new Ajax('reportAdmin/AJAX.php?a=loadReportFormHTML', {
		method: 'post',
		evalScripts: true,
		onComplete: function(responseText) {
		//	dbug.log('responseText=' + responseText);
			reportFormHTML = responseText; // this.response.text;
		//	loadReports(); // now that the icons are ready
		}
	}).request();
	
	
	/*
	var legendDiv = $('legendDiv');
	var codeSet = [1, 2, 3, 4, 5, 6, 99];
	var typeSet = ['Pothole', 'Pavement Failure', 'Plugged Culvert', 
		'Silted-In Ditch', 'Downed Sign', 'Overhanging Branches', 
		'On-Road Debris', 'Other'];
	codeSet.each(function(code, index) {
		var thisIcon = new GIcon(G_DEFAULT_ICON);
		thisIcon.image = "reportAdmin/images/marker" + code + ".png";
		markerOptionSet[code] = { icon: thisIcon };
		
		var legendItem = new Element('div');
		legendItem.adopt(new Element('img', { src: thisIcon.image }));
		legendItem.adopt(new Element('span',{ text: typeSet[index] }));
		legendDiv.adopt(legendItem);
	});
	*/
	
	GEvent.addListener(map, "click", function(overlay, latlng) {
		//only perform the click if the window is closed and the click was directly on the map.
		if(!overlay) {
			var reportFormDiv = new Element('div');
			reportFormDiv.setHTML(reportFormHTML);
			$(document.body).adopt(reportFormDiv);
			map.openInfoWindow(latlng, reportFormDiv);
			
			var theForm = $('reportForm');
			theForm.longitude.value = latlng.lng();
			theForm.latitude.value = latlng.lat();
			map.currentLanLng = latlng;
		}
	});

}



function submitReport(theForm){
	
	if(theForm.name.value == '') {
		alert('Please enter your name.\n\n(this is so we may reach you in case we have troubles locating the issue you\'re reporting)');
		theForm.name.focus();
		return false;
	}
	var phone = theForm.phoneNumber.value;
	if(phone == ''  || phone.replace(/\D/gi, '').length < 7) {
		alert('Please enter your phone number.\n\n(this is so we may reach you in case we have troubles locating the issue you\'re reporting)');
		theForm.phoneNumber.focus();
		return false;
	}
	if(theForm.ReportTypeID.value == '') {
		alert('Please indicate the type of issue you are reporting.');
		theForm.ReportTypeID.focus();
		return false;
	}
	
	new Ajax('reportAdmin/AJAX.php?a=submitReport', {
		method: 'post',
		data: theForm,
		onComplete: function() {
			map.closeInfoWindow();
			loadReports();
	//		theRoar.alert('Report Successfully Submitted', 
	//			"The location of the report has been added to our database.");
		//	$("message").set('html', '<h3>Report Successfully Sumbitted</h3><p>The location of the report has been added to our database.</p>');
		}
	}).request();
	return;
}



function createMarker(latlng, html, code) {
	
//	markerSet[
//	var blueIcon = new GIcon(G_DEFAULT_ICON);
//	blueIcon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png";
//  // Set up our GMarkerOptions object
//  markerOptions = { icon:letteredIcon };
//  var marker = new GMarker(point, markerOptions);
//	map.addOverlay(new GMarker(point, markerOptions));
	var marker = new GMarker(latlng, markerOptionSet[code]);
	GEvent.addListener(marker, 'click', function() {
		var markerHTML = html;
		marker.openInfoWindowHtml(markerHTML);
	});
	return marker;
}


function loadReports() {
	
	new Ajax('reportAdmin/AJAX.php?a=loadReports', {
		method: 'post',
		onComplete: function() {
			map.clearOverlays();
			var xmlDoc = this.response.xml;
			var markers = xmlDoc.documentElement.getElementsByTagName("Report");
			for (var i = 0; i < markers.length; i++) {
				var lng = markers[i].getAttribute("longitude");
				var lat = markers[i].getAttribute("latitude");
				
				if(lng && lat) {
					var latlng = new GLatLng(parseFloat(lat),parseFloat(lng));
					
					var html = '<div>'
					+ '<strong>Submitted:</strong> '
					+ markers[i].getAttribute("dateAdded")
					+ '<br /><strong>Type:</strong> '
					+ markers[i].getAttribute("type")
					+ '<br /><br /><strong>Approximate Location:</strong> '
					+ markers[i].getAttribute("address") 
					+ '</div>';

					var marker = createMarker(latlng, html, markers[i].getAttribute("code"));
					map.addOverlay(marker);
					

				}
			}
		}
	}).request();
}


function tidyPhoneNumber(thePhoneNumber) {
	
	if($type(thePhoneNumber)=='element') {
		thePhoneNumber.value = tidyPhoneNumber(thePhoneNumber.value);
		return;
	}
	
	if(thePhoneNumber == '')
		return '';
	
	var rawNumber, rawExtension;
	var parts = thePhoneNumber.split('x');
	
	// let's now get the numerals from the number:
	rawDigits = parts[0].replace(/\D/gi, '');
	
	// Strip off a leading one if present:
	if (rawDigits.charAt(0) == '1')
		rawDigits = rawDigits.substring(1);
	
	var result = thePhoneNumber;
	// Now we expect the number to have 10 digits.
	if(rawDigits.length == 10)		// we can put it into the format (xxx) xxx-xxxx
		result =  "(" + rawDigits.substring(0, 3) + ") " +
				       rawDigits.substring(3, 6) + "-" + rawDigits.substring(6, 10);
	else if(rawDigits.length == 7)	// we can put it into the format (xxx-xxxx
		result = rawDigits.substring(0, 3) + "-" + rawDigits.substring(3, 7);
	
	// Now let's tend to the extension, if present:
	if(parts.length > 1) {
		var extension = parts[1].replace(/\D/gi, '');
		if (extension.length > 0)
			result += " x" + extension;
	}
	
	return result;
}
