var CaseStudy = Class.create({
  initialize: function(client_name){
    if(client_name.indexOf("client-")===0)
      client_name = client_name.substring(7, client_name.length); 
    else if(client_name.indexOf("case-study-")===0)
      client_name = client_name.substring(11, client_name.length);
    this.name = client_name;
    this.logo = $('client-' + client_name);
    this.case_study = $('case-study-' + client_name);
  },
  addCurrent: function(){
    this.logo.addClassName("current");
    this.case_study.addClassName("current");    
  },
  removeCurrent: function(){
    this.logo.removeClassName("current");
    this.case_study.removeClassName("current");
  },
  equals: function(other){
    return this.name == other.name;
  },
  toString: function(){
    return "<CaseStudy: " + this.name +">";
  }
});

var ShowCase = {
  timer: null,
  sliding: false,
  current: function(){
    return new CaseStudy($$('div#case-study-container div.current')[0].id);
  },
  next: function(){
    var next_case = this.current().case_study.next();
    if(next_case)
      return new CaseStudy(next_case.id);
    else
      return null;
  },
  forward: function(){
    var current_case = this.current();
    var next_case = this.next();
    if(next_case)
      this.move(current_case, next_case);
  },
  get: function(client_name){
    return new CaseStudy(client_name);
  },
  setCurrent: function(client_name){
    $$('div#case-study-container div.case-study').each(function(elem){
      new CaseStudy(elem.id).removeCurrent();
    });
    new CaseStudy(client_name).addCurrent();
  },
  show: function(client_name){
    Effect.ScrollTo('case-studies-container');
    this.move(this.current(), this.get(client_name));
  },
  start: function(){
    this.timer = setInterval("ShowCase.forward()", 3000);
  },
  stop: function(){
    clearInterval(this.timer);
  },
  move: function(current_case, next_case){
    if(this.sliding)
      return false;
    if(current_case.equals(next_case))
      return false;
    this.sliding = true;
    var distance = current_case.case_study.positionedOffset()[0] - next_case.case_study.positionedOffset()[0];
    new Effect.Fade(current_case.case_study, {
      from: 1, to: 0.05, duration: 0.5 });
    new Effect.Move($('case-study-wrapper'), {
      x: distance, y: 0, mode: 'relative',
      transition: Effect.Transitions.sinoidal,
      beforeStart: function(){
        current_case.removeCurrent();
        next_case.addCurrent();
      },
      afterFinish: function(){
        current_case.case_study.setOpacity(1);
        ShowCase.sliding = false;
        if(ShowCase.timer && ShowCase.next() == null)
          ShowCase.stop();
      }
    });
  }
};
