$(document).ready(function($) {
  $('.site_section.americas, .site_section.africas, .site_section.indopacifics, .body#home, .body#coffee').
    find('#banner a:not([title=Espressos]):not("#region_espressos")').
    attr('title', function() { return "|" + this.title; }).
    cluetip({
      splitTitle: '|', showTitle: false,
      width: 100, positionBy: 'mouse', tracking: true,
      clickThrough: true,
      cluetipClass: 'banner'});

  $('.snapshots > li > a').
    attr('title', function() {
      return $(this).find('.caption').html() + "|" + this.title; }).
    cluetip({
      arrows: true,
      splitTitle: '|', showTitle: false,
      positionBy: 'fixed', leftOffset: -25,
      clickThrough: true,
      cluetipClass: 'snapshot'});

  $('.extended').prev().append(' ').append(
    $('<p class="read_more"></p>').html(
      $('<a href="#"></a>').text('Read more...').click(function(event) {
        $(this).parents('.text').find('.extended').slideToggle('slow');
        $(this).hide();
        return false;
      })
    )
  );

  var slideshow = $('#slideshow');
  if (slideshow.length) {
    var tag = window.location.toString().match(/([^/]+)\/?$/);
    $.getJSON('http://api.flickr.com/services/feeds/photos_public.gne' +
              '?id=43796163@N08&tags=' + tag +
              '&format=json&jsoncallback=?',
      function(data) {
        $.each(data.items, function(i, item) {
          var caption = $(item.description).not('p:eq(0),p:eq(1)');
          if (caption.text().match(/\S/)) {
            caption = $('<span class="caption"/>').html(caption);
          } else {
            caption = null;
          }

          $('<li></li>').append(
            $('<a/>').attr('href', item.link).
              append($('<img/>').attr('src', item.media.m)).
              append(caption)).
            appendTo(slideshow);
        });

        slideshow.cycle({
          timeout: 8000,
          speed: 2000,
          fx: 'fade'
        });
      }
    );
  }

  $('#promo ul').each(function(index) {
    var promo = $(this);
    setTimeout(function() {
      promo.cycle({
        timeout: 8000,
        speed: 2000,
        fx: 'fade'
      });
    }, 5000 * index);
  });

  $('#news_feed ul').cycle({
    timeout: 15000,
    speed: 3000,
    cleartypeNoBg: true,
    fx: 'scrollLeft'
  });

  // Links don't seem to work in IE unless they're somehow visible,
  // so we give each one a background image and position that blends
  // in with the main banner image. Except on the home page, where
  // the sun tracker already specifies a background position.
  var bannerImage = $('#banner > img').attr('src');
  $('#banner li:visible').filter(
    function() { return !$(this).css('background-position'); }
  ).each(
    function() {
      li = $(this);
      if (!li.css('background-position')) {
        li.css('background-position',
          li.css('left') + ' -' + li.css('top'));
      }
    }
  ).css('background-image', 'url(' + bannerImage + ')');
});
