//some global vars
document.domain = "roway.net"; //needed for iframe communication across sub-domains
var minzoom = 12;
var oldmarker;
//create a dummy icon to copy
var baseIcon = new GIcon();
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(10, 34);
baseIcon.infoWindowAnchor = new GPoint(5, 5);
baseIcon.infoShadowAnchor = new GPoint(18, 25);

var accuracyarray = new Array();
accuracyarray[0] =	"Unknown location."
accuracyarray[1] = 	"Country level accuracy."
accuracyarray[2] = 	"Region (state, province, prefecture, etc.) level accuracy."
accuracyarray[3] = 	"Sub-region (county, municipality, etc.) level accuracy."
accuracyarray[4] = 	"Town (city, village) level accuracy."
accuracyarray[5] = 	"Post code (zip code) level accuracy."
accuracyarray[6] = 	"Street level accuracy."
accuracyarray[7] = 	"Intersection level accuracy."
accuracyarray[8] = 	"Address level accuracy."

function nl2br(text){
	text=text.replace(/\\n/g, "<br>");
	return text;
}

function ConvertDate(datestring){ //converts 8/15/06 to unix timestamp
	//alert(datestring + " passed into ConvertDate()");
	var pattern = /\d+/g;
	var result = datestring.match(pattern);
	var thisdate = new Date(result[2],result[0] - 1,result[1]);
	var returnval = thisdate.getTime();
	//alert(returnval + " to be returned");
	return returnval;
}

function checkZoom(){
	if(map.getZoom() < minzoom){ 
		map.setZoom(minzoom);
	}
}
// showLocation() is called when you click on the Search button
// in the form.  It geocodes the address entered into the form
// and adds a marker to the map at that location.
function showLocation() {
	var address = document.forms[0].q.value;
	//alert(address);
	geocoder.getLocations(address, addAddressToMap);
}

// findLocation() is used to enter the sample addresses into the form.
function findLocation(address) {
	document.forms[0].q.value = address;
 	showLocation();
}

function drawRoute() { 
	if(activated == 1) {//if drawing has been enabled
		map.clearOverlays(); //clear current stuff
		var points = [];
		for (i = 0; i < x_array.length; i++) {
			var point = new GPoint(x_array[i], y_array[i]); //push the points on the array
			points.push(point);
			var icon = new GIcon(baseIcon); //custom icon
			if(typeof(get_radio_value) == 'function'){
				//get the icon selected on the page if possible
				thisicon =  get_radio_value(); //get the icon from the form
			}
			if(typeof(thisicon) != 'undefined'){
				icon.image = "http://www.roway.net/mdata/icons/" + thisicon;
				 //icon.image = "http://www.google.com/mapfiles/arrow.png";
			} else {
				icon.image = "http://www.roway.net/mdata/icons/white_lrg.png";
				 //icon.image = "http://www.google.com/mapfiles/arrow.png";
			}
			
			//Create marker
			var marker = new GMarker(point,icon);
			//place it on map (first click only)
			if(i == 0){
				map.addOverlay(marker);
			}
		}
		//get line color, either from inside the mapframe.mapform.linecolor.value or mapform.linecolor.value
		if(typeof(get_linecolor) == 'function'){
			linecolor = get_linecolor(); //get line color from form
		} else {
			linecolor = '#ED72A2';
		}
    	map.addOverlay(new GPolyline(points,linecolor));
	} //end if activated
} //end function

function CreateMarker(point,icon,html){
	var thisicon = new GIcon(baseIcon);
	//thisicon.image = "http://www.roway.net/mdata/icons/" + icon ;
	thisicon.image = "icons/" + icon;
	var marker = new GMarker(point,thisicon);
	GEvent.addListener(marker, "click", function() {
 	    var fixedhtml = '<div id="bubble">' + nl2br(html) + '</div>';
		marker.openInfoWindowHtml(fixedhtml);
	});
	return marker;
}

 // 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));
}

function ChangeMapDates(theform){
	map.clearOverlays();
	
	msd = theform.startdate.value;
	med = theform.enddate.value;
	checkmsd = ConvertDate(msd);
	checkmed = ConvertDate(med);
	if(checkmed <= checkmsd){
		alert("The end date cannot be before the start date");
	} else {
		//alert("Calling loadMapDate with " + msd + " and " + med);
		loadMapData(msd,med);
	}
 }
 
function clearAll() {
	map.clearOverlays();//clear overlays
	x_array = new Array(0);//new x coordinates
	y_array = new Array(0); //new y coordinates
	loadMapData(msd,med); //reinsert XML map data
}

//start/stop drawing
function startDraw(onoff){
	activated = onoff; //set global activated value
	if(onoff == 0){
		loadMapData(msd,med); //reinsert map data
	}
}

//the initial line draw
function drawOriginalRoute(selected_icon,selected_color) { 
	var points = [];
	if(x_array.length >= 1){
		for (i = 0; i < x_array.length; i++) {
			var point = new GPoint(x_array[i], y_array[i]);
			points.push(point);
			//custom icon {PURPLE FOR INDICATED SPOT}
			var icon = new GIcon(baseIcon);
			if(typeof(selected_icon) != 'undefined'){
				icon.image = "http://www.roway.net/mdata/icons/" + selected_icon;
			} else {
				icon.image = "http://www.roway.net/mdata/icons/white_lrg.png";
			}
			//var icon = new GIcon(baseIcon);
   			 //icon.image = "http://www.google.com/mapfiles/arrow.png";
			//icon.iconSize = new GSize(39, 34);
			var marker = new GMarker(point,icon);
			if(i == 0){
				map.addOverlay(marker);
			}
		}
		if(typeof(selected_color) != 'undefined'){
			map.addOverlay(new GPolyline(points,selected_color));
		} else {
			map.addOverlay(new GPolyline(points,"#ED72A2"));
		}
	}
}

// addAddressToMap() is called when the geocoder returns an
// answer.  It adds a marker to the map with an open info window
// showing the nicely formatted version of the address and the country code.
/*
function addAddressToMap(response) {
	//map.clearOverlays();
	if (!response || response.Status.code != 200) {
		alert("Sorry, we were unable to geocode that address");
	} else {
		place = response.Placemark[0];
		point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
		map.setCenter(point,16);
	}
	loadMapData(msd,med); //reinsert map data
}
*/
function addAddressToMap(response) {
 // map.clearOverlays();
 //alert(typeof(oldmarker));
 if(typeof(oldmarker) != 'undefined'){
	 //oldmarker.closeInfoWindowHtml();
  	map.removeOverlay(oldmarker);
  }
  if (typeof(response) == 'undefined' || response.Status.code != 200) {
    alert("That address could not found");
  } else {
    place = response.Placemark[0];
	point = new GLatLng(place.Point.coordinates[1],
                        place.Point.coordinates[0]);
	var icon = new GIcon(baseIcon);
    icon.image = "http://www.google.com/mapfiles/arrow.png";
	icon.iconSize = new GSize(39, 34);
    var marker = new GMarker(point,icon);

    map.addOverlay(marker);
	oldmarker = marker;
    marker.openInfoWindowHtml('<div id="bubble">Approximate Location:<br>' + place.address  + '<br>' + accuracyarray[place.AddressDetails.Accuracy] + '</div>');
	GEvent.addListener(marker, "click", function() {
		if (marker) {
			map.removeOverlay(marker);
  		}
	});
  }
  loadMapData(msd,med); //reinsert map data
}
