jQuery(function ($) {
  var notify = (function () {
    var ongoing = null;
    var origPos = $("#alert").css("top");

    $("#alert").click(function () {
      if (ongoing) window.clearTimeout(ongoing);
      $("#alert").animate({ "bottom": origPos });
    });
    
    var fancyAlert = function (message) {
      $("#alert .content").text(message);
      $("#alert").animate({ "top": "0" });
      if (ongoing) window.clearTimeout(ongoing);
      ongoing = window.setTimeout(function () {
        $("#alert").animate({ "top": origPos });
      }, 5000);
    };
    
    return function (message) {
      alert(message);
    };
  })();

  // ensure agreement is noted
  $("form.agreement-required").submit(function () {
    if (!$("#agree", this).attr("checked")) {
      notify("To continue with registration, you must check the box to " +
        "indicate that you understand and agree to the Club Guidelines.");
      return false;
    }
  });
  
  // puts a total figure in the last cell in any row with a class of "total"
  function update_totals() {
    $("tr.total").each(function () {
      var totalCell = $(this).find("> :last-child"); // the total cell is the last cell in the row
      var total = 0;
      $(this).siblings().each(function () {
        var cell = $(this).find("> :last-child:visible"); // find the cell in the last column
        var text = cell.text();
        if (text && text.match(/[0-9]+/)) { // find the first number in the text
          total += parseInt(text.match(/[0-9]+/)[0], 10);
        }
      });
      var oldValue = $(totalCell).text();
      $(totalCell).text(oldValue.replace(/[0-9]+/, total)); // replace the first number with the total
    });
  }
  
  // when a checkbox is toggled:
  // - enable or disable elements with a class name of 'enabled-by:' and the checkbox ID
  // - show or hide elements with a class name of 'displayed-by:' and the checkbox ID
  // - update totals (using function above)
  function checkbox_toggled() {
    var checkbox = this;
    var checked = $(checkbox).attr("checked");
    $(".enabled-by\\:" + checkbox.id).attr("disabled", checked ? "" : "disabled");
    $(".displayed-by\\:" + checkbox.id)[checked ? "show" : "hide"]();
  }

  // trigger both the above functions when changing a checkbox
  $("form input[type=checkbox]")
    .click(checkbox_toggled)
    .click(update_totals);
  
  // handle initial state of form
  $("form input[type=checkbox]").each(checkbox_toggled);
  update_totals();
  
  // when submitting a form, include an extra hidden field in the submission for each checkbox:
  // - the name of the field is the name of the checkbox with "-selected" appended
  // - the value of the field is "Yes" if the checkbox is checked, or "No" if not
  $("form").submit(function () {
    var form = this;
    $("input[type=checkbox]", form).each(function () {
      var checkbox = this;
      var id = checkbox.id + "-selected";
      var selected = $(checkbox).attr("checked") ? "Yes" : "No";
      if ($("#" + id).length == 0) {
        var $input = $("<input type='hidden'>");
        $input.attr("id", id).attr("name", id);
        $(form).append($input);
      }
      $('#' + id).attr("value",  selected);
    });
  });
  
  // ensure non-optional fields in each form are completed
  $("form.validated").submit(function () {
    var missingInfo = false;
    $(this).find("input, textarea").each(function () {
      if ($(this).hasClass("optional") || $(this).is(":disabled")) return; // skip optional fields
      var highlight = $(this).closest("tr");
      if ($(this).val() == "") {
        $(highlight).addClass("missing");
        missingInfo = true;
      } else {
        $(highlight).removeClass("missing");
      }
    });
    if (missingInfo) {
      notify("To submit your registration, you need to complete all required fields. These " +
        "are indicated in red.");
      return false;
    }
  });
  
  $(".slideshow").each(function () {
    var slideshow = this;
    $(slideshow).css("display", "block");
    
    var images = $("img", this);
    $(images).wrap($("<span class='slide'><a href='/gallery/'></a></span>"));
    
    var slides = $(".slide", this);
    var last = 0;
    $(slides[last]).css("opacity", "1.0");
    $(slides[last]).css("display", "block");
    
    var next = last + 1;
    if (next >= slides.length)
      next = 0;
    
    var start = new Date().getTime();
    setInterval(function () {
      $(slides[next]).css("display", "block");
      $(slides[next]).prependTo(slideshow).animate({ opacity: 1 }, 2000);
      $(slides[last]).animate({ opacity: 0 }, 2000, function () {
        $(this).css("display", "").css("opacity", "");
      });
      last = next;
      next++;
      if (next >= slides.length)
        next = 0;
    }, 6000);
  });
  
  // automatically focus the first control that requests it
  $(".autofocus").focus();
  
  // slideshow on photos
  $("a.photo").fancybox();
});