// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
// var $j = jQuery.noConflict();

jQuery.fn.adjust_all_fees = function() {
  var reg_type = $("input[id^=registration_missionary]:checked").val();
  var is_special = reg_type == "missionary" || reg_type == "seminarian";
  var adult_fee = "$225.00";
  var child_fee = "$75.00";
  var kid_cnt = 0;
  if (is_special) {
    adult_fee = "$125.00";
    child_fee = 0;
  }
  $(".attendee:visible").each(function(){
    var fee_field = $(this).find("input.fees");
    if ( $(this).find("input.age_radio_button:checked").val() == 'child' ) { 
      kid_cnt += 1;
      if (kid_cnt > 2) {child_fee = 0;};
      $(fee_field).val(child_fee);
    }
    else {
      $(fee_field).val(adult_fee);
    }
  });
}

jQuery.fn.calc_total = function() {
  if ( $(".attendee").size() > 0){
    var total = 0;
    $(".attendee:visible input.fees").each(function(){
      total += Number($(this).val().replace(/\$/,"")); // get rid of the dollar sign
    })
    if ($("input[id=registration_make_donation_true]").attr("checked")) {
      total +=  Number($("input[id=registration_donation]").val().replace(/\$/,""));
    }
    total +=  Number($("input[id=registration_cc_fee]").val().replace(/\$/,""));
    $("#registration_amt").val("$" + total.toFixed(2));
  }
}

// adjust_fee ONLY handles the radio buttons - a better name may be in order
jQuery.fn.adjust_fee = function(this_one) {
  var this_array = $(this_one).attr("id").split("_");
  var this_type = this_array.pop();
  
  switch (this_type){
    case "missionary":
      $(".agency_field").show();
      if(typeof agency != "undefined") { agency.destroy(); }
      agency = new LiveValidation('registration_agency', {validMessage: "Don't forget the country!"});
      agency.add(Validate.Presence, {failureMessage: "Must enter agency!"});
      $("label[for=registration_agency]:first").html("Mission Agency: <span class='help'>include where you serve</span>");
      $(".agency_field input#registration_agency").focus();
      $().adjust_all_fees();
      break;
    case "seminarian":
      if(typeof agency != "undefined") { agency.destroy(); }
      agency = new LiveValidation('registration_agency', {validMessage: "thank you"});
      agency.add(Validate.Presence, {failureMessage: "Must enter seminary!"});
      $("label[for=registration_agency]:first").html("Seminary: ");
      $(".agency_field").show();
      $("input#registration_agency").focus();
      $().adjust_all_fees();
      break;
    case "regular":
      if(typeof agency != "undefined") { agency.destroy(); }
      $(".agency_field").hide();
      $("input[id=registration_agency]").val("");
      $().adjust_all_fees();
      break;
    case "adult":
      $(this_one).parents('.left_col').children(".children_fields").hide();
      $().adjust_all_fees();
      break;
    case "child":
      $(this_one).parents('.left_col').children('.children_fields').show();
      $(this_one).parents('.left_col').children('.children_fields').find("input:text:first").focus();
      $().adjust_all_fees();
      //$("input[id=" + child_age +"]");
      break;
    case "true": // this is really weak, only allows one T/F radio button
      donation = new LiveValidation("registration_donation", {validMessage: "thank you for helping! (hit <tab> to re-calculate total)"});
      donation.add(Validate.Presence, {failureMessage: "please enter an amount"});
      donation.add(Validate.Numericality, {failureMessage: "must be a number"});
      $("#make_donation").show();
      $("input#registration_donation").get(0).focus();
      break;
    case "false": // this is really weak, only allows one T/F radio button
      $("#make_donation").hide();
      break;
  }
  //$(this_fee).val(the_fee);
  $().calc_total();
};

jQuery.fn.validate_fname = function(this_one) {
  var first_name = new LiveValidation($(this_one).attr("id"), {validMessage: "Thank You!"});
  first_name.add(Validate.Presence, {failureMessage: "Must enter a first name!"});    
};

jQuery.fn.validate_lname = function(this_one) {
  var last_name = new LiveValidation($(this_one).attr("id"), {validMessage: "Thank You!"});
  last_name.add(Validate.Presence, {failureMessage: "Must enter a last name!"});    
};

jQuery.fn.validate_name_tag = function(this_one) {
  var name_tag = new LiveValidation($(this_one).attr("id"), {validMessage: "Thank You!"});
  name_tag.add(Validate.Presence, {failureMessage: "Must enter a name for your name tag!"});    
};

jQuery.fn.validate_street = function(this_one) {
  var street = new LiveValidation($(this_one).attr("id"), {validMessage: "Thank You!"});
  street.add(Validate.Presence, {failureMessage: "Must enter a street address or PO box number!"});    
};

jQuery.fn.validate_city = function(this_one) {
  var city = new LiveValidation($(this_one).attr("id"), {validMessage: "Thank You!"});
  city.add(Validate.Presence, {failureMessage: "City name!"});    
};

jQuery.fn.validate_state = function(this_one) {
  var state = new LiveValidation($(this_one).attr("id"), {validMessage: "Thank You!"});
  state.add(Validate.Presence, {failureMessage: "Must enter name of state, province or region!"});    
};

jQuery.fn.validate_zip = function(this_one) {
  var zip = new LiveValidation($(this_one).attr("id"), {validMessage: "Thank You!"});
  zip.add(Validate.Presence, {failureMessage: "Must enter a zip or postal code!"});    
};

jQuery.fn.validate_country = function(this_one) {
  var country = new LiveValidation($(this_one).attr("id"), {validMessage: "Thank You!"});
  country.add(Validate.Presence, {failureMessage: "Must enter country!"});    
};

jQuery.fn.validate_email = function(this_one) {
  var email = new LiveValidation($(this_one).attr("id"), {validMessage: "Thank You!"});
  email.add(Validate.Presence, {failureMessage: "Must enter an email address!"});
  email.add(Validate.Email, {failureMessage: "Must enter a valid email address!"});
};

jQuery.fn.validate_donation = function(this_one) {
  var donation = new LiveValidation($(this_one).attr("id"), {validMessage: "Thank You for helping! (press tab to recalculate total)"});
  donation.add(Validate.Presence, { failureMessage: 'Do not leave blank (If you are going to donate, you must donate something!).'});
  donation.add(Validate.Numericality, {minimum: 0, tooLowMessage: "Sorry, you can't take money from us!", notANumberMessage: "Only numbers are allowed here."});
};

jQuery.fn.validate_age = function(this_one) {
  var age = new LiveValidation($(this_one).attr("id"), {validMessage: "Thank you!", onInvalid: function(){
    this.insertMessage(this.createMessageSpan() );
    this.addFieldClass();
    var txt = $(this.element).next("span").text();
    $(this.element).next("span.LV_invalid").html( txt ); // display message as html
  }});
  var msg = 'Over 13 is considered an adult<br />Consider re:mix <a href="http://www.rocktheworld.org/Group/Group.aspx?ID=1000032814" target="_blank">Click Here</a> (opens new window)';
  age.add(Validate.Presence, {failureMessage: "Must enter Age"});
  age.add(Validate.Numericality, {maximum: 13, tooHighMessage: msg});
};

jQuery.fn.adjust_age_fee = function(this_one) {
  var this_array = $(this_one).attr("id").split("_");
  var this_age = "input#" + this_array[0] + "_" + this_array[1] + "_age"
  var age = Number( $(this_one).val() );
  if ( age > 13 ){ $(this_age).val("adult"); }
  else { $(this_age).val("child"); }
  $().adjust_all_fees();
  $().calc_total();
}
// ...............................................
jQuery(function(){
  $(document).ready(function(){
      $('.rounded').corners();
      $('#shadow img')
        .height( $('fieldset#main').height() + 100)
        .width( $('fieldset#main').width() + 100);
      $('#navigation').dropDownMenu({timer: 500, parentMO: "parent_mo", childMO: "child_mo", levels: ['nav_top', 'nav_below']});
      $("table.striped tr:even").css("background-color", "#bbbbff");
      $("table.striped tr:odd").css("background-color", "#ffffff");
      
      var hx1 = $('#praytoday').height();
      var hx2 = $('#specialprayers').height();
      if (hx1 > hx2) {
        $('#specialprayers').height(hx1 + 16); // I have no idea why I have to add 16 to make it blip free
      } else {
        $('#praytoday').height(hx2);
      }
      $.editable.addInputType('autogrow',{
        element : function (settings, original) {
          var textarea = $('<textarea>');
          if (settings.rows) {
            textarea.attr('rows', settings.row);
          } else {
            textarea.height(settings.height);
          }
          if (settings.cols) {
            textarea.attr('cols', 'settings.cols');
          } else {
            textarea.width(settings.width);
          }
          $(this).append(textarea);
          return(textarea);
        },
        plugin : function(settings, origianl) {
          $('textarea', this).autogrow(settings.autogrow);
        }
      });
      $('.edit_area').editable('/stories/update_column',{
        loadurl: "/stories/show_column",
        loadtype: "POST",
        cancel: 'Forget it!',
        submit: 'Save it!',
        tooltip: "Click to edit...",
        type: 'autogrow',
        width: 700,
        autogrow : {
                lineHeight : 12,
                maxHeight  : 512
            }

      });
      $('.edit').editable('/stories/update_column',{
        loadurl: "/stories/show_column",
        loadtype: "POST",
        cancel: 'Forget it!',
        submit: 'Save it!',
        tooltip: "Click to edit...",
        width: 500
      });

      $('.edit_ticket_area').editable('/tickets/update_column',{
        loadurl: "/tickets/show_column",
        loadtype: "POST",
        cancel: 'Forget it!',
        submit: 'Save it!',
        tooltip: "Click to edit...",
        type: 'autogrow',
        width: 700,
        autogrow : {
                lineHeight : 12,
                maxHeight  : 512
            }

      });
      $('.edit_ticket').editable('/tickets/update_column',{
        loadurl: "/tickets/show_column",
        loadtype: "POST",
        cancel: 'Forget it!',
        submit: 'Save it!',
        tooltip: "Click to edit...",
        width: 500
      });

    });

    $(document).everyTime("20s", "prayers", function(){
      if ($("#specialprayers").text().length > 50 ) {
        $("#praytoday").toggle();
        $("#specialprayers").toggle();
      }
    });

    $().calc_total();
    
    $("input[id=registration_donation]").blur(function(){
      $().calc_total();
      return false;
    });
    
    $("input[id$=first_name]").focus(function(){
      $().validate_fname(this);
      return false;
    });
    
    $("input[id$=first_name]").blur(function(){
      $(this).closest(".attendee").find("input[id$=name_tag]").val( $(this).val() );
      return false;
    });
    
    $("input[id$=last_name]").focus(function(){
      $().validate_lname(this);
      return false;
    });
    
    $("input[id$=name_tag]").focus(function(){
      $().validate_name_tag(this);
      return false;
    });
    
    $("input[id$=street]").focus(function(){
      $().validate_street(this);
      return false;
    });
    
    $("input[id$=city]").focus(function(){
      $().validate_city(this);
      return false;
    });
    
    $("input[id$=state]").focus(function(){
      $().validate_state(this);
      return false;
    });
    
    $("input[id$=zip]").focus(function(){
      $().validate_zip(this);
      return false;
    });
    
    $("input[id$=country]").focus(function(){
      $().validate_country(this);
      return false;
    });
    
    $("input[id$=_email]").focus(function(){
      $().validate_email(this);
      return false;
    });
    
    $("input[id$=registration_donation]").focus(function(){
      $().validate_donation(this);
      return false;
    });
    
    $("input[id$=_age_yo]").focus(function(){
      $().validate_age(this);
      return false;
    });
    
  
  $(".toggle_tag_cloud").click(function(){
    $("#tag_cloud").toggle();
    return false;
  });
  
  // remove a family member - 
  // not needed. fn bound when adding a family member
  
  // add a family member
  $("input#add_another").click(function(){
    var index = Number( $(".attendee").size() + $(".xattendee").size() );
    var is_regular = $("input#registration_missionary_regular").attr("checked") == "checked";
    var new_div = "#[id=div_attendee_" + index + "]";
    var this_button = this;
    var pattern = /\d/;
    var last_age = $(".attendee:last input[label=Adult or Child?]:checked");
    var last_street = $("textarea[id$=street]:last").val(); // text area doesn't clone!
    var last_city = $("textarea[id$=city]:last").val(); // valzv doesn't clone!
    $(".attendee:last").clone().appendTo("#all_attendees");
    $().calc_total();
    //if($(".attendee:last .right_col").css("margin-top") == "-107px"){
    //  $(".attendee:last .right_col").css("margin-top", "-110px");
    //};
    $("textarea[id$=street]:last").val(last_street);
    $("textarea[id$=city]:last").val(last_city);
    $(".show_address:last").empty();
    $(".attendee:last input").each(function(){
      $(this).attr("name", $(this).attr("name").replace(pattern, index) );
      $(this).attr("id", $(this).attr("id").replace(pattern, index) );
    });
    $(".attendee:last textarea").each(function(){
      $(this).attr("name", $(this).attr("name").replace(pattern, index) );
      $(this).attr("id", $(this).attr("id").replace(pattern, index) );
    });
    // The following keeps the last age radio-button set correctly when cloning
    // and must come after the resetting of names and ids - or it doesn't work!
    $(last_age).attr("checked", "checked");
    var new_div = $(".attendee:last"); // this is the NEW last attendee
    //$(".attendee:last input[id$=last_name]").val($(".attendee:visible:eq(next_to_last) input[id$=last_name]").val());
    // bind the <Remove> button and it's function to remove a family member
    $(".add_on:last").show();
    $(".attendee:last .show_address_fields").hide();
    $(".attendee:last .show_address").show();
    $(".attendee:last label[for$=email] strong").remove();
    $("input.drop_attendee:last").bind("click", function(){
      $(new_div).hide().addClass("xattendee").removeClass("attendee").empty();
      $().adjust_all_fees(); // must do this in case a child is dropped
      $().calc_total();
    });
    $(new_div).find("input.age_radio_button").each(function(){
      $(this).bind("click", function(){$().adjust_fee(this); });
    });
    $(".attendee:last input[id$=age_yo]").bind("blur", function(){ $().adjust_age_fee(this); });
    $(".attendee:last input[id$=age_yo]").bind("focus", function(){ $().validate_age(this); });
    $(".attendee:last input[id$=title]").val("");
    $(".attendee:last input[id$=first_name]").bind("focus", function(){ $().validate_fname(this); });
    $(".attendee:last input[id$=first_name]").bind("blur", function(){ 
      $(this).closest(".attendee").find("input[id$=name_tag]").val( $(this).val() );
     }).focus();
    $(".attendee:last input[id$=first_name]").val("");
    $(".attendee:last input[id$=middle_name]").val("");
    $(".attendee:last input[id$=last_name]").bind("focus", function(){ $().validate_lname(this); });
    $(".attendee:last input[id$=suffix]").val("");
    $(".attendee:last input[id$=name_tag]").bind("focus", function(){ $().validate_name_tag(this); });
    $(".attendee:last input[id$=name_tag]").val("");
    $(".attendee:last label[for$=email]").css("color", "#000000");
    $(".attendee:last label[for$=email]").val("");
    $().adjust_all_fees();
    $().calc_total()
    return false;
  });
  
  $("input[id$=_age_yo]").blur(function(){
    $().adjust_age_fee(this);
    return false;
  });
  
  $("input:radio").change(function(){
    $(this).attr("checked", "checked");
    if ( $(this).attr("id") == "registration_make_donation_true" ){ 
      $("#donation_field").show();
      $("input#registration_donation").focus(); 
    }
    if ( $(this).attr("id") == "registration_make_donation_false" ){ $("#donation_field").hide(); }
    $().adjust_fee(this);
    return false;
  });
  
  return false;
});
