// ***************** BEGIN DECLARE GLOBAL VARIABLES *************************************************************************************
var verbose = 0;
var dataFileName = "./data/directory.xml";			// COMMENT: Specify the data file name.

var map;											// COMMENT: Create map array.
var startPoint = new GLatLng(38.9111, -77.00622);	// COMMENT: This variable holds the default map starting point.
var startZoom = 10;									// COMMENT: This variable holds the default map zoom level.
var bounds;											// COMMENT: This variable holds the map boundaries for use in our auto map movemenent.

var icons = [];										// COMMENT: Create icons array.  Since we're only using one type of marker, we'll only be using one element in the array for now.

var markers = [];									// COMMENT: This variable holds the dealer markers and data pulled from the dealers variable.

var numResults = 0;									// COMMENT: Create the array to hold the number of matching dealerships.

var availableMakes = [];							// COMMENT: This variable holds the makes that are available from the datafile.
var currentMakes = [];								// COMMENT: This variable holds the makes that are currently displayed.

var availableCounties = [];							// COMMENT: This variable holds the counties that are available from the datafile.
var currentCounty;									// COMMENT: This variable holds the county that is currently displayed.
// ***************** END DECLARE GLOBAL VARIABLES *************************************************************************************

// ***************** BEGIN FUNCTION TO LOAD MAP AND DATA *************************************************************************************
function startApp()
{

	if (GBrowserIsCompatible())
	{

		loadMap();		// COMMENT: Load the map and settings.
		getData();		// COMMENT: Load the data.

	} // end if (GBrowserIsCompatible())
	else
	{
		alert("Your browser is incompatible with this application.");
	}
} // end function startApp()

// ***************** BEGIN FUNCTION TO LOAD MAP AND DATA *************************************************************************************
function loadMap()
{
	map = new GMap2(document.getElementById("dealerdirectory_map"));	// COMMENT: Create a new map instance.
	map.enableContinuousZoom();											// COMMENT: Allow continous zooming in the map.
	map.enableDoubleClickZoom();										// COMMENT: Allow double click zooming.
	map.addControl(new GSmallMapControl());								// COMMENT: Add the small map controls.
	map.setCenter(startPoint, startZoom);									// COMMENT: Initialize the map and set the center point to Washington, D.C.

} // end function loadMap()
// ***************** END FUNCTION TO LOAD MAP AND DATA *************************************************************************************

// ***************** BEGIN FUNCTION TO LOAD DATAFILE *************************************************************************************
function getData()
{

	GDownloadUrl(dataFileName, function(data, responseCode)
	{

		var xml = GXml.parse(data);	// COMMENT: Parse the XML data.
		var dealers = xml.documentElement.getElementsByTagName("dealer");	// COMMENT: Get the dealer data.

		for (var i = 0; i < dealers.length; i++)	// COMMENT: Loop through the dealers from the XML file.
		{
			// ***************** BEGIN CREATE A NEW MARKER WITH THE KEY BEING THE DEALER'S ORGID *****************
			var tempID = GXml.value(dealers[i].getElementsByTagName("orgID")[0]);
			markers[tempID] =  new Object();
			markers[tempID].orgID = GXml.value(dealers[i].getElementsByTagName("orgID")[0]);
			markers[tempID].dealerName = GXml.value(dealers[i].getElementsByTagName("dealerName")[0]);
			markers[tempID].makes = GXml.value(dealers[i].getElementsByTagName("makes")[0]);
			markers[tempID].usedURL = GXml.value(dealers[i].getElementsByTagName("usedURL")[0]);
			markers[tempID].usedPhone = GXml.value(dealers[i].getElementsByTagName("usedPhone")[0]);
			markers[tempID].newURL = GXml.value(dealers[i].getElementsByTagName("newURL")[0]);
			markers[tempID].newPhone = GXml.value(dealers[i].getElementsByTagName("newPhone")[0]);
			markers[tempID].websiteURL = GXml.value(dealers[i].getElementsByTagName("websiteURL")[0]);
			if (markers[tempID].websiteURL)
			{
				markers[tempID].premium = "1";
			}
			else
			{
				markers[tempID].premium = "0";
			}
			markers[tempID].address = GXml.value(dealers[i].getElementsByTagName("address")[0]);
			markers[tempID].city = GXml.value(dealers[i].getElementsByTagName("city")[0]);
			markers[tempID].state = GXml.value(dealers[i].getElementsByTagName("state")[0]);
			markers[tempID].zipcode = GXml.value(dealers[i].getElementsByTagName("zipcode")[0]);
			markers[tempID].county = GXml.value(dealers[i].getElementsByTagName("county")[0]);
			markers[tempID].latitude = GXml.value(dealers[i].getElementsByTagName("latitude")[0]);
			markers[tempID].longitude = GXml.value(dealers[i].getElementsByTagName("longitude")[0]);
			markers[tempID].point = new GLatLng(parseFloat(markers[tempID].latitude), parseFloat(markers[tempID].longitude));
			// ***************** END CREATE A NEW MARKER WITH THE KEY BEING THE DEALER'S ORGID *****************

			addMake(markers[tempID].makes);	// COMMENT: Add the makes from this dealership into the list of available makes.
			addCounty(markers[tempID].county);	// COMMENT: Add the county from this dealership into the list of available counties.

		} // end for (var i = 0; i < dealers.length; i++)

		loadMakes();	// COMMENT: Load the makes from the datafile into the user's selection of checkboxes.
		loadCounties();	// COMMENT: Load the counties from the datafile into the user's selection box.

		document.getElementById("make_all").checked = true;	// COMMENT: Auto-check the SHOW ALL button on the initial load.
		filterResults("all");	// COMMENT: Turn on all dealerships for the initial load.

	});	// end GDownloadUrl(dataFileName, function(data, responseCode)

} // end function getData()
// ***************** BEGIN FUNCTION TO LOAD DATAFILE *************************************************************************************


// ***************** BEGIN FUNCTION TO ADD DISTINCT MAKE *************************************************************************************
function addMake(whichMakes)
{

	var tempMakes = whichMakes.split(", ");	// COMMENT: Split the makes based on ", ".

	for (i = 0; i < tempMakes.length; i++)	// COMMENT: Loop through all of the makes from this dealership.
	{
		if (!availableMakes[tempMakes[i]])	// COMMENT: Check to see if this make is already in the array of available makes.
		{
			availableMakes[tempMakes[i]] = 1;	// COMMENT: Add this make to the array of available makes.
		} // end if (!availableMakes[tempMakes[i]])
		else
		{
			availableMakes[tempMakes[i]]++;	// COMMENT: Increase the counter for this make.
		}
	} // end for (i = 0; i < tempMakes.length; i++)

} // end function addMake(whichMakes)
// ***************** END FUNCTION TO ADD DISTINCT MAKE *************************************************************************************

// ***************** BEGIN FUNCTION TO ADD DISTINCT COUNTY *************************************************************************************
function addCounty(whichCounty)
{
		if (!availableCounties[whichCounty])	// COMMENT: Check to see if this county is already in the array of available counties.
		{
			availableCounties[whichCounty] = 1;	// COMMENT: Add this make to the array of available counties.
		} // end if (!listofallCounties[whichCounty])

} // end function addCounty(whichCounty)
// ***************** END FUNCTION TO ADD DISTINCT COUNTY *************************************************************************************

// ***************** BEGIN FUNCTION TO CREATE THE CHECKBOXES FOR MAKES IN THE DATAFILE *************************************************************************************
function loadMakes()
{

	var tempHTML = "<ul class=\"makeul\">\n";
	tempHTML += "<li class=\"makeli\" style=\"display: none;\"><input class=\"makecheckbox\" id=\"make_all\" type=\"checkbox\" onclick=\"filterResults('all');\"> <strong>Show All</strong></li>\n";
	for (key in availableMakes)	// COMMENT: Add each available make to the checkbox list.
	{
		tempHTML += "<li class=\"makeli\"><input class=\"makecheckbox\" id=\"make_" + key.replace(" ", "_") + "\" type=\"checkbox\" onclick=\"filterResults();\"> " + key + " (" + availableMakes[key] + ")</li>\n";
	} // end for (key in availableMakes)
	tempHTML += "</ul>\n";

	document.getElementById("dealerdirectory_filtermake_autocode").innerHTML = tempHTML;	// COMMENT: Set the DIV with the generated checkboxes.

} // end function loadMakes()
// ***************** END FUNCTION TO CREATE THE CHECKBOXES FOR MAKES IN THE DATAFILE *************************************************************************************

// ***************** BEGIN FUNCTION TO CREATE THE SELCT BOX FOR COUNTIES IN THE DATAFILE *************************************************************************************
function loadCounties()
{
				
	var tempHTML = "<select id=\"countySelector\" name=\"countySelector\" class=\"county_selector\" onchange=\"filterResults();\">\n";
	tempHTML += "<option onselect=\"filterResults();\" value=\"all\"> Show All</option>\n";
	for (key in availableCounties)	// COMMENT: Add each available county to the select list.
	{
		tempHTML += "<option onselect=\"filterResults();\" value=\"" + key + "\"> " + key + "</option>\n";
	} // end for (key in availableMakes)
	tempHTML += "</select>\n";

	document.getElementById("dealerdirectory_filtercounty_autocode").innerHTML = tempHTML;	// COMMENT: Set the DIV with the generated checkboxes.

} // end function loadCounties()
// ***************** END FUNCTION TO CREATE THE SELCT BOX FOR COUNTIES IN THE DATAFILE *************************************************************************************

// ***************** BEGIN FUNCTION TO CREATE AND RETURN A MARKER *************************************************************************************
function createMarker(whichKey)
{

	icons[markers[whichKey].premium] = new GIcon();
	icons[markers[whichKey].premium].image = "./images/marker_" + markers[whichKey].premium + "_single.png";
	icons[markers[whichKey].premium].shadow = "./images/marker_shadow.png";
	icons[markers[whichKey].premium].iconSize = new GSize(19, 33);
	icons[markers[whichKey].premium].shadowSize = new GSize(36, 33);
	icons[markers[whichKey].premium].iconAnchor = new GPoint(9, 33);	// COMMENT: The pixel coordinate relative to the top left corner of the icon image at which this icon is anchored to the map.
	icons[markers[whichKey].premium].infoWindowAnchor = new GPoint(9, 15);	// COMMENT: The pixel coordinate relative to the top left corner of the icon image at which the info window is anchored t

	var point = new GLatLng(parseFloat(markers[whichKey].latitude), parseFloat(markers[whichKey].longitude));
	var tempMarker = new GMarker(point, icons[markers[whichKey].premium]);	// COMMENT: Create a new marker object.

	// ***************** BEGIN ADD MARKER CLICK EVENT LISTENER TO OPEN INFOWINDOW *****************
	GEvent.addListener(tempMarker, "click", function()
	{
		//dealerLogo created by TM 5/20/08
		var dealerLogo = markers[whichKey].dealerName.replace(/ /g, "_");
		dealerLogo = dealerLogo.replace(/[^A-Za-z0-9\._]/g,'');

		var tempHTML = "";
		tempHTML += "						<div id=\"dealerdirectory_infowindow\">\n";

		if (markers[whichKey].premium == "1")
		{
			tempHTML += "							<div class=\"leftcolumn\">\n";
			tempHTML += "								<a href=\"" + markers[whichKey].websiteURL + "\" target=\"_blank\"><img src=\"./imagesDealers/" + dealerLogo + ".jpg\" border=\"0\"></a><br>\n";
			tempHTML += "								<img src=\"./images/dealerdirectory_arrow.jpg\"> <a href=\"" + markers[whichKey].websiteURL + "\" target=\"_blank\">Dealer Website</a><br>\n";
			tempHTML += "								<img src=\"./images/dealerdirectory_arrow.jpg\"> <a href=\"http://www.cars.com/go/dealersearch/logDealerLead.jsp?orgid=" + markers[whichKey].orgID + "&leadType=map&paid=true&aff=national\" target=\"_blank\">Directions</a>\n";
			tempHTML += "							</div>\n";
		} // end if (markers[whichKey].premium == "1")
		tempHTML += "							<div class=\"rightcolumn\">\n";
		tempHTML += "								<span class=\"name\">" + markers[whichKey].dealerName + "</span><br>\n";
		tempHTML += "								" + markers[whichKey].address + "<br>\n";
		tempHTML += "								" + markers[whichKey].city + ", " + markers[whichKey].state + " " + markers[whichKey].zipcode + "<br>\n";
		if (markers[whichKey].newPhone)
		{
			tempHTML += "								New: " + markers[whichKey].newPhone;
		}
		if ((markers[whichKey].newPhone) && (markers[whichKey].usedPhone))
		{
			tempHTML += " &nbsp;|&nbsp; ";
		}
		if (markers[whichKey].usedPhone)
		{
			tempHTML += "Used: " + markers[whichKey].usedPhone;
		}
		tempHTML += "<br>\n";
		tempHTML += "								<span class=\"automakes\">\n";
		tempHTML += "									<b>Auto Makes: " + markers[whichKey].makes + "</b>\n";
		tempHTML += "								</span>\n";

		if (markers[whichKey].premium == "1")
		{
			if (markers[whichKey].newURL != "N/A")
			{
				tempHTML += "								<a href=\"" + markers[whichKey].newURL + "\" target=\"_blank\">See New Inventory</a>";
			}
			if ((markers[whichKey].newURL != "N/A") && (markers[whichKey].usedURL != "N/A"))
			{
				tempHTML += " &nbsp;|&nbsp; ";
			}
			if (markers[whichKey].usedURL != "N/A")
			{
				tempHTML += "<a href=\"" + markers[whichKey].usedURL + "\" target=\"_blank\">See Used Inventory</a>\n";
			}
		} // end if (markers[whichKey].premium == "1")

		tempHTML += "<br>\n";
		tempHTML += "							</div>\n";
		tempHTML += "						</div>\n";

		tempMarker.openInfoWindowHtml(tempHTML);	// COMMENT: Add the infowindow to the marker on the "click" event.
	});	// end GEvent.addListener(marker, "click", function()
	// ***************** END ADD MARKER CLICK EVENT LISTENER TO OPEN INFOWINDOW *****************

	GEvent.addListener(tempMarker, "mouseover", function()
	{

		var text = "<div id=\"wpMaps-marker\"><nobr>" + markers[whichKey].dealerName + "</nobr></div>";
		label = new ELabel(point, text);
		label.pixelOffset=new GSize(14,-33);
		map.addOverlay(label);	// add the label to the map on the "mouseover" event.

		tempMarker.setImage("./images/marker_" + markers[whichKey].premium + "_hover.png");	// COMMENT: Set the marker icon to its mouseover state.

	});	// end GEvent.addListener(marker, "mouseover", function()

	GEvent.addListener(tempMarker, "mouseout", function()
	{
		label.hide();	// COMMENT: First hide the label since this is faster, then remove it in the background while the label is hidden.
		map.removeOverlay(label);	// COMMENT: Now remove the label from the map on the "mouseout" event.

		tempMarker.setImage(icons[markers[whichKey].premium].image);	// COMMENT: Reset the marker icon back to its default

	});	// end GEvent.addListener(marker, "mouseout", function()

	return tempMarker;	// COMMENT: Return the marker object.

} // end function createMarker(point)
// ***************** END FUNCTION TO CREATE AND RETURN A MARKER *************************************************************************************

// ***************** BEGIN FUNCTION TO FILTER AND DISPLAY RESULTS *************************************************************************************
function filterResults(whichOptions)
{

	map.closeInfoWindow();	// COMMENT: Close any open infowindows while adding/removing markers.
	bounds = new GLatLngBounds();	// COMMENT: Reset the bounds.
	var numSelectedMakes = 0;	// COMMENT: Reset the number of selected makes.
	numResults = 0;	// COMMENT: Reset the number of found makes.

	currentCounty = document.getElementById("countySelector").options[document.getElementById("countySelector").selectedIndex].value;

	if (whichOptions == "all")	// COMMENT: Check or uncheck all the makes if the user checks/unchecks "Show All".
	{
		for (key in availableMakes)
		{
			if (document.getElementById("make_all").checked)
			{
				document.getElementById("make_" + key.replace(" ", "_")).checked = true;
			} // end if (document.getElementById("make_all").checked)
			else // from if (document.getElementById("make_all").checked)
			{
				document.getElementById("make_" + key.replace(" ", "_")).checked = false;
			} // end else from if (document.getElementById("make_all").checked)
		} // end for (key in availableMakes)
	} // end if (whichOptions == "all")

	for (key in availableMakes)	// COMMENT: Loop through all the available makes and determine whether to add or remove that make's markers from the map.
	{

		if (document.getElementById("make_" + key.replace(" ", "_")).checked)	// COMMENT: See if this make's checkbox is checked.
		{
			currentMakes[key] = 1;	// COMMENT: Add this make to the array of currently displayed makes.
			addMarkers(key, currentCounty);	// COMMENT: Add this make's markers to the map.
		}
		else // from if (document.getElementById("make_" + key.replace(" ", "_")).checked)
		{
			delete currentMakes[key];	// COMMENT: Remove this make from the array of currently displayed makes.
			removeMarkers(key, currentCounty)	// COMMENT: Remove this make's markers from the map.
		} // end else from if (document.getElementById("make_" + key.replace(" ", "_")).checked)
	} // end for (key in availableMakes)

	if (bounds.toString() == "((57.29577951308232, 180), (-57.29577951308232, -180))")	// COMMENT: Check if there are any mapped points.  If none, go to the default center and zoom, otherwise show the custom center and zoom.
	{
		map.setZoom(startZoom);
		map.panTo(startPoint);
	}
	else // from if (bounds.toString() == "((57.29577951308232, 180), (-57.29577951308232, -180))")
	{
		if (map.getBoundsZoomLevel(bounds) > 12)
		{
			map.setZoom(12);	// COMMENT: A BoundsZoomLevel is way too close, so back it out to 12.
		}
		else if (map.getBoundsZoomLevel(bounds) > 10)
		{
			map.setZoom(10);	// COMMENT: A BoundsZoomLevel is slightly too close, so back it out to 10.
		}
		else
		{
			map.setZoom(map.getBoundsZoomLevel(bounds));	// COMMENT: Zoom to the appropriate level encompassing all of the bounded points.
		}
		map.panTo(bounds.getCenter());	// COMMENT: Center on all of the bounded points.
	} // end else from if (bounds.toString() == "((57.29577951308232, 180), (-57.29577951308232, -180))")

	for (key in currentMakes)	// COMMENT: Loop through the current makes to see if there are any found results.
	{
		numSelectedMakes++;
	}

	if ((numSelectedMakes) && (!numResults))	// COMMENT: Show the 'no results found' message box.
	{
		toggleMessage('block');
	}
	else // from if (numResults)	// COMMENT: Hide the 'no results found' message box.
	{
		toggleMessage('none');
	} // end else from if (numResults)


} // end function filterResults(whichOptions)
// ***************** END FUNCTION TO FILTER AND DISPLAY RESULTS *************************************************************************************

// ***************** BEGIN FUNCTION TO ADD TO THE MAP THOSE MARKERS THAT MATCH THE SPECIFIED MAKE *************************************************************************************
function addMarkers(whichMake, whichCounty)
{

	for (key in markers)	// COMMENT: Loop through all of the markers.
	{
		if (markers[key].makes.indexOf(whichMake) > -1)	// COMMENT: Check if this marker has the specified make.
		{
			if ((whichCounty == "all") || (whichCounty == markers[key].county))	// COMMENT: Only map this marker if the county is "all" or matches.
			{
				if (!markers[key].marker)	// COMMENT: If the marker hasn't yet been added to the map, go ahead and add it now.
				{
					markers[key].marker = createMarker(key);
					map.addOverlay(markers[key].marker);
				}
				else // from if (!markers[key].marker)	// COMMENT: If the marker is already mapped but hidden, go ahead and show it now.
				{
					markers[key].marker.show();
				} // end else from if (!markers[key].marker)
				bounds.extend(markers[key].point);	// COMMENT: Extend the current bounds to enclose this point.
				numResults++;
			}
			else // from if ((whichCounty == "all") || (whichCounty == markers[key].county))	// COMMENT: Also check the county for this marker to make sure it matches (for when the user changes the county and a marker with a matched make but wrong county is on the map).
			{
				markers[key].marker.hide();
			} // end else from if ((whichCounty == "all") || (whichCounty == markers[key].county))
		}
	} // end for (key in markers)

} // end function addMarkers(whichMake, whichCounty)
// ***************** END FUNCTION TO ADD TO THE MAP THOSE MARKERS THAT MATCH THE SPECIFIED MAKE *************************************************************************************

// ***************** BEGIN FUNCTION TO ADD TO THE MAP THOSE MARKERS THAT MATCH THE SPECIFIED MAKE *************************************************************************************
function removeMarkers(whichMake, whichCounty)
{

	for (key in markers)	// COMMENT: Loop through all of the markers.
	{
		if (markers[key].makes.indexOf(whichMake) > -1)	// COMMENT: Check if this marker has the specified make.
		{
			var deleteFlag = 1;
			for (key2 in currentMakes)	// COMMENT: Loop through the current makes.
			{
				if (markers[key].makes.indexOf(key2) > -1)	// COMMENT: Don't delete this marker if it's make is still in the list of current makes (multiple makes per dealership)
				{
					deleteFlag = 0;
				} // end if (markers[key].makes.indexOf(key2) > -1)
			} // end for (key2 in currentMakes)
			if ((markers[key].marker) && (deleteFlag))
			{
				markers[key].marker.hide();	// COMMENT: Go ahead and hide this marker.
			//	document.getElementById("make_" + whichMake.replace(" ", "_")).checked = false;
			} // end if ((markers[key].marker) && (deleteFlag))
		}
	} // end for (key in markers)

} // end function removeMarkers(whichMake, whichCounty)
// ***************** END FUNCTION TO ADD TO THE MAP THOSE MARKERS THAT MATCH THE SPECIFIED MAKE *************************************************************************************

// ***************** BEGIN FUNCTION TO CLOSE THE 'NO MAKES FOUND' MESSAGE BOX *************************************************************************************
function toggleMessage(whichWay)
{

	document.getElementById('dealerdirectory_noresults').style.display = whichWay;

} // end function closeMessage()
// ***************** END FUNCTION TO CLOSE THE 'NO MAKES FOUND' MESSAGE BOX *************************************************************************************

function getStarted()
{
	document.getElementById('introMessage').style.display = "none";
}

function toggleAll(whichWay)
{

	switch (whichWay)
	{
		case "show" :
			document.getElementById("showAll").style.display = "none";
			document.getElementById("clearAll").style.display = "block";
			document.getElementById("make_all").checked = true;
			filterResults("all");
			break;
		case "clear" :
			document.getElementById("showAll").style.display = "block";
			document.getElementById("clearAll").style.display = "none";
			document.getElementById("make_all").checked = false;
			filterResults("all");
			break;
	}

}