var klassekartak = {
  initialize: function() {
    'Menu Masthead Skillscout Guests FAQ'.split(' ').each(function(n) {
      klassekartak[n].initialize();
    });
    this.registerEvents();
    this.externalizeLinks();
  },
  
  registerEvents: function() {
    document.addEvent('click', function(event) { 
      if (event.target.hasClass('deactivated')) event.stop();
    });
  },

  externalizeLinks: function() {
    $$('a').each(function(a) {
      if (a.href.indexOf('http://') == 0 && !a.href.contains(window.location.host)) {
        a.set('target', '_blank');
      }
    });
  },

  scrollContainer: window
};

klassekartak.Menu = {
  initialize: function() {
    this.links = $$('#navigation ul li a');
    
    klassekartak.scrollContainer.scrollTo(0, 0);
    this.scrollFx = new Fx.Scroll(klassekartak.scrollContainer, {
      onStart: function() { this.scrolling = true; }.bind(this),
      onComplete: function() { this.scrolling = null; }.bind(this)
    });

    this.links.each(function(link) {
      var scrollTarget = link.href.split('#')[1];
      if (!$(scrollTarget) || scrollTarget == 'enfontterrible') return;
      link.store('scrollTarget', $(scrollTarget));
      if($(scrollTarget + '_submenu')) link.store('submenu', new Submenu(scrollTarget + '_submenu', scrollTarget));
      this.register(link);
    }.bind(this));

    document.addEvent('scroll', function(event) {
      this.displayActiveSubmenu();
    }.bind(this));
    
    if ($('students'))
      this.scrollToSection($('nav_students'));
  },

  displayActiveSubmenu: function() {
    if (this.scrolling) return;
    this.links.each(function(link) {
      var scrollTarget = link.retrieve('scrollTarget');
      if (scrollTarget) {
        var delta = scrollTarget.offsetTop - window.scrollY;
        if (delta <= 90) {
          this.setActive(link);
        }
      }
    }, this);
  },

  register: function(link) {
    link.addEvent('click', function(event) {
      event.stop();
      this.scrollToSection(link);
    }.bind(this));
  },

  scrollToSection: function(link, callback) {
    this.setActive(link);
    this.scrollFx.cancel();
    var scrollTarget = link.retrieve('scrollTarget');
    if(link.retrieve('submenu')) {
      this.scrollFx.start(0, scrollTarget.offsetTop - 4);
    } else {
      this.scrollFx.start(0, scrollTarget.offsetTop + 26);
    }
    this.scrollFx.onComplete = function() {
      (callback || $empty)();
      this.scrolling = null;
    }.bind(this);
  },

  setActive: function(link) {
    var submenu;

    if (this.activeSubmenuLink) {
      submenu = this.activeSubmenuLink.retrieve('scrollTarget').retrieve('submenu');
      this.activeSubmenuLink.removeClass('active');
    }

    link.addClass('active');
    if (submenu) submenu.deactivate();

    submenu = link.retrieve('scrollTarget').retrieve('submenu');
    if (submenu) submenu.activate();
    this.activeSubmenuLink = link;
  },
  
  activateSubmenu: function(link) {
    var submenu = link.retrieve('scrollTarget').retrieve('submenu');
    if (submenu) submenu.activate();
  }
};

var Submenu = new Class({
  initialize: function(element, container) {
    this.element = $(element);
    this.container = $(container);
    this.content = this.container.getElement('div.content-wrapper');
    this.links = this.element.getElements('ul li a');
    this.container.store('submenu', this);

    this.registerEvents();
    this.element.pin().setStyle('display', 'none');
    this.setup();
  },
  
  registerEvents: function() {
    var instance = this;
    this.links.addEvent('click', function(event) {
      event.stop();
      instance.links.removeClass('active');
      instance.filter(this);
      this.addClass('active');
    });
  },

  setup: function() {
    var coords = this.container.getCoordinates();
    this.bounds = { top: coords.top, bottom: coords.bottom };
  },

  filter: function(link) {
    link.getPrevious('img').setStyle('display', '');
    new Request({
      method: 'get',
      url: link.href,
      data: { type: link.innerHTML },
      evalScripts: true,
      onSuccess: function(responseText) {
        this.content.empty().set('html', responseText);
        link.getPrevious('img').setStyle('display', 'none');
        new Fx.Scroll(klassekartak.scrollContainer).start(0, this.container.offsetTop);
        klassekartak.Guests.initialize();
      }.bind(this)
    }).send();
  },

  activate: function() {
    this.element.setStyle('display', 'block');
  },

  deactivate: function() {
    this.element.setStyle('display', 'none');
  }
});

klassekartak.Masthead = {
  initialize: function() {
    if (!$('student_thumbs'))
      return;
    this.active = true;
    this.registerFx();
    this.registerEvents();
    this.watch.periodical(1000, this);
  },
  
  registerFx: function() {
    this.hideFx = new Fx.Morph('masthead', { 
      duration: 500,
      onComplete: function() { $('masthead').setStyle('display', 'none' ); }
    });
    
    this.showFx = new Fx.Morph('masthead', { 
      duration: 500,
      onStart: function() { $('masthead').setStyles({ 'opacity': 0, 'display': 'block' }); }
    });
  },
  
  registerEvents: function() {
    $('student_thumbs').addEvents({
      'mouseenter': this.hide.bind(this),
      'mouseleave': this.show.bind(this)
    });
    this.tips = new Tips('.tooltip', { className: 'toolip-container' });
  },
  
  watch: function() {
    if (!this.mastheadHidden && $('masthead').getStyle('display') == 'none')
      this.showMasthead();
  },
  
  hide: function() {
    if (!this.active) return;

    this.showFx.cancel();
    this.hideFx.start({ opacity: [1, 0] });
    this.mastheadHidden = true;
  },
  
  show: function() {
    if (!this.active) return;
    
    this.hideFx.cancel();
    this.showFx.start({ opacity: [0, 1] });
    this.mastheadHidden = null;
  },
  
  activate: function() { this.active = true; },
  deactivate: function() { this.active = null; }
};

klassekartak.Skillscout = {
  initialize: function() {
    this.scout = $('skill_scout');
    if(!this.scout) return;
    this.actuator = $('skill_scout_actuator');
    this.categories = $$('#skill_filters a');
    this.thumbs = $$('#student_thumbs ul li a');
    this.registerEvents();
    this.visible = false;
    this.active = [];
  },
  
  registerEvents: function() {
    var that = this;
    this.fxSlide = new Fx.Slide(this.scout).hide();
    this.actuator.addEvent('click', this.toggle.bind(this));
    this.categories.addEvent('click', function(event) {
      event.stop();
      that.filter(this);
    });
    this.thumbs.addEvent('click', function(event) {
      if (this.hasClass('active')) event.stop();
    })
  },
  
  toggle: function() {
    this.fxSlide.toggle();
    this.visible = !this.visible;
    if (this.visible) {
      klassekartak.Masthead.hide();
      klassekartak.Masthead.deactivate();
    }
    else {
      klassekartak.Masthead.activate();
      klassekartak.Masthead.show();
    }
  },
  
  filter: function(category) {
    this.categories.removeClass('active');
    category.addClass('active');
    this.render(category.getAttribute('id'));
  },
  
  render: function(filter) {
    var visibles = [],
        invisibles = [];
    if (filter == 'filter_all') {
      visibles = this.thumbs;
    }
    else {
      this.thumbs.each(function(thumb) {
        (thumb.hasClass(filter) ? visibles : invisibles)['push'](thumb);
      });
    }
    visibles.each(function(visible) {
      new Fx.Morph(visible, { duration: 300 }).start({ opacity: 1 });
    });
    invisibles.each(function(invisible) {
      new Fx.Morph(invisible, { duration: 300 }).start({ opacity: 0 });
    });
  }
};

var Slideshow = new Class({
  initialize: function(container, images) {
    this.container = $(container);
    this.y = this.container.getPosition().y;
    this.controls = this.container.getElement('div.controls');
    this.caption = this.controls.getElement('div.caption');
    this.images = images;
    this.current = 0;
    
    this.registerBehaviors();
    //this.checkVisibility = this.checkForScroll.periodical(100, this);
    this.show(0);
    if (this.images.length > 1) this.hideControls();
  },
  
  registerBehaviors: function() {
    this.page = this.container.getElement('div.page');
    this.canvas = this.container.getElement('div.canvas');
    this.nextButton = this.container.getElement('div.slideshow div.next'),
    this.previousButton = this.container.getElement('div.slideshow div.previous');
    if (this.images.length < 2) {
      $$(this.page, this.nextButton, this.previousButton).setStyle('display', 'none');
      if (this.images[0].caption)
        this.controls.setStyle('opacity', 0);
      else
        return;
    }

    this.nextButton.addEvent('click', function() { this.show(this.current + 1); }.bind(this));
    this.previousButton.addEvent('click', function() { this.show(this.current - 1); }.bind(this));
    
    this.container.getElement('div.slideshow').addEvents({
      'mouseenter': this.showControls.bind(this),
      'mouseleave': this.hideControls.bind(this)
    });
    this.controlsFx = new Fx.Elements(
      $$(this.controls, this.nextButton, this.previousButton), 
      { duration: 500 }
    );
  },
  
  checkForScroll: function() {
    if (window.getScroll().y + this.container.getSize().y >= this.y) {
      this.show(0);
      if (this.images.length > 1) this.hideControls();
      $clear(this.checkVisibility);
    }
  },
  
  setLoading: function() {
    if (!this.canvas.hasClass('loading'))
      this.canvas.addClass('loading');
    this.canvas.getElement('img').setStyle('opacity', 0);
  },
  
  show: function(index) {
    index = index == -1 ? this.images.length-1 : (index == this.images.length ? 0 : index);
    var image = this.images[index];
    this.setLoading();
    if (!image)
      return;

    if (/.*\.gif|jpg|png$/i.test(image.src)) {
      new Asset.image(image.src, { onload: function(img) {
        this.canvas.empty();
        img.setStyle('display', 'none');
        img.inject(this.canvas);
        this.canvas.getParent('.slideshow-wrapper').setStyle('width', img.width+2);
        img.setStyle('display', 'block');
        this.showCaption(image);
      }.bind(this)});
    }
    else {
      this.canvas.set('html', image.src);
      this.showCaption(image);
    }

    this.page.set('html', index + 1 + '/' + this.images.length);
    this.current = index;
  },
  
  showCaption: function(image) {
    var offset = this.canvas.getHeight() - 53;
    if (image.caption && !new RegExp(/^\s*$/).test(image.caption)) {
      this.caption.show().set('html', image.caption);
      offset = this.canvas.getHeight() - (this.caption.getHeight() + 25);
    } else {
      this.caption.hide().set('html', '');
    }
    this.controls.show();
    this.nextButton.setStyle('background-position', 'right ' + offset + 'px');
    this.previousButton.setStyle('background-position', 'left ' + offset + 'px');
  },
  
  showControls: function() {
    this.controlsFx.cancel();
    this.controlsFx.start({
      '0': { 'opacity': 1 },
      '1': { 'opacity': 1 },
      '2': { 'opacity': 1 }
    });
  },
  
  hideControls: function() {
    this.controlsFx.cancel();
    this.controlsFx.start({
      '0': { 'opacity': 0 },
      '1': { 'opacity': 0 },
      '2': { 'opacity': 0 }
    });
  }
});

var Videos = new Class({
  initialize: function(container, videos) {
    this.container = $(container);
    this.slideshow = this.container.getElement('.slideshow');
    this.videos = new Hash({});
    this.y = this.container.getPosition().y;
    
    videos.each(function(video) { 
      this.videos.set(video.title, video.movie); 
    }, this);
    
    this.setupTitleLinks();
    //this.checkVisibility = this.checkForScroll.periodical(100, this);
    this.setActive(this.titles.getFirst('li'));
    
    if (this.videos.getLength() < 2)
      this.titles.setStyle('display', 'none');
  },
  
  checkForScroll: function() {
    if (window.getScroll().y + this.container.getSize().y >= this.y - 200) {
      this.setActive(this.titles.getFirst('li'));
      $clear(this.checkVisibility);
    }
  },
  
  setupTitleLinks: function() {
    this.titles = this.container.getElement('ul.videos');
    this.videos.each(function(movie, title) {
      var t = new Element('li', { html: '<a href="#">' + title + '</a>' });
      t.inject(this.titles);
      t.store('movie', movie);
      t.addEvent('click', function(event) { event.stop(); this.setActive(t); }.bind(this));
    }, this);
  },
  
  setActive: function(title) {
    this.titles.getElement('li a').removeClass('active');
    this.slideshow.set('html', title.retrieve('movie'));
    title.getElement('a').addClass('active');
  }
});

klassekartak.Guests = {
  initialize: function() {
    var that = this;
    this.fxScroll = new Fx.Scroll(klassekartak.scrollContainer, { offset: { x: 0, y: -80 }});
    $$('#guests_index a').addEvent('click', function(event) {
      event.stop();
      var id = this.href.split('#')[1],
          element = $(id);
      if (!element) {
        new Request({
          method: 'get',
          url: '/guests/show/' + id.replace('guest_', ''),
          evalScripts: true,
          onSuccess: function(responseText) {
            var entry = new Element('div').set('html', responseText);
            entry.inject($('guests_content_wrapper'));
            (function() { that.fxScroll.toElement($(id)); }).delay(200);
          }
        }).send();
        return;
      }
      that.fxScroll.toElement(element);
    });
  }
};

klassekartak.Tips = {
  initialize: function() {
    if (!$('student_thumbs')) return;
    this.tips = new Tips('.has-tooltip', {
      className: 'tooltip'
    });
  }
};

klassekartak.FAQ = {
  initialize: function() {
    this.faq = $('faq');
    this.actuators = this.faq.getChildren('h4');
    this.actuators.addEvent('click', function() {
      var paragraphs = this.getAllNext('p');
      $$(paragraphs[0], paragraphs[1]).toggle();
    });
  }
}

window.addEvent('domready', klassekartak.initialize.bind(klassekartak));
window.addEvent('load', klassekartak.Menu.displayActiveSubmenu.bind(klassekartak.Menu));

