// ================================================================================================
// Navigation

function goCountry(linkTarget)
{
	countryid = document.forms['locNav'].countryid.value;
	document.location = linkTarget+"?selectedloc=1&countryid="+countryid;
}

function goState(linkTarget)
{
	countryid = document.forms['locNav'].countryid.value;
	stateid   = document.forms['locNav'].stateid.value;
	
	if (stateid)
	{
		document.location = linkTarget+"?selectedloc=1&countryid="+countryid+"&stateid="+stateid;
	}
	else
	{
		goCountry();
	}
}

function goCity(linkTarget)
{
	countryid = document.forms['locNav'].countryid.value;
	stateid   = document.forms['locNav'].stateid.value;
	cityid    = document.forms['locNav'].cityid.value;
	
	if (stateid)
	{
		document.location = linkTarget+"?selectedloc=1&countryid="+countryid+"&stateid="+stateid+"&cityid="+cityid;
	}
	else
	{
		goState();
	}
}

// ================================================================================================
// Directory Listing Form

function directoryBrowseSection(sectionName)
{
	subcategoryDivId = "categories-"+sectionName;
	
	if (document.getElementById(subcategoryDivId))
	{
		styleDisplay = document.getElementById(subcategoryDivId).style.display;
		//console.log(sectionName, styleDisplay);
		
		if (styleDisplay == 'block')
		{
			directoryBrowseSectionOff(sectionName);
		}
		else
		{
			directoryBrowseSectionOn(sectionName);
		}
	}
}

function directoryBrowseSectionOff(sectionName)
{
	// Switch the Section to Closed
	document.getElementById('section-'+sectionName).className = 'SectionClosed';
	
	// Hide the categories
	document.getElementById('categories-'+sectionName).style.display = 'none';
}

function directoryBrowseSectionOn(sectionName)
{
	// Switch the Section to Open
	document.getElementById('section-'+sectionName).className = 'SectionOpen';
	
	// Show the categories
	document.getElementById('categories-'+sectionName).style.display = 'block';
}

// ================================================================================================
// Directory Listing Form

function directoryListingSection()
{
	sectionSelector = document.getElementById('sectionid');
	
	sectionId = sectionSelector.value;
	sectionName = sectionSelector.options[sectionSelector.selectedIndex].innerHTML;
	
	if (!sectionName)
	{
		sectionName = 'none';
	}
	
	categoryDisplay(sectionName);
}

function categoryDisplay(sectionName)
{
	categorySelectOff();
	categorySelectOn(sectionName);
}

function categorySelectOff()
{
	for (var z = 0; z < sectionIds.length; z++)
	{
		//console.log("switching off "+sectionIds[z]);
		document.getElementById('categoryselect'+sectionIds[z]).style.display = 'none';
	}
	document.getElementById('categoryselectnone').style.display = 'none';
}
function categorySelectOn(sectionName)
{
	//console.log("looking for sectionName", sectionName);
	document.getElementById('categoryselect'+sectionName).style.display = 'block';
}

// ================================================================================================
// Place a listing on the map

var mapMarkers = [];

function plotListing(listingId)
{
	//console.log("plotListing(",listingId,")");
	
	if (mapMarkers[listingId])
	{
		//console.log("already plotted...");
		mapMarkers[listingId].remove();
	}
	
	myListing = listingData[listingId];
	
	lat = myListing.lat;
	lon = myListing.lon;
	name = myListing.name;
	text = myListing.description;
	
	//console.log("lat/lon = "+lat+"/"+lon);
	
	thisMarker = new GMarker(new GLatLng(lat, lon));
	
	map.addOverlay(thisMarker);
	
	dropMarker(thisMarker, 200);
	
	GEvent.addListener(thisMarker, "click", function() {
		thisMarker.openInfoWindowHtml("<h3>"+name+"</h3><p>"+text+"</p>");
	});
	
	mapMarkers[listingId] = thisMarker;
}

// Drop marker from above
// http://onewheeledbicycle.com/2008/08/21/dropping-pins-in-google-maps/
function dropMarker(marker, height)
{
	// Make bouncable
	if (!marker.Xa)
	{
		marker.Xa = true;
		marker.qo(false);
	}
	marker.Pa = height;	// Current height
	marker.ri = height;	// Max height
	marker.av = 1;		// Direction (+ = down)
	marker.tc();		// Go baby!
}


// ================================================================================================
// Update Map

var AjaxLocation = 
{
	handleSuccess: function(o)
	{
		// o.responseText
		// o.responseXML
		//console.log(o.responseText);
		this.processResult(o);
	},
	handleFailure: function(o)
	{
		// o.responseText
		// o.responseXML
	},
	processResult: function(o)
	{
		//console.log("prefix=", this.prefix);
		
		try
		{
			var data = YAHOO.lang.JSON.parse(o.responseText);
		}
		catch (e)
		{
			// Error in JSON data!
		}
		
		//console.log("states:", states);
		//console.log("states length:", states.length);
		
		if (typeof(data) == "undefined")
		{
		}
		else
		{
			//console.log(data);
			
			newLat = data.geocode[0];
			newLon = data.geocode[1];
			newZoom = data.zoom;
			
			//console.log(newLat, newLon, newZoom);
			
			map.setCenter(new GLatLng(newLat, newLon), newZoom);
		}
	},
	startRequest: function(countryId, stateId, cityId)
	{
		YAHOO.util.Connect.asyncRequest('GET', '/ajax/location.php?countryid='+countryId+"&stateid="+stateId+"&cityid="+cityId, locationCallback);
	}
};

var locationCallback = {
	success: AjaxLocation.handleSuccess,
	failure: AjaxLocation.handleFailure,
	scope: AjaxLocation
};

function changeMapLocation(country, state, city)
{
	AjaxLocation.startRequest(country, state, city);
}

function updateMap(prefix, caller)
{
	//console.log("update map");
	//console.log("caller", caller);
	//console.log("caller id", caller.id);
	callerType = caller.id.substring((prefix.length+1));
	//console.log("callerType", callerType);
	
	countryid = document.getElementById(prefix+"-country").value;
	stateid   = 0;
	cityid    = 0;
	
	if (callerType == 'state' || callerType == 'city')
	{
		stateid = document.getElementById(prefix+"-state").value;
	}
	
	if (callerType == 'city')
	{
		cityid = document.getElementById(prefix+"-city").value;
	}
	
	//console.log("countryid", countryid, "stateid", stateid, "cityid", cityid);
	
	if (!markerPlaced)
	{
		changeMapLocation(countryid, stateid, cityid);
	}
}

// ================================================================================================

function emptyCategories(selectid)
{
	//console.log("emptySelector()", selectid);
	document.getElementById(selectid).options.length = 0;
}

var AjaxSectionChange = 
{
	sectionElementId: false,
	categoryElementId: false,
	showalltext: false, 
	handleSuccess: function(o)
	{
		// o.responseText
		// o.responseXML
		//console.log(o.responseText);
		this.processResult(o);
	},
	handleFailure: function(o)
	{
		// o.responseText
		// o.responseXML
	},
	processResult: function(o)
	{
		try
		{
			var categories = YAHOO.lang.JSON.parse(o.responseText);
		}
		catch (e)
		{
			// Error in JSON data!
		}
		
		//console.log("states:", states);
		//console.log("states length:", states.length);
		
		if (typeof(categories) == "undefined")
		{
			emptyCategories(this.categoryElementId);
		}
		else
		{
			emptyCategories(this.categoryElementId);
			
			if (this.showalltext)
			{
				document.getElementById(this.categoryElementId).options[(i+1)] = new Option('All Categories', 0);
			}
			
			if (categories.length > 0)
			{
				for (var i = 0; i < categories.length; i++)
				{
					cat = categories[i];
					//console.log(cat);
					
					var icount = this.showalltext ? (i+1) : i;
					
					document.getElementById(this.categoryElementId).options[icount] = new Option(cat.name, cat.id);
				}
			}
		}
	},
	startRequest: function(sectionElementId, categoryElementId, showalltext)
	{
		this.sectionElementId  = sectionElementId;
		this.categoryElementId = categoryElementId;
		this.showalltext       = showalltext;
		
		value = document.getElementById(sectionElementId).value;
		
		if (value == 0)
		{
			emptyCategories(categoryElementId);
			return;
		}
		else if (showalltext)
		{
			YAHOO.util.Connect.asyncRequest('GET', '/ajax/directory-categories.php?sectionname='+value, sectionChangeCallback);
		}
		else
		{
			YAHOO.util.Connect.asyncRequest('GET', '/ajax/directory-categories.php?sectionid='+value, sectionChangeCallback);
		}
	}
};

var sectionChangeCallback = {
	success: AjaxSectionChange.handleSuccess,
	failure: AjaxSectionChange.handleFailure,
	scope: AjaxSectionChange
};

function changeCountry(prefix)
{
	countryId = document.getElementById(prefix+'-country').value;
	
	AjaxCountryChange.startRequest(prefix, countryId);
}

function updateCategories(sectionElementId, categoryElementId, showalltext)
{
	AjaxSectionChange.startRequest(sectionElementId, categoryElementId, showalltext);
}

function updateBudget(sectionElementId)
{
	value = document.getElementById(sectionElementId).value;
	//alert(value);
	if (value == 1 || value == 3)
	{
		document.getElementById("BudgetBox").className = "";
	}
	else
	{
		document.getElementById("BudgetBox").className = "BudgetHide";
	}
}

// ================================================================================================
// Google Maps Geocode API

var markerPlaced = false;
var markerHtml = false;

var placePoint = function(point, isDraggable, adminMode)
{
	if (typeof(isDraggable) == "undefined")
	{
		isDraggable = true;
	}
	
	if (typeof('adminMode') == 'undefined')
	{
		adminMode = false;
	}
	
	if (!markerPlaced)
	{
		if (!point)
		{
			point = map.getCenter();
		}
		
		// Don't zoom if you're in admin mode
		if (!adminMode)
		{
			map.setCenter(point, 14);
		}
		
		marker = new GMarker(point, {draggable:isDraggable});
		map.addOverlay(marker);
		
		//marker.openInfoWindowHtml(markerHtml);
		
		if (document.getElementById('geocode_lat') && document.getElementById('geocode_lon'))
		{
			ll = marker.getLatLng();
			document.getElementById('geocode_lat').value = ll.y;
			document.getElementById('geocode_lon').value = ll.x;
			//console.log("lat=", document.getElementById('geocode_lat').value);
			//console.log("lon=", document.getElementById('geocode_lon').value);
		}
		
		GEvent.addListener(marker, "dragstart", function() {
			map.closeInfoWindow();
		});
		
		GEvent.addListener(marker, "dragend", function() {
			//marker.openInfoWindowHtml(markerHtml);
			
			ll = marker.getLatLng();
			document.getElementById('geocode_lat').value = ll.y;
			document.getElementById('geocode_lon').value = ll.x;
			//console.log("lat=", document.getElementById('geocode_lat').value);
			//console.log("lon=", document.getElementById('geocode_lon').value);
		});
		
		markerPlaced = true;
	}
}

function geocodeString(string)
{
	//console.log("geocoding '", string, "'");
	
	var geocoder = new GClientGeocoder();
	geocoder.getLatLng(string, placePoint);
}

function placeMarker()
{
	//console.log("placeMarker()");
	//console.log("markerPlaced=",markerPlaced);
	
	if (!markerPlaced)
	{
		building = document.forms['listingForm'].building.value;
		address1 = document.forms['listingForm'].address1.value;
		address2 = document.forms['listingForm'].address2.value;
		suburb   = document.forms['listingForm'].suburb.value;
		postcode = document.forms['listingForm'].postcode.value;
		country  = document.forms['listingForm']['location-country'].options[document.forms['listingForm']['location-country'].selectedIndex].innerHTML;
		
		/*building = document.listingForm.building.value;
		address1 = document.listingForm.address1.value;
		address2 = document.listingForm.address2.value;
		suburb   = document.listingForm.suburb.value;
		postcode = document.listingForm.postcode.value;
		country  = document.forms.listingForm['location-country'].options[document.forms.listingForm['location-country'].selectedIndex].innerHTML;*/
		
		markerElements = [];
		//if (building) { markerElements.push(building); }
		if (address1) { markerElements.push(address1); }
		if (address2) { markerElements.push(address2); }
		if (suburb)   { markerElements.push(suburb); }
		if (postcode) { markerElements.push(postcode); }
		if (country)  { markerElements.push(country); }
		//console.log("markerElements=",markerElements);
		
		// Make sure we have enough detail in the address supplied
		if (markerElements.length > 2)
		{
			geocodeStr = markerElements.join(", ");
			//console.log("geocodeStr=",geocodeStr);
			
			markerHtml = markerElements.join("<br>");
			//console.log("markerHtml=",markerHtml);
			
			// Send it off to be geocoded and a marker placed
			geocodeString(geocodeStr);
		}
		else
		{
			//console.log("not geocoded");
			// Can't geocode, just put the marker in the centre of the map
			placePoint(map.getCenter(), true);
		}
	}
	else
	{
		//console.log("marker already placed");
	}
}

function removeMarker()
{
	//console.log("removeMarker");
	if (typeof(marker) != "undefined")
	{
		marker.remove();
		markerPlaced = false;
		document.getElementById('geocode_lat').value = 0;
		document.getElementById('geocode_lon').value = 0;
	}
}