(function ($) {

$.widget( "ui.fundraiserLogin", {

  _init: function () {
    var self = this;
    return self.init_ui();
  },

  init_ui: function () {

    var self = this;
      
    var login_form = $( 'form.login-form', self.element ).ajaxForm({
      data: { ajax: 1 },
      success: function(html, textStatus) {
        self.element.html( html );
        self.init_ui();
      }
    });
      
    // Set hidden fundraiser id
    $( '#frid', self.element ).val( this.options.fundraiser_id );

    // Handle create fundrasing page button
    $( '.btn-create-page', self.element ).click( function () {
        var url = $( 'a.btn-create-page-url', self.element )[0].href;
        self.element.html( '<p>Loading form.</p>' );
        window.location.href = url;
        return false;
    } );

    $( 'form.forgot-password-form', self.element ).forgotPassword();

    // Lets let login form widgets know if they has data
    $( 'input', self.element ).bind( 'change.rubyWidget', function () {
        var widget = $( this );
        if( widget.val() == '' )
            widget.parents( '.frmField' ).addClass( 'rtg-empty' );
        else
            widget.parents( '.frmField' ).removeClass( 'rtg-empty' );
    } ).trigger( 'change.rubyWidget' );

    // Add/remove focus class to inputs
    $( 'input', self.element ).focus( function () {
        $( this )
            .parents( '.frmField' )
            .addClass( 'rtg-widget-focus' )
        ;
    } ).blur( function () {
        $( this )
            .parents( '.frmField' )
            .removeClass( 'rtg-widget-focus' )
        ;
    } );

    // When overlay label itself is clicked, focus the corresponding input underneath.
    $( '.label', self.element ).click( function() {
      $( this ).nextAll( 'input:first' ).focus();
    } );

    // Handle register now link
    $( '.register-now', self.element ).click( function () {
        self.element.html( '<p>Loading event registration page.</p>' );
        window.location.href = $( 'a.fr-register' )[0].href;
        return false;
    } );

    // Focus the "register now" link, so that one of the inputs
    // isn't focused by default without .focus() ever firing
    $( '.register-now', self.element ).focus();
  },

  destroy: function () {
      $.widget.prototype.destroy.apply( this, arguments );
  } // destroy

}); // $.widget

})(jQuery); // function($)

