// Declare variables for later use
var map = null;
var geocoder = null;
var sidebar;
var mapDiv;
var markers = new Array();
var centerLatitude;
var centerLongitude;
var fromaddress;

function initialize() 
{
	sidebar = document.getElementById('placelist');
	mapDiv = document.getElementById('map_canvas');
	filter1 = document.getElementById('filter_container');
	filter2 = document.getElementById('filter_show');

	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(mapDiv,options);

		map = new GMap2(mapDiv);
		// Init other map options
		//map.enableContinuousZoom();

		// Add the standard map controls
		map.addControl(new ExtMapTypeControl({showTraffic: true, showTrafficKey: true}));
		//map.setMapType(G_SATELLITE_MAP);
		map.addMapType(G_PHYSICAL_MAP);

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;
};
		//map.addControl(new GSmallMapControl());
		map.addControl(new GLargeMapControl());
		//map.addControl(new GScaleControl());
		//map.addControl(new GOverviewMapControl());
		//map.addControl(new GMapTypeControl());
		// Initialize the geocoder object
		geocoder = new GClientGeocoder();
		//set start address to city based on IP if in USA/Canada, center of USA if not
		startAddress(fromaddress);
		//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());


	}//end main if
}


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 startAddress(address) 
{
if (geocoder) 
	{
	geocoder.getLocations(
	address,
		function(response) 
		{
			if (!response.Placemark) 
			{
				//alert(address + " not found");
				map.setCenter(new GLatLng(39.8, -98.5), 4);
				centerLatitude=39.8;
				centerLongitude=-98.5;

			}
			else
			{
				//console.info('response.Placemark[0]',response.Placemark[0] );
				//console.info('response.point',response.Placemark[0].Point );

				place = response.Placemark[0];
				point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);

				map.setCenter(point, 12);  //was 13
				var marker = new GMarker(point);

				//map.addOverlay(marker);
				//marker.openInfoWindowHtml('<span class=bubble><b>'+place.address+'</b></span>');
				centerLongitude=point.lng();
				centerLatitude=point.lat();
				//console.info('showAddress cpoint',centerLongitude );
				//console.info('showAddress cpoint',centerLatitude );
				fromaddress=place.address;
	document.getElementById('planroute').href = 'planroute.php?fromaddress='+encode(place.address)
	+'&lat='+centerLatitude+'&lng='+centerLongitude;  
	document.getElementById('locator').href = 'locator.php?fromaddress='+encode(place.address)
	+'&lat='+centerLatitude+'&lng='+centerLongitude;  

			}
		}
		);
	}
	else
	{
		map.setCenter(new GLatLng(39.8, -98.5), 4);
		centerLatitude=39.8;
		centerLongitude=-98.5;
	}
}


function showAddress(address) 
{
	if (geocoder) 
	{
	geocoder.getLocations(
	address,
		function(response) 
		{
			if (!response.Placemark) 
			{
				alert(address + " not found");
			}
			else
			{
				//console.info('response.Placemark[0]',response.Placemark );
				//console.info('response.point',response.Placemark[0].Point );
				//console.info('response',response );

				place = response.Placemark[0];
				point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);

				map.setCenter(point, 12); //was 13
				var marker = new GMarker(point);

				map.addOverlay(marker);
				marker.openInfoWindowHtml('<span class=bubble><b>'+place.address+'</b></span>');
				centerLongitude=point.lng();
				centerLatitude=point.lat();
				//console.info('showAddress cpoint',centerLongitude );
				//console.info('showAddress cpoint',centerLatitude );
				fromaddress=place.address;
	document.getElementById('planroute').href = 'planroute.php?fromaddress='+encode(place.address)
	+'&lat='+centerLatitude+'&lng='+centerLongitude;  
	document.getElementById('locator').href = 'locator.php?fromaddress='+encode(place.address)
	+'&lat='+centerLatitude+'&lng='+centerLongitude;  

			}
		}
		);
	}
}





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.open('GET', 'weather.php?'+getVars+'&zoom='+mapZoom, 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);
	// mapZoomEnd: remove map markers when zoom changes
	for (var m = markers.length - 1; m >= 0; m--)
	{
		removeDataPoint(m);
	}
};

function removeDataPoint(m)
{
	//console.info('RDP',markers);
	// Remove the marker from the map
	map.removeOverlay(markers[m]);
	// Find and remove the sidebar entry  
	var id = markers[m].getPoint().toUrlValue();
	var sidebarRow = document.getElementById(id);
	if (sidebarRow) sidebar.removeChild(sidebarRow);
	// 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(address)
{
//	showAddress(this.fromaddress.value);

//	setCookie('fromadd', address); 
	fromaddress=address;
	showAddress(address);
	document.getElementById('locator').href = 'locator.php?fromaddress='+encode(fromaddress);  
	document.getElementById('planroute').href = 'planroute.php?fromaddress='+encode(fromaddress)
	+'&lat='+centerLatitude+'&lng='+centerLongitude;  

};


