var ZOOM_START = 5;
var ZOOM_START2 = 4;
var ZOOM_OUT_MIN = 7;
var zoomLevel = 5;

var map = null;
var geocoder = null;
var center_point = null;
var center_point_address = null;

var reasons = [];
var baseIcon = null;
var icon = null;
var countryIcon = null;
var zoneIcon = null;

var city = null;
var state = null;
var zip = null;
var country = null;

var incentive_info = new Array();


function initialize() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		map.addControl(new GLargeMapControl()); 
		map.addControl(new GMapTypeControl()); 
		map.setCenter(new GLatLng(38.598556, -98.437500), ZOOM_START);
		//map.enableScrollWheelZoom();
		geocoder = new GClientGeocoder();
		GEvent.addListener(map, "click", clicked);
		//GEvent.addListener(map, "mousemove", moved);
	}
}


function createMarkerClickHandler(marker, html) {
  return function() {
    marker.openInfoWindowHtml(html);
    return false;
  };
}


function createLabeledMarker(point, title, html, rank) {
  var markerOpts = {};

  markerOpts = {
	"icon": zoneIcon,
	"clickable": true,
	"labelText": title,
	"labelOffset": new GSize(-16, -8),
	"labelClass": "zone-marker"
	};
  var newPoint = point;
  var marker = new LabeledMarker(newPoint, markerOpts);

  GEvent.addListener(marker, "mouseover", function() {
    marker.setImage('/images/graycirclemarker.png');
  });

  GEvent.addListener(marker, "mouseout", function() {
    marker.setImage('/images/blackcirclemarker.png');
  });

  GEvent.addListener(marker, "infowindowclose", function() {
    marker.setImage('/images/blackcirclemarker.png');
  });

  return marker;
}


/******************************************************************************************
** createMap(): creates the containers for the map and map legend, Places the actual map,
** and plots the reps
*******************************************************************************************/
function createMap() {
	var mapContainerNode = document.getElementById("map-container");

	var mapNode = createNode("div","",mapContainerNode);
	mapNode.setAttribute("id","map");
	/*var mapLegendNode = createNode("div","",mapContainerNode);
	mapLegendNode.setAttribute("id","map-legend");
	createNodeWithText("strong","","Legend:",mapLegendNode);
	createNode("br","",mapLegendNode);
	createNodeWithText("div","","The Green marker indicates your location",mapLegendNode);
	createNodeWithText("div","","The Red marker indicates the zero motorcycle sales representative in your area",mapLegendNode);*/

	map = new GMap2(mapNode);

	map.addControl(new GSmallMapControl()); 
	
	map.setCenter(center_point,zoomLevel); 

	plotIncentives();
	createIncentiveListItems(country);

	// get the selected item in the country select box to match the country in the center of the map
	selectObj = document.getElementById('country');
	if (selectObj != null) {
		if (selectObj.options[selectObj.selectedIndex].value != country) {
			for (var i=0; i<selectObj.length; i++) {
				if (selectObj.options[i].value == country) {
					selectObj.selectedIndex = i;
				}
			}
		}
	}
}


function createIncentiveListItems(newCountry) {
	var incentiveList = document.getElementById('sidebar-list');
	while(incentiveList.hasChildNodes()){
		incentiveList.removeChild(incentiveList.childNodes[0])
	}

	var li;
	for (countryKey in country_incentives) {
		if ( (countryKey==newCountry) && (country_incentives[countryKey]['countryOptions']=='1') ) {
			li=document.createElement('li');
			var j=1;
			var textUrlInfo = '';
			var key = 'text'+j;
			while (key in country_incentives[countryKey]) {
				var title = '';
				if (country_incentives[countryKey]['title'+j]!='') {
					title = '<div class="info-title">'+country_incentives[countryKey]['title'+j]+'</div>';
				}
				var url = '';
				if (country_incentives[countryKey]['url'+j]!='') {
					url = "&nbsp;<a href=\""+country_incentives[countryKey]['url'+j]+"\" target=\"_blank\" class=\"info-link\">more info</a>";
				}
				textUrlInfo = textUrlInfo + title + '<p>'+country_incentives[countryKey]['text'+j]+url+'</p>';
				j++;
				key = 'text'+j;
			}
			li.innerHTML = '<div class="sidebar-text">'+textUrlInfo+'</div>';
			incentiveList.appendChild(li);
		}
	}

	for (i=0; i<incentives.length; i++) {
		if (incentives[i]['countryCode'] == newCountry) {
			li=document.createElement('li');
			var location = incentives[i]['countryCode'];
			if (incentives[i]['zone'] != '') {
				location = incentives[i]['zone'];
			}
			var incentiveName = incentives[i]['zoneName'];
			if ( (incentiveName=='') && (incentives[i]['countryCode'] in country_incentives) ) {
				incentiveName = country_incentives[incentives[i]['countryCode']]['name'];
			}
			li.innerHTML = '<div class="label">'+location+'</div><a href="#">' +incentiveName + '</a>';
			li.getElementsByTagName('a')[0].onclick = incentives[i]['handler'];
			incentiveList.appendChild(li);
		}
	}
}

  
function plotIncentives() {

	// for individual countries
	var j=1;
	for (countryKey in country_incentives) {
		if (country_incentives[countryKey]['countryOptions']=='1') {
			var heading = country_incentives[countryKey]['country'];
			
			var point = new GLatLng(country_incentives[countryKey]['lat'],country_incentives[countryKey]['lng']);

			var markerLabel = country_incentives[countryKey]['countryCode'];
			if (country_incentives[countryKey]['abbr'] != '') {
				markerLabel = country_incentives[countryKey]['abbr'];
			}	
			if (markerLabel.length>3) { markerLabel = markerLabel.substr(0,3); }

			var html = '';

			// the info window content
			var j=1;
			var textUrlInfo = '';
			var key = 'text'+j;
			while (key in country_incentives[countryKey]) {
				var title = '';
				if (country_incentives[countryKey]['title'+j]!='') {
					title = '<div class="info-title">'+country_incentives[countryKey]['title'+j]+'</div>';
				}
				var url = '';
				if (country_incentives[countryKey]['url'+j]!='') {
					url = "&nbsp;<a href=\""+country_incentives[countryKey]['url'+j]+"\" target=\"_blank\" class=\"info-link\">more info</a>";
				}
				textUrlInfo = textUrlInfo + '<div class="info-section">'+ title + '<p>' +country_incentives[countryKey]['text'+j]+url+'</p></div>';
				j++;
				key = 'text'+j;
			}
			
			html = '<div class="info-heading">'+heading+'</div><div class="info-content">'+textUrlInfo+'</div>';

			var marker = createLabeledMarker(point, markerLabel, html, j);

			var handler = createMarkerClickHandler(marker, html);
  			GEvent.addListener(marker, "click", handler);
			country_incentives[countryKey]['handler'] = handler;
  
			map.addOverlay(marker);
			j++;
		}
	}
	
	// for states / regions
	for (i=0; i<incentives.length; i++) {
		var heading = incentives[i]['zoneName']+', '+incentives[i]['country'];

		var point = new GLatLng(incentives[i]['lat'],incentives[i]['lng']);

		// the label
		var markerLabel = incentives[i]['countryCode'];
		if (incentives[i]['zone'] != '') {
			markerLabel = incentives[i]['zone'];
		}
		if (incentives[i]['abbr'] != '') {
			markerLabel = incentives[i]['abbr'];
		}
		if (markerLabel.length>3) { markerLabel = markerLabel.substr(0,3); }

		// the info window content
		var j=1;
		var textUrlInfo = '';
		var key = 'text'+j;
		while (key in incentives[i]) {
			if (incentives[i]['name'] != '') {
				var title = '';
				if (incentives[i]['title'+j]!='') {
					title = '<div class="info-title">'+incentives[i]['title'+j]+'</div>';
				}
				var url = '';
				if (incentives[i]['url'+j]!='') {
					url = "&nbsp;<a href=\""+incentives[i]['url'+j]+"\" target=\"_blank\" class=\"info-link\">more info</a>";
				}
				textUrlInfo = textUrlInfo + '<div class="info-section">' + title + '<p>'+incentives[i]['text'+j]+url+'</p></div>';
			}
			j++;
			key = 'text'+j;
		}
			
		html = textUrlInfo;
		
		if (incentives[i]['countryCode'] in country_incentives) {
			j=1;
			textUrlInfo = '';
			key = 'text'+j;
			while (key in country_incentives[incentives[i]['countryCode']]) {
				var title = '';
				if (country_incentives[incentives[i]['countryCode']]['title'+j]!='') {
					css = (html=='') ? 'info-title' : 'info-title2';
					title = '<div class="'+css+'">'+country_incentives[incentives[i]['countryCode']]['title'+j]+'</div>';
				}
				var url = '';
				if (country_incentives[incentives[i]['countryCode']]['url'+j]!='') {
					url = "&nbsp;<a href=\""+country_incentives[incentives[i]['countryCode']]['url'+j]+"\" target=\"_blank\" class=\"info-link\">more info</a>";
				}
				textUrlInfo = textUrlInfo + '<div class="info-section">' + title + '<p>'+country_incentives[incentives[i]['countryCode']]['text'+j]+url+'</p></div>';
				j++;
				key = 'text'+j;
			}
			
			html = html + textUrlInfo;
		}
		
		html = '<div class="info-heading">'+heading+'</div><div class="info-content">'+html+'</div>';

		var marker = createLabeledMarker(point, markerLabel, html, i);

		var handler = createMarkerClickHandler(marker, html);
  		GEvent.addListener(marker, "click", handler);
		incentives[i]['handler'] = handler;
  
		map.addOverlay(marker);

	}
}

/******************************************************************************************
** setCenterPoint(lat,lng,addressString): show the map defined by the center lat/long chosen  
** from one of the"did you mean" options
*******************************************************************************************/
function setCenterPoint(lat,lng,addressString) {
	center_point_address = addressString;
	
	center_point = new GLatLng(lat,lng);

	if (!map) {
		createMap();
	} else {
		map.setCenter(center_point,zoomLevel); 
	}
}


function setCenterForCountry() {
	zoomLevel = ZOOM_START;
	if ((country=='US') || (country=='AU') || (country=='CA')) zoomLevel = ZOOM_START2;

	if (country in country_incentives) {
		if ('centerLat' in country_incentives[country]) {
			if ('zoomLevel' in country_incentives[country]) {
				zoomLevel = country_incentives[country]['zoomLevel'];
			}
			setCenterPoint(country_incentives[country]['centerLat'], country_incentives[country]['centerLng'], country_incentives[country]['country']);
		} else {
			setCenterPoint(country_incentives[country]['lat'], country_incentives[country]['lng'], country_incentives[country]['country']);
		}
	} else {
		geocoder.getLocations(country, centerAddress);
	}
}


function countryChange(selectObj) { 
	var index = selectObj.selectedIndex; 
	var newCountry = selectObj.options[index].value; 
	if (newCountry!='') {
		country = newCountry;
		setCenterForCountry();
		createIncentiveListItems(newCountry);
	}
 } 


/******************************************************************************************
** setCenter(response): show the map defined by the center that was returned from 
** geocoder.getLocations
*******************************************************************************************/
function setCenter(response) {
	// Retrieve the object
	place = response.Placemark[0];
	center_point_address = place.address;

	// Retrieve the latitude and longitude
	center_point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);

	if (!map) {
		createMap();
	} else {
		map.setCenter(center_point,zoomLevel); 
	}
}


/******************************************************************************************
** setError(response): Display error that was returned from geocoder.getLocations
*******************************************************************************************/
function setError(response) {  // here
	var contentNode = document.getElementById("content");

	// ====== Decode the error status ======
	if (response) {
		var reason="Code "+response.Status.code;
		if (reasons[response.Status.code]) {
			reason = reasons[response.Status.code]
		} 
		createNodeWithText("div","top_message","Could not find address \""+city+", "+state+", "+zip+", "+country+"\" - "+reason,contentNode);
	} else {
		createNodeWithText("div","top_message","Could not find address \""+city+", "+state+", "+zip+", "+country+"\"",contentNode);
	}
}


/******************************************************************************************
** countryCenter(response): look at the result from geocoder.getLocations call from 
** stateCountryCenter. This was our last try.
*******************************************************************************************/
function countryCenter(response)
{
	if (!response || response.Status.code != G_GEO_SUCCESS) {
		setError(response);
	} else {
		setCenter(response);
	}
}


/******************************************************************************************
** centerAddress(response): look at the result from geocoder.getLocations call from 
** showAddress. If no locations found make another getLocations call but this time without
** the city.
** thanks to http://econym.org.uk/gmap/didyoumean.htm
*******************************************************************************************/
function centerAddress(response)
{
	if (!response || response.Status.code != G_GEO_SUCCESS) {
		if ( (response.Status.code == G_GEO_UNKNOWN_ADDRESS) || (response.Status.code == G_GEO_UNAVAILABLE_ADDRESS) ) {
			geocoder.getLocations(country, countryCenter);
		} else {
			setError(response);
		}
	} else {
		// ===== If there was more than one result, "ask did you mean" on them all =====
		if (response.Placemark.length > 1) { 
			var innerHTML = "Did you mean:";
			// Loop through the results
			for (var i=0; i<response.Placemark.length; i++) {
				var p = response.Placemark[i].Point.coordinates;
				innerHTML += "<br>"+(i+1)+": <a href='javascript:setCenterPoint(" +p[1]+","+p[0]+",\""+response.Placemark[i].address+"\")'>"+ response.Placemark[i].address+"<\/a>";
			}
			var contentNode = document.getElementById("content");
			var msgNode = createNode("div","top_message",contentNode);
			msgNode.setAttribute("id","didYouMean");
			msgNode.innerHTML = innerHTML;			
		} else {
			setCenter(response);
		}
	}
}


/******************************************************************************************
** initMap(myCity, myState, myCountry): initializes google map and global variables
*******************************************************************************************/
function initMap(myCity, myState, myZip, myCountry) {
	var contentNode = document.getElementById("content");
	city = myCity;
	state = myState;
	zip = myZip;
	country = myCountry;
	if (GBrowserIsCompatible()) {
	
		geocoder = new GClientGeocoder();
		if (geocoder) {
			zoneIcon = new GIcon();
			zoneIcon.image = '/images/blackcirclemarker.png';
			zoneIcon.iconSize = new GSize(22, 22);
			zoneIcon.iconAnchor = new GPoint(15,13);
			zoneIcon.infoWindowAnchor = new GPoint(18, 4);

			// ====== Array for decoding the failure codes ======
			reasons[G_GEO_SUCCESS]            = "Success";
			reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
			reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
			reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
			reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
			reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
			reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";

			return true;
		} else {
			var msgNode = createNodeWithText("div","top_message","Sorry, there is a problem with the Google Maps API",contentNode);
		}

	} else {
		var msgNode = createNodeWithText("div","top_message","Sorry, the Google Maps API is not compatible with this browser",contentNode);
		return false;
	}
}


/******************************************************************************************
** showAddress(myCity, myState, myZip, myCountry): start here
*******************************************************************************************/
function showCountry(myCountry) {
	initBrowser();
	if (initMap("", "", "", myCountry)) {
		setCenterForCountry();
	}
}
