function ValidateAndSubmit(evt) {
    var $group = $(evt.currentTarget).closest('fieldset');
    var isValid = true;
    var firstInvalidItem = null;
    var j = 0;
    $group.find(':input').each(function (i, item) {
        if (!$(item).valid()) {
            isValid = false;
            if (++j == 1) firstInvalidItem = item;
        }
    });
    if (!isValid) {
        evt.preventDefault();
        firstInvalidItem.focus();
    }
}

$(document).ready(function () {
    $('#main-nav > ul')
            .supersubs({
                minWidth: 8,
                maxWidth: 20,
                extraWidth: 1
            })
            .superfish({
                autoArrows: false
            });

    $('#homepage-slideshow').cycle({
        fx: 'fade',
        speed: 500,
        timeout: 8000
    });

    $('div.gallery-wrapper').cycle({
        fx: 'fade',
        speed: 200,
        timeout: 0,
        prev: '#gallery-prev',
        next: '#gallery-next'
    });

    $('#Form1').validate({
        onsubmit: false,
        errorPlacement: function (error, element) { return true; }
    });
    $('fieldset .causesValidation').click(ValidateAndSubmit);
    $('fieldset :text').keydown(function (evt) {
        if (evt.keyCode == 13) {
            evt.preventDefault();
            var $nextInput = $(this).nextAll(':input:first');
            if ($nextInput.is(':submit, :image')) $nextInput.click();
            else $nextInput.focus();
        }
    });
    $('#news-items a.gallery-image').colorbox({ rel: 'gallery', slideshow: true, slideshowAuto: true, photo: true, width: 780, height: 540, initialWidth: 780, initialHeight: 540, slideshowSpeed: 2000 });
    $('a.gallery-image img').hover(function() {
        $(this).stop().animate({opacity: "0.6"}, 'fast');
    },
    function() {
        $(this).stop().animate({opacity: "1"}, 'fast');
    });
});
