// Declare variables for later use 
var map = null;
var geocoder = null;
var sidebar;
var mapDiv;
var markers = new Array();
//var current_latitude;
//var current_longitude;
var fromaddress;
//var saved_latitude=null;
//var saved_longitude=null;
//var saved_location=null;
//var saved_zoom=null;

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);


		//map.addControl(new GSmallMapControl());
		map.addControl(new GLargeMapControl3D());
		//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

		if( getviewfromCookie() )		
			startLatLong(); 
		else
			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));
};

//this is used for the initial map
function startAddress(address) 
{
	if (geocoder) 
	{
	geocoder.getLocations(
	address,
		function(response) 
		{
			if (!response.Placemark) 
			{
				//if bad initial location passed it show default location
				//alert(address + " not found");
				map.setCenter(new GLatLng(default_latitude, default_longitude), default_zoom);
				current_latitude=default_latitude;
				current_longitude=default_longitude;
				current_zoom=default_zoom;
			}
			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>');
				current_longitude=point.lng();
				current_latitude=point.lat();
				current_zoom=12;
				//console.info('showAddress cpoint',current_longitude );
				//console.info('showAddress cpoint',current_latitude );
				fromaddress=place.address;
	document.getElementById('planroute').href = 'planroute.php?fromaddress='+encode(place.address)
	+'&lat='+current_latitude+'&lng='+current_longitude;  
	document.getElementById('locator').href = 'locator.php?fromaddress='+encode(place.address)
	+'&lat='+current_latitude+'&lng='+current_longitude;  

			}
		}
		);
	}
	else
	{
		alert("Geocoder Failed to Load");
//		map.setCenter(new GLatLng(default_latitude, default_longitude), default_zoom);
//		current_latitude=default_latitude;
//		current_longitude=default_longitude;
	}
}

//this is used for the initial map
function startLatLong() 
{
	current_latitude=saved_latitude;
	current_longitude=saved_longitude;
	current_location=saved_location;
	current_zoom=saved_zoom;
	fromaddress=saved_location;


	//console.log('startLatLong latitude',saved_latitude);
	//console.log('startLatLong longitude',saved_longitude);
	//console.log('startLatLong location',saved_location);
	//console.log('startLatLong zoom',saved_zoom);

//console.log( map.getZoom() );
	map.setCenter(new GLatLng(saved_latitude, saved_longitude), saved_zoom);
//console.log( map.getZoom() );

	//console.log('startLatLong zoom',saved_zoom);

}

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>');
				current_longitude=point.lng();
				current_latitude=point.lat();
				current_zoom=12;

				//console.info('showAddress cpoint',current_longitude );
				//console.info('showAddress cpoint',current_latitude );
				fromaddress=place.address;
	document.getElementById('planroute').href = 'planroute.php?fromaddress='+encode(place.address)
	+'&lat='+current_latitude+'&lng='+current_longitude;  
	document.getElementById('locator').href = 'locator.php?fromaddress='+encode(place.address)
	+'&lat='+current_latitude+'&lng='+current_longitude;  

			}
		}
		);
	}
}





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();
	current_zoom=mapZoom;


//console.log('mapMoveEnd',mapZoom);

	var mapcenter=map.getCenter();
	current_longitude=mapcenter.lng();	
	current_latitude=mapcenter.lat();

	//log the URL for testing
	//GLog.writeUrl('serverbranded.php?'+getVars+'&zoom='+mapZoom+filterurl);

	//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);

	////////////////////////////////////
	// Hide message if points are show
	////////////////////////////////////
	var size = 0, key;
    	for (key in points) {
        if (points.hasOwnProperty(key)) size++;
    	}
    	//console.log(size);
	if(size==0)
	{
		//console.log('no points found');
		document.getElementById('nolocations').style.display = 'block';
	}
	else
	{
		//console.log('points found');
		document.getElementById('nolocations').style.display = 'none';
	}

	////////////////////////////////////
	//removed old clusters
	////////////////////////////////////
	for (var m = markers.length - 1; m >= 0; m--)
	{
		if(markers[m].getIcon().type=='C') removeDataPoint(m);
		//console.log( markers[m].getIcon().type   ); 
	}

	////////////////////////////////////
	//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);
	}
	////////////////////////////////////
	// end request
	////////////////////////////////////

		}
	}
	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='+current_latitude+'&lng='+current_longitude
			+ "&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);
	}

//console.log('mapZoomEnd',newZoom);

};

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 encodeURI(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='+current_latitude+'&lng='+current_longitude;  

};

function findnear(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]);
				
				current_longitude=point.lng();
				current_latitude=point.lat();
				current_zoom=12;

				//retrieve the points
				var request = GXmlHttp.create();
				request.open('GET', 'serverfindnear.php?lat='+current_latitude+'&lng='+current_longitude+filterurl, true);

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

						//console.info(center);
						map.setCenter(new GLatLng(center.lat, center.lng), 12);
						current_latitude=center.lat;
						current_longitude=center.lng;
						current_zoom=12;
					}//end if

				}//end function
				request.send(null);

			}//end if placemark
		}//end function
		);
	}
}



function formshownear(address)
{
	fromaddress=address;
	findnear(address);
	document.getElementById('locator').href = 'locator.php?fromaddress='+encode(fromaddress);  
	document.getElementById('planroute').href = 'planroute.php?fromaddress='+encode(fromaddress)
	+'&lat='+current_latitude+'&lng='+current_longitude;  

};


function getviewfromCookie()
{
  	//var result=true;
  	var result=false;

//	if (getCookie('latitude')) saved_latitude=getCookie('latitude');
//	if (getCookie('longitude')) saved_latitude=getCookie('longitude');
//	if (getCookie('location')) saved_latitude=getCookie('location');
//	if (getCookie('zoom')) saved_latitude=getCookie('zoom');

	saved_latitude=getCookie('latitude');
	saved_longitude=getCookie('longitude');
	saved_location=getCookie('location');
	saved_zoom=parseInt(getCookie('zoom'));


	if (saved_latitude)
	{
	current_latitude=saved_latitude;
	current_longitude=saved_longitude;
	current_location=saved_location;
	current_zoom=saved_zoom;
	document.getElementById('fromadd').value=saved_location;
	result=true;
	}
//	console.log('Cookie get latitude',saved_latitude);
//	console.log('Cookie get longitude',saved_longitude);
//	console.log('Cookie get location',saved_location);
//	console.log('Cookie get zoom',saved_zoom);

	//startLatLong();

	return result;
}

function testcookie()
{
	console.log('testcookie');
	getviewfromCookie()
	startLatLong();
}

function saveview(location)
{
	saved_latitude=current_latitude;
	saved_longitude=current_longitude;
	saved_location=location;
	saved_zoom=current_zoom;

	setCookie2('latitude', saved_latitude);
	setCookie2('longitude', saved_longitude);
	setCookie2('location', saved_location);
	setCookie2('zoom', saved_zoom);


//	var latlng = new GLatLng(current_latitude,current_longitude);
        //geocoder.getLocations(latlng, showAddress);
 

//	console.log('saved latitude',saved_latitude);
//	console.log('saved longitude',saved_longitude);
//	console.log('saved location',saved_location);
//	console.log('saved zoom',saved_zoom);

//	setCookie('latitude', '');

};

function clearview()
{
//	saved_latitude='43.606';
//	saved_longitude='-124.181';
//	saved_location='my saved search';
//	saved_zoom='14';

	saved_latitude=null;
	saved_longitude=null;
	saved_location=null;
	saved_zoom=null;

	setCookie2('latitude', '');
	setCookie2('longitude', '');
	setCookie2('location', '');
	setCookie2('zoom', '');

	//startLatLong(); 
	//document.getElementById('fromadd').value=saved_location;
};






