var bubbleHTMLs = new Array();
var to_direction = new Array();
var from_direction = new Array();
var bounds = null;

function initializeMaps() {
	//	init hide result blocks
	document.getElementById('map-result-route').style.display = "none";
	document.getElementById('map-result-locations').style.display = "none";
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("maps"));
		map.addControl(new GLargeMapControl());
		map.enableScrollWheelZoom();
		map.setCenter(new GLatLng(40, -92), 3);
		
		// === create a GDirections Object ===
	    gdir = new GDirections(map, document.getElementById("direction-description"));
		// === Array for decoding the failure codes ===
		var reasons=[];
		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.";
		reasons[G_GEO_BAD_REQUEST]        = "A directions request could not be successfully parsed.";
		reasons[G_GEO_MISSING_QUERY]      = "No query was specified in the input.";
		reasons[G_GEO_UNKNOWN_DIRECTIONS] = "The GDirections object could not compute directions between the points.";
		
		  // === catch Directions errors ===
		GEvent.addListener(gdir, "error", function() {
			var code = gdir.getStatus().code;
			var reason="Code "+code;
			if (reasons[code]) {
				reason = reasons[code]
			} 
			document.getElementById('direction-description').innerHTML = "<p>Failed to obtain directions:<br />"+reason+"</p>";
		});
	    
		// Create a base icon for all of our markers that specifies the
		// shadow, icon dimensions, etc.
		baseIcon = new GIcon(G_DEFAULT_ICON);
		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(9, 34);
		baseIcon.infoWindowAnchor = new GPoint(9, 2);
		
		//	add custom zoom control box
		init_ZoomControl(map);
	}
}
function init_ZoomControl(map)
{
	var pos = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(0,0));
	pos.apply(document.getElementById("zoomControl"));
	map.getContainer().appendChild(document.getElementById("zoomControl"));
}
function clearMap()
{
	map.clearOverlays();
	document.getElementById("location-list").innerHTML = "";
	locations = new Array();
    locations_list_html = "";
    gmarkers = [];
    bubbleHTMLs = [];
    to_direction = [];
    from_direction = [];
	bounds = new GLatLngBounds();
}
function showMapLocations(state, sector, division)
{	
	//	clear map, location list (array), bound, ...
	clearMap();

	// Read the data from usa_locations.xml
	GDownloadUrl("../../pool/maps/usa_locations.xml", function(doc) {
		var xmlDoc = GXml.parse(doc);
		var markers = xmlDoc.documentElement.getElementsByTagName("marker");
		
		//	get markers by selectors
		for (var i = 0; i < markers.length; i++) {
			var location = markers[i];
			var adress = location.getElementsByTagName("adress");
			
			if((adress[0].getAttribute("state") == state || state==0) && (location.getAttribute("sector") == sector || sector==0) && (location.getAttribute("division") == division || division==0))
			{
				locations.push(location);
			}
		}
		for (var i = 0; i < locations.length; i++) {
			var location = locations[i];
			var adress = location.getElementsByTagName("adress");
			var contact = location.getElementsByTagName("contact");
			
			if(sector == 0 || location.getAttribute("sector") == sector)
			{
				// set point of location
				var lat = parseFloat(location.getAttribute("lat"));
				var lng = parseFloat(location.getAttribute("lng"));
				var point = new GLatLng(lat,lng);
				
				// add point to bound
				 bounds.extend(point);
				
				 //	create list content
				 var marker_nr = i+1;
				 locations_list_html += createListHtml(marker_nr,location, adress, contact);
				 
				 //	create bubble content
				 createBubbleHtml(location, adress, contact);
				 
				 
//	START DELETE				 
				//	html for bubble and list
				var locationLabel 	= location.getAttribute("label");
				var locationAdress	= adress[0].getAttribute("street")+", "+adress[0].getAttribute("city")+", "+adress[0].getAttribute("state")+" "+adress[0].getAttribute("zip")+" "+adress[0].getAttribute("country");
		
				
				var bubble = '<div class="p clearfix">'+
								'<h4>'+location.getAttribute("label")+'</h4>'+
								'<p>'+
									adress[0].getAttribute("street")+'<br />'+
									adress[0].getAttribute("city")+", "+adress[0].getAttribute("state")+" "+adress[0].getAttribute("zip")+
									' '+adress[0].getAttribute("country")+
								'</p>'+
							'</div>';
				var locationContact = '<p>'+
									'phone: '+contact[0].getAttribute("phone")+ '<br />'+
									'<a class="email" href="javascript:void();" onclick="this.href=\'mailto:'+contact[0].getAttribute("email")+'\'">'+
									contact[0].getAttribute("email")+'</a><br />'+
									'<a class="external" href="'+contact[0].getAttribute("web")+'" onclick="window.open(\''+contact[0].getAttribute("web")+'\'); return false;">'+
										contact[0].getAttribute("web")+
									'</a>'+
								'</p>';
//	END DELETE
				// create the marker
				var marker = createMarker(point,i,locationLabel,bubble,locationAdress, locationContact);
				map.addOverlay(marker);
			}
		}
		
		//When all the points have been processed, the zoom level can be set to fit the points.
		boundsZoomLevel = map.getBoundsZoomLevel(bounds) < 12 ? map.getBoundsZoomLevel(bounds) : 12;
		map.setZoom(boundsZoomLevel);
		map.setCenter(bounds.getCenter());
		
		// put the assembled locations_list_html contents into the location-list div
		if(locations.length == 0){
			document.getElementById("location-list").innerHTML = "<p>No locations found.</p>";
			// reset map
			map.setCenter(new GLatLng(40, -92), 3);
		}
		else{ 
			document.getElementById("location-list").innerHTML = locations_list_html;
		}
     	//sIFR.replaceElement(named({sSelector:"div#location-list h4", sFlashSrc: SIFR_SLAB_PATH, sColor:"#333333", sHoverColor:"#990000", sWmode:"transparent"}));
	});
	

	//	show locations result
	document.getElementById('map-result-locations').style.display = "block";
}









function createListHtml(i, location, adress, contact)
{
	var digit = i < 10 ? ' single-digit' : '';
	
    return 	'<div class="location'+digit+'">'+
				'<h4>'+i+') '+location.getAttribute("label")+'</h4>'+
				'<p>'+
					'<a class="teaser" href="javascript:myclick(' + (gmarkers.length) + ')">'+
						adress[0].getAttribute("street")+', '+adress[0].getAttribute("city")+', '+adress[0].getAttribute("state")+' '+adress[0].getAttribute("zip")+' '+adress[0].getAttribute("country")+
						' <img src="../../framework/_resources/css/core/img/icon-link.gif"/>'+
					'<\/a><br />'+
					'phone: '+contact[0].getAttribute("phone")+ '<br />'+
					'<a class="email" href="javascript:void();" onclick="this.href=\'mailto:'+contact[0].getAttribute("email")+'\'">'+
						contact[0].getAttribute("email")+
					'</a><br />'+
					'<a class="external" href="'+contact[0].getAttribute("web")+'" onclick="window.open(\''+contact[0].getAttribute("web")+'\'); return false;">'+
						contact[0].getAttribute("web")+
					'</a>'+
				'</p>'+
			'</div>';
}
function createBubbleHtml(location, adress, contact)
{
}



//This function zooms out until all current markers fit the map
function zoomToBound()
{
	if(bounds)
	{	
		map.setZoom(boundsZoomLevel);
		map.setCenter(bounds.getCenter());
	} else {
		map.setCenter(new GLatLng(40, -92), 3);
	}
}
//	This function clears route overlay and DOM
function clearDirection()
{
	if(gdir)
	{
		gdir.clear();
		document.getElementById("map-result-route").style.display = "none";
	}
}

//This function picks up the click and opens the corresponding info window
function myclick(i) {
	gmarkers[i].openInfoWindowHtml(bubbleHTMLs[i]);
	window.scrollTo(0,0);
}
//functions that open the directions forms
function tohere(i) {
  gmarkers[i].openInfoWindowHtml('<div style="height:160px;">'+to_direction[i]+'</div>');
}
function fromhere(i) {
  gmarkers[i].openInfoWindowHtml('<div style="height:160px;">'+from_direction[i]+'</div>');
}



// Creates a marker whose info window displays the letter corresponding to the given index.
function createMarker(point, index, locationLabel, bubble, locationAdress, locationContact) {
	// Create a lettered icon for this point using our icon class
	//	index starts at 0
	var marker_nr = index +1;
	
	var letteredIcon = new GIcon(baseIcon);
	if(marker_nr < 100){
		letteredIcon.image = "../../pool/maps/marker/red_" + marker_nr + ".png";
	}
	else{ //show emty icon 
		letteredIcon.image = "../../pool/maps/marker/marker.png";
	}
	
	//
	bubble += '<div class="p clearfix">'+locationContact+'</div>';
	
	//	define GDirection DOM
	// The info window version with the "to here" form open
    to_direction[index] = bubble +
	'<div class="p clearfix">'+
		'<p>Directions: '+
			'<strong>To here</strong> - <a href="javascript:fromhere('+index+')">From here</a>'+
		'</p>'+
	'</div>'+
	'<div class="p clearfix">'+
		'<form id="gmap-getDirection" action="javascript:getDirections($F($(\'saddr\')),$F($(\'daddr\')));">'+
			'<div class="rowb">'+
				'<label for="saddr">Start address:</label>'+
				'<input type="text" size="20" maxlength="200" name="saddr" id="saddr" value="" />'+
				'<input type="hidden" id="daddr" value="'+locationLabel+", "+locationAdress+"@"+ point.lat() + ',' + point.lng() + '" />'+
			'</div>'+
			'<div class="rowb-button">'+
		    	'<div class="description"></div>'+
		    	'<div class="select-button-bar clearfix"><a class="generic-button" href="javascript:submitForm(\'gmap-getDirection\');"><span><span>get direction</span></span></a></div>'
		    	'<div class="rowclear"></div>'+
		    '</div>'+
		'</form>'+
	'</div>';
    // The info window version with the "from here" form open
    from_direction[index] = bubble +
    	'<div class="p clearfix">'+
    		'<p>Directions: '+
    			'<a href="javascript:tohere('+index+')">To here</a> - <strong>From here</strong>'+
    		'</p>'+
    	'</div>'+
    	'<div class="p clearfix">'+
    		'<form id="gmap-getDirection" action="javascript:getDirections($F($(\'saddr\')),$F($(\'daddr\')));">'+
				'<div class="rowb">'+
					'<label for="daddr">End address:</label>'+
					'<input type="text" size="20" maxlength="200" name="daddr" id="daddr" value="" />'+
					'<input type="hidden" id="saddr" value="'+locationLabel+", "+locationAdress+"@"+ point.lat() + ',' + point.lng() + '" />'+
				'</div>'+
				'<div class="rowb-button">'+
			    	'<div class="description"></div>'+
			    	'<div class="select-button-bar clearfix"><a class="generic-button" href="javascript:submitForm(\'gmap-getDirection\');"><span><span>get direction</span></span></a></div>'
			    	'<div class="rowclear"></div>'+
			    '</div>'+
			'</form>'+
		'</div>';
			
    // The inactive version of the direction info
    bubble = bubble +
    	'<div class="p clearfix">'+
    		'<p>Directions: '+
    			'<a href="javascript:tohere('+index+')">To here</a> - <a href="javascript:fromhere('+index+')">From here</a>'+
    		'</p>'+
    	'</div>';
	
	
	// Set up our GMarkerOptions object
	markerOptions = { icon:letteredIcon };
	var marker = new GMarker(point, markerOptions);
	
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml('<div style="height:130px;">'+bubble+'</div>');
	});
		
	
	//GEvent.addListener(marker, "infowindowopen", function() {
		//if(map.getZoom() < 10) map.setCenter(marker.getLatLng(), 10);
	//});
	
	// save the info we need to use later for the location-list
    gmarkers.push(marker);
    bubbleHTMLs[index] = '<div style="height:130px;">'+bubble+'</div>';
    // add a line to the locations_list_html
//    locations_list_html += "<h4>"+marker_nr+") "+locationLabel+"</h4>";
//    locations_list_html += '<p><a class="teaser" href="javascript:myclick(' + (gmarkers.length-1) + ')">' + locationAdress + ' <img src="../../framework/_resources/css/core/img/icon-link.gif"/><\/a></p>';
//    locations_list_html += locationContact;

	return marker;
}
// ===== request the directions =====
function getDirections(startAdress, endAdress) {
	document.getElementById('direction-description').innerHTML = "";
	// ==== Set up the walk and avoid highways options ====
	var opts = {};
	if (document.getElementById("walk") && document.getElementById("walk").checked) {
		opts.travelMode = G_TRAVEL_MODE_WALKING;
	}
	if (document.getElementById("highways") && document.getElementById("highways").checked) {
		opts.avoidHighways = true;
	}
	// ==== set the start and end locations ====
	gdir.load("from: "+startAdress+" to: "+endAdress, opts);

	document.getElementById('map-result-route').style.display = "block";
}

/*
 *	sector - division dropdown
*/
function setDivision(sector)
{
	//	delete current values except "all"
	var field = $('division').options;
	field.length = 1;
	if(sector == 0)
	{
		var array = new Array();
		divisionArray['Corporate'].each(function(item){
			array.push(item);
		});
			divisionArray['Energy'].each(function(item){
			array.push(item);
		});
			divisionArray['Healthcare'].each(function(item){
			array.push(item);
		});
			divisionArray['Industry'].each(function(item){
			array.push(item);
		});
			divisionArray['Other Businesses'].each(function(item){
			array.push(item);
		});
		array = array.uniq();
		array.sort();
		array.each(function(item){
			var option = new Option(item, item, false, false);
			field[field.length]=option;
		});
		
	}
	else
	{
		divisionArray[sector].each(function(item){
			var option = new Option(item, item, false, false);
			field[field.length]=option;
		});
	}
}
