//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
	var iconInfo = new Array();
	
	iconInfo[fuelTypeEnum.cng] = new Array( "cng", new Array(50, 25, 25, 25, 45, 9, 16, 27 ));
	iconInfo[fuelTypeEnum.lng] = new Array( "lng", new Array(50, 25, 25, 25, 55, 0, 16, 27 ));
	iconInfo[fuelTypeEnum.lpg] = new Array( "lpg", new Array(50, 25, 25, 25, 55, 0, 16, 27 ));
	iconInfo[fuelTypeEnum.hydrogen] = new Array( "h2", new Array(37, 18, 18, 18, 42, 0, 15, 24 ));
	iconInfo[fuelTypeEnum.electric] = new Array( "electric", new Array(18, 18, 9, 18, 23, 0, 15, 24 ));
	iconInfo[fuelTypeEnum.e85] = new Array( "e85", new Array(40, 18, 20, 18, 45, 0, 15, 24 ));
	iconInfo[fuelTypeEnum.bd] = new Array( "bd", new Array(40, 18, 20, 18, 45, 0, 15, 24 ));
	
	// 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.
	var t;
	for( i=0; i < 7; i++ )
	{ 
		newIcons[i] = new GIcon(); oldIcons[i] = new GIcon(); badIcons[i] = new GIcon();
		
		newIcons[i].image = "/icons/" + iconInfo[i][0] + "_price.png";
		badIcons[i].image = "/icons/" + iconInfo[i][0] + "_bad.png";

		t = iconInfo[i][1];
		badIcons[i].iconSize = newIcons[i].iconSize = new GSize( t[0], t[1] );
		badIcons[i].iconAnchor = newIcons[i].iconAnchor = new GPoint( t[2], t[3] );
		badIcons[i].infoWindowAnchor = newIcons[i].infoWindowAnchor = new GPoint( t[4], t[5] );
		badIcons[i].labelAnchor = newIcons[i].labelAnchor = new GSize(-t[6], -t[7]);
		
		oldIcons[i] = newIcons[i];
		
		// Some specific stuff for BD
		if( i == fuelTypeEnum.bd )
		{
			var tempIcon = newIcons[i];
			newIcons[i] = new Array();
			for( var bd=0; bd <=5; bd++ )
			{
				newIcons[i][bd] = new GIcon();
				newIcons[i][bd].iconSize = tempIcon.iconSize;
				newIcons[i][bd].iconAnchor = tempIcon.iconAnchor;
				newIcons[i][bd].infoWindowAnchor = tempIcon.infoWindowAnchor;
				newIcons[i][bd].labelAnchor = tempIcon.labelAnchor;
				newIcons[i][bd].image = "/icons/" + iconInfo[i][0] + "_price_" + (bd*20) + ".png";
			}
		}
	}
}

function createMarkerD(pointData, isRoute ) {
 
	var labelText = pointData.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; break;
		case "LNG":	whichIcon = fuelTypeEnum.lng; break;
		case "LPG": whichIcon = fuelTypeEnum.lpg; break;
		case "HY": whichIcon = fuelTypeEnum.hydrogen; break;
		case "ELEC": whichIcon = fuelTypeEnum.electric; break;
		case "E85": whichIcon = fuelTypeEnum.e85; break;
		case "BD": whichIcon = fuelTypeEnum.bd; break;
		default: whichIcon = fuelTypeEnum.cng;
	   }
	
		myIcon = newIcons[whichIcon];
	   labelClass = "LabeledMarker_markerLabel";

	   if( pointData.old == 1 ) { labelClass = "LabeledMarker_old"; }

	   if( pointData.working == 0 ) {
	   		if( pointData.fuelType == "ELEC" ) 
	   			{ myIcon = badIcons[whichIcon]; }
	   		else 
	   			{if( isRoute == 0 )
	   				{labelText = '--&nbsp;X&nbsp;--'; }
	   			else
	   				{labelText = '- ' + labelText + ' -';}
	   			}
	   		}
	   		
	   	if( pointData.fuelType == "BD" )
	   	{
	   		var grade = Math.round(pointData.maxGrade / 20);
	   		myIcon = newIcons[whichIcon][grade];
	   	}
	
		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 finalString = pointData.tabText;
	
	var estimateWidth = 230; // Minimum width of comments field. This must be estimated
	if( pointData.name.length > 40 )
	{
		estimateWidth = estimateWidth + 9 * (pointData.name.length-40) + 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;

		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()
{
	if( document.fuel_type )
	{
		var a = document.getElementById( 'bd_legend' );
		if( a && document.fuel_type.bd && document.fuel_type.bd.checked == true )
			a.style.display = 'inline';
		else
			a.style.display = 'none';
	}
	
	update_mapD();
}

// Next is to add this to my php file instead of my javascript file
function createRouteText( pointData, whichPoint )
{
	var textArray = new Array();
	var i=0;
	
	textArray[i++] = pointData.routeText;
	
	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
		if( document.getElementById("datalink") )
			document.getElementById("datalink").innerHTML = '<a href="http://' +
				location.hostname + 
				'/index.php?bounds='+
				escape(sentBounds)+
				'&fuel_type=' + fuel_types + 
				'">Link to this map</a>';

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

		document.getElementById( "loading_status" ).style.display = 'inline';
		running = true;
		request.send(null);
	}
	prevZoom = map.getZoom();
}


function tc_debug( string )
{
		if( document.getElementById("debug") )
			document.getElementById("debug").innerHTML = "<p>" + string + "</p>";
}

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

				var xmlDoc = GXml.parse(request.responseText);
				if( !xmlDoc ) {
					running = false;
					return;
				}

				if (!xmlDoc.documentElement) {
					running = false;
					return;
				}
				var markers = xmlDoc.documentElement.getElementsByTagName("marker");

				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 debugString = "";
				var d = xmlDoc.documentElement.getElementsByTagName("d");
                                if( d && d[0] && d.length > 0 )
                                	{ debugString = d[0].getAttribute("value"); }
                 tc_debug( debugString );

				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 )
				{
					tooManyMessage = noStations;
				}
				else
				{
					var lastLatLng, maxDistance = 0;

					if( startLatLng ) { lastLatLng = startLatLng; }

					for (var i = 0; i < markers.length; i++)
					{
						id = markers[i].getAttribute("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);
						
							if( isRoute == 1 )
								point.routeText = markers[i].getAttribute("routeText");
								
							lastLatLng = point;
							point.id = markers[i].getAttribute("id");
							point.old = markers[i].getAttribute("old");
							point.name = markers[i].getAttribute("name");
							point.working = markers[i].getAttribute("working");
							point.comment = markers[i].getAttribute("comment");
							point.commentCount = markers[i].getAttribute("commentCount");
							point.fuelType = markers[i].getAttribute("fuelType");
							point.tabText = markers[i].getAttribute("tabText");
							point.labelText = markers[i].getAttribute("labelText");
	
							if( point.fuelType == "BD" )
							{
								point.maxGrade = markers[i].getAttribute("maxGrade");
								point.gradeList = markers[i].getAttribute("gradeList");
								point.grade = markers[i].getAttribute("grade");
							}
								
							marks[id] = createMarkerD( point, isRoute, whichStation+1 );
							map.addOverlay(marks[id]); 
							if( isRoute == 1 )
								routeTextArray[whichStation++] = createRouteText( point );
							
						}
					}
				}
				
				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);
						}

				if( tooManyMessage.length > 0 )
				{
					document.getElementById( 'map_error' ).innerHTML = tooManyMessage;
					document.getElementById( 'map_error' ).style.display = 'inline';
				}
				else
					document.getElementById( 'map_error' ).style.display = 'none';

				document.getElementById( "loading_status" ).style.display = 'none';

			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;
		document.getElementById( "loading_status" ).style.display = 'inline';

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