﻿/* search.js
 *
 * This file deals with all of the searching done by the map,
 * including the US, Iraq, Afghanistan automatica positioning
 *
 */

var geocoder = null;
var marker = null;

function removeText(sInput)
{
	if (document.getElementById(sInput).value == "Search ICAO, Region or City Here")
		document.getElementById(sInput).value = "";
}

function addText(sInput, sText)
{
	if (document.getElementById(sInput).value == "")
		document.getElementById(sInput).value = sText;
}

function runSearch(sSearchText)
{
	if (sSearchText == "Search ICAO, Region or City Here")
		return;
		
	if (sSearchText.length > 0)
	{
		if (sSearchText.length > 4)
		{
			findAddress(sSearchText);
		} else
		{
			findICAO(sSearchText);
		}
	}
}

function doSearchSubmit(e)
{
	var key;

	if (window.event)
	{
		key = event.keyCode;     //IE
	}
	else
		key = e.which;      //firefox


	if (key == 13)
	{
		runSearch(document.getElementById("txtSearch").value);
		if (window.event)
		{
			event.cancelBubble = true;
			event.returnValue = false;
		}

		if (window.event)
			return true;
		else
			return false;
	}
}

// search-related functions
function findAddress(address)
{
	if (geocoder == null)
		geocoder = new GClientGeocoder();
		
	if (geocoder)
	{
		geocoder.getLatLng(
					address,
					function(point)
					{
						if (!point)
						{
							alert("Location " + address + " was not found. Check the spelling and try again.");
						}
						else
						{
							map.setCenter(point, 11);
							setMarker(null, point);
						}
					}
				);
	}
}

function findICAO(searchText)
{
	var result = Maca.Web.v3.WebServices.SeeAndAvoidService.SearchForLocation(searchText, SucceedCallbackICAO);
}

function SucceedCallbackICAO(result)
{
	eval(result);

	if (arrLatLng != null)
	{
		var point = new GLatLng(arrLatLng[0], arrLatLng[1]);
		map.setCenter(point, 11);
		setMarker(null, point);
	}
	else if (sAddrSearch != null)
	{
		findAddress(sAddrSearch);
	}
}

function setMarker(overxlay, latlong)
{

	if (!marker)
	{
		marker = new GMarker(latlong);

		map.addOverlay(marker);
	}
	else
	{
		marker.setLatLng(latlong);
	}

}

function fnShowHideDropDown()
{
	var objDropDown = document.getElementById("dropdown");
	objDropDown.style.display = (objDropDown.style.display == "none") ? "block" : "none";
}

function fnSetValue(strValue)
{
	switch (strValue)
	{
		case "US":
			map.setCenter(new GLatLng(38.5, -98), 4);
			break;
		case "IR":
			map.setCenter(new GLatLng(33.5, 44), 6);
			break;
		case "AF":
			map.setCenter(new GLatLng(34, 65), 6);
			break;
		default:
			map.setCenter(new GLatLng(38.5, -98), 4);
			break;
	}
	fnShowHideDropDown();
}