jQuery(function($){
  var $yearActive, $monthActive,
      activeMonth, closeActive, openMonth,
      accordionYearHandler, accordionMonthHandler;
  
  $yearActive  = $('#nav_tm .year').first();
  $monthActive = $('#nav_tm .month').first().parent();
  
  activeYear = function($year){
    if($monthActive){
      closeActiveMonth();
      $monthActive = null;
    }
    
    if($yearActive && $yearActive.index() == $year.index()){
      closeActiveYear();
      $yearActive = null;
      
      return false;
    }
    
    if($yearActive)
      closeActiveYear();
      
    $yearActive = $year;
    
    if($year.has('ul:not(.highlights)').length > 0){
      openYear($year);
    }else{
      var url, ajaxData;
      
      url = $year.find('h3 a').attr('href');
      ajaxData = {ajax_timemachine: true, type: 'year'};
      
      $.get(url, ajaxData, function(data, status, xhr){
        if(status == "success"){
          var tmo;
          
          $year.append(data).css({height: Math.floor($year.find('h3').height()), overflow: 'hidden'});
          
          tmo = setTimeout(function(){
            clearTimeout(tmo);
            openYear($year);
          }, 1);
        }else{
          console.error(status);
        }
      }).error(function(){
        
      });
    }
  };
  
  closeActiveYear = function(){
    var finalHeight;
    
    finalHeight = Math.floor($yearActive.find('h3').height());
    
    $yearActive.css('overflow', 'hidden')
                .animate({height: finalHeight}, 500, function(){
                  $(this).css('overflow', 'visible').removeClass('current')
                  .find('> ul').css('display', 'none');
                });
  };
  
  openYear = function($year){
    var initialHeight, finalHeight;
    
    initialHeight = Math.floor($year.css('height', '').find('h3').height());
    $year.find('> ul').css('display', 'block');
    finalHeight   = $year.css('overflow', 'hidden').height();
    
    $year.css('height', initialHeight)
         .animate({height: finalHeight}, 500, function(){
           $(this).removeAttr('style').addClass('current');
         });
  };
  
  // month accordion methods
  activeMonth = function($list){
    if($monthActive && $list.index() == $monthActive.index()){
      closeActiveMonth();
      $monthActive = null;
      
      return false;
    }
    
    if($monthActive)
      closeActiveMonth();
    
    $monthActive = $list;

    if ($list.has('.day').length > 0){
      openMonth($list);
    }else{
      var url, ajaxData;
      
      url = $list.find('.month a').attr('href');
      ajaxData = {ajax_timemachine: true, type: 'month'};
      
      $.get(url, ajaxData, function(data, status, xhr){
        if(status == "success"){
          var tmo;
          
          $list.append(data);
          
          tmo = setTimeout(function(){
            clearTimeout(tmo);
            openMonth($list);
          }, 1);
        }else{
          console.error(status);
        }
      }).error(function(xhr, status, errorThrown){
        if(xhr.responseText.match(/li/gi).length > 0){
          $list.append(xhr.responseText);

          tmo = setTimeout(function(){
            clearTimeout(tmo);
            openMonth($list);
          }, 1);
        }
      });
    }
  };
  
  closeActiveMonth = function(){
    var finalHeight;
    
    finalHeight = Math.floor($monthActive.find('.month').height());
    //$monthActive.find('ul.highlights li').css('display', 'none');

    $monthActive.css('overflow', 'hidden')
                .animate({height: finalHeight}, 500, function(){
                  $(this).css('overflow', 'visible')
                  .find('> li.day').css('display', 'none');
                  //$(this).find('ul.highlights li').css('display', '');
                });
  };
  
  openMonth = function($list){
    var initialHeight, finalHeight;
    
    initialHeight = Math.floor($list.css('height', '').find('.month').height());
    $list.find('li.day').css('display', 'block');
    //$list.find('ul.highlights li').css('display', 'none');
    finalHeight   = $list.css('overflow', 'hidden').height();
    
    $list.css('height', initialHeight)
         .animate({height: finalHeight}, 500, function(){
           $(this).removeAttr('style');
           //$(this).find('ul.highlights li').css('display', '');
         });
  };
  
  // Events handlers
  accordionYearHandler = function(ev){
    var $year;
    
    $year = $(this).parents('.year');
    activeYear($year);
    
    return false;
  };
  
  accordionMonthHandler = function(ev){
    var $list;
    
    $list = $(this).parents('ul');
    activeMonth($list);
    
    return false;
  };
  
  $('#nav_tm').delegate('.day > a[href=#]', 'click', false);
  $('#nav_tm').delegate('.year h3 > a', 'click', accordionYearHandler);
  $('#nav_tm').delegate('.month > a', 'click', accordionMonthHandler);
  $('#nav_tm').delegate('.year h3', 'click', function(ev){ $(this).find('a:first').click(); });
  $('#nav_tm').delegate('.month', 'click', function(ev){ $(this).find('a:first').click(); });
});
