/**
  Projects gallery
  Author: Oli Matthews
**/

(function($){
  $.fn.press = function(name) {
    return this.each(function(){
      var i = 0,
          stage = $(this),
          list = $('#press_list', stage),
          item = $('.item', list),
          toggles = $('h2',item),
          children = $('.children',stage).hide().css('visibility','visible'),
          entry_i = 0,
          entry = $('.child',children),
          entry_toggles = $('a',entry),
          next_html =  $('#landing').html();
      stage.append('<div class="slide inactive"/><div class="slide active"/>');
      
      $('.slide.inactive').hide();
      $('.slide.active').show();
      
      toggles.click(function(){
        $(item[i]).removeClass('active');
        new_i = toggles.index(this);
        $('.children',item[i]).fadeOut();
        i = new_i;
        $('.children',item[i]).fadeIn();
        $(item[i]).addClass('active');
      });
      
      entry.click(function(){
        var thisEntry = $(this),
            next_html = $('.info',thisEntry).html();
        entry.removeClass('active');
        thisEntry.addClass('active');
        spin(next_html);
        return false;
      });
      
      
      entry.each(function(){
        var thisEntry = $(this),
            toReveal = $('<div class="info"/>').appendTo(thisEntry),
            image = $('img',thisEntry).remove().clone().appendTo(toReveal),
            text = $('.text',thisEntry).remove().clone().appendTo(toReveal),
            pdf = $('<p class="pdf"/>').html($('h3',thisEntry).html());
        
        if ($('a',pdf).attr('href') != '#') {
          pdf.appendTo(toReveal);
        }
      });
      
      item.each(function(){
        var thisItem = $(this);
      });
      
      spin(next_html);
      
      function spin(html) {
        var active = $('.slide.active'),
            inactive = $('.slide.inactive');
        
        inactive.html(html);
        
        $('img,.text,.pdf',inactive).show();
        
        inactive.fadeIn(function(){$(this).addClass('active').removeClass('inactive')});
        
        active.fadeOut(function(){$(this).removeClass('active').addClass('inactive')});
      }
    });
  };
})(jQuery);


$(document).ready(function(){
  $('#press').press();
});
