;(function($) {
  var app = new Sammy.Application(function() { with(this) {
    // debug = true;
    
    bind('run', function() {
      var context = this;
      var $image = $('#slideshow img')
      if($('#slideshow').children().length > 1){
        $image.css({ cursor:'pointer' });
        $('ul#pages').after('<div id="nav"></div>');
      }   
      var $slideshow = $('#slideshow');
      if($slideshow.length > 0){
        $('#slideshow') 
          .cycle({ 
            fx:     'fade', 
            speed:  'slow', 
            timeout: 0, 
            pager:  '#nav',
            next:   $image,
            pagerAnchorBuilder: function(idx, slide) { 
              return '<a href="#">' + (idx + 1) + '</a>'; 
            }
        });
      }


      $('#pages li li').biggerlink().hover(function(){
        // alert('this')
        $(this).find('span').css({'color':'#777'});
      },function(){
        $(this).find('span').css({'color':'#aaa'});
      });

      $('a#grid').click(function(){
        if($(this).hasClass('active')){
          $('#container').css({'background-image':'none'});
          $(this).removeClass('active');
        }else{
          $('#container').css({'background-image':'url(/images/kb/grid.png)'});
          $(this).addClass('active');
        }
        return false;
      });
      
      Cufon.replace($('#header h1 a'), { 
        fontFamily: 'Helvetica Neue Ex Thin',
        hover: true
      });
      //
      Cufon.replace($('#pages li a.title, h2 a, h2, li.tag a'), { 
        fontFamily: 'Helvetica Neue Ex Light',
        hover: true
      });
      
      $('ul#tags li a').each(function(){ 
        var url = $(this).attr('href').replace('/tags/', '#/');
        $(this).attr('href', url); 
      }).click(function(){
        $('#target').removeClass('open'); 
      });
      
      $('#container').prepend('<div id="waiting">Loading...</div>');
      $('#content').prepend('<div id="display"></div>');
      $('#display').hide();
        
    });
    
    get('#/', function() { with(this) {    
      // Preloads the thumbnails. Should try to cache this. 
      $('ul#tags li a').each(function(){   
        var text = $(this).attr('href').replace('#/', ''),
          url = '/tags/' + text 
          $.getJSON(url,
            function(data){
              $.each(data.items, function(i,item){  
                $("<img/>").attr("src", item.icon);
              });
            });
      });
    }});              
    
    get('#/:tag', function() { with(this) {  
      $display = $('#display');
      
      if($display.length > 0){
        $display.fadeOut('slow');
      }
      showActiveTags(params['tag'],'');
    }});  
    
    get('#/:tag/:id', function() { with(this) { 
      var itemId = '#item_' + params['id'],
        tagName = params['tag']
      $('#target').addClass('open');
      if($('#target').html() == ''){
        showActiveTags(tagName,itemId);
      }else{  
        showDisplayImage(tagName,itemId);
      }         
    }});
  }});
  
  $(function() {
    app.run();
  });
  // Chane
  function showDisplayImage(tagName,imageId){
    var $display = $('#display'),
      imageSrc = $(imageId + ' img').attr('src').replace('icon.png','small.jpg'),
      $image = $("<img/>").attr("src", imageSrc);
    
    $display.html('').fadeIn('fast');
    $('#waiting').show();  
      
    $image.prependTo('#display').hide();
    
    var next = $(imageId).next('a').attr('href');
    var previous = $(imageId).prev('a').attr('href');

    $image.load(function(){
      $(this).wrap('<a href="#/' + tagName + '"></a>');
      $('#waiting').hide();  
      
      // Centers the images vertically if they are horizontal
      var width = $(this).attr('width'), 
         height = $(this).attr('height');
      if(width > height){
        $(this).css({'margin-top':((480-height)/2 - 10) + 'px'});
      }
      $(this).fadeIn('slow');
      
      if(previous){
        $display.prepend('<a class="previous controls" href="' + previous + '">previous</a>');
      }else{
        $display.prepend('<span class="previous controls">previous</span>');
      };
      if(next){
        $display.append('<a class="next controls" href="' + next + '">next</a>');
      }else{
        $display.append('<span class="next controls" >next</span>');
      };
      
      $('#display .controls').css({
        background: 'none',
        textIndent: '-10000px'
      }).hover(function(){
        $(this).css({
          background: 'url(/images/kb/display.png)',
          textIndent: '0px'
        });
      },function(){
        $(this).css({
          background: 'none',
          textIndent: '-10000px'
        });
      });
    });
  }     
  
  function showActiveTags(tagName,item){   
    var $tags =  $('ul#tags li a'), 
      $tag = $('#' + tagName + ' a');
      
    $tags.each(function(){
      $(this).removeClass('active'); 
    }); 
    $tag.addClass('active');
                    
    Cufon.replace($tags, { 
      fontFamily: 'Helvetica Neue Ex Light',
      hover: true
    });     
    
    var url = $tag.attr('href').replace('#/','/tags/'),
      activeName = $('#tags li a.active').parent('li').attr('id'),
      $target = $('#target');

    if(!$target.hasClass('open') || $target.html() == ''){
      $('#waiting').show();  
      $.getJSON(url,
        function(data){ 
          $target.html('').removeClass('open');      
          $.each(data.items, function(i,item){    
            $item = $("<img/>").attr("src", item.icon);
            $item.appendTo("#target")
              .wrap('<a id="item_' + item.id + '" href="#/' + tagName + '/' + item.id + '" title="' + item.caption + '"></a>')
              .hide();
            $item.load(function(){
              $(this).fadeIn('fast');
            });
          });   
          if(item){ 
            showDisplayImage(tagName,item); 
          }
          $('#waiting').hide();
        });
    }  
  }

})(jQuery);



