/* Utility functions */
/* Requires jquery */

String.prototype.trim=function(){
    return this.replace(/^\s*|\s*$/g,'');
}

jQuery.fn.filterDropdown = function () {
	return this.each(function () {
		var D = $(this);
		var C = "";
		if ($("option", D).length <= 15) {
			return;
		}
//		D.css("width", D.css("width"));
//		D.css("height", D.css("height"));
		var E = D.attr("name") + "_searchbox";
		var A = $("<span />").insertAfter(D);
		$("<img />").attr("src", "/images/mag_glass.png").css("margin-left", "5px").css("vertical-align", "middle").toggle(function () {
			var F = $("#" + E)[0];
			F.__optioncache = [];
			$("option", D).each(function () {
				F.__optioncache.push(this);
			});
			C = "";
			$("#" + E).show()[0].focus();
		}, function () {
			C = D.val();
			$("#" + E).hide().val("").keyup();
		}).appendTo(A);
		var B = $("<input type=\"text\" />").attr("id", E).css("width", "100px").hide().appendTo(A).keyup(function () {
			var selectedVal = $("#"+D.attr("id")+" :selected").val();
			var I = this.value.toLowerCase();
			var H = this.__optioncache;
			for (var G = 0, F = D[0].options.length; G < F; G++) {
				D[0].options[0] = null;
			}
			for (var G = 0, F = H.length; G < F; G++) {
				if (H[G].text.toLowerCase().indexOf(I) != -1) {
					D[0].options.add(H[G], D[0].options.length);
				}
			}
			$("#"+D.attr("id")).val(selectedVal);
		});
	});
};

function geocode() {
	google.load("maps", "2", {"callback" : findLatLon});
}

function findLatLon() {
	var geocoder = new GClientGeocoder();
	
	var searchby = $("input[@name='searchby']:checked").val();

	if (searchby == 'club') {
		var club = $('#club :selected').val();
		var clubname = $('#club :selected').text();

		if (club != "") {
			$('#clubname').val(clubname);
			document.forms['find'].submit();
		}
		else {
			return false;
		}
	}
	else if (searchby == 'region') {
	
		var city = $("#city").val().trim();
		var province = $('#province :selected').val().trim();
		var country = $('#country :selected').val().trim();

		if (country == "") {
			return false;
		}

		var arrAddress	= new Array();
		if (city != "") { arrAddress.push(city); }
		if (province != "") { arrAddress.push(province); }
		if (country != "") { arrAddress.push(country); }
		var address = arrAddress.join(", ")

		var radius = $('#radius :selected').val().trim();
		if (radius == "" || province == "" || city == "") {
			if ($("#find").valid()) {
				$("#find").submit();
			}
		}
		else {
			geocoder.getLatLng(address, function(point) {
				if (point) {
					$("#lat").val(point.lat());
					$("#lon").val(point.lng());
					if ($("#find").valid()) {
						 $("#find").submit();
					}
					else {
						return false;
					}
				}
				else {
					alert(address+" not found.  Please correct the address and try again.");
					return false;
				}
			});
			return false;
		}
	}
}

function populateCities() {
	var country = $('#country :selected').val();
	var province = $('#province :selected').val();
	
	$.getJSON('/php-r/populatecities_json.php', {country: country, province: province}, function(json){ 
		$("#city").setOptions({data: json});	
  	}); 
}

function setDirections(fromAddress, toAddress) {
  map.clearOverlays();
  gdir.load("from: " + fromAddress + " to: " + toAddress);
  $('#fromAddress').val(fromAddress);
}

function handleErrors(){
   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
     alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
     alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);

   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
     alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);

//   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);

   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
     alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
     alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);

   else alert("An unknown error occurred.");

}

function showAddress(name, address) {
  var geocoder = new GClientGeocoder();
  geocoder.getLatLng(address,
    function(latlng) {
      if (!latlng) {
//        alert(address + " not found");

      } else {
        map.setCenter(latlng, 13);

		var marker = createMarker(latlng,name,address);
		map.addOverlay(marker);
      }
    }
  );
}


function createMarker(point,name,address) {
  var marker = new GMarker(point);

  // The info window version with the "to here" form open
  var html = '<b>'+name+'</b><br />'+address + '<br />Get directions to here from:<br />' +
     '<form action="#" onsubmit="setDirections(this.from.value, this.to.value); return false">' +
     '<input type="text" size="40" maxlength="40" name="from" id="from" value="" /><br />' +
     '<input value="Get Directions" type="submit" /><br />' +
     '<input type="hidden" name="to" id="to" value="'+name+"@"+ point.lat() + ',' + point.lng() + '" />';

  GEvent.addListener(marker, "click", function() {
    marker.openInfoWindowHtml(html);
  });
  return marker;
}