(function($) {
  $(function() {
    
    ////
    // Project Initiation form
    if ($("form#new_project").size() > 0) {
      var total_cost_node     = $("p#total-cost span.dollars"),
          project_code_node   = $("input#project_code"),
          total_cost          = 0,
          survey_cost         = 0,
          rater_charge        = 0,
          surveys             = $('input[name="project[survey_id]"]'),
          survey_participants = 0;

      // Survey buttons
      $('input[name="project[survey_id]"]').click(function() {
        // hide coupon field if this survey doesn't allow coupons
        if ($(this).hasClass("allow-coupons")) {
          project_code_node.parent().show();
        } else {
          project_code_node.parent().hide();
        }

        project_code_node.val("");
      }).filter(":checked").click();

      // Practitioner is contact? radio buttons
      $('input[name="project[practitioner_is_contact]"]').click(function() {
        var contact_info = $(this).parents("fieldset").find("fieldset");
        
        if ($('input[name="project[practitioner_is_contact]"]:checked').val() == "true") {
          contact_info.fadeOut();
        } else {
          contact_info.fadeIn();
        }
      }).filter(":checked").click();

      // Add participant link
      $("p.add_participant a").click(function() {
        var new_row = $("tr.participant:last").clone();
        
        new_row.find("input").each(function() {
          var self      = $(this),
              name      = $(this).attr("name"),
              id        = $(this).attr("id");
              new_index = parseInt(name.match(/\[(\d+)\]/)[1]) + 1;

          self.val("");
          self.attr("name", name.replace(/\[\d+\]/, "[" + new_index + "]"));
          self.attr("id", id.replace(/_\d+_/, "_" + new_index + "_"));
        });
        new_row.find("span").removeClass("fieldWithErrors");
        $("table#participants tbody").append(new_row);
        
        calculate_total();
        return false;
      });
      
      // Delete participant link
      $("table#participants tr.participant td:nth-child(4) a").live("click", function() {
        if ($("tr.participant").size() == 1) {
          $("p.add_participant a").click();
        }
        
        $(this).parents("tr.participant").remove();

        calculate_total();
        return false;
      });
      
      // Datepickers
      $('input[name="project[initiation_date]"]').datepicker({
        dateFormat: 'yy-mm-dd',
        hideIfNoPrevNext: true,
        minDate: first_available_start_date(),
        beforeShowDay: function(date) {
          if (date.getDay() == 2 || date.getDay() == 4) {
            return [true, ''];
          } else {
            return [false, ''];
          }
        },
        onClose: function(date) {
          var init = Date.parse(date);
          $("label[for$=reminder_1_date]").parent().find("em")
            .text(init.add(7).days().toString('MMMM dd, yyyy'));
          $("label[for$=reminder_2_date]").parent().find("em")
            .text(init.add(7).days().toString('MMMM dd, yyyy'));
          $("label[for$=feedback_due_date]").parent().find("em")
            .text(init.add(5).days().toString('MMMM dd, yyyy'));
          $("label[for$=reminder_3_date]").parent().find("em")
            .text(init.add(2).days().toString('MMMM dd, yyyy'));
          $("label[for$=completion_date]").parent().find("em")
            .text(init.add(7).days().toString('MMMM dd, yyyy'));
        }
      });
      
      // Toggle $50 fee message
      $('input[name="project[self_selecting_raters]"]').click(function() {
        var message = $('p.rater_message');
        
        if ($('input[name="project[self_selecting_raters]"]:checked').val() == 'true') {
          message.fadeOut();
        } else {
          message.fadeIn();
        }
      }).filter(':checked').click();
      

      function first_available_start_date() {
        var today = Date.today();
        
        switch (today.getDay()) {
          case 0:
            return today.add(2).days()
          case 1:
            return today.add(1).day();
          case 2:
            return today.add(2).days();
          case 3:
            return today.add(1).day();
          case 4:
            return today.add(5).days();
          case 5:
            return today.add(4).days();
          case 6:
            return today.add(3).days();
        }
      }

      $("input").live("click", calculate_total);

      function calculate_total() {
        survey_participants = $("tr.participant").size();

        if ($('input[name="project[self_selecting_raters]"]:checked').val() == 'true') {
          rater_charge = 0;
        } else {
          rater_charge = 50;
        }

        survey_cost = surveys.filter(":checked").parent().find("span.dollars").text() || "0";
        survey_cost = parseFloat(survey_cost.replace(/[$,]/g, ""));

        total_cost = (survey_cost + rater_charge) * survey_participants;

        total_cost_node.text("$" + total_cost.toFixed(2));
      }

      calculate_total();
    }
    
  });
})(jQuery);
