$(document).ready(function() {
  $(".slideshow").each(function() {
    var i = 0;
    var $slideshow = $(this);
    var $slides = $(".slide", $slideshow);
    $slides.css({'clear':'both', 'display':'block'});
    var $n = $(".next", $slideshow);
    var $b = $(".back", $slideshow);
    var $f = $(".finished", $slideshow);
    var c = this;
    function update_slide() {
      $slides.hide();
      $($slides[i]).show();
      (i >= ($slides.length-1)) ? $n.hide() : $n.show();
      (i <= 0) ? $b.hide() : $b.show();
      (i == ($slides.length-1)) ? $f.show() : $f.hide();
    };
    update_slide.apply(c);
    function validate() {
      var $s = $($slides[i]);
      if ($(".required", $s).length > 0) {
        var missing = [];
        $(".required", $s).each(function() {
          if ((($(this).attr('type') == 'checkbox') && !$(this).attr('checked')) || $(this).val().length == 0) {
            missing.push("- " + $("label", $(this).parent()).html().replace(/:$/,'').replace(/<span[^>]*>[^<]*<\/span>/i, ''));
          }
        });
        if (missing.length > 0) {
          alert("Please complete all required fields: \n\n" + missing.join("\n")); 
          return false;
        }
      }
      return true;
    };
    $n.click(function(ev) {
      if (!validate.apply(c)) {
        ev.stopPropagation();
        return false;
      } else {
        i++;
        update_slide.apply(c);
      }
    });
    $f.click(function(ev) {
      if (!validate.apply(c)) {
        ev.stopPropagation();
        return false;
      } else {
        $("form:first").submit();
      }
    });
    $b.click(function() {
      i--;
      update_slide.apply(c);
    });
  });
});

