$(document).ready(function(){
  App.init();
});

var App = {
  
  init:function(){
    $('.status').click(function(){
      App.toggleStatus(this);
    });
    
    $('.user_link').click(function(){
      document.location = $(this).attr('data-link-url');
    });

    $('.delete_link, .over_link').click(function(evt){
      evt.stopImmediatePropagation(); // stop other events from firing (used when click an item that is on top of an already clickable item)
    });
    
    $('.open_half_link').click(function(evt){
      evt.preventDefault(); // stop anchor href from firing
      evt.stopImmediatePropagation(); // stop other events from firing (used when click an item that is on top of an already clickable item)
      App.toggleSideBar(this);
    });        
    
    $('.timestamp').mouseover(function(){
      $(this).attr('data-relative-time', $(this).html());
      $(this).html($(this).attr('data-timestamp'));
    }).mouseout(function(){
      $(this).html($(this).attr('data-relative-time'));
    });
  },
  
  drawerState: false,
  currentStatusId: null,
  currentStatus: null,
  currentHalfOpenLink: null,
  currentHalfOpenType: null,
  
  backToListItem:function(el){
    window.location = '#status_' + this.currentStatusId;
  },
  
  toggleStatus:function(el){
    var id = $(el).attr('data-status-id');

    if(this.currentStatus) $(this.currentStatus).removeClass('current');
    if(this.currentStatusId == id && this.drawerState) return;
    
    this.currentStatusId = id;
    this.currentStatus = el;
    
    $(el).addClass('current');
    
    $('.right_column').addClass('open');
    
    $(window).scrollTop(10);
    
    if(!this.drawerState){
      $('.right_column .content').load("/statuses/"+id+".js");
    }
  },
  
  toggleSideBar:function(el){
    var t = $(el).attr('data-open-type');
    var href = $(el).attr('href');

    if(this.currentHalfOpenLink) $(this.currentHalfOpenLink).parents('li').removeClass('current');
    if(this.currentHalfOpenType == t && this.drawerState) return;

    this.currentHalfOpenType = t;
    this.currentHalfOpenLink = el;
    
    // $(el).addClass('current');
    $(el).parents('li').addClass('current');
    
    if(t == 'edit team')
      $('.right_column').addClass('open');
    else
      $('.right_column').addClass('open_half');
        
    if(!this.drawerState){
      $('.right_column .master.content').load(href+".js");
    }        
  },
  
  toggleFilterControl:function(val, target){
    var vals = $.map($('#applied_stream_controls .'+target+'_control'), function(a){return $(a).attr('data-control-id')});
    var index = $.inArray(val, vals);    
  
    if(index > -1)
      vals.splice(index, 1);
    else
      vals.push(val);
    
    $('#'+target).val(vals);
    $('#statuses_filter').submit();
  },
  
  removeFilters:function(target){    
    $('#'+target).val('');
    $('#statuses_filter').submit();
  }
  
}

