// Declare variables for later use
var map;
var gdir;
var newMarkers = [];
var latLngs = [];
var icons = [];
var markers = new Array();
var centerLatitude;
var centerLongitude;
var fromaddress;
var units=1609;

function initialize() 
{
	mapDiv = document.getElementById('map_canvas');
	if (!GBrowserIsCompatible())
	{
		mapDiv.innerHTML = 'Sorry, your browser isn\'t compatible with Google Maps.';
	}
	else
	{
		var options = {backgroundColor: '#D7D5E3',mapTypes: [G_NORMAL_MAP, G_SATELLITE_MAP, G_HYBRID_MAP, G_PHYSICAL_MAP]};

		map = new GMap2(document.getElementById("map_canvas"),options);
		//gdir = new GDirections(map, document.getElementById("directions"));
		gdir = new GDirections(map);
		//GEvent.addListener(gdir, "error", handleErrors);
		GEvent.addListener(gdir,"error", function() { alert("Directions Failed: "+gdir.getStatus().code); });


		GEvent.addListener(gdir, "addoverlay", onGDirectionsAddOverlay); // Triggers marker swap

		GEvent.addListener(gdir,"load", function() {
			setTimeout('customPanel(map,"map",gdir,document.getElementById("directions"))', 1);
		});

		//map.enableContinuousZoom();
		// Add the standard map controls
		map.addControl(new GLargeMapControl());
		//map.addControl(new GScaleControl());
		//map.addControl(new GOverviewMapControl());
		map.addControl(new GMapTypeControl());
		//if the city name is known based on IP address then route to nearest station as sample 
		if (fromaddress!="") 
		setDirections(fromaddress, toAddress, lang);
		else //show sample on driving direction if city name not known.
		setDirections("San Francisco", "Mountain View", lang);

		filter1 = document.getElementById('filter_container');
		filter2 = document.getElementById('filter_show');
		//load stored cookies for filter
		setfromCookie();
		summarizeFilter();

		// Attach events to refresh the marker display whenever the map moves
		GEvent.addListener(map, 'moveend', mapMoveEnd);
		GEvent.addListener(map, 'zoomend', mapZoomEnd);

		map.addControl(new PromoControl());
//console.info('getcookie',getCookie('units'));
		if (getCookie('units')) 
		{
			//document.getElementById('thelang').value =getCookie('units');
			if (getCookie('units')==1000) 
				document.getElementById('km').selected=true
			else
				document.getElementById('miles').selected=true
		}
		else
		{
			if (units==1000) 
				document.getElementById('km').selected=true
			else
				document.getElementById('miles').selected=true
		}

		
	}
}



var PromoControl = function() {};
  
PromoControl.prototype = new GControl(true);
  
PromoControl.prototype.initialize = function(map) {
	var container = document.createElement("div");
	container.innerHTML = 'Powered by<br>Web Marketing Inc.';
	container.style.width='200px';
	container.style.height='30px';
	container.style.fontSize='9px';
	map.getContainer().appendChild(container);
	return container;
};
  
PromoControl.prototype.getDefaultPosition = function() {
 	return new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(70, 0));
};


function setDirections(fromAddress, toAddress, locale) 
{
	  gdir.load("from: " + fromAddress + " to: " + toAddress, { "locale": locale , "getSteps":true});
}

/*
function handleErrors()
{
	if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
		alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
		alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
		alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_BAD_KEY)
		alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
		alert("Your direction addresses were not found. Please enter additional information.\n Error code: " + gdir.getStatus().code);
	else 
		alert("An unknown error occurred.");
}
*/
  
///////////////////////////////////////////////////////////////////////



// Note the 'addoverlay' GEvent listener inside initialize() function of the original code (above).
// 'load' event cannot be used

function onGDirectionsAddOverlay()
{ 
	// Remove the draggable markers from previous function call.
	for (var i=0; i<newMarkers.length; i++)
	{
		map.removeOverlay(newMarkers[i]);
	}

	// Loop through the markers and create draggable copies
	for (var i=0; i<=gdir.getNumRoutes(); i++)
	{
		var originalMarker = gdir.getMarker(i);
		latLngs[i] = originalMarker.getLatLng();
		icons[i] = originalMarker.getIcon();
		newMarkers[i] = new GMarker(latLngs[i],{icon:icons[i], draggable:true, title:'Draggable'});
		map.addOverlay(newMarkers[i]);

		// Get the new waypoints from the newMarkers array and call loadFromWaypoints by dragend
		GEvent.addListener(newMarkers[i], "dragend", function(){
			var points = [];
			for (var i=0; i<newMarkers.length; i++)
			{
				points[i]= newMarkers[i].getLatLng();
			}
			gdir.loadFromWaypoints(points, { "locale": lang , "getSteps":true});
			});

		//Bind 'click' event to original markers 'click' event
		copyClick(newMarkers[i],originalMarker);
		// Now we can remove the original marker safely
		map.removeOverlay(originalMarker);
	}

	function copyClick(newMarker,oldMarker)
	{
		GEvent.addListener(newMarker, 'click', function(){
			GEvent.trigger(oldMarker,'click');
			});
  	}
}







function mapMoveEnd()
{
	//refresh the marker display after the map has moved
	var bounds = map.getBounds();
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();
	var getVars = 'ne=' + northEast.toUrlValue()
	+ '&sw=' + southWest.toUrlValue()

	var mapZoom = map.getZoom();
	//log the URL for testing
	//GLog.writeUrl('serverbranded.php?'+getVars);

	//retrieve the points
	var request = GXmlHttp.create();
	request.open('GET', 'serverbranded.php?'+getVars+'&zoom='+mapZoom+filterurl, true);

	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			var jscript = request.responseText;
			var points;
			eval(jscript);

			//create each point from the list
			for (i in points) {
				var point = new GLatLng(points[i].lat,points[i].lng);
				createMarker(point,points[i].d,points[i].a,points[i].c,points[i].s,points[i].z,points[i].p,points[i].type,points[i].lat,points[i].lng,points[i].num);
			}
		}
	}
	request.send(null);

	// Get the map boundary coordinates
	var mapBounds = map.getBounds();
	// Remove markers from display that are no longer visible
	for (var m = markers.length - 1; m >= 0; m--)
		if (!mapBounds.contains(markers[m].getPoint()))
		     removeDataPoint(m);


 
};



function createMarker(point, dba, address,city,state,zip,phone,type,lat,lng,num) 
{
	//console.info(markers);
	//check to see if the marker is already there
	for (var m = markers.length - 1; m >= 0; m--)
	{
		if (markers[m].getPoint().equals(point)) return;
	}
	//must be a new marker
	var thisMarker = new GMarker(point, customIcons[type]);
	markers.push(thisMarker);

	if(type=='c') 
	{
		//cluster handling.
		GEvent.addListener(thisMarker, 'click', 
		function ()
		{
			// Clicking on a cluster zooms the map on its location
			map.setCenter(point, map.getZoom() + 2);
		});
	} 
	else
	{
//GLog.writeUrl(  (encode(dba+"@"+lat+","+lng))   );
		//station handling
		var linkname="home.php?storenum=";
		var html="<span class=bubble><img src='/imag/bubble_" + type + ".png' ><br>"
			+ "<b>"+dba + "</b><br>"
			+ address+ "<br>"
			+ city+","+state+" "+zip+"<br>"
			+ phone+ "<br>"
			+ "<a href=\"planroute.php?"
			+ "fromaddress="+encode(fromaddress)+'&lat='+centerLatitude+'&lng='+centerLongitude
			+ "&toaddress="+(encode(dba+"@"+lat+","+lng))+ "\">"+bubble_getdirection+"</a>"
			+ " - "
			+ "<a href=\"http://www." + type + "stations.com/" + linkname+num+ "\" target="+num+">" +bubble_moreinfo+" &gt;&gt;</a>"
			+ "<br>"
			+ "</span>";
		thisMarker.bindInfoWindowHtml(html, {maxWidth: 350});
		///////////////////////////////////////////////////
		//create a sidebar entry (alongside the map)
		//var sidebarRow = document.createElement('div');
		//sidebarRow.id = point.toUrlValue();
		//sidebarRow.className = 'sidebar_row';
		//sidebarRow.innerHTML = html;
		//sidebar.appendChild(sidebarRow);
		//sidebarRow.onclick = 
		//function ()
		//{	// A click on the sidebar entry triggers a click on its associated marker
		//	GEvent.trigger(thisMarker, "click")
		//};
		///////////////////////////////////////////////////

	}
	// Add the marker to the map
	map.addOverlay(thisMarker);

	return; 
}

function mapZoomEnd(oldZoom, newZoom)
{
	//console.info(markers);
	//console.info('mapzoomend',oldZoom, newZoom);
	//remove map markers when zoom changes
	for (var m = markers.length - 1; m >= 0; m--)
	{
		removeDataPoint(m);
	}
};

function removeDataPoint(m)
{
	// Remove the marker from the map
	map.removeOverlay(markers[m]);
	// Remove the marker from our own array
	markers.splice(m, 1);
	//console.info(markers);
};

function viewChange()
{
  	// viewChange: event handler called when the user has changed the type of data
  	// Remove all current markers from display  
	for (var m = markers.length - 1; m >= 0; m--)
	{
		removeDataPoint(m);
	}

  	// Trigger a refresh of the map to load new data
  	mapMoveEnd();
};

function encode(str) {
	var result = "";
	
	for (i = 0; i < str.length; i++) {
		if (str.charAt(i) == " ") result += "+";
		else result += str.charAt(i);
	}
	return escape(result);
}

function formsubmit(fromadd,toaddress,lang,theunits)
{
	//console.info('theunits',theunits);
	//setDirections(this.fromaddress.value, this.toaddress.value, '$lang' );
	fromaddress=fromadd;
	units=parseFloat(theunits);
	setDirections(fromaddress, toaddress, lang);
	document.getElementById('locator').href = 'locator.php?fromaddress='+encode(fromaddress);  
	document.getElementById('planroute').href = 'planroute.php?fromaddress='+encode(fromaddress);  
	//document.getElementById('thelang').value = theunits;  
	setCookie('units', theunits);
};


///////////////////////////////////////////////////
//  custom direction panel 
///////////////////////////////////////////////////
function customPanel(map,mapname,gdir,div)
{
	var html = "";
       
	// local functions 
 
	// waypoint banner
         function waypoint(point, type, address) {
           var target = '"' + mapname+".showMapBlowup(new GLatLng("+point.toUrlValue(6)+"))"  +'"';
           html += '<table class="waypoint">';
           html += '  <tr class="cursorpoint" onclick='+target+'>';
           html += '    <td class="wpicon">';
           html += '      <img src="http://www.google.com/intl/en_ALL/mapfiles/icon_green'+type+'.png">'
           html += '    </td>';
           html += '    <td class="wpaddress">';
           html +=        address;
           html += '    </td>';
           html += '  </tr>';
           html += '</table>';
         }
 
         // route distance 
         function routeDistance(dist) {
           html += '<div class="routedistance">' + dist + '</div>';
         }      
 
         // step detail 
         function detail(point, num, description, dist) {
           var target = '"' + mapname+".showMapBlowup(new GLatLng("+point.toUrlValue(6)+"))"  +'"';
           html += '<table class="routestep">';
           html += '  <tr class="cursorpoint" onclick='+target+'>';
           html += '    <td class="stepnum">';
           html += '      <a href="javascript:void(0)"> '+num+'. </a>';
           html += '    </td>';
           html += '    <td class="stepdesc">';
           html +=        description;
           html += '    </td>';
           html += '    <td class="stepdist">';
           html +=        dist;
           html += '    </td>';
           html += '  </tr>';
           html += '</table>';
         }
 
          function convert_dist(meters) {
          	output = parseInt(meters,10); 
		if (units == 1000) {
         		if (output > 200) { //was 999
         			output = output / units;
         			name = 'Km'; 
         		}
			else {
				name = 'm';
			}
         	} else if (units == 1609) {
         		if (output > 100) { //was  1608
         			output = output / units;
         			name = 'mi'; 
         		} 
			else {
         			output = output * 3.281;
         			name = 'ft'; 
         		}
         	} 
         	bef = output; 
         	output = Math.round(output*10.0)/10.0;
         	return output+"&nbsp;"+name;
         }
 
         // read through the GRoutes and GSteps 
 
         for (var i=0; i<gdir.getNumRoutes(); i++) {
           if (i==0) {
             var type="A";
           } else {
             var type="pause";
           }
           var route = gdir.getRoute(i);
           var geocode = route.getStartGeocode();
           var point = route.getStep(0).getLatLng();
           // Waypoint at the start of each GRoute
           waypoint(point, type, geocode.address);
           routeDistance(convert_dist(route.getDistance().meters)+" (about "+route.getDuration().html+")");
 
           for (var j=0; j<route.getNumSteps(); j++) {
             var step = route.getStep(j);
             // detail lines for each step 
             detail(step.getLatLng(), j+1, step.getDescriptionHtml(), convert_dist(step.getDistance().meters));
           }
         }
         
         // the final destination waypoint  
         var geocode = route.getEndGeocode();
         var point = route.getEndLatLng();
         waypoint(point, "B", geocode.address);
                  
         // drop the whole thing into the target div
         div.innerHTML = html;
 
} 
///////////////////////////////////////////////////
//  end custom direction panel 
///////////////////////////////////////////////////

