jQuery.ajaxSetup({cache: false});

function Achievement( params ){
  for( i in params){
    this[i] = params[i];
  };
  // IE wants / instead of - in date strings
  this.date = new Date(Date.parse(this.date.replace(/-/g,'/')));
  this.year = function(){
    return this.date.getFullYear();
  }
  this.dayOfYear = function(){
    return Math.ceil((this.date - new Date(this.date.getFullYear(),0,1)) / 86400000);
  }
  this.yearPercent = function(){
    return Math.round( this.dayOfYear() / 365 * 100 );
  }
}

var Timeline = {
  init: function(){
    jQuery('#tl-timeline tbody tr, #tl-timeline tbody tr li').live( 'mouseover mouseout', Timeline.handleHover);
    jQuery('.tl-events li > a.tip').live('click', Timeline.handleEventClick );
    jQuery('#close-timeline').click( Timeline.toggle );
    jQuery('#event-content .close').live('click', Timeline.closeEventContent);

    jQuery('#tl-timeline thead th').css({width: (jQuery('#tl-timeline').width() / jQuery('#tl-timeline thead th').length )});
    
    Timeline.loadData('Industry');
    Timeline.loadData('GenomeQuest');
  },
  toggle: function(){
    if(!jQuery('#timeline-container').hasClass('active')){
      jQuery(jQuery('.tl-events li > a.tip')[0]).trigger('click');
    } else {
      Timeline.deactivate();
    }
  },
  handleHover: function(e){
    if( e.type == 'mouseover' ){
      jQuery(this).addClass('hover');
    } else {
      jQuery(this).removeClass('hover');
    }
  },
  activate: function(){
    jQuery('#timeline-container').addClass('active');
    _gaq.push(['_trackEvent','timeline','Activated']); // track on GA
  },
  initYearLines: function(){
    var yearCount = jQuery('#tl-timeline thead th').length;
    var eachWidth = jQuery('#tl-timeline tbody tr:first td:nth-child(2)').width();
    for( var i = 1; i < yearCount; i++){
      jQuery('#tl-yearlines').append(jQuery('<li class="year-line" />').css({width:eachWidth+'px'}));
    }
  },
  deactivate: function(){
    Timeline.closeEventContent();
    jQuery('#timeline-container, #timeline-container .active').removeClass('active');
    jQuery('#timeline-container').css({height: 100});
    _gaq.push(['_trackEvent','timeline','Deactivated']); // track on GA
  },
  loadData: function( name ){
    var row = jQuery('<tr id="timeline-'+name+'">');
    row.append( jQuery('<td class="tl-company"><img src="/timelines/logo-'+String(name).toLowerCase()+'.png" alt="'+name+'" /></td>'));
    var earliestYear = new Date().getFullYear() - jQuery('#tl-timeline thead th').length+2;
    for( var i=earliestYear; i <= new Date().getFullYear(); i++){
      row.append( jQuery('<td class="tl-year y-'+i+'"></td>').append(jQuery('<ul class="tl-events"></ul>')) );
    }
    jQuery('#tl-timeline tbody').append( row );
    jQuery.getJSON('/timelines/'+String(name).toLowerCase()+'-achievements.json', function( achievements ){ 
      jQuery(achievements).each(function(i, o){
        a = new Achievement( o );
        
        var li = jQuery('<li style="left: '+a.yearPercent()+'%;" class="strength-'+a.strength+'"></li>');
        li.data('achievement', a);
        li.append( jQuery(['<a href="#" class="tip" title="',a.title,'"></a>'].join('')));
        jQuery('tr#timeline-'+name+' td.y-'+a.year()+' ul').append( li );
      });
      jQuery(".tip").tipTip({defaultPosition: 'top', edgeOffset: 6, delay: 50});
      
      if( jQuery('#tl-yearlines li').length == 1 ) {
        Timeline.initYearLines();
      }
    });
  },
  closeEventContent: function(e){
    if(e){ e.preventDefault(); }
    jQuery('#tl-timeline .active').removeClass('active');
    jQuery('#tl-timeline .hover').removeClass('hover');  
    jQuery('#event-content, .tl-events span.dot, .tl-events span.line').remove();
  },
  handleEventClick: function(e){
    console.log(e);
    e.preventDefault();
    
    if(!jQuery('#timeline-container').hasClass('active')){
      Timeline.activate();
    }

    var li = jQuery(this).parent('li');
    var achievement = li.data('achievement');

    _gaq.push(['_trackEvent','timeline',achievement.title]); // track on GA

    jQuery('#tiptip_holder').hide();
    
    Timeline.closeEventContent();

    jQuery(this).parents('tr, li').addClass('active');

    li.append('<span class="dot" />').append('<span class="line" />')
    var eventContent = jQuery('<div id="event-content"/>');
    eventContent.prepend( jQuery('<a class="close" href="#">close</a>') );
    eventContent.append( jQuery('<h4>'+achievement.title+'</h4>') );
    eventContent.append( achievement.content );

    if( achievement.url && achievement.url.length > 0 ) {
      eventContent.children('p:last').append( jQuery('<br /><a href="'+achievement.url+'" target="_blank" class="more">More Information</a>') );
    }
    if( achievement.image && achievement.image.length > 0) {
      eventContent.children('p:first').prepend( jQuery('<img src="'+achievement.image+'" align="right" />') );
    }

    li.append( eventContent );

    eventContent.fadeIn('fast',function(){
      // Expand the content box down until it's Xpx from the top of the last row
      if(jQuery('#timeline-container').height() < jQuery('#event-content').position().top + jQuery('#event-content').height() + 40){
        jQuery('#timeline-container').css({height: jQuery('#event-content').position().top + jQuery('#event-content').height() + 40});
      }
    });

    // Push the content box down until it's Xpx from the top of the last row
    while(jQuery('#event-content').offset().top < jQuery('#tl-timeline tr:last').offset().top + 65){
      jQuery('#event-content').css({top: jQuery('#event-content').position().top + 2});
      jQuery('li.active .line').css({height: jQuery('#event-content').position().top + 2});
    }

    // Move the content box horizontally until it's within the bounds
    while( 
      jQuery('#event-content').offset().left + jQuery('#event-content').width() > // Content right edge
      jQuery('#tl-timeline').offset().left + jQuery('#tl-timeline').width() - 10 // Timeline right edge
    ){
      jQuery('#event-content').css({left: jQuery('#event-content').position().left - 20});
    }

    jQuery('.line').fadeTo('slow',1);
  }
}
