/**
 * Strictly Jquery based flickr thickboxing.
 * Will find and destroy (thickbox) any images meeting the following
 * conditions:
 *
 * - Includes "flickr.com" in its src attribute.
 * - Is not contained within a link.
 * - Flickr API request succeeds.
 *
 * @TODO: probably should cache API call results so that it doesn't
 * hit flickr every time the user clicks the thickbox.
 *
 * @TODO: probably should have the API key stored & retrieved via
 * Drupal.settings... but who's gonna release this anyway? : )
 */
$(document).ready(function() {
  $('img[src*=flickr.com]').each(function() {
    var api_key = '';
    var img = $(this);
    if (!img.parents('a').size()) {
      img.css('cursor', 'pointer');
      img.click(function() {
        var t = img.attr('title') || img.attr('alt') || null;
        var a = img.attr('src');
        var g = img.attr('rel') || false;

        // Use string trickery to get the image id
        var start = a.lastIndexOf('/') + 1;
        var end = a.indexOf('_', start);
        var id = a.substring(start, end);

        // Get the base url including server id
        var flickr_url = 'http://farmx.static.flickr.com/';
        var base_url = a.indexOf('/', flickr_url.length);
        base_url = a.substr(0, base_url);

        // API key
        var key = "6a12a7e8c27f63a85bb39ee2b692822c";

        // Super long flickr query string
        var url = 'http://api.flickr.com/services/rest/?format=json&jsoncallback=?&method=flickr.photos.getinfo&api_key='+key+'&photo_id='+id;

        // Make the API request and show the Thickbox
        $.getJSON(url, function(data) {
          if (data.photo.originalsecret) {
            a = base_url + '/' + id + '_' + data.photo.originalsecret + '_o.' + data.photo.originalformat;
          }
          if (data.photo.title._content) {
            t = data.photo.title._content;
          }
          // tb_setBrowserExtra();
          tb_show(t, a, g);
        });
      });
    }
  });
});

