function Carousel(args) {
  this.selectedIndex = args.selectedIndex || 0;
  this.id = args.id || "carousel";
  
  this.prev = function() {
    if (this.leftButton().hasClass('disabled')) return;
    this.selectedIndex--;
    this.animate();
  }
  
  this.next = function() {
    if (this.rightButton().hasClass('disabled')) return;
    this.selectedIndex++;
    this.animate();
  }
  
  this.animate = function(callback) {
    var cur = this.currentItem();
    var left = $(this.id).width() / 2 - 320;
    this.items().removeClass('selected');
    $('#contentFlowCaption').animate({opacity:0}, 50);
    cur.addClass('selected');
    cur.animate({left:left,top:$(this.id).height() / 2 - 281/2});
    cur.find('img').animate({width:500,height:281,opacity:1}, function() {
      $('#contentFlowCaption').text(cur.find('.caption').text()).animate({opacity:1}, 100);
      Cufon.replace('#contentFlowCaption', {});
      if (callback) callback();
    });
    cur.prev().animate({left:left - 210,top:$(this.id).height() / 2 - 112/2});
    cur.prevUntil().find('img').animate({width:200,height:112,opacity:0.25});
    cur.nextUntil().find('img').animate({width:200,height:112,opacity:0.25});
    cur.next().animate({left:left + 510,top:$(this.id).height() / 2 - 112/2});
    cur.prev().prevUntil().animate({left:-500});
    cur.next().nextUntil().animate({left:1100});
    this.updateButtonStatus();
  }
  
  this.updateButtonStatus = function() {
    var count = this.items().length;
    if (this.selectedIndex == 0) this.leftButton().addClass('disabled');
    else this.leftButton().removeClass('disabled');
    if (this.selectedIndex == count - 1) this.rightButton().addClass('disabled');
    else this.rightButton().removeClass('disabled');
  }
  
  this.setup = function() {
    var instance = this;
    $(this.id + ' .left.button').unbind('click').click(function() { instance.prev(); });
    $(this.id + ' .right.button').unbind('click').click(function() { instance.next(); });
    var i = 180;
    this.items().each(function() {
      $(this).css('left', i + 'px');
      if (this.id == instance.currentItem()[0].id) {
        $(this).find('img').css({width: '500px', height: '281px'});
      }
      else {
        $(this).find('img').css({width: '200px', height: '112px'});
      }
      $(this).css('top', ($(instance.id).height() / 2 - 281/2) + 'px');
      i += $(this).width() + 20;
    });
    $('#contentFlow a').each(function() {
      var link = this;
      var title = $(this).parents('.item').children('.caption').text();
      Shadowbox.setup(this, {
        title:title, autoplayMovies:true, width:720, height:405,
        onOpen: function() { return instance.itemClicked(link); }
      });
    })
    
    this.animate(function() {
      if (args.immediatePopup) instance.currentItem().find('a').click();
    });
  }

  this.itemClicked = function(link) {
    fixShadowbox();
    if (this.currentItem().find('a')[0] != link) return false;
    var credits = this.currentItem().find('.credits');
    var cat = $('#catNav ul li:visible').text();
    var title = this.currentItem().find('.caption').text();
    if ($('#sb-credits').length == 0) $('#sb-info').after('<div id="sb-credits" />');
    window.location.hash = escape(cat + '/' + title);
    $('#sb-credits').html(
      "<div class='share-post'>" +
		    "<a class='twitter'  href='http://twitter.com/home/?status=Check+out+this+website+" + escape(window.location.href) + "'>Twitter</a>" +
        "<fb:like layout='button_count' href='" + window.location.href + "' width='55'></fb:like>" +
		  "</div>");
    var og = {title:title, type:"movie", image:this.currentItem().find('img').attr('src'), url:window.location.href};
    for (var key in og) {
      $('head meta[property^="og:' + key + '"]').remove();
      $('head').append($("<meta property='og:" + key + "' content='" + og[key] + "' />"));
    }
    FB.XFBML.parse(document.getElementById('sb-credits'));
    if (credits.text().length > 0) {
      $('#sb-credits').append("<h3>Credits</h3><p>" + credits.html() + "</p>");
    }
  }
  
  this.items = function() {
    return $(this.id + ' .item');
  }
  
  this.currentItem = function() {
    return $(this.items()[this.selectedIndex]);
  }
  
  this.caption = function() {
    return this.currentItem().children('.caption').text();
  }

  this.content = function() {
    return this.currentItem().children('.content');
  }

  this.leftButton = function() {
    return $(this.id + ' .left.button');
  }
  
  this.rightButton = function() {
    return $(this.id + ' .right.button');
  }
  
  this.setup();
}

function initFonts() {
  Cufon.replace('#menu-navigation a, h2, h3, h4, h5, h6, #catNav li', {});
}

function fixShadowbox() {
  $('#sb-title').before($('#sb-nav'));
}

function initShadowBox() {
  Shadowbox.init({flashVars:{lightcolor:'0xCCCCCC'},onOpen:fixShadowbox});
}

function initNewsImages() {
  $('#content .entry img').each(function() {
    if ($(this).parent().is('a')) { var src = $(this).parent().attr('href'); }
    else { var src = this.src; }
    var img = $("<img src='" + src + "' />").hover(function() { $(this).animate({opacity: 1}, 50); }, 
      function() { $(this).animate({opacity: 0.4}, 'fast'); });
    $('#images').prepend($("<a href='" + this.src + "' />").append(img));
  });
  Shadowbox.setup("#images a", {gallery:"News Images"});
  $(window).resize(function() {
    $('#images').css('left', ($('#content').offset().left + 680) + 'px');
  })
  $('#images').css('left', ($('#content').offset().left + 680) + 'px');
}

function updateCatNavButtons() {
  var vis = $('#catNav ul li:visible');
  if (vis.next().length == 0) $('#catNav .left.button').addClass('disabled');
  else $('#catNav .left.button').removeClass('disabled');
  if (vis.prev().length == 0) $('#catNav .right.button').addClass('disabled');
  else $('#catNav .right.button').removeClass('disabled');
}

function initCarousel() {
  $('#catNav .left.button').click(function() {
    var vis = $('#catNav ul li:visible');
    if (vis.next().length == 0) return;
    loadCarouselCategory(vis.next().text());
  });
  $('#catNav .right.button').click(function() {
    var vis = $('#catNav ul li:visible');
    if (vis.prev().length == 0) return;
    loadCarouselCategory(vis.prev().text());
  });
  
  // remove links
  $('#catNav ul li').each(function() {
    $(this).html($(this).text());
  })
  
  // fix recent movies links
  $("#menu-recent-movies a").click(function() {
    window.location = $(this).attr('href');
    initCarouselFromHash(true);
    return false;
  });
  
  // auto-loading of #cat/title hash
  initCarouselFromHash(true);
}

function initCarouselFromHash(firstTime) {
  var hash = unescape(window.location.hash).substring(1);
  if (hash.length > 0) {
    var args = hash.split('/'), cat = args[0], title = args[1];
    loadCarouselCategory(cat, function() {
      if (!title) return;
      for (var i = 0; i < $('#contentFlow .items .item').length; i++) {
        var otherTitle = $($('#contentFlow .items .item')[i]).find('.caption').text();
        if (title == otherTitle) {
          return new Carousel({id:'#contentFlow',selectedIndex:i,immediatePopup:firstTime});
        }
      }
    });
  }
  else if (firstTime) {
    loadCarouselCategory($('#catNav ul li:first').text());
  }
}

function loadCarouselCategory(cat, callback) {
  $('#catNav ul li').hide().each(function() {
    if ($(this).text() == cat) { $(this).css('display', 'inline'); return; }
  });
  $('#contentFlow').addClass('loading');
  $('#contentFlow .items').html('');
  $.get(window.location.pathname + window.location.search, {category: cat}, function(data) {
    $('#contentFlow .items').html(data);
    $('.post .title h2').text("Films: " + cat);
    Cufon.replace('.post .title h2', {});
    $('#contentFlow').removeClass('loading');
    if (!callback || !callback()) {
      new Carousel({id: '#contentFlow'});
    }
  });
  updateCatNavButtons();
}

function twitterCallback2(twitters) {
  var statusHTML = [];
  for (var i=0; i<twitters.length; i++){
    var username = twitters[i].user.screen_name;
    var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
      return '<a href="'+url+'">'+url+'</a>';
    }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
      return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
    });
    statusHTML.push('<li><span>'+status+'</span> <a style="font-size:85%" href="http://twitter.com/'+username+'/statuses/'+twitters[i].id+'">'+relative_time(twitters[i].created_at)+'</a></li>');
  }
  $('#twitter_update_list').html(statusHTML.join('')).removeClass('loading');
}

function relative_time(time_value) {
  var values = time_value.split(" ");
  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
  var parsed_date = Date.parse(time_value);
  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
  delta = delta + (relative_to.getTimezoneOffset() * 60);

  if (delta < 60) {
    return 'less than a minute ago';
  } else if(delta < 120) {
    return 'about a minute ago';
  } else if(delta < (60*60)) {
    return (parseInt(delta / 60)).toString() + ' minutes ago';
  } else if(delta < (120*60)) {
    return 'about an hour ago';
  } else if(delta < (24*60*60)) {
    return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
  } else if(delta < (48*60*60)) {
    return '1 day ago';
  } else {
    return (parseInt(delta / 86400)).toString() + ' days ago';
  }
}

$(initFonts);
$(initShadowBox);

