// 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
}

// Replace map with interactive version.
function fixMaps() {
    // class=map applied to A element with IMG inside
    $("a.map").each(function() {
        var that = this;
        var href = $(this).attr("href");
        var id = $(this).attr("id");
        var classes = $(this).attr("class");
        var output = "<iframe src=\"" + href + "&output=embed" + "\" class=\"" + classes + "\" id=\"" + id + "_int\"></iframe>";
        $(this).after(output);
        $(this).remove();
    });
}

// fixes widowed words
function widont() {
    $('h1,h2,h3,li,p').each(function() {
        $(this).html($(this).html().replace(/\s([^\s<]{0,10})\s*$/, '&nbsp;$1'));
    });
}

// Sets up DT/DD elements to show/hide when title clicked.
// Pass a filter variable to affectChildrenOfElement, or leave blank to affect all DL lists.
// We assume these have one DD to a DT.
function setupDTDDHideShow(affectChildrenOfElement) {
/*    // wraps DT in A element that shows/hides the first DD element underneath it.
    $(affectChildrenOfElement + " dt").each(function() {
        var that = this;
        $(this).next("dd").hide();
        $(this).wrap("<a></a>").css("cursor", "pointer");
        $(this).click(function() {
            var obj = $(this).next("dd");
            var isHidden = (obj.css("display") == none);
            if (isHidden) { obj.show("fast"); } else { obj.hide("fast"); }
        });
    });
*/}

// Makes links open in their own window
function makeExternalLinksOpenInNewWindow() {
    var url = window.location.href; //.replace(/(http:\/\/[A-Za-z0-9\-_\.]+?)\/.*/i, "$1");
    var defaultWindowOptions = "";
    var links = $("a");
    for (var i = 0; i < links.length; i++) {
        var l = links[i];
        if ( ( ($(l).attr("href").indexOf("http://") == 0 || $(l).attr("href").indexOf("https://") == 0) && $(l).attr("href").indexOf(url) != 0 ) || $(l).attr("rel") == "external") {
            $(l).click(function() {
                window.open($(this).attr("href"), "", defaultWindowOptions, true);
                return false; // prevent click through
            });
        }
    }
}

// After page is loaded...
$(function() {

    // Interactive maps
    fixMaps();

    makeExternalLinksOpenInNewWindow();

    // 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 $(".photos").lightBox == 'function') {
        $(".photos a").lightBox({
            overlayBgColor: "#009",
            overlayOpacity: 0.8,
            imageLoading: "/global/images/lightbox-ico-loading.gif",
            imageBtnClose: "/global/images/lightbox-btn-close.gif",
            imageBtnPrev: "/global/images/lightbox-btn-prev.gif",
            imageBtnNext: "/global/images/lightbox-btn-next.gif",
            imageBlank: "/global/images/lightbox-blank.gif"
        });
    }
    //}

    // fix widowed words
    widont();

    // set up FAQ to hide/show DT DDs
    setupDTDDHideShow("#faq");

});
