// if a field is bad, return any extra message this is supposed to provide
// to append to a string to be shown, and add the class "invalid" to the
// field (or remove it if the field is good).
function badField(fieldSelector,matchRegex,messageIfInvalid){
	var $elem=$(fieldSelector);
	if(!$elem.attr("value").match(matchRegex)){
		$elem.addClass("invalid");
		return (messageIfInvalid == undefined ? '' : messageIfInvalid);
	}
	$elem.removeClass("invalid")
	return "";
}

// Validate the contact form.
function vContactForm(){
	var bad='';
	bad += badField("#cname", /\w+\s+\w+/i, "Please include your first and last name.\r\n");
	bad += badField("#cemail", /^[A-Z0-9._%+-]+@(?:[A-Z0-9\-]+\.)+[A-Z]{2,4}$/i, "Please include a valid email address.\r\n");
	//bad += badField("#cphone", /(?:1[-. ]?)?\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4}).*/i, "Please include your 10-digit phone number.\r\n");
	bad += badField("#message", /.+/i, "Please include a message.\r\n");
	if (bad.length > 0) {
		// we have errors
		$("#contactFormError").remove();
		$("#contactForm").prepend("<div id=\"contactFormError\"><p>There is a problem sending the contact form.</p><ul><li>" + bad.substring(0, bad.length - 2).replace("\r\n", "</li><li>") + "</li></div>");
		return false
	}
	return true
}


// After page is loaded...
$(function() {

  // Replace map with interactive version.
  //  $("#map").css("display", "none").after("<iframe src=\"http:\/\/maps.google.com/maps?f=q&amp;source=s_q&amp;hl=en&amp;geocode=&amp;q=orange+county+wound+and+hyperbaric&amp;sll=37.0625,-95.677068&amp;sspn=46.898798,55.898438&amp;ie=UTF8&amp;iwloc=near&amp;ll=33.75166,-117.834909&amp;spn=0.080263,0.040284&amp;output=embed\"></iframe>");
  //  $("#map").remove();

  // For any mailto links, replace " AT " and " D0T " - fools simple email scrapers.
  $("a[href^=mailto]").each(function() {
    $(this).attr("href", $(this).attr("href").replace(/%20AT%20| AT /g, "@").replace(/%20D0T%20| D0T /g, "."));
    $(this).html($(this).html().replace(/%20AT%20| AT /g, "@").replace(/%20D0T%20| D0T /g, "."));
  });

  // validate contact form
  $("#contactForm").submit(vContactForm);

  // If #photoGallery exists and lightbox is loaded, lightbox it
  if (typeof $("#photoGallery").lightBox == 'function') {
    $("#photoGallery li a").lightBox({
      overlayBgColor: "#ccf",
      overlayOpacity: 0.8
    });
  }
  //}

  // LAST: embed Google maps instead of the static image
  if ($("#directionsPage").length > 0) {
    var gmEmbed = "<iframe id=\"map\" scrolling=\"no\" src=\"{0}\"></iframe>"
    var mapUrl = $("#directionsPage #map").attr("href");
    $("#directionsPage #map").after(gmEmbed.replace(/\{0\}/, mapUrl + "&amp;output=embed"));
    $("#directionsPage #map").remove();
    mapUrl = $("#directionsPage #map2").attr("href");
    $("#directionsPage #map2").after(gmEmbed.replace(/\{0\}/, mapUrl + "&amp;output=embed"));
    $("#directionsPage #map2").remove();
  }

});
