//This file created by Barry Hunter www.nearby.org.uk (c) July 2007
// Modified for CNGPrices.com November 2007, credit to Barry and nearby.ork.uk

var addressMarker;

//the ajax request object
var request, req;

//the 'dafault' icon
// These are for cngprices.com only
var baseIcon;
var grayIcon;
var blackIcon;

// Other sites use these icons
var newIcons = new Array();
var oldIcons = new Array();
var badIcons = new Array();

var isCNGPrices = 0;

// The ID of the current info window
var infoWindowID = -1;

var fuelTypeEnum = {cng:0, e85:1, hydrogen:2, lng:3, lpg:4, electric:5, bd:6 };
var fuelNameArray = new Array("CNG - Compressed Natural Gas", "E85 Ethanol", "Hydrogen", 
	"LNG - Liquefied Natural Gas", "LPG - Liquefied Propane Gas",
	"Electric Charging Station", "Biodiesel");
var default_fuel_type = 0;

//array of markers so we can keep track of which to remove
var marks = new Array();

//shortcut to the message div
var m;
var route; // shortcut to route area (in route results)

//is the a fetch in progress?
var running = false;

// For directions
var startLatLng, endLatLng;

//these are for zoomin optimization (if prev zoom had all markers then no need to load them again for zooming in)
var prevZoom = -1;
var shownall = false;
var sentBounds = '';


// the icon maker for cngprices.com
function makeCNGIcons() {
  //this is the 'default' icon to load
  baseIcon = new GIcon();
  grayIcon = new GIcon();
  blackIcon = new GIcon();

  baseIcon.image = "images/red_box_arrow_37_18.png";
  blackIcon.iconSize = grayIcon.iconSize = baseIcon.iconSize = new GSize(37, 18);
  blackIcon.iconAnchor = grayIcon.iconAnchor = baseIcon.iconAnchor = new GPoint(18, 18);
  blackIcon.infoWindowAnchor = grayIcon.infoWindowAnchor = baseIcon.infoWindowAnchor = new GPoint(42, 0);
  blackIcon.labelAnchor = grayIcon.labelAnchor = baseIcon.labelAnchor = new GPoint( -16, -26 );
  
  grayIcon.image = "images/uglyred_icon_37_21.png";
  blackIcon.image = "images/black_icon_37_21.png";
}

// The icon maker for the other sites
function makeIcons()
{
	// newIcons contains icons for pricing that is good
	// oldIcons contains icons for pricing that is more than 30 days old
	// badIcons contains icons for stations that are not functioning

	// It would be nice if all the icons were the same, then we could just have some
	// loops here, but all the icons are a bit different, so we have some work to do.
	for( i=0; i < 7; i++ )
		{ newIcons[i] = new GIcon(); oldIcons[i] = new GIcon(); badIcons[i] = new GIcon(); }

	newIcons[fuelTypeEnum.cng].image = "icons/cng_price.png";
	badIcons[fuelTypeEnum.cng].image = "icons/cng_bad.png";
	badIcons[fuelTypeEnum.cng].iconSize = newIcons[fuelTypeEnum.cng].iconSize = new GSize( 50, 25 );
	badIcons[fuelTypeEnum.cng].iconAnchor = newIcons[fuelTypeEnum.cng].iconAnchor = new GPoint( 25, 25 );
	badIcons[fuelTypeEnum.cng].infoWindowAnchor = newIcons[fuelTypeEnum.cng].infoWindowAnchor = new GPoint( 45, 9 );
	badIcons[fuelTypeEnum.cng].labelAnchor = newIcons[fuelTypeEnum.cng].labelAnchor = new GSize(-16, -27);

	newIcons[fuelTypeEnum.lng].image = "icons/lng_price.png";
	badIcons[fuelTypeEnum.lng].image = "icons/lng_bad.png";
	badIcons[fuelTypeEnum.lng].iconSize = newIcons[fuelTypeEnum.lng].iconSize = new GSize( 50, 25 );
	badIcons[fuelTypeEnum.lng].iconAnchor = newIcons[fuelTypeEnum.lng].iconAnchor = new GPoint( 25, 25 );
	badIcons[fuelTypeEnum.lng].infoWindowAnchor = newIcons[fuelTypeEnum.lng].infoWindowAnchor = new GPoint( 55, 0 );
	badIcons[fuelTypeEnum.lng].labelAnchor = newIcons[fuelTypeEnum.lng].labelAnchor = new GSize( -16, -27 );

	newIcons[fuelTypeEnum.lpg].image = "icons/lpg_price.png";
	badIcons[fuelTypeEnum.lpg].image = "icons/lpg_bad.png";
	badIcons[fuelTypeEnum.lpg].iconSize = newIcons[fuelTypeEnum.lpg].iconSize = new GSize( 50, 25 );
	badIcons[fuelTypeEnum.lpg].iconAnchor = newIcons[fuelTypeEnum.lpg].iconAnchor = new GPoint( 25, 25 );
	badIcons[fuelTypeEnum.lpg].infoWindowAnchor = newIcons[fuelTypeEnum.lpg].infoWindowAnchor = new GPoint( 55, 0 );
	badIcons[fuelTypeEnum.lpg].labelAnchor = newIcons[fuelTypeEnum.lpg].labelAnchor = new GSize( -16, -27 );

	newIcons[fuelTypeEnum.hydrogen].image = "icons/h2_price.png";
	badIcons[fuelTypeEnum.hydrogen].image = "icons/h2_bad.png";
	badIcons[fuelTypeEnum.hydrogen].iconSize = newIcons[fuelTypeEnum.hydrogen].iconSize = new GSize( 37, 18 );
	badIcons[fuelTypeEnum.hydrogen].iconAnchor = newIcons[fuelTypeEnum.hydrogen].iconAnchor = new GPoint( 18, 18 );
	badIcons[fuelTypeEnum.hydrogen].infoWindowAnchor = newIcons[fuelTypeEnum.hydrogen].infoWindowAnchor = new GPoint( 42, 0 );
	badIcons[fuelTypeEnum.hydrogen].labelAnchor = newIcons[fuelTypeEnum.hydrogen].labelAnchor = new GSize( -15, -24 );

	newIcons[fuelTypeEnum.electric].image = "icons/electric_price.png";
	badIcons[fuelTypeEnum.electric].image = "icons/electric_bad.png";
	badIcons[fuelTypeEnum.electric].iconSize = newIcons[fuelTypeEnum.electric].iconSize = new GSize( 18, 18 );
	badIcons[fuelTypeEnum.electric].iconAnchor = newIcons[fuelTypeEnum.electric].iconAnchor = new GPoint( 9, 18 );
	badIcons[fuelTypeEnum.electric].infoWindowAnchor = newIcons[fuelTypeEnum.electric].infoWindowAnchor = new GPoint( 23, 0 );
	badIcons[fuelTypeEnum.electric].labelAnchor = newIcons[fuelTypeEnum.electric].labelAnchor = new GSize( -15, -24 );

	newIcons[fuelTypeEnum.e85].image = "icons/e85_price.png";
	badIcons[fuelTypeEnum.e85].image = "icons/e85_bad.png";
	badIcons[fuelTypeEnum.e85].iconSize = newIcons[fuelTypeEnum.e85].iconSize = new GSize( 40, 18 );
	badIcons[fuelTypeEnum.e85].iconAnchor = newIcons[fuelTypeEnum.e85].iconAnchor = new GPoint( 20, 18 );
	badIcons[fuelTypeEnum.e85].infoWindowAnchor = newIcons[fuelTypeEnum.e85].infoWindowAnchor = new GPoint( 45, 0 );
	badIcons[fuelTypeEnum.e85].labelAnchor = newIcons[fuelTypeEnum.e85].labelAnchor = new GSize( -15, -24 );

	newIcons[fuelTypeEnum.bd].image = "icons/bd_price.png";
	badIcons[fuelTypeEnum.bd].image = "icons/bd_bad.png";
	badIcons[fuelTypeEnum.bd].iconSize = newIcons[fuelTypeEnum.bd].iconSize = new GSize( 40, 18 );
	badIcons[fuelTypeEnum.bd].iconAnchor = newIcons[fuelTypeEnum.bd].iconAnchor = new GPoint( 20, 18 );
	badIcons[fuelTypeEnum.bd].infoWindowAnchor = newIcons[fuelTypeEnum.bd].infoWindowAnchor = new GPoint( 45, 0 );
	badIcons[fuelTypeEnum.bd].labelAnchor = newIcons[fuelTypeEnum.bd].labelAnchor = new GSize( -15, -24 );

	// Temporarily point other icons to new icons
	for( i = 0; i < 7; i++ )
		{ oldIcons[i] = newIcons[i]; }
}


function showAddress(address) {
	if (geocoder) {
		geocoder.getLatLng(address,function(point) {
			if (!point) {
				alert("Your entry '" + address + "' could not be geocoded, please try again");
			} else {
				if (addressMarker) {
					map.removeOverlay(addressMarker);
				}
				addressMarker = new GMarker(point);
				map.setCenter(point, 12);
				map.addOverlay(addressMarker);
				}
			});
	}
}

function formatCurrency(num) {
        num = num.toString().replace(/\$|\,/g,'');
        if(isNaN(num))
                num = "0";
        sign = (num == (num = Math.abs(num)));
        num = Math.floor(num*100+0.50000000001);
        cents = num%100;
        num = Math.floor(num/100).toString();
        if(cents<10)
        cents = "0" + cents;
        for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.substring(0,num.length-(4*i+3))+','+
        num.substring(num.length-(4*i+3));
        return (((sign)?'':'-') + num + '.' + cents);
}

function createMarkerD(pointData, isRoute, whichStation ) {
   var labelText;
    if( isRoute == 1 )
		labelText = whichStation;
	else if( pointData.fuelType != "ELEC" )
	{
    	if ( pointData.price < 0 ){
    	  labelText = pointData.currency + "?";
    	} else {
      		labelText = pointData.currency + formatCurrency(pointData.price);// '$' + Math.round( pointData.price*100)/100;
	    }
	}
	else // if electric, no label
		labelText = "";
 
   var myIcon;
   var iconString = "";
   var iconWidth, iconHeight;
   
   if( isCNGPrices == 1 )
   {
		if( pointData.old == 1 ) { myIcon = grayIcon; } else { myIcon = baseIcon; }
		if( pointData.working == 0 ) { myIcon = blackIcon; }

    	opts = {
      		"icon": myIcon,
      		"clickable": true,
      		"labelText": labelText,
      		"labelOffset": new GSize(-16, -26)
    	};
    }
    else // all other sites
    {
	   // Check the fuel type
	   switch( pointData.fuelType )
	   {
		case "CNG":
			whichIcon = fuelTypeEnum.cng;
			iconString = "icons/cng_icon_27_18.png"; iconWidth = 27; iconHeight = 18;
			break;
		case "LNG":
			whichIcon = fuelTypeEnum.lng;
			iconString = "icons/lng_icon_27_19.png"; iconWidth = 27; iconHeight = 19;
			break;
		case "LPG":
			whichIcon = fuelTypeEnum.lpg;
			iconString = "icons/lpg_icon_27_17.png"; iconWidth = 27; iconHeight = 17;
			break;
		case "HY":
			whichIcon = fuelTypeEnum.hydrogen;
			iconString = "icons/h2_icon_23_18.png"; iconWidth = 23; iconHeight = 18;
			break;
		case "ELEC":
			whichIcon = fuelTypeEnum.electric;
			iconString = "icons/electric_icon_18_18.png"; iconWidth = 18; iconHeight = 18;
			break;
		case "E85":
			whichIcon = fuelTypeEnum.e85;
			iconString = "icons/e85_icon_27_16.png"; iconWidth = 27; iconHeight = 16;
			break;
		case "BD":
			whichIcon = fuelTypeEnum.bd;
			iconString = "icons/bd_icon.png"; iconWidth = 13; iconHeight = 19;
			break;
		default: whichIcon = fuelTypeEnum.cng;
	   }
	
	   labelClass = "LabeledMarker_markerLabel";
	   if( pointData.old == 1 ) { myIcon = newIcons[whichIcon]; labelClass = "LabeledMarker_old"; }
		else { myIcon = newIcons[whichIcon]; }
	   if( pointData.working == 0 ) {
	   		if( pointData.fuelType == "ELEC" ) 
	   			{ myIcon = badIcons[whichIcon]; }
	   		else 
	   			{if( isRoute == 0 )
	   				{myIcon = newIcons[whichIcon]; labelText = '--&nbsp;X&nbsp;--'; }
	   			else
	   				{myIcon = newIcons[whichIcon]; labelText = '- ' + labelText + ' -';}
	   			}
	   		}
	
		var opts = {
		  "icon": myIcon,
		  "clickable": true,
		  "labelText": labelText,
		  "labelClass": labelClass,
		  "labelOffset": new GSize(myIcon.labelAnchor.width, myIcon.labelAnchor.height)
		};
    }
    
    var marker = new LabeledMarker( pointData, opts );
	//var marker = new GMarker( pointData );
	var finalString = '';

	countryString = '';
	if( pointData.country.indexOf( 'USA' ) == -1 )
	{
		countryString = ' ' + pointData.country;
	}

	html = '<a href="http://maps.google.com/maps?f=q&q=' +
                escape(pointData.address + countryString) + '" target="_blank" ' +
		'alt="Show on Google maps in a new window"' +
		'title="Show on Google maps in a new window">';

   var priceString = "";
   var payment = "";

	var preText, flagText;
	if( pointData.working == 0 )
		{ preText = 'This station is <b>not operational</b> (reported ' + pointData.workingDate + ')<br/>';
		  if( pointData.reasonDown.length > 3 ) preText = preText + 'Reason down: ' + pointData.reasonDown + '<br/>';
		  flagText = 'Click here if this station is operational again.'; }
	else
		{ preText = 'This station is operational as of ' + pointData.workingDate + '<br/>';
		  flagText = 'Click here if this station is not operational'; }
	
	var flagForm = preText + '<a href="update_flag.php?id=' + pointData.id + 
		'&name=' + escape( pointData.name ) + '&address=' + escape( pointData.address ) +
		 '&currentlyWorking=' + pointData.working + '">' + flagText + '</a>';

	if( pointData.fuelType != "ELEC" )
	{
        var formString = '<form name="update" action="update_price.php">' +
                '<input type="hidden" name="name" value="' + pointData.name + '">' +
                '<input type="hidden" name="id" value="' + pointData.id + '">' +
                '<input type="hidden" name="address" value="' + pointData.address + '">' +
                '<input type="hidden" name="price" value="' + pointData.price + '">' + pointData.currency +
                '<input style="margin-top: 3px; font-family: Arial; border: 1px solid #333333; background: #eeeeee; color:#222222; font-size: 8pt;" type="text" name="newPrice" size="6">&nbsp;' +
				'per ' + pointData.units + '&nbsp;' + 
                '<input type="submit" style="margin-top: 3px; font-size: 8pt; font-family:Arial;" value="Update price">' +
                '</form>';

        if( pointData.price > 0 )
        {
        	if( isCNGPrices == 1 )
        	{
				 priceString = '<p> <a href="convert.php?price=' + pointData.price +
				'&unitsStart=' + pointData.units + '&currencyStart=' + pointData.currency +
				'" alt="Convert currency and units" title="Convert currency and units" target="_">' +
				pointData.currency + formatCurrency(pointData.price) + '</a> per ' + pointData.units +
				' (Updated <a href="history.php?id=' + pointData.id +
				'" target="_blank" alt="View price history for this station" title="View price history for this station">' +
				pointData.date + '</a>)</p><p>Have a newer price?</p>' + formString;
			}
			else
        	{
				 priceString = '<p>' + pointData.currency + formatCurrency(pointData.price) + '</a> per ' + pointData.units +
				' (Updated <a href="history.php?id=' + pointData.id +
				'" target="_blank" alt="View price history for this station" title="View price history for this station">' +
				pointData.date + '</a>)</p><p>Have a newer price?</p>' + formString;
			}
			
        }
        else
        {
                priceString = '<p>The price is unknown. Do you know the price?</p> ' + formString;
        }

        var payment = "";
        if( pointData.payment.indexOf( 'Cash' ) == -1 && pointData.payment.indexOf( 'aster' ) == -1 )
        {
                payment = "<p>This station may require special forms of payment.</p>";
        }

	} // end if !electric
	
	var cardKey = "";
	if( pointData.access.indexOf( 'card key' ) != -1 )
	{
			cardKey = "<p>This station may require card key access.</p>";
	}

	var divString;
	if( pointData.working == 0 )
		{ divString = '<div id="info-window" style="background:#ffcccc"><p style="font-size: 14px; color:red;">Station not operational</p>'; }
		else { divString = '<div id="info-window">'; }

	if( isCNGPrices )
	{
		finalString =  divString + '<div id="info-window"><h3>' + pointData.name + '&nbsp;&nbsp;</h3>' +
		  html +
		  '<p>'+pointData.address+ countryString + '</a></p>' +
		  '<p>' + pointData.phone + '</p>' + cardKey + payment +
		  priceString + flagForm + '</div>'
	}
	else
	{
		finalString =  divString + 
			'<img src="' + iconString + '" width="' + iconWidth + 
			'" height = "' + iconHeight + '" align="left">&nbsp;' +
			fuelNameArray[whichIcon] + '<br/>' +  
			'<h3>' + pointData.name + '&nbsp;&nbsp;</h3>' +
			html +
			'<p>'+pointData.address+'</a></p>' +
			'<p>' + pointData.phone + '</p>' + cardKey + payment +
			priceString + flagForm + '</div>'
	}

	var estimateWidth = 230; // Minimum width of comments field. This must be estimated
	if( pointData.name.length > 40 )
	{
		estimateWidth = estimateWidth + 9 * (pointData.name.length-40);
	}

	var commentString = 'Comment';
	if( pointData.commentCount == 1 ) { commentString = pointData.commentCount + ' ' + commentString; }
	else if( pointData.commentCount > 1 ) { commentString = pointData.commentCount + ' ' + commentString + 's'; }
	else { commentString = commentString + 's'; }

	GEvent.addListener(marker, "click", function() {
		infoWindowID = pointData.id;
		//finalString = finalString + '<p>' + Math.random() + '</p>';
		marker.openInfoWindowTabsHtml([new GInfoWindowTab('Location',finalString), new GInfoWindowTab(commentString,'<div id="info-comment" style="width:' + estimateWidth + 'px;">'+pointData.comment+'</div>')]);
	});

	return marker;
} // end funciton createmarkerd

function getFuelTypes()
{
	fuel_counter = 0;
	if( document.fuel_type && document.fuel_type.fuel_radio )
	{
		for( var i = 0; i < document.fuel_type.fuel_radio.length; i++ )
		{
			if( document.fuel_type.fuel_radio[i].checked )
			{
				switch( document.fuel_type.fuel_radio[i].value )
				{
					case "bd": fuel_counter += 64; break;
					case "cng": fuel_counter += 1; break;
					case "hydrogen": fuel_counter += 4; break;
					case "e85": fuel_counter += 2; break;
					case "lng": fuel_counter += 8; break;
					case "lpg": fuel_counter += 16; break;
					case "electric": fuel_counter += 32; break;
					default: break;
				}
			}
		}
	}
	else if( document.fuel_type )
	{
		if( document.fuel_type.cng && document.fuel_type.cng.checked ) { fuel_counter += 1; }
		if( document.fuel_type.e85 && document.fuel_type.e85.checked ) { fuel_counter += 2; }
		if( document.fuel_type.hydrogen && document.fuel_type.hydrogen.checked ) { fuel_counter += 4; }
		if( document.fuel_type.lng && document.fuel_type.lng.checked ) { fuel_counter += 8; }
		if( document.fuel_type.lpg && document.fuel_type.lpg.checked ) { fuel_counter += 16; }
		if( document.fuel_type.electric && document.fuel_type.electric.checked ) { fuel_counter += 32; }
		if( document.fuel_type.bd && document.fuel_type.bd.checked ) { fuel_counter += 64; }
	}

	// need to have default fuel type for sites with one fuel only
	if( fuel_counter == 0 ) fuel_counter = default_fuel_type;
	return fuel_counter;
}

function selectAllFuels( selectHow )
{
	if( document.fuel_type )
	{
		if( document.fuel_type.cng ) document.fuel_type.cng.checked = selectHow;
		if( document.fuel_type.e85 ) document.fuel_type.e85.checked = selectHow;
		if( document.fuel_type.hydrogen ) document.fuel_type.hydrogen.checked = selectHow;
		if( document.fuel_type.lng ) document.fuel_type.lng.checked = selectHow;
		if( document.fuel_type.lpg ) document.fuel_type.lpg.checked = selectHow;
		if( document.fuel_type.electric ) document.fuel_type.electric.checked = selectHow;
		if( document.fuel_type.bd ) document.fuel_type.bd.checked = selectHow;
	}
	update_map_fuel_check();
}

function update_map_fuel_check()
{
	update_mapD();
}

function displayIconInfo()
{
	this.iconString = '';
	this.iconWidth = 0;
	this.iconHeight = 0;
}

function getDisplayIconPath( fuelType )
{
	var returnValue = new displayIconInfo();
	
   // Check the fuel type
   switch( fuelType )
   {
	case "CNG":
		returnValue.iconString = "icons/cng_icon_27_18.png"; returnValue.iconWidth = 27; returnValue.iconHeight = 18;
		break;
	case "LNG":
		returnValue.iconString = "icons/lng_icon_27_19.png"; returnValue.iconWidth = 27; returnValue.iconHeight = 19;
		break;
	case "LPG":
		returnValue.iconString = "icons/lpg_icon_27_17.png"; returnValue.iconWidth = 27; returnValue.iconHeight = 17;
		break;
	case "HY":
		returnValue.iconString = "icons/h2_icon_23_18.png"; returnValue.iconWidth = 23; returnValue.iconHeight = 18;
		break;
	case "ELEC":
		returnValue.iconString = "icons/electric_icon_18_18.png"; returnValue.iconWidth = 18; returnValue.iconHeight = 18;
		break;
	case "E85":
		returnValue.iconString = "icons/e85_icon_27_16.png"; returnValue.iconWidth = 27; returnValue.iconHeight = 16;
		break;
	case "BD":
		returnValue.iconString = "icons/bd_icon.png"; returnValue.iconWidth = 13; returnValue.iconHeight = 19;
		break;
   }
   
   return returnValue;
}

function createRouteText( pointData, whichPoint )
{
	var textArray = new Array();
	var downReason = "";
	var i = 0;

	var countryString = '';
	if( pointData.country.indexOf( 'USA' ) == -1 )
	{
		countryString = ' ' + pointData.country;
	}


	textArray[i++] = '<tr class="border_table"><td class="border_table"><span id="station_number">' + whichPoint + '</span></td>';
	textArray[i++] = '<td class="border_table">' 
		+ '<a href="http://maps.google.com/maps?f=q&q=' +
		escape( pointData.address + countryString ) + '" border="0" target="_blank">' + 
		'<img src="mini_maps/' + pointData.id + '.png" border="0" width="120" height="120"></a></td>';
	textArray[i++] = '<td class="border_table">';
	if( pointData.working == 0 )
	{
		if( pointData.reasonDown.length > 3 ) downReason = "(" + pointData.reasonDown + ")";
		textArray[i++] = "This station is currently marked as <strong>not working</strong>" + downReason + "<br/>";
	}

	if( isCNGPrices == 0 )
	{
		iconInfo = getDisplayIconPath( pointData.fuelType );
		textArray[i++] = '<img src="' + iconInfo.iconString + '" width="' + iconInfo.iconWidth + 
			'" height = "' + iconInfo.iconHeight + '" align="left">&nbsp;';		
	}

	if( pointData.price > 0 )
		textArray[i++] = '(' + pointData.currency + formatCurrency(pointData.price) + '</a> per ' + pointData.units + ") ";

	textArray[i++] ="<strong>" + pointData.name + "</strong>";
	if( pointData.phone.length > 3 )
		textArray[i++] = " (" + pointData.phone + ")";
	textArray[i++] = "<br/>" + pointData.address + countryString;
	textArray [i++] = ' (GPS: ' + pointData.lat().toFixed(5) + ', ' + pointData.lng().toFixed(5) + ')';

	if( pointData.payment.length > 3 )
		textArray[i++] = "<br/>Payment: " + pointData.payment;
	if( pointData.directions &&  pointData.directions.length > 5 )
	{
		textArray[i++] = "<br/><strong>Directions:</strong> " + pointData.directions;
	}

	if( pointData.distanceFromLastStation )
	{
		if( whichPoint > 1 ) theText = "previous station: "; else theText = "starting location: ";
		textArray[i++] = "<br/>Distance from " + theText + Math.round( pointData.distanceFromLastStation/1000*0.62137 + 0.5) +
			" miles (" + Math.round( pointData.distanceFromLastStation/1000 + 0.5 ) + " km)";
	}

	if( pointData.distanceToEnd )
	{
		textArray[i++] = "<br/>Distance to end location: " + Math.round( pointData.distanceToEnd/1000*0.62137 + 0.5) +
			" miles (" + Math.round( pointData.distanceToEnd/1000 + 0.5 ) + " km)";
	}

/*	if( pointData.commentCount > 0 )
	{
		textArray[i++] = '<div id="noprint"><div id="routeComment">'
			+ pointData.comment + '</div></div>';
	} */

	textArray[i++] = "</td></tr>";

	returnString = textArray.join("");

	return returnString;
}

function update_mapD() {
	if (running) {
		request.abort();
		running = false;
	}
	if (shownall == false || map.getZoom() >= prevZoom) {
		var bounds = map.getBounds();

		var center = map.getCenter();
		var zoom = map.getZoom();
		
		sentBounds = bounds.toString()
		//alert( sentBounds );

		var fuel_types = getFuelTypes();

		//setup links that utalise the current map location
		document.getElementById("datalink").innerHTML = '<a href="http://' +
			location.hostname + 
			'/index.php?bounds='+
			escape(sentBounds)+
			'&feul_type=' + fuel_types + 
			'">Link to this map</a>';

		request = GXmlHttp.create();
		request.open("GET", "dynamicMaps.xml.php?bounds=" + sentBounds + 
			"&fuel_type=" + fuel_types, true);
		
		request.onreadystatechange = processXMLResponse;

		m.innerHTML = "Updating stations...";
		running = true;
		request.send(null);
	}
	prevZoom = map.getZoom();
}

function processXMLResponse() {
			if (request.readyState == 4 && running) {
				var routeTextArray = new Array();
				
				var whichStation = 0;

				//alert(request.responseText);

				//m.innerHTML = "Parsing XML..";
				var xmlDoc = GXml.parse(request.responseText);
				if( !xmlDoc ) {
					m.innerHTML = "Error: no XML doc";
					running = false;
					return;
				}

				if (!xmlDoc.documentElement) {
					m.innerHTML = "Error: Unable to Parse XML";
					running = false;
					return;
				}
				var markers = xmlDoc.documentElement.getElementsByTagName("marker");
				// m.innerHTML = "Marker count: " + markers.length;

				var tooManyMessage = '';
				var validCount = 0;
				var noStations;
				
				var countMain = xmlDoc.documentElement.getElementsByTagName("count");
                                if( countMain && countMain[0] && countMain.length > 0 ) validCount = parseFloat(countMain[0].getAttribute("value"));

				var isRoute = 0;
				var isRouteElement = xmlDoc.documentElement.getElementsByTagName("isroute");
                                if( isRouteElement && isRouteElement[0] && isRouteElement.length > 0 ) isRoute = parseInt(isRouteElement[0].getAttribute("value"));


				if( isRoute == 0 )
					noStations = "No stations. Zoom out or move map to find stations.";
				else
					noStations = "Sorry, there are no stations along your route.";
					
				if( validCount > 150 ) { tooManyMessage = "Too many stations to list. Zoom in for more detail."; }
				//alert("Count: "  +countMain.length + ' Valid count: ' + validCount );

				//flag all current markers as old
				for (i in marks) 
					if (marks[i] != null) 
						marks[i].old = true;

				if( validCount == 0 )
				{
					m.innerHTML = noStations;
					tooManyMessage = noStations;
					//running = false;
					//return;
				}
				else
				{
				//	m.innerHTML = "Adding Markers2...";
					var lastLatLng, maxDistance = 0;

					if( startLatLng ) { lastLatLng = startLatLng; }

					for (var i = 0; i < markers.length; i++)
					{
						id = markers[i].getAttribute("id");
						// m.innerHTML = "ID: " + id;
						if (marks[id] && marks[id] != null)
						{
							//we have this one so lets flag it as valid
							marks[id].old = false;
						}
						else
						{
							lat = markers[i].getAttribute("lat");
							lng = markers[i].getAttribute("lng");
							var point = new GLatLng(parseFloat(lat), parseFloat(lng));

							if( i == 0 && (!startLatLng) ) lastLatLng = point;

							if( lastLatLng )
								point.distanceFromLastStation = point.distanceFrom( lastLatLng );

							if( i == markers.length-1 && (endLatLng) )
							{
								point.distanceToEnd = point.distanceFrom( endLatLng );
								if( point.distanceToEnd > maxDistance )
									maxDistance = point.distanceToEnd;
							}
							
							if( point.distanceFromLastStation > maxDistance )
								maxDistance = point.distanceFrom(lastLatLng);
						
							lastLatLng = point;
							point.id = markers[i].getAttribute("id");
							point.price = markers[i].getAttribute("price");
							point.name = markers[i].getAttribute("name");
							point.directions = markers[i].getAttribute("directions");
							point.address = markers[i].getAttribute("address");
							point.phone = markers[i].getAttribute("phone");
							point.date = markers[i].getAttribute("date");
							point.access = markers[i].getAttribute("access");
							point.payment = markers[i].getAttribute("payment");
							point.old = markers[i].getAttribute("old");
							point.working = markers[i].getAttribute("working");
							point.reasonDown = markers[i].getAttribute("reasonDown");
							point.workingDate = markers[i].getAttribute("workingDate");
							point.country = markers[i].getAttribute("country");
							point.units = markers[i].getAttribute("units");
							point.currency = markers[i].getAttribute("currency");
							point.comment = markers[i].getAttribute("comment");
							point.commentCount = markers[i].getAttribute("commentCount");
							point.fuelType = markers[i].getAttribute("fuelType");
	
							//add any extra fields to this line
							marks[id] = createMarkerD( point, isRoute, whichStation+1 );
							map.addOverlay(marks[id]); 
							if( isRoute == 1 )
								routeTextArray[whichStation++] = createRouteText( point, whichStation );
							
						}
					}
				}
				
				// m.innerHTML = "Removing Old Markers...";
				for (i in marks) 
					if (marks[i] != null) 
						if (marks[i].old == true && i != infoWindowID) {
							map.removeOverlay(marks[i]);
							marks[i] = null; //marks.splice(i,1);
						}

				m.innerHTML = tooManyMessage;

			if( isRoute == 1 )
			{
				maxDistance = maxDistance / 1000; // convert to km
				maxMiles = maxDistance * 0.62137;

				if( maxDistance > 0 )
					distanceText = "<p>Maximum distance between stations is approximately " +
						Math.round(maxMiles+0.5) + " miles ("  + Math.round(maxDistance) + " km) as the crow flies. All distances between stations shown below are also listed as the crow flies and represent the minimum possible driving distance. Please be aware of this as you plan your trip.</p><br/>";
				else
					distanceText = "";

				disclaimerText = "<p>As always with routes, directions, and stations, call ahead to verify hours" +
					" of operation, methods of payment, and the status of the station.</p>";
				disclaimerEnd = "<p>In giving this route and station list, the web site and its operators do not" +
					" give a claim of correctness of the information. Verification of all information given" +
					" on this site is the responsibility of the user.</p>";
				route.innerHTML = '<br/> ' + distanceText + disclaimerText + '<table cellpadding="5" class="border_table">' +
					routeTextArray.join("") + '</table>'  + disclaimerEnd;
				} // isRoute == 1

				running = false;
			}
		}//end function


function add_route_overlay() {
         if( firstUpdate == 1 ) {
			firstUpdate = 0;
			var myLine = directions.getPolyline();
			var vertexCount = myLine.getVertexCount();
			var indexArray = new Array();
			var i=0;

			var increment;
			if( vertexCount < 50 ) increment = 1; else if( vertexCount < 500 ) increment = 10; else increment = 20;

			var tempLineArray = new Array();
			for( var j=0; j < vertexCount; j+=increment ) // only do portion of the vertices - it still works!
			{
					curLatLng = myLine.getVertex(j);
					indexArray[i++] = curLatLng.toUrlValue(4) + "T"; // T is as good as any delimiter
			}

			// Now join them
			vertexString = "vertices=" + indexArray.join("");


		// Add the fuel type string
		var fuel_types = route_fuel_types;
		
		vertexString = vertexString + "&fuel_type=" + fuel_types;
		
                // Great, this is all working. Now let's pass it to the parser
                 // Create Google XmlHttpRequest object
		// request is a global variable
		 request = GXmlHttp.create();

		 request.open("POST", "processRoute.xml.php", true);

		 request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		 request.setRequestHeader("Content-length", vertexString.length+10);
		 request.setRequestHeader("Connection", "close");

		// request.onreadystatechange = function () {};	
		 request.onreadystatechange = processXMLResponse;

		running = true;
		m.innerHTML = "Updating stations...";

		request.send( vertexString );
        }
} // end of function
