//-----------------------------------------------------------------------------------------------------------------------
function ShowBlock( Obj ){
        document.getElementById(Obj).style.display = "block";
}
//-----------------------------------------------------------------------------------------------------------------------
function ShowInline( Obj ){
        document.getElementById(Obj).style.display = "inline";
}
//-----------------------------------------------------------------------------------------------------------------------
function Hide( Obj ){
        document.getElementById(Obj).style.display = "none";
}
//-----------------------------------------------------------------------------------------------------------------------
function Disable( Obj ) {
        document.getElementById(Obj).disabled = true;
}
//-----------------------------------------------------------------------------------------------------------------------
function Enable( Obj ) {
        document.getElementById(Obj).disabled = false;
}
//-----------------------------------------------------------------------------------------------------------------------


//map globals

var map;
var stationClickedID = 0;
var gmarker = [];
var numMarkers = 0;
var defaultStationDataText = null;
var StationDataIsShowing = false;

//------------------------------------------------------------------------------------------------------------------------
//start elabel functions
/*
* LabeledMarker Class
*
* Copyright 2007 Mike Purvis (http://uwmike.com)
* 
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* 
*       http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This class extends the Maps API's standard GMarker class with the ability
* to support markers with textual labels. Please see articles here:
*
*       http://googlemapsbook.com/2007/01/22/extending-gmarker/
*       http://googlemapsbook.com/2007/03/06/clickable-labeledmarker/
*/

/**
 * Constructor for LabeledMarker, which picks up on strings from the GMarker
 * options array, and then calls the GMarker constructor.
 *
 * @param {GLatLng} latlng
 * @param {GMarkerOptions} Named optional arguments:
 *   opt_opts.labelText {String} text to place in the overlay div.
 *   opt_opts.labelClass {String} class to use for the overlay div.
 *     (default "LabeledMarker_markerLabel")
 *   opt_opts.labelOffset {GSize} label offset, the x- and y-distance between
 *     the marker's latlng and the upper-left corner of the text div.
 */
function LabeledMarker(latlng, opt_opts){
  this.latlng_ = latlng;
  this.opts_ = opt_opts;

  this.labelText_ = opt_opts.labelText || "";
  this.labelClass_ = opt_opts.labelClass || "LabeledMarker_markerLabel";
  this.labelOffset_ = opt_opts.labelOffset || new GSize(0, 0);
  
  this.clickable_ = opt_opts.clickable || true;
  
  if (opt_opts.draggable) {
  	// This version of LabeledMarker doesn't support dragging.
  	opt_opts.draggable = false;
  }
  
  GMarker.apply(this, arguments);
}


// It's a limitation of JavaScript inheritance that we can't conveniently
// inherit from GMarker without having to run its constructor. In order for 
// the constructor to run, it requires some dummy GLatLng.
LabeledMarker.prototype = new GMarker(new GLatLng(0, 0));

/**
 * Is called by GMap2's addOverlay method. Creates the text div and adds it
 * to the relevant parent div.
 *
 * @param {GMap2} map the map that has had this labeledmarker added to it.
 */
LabeledMarker.prototype.initialize = function(map) {
  // Do the GMarker constructor first.
  GMarker.prototype.initialize.apply(this, arguments);
  
  this.map_ = map;
  this.div_ = document.createElement("div");
  this.div_.className = this.labelClass_;
  this.div_.innerHTML = this.labelText_;
  this.div_.style.position = "absolute";
  this.div_.style.cursor = "pointer";
  this.div_.style.fontSize = "12px";
  map.getPane(G_MAP_MARKER_PANE).appendChild(this.div_);

  if (this.clickable_) {
    /**
     * Creates a closure for passing events through to the source marker
     * This is located in here to avoid cluttering the global namespace.
     * The downside is that the local variables from initialize() continue
     * to occupy space on the stack.
     *
     * @param {Object} object to receive event trigger.
     * @param {GEventListener} event to be triggered.
     */
    function newEventPassthru(obj, event) {
      return function() { 
        GEvent.trigger(obj, event);
      };
    }
  
    // Pass through events fired on the text div to the marker.
    var eventPassthrus = ['click', 'dblclick', 'mousedown', 'mouseup', 'mouseover', 'mouseout'];
    for(var i = 0; i < eventPassthrus.length; i++) {
      var name = eventPassthrus[i];
      GEvent.addDomListener(this.div_, name, newEventPassthru(this, name));
    }
  }
}

/**
 * Move the text div based on current projection and zoom level, call the redraw()
 * handler in GMarker.
 *
 * @param {Boolean} force will be true when pixel coordinates need to be recomputed.
 */
LabeledMarker.prototype.redraw = function(force) {
  GMarker.prototype.redraw.apply(this, arguments);
  
  // Calculate the DIV coordinates of two opposite corners of our bounds to
  // get the size and position of our rectangle
  var p = this.map_.fromLatLngToDivPixel(this.latlng_);
  var z = GOverlay.getZIndex(this.latlng_.lat());
  
  // Now position our div based on the div coordinates of our bounds
  this.div_.style.left = (p.x + this.labelOffset_.width) + "px";
  this.div_.style.top = (p.y + this.labelOffset_.height) + "px";
  this.div_.style.zIndex = z; // in front of the marker
}

/**
 * Remove the text div from the map pane, destroy event passthrus, and calls the
 * default remove() handler in GMarker.
 */
 LabeledMarker.prototype.remove = function() {
  GEvent.clearInstanceListeners(this.div_);
  this.div_.parentNode.removeChild(this.div_);
  this.div_ = null;
  GMarker.prototype.remove.apply(this, arguments);
}

/**
 * Return a copy of this overlay, for the parent Map to duplicate itself in full. This
 * is part of the Overlay interface and is used, for example, to copy everything in the 
 * main view into the mini-map.
 */
LabeledMarker.prototype.copy = function() {
  return new LabeledMarker(this.latlng_, this.opt_opts_);
}


//end Elable functions	
//--------------------------------------------------------------------------------------------------------------------------
function GoToStation(mapID){
	GEvent.trigger(gmarker[mapID-1], "click");
	StationDataIsShowing = true;
}
//-----------------------------------------------------------------------------------------------------------------------
function createMarker(mapID, hid) {
	
	var point = new GLatLng(document.getElementById("Lat"+mapID).value, document.getElementById("Long"+mapID).value);

	if(document.getElementById("hprfmtd"+mapID).innerHTML.search("#009900") > 0){
		color = "green";
	} else if(document.getElementById("hprfmtd"+mapID).innerHTML.search("#ff9900") > 0) {
		// Some browsers convert colors to lower case
		color = "orange";
	} else if(document.getElementById("hprfmtd"+mapID).innerHTML.search("#FF9900") > 0) {
		// Some browsers convert colors to upper case
		color = "orange";
	} else {
		color = "red";
	}
	
	var icon = new GIcon();
	icon.image = "http://www.gaspricewatch.com/images/push_"+color+".gif";
	icon.iconSize = new GSize(43, 31);
	icon.iconAnchor = new GPoint(30, 28);
	icon.infoWindowAnchor = new GPoint(20, 1);
	
	var opts = {};
	
	opts = {
		"icon": icon,
		"clickable": true,
		"draggable": false,
		"labelText": document.getElementById("hprfmtd"+mapID).firstChild.innerHTML,
		"labelOffset": new GSize(-21, -27)
	};
	var marker = new LabeledMarker(point, opts);
	//map.addOverlay(label);

	//var marker = new GMarker(point, icon);

	GEvent.addListener(marker, 'click', function() {
		stationClickedID = hid;
		var markerLatLon = marker.getPoint();
		map.panTo(new GLatLng(markerLatLon.lat(),markerLatLon.lng()));
	});
	
	gmarker[mapID-1] = marker;	
	return marker;
}
//-----------------------------------------------------------------------------------------------------------------------
function load() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		map.checkResize();
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		map.addControl(new GScaleControl());
		map.enableDoubleClickZoom();
		
		if(document.getElementById("NumRecCnt")){
			
			numMarkers = document.getElementById("NumRecCnt").value;

			for(i=0; i < numMarkers; i++){	
				var marker = createMarker(i)
				map.addOverlay(marker);
			}
		} else {
			map.setCenter(new GLatLng(39.099722,-94.578333), 4);
		}
	}
	defaultStationDataText = document.getElementById("stationdata").innerHTML;
	GEvent.addListener(map, "moveend", function() {	ReQueryMap(); });
}
//-----------------------------------------------------------------------------------------------------------------------
function ShowAddress(address) {
	geocoder = new GClientGeocoder();  
	geocoder.getLatLng(
		address,
		function(point) {
			if (!point) {
				alert(address + " not found");
			} else {
				var latlon = point+'';
				latlonArray = latlon.split(',');
				lat = latlonArray[0].substr(1,latlonArray[0].length);
				lon = latlonArray[1].substr(0,latlonArray[1].length-2);
				map.setCenter(new GLatLng(lat, lon), 14);
			}
		}  
	);
}
//-----------------------------------------------------------------------------------------------------------------------
function ReQueryMap(){
	map.clearOverlays();
  	document.getElementById("stationdata").innerHTML = defaultStationDataText;
	StationDataIsShowing = false;
	Hide("message");
	document.getElementById("message").innerHTML = '';
	
	if(map.getZoom() > 12){
		if(document.getElementById("loadingmessage")){
			document.getElementById("loadingmessage").innerHTML = "Loading Stations...";
		} else {
			document.getElementById("results").innerHTML = "Loading Stations...";
		}
		
		//get map bounds and assign to hidden inputs
		var bounds = map.getBounds();
		var southWest = bounds.getSouthWest();
		var northEast = bounds.getNorthEast();
		
		document.getElementById("minLat").value = southWest.lat();
		document.getElementById("maxLat").value = northEast.lat();
		document.getElementById("minLon").value = northEast.lng();
		document.getElementById("maxLon").value = southWest.lng();

		var request = GXmlHttp.create();
		request.open("GET", "http_requests/stations.asp?F="+document.getElementById("Filterby").value+"&S="+document.getElementById("Sortby").value+"&maxLat="+ document.getElementById("maxLat").value +"&minLat="+ document.getElementById("minLat").value +"&maxLon="+ document.getElementById("maxLon").value +"&minLon="+ document.getElementById("minLon").value +"", true);
		request.onreadystatechange = function() {  
			if (request.readyState == 4) {
				document.getElementById("results").innerHTML = request.responseText; 
				
				//rebuild the map
				numMarkers = document.getElementById("NumRecCnt").value;
				for(i = 1; i <= numMarkers; i++){
					var hid = document.getElementById("hid"+i).value;
					var marker = createMarker(i, hid);
					map.addOverlay(marker);
					
					if(document.getElementById("hid"+i)){
						if(document.getElementById("hid"+i).value == stationClickedID){
							GEvent.clearListeners(map, "moveend");
							GEvent.addListener(map, "moveend", function() {	GEvent.clearListeners(map, "moveend");	GEvent.addListener(map, "moveend", function() {	ReQueryMap(); }); });
							//var html = "<div><table cellpadding='5'><tr><td valign='top' style='border-right: 1px solid #cccccc'><span>"+ document.getElementById("hprfmtd"+i).innerHTML + document.getElementById("htmfmtd"+i).innerHTML +"<br /></span></td><td valign='top'>" + document.getElementById("hstn"+i).value + "<br />" + document.getElementById("hstr"+i).value + "<br />" + document.getElementById("hxstr"+i).value + "<br />" + document.getElementById("hcity"+i).value + ". " + document.getElementById("hst"+i).value + "</td></tr></table></div>";
							var dirForm = '<form action="http://maps.google.com/maps" method="get" target="_blank"><p><label for="saddr">&nbsp;&nbsp;Start Address:&nbsp;</label><br /><input type="text" name="saddr" id="saddr" value=""/><br /><input type="submit" value="Go" /><input type="hidden" name="daddr" value="' + document.getElementById("hstr"+i).value + ', ' + document.getElementById("hcity"+i).value + ', ' + document.getElementById("hst"+i).value+'" /><input type="hidden" name="hl" value="en" /></p></form>';
							var infoTabs = [  new GInfoWindowTab("Station Info", "<div><table cellpadding='5'><tr><td valign='top' style='border-right: 1px solid #cccccc'><span>"+ document.getElementById("hprfmtd"+i).innerHTML + document.getElementById("htmfmtd"+i).innerHTML +"<br /></span></td><td valign='top' style='border-right: 1px solid #cccccc; padding: 10px'>" + document.getElementById("hstn"+i).value + "<br />" + document.getElementById("hstr"+i).value + "<br />" + document.getElementById("hxstr"+i).value + "<br />" + document.getElementById("hcity"+i).value + ", " + document.getElementById("hst"+i).value + "</td><td width='130'><div style='margin: 4px; border: 1px solid #CCCCCC; padding: 3px; height: 125px; width: 125px;'>"+ document.getElementById("GAdCode1").innerHTML + "</div></td></tr></table></div>"),
							  new GInfoWindowTab("Directions", "<table cellpadding='5'><tr><td valign='top' style='border-right: 1px solid #cccccc'>Get directions by entering<br />the starting address below.<br />"+dirForm+"</td><td><div style='margin: 4px; border: 1px solid #CCCCCC; padding: 3px; height: 125px; width: 125px;'>"+ document.getElementById("GAdCode1").innerHTML + "</div></td></tr></table>")];
							document.getElementById("stationdata").innerHTML = document.getElementById("hstationdata"+i).innerHTML;
							document.getElementById("hstationdata"+i).innerHTML = '';
							//marker.openInfoWindowHtml(html);
							marker.openInfoWindowTabsHtml(infoTabs);
							stationClickedID = 0;
							StationDataIsShowing = true;
						}
					}
				}
			}
		}
		request.send(null);
	} else {
		map.clearOverlays();
		document.getElementById("results").innerHTML = 'Enter a location using the control panel above, or search directly in the map<b>:</b><ul><li>Drag the map with your mouse<li>Double-Click to zoom in<li>Use the slider to zoom in and out</ul>Zoom in to the 5th "notch" to see stations.<br><br>or go to the <a href="http://www.gaspricewatch.com/new/default_V2.asp" target="_top">TEXT version</a>';
		document.getElementById("minLat").value = '';
		document.getElementById("maxLat").value = '';
		document.getElementById("minLon").value = '';
		document.getElementById("maxLon").value = '';
		StationDataIsShowing = false;
	}

}
//-----------------------------------------------------------------------------------------------------------------------
function UpdatePrices(mapID){
	
	var Reg;
	var Mdg;
	var Prm;
	var E85;
	var Dsl;
	var BDs;
	var TDs;
	var UDs;
	
	if(document.getElementById("Reg"+mapID)){
		Reg = document.getElementById("Reg"+mapID).value;
	}
	if(document.getElementById("Mdg"+mapID)){
		Mdg = document.getElementById("Mdg"+mapID).value;
	}
	if(document.getElementById("Prm"+mapID)){
		Prm = document.getElementById("Prm"+mapID).value;
	}
	if(document.getElementById("E85"+mapID)){
		E85 = document.getElementById("E85"+mapID).value;
	}
	if(document.getElementById("Dsl"+mapID)){
		Dsl = document.getElementById("Dsl"+mapID).value;
	}
	
	if(document.getElementById("BDs"+mapID)){
		BDs = document.getElementById("BDs"+mapID).value;
	}
	
	if(document.getElementById("TDs"+mapID)){
		TDs = document.getElementById("TDs"+mapID).value;
	}
	if(document.getElementById("UDs"+mapID)){
		UDs = document.getElementById("UDs"+mapID).value;
	}
	
	Disable("update"+mapID);
	
	var request = GXmlHttp.create();
	request.open("GET", "http_requests/UpdatePrices.asp?sp="+ document.getElementById("SpNm").value +"&ps="+ document.getElementById("SpPs").value +"&B="+ BDs +"&D="+ Dsl +"&E="+ E85 +"&H="+document.getElementById("hid"+mapID).value +"&M="+ Mdg +"&P="+ Prm +"&R="+ Reg +"&U="+ UDs +"&T="+ TDs , true);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			ShowBlock("message");
			document.getElementById("message").innerHTML = request.responseText; 
		}
	}
	request.send(null);
	Enable("update"+mapID);
}
//-----------------------------------------------------------------------------------------------------------------------
function GetMyPage(){
	var request = GXmlHttp.create();
	request.open("GET", "http_requests/MyPage.asp?F="+document.getElementById("Sortby").value+"&sp="+document.getElementById("SpNm").value+"&ps="+ document.getElementById("SpPs").value, true);
	request.onreadystatechange = function() {  
		if (request.readyState == 4) {
			document.getElementById("results").innerHTML = request.responseText; 
		}
	}
	request.send(null);
}
//-----------------------------------------------------------------------------------------------------------------------
function AddStationToMyPage(mapID){
	Disable("add"+mapID);
	var request = GXmlHttp.create();
	request.open("GET", "http_requests/AddStation.asp?sp="+ document.getElementById("SpNm").value +"&sq="+ document.getElementById("hid"+mapID).value +"&ps="+ document.getElementById("SpPs").value, true);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
		  ShowBlock("message");
		  document.getElementById("message").innerHTML = request.responseText; 
		}
	}
	request.send(null);
	Enable("add"+mapID);
}
