/**
 * Called prior to doing an rss widget update.  This will put an overlay on the
 * widget body and then return the url to be requested for the update.
 */
function preUpdateRss ( pWidgetId ) {

  addWidgetOverlay( pWidgetId );

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

  var queryString = 'w[i]=' + pWidgetId;
  queryString += '&rss[u]=' + escape( widgetForm.find( '#u_' + pWidgetId ).val( ) );
  queryString += '&rss[n]=' + escape( widgetForm.find( '#n_' + pWidgetId ).val( ) );
  queryString += '&rss[t]=' + escape( widgetForm.find( '#t_' + pWidgetId ).val( ) );
  queryString += '&rss[ft]=' + escape( widgetForm.find( '#ft_' + pWidgetId ).attr( 'checked' ) );
  return '/' + gUrls['portalPrefix'] + 'ajaxwidget.xml?' + queryString;
}

/**
 * Called after the rss widget has been updated.  This will remove the overlay and
 * update the feedurl attribute for the widget.  This then forces a reload of the
 * rss feed.
 */
function postUpdateRss ( pWidgetId, pData ) {

  var success = $( pData ).find( 'rss' ).find( 'success' ).text( );

  if( success == 'true' ) {
    var config = getRssConfigFromXml( $( pData ).find( 'rss' ) );
    var feedUrl = $( pData ).find( 'rss' ).find( 'u' ).text( );
    var rssDiv = $( '#widget_' + pWidgetId + ' .widget-body .rss_feed' );
    rssDiv.attr( 'u', config.url );
    rssDiv.attr( 'n', config.num );
    rssDiv.attr( 't', config.title );
    rssDiv.attr( 'ft', config.feedTitle );
    initializeRssFeed( rssDiv, pWidgetId );
  }
  else {
    // show an error message
  }

  removeWidgetOverlay( pWidgetId );

}

function initializeAllRssFeeds ( ) {
  $( '.rss_feed:not(.local)' ).each( function( ) {
    var rssDiv = $( this );
    initializeRssFeed( rssDiv, parseId( $( this ).attr( 'id' ) ) );
  } );
}

function getRssConfigFromXml ( pXml ) {

  var data = new Object( );
  data.url = pXml.find( 'u' ).text( );
  data.num = pXml.find( 'n' ).text( );
  data.title = pXml.find( 't' ).text( );
  data.feedTitle = pXml.find( 'ft' ).text( ) == 'true';

  return data;

}

function getRssConfig ( pDiv ) {

  var data = new Object( );
  data.url = pDiv.attr( 'u' );
  data.num = pDiv.attr( 'n' );
  data.title = pDiv.attr( 't' );
  data.feedTitle = pDiv.attr( 'ft' ) == 'true';
  data.fullContent = pDiv.attr( 'fc' ) == 'true';
  data.isLocal = pDiv.attr( 'lo' ) == 'y';
  data.sourceHost = pDiv.attr( 'sh' );

  return data;

}

function initializeRssFeed ( pDiv, pWidgetId ) {

  var data = getRssConfig( pDiv )
  if( data.url != null && $.trim( data.url ) != '' ) {

    var feed = new google.feeds.Feed( data.url );
    feed.setNumEntries( data.num );

    feed.load( function( pResult ) {
      if( !pResult.error ) {
        pDiv.empty( );

        // update the feed entries
        for( var i = 0; i < pResult.feed.entries.length; i++ ) {
          var entry = pResult.feed.entries[i];
          var date = new Date( entry.publishedDate );
          var dateString = date.toLocaleDateString( ) + ' - ' + date.toLocaleTimeString( );
          var content = data.fullContent ? entry.content : entry.contentSnippet;
          pDiv.append( gRssEntryTemplate.replace( "RSS_LINK", entry.link ).replace( "RSS_TITLE", entry.title ).replace( "RSS_DATE", dateString ).replace( "RSS_CONTENT", content ).replace( "RSS_NUM", 'rss_entry_' + ( i + 1 ) ) );
        }

        // update the widget title if it's a default title
        var title = pResult.feed.title;
        if( !data.feedTitle && data.title != null && data.title != '' ) {
          title = data.title;
        }
        $( '#widget_' + pWidgetId + ' .widget-head a.title.default' ).html( title );
      }
      else {
        // show an error message
        pDiv.empty( );
        pDiv.append( gErrorTemplate.replace( 'ERROR_MESSAGE', pResult.error.message ) );
      }
    });
  }
}

preUpdateCallbacks['rss'] = preUpdateRss;
postUpdateCallbacks['rss'] = postUpdateRss;

google.setOnLoadCallback( initializeAllRssFeeds );
google.load( 'feeds', '1', {nocss:1} );

// initialize all local rss feeds
$( document ).ready( function ( ) {

  $( '.rss_feed.local' ).each( function ( ) {
    var rssDiv = $( this );
    initializeLocalRssFeed( rssDiv, parseId( $( this ).attr( 'id' ) ) );
  } );

} );

// initialize a local rss feed
function initializeLocalRssFeed ( pDiv, pWidgetId ) {

  var data = getRssConfig( pDiv );

  $.getFeed( {
    url: data.url,
    success: function ( pFeed ) {

      if( pFeed.items.length == 0 ) {
        pDiv.empty( );
        var msg = pDiv.attr( 'em' );
        if( msg == null || msg == '' ) {
          msg = 'No items in feed.';
        }
        pDiv.append( gErrorTemplate.replace( 'ERROR_MESSAGE', msg ) );
      }

      for( var i = 0; i < pFeed.items.length && i < data.num; i++ ) {

        var item = pFeed.items[i];

        var date = new Date( item.updated );
        var dateString = date.toLocaleDateString( ) + ' - ' + date.toLocaleTimeString( );
        var content = item.description;

        pDiv.append( gRssEntryTemplate.replace( "RSS_LINK", item.link ).replace( "RSS_TITLE", item.title ).replace( "RSS_DATE", dateString ).replace( "RSS_CONTENT", content ).replace( "RSS_NUM", 'rss_entry_' + ( i + 1 ) ) );

      }

    },

    empty: function ( ) {
      if( !pDiv.children( ).exists( ) ) {
        // show an error message
        pDiv.empty( );
        pDiv.append( gErrorTemplate.replace( 'ERROR_MESSAGE', 'Unable to load the feed' ) );
      }
    },
    error: function ( ) {
      if( !pDiv.children( ).exists( ) ) {
        // show an error message
        pDiv.empty( );
        pDiv.append( gErrorTemplate.replace( 'ERROR_MESSAGE', 'Unable to load the feed' ) );
      }
    }
  } );

}

