$(document).ready(function() {

  buildErrorSpans();
  bindLoadingIndicators();
  bindFieldValidation();
  bindRegistrationFormSubmit();
  bindClubRegistrationDetails();

});


//
// bind check to validate per field
//
function bindFieldValidation() {

  $('.registrationFormField').blur( function() {
    var fieldName = $(this).attr('id');
    var fieldValue = $(this).val();
    var json = {field: fieldName, value: fieldValue};

    $.ajax({
      type: 'POST',
      url: '/registrations/validate_field',
      data: json,
      dataType: 'json',
      success: fieldResponse
    });

    //
    // handle the response for a given field validation
    //
    function fieldResponse(data) {
      // if there were errors, update the screen
      if(data) {
        if(data['errors']) {
          $('#' + fieldName + 'Error').show().text(data['errors'][fieldName]);
          $('#' + fieldName).addClass('registrationFormFieldError');
        }
      }
      // else clear them
      else {
        $('#' + fieldName + 'Error').hide();
        $('#' + fieldName).removeClass('registrationFormFieldError');
      }
    }

  });
}


//
// Registration form submission
//
function bindRegistrationFormSubmit() {
  $('#registrationSubmit').click( function() {

    // build JSON to POST
    var json = new Object;
    $('.registrationFormField').each( function() {
      var fieldName = $(this).attr('id');
      var fieldValue = $(this).val();
      json[fieldName] = fieldValue;
    });

    // also pick up hidden event ID field
    json['event_id'] = $('#event_id').val();


    $.ajax({
      type: 'POST',
      url: '/registrations/validate_form',
      data: json,
      dataType: 'json',
      success: formResponse
    });
  
  
    // 
    // handle the entire response
    //
    function formResponse(data) {

      if(data) {
        // loop through and identify any errors
        if(data['errors']) {
          for (var fieldName in data['errors']) {
            $('#' + fieldName + 'Error').show().text(data['errors'][fieldName]); 
            $('#' + fieldName).addClass('registrationFormFieldError');
          }
        }
        else if(data['success']) {
          // bind submit to disable after publishing
          $('#registrationSubmit').attr('disabled', 'true');

          // display registration success
          $('#registrationSuccess').fadeIn('fast');

          if (data['affectedClub']) {
            // highlight club registrant joined
            var id = data['affectedClub'].split(' ').join('');
            $('#' + id + 'Row').effect('highlight', {}, 5000);

            // update count
            var genderToUpdateClass = '.maleRegistrationTotal';
            if (data['affectedGender'] == 'F') {
              genderToUpdateClass = '.femaleRegistrationTotal';
            }
            var currentCount = $('#' + id + 'Row').children(genderToUpdateClass).text()  
            currentCount = parseInt(currentCount) + 1;
            $('#' + id + 'Row').children(genderToUpdateClass).text(currentCount);
          }
        }
      }
      else {
        $('#' + fieldName + 'Error').hide();
        $('#' + fieldName).removeClass('registrationFormFieldError');
      }
    }

  });
}

function buildErrorSpans() {
  $('.registrationFormField').each( function() {
    var fieldName = $(this).attr('id');
    $(this).after(buildErrorSpan(fieldName));
  });
}

function buildErrorSpan(fieldName) {
  return '<span id="' + fieldName + 'Error" class="registrationFormFieldError"></span>';
}

function bindLoadingIndicators() {
  $('.loadingIndicator').bind( 'ajaxSend', function(e, xhr, settings) {
    if (settings.url == '/registrations/validate_form') {
      $(this).text('Registering...');
    }
  }).bind('ajaxComplete', function(e, xhr, settings) {
    if (settings.url == '/registrations/validate_form') {

      var response = JSON.parse(xhr.responseText);
      if (response['success']) {
        $(this).text('Registration Complete');
      }
      else if (response['errors']) {
        $(this).text('You\'ll have to fix the highlighted errors before registering');
      }
      else {
        $(this).text('');
      }
    }
  });
}

function bindClubRegistrationDetails() {
  $('.eventClubRegistrationDetails').bind('click', function() {
  });

  $('.clubName').bind('click', function() {
    var club = $(this).children('a').text();
    var eventId = $('#hiddenEventId').text();
    var json = {"club":club, "eventId":eventId}
    json = JSON.stringify(json);
     
    $.ajax({
      type: 'POST',
      url: '/registrations/club_registration_details',
      data: json,
      contentType: 'application/json',
      dataType: 'json',
      success: buildClubRegistrationDetails
    });

  });
}

function buildClubRegistrationDetails(data) {
  //var response = data;
  var response = JSON.parse(data);
  $('#onlineRegistrationDetailsTitle').text(response.club);

  //clear existing values
  var registrantTableRows = $('#onlineRegistrationDetailsBody'); 
  registrantTableRows.children().remove();
  
  // make table of names
  for (var i = 0; i < response.registrants.length; i++) {
    registrantTableRows.append(buildRow(response.registrants[i]));
  }
}

function buildRow(registrant) {
  var row = document.createElement('tr');
  var td = document.createElement('td');
  td.innerHTML = registrant;

  row.appendChild(td);
  return row;
}

