var state_desc = new Array();
var state_duplicate = new Array();
var t = new Array();
var state_viewed = new Array();
var xmlHttpRead = new Array();
var xmlHttpSave = new Array();
var xmlHttpInteresting = new Array();

// Used to create xmlHttp objects for multiple browsers
function GetXmlHttpObject() {
  xmlHttpObject=null;
  try {
    // Firefox, Opera 8.0+, Safari
    xmlHttpObject=new XMLHttpRequest();
  } catch (e) {
    // Internet Explorer
    try {
      xmlHttpObject=new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      xmlHttpObject=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }

  return xmlHttpObject;
}

function changeViewedColor(id,mark_as_read) {
  if (xmlHttpViewed.readyState == 4 || xmlHttpViewed.readyState == "complete") {
    // Get the data from the server's response
    var result=xmlHttpViewed.responseText;

    // Check to see if the update was a success
    if (result == 1 || result == "<") {
      id_view = "title_" + id;

      if (document.getElementById) {
        // Make sure the title hadn't been turned gray after expanding the item
        if (document.getElementById(id_view).style.color != "#808080") {
          document.getElementById(id_view).style.color = "purple";
        }

        // Set the state_viewed variable to be used by the save and not_interesting functions
        state_viewed[id]=1;
      }

      if (mark_as_read == 1) {
        // Item was marked read in addition to viewed
        if (document.getElementById) {
          document.getElementById(id_view).style.fontWeight = "normal";
        } else if (document.all) { //IS IE 4 or 5 (or 6 beta)
          eval( "document.all." + id_view + ".style.fontWeight = normal");
        } else if (document.layers) { //IS NETSCAPE 4 or below
          document.layers[id_view].fontWeight = "normal";
        }
      }
    }
  }
}

function viewed_delay(id,mark_as_read) {
  return (function(){
      /* This inner function is to be executed with - setTimeout
         - and when it is executed it can read, and act upon, the
         parameters passed to the outer function:-
      */

    xmlHttpViewed=GetXmlHttpObject();
    if (xmlHttpViewed != null) {
      var url="/ajax_viewed?id=" + id + "&mark_as_read=" + mark_as_read;
      xmlHttpViewed.open("GET",url,true);
      xmlHttpViewed.onreadystatechange=function(){changeViewedColor(id,mark_as_read)};
      xmlHttpViewed.send(null);
    }
  });
}

function toggle_desc_delay(id,mark_as_read) {
  if (document.getElementById) { 
    id_desc = "desc_" + id;
    id_item = "item_" + id;
    id_read_unread = "read_unread_" + id;
    id_simple = "simple_" + id;

    if (document.getElementById(id_read_unread)) {
      state_read=document.getElementById(id_read_unread).innerHTML;
    } else {
      state_read="";
    }

    // Controls whether to hide or display the description and sets the timer to mark the item viewed and/or read
    if (state_desc[id] == 'block') {
      state_desc[id] = 'none';
      clearTimeout(t[id]);

      if (state_read == "Mark Unread") {
        document.getElementById(id_item).style.backgroundColor = "#E0E0E0";
      } else {
        document.getElementById(id_item).style.backgroundColor = "#F6F6F6";
      }
    } else {
      state_desc[id] = 'block';
      t[id]=setTimeout(function(){viewed_delay(id,mark_as_read)},10000);
      document.getElementById(id_item).style.backgroundColor = "#FFFFFF";
    }

    if (document.getElementById(id_simple)) {
      document.getElementById(id_simple).style.display = state_desc[id];
    }
    document.getElementById(id_desc).style.display = state_desc[id];
  }
}

function toggle_desc(id) {
  if (document.getElementById) {
    id_desc = "desc_" + id;
    id_item = "item_" + id;
    id_read_unread = "read_unread_" + id;
    id_simple = "simple_" + id;

    // Detect the browser and device being used
    user_agent=navigator.userAgent;

    if (document.getElementById(id_read_unread)) {
      state_read=document.getElementById(id_read_unread).innerHTML;
    } else {
      state_read="";
    }

    // Controls whether to hide or display the description and sets the timer to mark the item viewed and/or read
    if (state_desc[id] == 'block') {
      state_desc[id] = 'none';

      if (user_agent.match("iPhone") || user_agent.match("BlackBerry") || user_agent.match("Android")) {
        // Don't change the background color
      } else {
        if (state_read == "Mark Unread") {
          document.getElementById(id_item).style.backgroundColor = "#E0E0E0";
        } else {
          document.getElementById(id_item).style.backgroundColor = "#F6F6F6";
        }
      }
    } else {
      state_desc[id] = 'block';

      if (user_agent.match("iPhone") || user_agent.match("BlackBerry") || user_agent.match("Android")) {
        // Don't change the background color
      } else {
        document.getElementById(id_item).style.backgroundColor = "#FFFFFF";
      }
    }

    if (document.getElementById(id_simple)) {
      document.getElementById(id_simple).style.display = state_desc[id];
    }
    document.getElementById(id_desc).style.display = state_desc[id];

    // Position the item so it can be read more easily

    // Determine how much the page has been scrolled from the original position
    window_position=window.pageYOffset;

    // Get the initial position of the top of the item
    item_initial_position=document.getElementById(id_item).offsetTop;

    // Calculate the current position of the object relative to the top of the window
    // A positive number indicates how much below the top of the page the item is
    // A negative number indicates how much above (off) the page the item is
    item_current_position=item_initial_position - window_position;

    // Get the height of the item
    item_height=document.getElementById(id_item).offsetHeight;

    // Get the height of the window
    window_height=window.innerHeight;

    // Determines the position of the bottom of the item
    // A positive number means it's on screen
    // A negative number means it's off screen
    bottom_position=window_height - item_current_position - item_height;

    // Determine how much to scroll the page
    if (item_current_position < 0) {
      // The top of the item is off the top of the screen and needs to be brought back
      window.scrollTo(0,item_initial_position);
    } else if (item_height > window_height) {
      // The height of the item is > than the window so it should be scrolled to the top
      // The amount to scroll is determined by the item's current position
      if (user_agent.match("iPhone")) {
        // If this is an iPhone 3 or earlier a different scrolling is needed
        if (user_agent.match("iPhone OS 3") || user_agent.match("iPhone OS 2") || user_agent.match("iPhone OS 1")) {
          window.scrollBy(0,item_initial_position);
        } else {
          window.scrollBy(0,item_current_position);
        }
      } else {
        window.scrollBy(0,item_current_position);
      }
    } else {
      if (bottom_position < 0) {
        // The bottom of the window is off the screen
        // The amount to scroll is determined by how far the item's bottom is below the screen

        if (user_agent.match("iPhone")) {
          // If this is an iPhone 3 or earlier a different scrolling is needed
          if (user_agent.match("iPhone OS 3") || user_agent.match("iPhone OS 2") || user_agent.match("iPhone OS 1")) {
            bottom_position=window_height - item_initial_position - item_height;
          }
        }
        window.scrollBy(0,-bottom_position);
      }

      $("img").load(function(){
        reposition(id_item);
      });

      // Set a max amount of time that repositioning should still be done
      var t=setTimeout(function(){$("img").unbind('load')},5000);
    }
  }
}

function reposition(id_item) {
  // Position the item so it can be read more easily
  // This function will run delayed in time to account for any images loading

  if (document.getElementById(id_item)) {
    // Determine how much the page has been scrolled from the original position
    window_position=window.pageYOffset;

    // Get the initial position of the top of the item
    item_initial_position=document.getElementById(id_item).offsetTop;

    // Calculate the current position of the object relative to the top of the window
    // A positive number indicates how much below the top of the page the item is
    // A negative number indicates how much above (off) the page the item is
    item_current_position=item_initial_position - window_position;

    // Get the height of the window
    window_height=window.innerHeight;

    // Get the height of the item
    item_height=document.getElementById(id_item).offsetHeight;

    // Determines the position of the bottom of the item
    // A positive number means it's on screen
    // A negative number means it's off screen
    bottom_position=window_height - item_current_position - item_height;

    // Determine how much to scroll the page
    if (item_current_position < 0) {
      // The top of the item is off the top of the screen and needs to be brought back
      window.scrollBy(0,item_current_position);
    } else if (item_height > window_height) {
      // The height of the item is > than the window so it should be scrolled to the top
      // The amount to scroll is determined by the item's current position
      window.scrollBy(0,item_current_position);
    } else if (bottom_position < 0) {
      // The bottom of the window is off the screen
      // The amount to scroll is determined by how far the item's bottom is below the screen
      window.scrollBy(0,-bottom_position);
    }
  }
}

function titleExpand(event,id,viewed) {
  id_item = "item_" + id;
  id_desc = "desc_" + id;
  id_title = "title_" + id;
  id_preview = "preview_" + id;
  id_view = "view_" + id;
  id_footer = "footer_" + id;

  if (event.target) {
    var evt=event.target.id;
    var evtParent=event.target.parentNode.id;
  } else {
    // Internet Explorer's method
    var evt=event.srcElement.id;
    var evtParent=event.srcElement.parentNode.id;
  }

  // Determine if a subelement was clicked.
  // If it is then another element has already been clicked and nothing should be done.
  if ((evt == "" && (evtParent == id_item || evtParent == id_title || evtParent == id_view || evtParent == id_preview || evtParent == id_footer)) || evt == id_item || evt == id_preview || (evt == id_footer && evtParent == id_desc)) {
    // Determine which toggle_desc function to run
//    if (viewed == 1) {
      toggle_desc(id);
//    } else {
//      toggle_desc_delay(id);
//    }
  }
}

function toggle_duplicate(id) {
  // Check to see if more than one id was passed
  if (id.match("_")) {
    // Multiple ids were passed
    var id_array = id.split('_');
    id_first = id_array[0];
  } else {
    // Only one id was passed
    var id_array = new Array();
    id_array[0] = id;
  }

  for (idx in id_array) {
    id_dup = "duplicate_" + id_array[idx];

    if (state_duplicate[id_array[idx]] == 'block') {
      state_duplicate[id_array[idx]] = 'none';
    } else {
      state_duplicate[id_array[idx]] = 'block';
    }

    if (document.getElementById) {
      document.getElementById(id_dup).style.display = state_duplicate[id_array[idx]];
    } else if (document.all) { //IS IE 4 or 5 (or 6 beta)
      eval( "document.all." + id_dup + ".style.display = " + state_duplicate[id_array[idx]]);
    } else if (document.layers) { //IS NETSCAPE 4 or below
      document.layers[id_dup].visibility = state_duplicate[id_array[idx]];
    }
  }
}

function viewed(id) {
  if (document.getElementById) { 
    id_title = "title_" + id;

    // Make sure the title hadn't been turned gray after expanding the item
    if (document.getElementById(id_title).style.color != "#808080") {
      document.getElementById(id_title).style.color = "purple";
    }

    // Set the state_viewed variable to be used by the save and not_interesting functions
    state_viewed[id]=1;
  }
}

function changeSave(id,fid,viewed) {
  // Check to see if more than one id was passed
  if (id.match("_")) {
    // Multiple ids were passed
    var id_array = id.split('_');
    id_first = id_array[0];
  } else {
    // Only one id was passed
    id_first = id;
  }

  id_save = "save_" + id_first;
  id_title = "title_" + id_first;
  id_read_unread = "read_unread_" + id_first;
  id_feed = "feed_" + id_first;
  id_desc = "desc_" + id_first;
  id_interesting = "interesting_" + id_first;
  id_not_interesting = "not_interesting_" + id_first;

  document.getElementById(id_save).src = "/themes/feedsanywhere/starred-interesting.png";
  document.getElementById(id_interesting).src = "/themes/feedsanywhere/interesting-green-29x29.png";
  document.getElementById(id_not_interesting).src = "/themes/feedsanywhere/not_interesting-29x29.png";

  if (fid == "saved") {
    // The opposite behavior should happen vs usual
    if (viewed == 1) {
      document.getElementById(id_title).style.color = "purple";
    } else {
      document.getElementById(id_title).style.color = "blue";
    }
    if (document.getElementById(id_read_unread)) {
      // Make sure the element exists before modifying it
      document.getElementById(id_read_unread).style.color = "blue";
    }
    document.getElementById(id_save).style.color = "blue";
    document.getElementById(id_feed).style.color = "blue";
    document.getElementById(id_desc).style.color = "black";
  } else {
    document.getElementById(id_title).style.color = "gray";
    if (document.getElementById(id_read_unread)) {
      // Make sure the element exists before modifying it
      document.getElementById(id_read_unread).style.color = "gray";
    }
    if (fid > 0) {
      // Do nothing because the feed is not displayed
    } else {
      document.getElementById(id_feed).style.color = "gray";
    }
    document.getElementById(id_desc).style.color = "gray";

    // Change the class so the item isn't counted when determining whether Mark Page Read should be shown
    $("#" + id_read_unread).removeClass("mark-read");
    $("#" + id_read_unread).addClass("mark-read-saved");

    // Check to see if the Mark Page Read menu entry needs to be hidden
    markRead=0;
    $(".mark-read").each(function () {
      if ($(this).html() == "Mark Read" ) {
        markRead=1;
        return false;
      }
    });

    if (markRead == 0) {
      // Hide the Mark Page Read menu
      $("#menu_page_read").hide();

      // If Mark All Read and Mark Page Unread are also hidden the menu_read_group needs to be hidden as well
      if ($("#menu_page_unread").is(":visible") || $("#menu_all_read").is(":visible")) {
        // Do nothing
      } else {
        // Hide menu_read_group
        $("#menu_read_group").hide();
      }
    }
  }
}

function changeSaveOnChange(id_first,interesting) {
  if (xmlHttpSave[id_first].readyState == 4 || xmlHttpSave[id_first].readyState == "complete") {
    // Get the data from the server's response
    var result=xmlHttpSave[id_first].responseText;

    // Make sure the query was a success before changing the color
    if ((result > 1 || result == 0) && result != "") {
      alert("The item could not be saved. Please check your connection and try again later.");
      id_save = "save_" + id_first;

      if (interesting == 1) {
        document.getElementById(id_save).save = "/themes/feedsanywhere/star-interesting.png";
      } else if (interesting == 0) {
        document.getElementById(id_save).save = "/themes/feedsanywhere/star-not-interesting.png";
      } else {
        document.getElementById(id_save).save = "/themes/feedsanywhere/star-neutral.png";
      }

      // Change the class so the item is counted when determining whether Mark Page Read should be shown
      $("#read_unread_" + id_first).removeClass("mark-read-saved");
      $("#read_unread_" + id_first).addClass("mark-read");
    }
  }
}

function changeRemove(id,fid,viewed,interesting) {
  // Check to see if more than one id was passed
  if (id.match("_")) {
    // Multiple ids were passed
    var id_array = id.split('_');
    id_first = id_array[0];
  } else {
    // Only one id was passed
    id_first = id;
  }

  id_save = "save_" + id_first;
  id_title = "title_" + id_first;
  id_read_unread = "read_unread_" + id_first;
  id_feed = "feed_" + id_first;
  id_desc = "desc_" + id_first;

  if (interesting == 1) {
    document.getElementById(id_save).src = "/themes/feedsanywhere/star-interesting.png";
  } else {
    document.getElementById(id_save).src = "/themes/feedsanywhere/star-not-interesting.png";
  }

  if (fid != "saved") {
    if (viewed == 1) {
      document.getElementById(id_title).style.color = "purple";
    } else {
      document.getElementById(id_title).style.color = "blue";
    }
    if (document.getElementById(id_read_unread)) {
      // Make sure the element exists before modifying it
      document.getElementById(id_read_unread).style.color = "blue";
    }
    document.getElementById(id_save).style.color = "blue";
    if (fid > 0) {
      // Do nothing because the feed is not displayed
    } else {
      document.getElementById(id_feed).style.color = "blue";
    }
    document.getElementById(id_desc).style.color = "black";

    // Change the class so the item is counted when determining whether Mark Page Read should be shown
    $("#" + id_read_unread).removeClass("mark-read-saved");
    $("#" + id_read_unread).addClass("mark-read");
  }
}

function changeRemoveOnChange(id_first,interesting) {
  if (xmlHttpSave[id_first].readyState == 4 || xmlHttpSave[id_first].readyState == "complete") {
    // Get the data from the server's response
    var result=xmlHttpSave[id_first].responseText;

    // Make sure the query was a success before changing the color
    if ((result > 1 || result == 0) && result != "") {
      alert("The item could not be removed. Please check your connection and try again later.");
      id_save = "save_" + id_first;

      if (interesting == 1) {
        document.getElementById(id_save).save = "/themes/feedsanywhere/starred-interesting.png";
      } else {
        document.getElementById(id_save).save = "/themes/feedsanywhere/starred-not-interesting.png";
      }

      // Change the class so the item isn't counted when determining whether Mark Page Read should be shown
      $("#read_unread_" + id_first).removeClass("mark-read");
      $("#read_unread_" + id_first).addClass("mark-read-saved");
    }
  }
}

function save(id,fid,page,viewed) {
  // Check to see if more than one id was passed
  if (id.match("_")) {
    // Multiple ids were passed
    var id_array = id.split('_');
    id_first = id_array[0];
  } else {
    // Only one id was passed
    id_first = id;
  }

  if (fid == "similar" || fid > 0) {
    // Clear preload Page because saved items are shown so changing one will affect the next page
    $("#items_and_nav").data("preload","");
  }

  // Determine whether a Save or Remove link was clicked
  id_save = "save_" + id_first;
  if (document.getElementById) {
    state_save=document.getElementById(id_save).src;

    position=state_save.lastIndexOf("/") + 1;
    flag=state_save.slice(position);

    // Determine the current viewed state
    // The original value when the page is loaded gets passed to the function
    // If the state has been change it will be stored in the state_viewed[entry_id] array
    if (state_viewed[id_first] == 1) {
      viewed=state_viewed[id_first];
    }

    xmlHttpSave[id_first]=GetXmlHttpObject();
    if (flag == "starred-interesting.png" || flag == "starred-not-interesting.png") {
      // Remove the item from the saved list
      if (xmlHttpSave[id_first] != null) {
        if (flag == "starred-interesting.png") {
          interesting=1;
          changeRemove(id,fid,viewed,interesting);
        } else {
          interesting=0;
          changeRemove(id,fid,viewed,interesting);
        }
        var url="/ajax_remove?id=" + id_first;
        xmlHttpSave[id_first].open("GET",url,true);
        xmlHttpSave[id_first].onreadystatechange=function(){changeRemoveOnChange(id_first,interesting)};
        xmlHttpSave[id_first].send(null);

        // Automatically mark the item as read
        id_read_unread = "read_unread_" + id_first;
        if (document.getElementById(id_read_unread).innerHTML == "Mark Read") {
          xmlHttpRead[id_first]=GetXmlHttpObject();
          changeRead(id,0,0);
          var url="/ajax_read?r=" + id;
          xmlHttpRead[id_first].open("GET",url,true);
          xmlHttpRead[id_first].onreadystatechange=function(){changeReadOnChange(id_first,0)};
          xmlHttpRead[id_first].send(null);
        }
      } else {
        // Redirect to the remove.php page because ajax isn't supported
        var url="/remove?id=" + id_first + "&fid=" + fid + "&page=" + page;
        document.location.href=url;
      }
    } else {
      // Determine the item's interesting status
      if (flag == "star-interesting.png") {
        // Marked as interesting
        interesting=1;
      } else if (flag == "star-not-interesting.png") {
        // Marked as not interesting
        interesting=0;
      } else {
        // Score is unsure
        interesting=2;
      }

      // Save the item
      if (xmlHttpSave[id_first] != null) {
        changeSave(id,fid,viewed);
        var url="/ajax_save?id=" + id_first;
        xmlHttpSave[id_first].open("GET",url,true);
        xmlHttpSave[id_first].onreadystatechange=function(){changeSaveOnChange(id_first,interesting)};
        xmlHttpSave[id_first].send(null);
      } else {
        // Redirect to the save.php page because ajax isn't supported
        var url="/save?id=" + id_first + "&fid=" + fid + "&page=" + page;
        document.location.href=url;
      }
    }
  } else {
    if (fid == "saved") {
      // Redirect to the remove.php page because ajax isn't supported
      var url="/remove?id=" + id_first + "&fid=" + fid + "&page=" + page;
      document.location.href=url;
    } else {
      // Redirect to the save.php page because ajax isn't supported
      var url="/save?id=" + id_first + "&fid=" + fid + "&page=" + page;
      document.location.href=url;
    }
  }
}

function changeNotInteresting(id_first) {
  id_interesting = "interesting_" + id_first;
  id_not_interesting = "not_interesting_" + id_first;
  id_save = "save_" + id_first;

  document.getElementById(id_interesting).src = "/themes/feedsanywhere/interesting-29x29.png";
  document.getElementById(id_not_interesting).src = "/themes/feedsanywhere/not_interesting-red-29x29.png";

  // Determine if the item is saved or not
  state_save=document.getElementById(id_save).src;
  position=state_save.lastIndexOf("/") + 1;
  flag=state_save.slice(position);

  if (flag == "starred-interesting.png") {
    document.getElementById(id_save).src = "/themes/feedsanywhere/starred-not-interesting.png";
  } else if (flag == "star-interesting.png" || flag == "star-neutral.png") {
    document.getElementById(id_save).src = "/themes/feedsanywhere/star-not-interesting.png";
  }
}

function changeNotInterestingOnChange(id_first) {
  if (xmlHttpInteresting[id_first].readyState == 4 || xmlHttpInteresting[id_first].readyState == "complete") {
    // Get the data from the server's response
    var result=xmlHttpInteresting[id_first].responseText;

    // Make sure the query was a success before changing the color
    if ((result > 1 || result == 0) && result != "" && document.getElementById(id_not_interesting)) {
      alert("The item could not be marked as not interesting. Please check your connection and try again later.");
      id_not_interesting = "not_interesting_" + id_first;
      document.getElementById(id_not_interesting).src = "/themes/feedsanywhere/not_interesting-29x29.png";
    }
  }
}

function changeInteresting(id_first) {
  id_interesting = "interesting_" + id_first;
  id_not_interesting = "not_interesting_" + id_first;
  id_save = "save_" + id_first;

  document.getElementById(id_interesting).src = "/themes/feedsanywhere/interesting-green-29x29.png";
  document.getElementById(id_not_interesting).src = "/themes/feedsanywhere/not_interesting-29x29.png";

  // Determine if the item is saved or not
  state_save=document.getElementById(id_save).src;
  position=state_save.lastIndexOf("/") + 1;
  flag=state_save.slice(position);

  if (flag == "starred-not-interesting.png") {
    document.getElementById(id_save).src = "/themes/feedsanywhere/starred-interesting.png";
  } else if (flag == "star-not-interesting.png" || flag == "star-neutral.png") {
    document.getElementById(id_save).src = "/themes/feedsanywhere/star-interesting.png";
  }
}

function changeInterestingOnChange(id_first) {
  if (xmlHttpInteresting[id_first].readyState == 4 || xmlHttpInteresting[id_first].readyState == "complete") {
    // Get the data from the server's response
    var result=xmlHttpInteresting[id_first].responseText;

    // Make sure the query was a success before changing the color
    if ((result > 1 || result == 0) && result != "" && document.getElementById(id_not_interesting)) {
      alert("The item could not be marked as interesting. Please check your connection and try again later.");
      id_interesting = "interesting_" + id_first;
      document.getElementById(id_interesting).src = "/themes/feedsanywhere/interesting-29x29.png";
    }
  }
}

function notInteresting(id,page,auto,feed_num) {
  // Check to see if more than one id was passed
  if (id.match("_")) {
    // Multiple ids were passed
    var id_array = id.split('_');
    id_first = id_array[0];
  } else {
    // Only one id was passed
    id_first = id;
  }

  if (document.getElementById) {
    xmlHttpInteresting[id_first]=GetXmlHttpObject();
    if (xmlHttpInteresting[id_first] != null) {
      changeNotInteresting(id_first);
      var url="/ajax_not_interesting?id=" + id_first;
      xmlHttpInteresting[id_first].open("GET",url,true);
      xmlHttpInteresting[id_first].onreadystatechange=function(){changeNotInterestingOnChange(id_first)};
      xmlHttpInteresting[id_first].send(null);

      // Automatically mark the item as read
      id_read_unread = "read_unread_" + id_first;
      if (document.getElementById(id_read_unread).innerHTML == "Mark Read") {
        xmlHttpRead[id_first]=GetXmlHttpObject();
        changeRead(id,0,0);
        var url="/ajax_read?r=" + id;
        xmlHttpRead[id_first].open("GET",url,true);
        xmlHttpRead[id_first].onreadystatechange=function(){changeReadOnChange(id_first,0)};
        xmlHttpRead[id_first].send(null);
      }
    } else {
      // Redirect to the not_interesting page because ajax isn't supported
      var url="/not_interesting?id=" + id + "&page=" + page;
      document.location.href=url;
    }
  } else {
    // Redirect to the not_interesting page because ajax isn't supported
    var url="/not_interesting?id=" + id + "&page=" + page;
    document.location.href=url;
  }
}

function Interesting(id,page,auto,feed_num) {
  // Check to see if more than one id was passed
  if (id.match("_")) {
    // Multiple ids were passed
    var id_array = id.split('_');
    id_first = id_array[0];
  } else {
    // Only one id was passed
    id_first = id;
  }

  if (document.getElementById) {
    xmlHttpInteresting[id_first]=GetXmlHttpObject();
    if (xmlHttpInteresting[id_first] != null) {
      changeInteresting(id_first);
      var url="/ajax_interesting?id=" + id_first;
      xmlHttpInteresting[id_first].open("GET",url,true);
      xmlHttpInteresting[id_first].onreadystatechange=function(){changeInterestingOnChange(id_first)};
      xmlHttpInteresting[id_first].send(null);

      // Subscribe to the feed if auto_subscribe is enabled and the feed has not already been subscribed to
      if (document.getElementById("subscribe_title")) {
        if (document.getElementById("subscribe_title").innerHTML == "Subscribe") {
          if (auto == 1) {
            // Subscribe to the feed
            autoAddFeed(feed_num);
          } else if (auto == 2) {
            // Ask the user if they want to be automatically subscribed to feeds that are marked interesting
            var r=confirm("Do you want to subscribe to this feed?");
            if (r==true) {
              // Subscribe to the feed
              autoAddFeed(feed_num);
            }
          }
        }
      } else if (auto == 1) {
        // Subscribe to the feed
        autoAddFeed(feed_num);
      }
    } else {
      if (document.getElementById("subscribe_title")) {
        // Subscribe to the feed if auto_subscribe is enabled and the feed has not already been subscribed to
        if (auto == 1 && document.getElementById("subscribe_title").innerHTML == "Subscribe") {
          autoAddFeed(feed_num);
        }
      }

      // Redirect to the not_interesting page because ajax isn't supported
      var url="/interesting?id=" + id_first + "&page=" + page;
      document.location.href=url;
    }
  } else {
    // Redirect to the interesting page because ajax isn't supported
    var url="/interesting?id=" + id + "&page=" + page;
    document.location.href=url;
  }
}

function changeUnread(id,page_read,read_status) {
  if (id.match("_")) {
    // Multiple ids were passed
    var id_array = id.split('_');
    id_first = id_array[0];
  } else {
    // Only one id was passed
    var id_array = new Array();
    id_array[0] = id;
  }

  for (idx in id_array) {
    id_read_unread = "read_unread_" + id_array[idx];
    id_read_unread_footer = "read_unread_footer_" + id_array[idx];
    id_title = "title_" + id_array[idx];
    id_item = "item_" + id_array[idx];

    if (document.getElementById(id_title)) {
      document.getElementById(id_title).style.fontWeight = "bold";
    }

    if (document.getElementById(id_read_unread)) {
      document.getElementById(id_read_unread).innerHTML = "Mark Read";
    }

    if (document.getElementById(id_read_unread_footer)) {
      document.getElementById(id_read_unread_footer).innerHTML = "Mark Read";
    }

    // The color differs depending upon whether or not the description is expanded
    if (document.getElementById(id_item)) {
      if (state_desc[id] == 'block' || page_read > 0) {
        document.getElementById(id_item).style.backgroundColor = "#FFFFFF";
      } else {
        document.getElementById(id_item).style.backgroundColor = "#F6F6F6";
      }
    }
  }

  // Mark Page Read should be displayed
  $("#menu_read_group").show();
  $("#menu_page_read").show();

  // Check to see if the Mark Page Unread menu entry needs to be hidden
  markUnread=0;
  $(".mark-read").each(function () {
    if ($(this).html() == "Mark Unread" ) {
      markUnread=1;
      return false;
    }
  });

  if (markUnread == 0) {
    // Hide the Mark Page Unread menu
    $("#menu_page_unread").hide();
  }
}

function changeUnreadOnChange(id_first,page_read) {
  id_read_unread = "read_unread_" + id_first;
  id_read_unread_footer = "read_unread_footer_" + id_first;
  id_title = "title_" + id_first;

  if (xmlHttpUnread[id_first].readyState == 4 || xmlHttpUnread[id_first].readyState == "complete") {
    // Get the data from the server's response
    var result=xmlHttpUnread[id_first].responseText;

    // Make sure the query was a success before changing the color
    if ((result > 1 || result == 0) && result != "") {
      alert("The item could not be marked unread. Please check your connection and try again later.");
      document.getElementById(id_title).style.fontWeight = "normal";
      document.getElementById(id_read_unread).innerHTML = "Mark Unread";
      document.getElementById(id_read_unread_footer).innerHTML = "Mark Unread";

      // Mark Page Unread should be displayed
      $("#menu_read_group").show();
      $("#menu_page_unread").show();

      // Check to see if the Mark Page Read menu entry needs to be hidden
      markRead=0;
      $(".mark-read").each(function () {
        if ($(this).html() == "Mark Read" ) {
          markRead=1;
          return false;
        }
      });

      if (markRead == 0) {
        // Hide the Mark Page Read menu
        $("#menu_page_read").hide();
      }
    }
  }
}

function changeRead(id,page_read,read_status) {
  // Check to see if more than one id was passed
  if (id.match("_")) {
    // Multiple ids were passed
    var id_array = id.split('_');
    id_first = id_array[0];
  } else {
    // Only one id was passed
    var id_array = new Array();
    id_array[0] = id;
  }

  for (idx in id_array) {
    id_read_unread = "read_unread_" + id_array[idx];
    id_read_unread_footer = "read_unread_footer_" + id_array[idx];
    id_title = "title_" + id_array[idx];
    id_item = "item_" + id_array[idx];

    if (document.getElementById(id_title)) {
      document.getElementById(id_title).style.fontWeight = "normal";
    }

    if (document.getElementById(id_read_unread)) {
      document.getElementById(id_read_unread).innerHTML = "Mark Unread";
    }

    if (document.getElementById(id_read_unread_footer)) {
      document.getElementById(id_read_unread_footer).innerHTML = "Mark Unread";
    }

    // The color differs depending upon whether or not the description is expanded
    if (document.getElementById(id_item)) {
      if (state_desc[id] == 'block' || page_read > 0) {
        document.getElementById(id_item).style.backgroundColor = "#E7E7E7";
      } else {
        document.getElementById(id_item).style.backgroundColor = "#E0E0E0";
      }
    }
  }

  // Mark Page Unread should be displayed
  $("#menu_read_group").show();
  $("#menu_page_unread").show();

  // Check to see if the Mark Page Read menu entry needs to be hidden
  markRead=0;
  $(".mark-read").each(function () {
    if ($(this).html() == "Mark Read" ) {
      markRead=1;
      return false;
    }
  });

  if (markRead == 0) {
    // Hide the Mark Page Read menu
    $("#menu_page_read").hide();
  }
}

function changeReadOnChange(id_first,page_read) {
  id_read_unread = "read_unread_" + id_first;
  id_read_unread_footer = "read_unread_footer_" + id_first;
  id_title = "title_" + id_first;

  if (xmlHttpRead[id_first].readyState == 4 || xmlHttpRead[id_first].readyState == "complete") {
    // Get the data from the server's response
    var result=xmlHttpRead[id_first].responseText;

    // Make sure the query was a success before changing the color
    if ((result > 1 || result == 0) && result != "") {
      alert("The item could not be marked read. Please check your connection and try again later.");
      document.getElementById(id_title).style.fontWeight = "bold";
      document.getElementById(id_read_unread).innerHTML = "Mark Read";
      document.getElementById(id_read_unread_footer).innerHTML = "Mark Read";

      // Mark Page Read should be displayed
      $("#menu_read_group").show();
      $("#menu_page_read").show();

      // Check to see if the Mark Page Unread menu entry needs to be hidden
      markUnread=0;
      $(".mark-read").each(function () {
        if ($(this).html() == "Mark Unread" ) {
          markUnread=1;
          return false;
        }
      });

      if (markUnread == 0) {
        // Hide the Mark Page Unread menu
        $("#menu_page_unread").hide();
      }
    }
  }
}

function read_unread(id,fid,page,read_status,page_read) {
  // read_status is used if document.getElementById fails or only Google Reader needs to be updated
  // read_status = 0 means mark read
  // read_status = 1 means mark unread
  // read_status = 2 means mark read or unread in Google Reader only
  // read_status = 3 means mark the items read on the screen, but don't do anything using Ajax
  // page_read = 0 means an individual item was clicked
  // page_read = 1 means the page is being marked read
  // page_read = 2 means the page is being marked unread

  // Mark sure an id was passed
  if (id != "") {
    // Check to see if more than one id was passed
    if (id.match("_")) {
      // Multiple ids were passed
      var id_array = id.split('_');
      id_first = id_array[0];
    } else {
      // Only one id was passed
      var id_array = new Array();
      id_array[0] = id;
      id_first = id;
    }

    // Determine whether a Read or Unread link was clicked
    // Make sure the item wasn't saved
    id_read_unread = "read_unread_" + id_first;
    if (document.getElementById) {
      if (page_read == 0) {
        state_read=document.getElementById(id_read_unread).innerHTML;
      } else if (page_read == 1) {
        state_read="Mark Read";
        id="";

        // Determine which items need to be marked read
        for (idx in id_array) {
          id_read = "read_unread_" + id_array[idx];

          if (document.getElementById(id_read)) {
            // For any view except the Saved view we need to filter out saved items from the results
            if (fid == "saved") {
              flag="";
            } else {
              id_save = "save_" + id_array[idx];
              state_save=document.getElementById(id_save).src;
              position=state_save.lastIndexOf("/") + 1;
              flag=state_save.slice(position);
            }

            if (document.getElementById(id_read).innerHTML == "Mark Read" && flag != "starred-interesting.png" && flag != "starred-not-interesting.png" && flag != "starred.png") {
              if (id_first == 0) {
                id_first=id_array[idx];
              }

              if (id == "") {
                id=id_array[idx];
              } else {
                id+="_" + id_array[idx];
              }
            } else if (id_first == id_array[idx]) {
              id_first=0;
            }
          }
        }
      } else {
        state_read="Mark Unread";
        id="";

        // Determine which items need to be marked unread
        for (idx in id_array) {
          id_read = "read_unread_" + id_array[idx];

          if (document.getElementById(id_read)) {
            id_save = "save_" + id_array[idx];
            state_save=document.getElementById(id_save).src;
            position=state_save.lastIndexOf("/") + 1;
            flag=state_save.slice(position);

            if (document.getElementById(id_read).innerHTML == "Mark Unread" && flag != "starred-interesting.png" && flag != "starred-not-interesting.png" && flag != "starred.png") {
              if (id_first == 0) {
                id_first=id_array[idx];
              }

              if (id == "") {
                id=id_array[idx];
              } else {
                id+="_" + id_array[idx];
              }
            } else if (id_first == id_array[idx]) {
              id_first=0;
            }
          }
        }
      }

      if (state_read == "Mark Read" && id != "") {
        xmlHttpRead[id_first]=GetXmlHttpObject();
        if (xmlHttpRead[id_first] != null) {
          changeRead(id,page_read,read_status);
          if (read_status == 2) {
            var url="/ajax_read_google?r=" + id + "&fid=" + fid;
          } else {
            var url="/ajax_read?r=" + id;
          }
          if (read_status < 3) {
            xmlHttpRead[id_first].open("GET",url,true);
            xmlHttpRead[id_first].onreadystatechange=function(){changeReadOnChange(id_first,page_read)};
            xmlHttpRead[id_first].send(null);
          }
        } else {
          // Redirect to the mark_read page because ajax isn't supported
          var url="/mark_read?r=" + id + "&fid=" + fid + "&page=" + page;
          document.location.href=url;
        }
      } else if (id != "") {
        xmlHttpUnread[id_first]=GetXmlHttpObject();
        // The link was Mark 'Unread'
        if (xmlHttpUnread[id_first] != null) {
          changeUnread(id,page_read,read_status);
          if (read_status == 2) {
            var url="/ajax_unread_google?ur=" + id + "&fid=" + fid;
          } else {
            var url="/ajax_unread?ur=" + id;
          }
          if (read_status < 3) {
            xmlHttpUnread[id_first].open("GET",url,true);
            xmlHttpUnread[id_first].onreadystatechange=function(){changeUnreadOnChange(id_first,page_read)};
            xmlHttpUnread[id_first].send(null);
          }
        } else {
          // Redirect to the mark_read page because ajax isn't supported
          var url="/mark_unread?ur=" + id + "&fid=" + fid + "&page=" + page;
          document.location.href=url;
        }
      }
    } else {
      if (read_status == 1) {
        // Redirect to the mark_read page because ajax isn't supported
        var url="/mark_unread?ur=" + id + "&fid=" + fid + "&page=" + page;
      } else {
        // Redirect to the mark_read page because ajax isn't supported
        var url="/mark_read?r=" + id + "&fid=" + fid + "&page=" + page;
      }
      document.location.href=url;
    }
  }
}

function changeMarkAllRead() {
  if (xmlHttpMarkAllRead.readyState == 4 || xmlHttpMarkAllRead.readyState == "complete") {
    // Get the data from the server's response
    var result=xmlHttpMarkAllRead.responseText;
  }
}

function markAllRead(fid,gid,search_url) {
  // markAllRead only updates Google Reader
  // fid is the feed_id being passed
  // gid is the URL formatted group if similar items are being marked read
  // search_url are the URL formatted search terms to modify the query

  // range will contain the value designating the appropriate date range to mark all read
  range = $("#range-radio input:radio:checked").val();

  xmlHttpMarkAllRead=GetXmlHttpObject();
  if (xmlHttpMarkAllRead != null) {
    var url="/ajax_read_google?r=all&fid=" + fid + gid + search_url + "&range=" + range;
    xmlHttpMarkAllRead.open("GET",url,true);
    xmlHttpMarkAllRead.onreadystatechange=function(){changeMarkAllRead()};
    xmlHttpMarkAllRead.send(null);
  }
}

function hideFeedDescriptions() {
  if (xmlHttpFeedDesc.readyState == 4 || xmlHttpFeedDesc.readyState == "complete") {
    // Get the data from the server's response
    var result=xmlHttpFeedDesc.responseText;
  }
}

function showFeedDescriptions() {
  if (xmlHttpFeedDesc.readyState == 4 || xmlHttpFeedDesc.readyState == "complete") {
    // Get the data from the server's response
    var result=xmlHttpFeedDesc.responseText;
  }
}

function toggle_feed_descriptions(find_feed_desc) {
  xmlHttpFeedDesc=GetXmlHttpObject();
  if (xmlHttpFeedDesc == null) {
    // Redirect to the non-javascript page because Ajax isn't supported
    if (find_feed_desc == 1) {
      url="/show_feed_descriptions";
    } else {
      url="/hide_feed_descriptions";
    }
    document.location.href=url;
  } else {
    if (document.getElementById) {
      // Check to see which link was clicked
      if (document.getElementById("menu_feed_descriptions").innerHTML == "Show Feed Descriptions") {
        // Show the descriptions
        var e=document.getElementsByName("find_feed_description");
        for (var i=0;i<e.length;i++) {
          e[i].style.display = "inline";
        }
        var e=document.getElementsByTagName("span");
        for (var i=0;i<e.length;i++) {
          e[i].style.display = "inline";
        }

        // Change the menu to reflect the new setting
        document.getElementById("menu_feed_descriptions").innerHTML = "Hide Feed Descriptions";

        // Update the find_feed_desc setting in user_prefs
        var url="/ajax_show_feed_descriptions";
        xmlHttpFeedDesc.open("GET",url,true);
        xmlHttpFeedDesc.onreadystatechange=function(){showFeedDescriptions()};
        xmlHttpFeedDesc.send(null);
      } else {
        // Hide the descriptions
        var e=document.getElementsByName("find_feed_description");
        for (var i=0;i<e.length;i++) {
          e[i].style.display = "none";
        }
        var e=document.getElementsByTagName("span");
        for (var i=0;i<e.length;i++) {
          e[i].style.display = "none";
        }

        // Change the menu to reflect the new setting
        document.getElementById("menu_feed_descriptions").innerHTML = "Show Feed Descriptions";

        // Update the find_feed_desc setting in user_prefs
        var url="/ajax_hide_feed_descriptions";
        xmlHttpFeedDesc.open("GET",url,true);
        xmlHttpFeedDesc.onreadystatechange=function(){hideFeedDescriptions()};
        xmlHttpFeedDesc.send(null);
      }
    } else {
      // Redirect to the non-javascript page because the needed feature isn't supported
      if (find_feed_desc == 1) {
        url="/show_feed_descriptions";
      } else {
        url="/hide_feed_descriptions";
      }
      document.location.href=url;
    }
  }
}

function goToWebsiteOnChange() {
  if (xmlHttpGoTo.readyState == 4 || xmlHttpGoTo.readyState == "complete") {
    // Get the data from the server's response
    var result=xmlHttpGoTo.responseText;
  }
}

function goToWebsite(id,v,m,f,i,mark_as_read) {
  // Updates the link color, viewed status, and mark read as is appropriate

  // Check to see if more than one id was passed
  if (id.match("_")) {
    // Multiple ids were passed
    var id_array = id.split('_');
    id_first = id_array[0];
  } else {
    // Only one id was passed
    id_first = id;
  }

  // Confirm the read or unread status
  id_read = "read_unread_" + id_first;
  if (document.getElementById(id_read).innerHTML == "Mark Read") {
    m=0;
  } else if (document.getElementById(id_read).innerHTML == "Mark Unread") {
    m=1;
  }

  // Confirm the viewed status
  id_title = "title_" + id_first;
  // Make sure the title hadn't been turned gray after expanding the item
  if (document.getElementById(id_title).style.color == "#808080") {
    v=0;
  } else if (document.getElementById(id_title).style.color == "purple") {
    v=1;
  }

  // If the item isn't already viewed the color should change
  if (v != 1) {
    viewed(id_first);
  }

  xmlHttpGoTo=GetXmlHttpObject();
  if (xmlHttpGoTo == null) {
    // Redirect to the non-javascript page because Ajax isn't supported
    url="/go?id=" + id_first + "&v=" + v + "&m=" + m + "&f=" + f + "&i=" + i;
    document.location.href=url;
  } else {
    if (document.getElementById) {
      if (mark_as_read == 1 && m == 0) {
        changeRead(id,0,0);
      }
      var url="/ajax_go?id=" + id_first + "&v=" + v + "&m=" + m + "&f=" + f + "&i=" + i + "&mr=" + mark_as_read;
      xmlHttpGoTo.open("GET",url,true);
      xmlHttpGoTo.onreadystatechange=function(){goToWebsiteOnChange()};
      xmlHttpGoTo.send(null);
    } else {
      // Redirect to the non-javascript page because the needed feature isn't supported
      url="/go?id=" + id_first + "&v=" + v + "&m=" + m + "&f=" + f + "&i=" + i;
      document.location.href=url;
    }
  }
}

function highlightItem(id,op) {
  // Used on mouseover to highlight an item.
  // id is the entry_id being highlighted and op tells whether the highlight should be added or removed

  // Only change the highlighting if the item is collapsed
  if (state_desc[id] != 'block') {
    if (document.getElementById) {
      id_item = "item_" + id;
      id_read_unread = "read_unread_" + id;

      if (document.getElementById(id_read_unread)) {
        state_read=document.getElementById(id_read_unread).innerHTML;
      } else {
        state_read="";
      }

      if (op == 1) {
        // Highlight the item
        if (state_read == "Mark Unread") {
          document.getElementById(id_item).style.backgroundColor = "#E0E0E0";
        } else {
          document.getElementById(id_item).style.backgroundColor = "#F6F6F6";
        }
      } else {
        // Set the item back to normal
        if (state_read == "Mark Unread") {
          document.getElementById(id_item).style.backgroundColor = "#E7E7E7";
        } else {
          document.getElementById(id_item).style.backgroundColor = "#FFFFFF";
        }
      }
    }
  }
}

function addFeed() {
  if (xmlHttpFeed.readyState == 4 || xmlHttpFeed.readyState == "complete") {
    // Get the data from the server's response
    var result=xmlHttpFeed.responseText;

    // Make sure the query was a success before changing the color
    if (result == 0) {
      alert("The feed could not be subscribed to. Please check your connection and try again later.");

      if (document.getElementById("subscribe_title")) {
        document.getElementById("subscribe_title").innerHTML = "Subscribe";
      }

      if (document.getElementById("subscribe_menu")) {
        document.getElementById("subscribe_menu").innerHTML = "Subscribe";
      }
    } else if (result != 1 && result != "") {
      // Change the star icons to reflect whether an item is interesting or not
      // result format is interesting entry_ids separated by and underscore and closed by a :
      // not interesting entries follow the :

      // Split the result into interesting and not interesting arrays
      var int_array = result.split(":");
      interesting = int_array[0];
      not_interesting = int_array[1];

      // Update the icon for each interesting item
      if (interesting != "") {
        if (interesting.match("_")) {
          // There is more than one interesting item to check
          var int_array2 = interesting.split("_");

          for (idx in int_array2) {
            id_save = "save_" + int_array2[idx];
            id_interesting = "interesting_" + int_array2[idx];

            if (document.getElementById(id_save)) {
              state_save=document.getElementById(id_save).src;
              position=state_save.lastIndexOf("/") + 1;
              flag=state_save.slice(position);

              if (flag == "starred-not-interesting.png") {
                document.getElementById(id_save).src = "/themes/feedsanywhere/starred-interesting.png";
              } else {
                document.getElementById(id_save).src = "/themes/feedsanywhere/star-interesting.png";
              }
            }

            if (document.getElementById(id_interesting)) {
              document.getElementById(id_interesting).src = "/themes/feedsanywhere/interesting-green-29x29.png";
            }
          }
        } else {
          // There is only one interesting item
          id_save = "save_" + interesting;
          id_interesting = "interesting_" + interesting;

          if (document.getElementById(id_save)) {
            state_save=document.getElementById(id_save).src;
            position=state_save.lastIndexOf("/") + 1;
            flag=state_save.slice(position);

            if (flag == "starred-not-interesting.png") {
              document.getElementById(id_save).src = "/themes/feedsanywhere/starred-interesting.png";
            } else {
              document.getElementById(id_save).src = "/themes/feedsanywhere/star-interesting.png";
            }
          }

          if (document.getElementById(id_interesting)) {
            document.getElementById(id_interesting).src = "/themes/feedsanywhere/interesting-green-29x29.png";
          }
        }
      }

      // Update the icon for each not interesting item
      if (not_interesting != "") {
        if (not_interesting.match("_")) {
          // There is more than one not interesting item to check
          var int_array2 = not_interesting.split("_");

          for (idx in int_array2) {
            id_save = "save_" + int_array2[idx];
            id_not_interesting = "not_interesting_" + int_array2[idx];

            if (document.getElementById(id_save)) {
              state_save=document.getElementById(id_save).src;
              position=state_save.lastIndexOf("/") + 1;
              flag=state_save.slice(position);

              if (flag == "starred-interesting.png") {
                document.getElementById(id_save).src = "/themes/feedsanywhere/starred-not-interesting.png";
              } else {
                document.getElementById(id_save).src = "/themes/feedsanywhere/star-not-interesting.png";
              }
            }

            if (document.getElementById(id_not_interesting)) {
              document.getElementById(id_not_interesting).src = "/themes/feedsanywhere/not_interesting-red-29x29.png";
            }
          }
        } else {
          // There is only one not interesting item
          id_save = "save_" + not_interesting;
          id_not_interesting = "not_interesting_" + not_interesting;

          if (document.getElementById(id_save)) {
            state_save=document.getElementById(id_save).src;
            position=state_save.lastIndexOf("/") + 1;
            flag=state_save.slice(position);

            if (flag == "starred-interesting.png") {
              document.getElementById(id_save).src = "/themes/feedsanywhere/starred-not-interesting.png";
            } else {
              document.getElementById(id_save).src = "/themes/feedsanywhere/star-not-interesting.png";
            }
          }

          if (document.getElementById(id_not_interesting)) {
            document.getElementById(id_not_interesting).src = "/themes/feedsanywhere/not_interesting-red-29x29.png";
          }
        }
      }
    }
  }
}

function deleteFeed() {
  if (xmlHttpFeed.readyState == 4 || xmlHttpFeed.readyState == "complete") {
    // Get the data from the server's response
    var result=xmlHttpFeed.responseText;

    // Make sure the query was a success before changing the color
    if ((result > 1 || result == 0) && result != "") {
      alert("The feed could not be unsubscribed. Please check your connection and try again later.");
      document.getElementById("subscribe_title").innerHTML = "Unsubscribe";
      document.getElementById("subscribe_menu").innerHTML = "Unsubscribe";
    }
  }
}

function addDeleteFeed(fid,page,act) {
  // fid is the feed_id
  // page is the current page the user is on so they can be returned to the same point
  // act determines whether a feed is being subscribed (1) to or unsubscribed (0) to
  // After subscribing or unsubscribing to the feed the interesting status needs to be updated

  // Make sure a valid feed_id is used
  if (fid > 0) {
    if (document.getElementById) {
      xmlHttpFeed=GetXmlHttpObject();
      if (xmlHttpFeed == null) {
        // Redirect to the non-javascript page because Ajax isn't supported
        if (document.getElementById("subscribe_menu").innerHTML == "Subscribe") {
          url="/add_feed?fid=" + fid + "&page=" + page;
        } else {
          url="/delete_feed?fid=" + fid + "&page=" + page;
        }
        document.location.href=url;
      } else {
        // Check to see which link was clicked
        if (document.getElementById("subscribe_menu").innerHTML == "Subscribe") {
          // The user wants to subscribe to the feed
          document.getElementById("subscribe_menu").innerHTML = "Unsubscribe";

          if (document.getElementById("subscribe_title")) {
            document.getElementById("subscribe_title").innerHTML = "Unsubscribe";
          }

          // Contact the server and subscribe to the feed
          var url="/ajax_add_feed?fid=" + fid;
          xmlHttpFeed.open("GET",url,true);
          xmlHttpFeed.onreadystatechange=function(){addFeed()};
          xmlHttpFeed.send(null);
        } else {
          // The user wants to unsubscribe to the feed
          document.getElementById("subscribe_menu").innerHTML = "Subscribe";

          if (document.getElementById("subscribe_title")) {
            document.getElementById("subscribe_title").innerHTML = "Subscribe";
          }

          // Contact the server and unsubscribe to the feed
          var url="/ajax_delete_feed?fid=" + fid;
          xmlHttpFeed.open("GET",url,true);
          xmlHttpFeed.onreadystatechange=function(){deleteFeed()};
          xmlHttpFeed.send(null);
        }
      }
    } else {
      // Redirect to the non-javascript page because the needed feature isn't supported
      if (act == 1) {
        url="/add_feed?fid=" + fid + "&page=" + page;
      } else {
        url="/delete_feed?fid=" + fid + "&page=" + page;
      }
      document.location.href=url;
    }
  }
}

function checkStatus(fid) {
  // Update each items star icon with its interesting status
  // fid is the feed_id

  // Make sure a valid feed_id is used
  if (fid > 0 || fid == "interesting" || fid == "all" || fid == "saved" || fid == "popular") {
    if (document.getElementById) {
      xmlHttpAddFeed=GetXmlHttpObject();
      if (xmlHttpAddFeed == null) {
        // Do nothing
      } else {
        // Contact the server and subscribe to the feed
        var url="/ajax_check_status?fid=" + fid;
        xmlHttpAddFeed.open("GET",url,true);
        xmlHttpAddFeed.onreadystatechange=function(){addFeed()};
        xmlHttpAddFeed.send(null);
      }
    }
  }
}

function autoAddFeed(fid) {
  // Subscribe to the feed
  if (document.getElementById) {
    xmlHttpAddFeed=GetXmlHttpObject();
    if (xmlHttpAddFeed == null) {
      // Do nothing
    } else {
      // Is the feed being subscribed to also being viewed now?
      if (document.getElementById("subscribe_menu")) {
        if (document.getElementById("subscribe_menu").innerHTML == "Subscribe") {
          // The user wants to subscribe to the feed
          document.getElementById("subscribe_menu").innerHTML = "Unsubscribe";

          if (document.getElementById("subscribe_title").innerHTML == "Subscribe") {
            document.getElementById("subscribe_title").innerHTML = "Unsubscribe";
          }
        }
      }

      // Contact the server and subscribe to the feed
      var url="/ajax_add_feed?fid=" + fid;
      xmlHttpAddFeed.open("GET",url,true);
      xmlHttpAddFeed.onreadystatechange=function(){addFeed()};
      xmlHttpAddFeed.send(null);
    }
  }
}

function changeWidth(psetting,simple) {
  // Resets the page based upon the current page width
  // psetting determines whether previews should be shown. It is used by the preview() function.
  // simple determines whether simple view is shown

  // Set sbw to the window's width
  sbw=$(window).width();

  // Hide the top menu if the width it too small
  if (sbw < 550) {
    $("#menu_header").removeClass("menu-header-inline");
    $("#menu_header").addClass("menu-header-block");
    $("#menu_logo").removeClass("menu-logo-inline");
    $("#menu_logo").addClass("menu-logo-block");
  } else {
    $("#menu_header").removeClass("menu-header-block");
    $("#menu_header").addClass("menu-header-inline");
    $("#menu_logo").removeClass("menu-logo-block");
    $("#menu_logo").addClass("menu-logo-inline");
  }

  // Set the width to limit position the front page image properly
  if (document.getElementById("front_page")) {
    if (sbw > 800) {
      document.getElementById("front_page").style.width="800px";
    } else {
      document.getElementById("front_page").style.width="100%";
    }
  }

  // For small screens the login box should move to the top of the screen
  if (document.getElementById("home-login-box")) {
    if (sbw > 775) {
      document.getElementById("home-login-box").style.cssFloat="right";

      // Reset the image to its original size
      document.getElementById("home-main-image").style.width="494px";

      document.getElementById("box-content").style.padding="24px";

      // Get the top position. This will be used to calculate the login box position.
      if (document.getElementById("top_position")) {
        // Get the top position. This will be used to calculate the login box position.
        t_position=document.getElementById("top_position").offsetTop;
      }

      if (document.getElementById("bottom_position")) {
        // Get the bottom position. This will be used to calculate the login box position.
        b_position=document.getElementById("bottom_position").offsetTop;
      }

      // Define the height of the login box. It is used for calculation margin-top.
      login_height=document.getElementById("home-login-box").clientHeight;

      // Calculate the margin-top for the login box
      login_margin=(b_position - t_position - login_height - 20) / 2;

      // Make sure login_margin doesn't go below -8 or it could mess thing up
      if (login_margin < -8) {
        login_margin=-8;
      }

      document.getElementById("home-login-box").style.marginTop=login_margin + "px";
    } else if (sbw > 500) {
      document.getElementById("home-login-box").style.cssFloat="right";

      // Need to scale the image so the login box can stay to the right
      image_width=sbw - 285;
      document.getElementById("home-main-image").style.width=image_width + "px";

      document.getElementById("box-content").style.padding="24px";

      // Get the top position. This will be used to calculate the login box position.
      if (document.getElementById("top_position")) {
        // Get the top position. This will be used to calculate the login box position.
        t_position=document.getElementById("top_position").offsetTop;
      }

      if (document.getElementById("bottom_position")) {
        // Get the bottom position. This will be used to calculate the login box position.
        b_position=document.getElementById("bottom_position").offsetTop;
      }

      // Define the height of the login box. It is used for calculation margin-top.
      login_height=document.getElementById("home-login-box").clientHeight;

      // Calculate the margin-top for the login box
      login_margin=(b_position - t_position - login_height - 20) / 2;

      // Make sure login_margin doesn't go below -8 or it could mess thing up
      if (login_margin < -8) {
        login_margin=-8;
      }

      document.getElementById("home-login-box").style.marginTop=login_margin + "px";
    } else {
      document.getElementById("home-login-box").style.cssFloat="none";
      document.getElementById("home-login-box").style.marginTop="0px";
      document.getElementById("box-content").style.padding="16px";

      // Create a little padding around the image
      image_width=sbw - 8;
      document.getElementById("home-main-image").style.width=image_width + "px";
    }
  }

  // Adjust how and when the search boxes are displayed based on screen width
  if (sbw > 640) {
    $("#search-text1").show();
    $("#submit-search1").show();
  } else {
    $("#search-text1").hide();
    $("#submit-search1").hide();
  }

  // Make sure the proper ads are displaying
  displayAds();

  if (document.getElementById("ad_sidebar2")) {
    if (document.getElementById("ad_sidebar2").style.display == "block") {
      displayBottomAds();
    }
  }

  // Determine whether or not previews should be shown for each item
  if (psetting < 2 ) {
    preview(psetting,simple);
  }
}

function displayAds() {
  // The page.tpl.php, menu.php, and footer.php files pick the id name based on the page
  // Either Google or Amazon ads are shown based upon the id

  // Set sbw to the window's width
  sbw=$(window).width();

  if (sbw > 800) {
    if (document.getElementById("ad_mobile")) {
      document.getElementById("ad_mobile").style.display="none";
    }

    // Make sure a line is drawn between the items and ad
    if (document.getElementById("middle")) {
      document.getElementById("middle").style.borderRightColor="gray";
      document.getElementById("middle").style.borderRightWidth="1px";
      document.getElementById("middle").style.borderRightStyle="solid";

      // Make room for the ad
      document.getElementById("middle").style.marginRight="168px";
    }

    // Display the sidebar ads
    if (document.getElementById("ad_sidebar")) {
      document.getElementById("ad_sidebar").style.display="block";
    }
  } else {
    if (document.getElementById("ad_sidebar")) {
      document.getElementById("ad_sidebar").style.display="none";
    }

    if (document.getElementById("ad_sidebar2")) {
      document.getElementById("ad_sidebar2").style.display="none";
      document.getElementById("ad_sidebar2").src="";
    }

    // Remove the line between the items and ad
    if (document.getElementById("middle")) {
      document.getElementById("middle").style.borderRightWidth="0";

      // Use the space the ad used to occupy
      document.getElementById("middle").style.marginRight="0";
    }

    // Display a banner ad
    if (document.getElementById("ad_mobile")) {
      // Make sure there is actually something to display
      if ($("#ad_mobile").html() != "<!-- google_afm -->") {
        document.getElementById("ad_mobile").style.display="block";
      }
    }
  }
}

function displayBottomAds() {
  // Positions the bottom right ad if the page is long enough

  // Set sbw to the window's width
  sbw=$(window).width();

  footerPosition=document.getElementById("footer").offsetTop;

  if (sbw > 800 && footerPosition > 1500) {
    // If the footer is far enough down the page a second add should be shown in the sidebar
    if (document.getElementById("ad_sidebar2")) {
      if (document.getElementById("ad_sidebar2").style.display != "block") {
        document.getElementById("ad_sidebar2").style.display="block";
        document.getElementById("ad_sidebar2").style.position="absolute";
        sidebarLeft=$(window).width() - 168;
        document.getElementById("ad_sidebar2").style.left=sidebarLeft + "px";
        document.getElementById("ad_sidebar2").style.height="608px";
        document.getElementById("ad_sidebar2").src="/ad_sidebar_google.html";
      }

      sidebarTop=document.getElementById("footer").offsetTop - 608;
      document.getElementById("ad_sidebar2").style.top=sidebarTop + "px";
    }
  } else {
    if (document.getElementById("ad_sidebar2")) {
      document.getElementById("ad_sidebar2").style.display="none";
      document.getElementById("ad_sidebar2").src="";
    }
  }
}

function preview(setting,simple) {
  // Checks whether the user has previews enabled and displays them if appropriate
  // setting determines whether the preview should be shown
  // simple determines whether the simple view is being used, 0 (disabled) is the default
  // If the screen is too small previews should not be shown

  // Determine if sidebar ads are being shown
  if (document.getElementById("ad_sidebar")) {
    if (document.getElementById("ad_sidebar").style.display == "none") {
      sidebar_width=0;
    } else {
      sidebar_width=168;
    }
    min_screen_width=900;
  } else {
    sidebar_width=0;
    min_screen_width=750;
  }

  // Set sbw to the window's width
  if (window.innerWidth) {
    sbw=window.innerWidth;
  } else if (document.all) {
    sbw=document.body.clientWidth;
  } else {
    sbw=0;
  }

  if (setting == 1 && sbw > min_screen_width) {
    // Show previews

    // Determine how long the item can be and still have the preview shown
    var maxLength = (sbw - sidebar_width) / 11;

    // Setup the formatting so the preview displays properly
    if (document.getElementsByName("preview_div") && document.getElementsByName("preview_title") && document.getElementsByName("preview")) {
      var d=document.getElementsByName("preview_div");
      var t=document.getElementsByName("preview_title");
      var p=document.getElementsByName("preview");
      for (var i=0;i<d.length;i++) {
        txt=t[i].innerHTML;
        long=txt.length - 63; // 63 accounts for the Google ad hints

        // Make sure the entire title will be shown
        if (long < maxLength) {
          if (d[i] && p[i]) {
            d[i].style.paddingLeft = "0px";
            d[i].style.overflow = "hidden";
            d[i].style.whiteSpace = "nowrap";
            p[i].style.display = "inline";
          }
        }
      }
    }
  } else if (setting > 1) {
    // Do nothing
  } else {
    // Hide previews
    // Setup the formatting so the item displays properly without a preview
    if (document.getElementsByName("preview_div")) {
      var d=document.getElementsByName("preview_div");
      var p=document.getElementsByName("preview");
      for (var i=0;i<d.length;i++) {
        if (d[i] && p[i]) {
          if (simple == 1) {
            d[i].style.paddingLeft = "0px";
          } else if (document.getElementById("fa_login")) {
            d[i].style.paddingLeft = "0px";
          } else {
            d[i].style.paddingLeft = "30px";
          }
          d[i].style.overflow = "visible";
          d[i].style.whiteSpace = "normal";
          p[i].style.display = "none";
        }
      }
    }
  }
}

function undiscoverStatus() {
  if (xmlHttpUndiscover.readyState == 4 || xmlHttpUndiscover.readyState == "complete") {
    // Get the data from the server's response
    var result=xmlHttpUndiscover.responseText;

    // Alert the user if the update failed
    if ((result > 1 || result == 0) && result != "") {
      alert("The discover setting could not be cleared. Please check your connection and try again later.");
    }
  }
}

function undiscover(gid,page,qstr) {
  // Sets it so only similar items from subscribed feeds are shown
  // gid is the group id
  // page is the current page number being viewed
  // qstr is the query string from the page so the correct items can be shown

  // Set the discover setting = 1 then reload the page
  if (document.getElementById("discover_icon") && document.getElementById("discover_link")) {
    xmlHttpUndiscover=GetXmlHttpObject();
    if (xmlHttpUndiscover == null) {
      // Use a regular URL instead of Ajax
      var url="/undiscover?fid=similar&gid=" + gid + "&page=" + page;
      document.location.href=url;
    } else {
      prevIcon=document.getElementById("discover_icon").src;
      if (prevIcon.match("undiscover")) {
        document.getElementById("discover_icon").src = "/themes/feedsanywhere/discover.png";
        document.getElementById("discover_link").title = "Only show items from subscribed feeds";
        var url="/ajax_discover";
        disc=1;
      } else {
        document.getElementById("discover_icon").src = "/themes/feedsanywhere/undiscover.png";
        document.getElementById("discover_link").title = "Discover similar items from unsubscribed feeds";
        var url="/ajax_undiscover";
        disc=0;
      }

      xmlHttpUndiscover.open("GET",url,true);
      xmlHttpUndiscover.onreadystatechange=function(){undiscoverStatus()};
      xmlHttpUndiscover.send(null);

      if (document.getElementById("items_and_nav")) {
        // Update the items without a page load
        xmlHttpItems=GetXmlHttpObject();
        if (xmlHttpItems == null) {
          // Reload the page
          var url="/feed/similar/" + gid + "?page=" + page;
          document.location.href=url;
        } else {
          // Get the position of the top of the item
          item_position=$("#items_and_nav").offset();

          // Get the height of the window
          window_height=$(window).height();

          // Get the height of the item
          item_height=$("#items_and_nav").height();

          // Determines the position of the bottom of the item
          // A positive number means it's on screen
          // A negative number means it's off screen
          bottom_position=window_height - item_position.top - item_height - 17;

          if (bottom_position > 0) {
            // The bottom of items and nav is on screen
            // Position the loading image in the center of items_and_nav
            midH=item_height / 2 + item_position.top - 25;
          } else {
            // Find the vertical middle of the screen and adjust for the image size
            midH=window_height / 2 - 8;
          }

          // Set sbw to the window's width
          sbw=$(window).width();

          // Determine the middle of the visible screen
          midW=sbw / 2 - 8;

          // Adjust the opacity or the text
          $("#items_and_nav").fadeTo(1000, 0.3);

          // Show a notice that new content is being loaded if the items aren't returned quickly.
          $.loading(true, {img:'/loading.gif', align: {top:midH,left:midW}});

          var url="/ajax_items?discover=" + disc + "&" + qstr + "&sbw=" + sbw;
          $.get(url, function(result) {
            // Update the page with the new data
            itemsStatus(qstr,result);
          });

          // Move to the top of the page
          window.scrollTo(0,0);
        }
      } else {
        // Reload the page
        var url="/feed/similar/" + gid + "?page=" + page;
        document.location.href=url;
      }
    }
  } else {
    // Use a regular URL instead of Ajax
    var url="/undiscover?fid=similar&gid=" + gid + "&page=" + page;
    document.location.href=url;
  }
}

function itemsStatus(qstr,newItems) {
  // Updates the page when the query completes
  // qstr is the query string passed to the original function. It is needed for setting the onclick behavior of the search box

  // Strip the feed heading from the front
  newItems=newItems.split("|*_|");

  // Display the new items
  $("#items_and_nav").html(newItems[3]);

  // Adjust the positioning for the gotowebsite icon
  adjustForFontSize();

  // Clear preloadPage so an old value doesn't get used again
  $("#items_and_nav").data("preload","");

  // Stop showing the loading status
  $.loading(false);

  // Restore the opacity to normal
  $("#items_and_nav").fadeTo("fast", 1.0);

  // Update the heading
  $("#feed-title").html(newItems[4]);

  // Determine whether or not previews should be shown for each item
  if (newItems[1] < 2) {
    preview(newItems[1],newItems[2]);
  }

  // Update the search link
  $("#search-google").html(newItems[0]);

  // Update the search box at the top
  searchText1=$("#search-text2").val();
  $("#search-text1").val(searchText1);

  // Update the menu

  // Update Mark Page Read

  // Get the data from ajax_items
  markPageRead=newItems[5];

  // Parse the data from ajax_items
  markPageRead=markPageRead.split(",");

  // Rename the variables for better code readability
  entry_ids=markPageRead[0];
  feed_id=markPageRead[1];
  page_num=markPageRead[2];
  nav=markPageRead[3];
  readUnread=markPageRead[4];
  num_unread=markPageRead[5];
  page_unread=markPageRead[6];
  numItemsDisplayed=markPageRead[7];
  hideUnread=markPageRead[8];
  int1000=markPageRead[9];
  all1000=markPageRead[10];
  discover=markPageRead[11];

  // Contains the entry_ids on the page that are in a group
  if (newItems[6] != "") {
    // Display similar icons and unread counts as appropriate

    // Fetch the HTML for each of the grouped items
    $.post("/ajax_similar", { s: newItems[6], page: page_num, discover: discover, hide_unread: hideUnread }, function(result) {
      // Break out the items for each entry_id that needs similar items for be displayed
      if (result != "") {
        similarItems=result.split("|*_|");

        // Loop through each entry that was returned
        for (entry in similarItems) {
          itemEntry=similarItems[entry].split("%%%");

          entryID=itemEntry[0];
          similarIcon=itemEntry[1];
          similar=itemEntry[2];

          // Update the icon in the title and description footer
          $("#sim_icon_" + entryID).html(similarIcon);
          $("#similar_" + entryID).html(similar);
        }
      }
    });
  }

  // Update the URL hash to reflect the current page
  window.location.hash=page_num;

  // Strip read_unread and feed_view from the link. They aren't needed.
  qstrTemp="";
  qstr_read_temp="";

  qstr_array=qstr.split("&");
  for (q in qstr_array) {
    if (qstr_array[q].match("read_unread=") || qstr_array[q].match("feed_view=")) {
      // Don't include this part in the new query string
    } else {
      if (qstr_array[q].match("skip=")) {
        // Set up the mark page read link
        qstr_read_temp="&" + qstr_array[q] + "_" + entry_ids;
      } else {
        // Recontruct the link
        if (qstrTemp == "") {
          qstrTemp=qstr_array[q];
        } else {
          qstrTemp+="&" + qstr_array[q];
        }
      }
    }
  }
  qstr=qstrTemp;

  // Append the entry ids for items being marked read so they are skipped
  if (qstr_read_temp == "") {
    qstr_read=qstr + "&skip=" + entry_ids;
  } else {
    qstr_read=qstr + qstr_read_temp;
  }

  // Determine whether Mark Page Read should be shown
  if (page_unread > 0) {
    $("#menu_read_group").show();
    $("#menu_page_read").show();
  } else {
    $("#menu_page_read").hide();
  }

  // Unbind the current click event to the following isn't additive
  $("#mark_page_read").unbind('click');

  // Only add navigation if a new page needs to be loaded
  if (nav == 1 && entry_ids != "") {
    $("#mark_page_read").click(function(){
      // Mark the items read
      read_unread(entry_ids,feed_id,page_num,0,1);

      // Show the new page
      navigation(qstr_read,2);

      return false;
    });
  } else if (entry_ids != "") {
    $("#mark_page_read").click(function(){
      // Mark the items read
      read_unread(entry_ids,feed_id,page_num,0,1);

      return false;
    });
  }

  // Check to see whether Mark All Read should be shown
  if (num_unread == page_unread || numItemsDisplayed < 10) {
    // Hide Mark All Read when all unread items are on the current screen
    $("#menu_all_read").hide();
  } else {
    // Mark All Read should be displayed
    $("#menu_read_group").show();
    $("#menu_all_read").show();
  }

  // Update Mark Page Unread

  // Unbind the current click event to the following isn't additive
  $("#mark_page_unread").unbind('click');

  $("#mark_page_unread").click(function(){
    // Mark the items unread
    read_unread(entry_ids,feed_id,page_num,1,2);

    return false;
  });

  // Determine whether Mark Page Unread should be shown
  if (readUnread == 0 || page_unread == numItemsDisplayed) {
    // Mark Page Unread should be hidden unless an item is individually marked read if only unread items are being shown
    // Mark Page Unread should also be hidden if all items are being shown, but only unread on this page
    $("#menu_page_unread").hide();
  } else {
    $("#menu_read_group").show();
    $("#menu_page_unread").show();
  }

  // Determine if menu_read_group needs to be shown
  if (num_unread == page_unread && page_unread == 0 && (readUnread == 0 || page_unread == numItemsDisplayed)) {
    $("#menu_read_group").hide();
  }

  // Update unread counts
  if (hideUnread == 0) {
    if (feed_id == "interesting" && (num_unread > 0 || num_unread == "1000+")) {
      document.getElementById("menu_interesting").innerHTML = "Show Interesting (" + num_unread + ")";
      if (all1000 > 0) {
        getUnreadCount(0,1,2,1);
      } else {
        getUnreadCount(0,1,1,1);
      }
    } else if (feed_id == "saved" && (num_unread > 0 || num_unread == "1000+")) {
      document.getElementById("menu_saved").innerHTML = "Show Saved (" + num_unread + ")";
      if (int1000 > 0 && all1000 > 0) {
        getUnreadCount(2,0,2,1);
      } else if (int1000 > 0) {
        getUnreadCount(2,0,1,1);
      } else if (all1000 > 0) {
        getUnreadCount(1,0,2,1);
      } else {
        getUnreadCount(1,0,1,1);
      }
    } else if (feed_id == "all" && (num_unread > 0 || num_unread == "1000+")) {
      document.getElementById("menu_all").innerHTML = "Show All (" + num_unread + ")";
      if (int1000 > 0) {
        getUnreadCount(2,1,0,1);
      } else {
        getUnreadCount(1,1,0,1);
      }
    } else if (feed_id == "popular" && (num_unread > 0 || num_unread == "1000+")) {
      document.getElementById("menu_popular").innerHTML = "Show Popular (" + num_unread + ")";
      if (int1000 > 0 && all1000 > 0) {
        getUnreadCount(2,1,2,0);
      } else if (int1000 > 0) {
        getUnreadCount(2,1,1,0);
      } else if (all1000 > 0) {
        getUnreadCount(1,1,2,0);
      } else {
        getUnreadCount(1,1,1,0);
      }
    } else {
      if (int1000 > 0 && all1000 > 0) {
        getUnreadCount(2,1,2,1);
      } else if (int1000 > 0) {
        getUnreadCount(2,1,1,1);
      } else if (all1000 > 0) {
        getUnreadCount(1,1,2,1);
      } else {
        getUnreadCount(1,1,1,1);
      }
    }
  }

  // Set sbw to the window's width
  sbw=$(window).width();

  user_agent=navigator.userAgent;

  // Refresh the appropriate ad
  if (sbw > 800) {
    // Do nothing because the ads are loaded through an iframe
  } else {
    if (user_agent.match("iPhone")) {
      // Do nothing
    } else {
      $.get("/ajax_phone_ads.php", function(result) {
        $("#ad_mobile").html(result);
      });
    }
  }

  // Different query strings are needed depending upon showing unread only or read and unread
  if (readUnread == 1) {
    // The page number needs to be incremented

    if (qstr.match("page=")) {
      // This variable will be used to rebuild the query string
      qstrTemp="";

      qstr_array=qstr.split("&");
      for (q in qstr_array) {
        if (qstr_array[q].match("page=")) {
          // Will break the link into two parts with the second one being the page number
          next_array = qstr_array[q].split('=');
          page_num = parseInt(next_array[1]);
          if (page_num > 0) {
            page_num += 1;
          }

          // Recontruct the page parameter
          qstr_array[q]="page=" + page_num;
        }

        // Recontruct the link
        if (qstrTemp == "") {
          qstrTemp=qstr_array[q];
        } else {
          qstrTemp+="&" + qstr_array[q];
        }
      }
    } else {
      // Page isn't passed which means the page = 1
      qstrTemp=qstr + "&page=2";
    }

    // Preload the next page
    url="/ajax_items?" + qstrTemp + "&sbw=" + sbw + "&preload=1";
    $.get(url, function(result) {
      if ($("#items_and_nav").html() != result) {
        $("#items_and_nav").data("preload",result);

        // Mark the time that the preload was created and add one hour so a freshness check can be done before using it
        preloadTime=new Date().getTime() + 3600000;
        $("#items_and_nav").data("expiration",preloadTime);
      }
    });
  } else if (nav == 1 && entry_ids != "") {
    // Preload the next page
    url="/ajax_items?" + qstr_read + "&sbw=" + sbw + "&preload=1";
    $.get(url, function(result) {
      if ($("#items_and_nav").html() != result) {
        $("#items_and_nav").data("preload",result);

        // Mark the time that the preload was created and add one hour so a freshness check can be done before using it
        preloadTime=new Date().getTime() + 3600000;
        $("#items_and_nav").data("expiration",preloadTime);
      }
    });
  } else {
    // Clear preloadPage because there isn't a next page
    $("#items_and_nav").data("preload","");
  }

  if (document.getElementById("ad_sidebar2")) {
    document.getElementById("ad_sidebar2").style.display="none";
    document.getElementById("ad_sidebar2").src="";
  }

  $("img").load(function(){
    displayBottomAds();
  });
}

function selectAll() {
  var x=document.getElementById("new_user");
  for (var i=0;i<x.length;i++) {
    x.elements[i].checked=true;
  }
}

function selectNone() {
  var x=document.getElementById("new_user");
  for (var i=0;i<x.length;i++) {
    x.elements[i].checked=false;
  }
}

function getUnreadCountStatus(interesting,saved,all,popular,category) {
  // The passed parameters = 1 if the unread count needs to be updated

  if (xmlHttpUnread.readyState == 4 || xmlHttpUnread.readyState == "complete") {
    // Get the data from the server's response
    var result=xmlHttpUnread.responseText;

    if (result.match("|")) {
      // Valid results were found and the unread counts need to be extracted
      var unread_array = result.split("|");

      // Update the Interesting unread count
      if (interesting == 1 && document.getElementById("menu_interesting") && (unread_array[0] > 0 || unread_array[0] == "1000+")) {
        document.getElementById("menu_interesting").innerHTML = "Show Interesting (" + unread_array[0] + ")";
      } else if (interesting == 2 && document.getElementById("menu_interesting")) {
        document.getElementById("menu_interesting").innerHTML = "Show Interesting (1000+)";
      }

      // Update the Saved unread count
      if (saved == 1 && document.getElementById("menu_saved") && (unread_array[1] > 0 || unread_array[1] == "1000+")) {
        document.getElementById("menu_saved").innerHTML = "Show Saved (" + unread_array[1] + ")";
      } else if (saved == 2 && document.getElementById("menu_saved")) {
        document.getElementById("menu_saved").innerHTML = "Show Saved (1000+)";
      }

      // Update the All unread count
      if (all == 1 && document.getElementById("menu_all") && (unread_array[2] > 0 || unread_array[2] == "1000+")) {
        document.getElementById("menu_all").innerHTML = "Show All (" + unread_array[2] + ")";
      } else if (all == 2 && document.getElementById("menu_all")) {
        document.getElementById("menu_all").innerHTML = "Show All (1000+)";
      }

      // Update the Category unread count
      if (category == 1 && document.getElementById("menu_category") && (unread_array[4] > 0 || unread_array[4] == "1000+")) {
        document.getElementById("menu_category").innerHTML = "Show Category (" + unread_array[4] + ")";
      } else if (category == 2 && document.getElementById("menu_category")) {
        document.getElementById("menu_category").innerHTML = "Show Category (1000+)";
      }

      // Update the Popular unread count
      if (popular == 1 && document.getElementById("menu_popular") && (unread_array[3] > 0 || unread_array[3] == "1000+")) {
        document.getElementById("menu_popular").innerHTML = "Show Popular (" + unread_array[3] + ")";
      }
    }
  }
}

function getUnreadCount(interesting,saved,all,popular) {
  // Get the unread count for each listing in the menu
  // interesting needs to be updated if set to 1
  // saved needs to be updated if set to 1
  // all needs to be updated if set to 1
  // popular needs to be updated if set to 1

  xmlHttpUnread=GetXmlHttpObject();
  if (xmlHttpUnread != null) {
    // Determine if the user has any categories
    if (document.getElementById("menu_category")) {
      category=1;
    } else {
      category=0;
    }

    var url="/ajax_get_unread_count?i=" + interesting + "&s=" + saved + "&a=" + all + "&p=" + popular + "&c=" + category;
    xmlHttpUnread.open("GET",url,true);
    xmlHttpUnread.onreadystatechange=function(){getUnreadCountStatus(interesting,saved,all,popular,category)};
    xmlHttpUnread.send(null);
  }
}

function navigation(qstr,nextPage) {
  // Loads the items for the next page that was requested
  // qstr is the query string defining the items to be loaded
  // nextPage is set to 1 when Next was clicked and all items have been marked read
  // nextPage is set to 2 when the Mark Page Read link was selected

  // Remove any legacy search string
  qstr=qstr.replace(/&search_text=.*/,"");

  // Check to see if all items have been marked read already and decrement the page being fetched if they have
  if (nextPage == 1) {
    markRead=0;
    m=0;
    $(".mark-read").each(function () {
      // Keep a counter to make sure all of the items haven't been saved
      m++;

      if ($(this).html() == "Mark Read" ) {
        markRead=1;
        return false;
      }
    });

    if (markRead == 0 && m > 0) {
      // This variable will be used to rebuild the query string
      qstrTemp="";

      qstr_array=qstr.split("&");
      for (q in qstr_array) {
        if (qstr_array[q].match("page=")) {
          // Extract the page number and decrement it before rebuilding the query string

          // Will break the link into two parts with the second one being the page number
          next_array = qstr_array[q].split('=');
          page_num = parseInt(next_array[1]);
          if (page_num > 1) {
            page_num -= 1;
          }

          // Recontruct the page parameter
          qstr_array[q]="page=" + page_num;
        }

        // Recontruct the link
        if (qstrTemp == "") {
          qstrTemp=qstr_array[q];
        } else {
          qstrTemp+="&" + qstr_array[q];
        }
      }

      // Use the newly created query string
      qstr=qstrTemp;
    }
  }

  // Get the position of the top of the item
  item_position=$("#items_and_nav").offset();

  // Get the height of the window
  window_height=$(window).height();

  // Get the height of the item
  item_height=$("#items_and_nav").height();

  // Determines the position of the bottom of the item
  // A positive number means it's on screen
  // A negative number means it's off screen
  bottom_position=window_height - item_position.top - item_height - 17;

  user_agent=navigator.userAgent;

  if (bottom_position > 0) {
    // The bottom of items and nav is on screen

    // Adjustments to the centering needs to be made on the iPhone because the address bar is considered part of the height
    if (user_agent.match("iPhone")) {
      midH=item_height / 2 + item_position.top - 8;
    } else {
      // Position the loading image in the center of items_and_nav
      midH=item_height / 2 + item_position.top - 25;
    }
  } else {
    // Find the vertical middle of the screen and adjust for the image size

    // Adjustments to the centering needs to be made on the iPhone because the address bar is considered part of the height
    if (user_agent.match("iPhone")) {
      midH=window_height / 2 + 9;
    } else {
      midH=window_height / 2 - 8;
    }
  }

  // Set sbw to the window's width
  sbw=$(window).width();

  // Get the width of the items_and_nav section
  item_width=$("#items_and_nav").width();

  if (sbw > item_width) {
    // Determine the middle of the items_and_nav section
    midW=item_width / 2 - 8;
  } else {
    // Determine the middle of the visible screen
    midW=sbw / 2 - 8;
  }

  // Move to the top of the page
  window.scrollTo(0,0);

  if (document.getElementById("items_and_nav")) {
    // Get the current time so it can be compared with the last preload expiration time to determine if the preload is still valid
    currentTime=new Date().getTime();

    // Get the search_text and add it to the query string
    if (document.getElementById("search-text1")) {
      searchText=$("#search-text1").val();
    } else if (document.getElementById("search-text2")) {
      searchText=$("#search-text2").val();
    } else {
      searchText="";
    }

    // Use Post to fetch results if a search is being done
    if (searchText != "") {
      // Rebuild the query string with the search terms
      qstr=qstr + "&search_text=" + searchText;
    }

    if (((nextPage == 1 && markRead == 0) || nextPage == 2) && $("#items_and_nav").data("preload") != "" && currentTime < $("#items_and_nav").data("expiration")) {
      // Use the preloadPage value

      // Adjust the opacity or the text
      $("#items_and_nav").fadeTo(500, 0.3);

      // Show a notice that new content is being loaded if the items aren't returned quickly.
      $.loading(true, {img:'/loading.gif', align: {top:midH,left:midW}});

      var t=setTimeout(function(){itemsStatus(qstr,$("#items_and_nav").data("preload"))},500);
    } else {
      // Update the items without a page load

      // Adjust the opacity or the text
      $("#items_and_nav").fadeTo(1000, 0.3);

      // Show a notice that new content is being loaded if the items aren't returned quickly.
      $.loading(true, {img:'/loading.gif', align: {top:midH,left:midW}});

      var url="/ajax_items?" + qstr + "&sbw=" + sbw;
      $.get(url, function(result) {
        // Update the page with the new data
        itemsStatus(qstr,result);
      });

      // Move to the top of the page
      window.scrollTo(0,0);
    }

    // Reload the sidebar or iPhone ad now that a new page has been loaded
    if (sbw > 800 && document.getElementById("ad_sidebar")) {
      document.getElementById("ad_sidebar").contentDocument.location.reload(true);
    } else if ((user_agent.match("iPhone") || user_agent.match("iOS")) && document.getElementById("ad_mobile")) {
      document.getElementById("ad_mobile").contentDocument.location.reload(true);
    }
  } else {
    // Reload the page
    var url="/feeds.php?" + qstr;
    document.location.href=url;
  }
}

function selectFeedStatus() {
  if (xmlHttpSelectFeed.readyState == 4 || xmlHttpSelectFeed.readyState == "complete") {
    // Get the data from the server's response
    var result=xmlHttpSelectFeed.responseText;

    if (result.match("|")) {
      // Data is returned in the format feed_id|unread_count|*_|feed_id|unread_count|*_| ... and so on
      // Valid results were found and the unread counts need to be extracted
      var feed_array = result.split('|*_|');

      for (feed in feed_array) {
        // Separate out the feed_id and unread count
        var subscribed_array = feed_array[feed].split('|');

        // Get the feed_id and unread count
        subscribedFeed=subscribed_array[0];
        subscribedUnread=subscribed_array[1];

        // Get the name of the feed
        feedName=$("#feed-" + subscribedFeed).html();

        // Format how the feed will display
        feedDisplay=feedName + " (" + subscribedUnread + ")";

        // Updated the feed name with the unread count
        $("#feed-" + subscribedFeed).html(feedDisplay);
      }
    }

    getUnreadCount(1,1,1,1);
  }
}

function selectFeed() {
  // Get the unread counts for each subscribed feed

  xmlHttpSelectFeed=GetXmlHttpObject();
  if (xmlHttpSelectFeed != null) {
    var url="/ajax_select_feed";
    xmlHttpSelectFeed.open("GET",url,true);
    xmlHttpSelectFeed.onreadystatechange=function(){selectFeedStatus()};
    xmlHttpSelectFeed.send(null);
  }
}

function showReadUnread(qstr,readUnread) {
  // Loads a new page and updates the menu entry
  // qstr contains the information needed to load the new items
  // readUnread tells us whether unread or read and unread items are to be displayed

  // Clear preloadPage so an old value doesn't get used again
  $("#items_and_nav").data("preload","");

  // Add the appropriate readUnread request to the query string
  qstrNew=qstr + "&read_unread=" + readUnread;

  // Show the new page
  navigation(qstrNew,0);
}

function changeView(qstr,feedView) {
  // Loads a new page and updates the menu entry
  // qstr contains the information needed to load the new items
  // feedView tells us whether the Title or Combined View needs to be displayed

  // Clear preloadPage so an old value doesn't get used again
  $("#items_and_nav").data("preload","");

  // Add the appropriate feed_view request to the query string
  qstrNew=qstr + "&feed_view=" + feedView;

  // Show the new page
  navigation(qstrNew,0);
}

function preloadImages() {
  // Preload images needed by the UI to reduce lag when buttons are clicked

  if (document.images) {
    preload_image1 = new Image(32,32);
    preload_image1.src="/themes/feedsanywhere/star-interesting.png";
    preload_image2 = new Image(32,32);
    preload_image2.src="/themes/feedsanywhere/star-neutral.png";
    preload_image3 = new Image(32,32);
    preload_image3.src="/themes/feedsanywhere/star-not-interesting.png";
    preload_image4 = new Image(32,32);
    preload_image4.src="/themes/feedsanywhere/starred-interesting.png";
    preload_image5 = new Image(32,32);
    preload_image5.src="/themes/feedsanywhere/starred-not-interesting.png";
    preload_image6 = new Image(14,14);
    preload_image6.src="/themes/feedsanywhere/email.png";
    preload_image7 = new Image(14,14);
    preload_image7.src="/themes/feedsanywhere/discover.png";
    preload_image8 = new Image(14,14);
    preload_image8.src="/themes/feedsanywhere/undiscover.png";
    preload_image9 = new Image(29,29);
    preload_image9.src="/themes/feedsanywhere/interesting-29x29.png";
    preload_image10 = new Image(29,29);
    preload_image10.src="/themes/feedsanywhere/not_interesting-29x29.png";
    preload_image11 = new Image(29,29);
    preload_image11.src="/themes/feedsanywhere/interesting-green-29x29.png";
    preload_image12 = new Image(29,29);
    preload_image12.src="/themes/feedsanywhere/not_interesting-red-29x29.png";
    preload_image13 = new Image(16,16);
    preload_image13.src="/loading.gif";
    preload_image14 = new Image(22,22);
    preload_image14.src="/themes/feedsanywhere/configure-blue.png";
  }
}

function sortDate(qstr) {
  // Change the item sorting to by date, newest first

  // Add the appropriate sort request to the query string
  qstrNew=qstr + "&sort_type=0";

  // Clear preloadPage so an old value doesn't get used again
  $("#items_and_nav").data("preload","");

  // Show the new page
  navigation(qstrNew,0);

  // Update the settings menu to reflect the new sorting
  $("#score-check").hide();
  $("#oldest-check").hide();
  $("#date-check").show();
}

function sortOldest(qstr) {
  // Change the item sorting to by date, oldest first

  // Add the appropriate sort request to the query string
  qstrNew=qstr + "&sort_type=2";

  // Clear preloadPage so an old value doesn't get used again
  $("#items_and_nav").data("preload","");

  // Show the new page
  navigation(qstrNew,0);

  // Update the settings menu to reflect the new sorting
  $("#score-check").hide();
  $("#date-check").hide();
  $("#oldest-check").show();
}

function sortScore(qstr) {
  // Change the item sorting to by score

  // Add the appropriate sort request to the query string
  qstrNew=qstr + "&sort_type=1";

  // Clear preloadPage so an old value doesn't get used again
  $("#items_and_nav").data("preload","");

  // Show the new page
  navigation(qstrNew,0);

  // Update the settings menu to reflect the new sorting
  $("#date-check").hide();
  $("#oldest-check").hide();
  $("#score-check").show();
}

function sortRelevance(qstr,relevance) {
  // Change whether searches are sorted by relevance or not
  // relevance = 0 means relevance is being used
  // relevance = 1 means either date or score is being used

  // Add the appropriate sort request to the query string
  qstrNew=qstr + "&sort_relevance=" + relevance;

  // Clear preloadPage so an old value doesn't get used again
  $("#items_and_nav").data("preload","");

  // Show the new page
  navigation(qstrNew,0);

  // Update the settings menu to reflect the new sorting
  if (relevance == 1) {
    $("#relevance-check").hide();
    $("#relevance-check").data("check",0);
    $("#sort-date").removeClass("settings-gray");
    $("#sort-oldest").removeClass("settings-gray");
    $("#sort-score").removeClass("settings-gray");
  } else {
    $("#relevance-check").show();
    $("#relevance-check").data("check",1);
    $("#sort-date").addClass("settings-gray");
    $("#sort-oldest").addClass("settings-gray");
    $("#sort-score").addClass("settings-gray");
  }
}

function enablePreview(simple,user_id,qstr) {
  // Toggle the setting that determines whether previews are shown
  // simple determines whether the simple view is being used, 0 (disabled) is the default
  // user_id == 0 if the visitor is not logged in
  // qstr is the query string to be used to reload the page if the visitor is not logged in

  // Do not use the preload page because it won't show the correct preview anymore
  $("#items_and_nav").data("preload","");

  // Determine the current setting
  if ($("#preview-check").is(":visible")) {
    // Turn off previews
    $("#preview-check").hide();

    if (user_id == 0) {
      navigation(qstr + "&preview=0");
    } else {
      preview(0,simple);
      url="/ajax_preview?preview=0";

      // Update the setting on the server
      $.get(url);
    }
  } else {
    // Turn on previews
    $("#preview-check").show();

    if (user_id == 0) {
      navigation(qstr + "&preview=1");
    } else {
      preview(1,simple);
      url="/ajax_preview?preview=1";

      // Update the setting on the server
      $.get(url);
    }
  }
}

function searchMenuAdjustments(searchText) {
  // Check to see if sorting entries in the menu need to be adjusted
  // searchText contains the string being search for

  if (searchText != "") {
    // Show the Sort by Relevance menu entry and gray out the others if relevance is being used
    $("#sort-relevance").show();

    if ($("#relevance-check").data("check") == 1) {
      $("#sort-date").addClass("settings-gray");
      $("#sort-oldest").addClass("settings-gray");
      $("#sort-score").addClass("settings-gray");
    }
  } else {
    // This is not a search so relevance should be hidden and date and score restored
    $("#sort-relevance").hide();
    $("#sort-date").removeClass("settings-gray");
    $("#sort-oldest").removeClass("settings-gray");
    $("#sort-score").removeClass("settings-gray");
  }
}

function settingsMenu(qstr,simple,user_id) {
  // Contains the actions needed to enable the settings menu so they aren't downloaded with every page
  // qstr is the query string that is needed to load the new page
  // simple determines whether the simple view is being used, 0 (disabled) is the default
  // Passes the user_id which == 0 if the visitor is not logged in

  // Determine the action when the user selects sort by date (newest)
  $("#sort-date").click(function() {
    if ($("#date-check").is(":visible")) {
      // Do nothing
    } else {
      sortDate(qstr);
      $("#subnav").slideUp("fast");
    }
    return false;
  });

  // Determine the action when the user selects sort by date (oldest)
  $("#sort-oldest").click(function() {
    if ($("#oldest-check").is(":visible")) {
      // Do nothing
    } else {
      sortOldest(qstr);
      $("#subnav").slideUp("fast");
    }
    return false;
  });

  // Determine the action when the user selects sort by score
  $("#sort-score").click(function() {
    if ($("#score-check").is(":visible")) {
      // Do nothing
    } else {
      sortScore(qstr);
      $("#subnav").slideUp("fast");
    }
    return false;
  });

  // Determine the action when the user selects sort by relevance
  $("#sort-relevance").click(function() {
    if ($("#relevance-check").is(":visible")) {
      sortRelevance(qstr,1);
    } else {
      sortRelevance(qstr,0);
    }
    $("#subnav").slideUp("fast");
    return false;
  });

  // Determine the action when the user selects show title view
  $("#show-title").click(function() {
    if ($("#title-check").is(":visible")) {
      // Do nothing
    } else {
      $("#combined-check").hide();
      $("#title-check").show();
      $("#simple-view").removeClass("settings-gray");
      $("#enable-preview").removeClass("settings-gray");
      $("#enable-preview").click(function() {
        enablePreview(simple,user_id,qstr);
        $("#subnav").slideUp("fast");
        return false;
      });
      changeView(qstr,0);
      $("#subnav").slideUp("fast");
    }
    return false;
  });

  // Determine the action when the user selects show combined view
  $("#show-combined").click(function() {
    if ($("#combined-check").is(":visible")) {
      // Do nothing
    } else {
      $("#title-check").hide();
      $("#combined-check").show();
      $("#simple-view").addClass("settings-gray");
      $("#enable-preview").addClass("settings-gray");
      $("#enable-preview").unbind('click');
      changeView(qstr,1);
      $("#subnav").slideUp("fast");
    }
    return false;
  });

  // Determine the action when the user selects use simple view
  $("#simple-view").click(function() {
    if ($("#simple-check").is(":visible")) {
      $("#simple-check").hide();
      changeSimple(qstr,0);
    } else {
      $("#simple-check").show();
      changeSimple(qstr,1);
    }
    $("#subnav").slideUp("fast");
    return false;
  });

  // Determine the action when the user selects show unread only
  $("#show-unread").click(function() {
    if ($("#unread-check").is(":visible")) {
      // Do nothing
    } else {
      $("#read-unread-check").hide();
      $("#unread-check").show();
      showReadUnread(qstr,0);
      $("#subnav").slideUp("fast");
    }
    return false;
  });

  // Determine the action when the user selects show read and unread
  $("#show-read-unread").click(function() {
    if ($("#read-unread-check").is(":visible")) {
      // Do nothing
    } else {
      $("#unread-check").hide();
      $("#read-unread-check").show();
      showReadUnread(qstr,1);
      $("#subnav").slideUp("fast");
    }
    return false;
  });

  // Highlight menu entries when the mouse hovers over them
  $(".settings-links").hover(function() {
    // Make sure the menu item has not been grayed out
    if ($(this).is(".settings-gray")) {
      // Do nothing
    } else {
      $(this).addClass("settings-highlight");
    }
  }, function() {
    $(this).removeClass("settings-highlight");
  });

  // Make the menu appear when the icon is clicked and position it appropriately
  $("#feed-settings").click(function() {
    if ($(this).parent().find("ul.subnav").is(":visible")) {
      // Hide the menu if the trigger is clicked when the menu is already displayed
      $("#subnav").slideUp("fast");
    } else {
      // Find the top of the heading
      headingTop=document.getElementById("feed-heading").offsetTop;

      // Find the height of the heading
      headingHeight=document.getElementById("feed-heading").offsetHeight;

      // Find the top of the menu icon
      menuTop=document.getElementById("feed-settings").offsetTop;

      // Calculate the location of the bottom of the heading
      headingBottom=headingTop + headingHeight;

      // subnav should be below headingBottom
      subnavTop=headingBottom - menuTop - 8;

      // Calculate the horizontal position of the menu
      sbw=$(window).width();  // Set sbw to the window's width
      subnavWidth=$("#subnav").width();

      // Account for sidebar adds if they are shown
      if ($("#ad_sidebar").is(":visible")) {
        subnavLeft=sbw - subnavWidth - 16 - $("#ad_sidebar").width();
      } else {
        subnavLeft=sbw - subnavWidth - 16;
      }

      $("#subnav").css("left",subnavLeft);

      // Opera needs positioning adjusted
      user_agent=navigator.userAgent;
      if (user_agent.match("Opera")) {
        // Check the positioning to make sure the menu appears in the right area
        // pageYOffset tells how much the page has been scrolled from its initial position
        windowPosition=window.pageYOffset;

        // Calculate the position the menu should be displayed
        subnavTop+=windowPosition;
        subnavTop+="px";

        // Set the top position for the menu to appear
        $("#subnav").css("top",subnavTop);
      } else {
        // Set the top position for the menu to appear
        subnavTop+="px";
        $("#subnav").css("top",subnavTop);
      }

      //Following events are applied to the subnav itself (moving subnav up and down)
      $("#subnav").slideDown("fast").show(); //Drop down the subnav on click

      $("#subnav").hover(function() {
      }, function(){
        $("#subnav").slideUp("fast"); //When the mouse hovers out of the subnav, move it back up
      });
    }
  });

  // Change the icon when the mouse is over it to indicate interactivity
  $("#feed-settings").hover(function() {
    $("#feed-settings").attr("src","/themes/feedsanywhere/configure-blue.png");
  }, function(){
    $("#feed-settings").attr("src","/themes/feedsanywhere/configure-black.png");
  });

  // Move the menu icon to vertically center it in the heading
  menuIconAlign();
}

function menuIconAlign() {
  // Moves the menu icon to vertically center it in the heading

  // Find the height of the search box
  searchHeight=document.getElementById("search-box").offsetHeight;

  // Calculate how much to shift the top of the icon
  shiftIcon=(searchHeight - 22) / 2 - 2;

  // Move the icon
  $("#feed-settings").css("margin-top",shiftIcon);
}

function adjustForFontSize() {
  // Repositions the gotowebsite icon based on the browser's fontsize

  // Get the current font size and return only the number
  fontSize=parseFloat($("html").css("font-size"));

  // If the font is more than 2pt larger or smaller than 14pt the positioning will need to be adjusted
  if (fontSize < 13 || fontSize > 15) {
    // The icon needs to be shifted
    shiftMarginTop=fontSize - 14;
    $(".gotowebsite").css("margin-top",shiftMarginTop);

    shiftMarginSimple=fontSize - 14 - 2;
    $(".gotowebsite-simple").css("margin-top",shiftMarginSimple);
  } else {
    $(".gotowebsite").css("margin-top",0);
    $(".gotowebsite-simple").css("margin-top","-2px");
  }
}

function changeSimple(qstr,simple) {
  // Loads a new page and changes the simple view setting
  // qstr contains the information needed to load the new items
  // simple tells us whether simple view is being enabled (1) or disabled (0)

  // Clear preloadPage so an old value doesn't get used again
  $("#items_and_nav").data("preload","");

  // Add the appropriate feed_view request to the query string
  qstrNew=qstr + "&simple_view=" + simple;

  // Show the new page
  navigation(qstrNew,0);
}

function editFeedMenu() {
  // Set up the actions needed when activating the Edit Feed Menu on the Select a Feed page

  // Highlight menu entries when the mouse hovers over them
  $(".settings-links").hover(function() {
    // Make sure the menu item has not been grayed out
    if ($(this).is(".settings-gray")) {
      // Do nothing
    } else {
      $(this).addClass("settings-highlight");
    }
  }, function() {
    $(this).removeClass("settings-highlight");
  });

  // Hide the menu when moving the mouse away from it
  $(".edit-feed").hover(function() {
    // Do nothing
  }, function() {
    $(this).slideUp("fast");

    // Find the item's feed_id so the icon can be switched back to a plus
    fid=this.id.replace("feed-","").replace("-menu","");
    $("#feed-" + fid + "-button").attr("src","/themes/feedsanywhere/plus.png");
  });
}

function changeSubscription(fid) {
  // Subscribe or unsubscribe to a feed depending upon which text was clicked
  // fid is the feed_id

  // Make sure a valid feed_id is used
  if (fid > 0) {
    // Check to see which link was clicked
    subscribeAction=$("#feed-" + fid + "-unsub").html();
    if (subscribeAction == "Subscribe") {
      // The user wants to subscribe to the feed
      $("#feed-" + fid + "-unsub").html("Unsubscribe");

      // Contact the server and subscribe to the feed
      url="/ajax_add_feed?fid=" + fid;
    } else {
      // The user wants to unsubscribe to the feed
      $("#feed-" + fid + "-unsub").html("Subscribe");

      // Contact the server and unsubscribe to the feed
      url="/ajax_delete_feed?fid=" + fid;
    }
    $.get(url);
  }
}

function changeCategory(fid) {
  // Display a dialog box with the possible categories and checks for the ones the feed is a part of
  // fid is the feed_id

  // Make sure a valid feed_id is used
  if (fid > 0) {
    // Close the menu
    $("#feed-" + fid + "-menu").slideUp("fast");
    $("#feed-" + fid + "-button").attr("src","/themes/feedsanywhere/plus.png");

    // Set the input box's font size to be the same as the rest of the page
    fontSize=$("html").css("font-size");
    $(".settings-options").css("font-size", fontSize);

    // Save the feed_id to be used if the user selects Save
    $("#category-form").data("fid",fid);

    // Make sure an existing category exists, otherwise the Create a New Category dialog needs to be loaded
    numCategories=$("#category-form").data("num-categories");

    if (numCategories > 0) {
      // Open the dialog to edit the name
      $("#category-form").dialog('open');

      // Calculate the optimal position of the left side of the input box
  //    dPosition=$("#cat-menu").position("left");
  //    lPosition=14 - dPosition.left;
  //    $("#cat-menu").css("left", lPosition);

      // Calculate the correct width of the dialog box to account for differences between browsers and settings
      dWidth=$("#cat-menu").width() + 28;

      // Make sure the width isn't bigger than the screen
      sbw=$(window).width();

      if (dWidth > sbw || sbw <= 320) {
        // Match the dialog width to the screen size
        dWidth=sbw - 6;

        // Recalculate the width if the input box
        inputWidth=dWidth - 40;
        $("#cat-menu").width(inputWidth);

        $("#category-form").dialog('option', 'position', 'left');
      } else if (dWidth < 314) {
        // Make sure dWidth has a minimum width
        dWidth=314;

        // Recalculate the width if the input box
        inputWidth=dWidth - 28;
        $("#cat-menu").width(inputWidth);
      }

      // Set the calculated dialog width
      $("#category-form").dialog('option', 'width', dWidth);

      // Determine which checks need to be displayed

      // Get the list of categories this feed is a part of
      if ($("#category-form").data("categories-" + fid)) {
        catList=$("#category-form").data("categories-" + fid);

        if (catList != "" && catList != "undefined") {
          // Check to see if the feed belongs to more than one category
          if (catList >= 0) {
            // Only one category was found
            $("#cat-" + catList + "-check").show();
          } else if (catList.match(",").toString()) {
            // Create an array of the categories. They are numbers corresponding to all feeds in alphabetical order.
            catList=catList.split(",");

            // Display the check boxes for the categories that were found
            for (catNum in catList) {
              $("#cat-" + catNum + "-check").show();
            }
          }
        }
      } else {
        catList="";
      }
    } else {
      // No categories have been created yet so the Create a New Category dialog needs to be shown
      newCategory();
    }
  }
}

function categoryToggle(cid,catNum) {
  // Updates the database and Google Reader (if appropriate) with the new category
  // The check box is toggled to indicate an action was taked
  // cid is the name of the category
  // catNum is the number of the category in alphabetical order that is used to identify the list item

  // Get the feed_id that is being added to the category
  fid=$("#category-form").data("fid");

  // Make sure a valid feed_id was found
  if (fid > 0) {
    // Determine whether the feed belongs to the category
    if ($("#cat-" + catNum + "-check").is(":visible")) {
      catAction="remove";
    } else {
      catAction="add";
    }

    // Change the visibility of the check box
    if (catAction == "add") {
      $("#cat-" + catNum + "-check").show();

      // Update the list that shows which categories the feed belongs to
      feedCategoryList=$("#category-form").data("categories-" + fid);
      if (feedCategoryList == "") {
        feedCategoryList=catNum + '';
      } else {
        feedCategoryList=feedCategoryList + "," + catNum;
      }

      $("#category-form").data("categories-" + fid,feedCategoryList);
    } else {
      $("#cat-" + catNum + "-check").hide();

      // Update the list that shows which categories the feed belongs to
      feedCategoryList=$("#category-form").data("categories-" + fid);

      if (feedCategoryList != "" && feedCategoryList != "undefined") {
        if (feedCategoryList >= 0) {
          feedCategoryList="";
        } else if (feedCategoryList.match(",").toString()) {
          catNum1="," + catNum;
          feedCategoryList=feedCategoryList.replace(catNum1,"");
          catNum2=catNum + ",";
          feedCategoryList=feedCategoryList.replace(catNum2,"");
        }

        $("#category-form").data("categories-" + fid,feedCategoryList);
      }
    }

    // Upload the category change to FeedsAnywhere and Google Reader (if syncing is enabled)
    $.post("/ajax_toggle_category", { fid: fid, cid: cid, action: catAction });
  }
}

function newCategory() {
  // Displays a dialog box to enter a new category

  // Get the feed_id that is being added to the category
  fid=$("#category-form").data("fid");

  // Close the previous dialog box
  $("#category-form").dialog('close');

  // Hide all checks so the appropriate ones will be displayed next time
  $(".category-check").hide();

  // Clear the input box
  $("#category-name").attr("value","");

  // Open the dialog to edit the name
  $("#category-new-form").dialog('open');

  // Calculate the correct width of the dialog box to account for differences between browsers and settings
  dWidth=$("#category-name").width() + 28;

  // Make sure the width isn't bigger than the screen
  sbw=$(window).width();
  if (dWidth > sbw || sbw <= 320) {
    // Match the dialog width to the screen size
    dWidth=sbw - 6;

    // Recalculate the width if the input box
    inputWidth=dWidth - 40;
    $("#category-name").width(inputWidth);

    $("#category-new-form").dialog('option', 'position', 'left');
  }

  // Set the calculated dialog width
  $("#category-new-form").dialog('option', 'width', dWidth);
}

function categorySave() {
  // Updates the database and Google Reader (if appropriate) with the new category

  // Get the feed_id that is being added to the category
  fid=$("#category-form").data("fid");

  // Make sure a valid feed_id was found
  if (fid > 0) {
    // Get the name for the category
    cid=$("#category-name").attr("value");

    if (cid != "") {
      // This category is new and needs to be added
      catAction="add";

      // Upload the new name to FeedsAnywhere and Google Reader (if syncing is enabled)
      $.post("/ajax_toggle_category", { fid: fid, cid: cid, action: catAction });

      // Determine what c should be for the new category and increment the number of categories
      numCat=$("#category-form").data("num-categories");
      c="c" + numCat;
      newNumCat=parseInt(numCat) + 1;
      $("#category-form").data("num-categories",newNumCat);

      // Display the category on the page
      allCategories=$("#display-categories").html();
      allCategories+="  <div id=\"feed-" + c + "-list\" class=\"feed-list\">\n    <img id=\"feed-" + c + "-button\" class=\"show_feed_menu\" onclick=\"showFeedMenu('" + c + "'); return false;\" src=\"/themes/feedsanywhere/plus.png\" />\n    <a id=\"feed-" + c + "\" href=\"/category/" + cid + "\" class=\"bold\">" + cid + "</a>\n  </div>\n  <ul id=\"feed-" + c + "-menu\" class=\"edit-feed\">\n    <li id=\"feed-" + c + "-delete\" class=\"settings-links\" onclick=\"categoryDelete('" + cid + "','" + c + "')\">\n      <div>Delete</div>\n    </li>\n    <li id=\"feed-" + c + "-rename\" class=\"settings-links\" onclick=\"categoryRename('" + cid + "','" + c + "')\">\n      <div>Rename</div>\n    </li>\n  </ul>\n";
      $("#display-categories").html(allCategories);

      // Make sure the image is displayed
      $("#feed-" + c + "-button").show();

      // Add the new category to cat-menu
      catMenu=$("#cat-menu").html();
      catMenu+="      <li id=\"cat-" + c + "\" class=\"settings-links\" onclick=\"categoryToggle('" + cid + "'," + numCat + ")\">\n        <span id=\"cat-" + numCat + "-check\" class=\"category-check\">&#x2713;</span>\n        <div class=\"settings-options\">" + cid + "</div>\n      </li>\n";
      $("#cat-menu").html(catMenu);

      // Update the list for the feed that shows what categories it belongs to
      feedCategoryList=$("#category-form").data("categories-" + fid);

      // Convert to a string to avoid errors
      feedCategoryList=String(feedCategoryList);

      if (feedCategoryList == "" || feedCategoryList == "undefined") {
        feedCategoryList=numCat + '';
      } else {
        feedCategoryList=feedCategoryList + "," + numCat;
      }

      $("#category-form").data("categories-" + fid,feedCategoryList);

      // Reset the classes to support the correct hovering changes for the category menus
      editFeedMenu();
    }
  }

  // Clear the feed_id until the next time Add to a Category is chosen
  $("#category-form").data("fid","");

  $("#category-new-form").dialog('close');
}

function rename(fid,feedName) {
  // Displays an edit box to allow renaming the feed
  // fid is the feed_id
  // feedName is the current name of the feed to provide as a default

  // Make sure a valid feed_id is used
  if (fid > 0) {
    // Close the menu
    $("#feed-" + fid + "-menu").slideUp("fast");
    $("#feed-" + fid + "-button").attr("src","/themes/feedsanywhere/plus.png");

    // Set the input box's font size to be the same as the rest of the page
    fontSize=$("html").css("font-size");
    $("#rename-name").css("font-size", fontSize);

    // Open the dialog to edit the name
    $("#rename-form").dialog('open');

    // Calculate the optimal position of the left side of the input box
//    dPosition=$("#rename-name").position("left");
//    lPosition=14 - dPosition.left;
//    $("#rename-name").css("left", lPosition);

    // Calculate the correct width of the dialog box to account for differences between browsers and settings
    dWidth=$("#rename-name").width() + 28;

    // Make sure the width isn't bigger than the screen
    sbw=$(window).width();
    if (dWidth > sbw || sbw <= 320) {
      // Match the dialog width to the screen size
      dWidth=sbw - 6;

      // Recalculate the width if the input box
      inputWidth=dWidth - 40;
      $("#rename-name").width(inputWidth);

      $("#rename-form").dialog('option', 'position', 'left');
    }

    // Set the calculated dialog width
    $("#rename-form").dialog('option', 'width', dWidth);

    // Get the current name and apply it to the text field
    $("#rename-name").attr("value",feedName);

    // Save the feed_id and original feed name to be used if the user selects Save
    $("#rename-form").data("fid",fid);
    $("#rename-form").data("feedName",feedName);
  } else {
    alert("The feed cannot be renamed.");
  }
}

function renameSave() {
  // Updates the database and Google Reader (if appropriate) with the new feed name

  // Get the feed_id that was renamed
  fid=$("#rename-form").data("fid");

  // Make sure a valid feed_id was found
  if (fid > 0) {
    // Get the current name for the feed
    feedName=$("#rename-form").data("feedName");

    // Get the new name for the feed
    newName=$("#rename-name").attr("value");

    // Upload the new name to FeedsAnywhere and Google Reader (if syncing is enabled)
    $.post("/ajax_rename_feed", { fid: fid, title: newName });

    // Change the name in the feed list being displayed

    // Find the original title and determine the unread count
    origTitle=$("#feed-" + fid).html();
    origTitle=origTitle.replace("&gt;",">");
    origTitle=origTitle.replace("&lt;","<");
    unreadCount=origTitle.replace(feedName,"");

    // Update the feed name on the page
    $("#feed-" + fid).html(newName + unreadCount);

    $("#feed-" + fid + "-rename").unbind('click');

    $("#feed-" + fid + "-rename").click(function(){
      rename(fid,newName);
    });
  }

  $("#rename-form").dialog('close');
}

function categoryRename(cid,c) {
  // Displays an edit box to allow renaming the category
  // cid the the name of the existing feed
  // c is the number corresponding to the id displaying the category on the Select a Feed page

  // Make sure a valid feed_id is used
  if (cid != "") {
    // Close the menu
    $("#feed-" + c + "-menu").slideUp("fast");
    $("#feed-" + c + "-button").attr("src","/themes/feedsanywhere/plus.png");

    // Set the input box's font size to be the same as the rest of the page
    fontSize=$("html").css("font-size");
    $("#category-rename-name").css("font-size", fontSize);

    // Open the dialog to edit the name
    $("#category-rename-form").dialog('open');

    // Calculate the correct width of the dialog box to account for differences between browsers and settings
    dWidth=$("#category-rename-name").width() + 28;

    // Make sure the width isn't bigger than the screen
    sbw=$(window).width();
    if (dWidth > sbw || sbw <= 320) {
      // Match the dialog width to the screen size
      dWidth=sbw - 6;

      // Recalculate the width if the input box
      inputWidth=dWidth - 40;
      $("#category-rename-name").width(inputWidth);

      $("#category-rename-form").dialog('option', 'position', 'left');
    }

    // Set the calculated dialog width
    $("#category-rename-form").dialog('option', 'width', dWidth);

    // Get the current name and apply it to the text field
    $("#category-rename-name").attr("value",cid);

    // Save the feed_id and original feed name to be used if the user selects Save
    $("#category-rename-form").data("cid",cid);
    $("#category-rename-form").data("c",c);
  } else {
    alert("The feed cannot be renamed.");
  }
}

function categoryRenameSave() {
  // Updates the database and Google Reader (if appropriate) with the new category name

  // Get the current name of the category that was renamed and it's identifier on the page
  cid=$("#category-rename-form").data("cid");
  c=$("#category-rename-form").data("c");

  // Make sure a valid feed_id was found
  if (cid != "") {
    // Get the new name for the category
    newName=$("#category-rename-name").attr("value");

    // Upload the new name to FeedsAnywhere and Google Reader (if syncing is enabled)
    $.post("/ajax_rename_category", { cid: cid, newName: newName });

    // Find the original title and determine the unread count
    origTitle=$("#feed-" + c).html();
    origTitle=origTitle.replace("&gt;",">");
    origTitle=origTitle.replace("&lt;","<");
    unreadCount=origTitle.replace(cid,"");

    // Update the category name on the page
    $("#feed-" + c).html(newName + unreadCount);

    // Update the rename action
    $("#feed-" + c + "-rename").unbind('click');
    $("#feed-" + c + "-rename").click(function(){
      categoryRename(newName,c);
    });

    // Update the delete action
    $("#feed-" + c + "-delete").unbind('click');
    $("#feed-" + c + "-delete").click(function(){
      categoryDelete(newName,c);
    });

    // Update the link to display the new category
    $("#feed-" + c).attr('href',newName);

    // Change the name in the category list being displayed
    // Get the html from cat-menu and replace the cid with the new name
    catMenu=$("#cat-menu").html();
    catMenu=catMenu.replace(new RegExp(cid,"g"),newName);
    $("#cat-menu").html(catMenu);
  }

  // Close the dialog box
  $("#category-rename-form").dialog('close');
}

function categoryDelete(cid,c) {
  // Deletes the current category after asking the user if that is really what they want to do
  // cid the the name of the existing feed
  // c is the number corresponding to the id displaying the category on the Select a Feed page

  // Make sure a valid category is given
  if (cid != "") {
    // Close the menu
    $("#feed-" + c + "-menu").slideUp("fast");
    $("#feed-" + c + "-button").attr("src","/themes/feedsanywhere/plus.png");

    // Set the input box's font size to be the same as the rest of the page
    fontSize=$("html").css("font-size");
    $("#category-delete-form").css("font-size", fontSize);

    // Open the dialog to edit the name
    $("#category-delete-form").dialog('open');

    // Calculate the correct width of the dialog box to account for differences between browsers and settings
    dWidth=$("#category-delete-form").width() + 28;

    // Make sure the width isn't bigger than the screen
    sbw=$(window).width();
    if (dWidth > sbw || sbw <= 320) {
      // Match the dialog width to the screen size
      dWidth=sbw - 6;

      // Recalculate the width if the input box
      inputWidth=dWidth - 40;
      $("#category-delete-form").width(inputWidth);

      $("#category-delete-form").dialog('option', 'position', 'left');
    }

    // Set the calculated dialog width
    $("#category-delete-form").dialog('option', 'width', dWidth);

    // Save the category name to be used if the user selects Save
    $("#category-delete-form").data("cid",cid);
    $("#category-delete-form").data("c",c);
  } else {
    alert("The feed cannot be renamed.");
  }
}

function categoryDeleteYes() {
  // Updates the database and Google Reader (if appropriate) to remove the category

  // Get the current name of the category being deleted and it's identifier on the page
  cid=$("#category-delete-form").data("cid");
  c=$("#category-delete-form").data("c");

  // Make sure a valid category was found
  if (cid != "") {
    // Upload the new name to FeedsAnywhere and Google Reader (if syncing is enabled)
    $.post("/ajax_delete_category", { cid: cid });

    // Remove the category from the page
    $("#feed-" + c + "-list").hide();
    $("#feed-" + c + "-list").html("");
    $("#feed-" + c + "-menu").hide();
    $("#feed-" + c + "-menu").html("");

    // Get rid of the rename action
    $("#feed-" + c + "-rename").unbind('click');

    // Get rid of the delete action
    $("#feed-" + c + "-delete").unbind('click');

    // Remove the deleted category from cat-menu
    $("#cat-" + c).hide();
    $("#cat-" + c).html("");
  }

  // Close the dialog box
  $("#category-delete-form").dialog('close');
}

function editLink(fid) {
  // Displays an edit box to allow changing the feed's URL
  // fid is the feed_id

  // Make sure a valid feed_id is used
  if (fid > 0) {
    // Close the menu
    $("#feed-" + fid + "-menu").slideUp("fast");
    $("#feed-" + fid + "-button").attr("src","/themes/feedsanywhere/plus.png");

    // Clear the text box
    $("#edit-url-name").attr("value","");

    // Set the input box's font size to be the same as the rest of the page
    fontSize=$("html").css("font-size");
    $("#edit-url-name").css("font-size", fontSize);

    // Open the dialog to edit the name
    $("#edit-url-form").dialog('open');

    // Calculate the optimal position of the left side of the input box
    dPosition=$("#edit-url-name").position("left");
    lPosition=14 - dPosition.left;
    $("#edit-url-name").css("left", lPosition);

    // Calculate the correct width of the dialog box to account for differences between browsers and settings
    dWidth=$("#edit-url-name").width() + 28;

    // Make sure the width isn't bigger than the screen
    sbw=$(window).width();
    if (dWidth > sbw || sbw <= 320) {
      // Match the dialog width to the screen size
      dWidth=sbw - 6;

      // Recalculate the width if the input box
      inputWidth=dWidth - 40;
      $("#edit-url-name").width(inputWidth);

      $("#edit-url-form").dialog('option', 'position', 'left');
    }

    // Set the calculated dialog width
    $("#edit-url-form").dialog('option', 'width', dWidth);

    // Save the feed_id to be used if the user selects Save
    $("#edit-url-form").data("fid",fid);
  } else {
    alert("The feed's link cannot be changed.");
  }
}

function editLinkSave() {
  // Updates the database with the new link and creates a duplicate feed with the old one

  // Get the feed_id for the link that is changing
  fid=$("#edit-url-form").data("fid");

  // Make sure a valid feed_id was found
  if (fid > 0) {
    // Get the new link for the feed
    newLink=$("#edit-url-name").attr("value");

    // Upload the new link to FeedsAnywhere
    $.post("/ajax_edit_link", { fid: fid, newLink: newLink });

    $("#feed-" + fid).attr("title",newLink);
  } else {
    alert("An invalid feed was referenced.");
  }

  $("#edit-url-form").dialog('close');

  // Close the menu
  $("#feed-" + fid + "-menu").slideUp("fast");
  $("#feed-" + fid + "-button").attr("src","/themes/feedsanywhere/plus.png");
}

function showFeedMenu(fid) {
  // Display the feed menu to allow managing the feed
  // fid is the feed_id

  id_feed_menu="feed-" + fid + "-menu";

  // Check to see if the menu is being expanded or collapsed
  checkOpen=$("#feed-" + fid + "-button").attr("src");
  if (checkOpen == "/themes/feedsanywhere/minus.png") {
    // Collapse the menu
    $("#feed-" + fid + "-button").attr("src","/themes/feedsanywhere/plus.png");
    $("#feed-" + fid + "-menu").slideUp("fast").hide();
  } else if (document.getElementById(id_feed_menu)) {
    // Expand the menu
    $("#feed-" + fid + "-button").attr("src","/themes/feedsanywhere/minus.png");
    $("#feed-" + fid + "-menu").slideDown("fast").show();

    // Check to make sure the menu doesn't open off the page. Scroll down if it does.
    t=setTimeout(function() {
      // Determine how much the page has been scrolled from the original position
      windowPosition=window.pageYOffset;

      // Get the initial position of the top of the item
      itemOffsetTop=document.getElementById(id_feed_menu).offsetTop;

      // Calculate the current position of the object relative to the top of the window
      // A positive number indicates how much below the top of the page the item is
      // A negative number indicates how much above (off) the page the item is
      itemPosition=itemOffsetTop - windowPosition;

      // Get the height of the item
      itemHeight=document.getElementById(id_feed_menu).offsetHeight;

      // Get the height of the window
      windowHeight=window.innerHeight;

      // Determines the position of the bottom of the item
      // A positive number means it's on screen
      // A negative number means it's off screen
      bottomPosition=windowHeight - itemPosition - itemHeight;

      if (bottomPosition < 10) {
        // The bottom of the window is off the screen

        // Detect the browser and device being used
        user_agent=navigator.userAgent;

        if (user_agent.match("iPhone")) {
          // If this is an iPhone 3 or earlier a different scrolling is needed
          if (user_agent.match("iPhone OS 3") || user_agent.match("iPhone OS 2") || user_agent.match("iPhone OS 1")) {
            bottomPosition=windowHeight - itemOffsetTop - itemHeight;
          }
        }

        // The amount to scroll is determined by how far the item's bottom is below the screen
        window.scrollBy(0,-bottomPosition + 4);
      }
    }, 200);
  }
}

function showCategoryMenu(fid) {
  // Display a list of categories that the user can choose from
  // fid is the feed_id

  id_cat_feed_menu="cat-" + fid + "-menu";

  // Check to see if the category menu is being displayed or hidden
  if ($("#cat-" + fid + "-menu").is(":visible")) {
    // Collapse the menu
    $("#cat-" + fid + "-menu").slideUp("fast").hide();
  } else if (document.getElementById(id_cat_feed_menu)) {
    // Expand the menu
    $("#cat-" + fid + "-menu").slideDown("fast").show();

    // Check to make sure the menu doesn't open off the page. Scroll down if it does.
    t=setTimeout(function() {
      // Determine how much the page has been scrolled from the original position
      windowPosition=window.pageYOffset;

      // Get the initial position of the top of the item
      itemOffsetTop=document.getElementById(id_cat_feed_menu).offsetTop;

      // Calculate the current position of the object relative to the top of the window
      // A positive number indicates how much below the top of the page the item is
      // A negative number indicates how much above (off) the page the item is
      itemPosition=itemOffsetTop - windowPosition;

      // Get the height of the item
      itemHeight=document.getElementById(id_cat_feed_menu).offsetHeight;

      // Get the height of the window
      windowHeight=window.innerHeight;

      // Determines the position of the bottom of the item
      // A positive number means it's on screen
      // A negative number means it's off screen
      bottomPosition=windowHeight - itemPosition - itemHeight;

      if (bottomPosition < 10) {
        // The bottom of the window is off the screen

        // Detect the browser and device being used
        user_agent=navigator.userAgent;

        if (user_agent.match("iPhone")) {
          // If this is an iPhone 3 or earlier a different scrolling is needed
          if (user_agent.match("iPhone OS 3") || user_agent.match("iPhone OS 2") || user_agent.match("iPhone OS 1")) {
            bottomPosition=windowHeight - itemOffsetTop - itemHeight;
          }
        }

        // The amount to scroll is determined by how far the item's bottom is below the screen
        window.scrollBy(0,-bottomPosition + 4);
      }
    }, 200);
  }
}

function showCategoryList() {
  // Display the list of categories in the menu to choose from

  // Check to see if the menu is being expanded or collapsed
  if ($("#feed-category-list").is(":visible")) {
    // Collapse the menu
    $("#feed-category-list").slideUp("fast").hide();
  } else if (document.getElementById("feed-category-list")) {
    // Expand the menu
    $("#feed-category-list").slideDown("fast").show();

    // Check to make sure the menu doesn't open off the page. Scroll down if it does.
    t=setTimeout(function() {
      // Determine how much the page has been scrolled from the original position
      windowPosition=window.pageYOffset;

      // Get the initial position of the top of the item
      itemOffsetTop=document.getElementById("feed-category-list").offsetTop;

      // Calculate the current position of the object relative to the top of the window
      // A positive number indicates how much below the top of the page the item is
      // A negative number indicates how much above (off) the page the item is
      itemPosition=itemOffsetTop - windowPosition;

      // Get the height of the item
      itemHeight=document.getElementById("feed-category-list").offsetHeight;

      // Get the height of the window
      windowHeight=window.innerHeight;

      // Determines the position of the bottom of the item
      // A positive number means it's on screen
      // A negative number means it's off screen
      bottomPosition=windowHeight - itemPosition - itemHeight;

      if (bottomPosition < 10) {
        // The bottom of the window is off the screen

        // Detect the browser and device being used
        user_agent=navigator.userAgent;

        if (user_agent.match("iPhone")) {
          // If this is an iPhone 3 or earlier a different scrolling is needed
          if (user_agent.match("iPhone OS 3") || user_agent.match("iPhone OS 2") || user_agent.match("iPhone OS 1")) {
            bottomPosition=windowHeight - itemOffsetTop - itemHeight;
          }
        }

        // The amount to scroll is determined by how far the item's bottom is below the screen
        window.scrollBy(0,-bottomPosition + 4);
      }
    }, 200);
  }
}

function goToCategory(cid) {
  // Switch to the page for the category that was passed
  // cid is the category

  var url="/category/" + cid;
  document.location.href=url;
}

function manageSubscriptions() {
  // Displays extra elements on the Select a Feed page to facilitate renaming feeds, unsubscribing, and import/export OPML.

  // The second line needs to be indented if there is a word wrap
  $(".feed-list").css("padding-left", "34px");
  $(".feed-list").css("text-indent", "-26px");

  $("#import-export").show();
  $(".show_feed_menu").show();
}

function hideGoogleError() {
  // Clear the gr_auth field and hide the authentication error message.

  // Update the user's gr_auth setting so the error will not appear again
  var url="/ajax_clear_auth";
  $.get(url);

  // Hide the error currently shown on the page
  $("#google-login-error").hide();
}
