// remap jQuery to $
(function($){})(window.jQuery);


/* trigger when page is ready */
$(document).ready(function (){

	$("#showDialogue").click(function(){
		$("#dialogueContainer").fadeIn("slow");
	});
	
	$("#backgroundCover").bind("click", function(){
		$("#dialogueContainer").fadeOut("fast");
	});
	
	$("#bAdd").bind("click", function(){
		showLocation(); 
		return false;
	});

});

// 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) {
  $("#dialogueContainer").fadeOut("fast");
  map.clearOverlays();
  
  if (!response || response.Status.code != 200) {
    alert("Sorry, we were unable to place that address");
  }
  else {
    place = response.Placemark[0];
    point = new GLatLng(place.Point.coordinates[1],
                        place.Point.coordinates[0]);
	store_address(place.Point.coordinates[1], place.Point.coordinates[0], document.getElementById('emailaddress').value, document.getElementById('fullname').value);
    marker = new GMarker(point);
    map.addOverlay(marker);
    marker.openInfoWindowHtml(place.address + '<br>' + '<h3>A new Kyle lives here!<\/h3><p>Thank you for adding a Kyle to the planetary map of Kyles.<\/p>');
  }
}

// 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() {
  var email = $('#emailaddress').val();
  var name = $('#fullname').val();
  if(name.substring(4,0) != "Kyle" && name.substring(4,0) != "kyle"){
	 alert("It seems as though your name is not Kyle");
	 return false;
  }
  if(!validateEmail(email)){
	alert('Please enter a valid email address.');
	return false;
  }
  var address = document.forms[0].q.value;
  geocoder.getLocations(address, addAddressToMap);
}

// findLocation() is used to enter the sample addresses into the form.
function findLocation(address) {
  document.forms[0].q.value = address;
  showLocation();
}

function store_address(lat, lng, email, fullname){
	$.post("store_address.php",{lat: lat, lng: lng, action: "update", emailaddress: email, fullname: fullname}); 
	return false;
}

function selectField(el){
	if(el.value=="Email Address" || el.value=="Address" || el.value=="Full Name"){
		el.select()
	}
}

function validateEmail(src){
	var emailReg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*\.(\w{2}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum|ca))$/;
	var regex = new RegExp(emailReg);
	return regex.test(src);
}


/* optional triggers

$(window).load(function() {
	
});

$(window).resize(function() {
	
});

*/
