// The maximum number of pages to store for each widget
var maxCachePages = 5;

// The script to send the AJAX request to
var widgetAjaxScript = "/wp-includes/widgets/ajax.php";

// Stores cached pages for each widget
var widgetPageCache = new Array();

  
  
/*
 * Loads the next page of data for the widget specified
 *
 * @param String  The widget ID as set in the widget class
 * @param String  A string of arguments (& separated) to pass to the AJAX script
 * @param Boolean Set to TRUE when calling this function to change filters or sorting and you want to
 *          REPLACE the current data with new data
 * @return  Bool  Returns TRUE if the request was a success, else returns FALSE so the nojs link works
 */
function loadWidgetContent( widgetId, addVars, overwriteContent )
{
  // We will always be loading the next page, and never skipping pages. If we need to load multiple
  // pages, this function should be called multiple times, in the order the pages are to be loaded.
  // The exception is if we are changing the sort on the data, because we will need to start back at the first page
  if( (typeof change_sort) != "undefined" && change_sort != false )
  {
  	eval("w_" + widgetId).pagesLoaded = 0;
  	pageNum = 1;
  }
  else
  	pageNum = eval("w_" + widgetId).pagesLoaded + 1;
 
  // If we have already loaded all of the pages for this widget, don't do the send unless sorting is required or 
  // we are replacing existing content
  w_lpages = eval( "w_" + widgetId ).pagesLoaded;
  w_tpages = eval( "w_" + widgetId ).pageCount;
  if( w_lpages >= w_tpages && !overwriteContent )
  {
  	return false;
  }
  
  if( (typeof change_sort) != "undefined" && change_sort != false )
  {
	  // Get the  direction to sort by. We will use the default for this field UNLESS
	  // the widget is already sorted by this field. If that is the case, then we want
	  // to reverse the sort order
	  if( widget_sortby == eval("widget_sortby_" + widgetId) )
	  {
	    eval("curr_dir = widget_sortdir_" + widgetId);

	    if( curr_dir == "ASC" )
	      sortDir = "DESC";
	    else if( curr_dir == "DESC" )
	      sortDir = "ASC";
	    
	    updateWidgetSort( widgetId, widget_sortby, sortDir );
	  }
	  else
	  {
	    updateWidgetSort( widgetId, widget_sortby, widget_sortdir );
	    sortDir = widget_sortdir;
	  }
  }
  
  if( widget_sortby == "" || widget_sortby == null )
  {
    sortby = "";
  }
  else
  {
	  // Add "name ASC" as the secondary sort if we are not already sorting by name
	  if( widget_sortby != "name" )
	    sortby = widget_sortby + " " + sortDir + ",name ASC";
	  else if( widget_sortby != "" && widget_sortby != null )
	    sortby = widget_sortby + " " + sortDir;
  }

  // Create the JQuery object to make the AJAX request
  turbine_j.ajax( 
  {   
   type: "POST",
   url: widgetAjaxScript,
   data: "widget=" + widgetId + "&page=" + pageNum + "&" + addVars + "&" + widgetId + "_sort=" + sortby,   
   beforeSend: function()
    {
      // Update the widget data to reflect that we have loaded another page
      //eval( "w_" + widgetId ).pagesLoaded += 1;
      eval( "w_" + widgetId ).pagesLoaded = pageNum;
      eval( "w_" + widgetId ).updateItemsLoaded();
      eval( "w_" + widgetId ).updateNextLoadAt();
      //html = "<img src='/wp-content/themes/default/images/base/widget_loading.png' />";
    }, 
   success: function(ret_html, v2)
   { 
    //If data is retrieved, append it to the current HTML UNLESS we sorted, in which case replace it. We know that we sorted
    // because the change_sort flag is only true when we first make the call to get the first page of a new sort
    if( ( (typeof change_sort) != "undefined" && change_sort != false ) || overwriteContent  )
    {
    	turbine_j("#scrollsizer_" + widgetId).html( ret_html );
    	 
	    // Since this is a new set of data, see if we need to resize the scrollpane to fit the new count. Also reset the number
	    // of loaded pages to 1 and reset the offset to the original
	    eval( "w_" + widgetId).pagesLoaded = 1;
	    eval( "w_" + widgetId ).updateItemsLoaded();
	    eval( "w_" + widgetId).currentOffset = eval( "w_" + widgetId ).startOffset;
    }
   	else
   	{
   	 	// Get previous HTML
		  currHTML = document.getElementById("scrollsizer_" + widgetId).innerHTML;
   		turbine_j("#scrollsizer_" + widgetId).html( currHTML + ret_html); 
   	}
   	
   }
   
  });

  return true;
}

/*
 * Updates the header for a widget. This does NOT update the scrollable content, just items like the principle characters
 *
 * @param String  The widget ID as set in the widget class
 * @param String  The ID of the element to write the content to
 * @param String  A string of arguments (& separated) to pass to the AJAX script
 * @return  Bool  Returns TRUE if the request was a success, else returns FALSE
 */
function updateWidgetHeader( widgetId, outputElement, addVars )
{
  // Create the JQuery object to make the AJAX request
  turbine_j.ajax( 
  {   
   type: "POST",
   url: widgetAjaxScript,
   data: "widget=" + widgetId + "&" + addVars,   
   beforeSend: function()
    {
      //html = "<img src='/wp-content/themes/default/images/base/widget_loading.png' />";
    }, 
   success: function(ret_html, v2)
   { 
    document.getElementById( outputElement ).innerHTML = ret_html;

   } 
   
  });

  return true;
}

/*
 * Each widget has 2 Javascript vars that track what field the widget is currently sorted by, as well as which
 * direction (asc/desc). This function updates both of those values so that they have the correct data/
 *
 * @param String  The widget ID as set in the widget class
 * @param String  The current field being sorted by (i.e. class_id or name)
 * @param String  The direction of the sort (ASC or DESC)
 *
 * @return        null
 */
function updateWidgetSort( widgetId, sortBy, sortDir )
{
  eval("widget_sortby_" + widgetId + " = \"" + sortBy + "\";");
  eval("widget_sortdir_" + widgetId + " = \"" + sortDir + "\";");

  sortObj = eval("w_" + widgetId);
  
  // Update the sorting icon - replace the current one with a space and then add the new one
  if( sortDir == "DESC" )
  	sort_arrow = themeUri + "common/misc/sort_arrow_down.gif";
  else
  	sort_arrow = themeUri + "common/misc/sort_arrow_up.gif";
  	
  // Empty current if there is one
  if( sortObj.sortBy != "" )
  	document.getElementById( widgetId + "_" + sortObj.sortBy ).innerHTML = "";
  	
  document.getElementById( widgetId + "_" + sortBy ).innerHTML = '<img src="' + sort_arrow + '" border="0" />';
  // Se this to current sorting method now
  sortObj.sortBy = sortBy;
}
