// 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'));
    });
}

// For any mailto links, replace " AT " and " D0T " - fools simple email scrapers.
function fixEmailAddresses() {
    $("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, "."));
    });
}


// If #photoGallery exists and lightbox is loaded, lightbox it
function setupPhotoListsWithLightbox(){
    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"
        });
    }
}

// All external links should open in a new window. Text is appended to the link title to indicate that 
// clicking the link opens in a new window.
function openAllExternalLinksInNewWindow() {
    $("a[href^=http]").not("a[href^=#]").each(function() {
        if (this.href.indexOf(location.hostname) == -1) {
            var newTitle = $(this).attr("title") + " (opens in a new window)";
            $(this).attr('target', '_blank').attr("title", newTitle).find("img").attr("title", newTitle);
        }
    });
}


// After page is loaded...
$(function() {

    // Interactive maps
    fixMaps();

    fixEmailAddresses();

    // validate contact form
    $("#contactForm").submit(vContactForm);

    setupPhotoListsWithLightbox();

    // fix widowed words
    widont();

    openAllExternalLinksInNewWindow();

    /* specific to cabelo ---- */

    // Disable skype from messing up phone # on top
    $("#topheader .tel").html("(727) 372<span style=\"display:none;\">_</span>-5555");


});
