$(document).ready(function() {
  // If something has the .default_focus class, give it the focus first before anything else grabs it
  $( '.default_focus' ).focus();

  // Brute-force hiding of everything on a page with a details_fld class
  $( '.conditional_reveal_element' ).hide();

  // Initialize the thickbox settings
  if ('function' == typeof tb_init) {
    tb_init('a.thickbox, area.thickbox, input.thickbox');
    imgLoader = new Image();
    imgLoader.src = "http://assets.max.adobe.com/images/loadingAnimation.gif";
  }

  $( '.details_toggle' ).each( details_toggle );

  $( '.checkbox_toggle' ).each( checkbox_toggle );

  $( '.radio_toggle' ).each( radio_toggle );

  $( '.required' ).each( requirify_labels );

  $( '.error' ).each( errorify_labels );

  $( '.item_show_labs' ).click( show_pre_conference_labs );

  $( '.item_hide_labs' ).click( hide_pre_conference_labs );

  $( '.hotel_toggle' ).each( hotel_toggle );

  $( '.hotel_block_toggle' ).each( hotel_block_toggle );

  $( '.item_toggle' ).each( item_toggle );

  $( '.take_two_toggle' ).each( take_two_toggle );

  $( '.add_to_waiting_list' ).each( add_to_waiting_list );


  $('body.nominations,body.promotions').each(function() {
    $(this)
      .find('#show_hotel_blocks')
        .each(hotelBlockDisplay)
        .click(hotelBlockDisplay);

    $(this)
      .find('input:checkbox#nomination_cross_charge,input:checkbox#promotion_cross_charge')
        .each(costCenterDisplay)
        .click(costCenterDisplay);

    // FIXME: figure out why this code does not work on the administrator screen
    if ($(this).hasClass('administrator'))
      return;

    // show/hide nominees
    $(this)
      .find('input:radio[name="nomination[nomination_type]"]')
        .each(nomineeDisplay)
        .click(nomineeDisplay);
 });

});

// Show/hide any text_area fields associated with an element defined by .details_toggle
function details_toggle()
{
  var details = $('#' + $(this).attr('id') + '_details').parent('div');

  var showHide = function() {
    var show = $(this).val() == 'Other (Please Specify)' || $(this).val() == 'Allergy (Please Specify)';
    details[ show ? 'show' : 'hide' ]();
  };

  // set the initial state of the details properly
  $(this).each(showHide);

  // show the details when "Other" option is selected or loses focus
  $(this).change(showHide).blur(showHide);
}

// Toggles other page elements based on whether or not a checkbox is checked
// To use this, give the checkbox a class of .checkbox_toggle and id the element to be affected
// the same id as the checkbox appended with _details
function checkbox_toggle()
{
 // setting the click action
 $( this ).click( function() {
  var target_id = ( '#' + $( this ).attr( 'id' ) ).replace( /_+[0-9]+/, '' )  + '_details';
   var target_div = $( target_id ).parent( 'div' );

   if ( $( this ).is( ':checked' ) )
     { target_div.show(); }
   else
     { target_div.hide(); }
 });

 // get the state and hiding/showing...
 var target_id = ( '#' + $( this ).attr( 'id' ) ).replace( /_+[0-9]+/, '' )  + '_details';
  var target_div = $( target_id ).parent( 'div' );

  if ( $( this ).is( ':checked' ) )
    { target_div.show(); }
  else
    { target_div.hide(); }
}

function radio_toggle()
{
 $( this ).click( function() {
  var target_id = ( '#' + $( this ).attr( 'id' ) ).replace( /_+[0-9]+/, '' )  + '_details';
  var target_div = $( target_id ).parent( 'div' );

  // Hide all other elements marked with conditional_reveal_element
  $( '.conditional_reveal_element' ).hide();

  // Show just the one attached to this radio button
  target_div.show();

  // Select the first form element within the div that was just shown
  target_div.find( "input[type='text']:first" ).focus();
  });

 // find the checked radio button... get the target_div... hide the others, and show it!
 var target_id = ( '#' + $( this ).attr( 'id' ) ).replace( /_+[0-9]+/, '' )  + '_details';
 var target_div = $( target_id ).parent( 'div' );

 if ( $( this ).is( ':checked' ) )
 { target_div.show(); }
 else
 { target_div.hide(); }
}

// make required field labels have the required class!
function requirify_labels()
{
  $('label[for='+$(this).attr('id')+']').addClass('required');
}

// make error field labels have the error class!
function errorify_labels()
{
  $('label[for='+$(this).attr('id')+']').addClass('error');
}

function showRoommateDetails(element)
{
  $('#roommates').hide();
  $('#roommate1').hide();
  $('#roommate2').hide();
  $('#roommate3').hide();

  if (element.value == '2' || element.value == '3' || element.value == '4')
  {
    $('#roommates').show();
    $('#roommate1').show();
  }

  if (element.value == '3' || element.value == '4')
  {
    $('#roommate2').show();
  }

  if (element.value == '4')
  {
    $('#roommate3').show();
  }
}

function show_pre_conference_labs()
{
  $('#pre_conference_labs').show();
}

function hide_pre_conference_labs()
{
  $('#no-pre-event-lab').attr("checked", true);

  $('#pre_conference_labs').hide();
}

function delete_contents_if_off( checkbox_obj, field_id )
{
  if ( checkbox_obj.checked )
  {  }
  else
  {
   field = $( field_id );
   field.val("");
  }
}

function hotelBlockDisplay() {
  var visible = $('#show_hotel_blocks').is(':checked');
  $('#hotel_blocks')[ visible ? 'show' : 'hide' ]();
}

function costCenterDisplay() {
  var costCenter = $('#nomination_cost_center,#promotion_cost_center').parent('div');
  var visible    = $(this).is(':checked');

  costCenter[ visible ? 'show' : 'hide' ]();
}

/* ------------------------------ Nomination scripts ------------------------------ */
// if the nomination type "organization" is checked, then display
// the nominee name, otherwise keep it hidden
// UPDATED: hide "Why should I attend" and Justification as well
// UPDATED: bunch more logic for show/hide depending on the radio button chosen
function nomineeDisplay() {
  var nomineeFirstName = $('#nomination_nominee_firstname');
  var nomineeLastName = $('#nomination_nominee_lastname');
  var nomineeCompanyName = $('#nomination_nominee_name');

  var trainingSelect 		= 	$('#training_select');
  var organizationSelect 	=	$('#organization_select');
  var meetingSelect	 		=	$('#meeting_select');
  var supportSelect	 		=	$('#support_select');


  var codesRequested = $('#codes_requested');

  var nomineeCrossCharge = $('#nomination_cross_charge');
  var companyApproveText = $('#companyApproval');
  var personalApproveText = $('#personalApproval');

  // for a customer
  if($('#nomination_type_organization').is(':checked'))
  {
    nomineeFirstName
      .removeAttr('disabled')
      .parent('div:hidden')
        .show();

 nomineeLastName
     .removeAttr('disabled')
     .parent('div:hidden')
       .show();

  nomineeCompanyName
      .removeAttr('disabled')
      .parent('div:hidden')
        .show();


 // kinda hacky: show/hide select lists
 organizationSelect.show();
 trainingSelect.hide();
 meetingSelect.hide();
 supportSelect.hide();
 codesRequested.show();
 companyApproveText.show();
 personalApproveText.hide();
  }
  // personal for training
  else if($('#nomination_type_training').is(':checked'))
  {
 nomineeFirstName
      .attr('disabled', 'disabled')
      .parent('div:visible')
        .hide();

    nomineeFirstName.val('');

 nomineeLastName
      .attr('disabled', 'disabled')
      .parent('div:visible')
        .hide();

    nomineeLastName.val('');

  nomineeCompanyName
      .attr('disabled', 'disabled')
      .parent('div:visible')
        .hide();

    nomineeCompanyName.val('');

 // kinda hacky: show/hide select lists
 organizationSelect.hide();
 trainingSelect.show();
 meetingSelect.hide();
 supportSelect.hide();
 codesRequested.hide();
 companyApproveText.hide();
 personalApproveText.show();
  }
  // myself to attend MAX/meetings
  else if($('#nomination_type_meeting').is(':checked'))
  {
    nomineeFirstName
      .attr('disabled', 'disabled')
      .parent('div:visible')
        .hide();

    nomineeFirstName.val('');

 nomineeLastName
      .attr('disabled', 'disabled')
      .parent('div:visible')
        .hide();

    nomineeLastName.val('');

  nomineeCompanyName
      .attr('disabled', 'disabled')
      .parent('div:visible')
        .hide();

    nomineeCompanyName.val('');

 // this ONE has NO cross charge
 nomineeCrossCharge.val('false')

 // kinda hacky: show/hide select lists
 organizationSelect.hide();
 trainingSelect.hide();
 supportSelect.hide();
 meetingSelect.show();
 codesRequested.hide();
 companyApproveText.hide();
 personalApproveText.show();
  }
  // myself to support MAX programs
  else
  {
    nomineeFirstName
      .attr('disabled', 'disabled')
      .parent('div:visible')
        .hide();

    nomineeFirstName.val('');

 nomineeLastName
      .attr('disabled', 'disabled')
      .parent('div:visible')
        .hide();

    nomineeLastName.val('');

  nomineeCompanyName
      .attr('disabled', 'disabled')
      .parent('div:visible')
        .hide();

    nomineeCompanyName.val('');

 // this ONE has NO cross charge
 nomineeCrossCharge.val('false')

 // kinda hacky: show/hide select lists
 organizationSelect.hide();
 trainingSelect.hide();
 supportSelect.show();
 meetingSelect.hide();
 codesRequested.hide();
 companyApproveText.hide();
 personalApproveText.show();
  }

}

function hideNominationProducts()
{
  $('#nomination_product_id')
    .parent('div:visible')
      .hide();
}



/* ------------------------------ Nomination scripts ------------------------------ */


/* ------------------------------ Javascript Form Validations ------------------------------ */

// Validates that the contact info form contains the content it should before we ever send it back to the server for data validation
function validate_contact_info_form()
{
 var result = true;
 var el = $( '#community_membership' );
 var fld1 = $( '#community_leader_first_name' );
 var fld2 = $( '#community_leader_last_name' );

 if ( el && fld1 && el.is( ':checked' ) && ( '' == fld1.val() ) )
 {
  result = false;
  fld1.focus();
  alert( 'Please enter a valid Community Leader first name.' );
 }
 else if ( el && fld2 && el.is( ':checked' ) && ( '' == fld2.val() ) )
 {
  result = false;
  fld2.focus();
  alert( 'Please enter a valid Community Leader last name.' );
 }

 return result;
}


// Validates that the item form contains the content it should before we ever send it back to the server for data validation
function validate_items_form()
{
 var result = true;

 var el = $( '#guest_pass_checkbox' );
 var fld = $( '#guest_name' );

 if ( el && fld && el.is( ':checked' ) && ( '' == fld.val() ) )
 {
  result = false;
  fld.focus();
  alert( 'Please enter a valid name for your Guest Social Pass.' );
 }

 return result;
}

function hotel_toggle()
{

 //alert("toggle " + path_prefix + "/administrators/hotel_detail/" + $( this ).attr( 'id' ));

 $( this ).click( function() {
  var target_id = ( '#' + $( this ).attr( 'id' ) ).replace( /_+[0-9]+/, '' )  + '_hotel';
  var spinner_id = ( '#' + $( this ).attr( 'id' ) ).replace( /_+[0-9]+/, '' )  + '_loader';

  if ($(target_id).is(':visible'))
  {
   $(target_id).hide(true);
  }
  else
  {
   $(spinner_id).show(true);

   // sucking on some AJAX to load ONLY the data for the hotel clicked
   $.get(path_prefix + "/hotels/" + $( this ).attr( 'id' ) + "/hotel_detail" ,function(data){
    $(target_id).html(data)
    $(target_id).show(true);
    $(spinner_id).hide(true);
   });

  }
  });

}

function hotel_block_toggle()
{
 var hotel_block_id = 0;

 $( this ).click( function() {
  var target_id = ( '#' + $( this ).attr( 'id' ) ).replace( /_+[0-9]+/, '' )  + '_hotel_block';
  var spinner_id = ( '#' + $( this ).attr( 'id' ) ).replace( /_+[0-9]+/, '' )  + '_loader';

  if ($(target_id).is(':visible'))
  {
   $(target_id).hide(true);
  }
  else
  {

 $(spinner_id).show(true);

   // sucking on some AJAX to load ONLY the data for the hotel clicked
   $.get(path_prefix + "/hotel_room_blocks/" + $( this ).attr( 'id' ) + "/hotel_block_summary" ,function(data){
    $(target_id).html(data)
    $(target_id).show(true);
    $(spinner_id).hide(true);


   });
  }
  });
}


function item_toggle()
{


 $( this ).click( function() {
  var target_id = ( '#' + $( this ).attr( 'id' ) ).replace( /_+[0-9]+/, '' )  + '_item';
  var spinner_id = ( '#' + $( this ).attr( 'id' ) ).replace( /_+[0-9]+/, '' )  + '_item_loader';

  if ($(target_id).is(':visible'))
  {
   $(target_id).hide(false);
  }
  else
  {
   $(spinner_id).show(false);

 //alert('item toggle ID = ' + $( this ).attr( 'id' ) + ' path = ' + path_prefix + "/administrators/" + $( this ).attr( 'id' ) + "/item_summary");
   // sucking on some AJAX to load ONLY the data for the hotel clicked
   $.get(path_prefix + "/administrators/" + admin_id + "/item_summary/?item_id=" + $( this ).attr( 'id' ), function(data){
    $(target_id).html(data)
    $(target_id).show(false);
    $(spinner_id).hide(false);
   });

  }
 });

}

function take_two_toggle()
{


 $( this ).click( function() {
  var target_id = ( '#' + $( this ).attr( 'id' ) ).replace( /_+[0-9]+/, '' )  + '_item';
  var spinner_id = ( '#' + $( this ).attr( 'id' ) ).replace( /_+[0-9]+/, '' )  + '_item_loader';

  if ($(target_id).is(':visible'))
  {
   $(target_id).hide(false);
  }
  else
  {
   $(spinner_id).show(false);

 // sucking on some AJAX to load ONLY the data for the item
   $.get(path_prefix + "/administrators/" + admin_id + "/take_two_detail/?date=" + $( this ).attr( 'id' ), function(data){
    $(target_id).html(data)
    $(target_id).show(false);
    $(spinner_id).hide(false);
   });

  }
 });

}


function add_to_waiting_list()
{
 $( this ).click( function() {
    var target_id = '#' + $( this ).attr( 'id' );
   var waiting_list_id  = $( this ).attr( 'id' );

  // get the value of attendee_id from the hidden form element
  var attendee_id = $("#attendee_id").val();

  // huffing some AJAX
    $.post("/waiting_lists/" + waiting_list_id + "/add_attendee/?attendee_id=" + attendee_id ,function(data){
   // data is just the 'you've been added' message
     $(target_id).text(data)

  });

    });
}
