/**
 * Registry of callback functions for moving widgets.
 */
var moveCallbacks = new Array( );
var preUpdateCallbacks = new Array( );
var postUpdateCallbacks = new Array( );

/**
 * Widget initialization.
 */
$( document ).ready( function ( ) {

  if( gUserInfo.loggedIn ) {

    // make all 'widget-container' containers sortable
    $( '.widget-sort' ).sortable( {
      placeholder: 'ui-state-highlight sortable-placeholder',
      connectWith: '.widget-sort',
      handle: '.move-handle',
      stop: function ( pEvent, pUi ) {
        moveWidget( pEvent, pUi );
      }
    } );

    // hook up the 'available' widgets control
    $( '#available-widgets-open' ).bind( 'click', function ( ) {
      $( '#available-widgets' ).slideToggle( );
      $( '#available-widgets-open .ui-icon' ).toggleClass( 'ui-icon-arrowstop-1-s' ).toggleClass( 'ui-icon-arrowstop-1-n' );;
    } );

  }

  // add 'over' states to icons
  $( '.icon-wrapper' ).hover(
    function ( ) { $( this ).addClass( 'ui-state-hover' ); },
    function ( ) { $( this ).removeClass( 'ui-state-hover' ); }
  );

} );


/**
 * Called when a widget is moved on the page.  This sends the ajax request back
 * to update the user's profile.
 */
function moveWidget ( pEvent, pUi ) {

  var fields = new Array( );

  // get all widgets on the page and build up the list of widget ids for each field
  $( '.widget' ).each( function ( ) {
    var widgetId = parseId( $( this ).attr( 'id' ) );
    var fieldId = parseId( $( this ).parents( '.widget-container' ).attr( 'id' ) );

    if( widgetId && fieldId ) {

      if( !fields[fieldId] ) {
        fields[fieldId] = new Array( );
      }
      fields[fieldId].push( widgetId );

    }
  } );

  for( i in fields ) {
    fields[i] = 'w[fds][' + i + ']=' + fields[i].valueOf( );
  }

  var type = $('.widget', pUi.item).attr( 'type' );
  if( moveCallbacks[type] ) {
    var movedId = parseId( pUi.item.attr( 'id' ) );
    moveCallbacks[type]( pEvent, pUi );
  }

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


/**
 * Called when the user adds a widget to the page with the 'add' link.
 */
function addWidget ( pWidgetName ) {

  if( pWidgetName != null ) {

    $( '.widget.loading-placeholder' ).clone( ).prependTo( '.widget-container.main' ).show( );

    fieldId = parseId( $( '.widget-container.main' ).attr( 'id' ) );

    if( fieldId ) {

      $.get( '/' + gUrls['portalPrefix'] + 'addwidget.html?w[a]=' + pWidgetName + '&w[fd]=' + fieldId, function ( pHtml ) {

        $( '.widget-container.main .widget.loading-placeholder' ).fadeOut( 'slow', function ( ) {
          $( this ).remove( );
          $( pHtml ).prependTo( '.widget-container.main' );
          ApplyAllColors( );
        } );
      } );
    }

  }
}


/**
 * Called when a user removes a widget from the page.
 */
function removeWidget ( pWidgetId ) {

  addWidgetOverlay( pWidgetId );

  $.get( '/' + gUrls['portalPrefix'] + 'removewidget.html?w[r]=' + pWidgetId, function ( pHtml ) {

    if( pHtml ) {
      $( '#widget_' + pWidgetId ).fadeOut( 'slow', function( ) {
        $( this ).parent( ).remove( );
      } );
    }

  } );
}


/**
 * Called when a user clicks the 'edit options' control on a widget.
 */
function showWidgetControls ( pWidgetId ) {
  $( '#widget_' + pWidgetId + ' .widget-control' ).slideToggle( );
}

/**
 * Called when a widget options form is submitted.
 */
function updateWidget ( pWidgetId ) {

  // get the widget type
  var type = $( '#widget_' + pWidgetId ).attr( 'type' );

  var url = 'ajaxwidget.xml';

  // call the pre-move callback if defined
  if( preUpdateCallbacks[type] ) {
    url = preUpdateCallbacks[type]( pWidgetId );
  }

  $.get( url, function( pData ) {
    if( postUpdateCallbacks[type] ) {
      postUpdateCallbacks[type]( pWidgetId, pData );
    }
  } );

  return false;
}

/**
 * Adds an overlay and spinner image to the widget body.
 */
function addWidgetOverlay ( pWidgetId ) {
  var widgetBody = $( '#widget_' + pWidgetId + ' .widget-body' );
  var height = widgetBody.height( );
  var topMargin = Math.round( height / 2 - 16 );
  widgetBody.append( '<div class="ui-widget-overlay widget-loading"><img style="margin-top: ' + topMargin + 'px;" src="' + gUrls['content'] + 'sites/playerportal/modules/lotro-base/images/misc/loading.gif" /></div>' );
}

/**
 * Removes the widget overlay from the widget body.
 */
function removeWidgetOverlay ( pWidgetId ) {
  $( '#widget_' + pWidgetId + ' .widget-body .widget-loading' ).remove( );
}

/**
 * Parses a numeric id out of an element id string.
 */
function parseId ( pElementId ) {

  var id = null;

  if( pElementId && pElementId.indexOf( '_' ) >= 0 ) {
    id = pElementId.substring( pElementId.lastIndexOf( '_' ) + 1 );
  }

  return id;

}

/**
 * Called prior to doing a character select update on a widget.
 */
function preUpdateCharSelect ( pWidgetId ) {

  addWidgetOverlay( pWidgetId );

  var widgetType = $( '#widget_' + pWidgetId ).attr( 'type' );

  var widgetForm = $( '#widget_' + pWidgetId + '_form' );

  var queryString = 'w[i]=' + pWidgetId;
  queryString += '&' + widgetType + '[cid]=' + escape( widgetForm.find( '#cid_' + pWidgetId ).val( ) );

  return '/' + gUrls['portalPrefix'] + 'ajaxwidget.html?' + queryString;
}

/**
 * Called after doing a character select update on a widget.
 */
function postUpdateCharSelect ( pWidgetId, pData ) {

  var widgetType = $( '#widget_' + pWidgetId ).attr( 'type' );

  $( '#widget_' + pWidgetId + ' .widget-body' ).empty( ).append( pData );

  removeWidgetOverlay( pWidgetId );

}

/**
 * Called on the anonymous form of the char select in a widget
 */
function changeChar ( pInput ) {
  var widgetForm = $( pInput ).parent( );
  var charBase = widgetForm.find( '#charBase' ).val( );
  var widgetName = widgetForm.find( '#widgetName' ).val( );
  var charValue = widgetForm.find( '#cid' ).val( );
  var url = charBase + charValue + '/' + widgetName;
  window.location = url;
  return false;
}

preUpdateCallbacks['skirmishlog'] = preUpdateCharSelect;
postUpdateCallbacks['skirmishlog'] = postUpdateCharSelect;
preUpdateCallbacks['character'] = preUpdateCharSelect;
postUpdateCallbacks['character'] = postUpdateCharSelect;
preUpdateCallbacks['activitylog'] = preUpdateCharSelect;
postUpdateCallbacks['activitylog'] = postUpdateCharSelect;
preUpdateCallbacks['skirmishcharts'] = preUpdateCharSelect;
postUpdateCallbacks['skirmishcharts'] = postUpdateCharSelect;


