var ARFSflickrConfig = new Object();
ARFSflickrConfig.apiKey = '9cb97ca9da128611fa49ec94b5581a6a';
ARFSflickrConfig.groupId = '1324883@N25';
ARFSflickrConfig.extras = "owner_name, original_format, o_dims, path_alias, url_m, url_z";
ARFSflickrConfig.max_height = 300;
ARFSflickrConfig.max_width = 400;

$(function(){
  doFlickr();
});

function getPoolPhotoByIndex(photo_index)
{
  // Get the photo using flickr.groups.pools.getPhotos.  By setting the per_page size to one, the photo_index and page_index become the same thing.
  $.getJSON(
    "http://api.flickr.com/services/rest/?method=flickr.groups.pools.getPhotos&format=json&jsoncallback=?",
    {
      group_id: ARFSflickrConfig.groupId,
      api_key: ARFSflickrConfig.apiKey,
      page: photo_index, 
      per_page: 1,
      extras: ARFSflickrConfig.extras
    },
    function(data)
    {
      var anchor = document.createElement("a");
      //$(anchor).attr("href", 'http://www.flickr.com/photos/' + data.photos.photo[0].owner + '/' + data.photos.photo[0].id );
      $(anchor).attr("href", 'http://www.flickr.com/groups/explore_lincoln/');

      var title = limit(data.photos.photo[0].title);
      $(anchor).html(title);
      $("#flickr_in").html(anchor);
      // The 'z' size isn't documented as being supported by flickr.groups.pools.getPhotos but seems to work.  So lets try to get that size and revert to the 'm' size if we can't.
      if ('url_z' in data.photos.photo[0])
      {
        $("#flickr").css("background-image", "url(" + data.photos.photo[0].url_z + ")");
      }
      else
      {
        $("#flickr").css("background-image", "url(" + data.photos.photo[0].url_m + ")");
      }
      hideFlickrLoading();
    }
  );
}
function limit(string)
{
  var max_length = 60;
  if (string.length > max_length)
  {
    string = string.substring(0, max_length) + "...";
  }
  return string;
}
function showFlickrLoading()
{
  var loading = document.createElement("img");
  $(loading).attr("id", "flickrloader");
  $(loading).attr("src", "images/ajax-loader-circle.gif");
  $("#flickr").append(loading);
}
function hideFlickrLoading()
{
  $("#flickrloader").hide();
}
function doFlickr()
{
  showFlickrLoading();
  // Count the total number of images by setting the per_page size to 1, and then by checking the number of pages returned by flickr.groups.pools.getPhotos()
  $.getJSON(
    "http://api.flickr.com/services/rest/?method=flickr.groups.pools.getPhotos&format=json&jsoncallback=?",
    {
      group_id: ARFSflickrConfig.groupId,
      api_key: ARFSflickrConfig.apiKey,
      per_page: 1
    },
    function(data)
    {
      var random_photo_index = parseFloat(Math.floor(Math.random()*(parseFloat(data.photos.total) + 1)));
      getPoolPhotoByIndex(random_photo_index)
    }
  );
}
