
// TODO: remove Friendship Requests header when all friends managed (or just show a 'no current requests' message)
// TODO: better style
//          - Help text
//          - headers for requests / current friends
// TODO: while deleting, make any click select that user?
// TODO: figure out in-place update to change number to show on main page

preUpdateCallbacks['friends'] = preUpdateFriends;
postUpdateCallbacks['friends'] = postUpdateFriends;

function preUpdateFriends ( pWidgetId ) {
  addWidgetOverlay( pWidgetId );
}

function postUpdateFriends ( pWidgetId ) {
  removeWidgetOverlay( pWidgetId );
}

/* document.ready setup */
$(function() {
  var state = 'static';

  // init sortable but immediately disable
  $('.friend-sort').sortable( );
  stopSort( ); // use this to initialize things into non-sortable state

  // hide help tip until sorting is active
  $('#friends-sorting-help').hide();

  // bind starting and stopping to clicking the button
  $('#friends-button-sort').click( function() {
    if( 'static' == state ) {
      $(this).attr('value','Save Order');
      startSort();
      state = 'sorting';
    } else {
      $(this).attr('value','Enable Sorting');
      stopSort();
      saveOrder();
      state = 'static';
    }
  });

  // handle delete friends buttons
  var delete_state = 'none';
  $('#friends-button-delete').click( function() {
    if( 'none' == delete_state ) {
      // change button name and add proper checkboxes to each friend
      $(this).attr('value','Delete Selected Friends');
      // add a checkbox to each friend
      $('.friend-name').each( function( k, friend_name_div ) {
        var friendId = parseId( $( this ).parent().attr('id') );
        $(friend_name_div).prepend('<input type="checkbox" value="friend_'+friendId+'"/>');
      });
      delete_state = 'selecting';
    } else {
      // grab all IDs and issue delete AJAX call
      var friendsToDelete = Array( );
      // find all friends that are selected, add them to a list, remove them from the screen
      $('.friend-name input').each( function() {
        if( $(this).attr('checked') == true ) {
          var friendId = parseId( $(this).attr('value') );
          friendsToDelete.push( friendId );
          // remove this friend div from the page
          $('#friend_'+friendId).remove();
        }
      });

      var deleteList = friendsToDelete.join(',');

      // send the ajax call
      $.ajax( {
        type: 'POST',
        url: '/' + gUrls['portalPrefix'] + 'null.xml',
        data: 'friends[dfl]='+deleteList
      } );

      // remove checkboxes and set state back to normal viewing mode
      $('.friend-name input').remove();
      $(this).attr('value','Mark Friends for Deletion');
      delete_state = 'none';
    }
  });

  // wire up accept friend button
  $('.friend-accept').click( function() {
    handleFriendRequest( this );
  });

  // wire up reject friend button
  $('.friend-reject').click( function() {
    handleFriendRequest( this );
  });

  // disable clicking on friend links while sorting is active
  $('.friend-sort a').click( function(e) {
    if( 'sorting' == state ) {
      e.preventDefault( );
    }
  });
});

/**
 * Take a button, get the ID, figure out if it's accept or reject, call AJAX
 **/
function handleFriendRequest( pButton ) {
  var userId = parseId( $(pButton).attr('id') );
  var action = null;
  
  // figure out which button was clicked
  if( $(pButton).hasClass('friend-accept') ) {
    action = 'accept';
    queryArg = 'af';
  } else if ( $(pButton).hasClass('friend-reject') ) {
    action = 'reject';
    //queryArg = 'rf'; - RF is request friendship?
    queryArg = 'jf';
  }

  // if request is rejected, make the whole div go away
  friendDiv = $(pButton).parents('div.pending-friend')[ 0 ];
  if( 'reject' == action ) {
    $(friendDiv).remove();
  } else if ( 'accept' == action ) {
    // first, remove button div
    $('.request-buttons',friendDiv).remove();
    // move this div to the sortable friend div
    $(friendDiv).appendTo('#friend-sort'); 
    // change the id to match the pattern
    $(friendDiv).attr('id','friend_'+userId);
    // change the CSS class to match the friend-sort div
    $(friendDiv).addClass('friend').removeClass('pending-friend');
  }

  // send the ajax call
  $.ajax( {
    type: 'POST',
    url: '/' + gUrls['portalPrefix'] + 'null.xml',
    data: 'friends['+queryArg+']='+userId
  } );
}

/* enable sorting, disable selection, show sorting help div */
function startSort ( ) {
  $('.friend-sort').sortable('enable');
  $('.friend-sort').disableSelection();
  $('#friends-sorting-help').show();
}

/* disable sorting, make elements selectable, hide the help div */
function stopSort ( ) {
  $('.friend-sort').sortable('disable');
  $('.friend-sort').enableSelection();
  $('#friends-sorting-help').hide();
}

/* determine the order of the divs, send that order to the AJAX handler */
function saveOrder ( ) {
  var friends = new Array( );
  $( '.friend' ).each( function( ) {
    var friendId = parseId( $( this ).attr('id') );

    if( friendId ) {
      friends.push( friendId );
    }
  });

  // send the ajax call
  $.ajax( {
    type: 'POST',
    url: '/' + gUrls['portalPrefix'] + 'null.xml',
    data: 'friends[nfo]='+friends.join( ',' )
  } );
}

