// -- instance of DealerSvcClass for use in page
var DealerSvc = new DealerSvcClass();

window.addEvent('domready', function()
{	
	// -- continent select
	var continent;

	// -- country select
	var country;

	// -- region select
	var region;
	
	if (continent = $('continent')) 
	{
		continent.addEvent('change', function()
		{
			var value = continent.get('value');
			if (value != 0 && value != '')
			{
				addSelectOptions('Loading...', $('country'), null);
				addSelectOptions('Select a region', $('region'), null);
				
				var params = {continent : value};
				/* when continent is selected, load countries as result */
				DealerSvc.search(DealerSvc.CONTINENTS, params, onCountries);
			}
		});
	}
	
	if (country = $('country'))
	{
		country.addEvent('change', function()
		{
			var value = country.get('value');
			if (value != 0 && value != '')
			{
				// alert(value);
				addSelectOptions('Loading...', $('region'), null);
				
				var params = {country : value};
				/* when country is selected, load regions as result */
				DealerSvc.search(DealerSvc.COUNTRIES, params, onRegions);
			}
		});
	}
	
	if (region = $('region'))
	{
		region.addEvent('change', function()
		{
			var continentValue = continent.get('value');
			var countryValue = country.get('value');
			// var regionValue = (continentValue == 1) ? region.get('value') : region.get('text');
			
			var regionValue = region.get('value');
			
			if (countryValue != 0 && countryValue != '' && regionValue != 0 && regionValue != '')
			{
				// alert(countryValue + " " + regionValue);
				$('dealer_search_result').innerHTML = '<em>Searching for dealers...</em>';
				var params = {country: countryValue, region: regionValue};
				/* when region is selected, load dealers as result */
				DealerSvc.search(DealerSvc.REGIONS, params, onDealers);
			}
		});
	}
	
	var rangeSearch;
	if (rangeSearch = $('rangeSearch'))
	{
		rangeSearch.addEvent('click', function()
		{
			tryRangeSearch();
		});
	}
	
	var zipField;
	if (zipField = $('zip'))
	{
		zipField.addEvent('keypress', function(event) 
		{
			var event = new Event(event);
			if (event.key == 'enter')
				tryRangeSearch();
		});
	}
	
});

function addSelectOptions(defaultStr, select, results)
{
	var option = new Option(defaultStr, '', true, false);
	select.options.length = 0;
	
	// -- sorry, WC3 I have to make IE happy
	//select.add(option, null);
	select.options[select.options.length] = option;
	
	if (results)
	{
		for (var i = 0; i < results.length; i++) 
		{
			var pair = results[i];
			option = new Option(pair[1], pair[0], false, false);
			// -- and again with the IE
			//select.add(new Option(pair[1], pair[0], false, false), null);
			select.options[select.options.length] = option;
		}
	}
}

function onCountries(text, xml)
{
	if (text.length) 
	{		
		var results = parseXmlListToArray(xml);
		var select = $('country');
		addSelectOptions('Select a country', $('country'), results);
	}
}

function onDealers(text, xml)
{
	$('dealer_search_result').innerHTML = text;
}

function onRegions(text, xml)
{
	if (text.length) 
	{
		var results = parseXmlListToArray(xml, null, true);
		var select = $('country');
		addSelectOptions('Select a region', $('region'), results);	
	}
}

function parseDealerList(data)
{
	document.write(data);
}

function parseXmlListToArray(xml, tag, reversed) 
{
	tag = tag || 'KeyValuePairOfstringstring';
	reversed = reversed || false;
	var xmlList = xml.getElementsByTagName(tag);
	var results = [];
	for (var i = 0; i < xmlList.length; i++)
	{
		var key;
		var keyNode;
		var value;
		var valueNode;
		if (!reversed)
		{
			if (keyNode = xmlList[i].getElementsByTagName("key")[0].firstChild) 
			{
				key = keyNode.nodeValue;
			}
			else
			{
				key = "";
			}
			if (valueNode = xmlList[i].getElementsByTagName("value")[0].firstChild) 
			{
				value = valueNode.nodeValue;
			}
			else 
			{
				value = key;
			}
		}
		else 
		{
			if (valueNode = xmlList[i].getElementsByTagName("key")[0].firstChild) 
			{
				value = valueNode.nodeValue;
			}
			else 
			{
				value = '';
			}
			if (keyNode = xmlList[i].getElementsByTagName("value")[0].firstChild) 
			{
				key = keyNode.nodeValue;
			}
			else
			{
				key = value;
			}
		}
		results[i] = [key, value];
	}
	return results;
}

function tryRangeSearch()
{
	var withinValue = parseInt($('range').get('value'));
	var zipValue    = $('zip').get('value');
	
	if (!withinValue) withinValue = 10;
	
	if (zipValue.length)
	{
		$('dealer_search_result').innerHTML = "<em>Searching in " + zipValue + ' within ' + withinValue + " miles...</em>"
		var params = {zip: zipValue, radius: withinValue};
		DealerSvc.search(DealerSvc.ZIPCODE, params, onDealers);
	}
}


/******

LEGACY MAP CODE

******/


var map;
var geocoder;
var strShopDetails = "";
var boolMapVisible = false;

function doMapLoad() 
{
	map = new GMap2(document.getElementById("map"));
	map.setCenter(new GLatLng(33.642699, -117.735932), 10);
	map.addControl(new GLargeMapControl()); //map.addControl(new GSmallMapControl());
	geocoder = new GClientGeocoder();
}

// addAddressToMap() is called when the geocoder returns an answer.  
// It adds a marker to the map with an open info window showing the nicely 
// formatted version of the address and the country code.
function addAddressToMap(response) 
{
	map.clearOverlays();
	if (!response || response.Status.code != 200) 
	{
		//alert("Sorry. We were unable to map that address. \n\n [" + response.Status.code + "]");
		//AGMapToggle(false);
	} 
	else 
	{
		//AGMapToggle(true)
		place = response.Placemark[0];
		point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
		marker = new GMarker(point);
		map.addOverlay(marker);

		//irv coords
		//alert(place.Point.coordinates[1] + ' -- ' + place.Point.coordinates[0]);

		//text for popup
		marker.openInfoWindowHtml('<div class=\"mapBubbleText\">' + strShopDetails +  '</div>');

		//marker.openInfoWindowHtml(place.address + '<br>');
		//+ '<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode);
	}
}

// showLocation() is called when you click on the Search button in the form.  It geocodes the address entered into the form and adds a marker to the map at that location.
function showLocation(address) 
{
	//alert(address);
	geocoder.getLocations(address, addAddressToMap);
}

function googleLoadDealerMap(strAddressForMap, shopDetails)
{
	var enableGoogleMap = true;
	var f = '|';
	var r = ',';
	var addr = strAddressForMap.replace(f,r).replace(f,r);

	if (enableGoogleMap)
	{
		//test - showLocation("8750 Research Drive, Irvine, CA, USA");
		showLocation(addr);
		strShopDetails  = shopDetails;
	}
	
	return false;
}

function AGMapToggle(boolShow) 
{
	if (boolShow) 
	{
		// document.getElementById("rightContentContainer_Map").style.visibility = 'visible';
		// document.getElementById("rightContentContainer_Map").style.display = 'block';

		document.getElementById("map").style.visibility = 'visible';
		document.getElementById("map").style.display = 'block';

		// document.getElementById("NoResultsMessage").style.visibility = 'hidden';
		// document.getElementById("NoResultsMessage").style.display = 'none';
	} 
	else 
	{
		// document.getElementById("rightContentContainer_Map").style.visibility = 'visible';
		// document.getElementById("rightContentContainer_Map").style.display = 'block';

		document.getElementById("map").style.visibility = 'hidden';
		document.getElementById("map").style.display = 'none';

		// document.getElementById("NoResultsMessage").style.visibility = 'visible';
		// document.getElementById("NoResultsMessage").style.display = 'block';
	}
}

function AGMapClose() 
{
	//document.getElementById("rightContentContainer_Map").style.visibility = 'hidden';
	//document.getElementById("rightContentContainer_Map").style.display = 'none';
}
