﻿; (function($) {


$(document).ready(function(){

  // Links with target="_blank" need javascript for ie.

  $( 'a[target="_blank"]' )
    .unbind( 'click' )
    .bind( 'click', function(ev) {
      window.open( this.href );
      return false;
    } );

  // User clicks on a video thumbnail:
  //   * highlight that video thumbnail
  //   * load video in player
  //   * switch out caption in sidebar

  $('.small-video a').click( function() {
    var li = $(this).parent('.small-video li');
    var url = $('.video-url', li).attr('href');
    var caption = $('.video-caption', li).html();

    $('.small-video li').removeClass('active');
    li.addClass('active');

    $('.video iframe').attr('src', url);

    if (caption)
      $('#sidebar .sidebar-content').html(caption);

    return false;
  } );


  // User clicks on bio name
  //   * highlight that name in the sidebar
  //   * show the associated bio text.

  $('.site-iluminate .bio-names a').click( function() {

    var href = $(this).attr('href');
    var li = $(this).parent('.bio-names li');

    $('#sidebar .bio-names .active').removeClass('active');
    li.addClass('active');

    $('.bio.active').removeClass('active');
    $(href).addClass('active');

    return false;
  } );


  // User clicks on a bio image
  //   * highlight that bio image
  //   * show the associated bio text.
  //   * TODO show the secondary bio image (action shot)

  $('.site-teamiluminate .bio-images a').click( function() {

    var href = $(this).attr('href');
    var li = $(this).parent('.bio-images li');

    $('#sidebar .bio-images .active').removeClass('active');
    li.addClass('active');

    $('.bio.active').removeClass('active');
    $(href).addClass('active');

    return false;
  } );


  // User clicks on a gallery image
  //   * show the image in the large gallery view
  //   * TODO show caption text in the sidenav

  $('.gallery-images a').click( function() {

    var href = $(this).attr('href');
    var id = href.replace(/^#/,'');

    $('#content .main-image').removeClass('active');
    $('#content .main-image.'+id ).addClass('active');

    $('#sidebar .caption').removeClass('active');
    $('#sidebar .caption.'+id ).addClass('active');

    return false;
  } );


  // Set up image carousels for the team and gallery pages.
  // FIXME clean this up when carousel becomes a $.ui.widget

  var body = $( 'body' );

  if (body.hasClass('section-team')) {
    $.carouselize( body, {
      orientation : 'vertical',
      pagesize    : 2,
      deltasize   : 1,
      speed       : 3
    } );
  }

  if (body.hasClass('section-gallery')) {
    $.carouselize( body, {
      orientation : 'horizontal',
      pagesize    : 5,
      deltasize   : 5,
      speed       : 5
    } );
  }

  // For all the text inputs, set them up for overlay "hints".

  overlayInputs( $('input:text, input:password, textarea') );

  // Set up jQuery ui datepicker widgets for all calendar form inputs.
  // Work around the fact that blur fires, and the overlay gets
  // reinstated, before the datepicker actually sets the input value.

  if ($.ui) {
    $('.calendar').datepicker({
      onClose: function( dateText, inst ) {
        if (dateText != '')
          $(this).removeClass('overlaid');
      }
    });
  }

  // Handle the mailing list registration form at top.
  // Handle the signup registration form
  // Handle the booking page form

  ajaxizeForm( $('.form-registration') );
  ajaxizeForm( $('.form-signup') );
  ajaxizeForm( $('.form-booking') );
  ajaxizeForm( $('.form-rentals') );

});


function overlayInputs( inputs ) {

  inputs.each( function() {

    var elem = $(this);

    // If the element has a title attribute and the input is blank,
    // use this as the default overlay value.

    var title = elem.attr('title');

    if ((elem.val() == '' || elem.val() == title) && title) {
      elem.val(title);
      elem.addClass('overlaid');
      elem.data('val', elem.val());
    }

    // Clear / restore overlay value on focus / blur.

    elem.bind('focus', function(){
      if(elem.val() == elem.data('val')) {
        elem.val('');
        elem.removeClass('overlaid');
      }
    }).bind('blur', function(){
      if(elem.val() == '') {
        elem.val(elem.data('val'));
        elem.addClass('overlaid');
      }
    });

  });

}


function ajaxizeForm(form) {

  // Submit a form via ajax.
  // Expects a JSON response with error information.

  $( 'input:submit', form ).click( function() {

    // Disable the submit button to prevent multiple submissions.
    // Re-enable it when the ajax call completes.

    var button = $(this);
    button.attr('disabled', 'disabled');
    button.addClass('working');


    form.ajaxSubmit({

      beforeSerialize: function() {

        // Clear any fields that just have the default overlay value.

        $( 'input:text, input:password, textarea', form ).each( function() {
          if ($(this).val() == $(this).attr('title'))
            $(this).val('');
        } );

      },

      beforeSend: function() {

        // Clear any previous error and status messages

        $( '.message', form ).html('');
        $( '.message', form ).removeClass( 'message-error message-success' );
        $( '.error',   form ).html('');
      },

      success: function( rsp, status, req ) {

        // If there were form errors, display field-specific errors.

        if (rsp.form_errors) {
          for (var key in rsp.form_errors) {
            var value = rsp.form_errors[key];
            $( '.'+key+'-field .error', form ).html( value );
          }
        }

        // If there was any kind of error, echo back form values for resubmission.

        if (rsp.error) {
          for (var key in rsp.form_data) {
            var value = rsp.form_data[key];
            // $( '.'+key+'-field :input', form ).val( value );
          }
        }

        // Display overall status message.

        var message = $( '.message', form );
        message.css( { 'display': 'none' } );
        message.html( rsp.error ? rsp.error : rsp.message );
        message.addClass( rsp.error ? 'message-error' : 'message-success' );
        message.show( 500 );

        // Reset the form if there were no errors.

        if (!rsp.error)
          $( form )[0].reset();

      },

      error: function() {

        // HTTP error

        var message = $( '.message', form );
        message.html( "There was an error." );
        message.addClass( 'message-error' );

      },

      complete: function() {
        $( ':input', form ).removeClass('overlaid');
        overlayInputs( $('input:text, input:password, textarea', form) );
        button.removeAttr('disabled');
        button.removeClass('working');
      }

    });

    return false;
  });
}


})(jQuery);


