// Custom javascript
// Copyright (c) 2008 Aeron Glemann <http://electricprism.com/aeron>
// MIT-style license

var pusher = new Class({
  initialize: function(){
    var el = $('projects');
    
    if ($E('.results', el)){ // hide shown results
      el.addEvent('mouseenter', function(){
        this.effect('top', { transition: Fx.Transitions.quadInOut }).start(0, -49);
        this.removeEvents('mouseenter');
      });
    }
  }
});

var messenger = new Class({
  initialize: function(){
    this.f = $E('form');

    if (!this.f){ return false; }

    var size = this.f.getSize();
    
    this.f.setStyles({ 'height': 0, 'opacity': 0 }).addEvent('submit', this.validate.bindWithEvent(this));
    
    this.fx = new Fx.Styles(this.f, { transition: Fx.Transitions.quadInOut, wait: false });

    $ES('.contact a').each(function(a){
      a.addEvent('click', function(y){
        if (this.f.getStyle('height').toInt() > 0){ // visible
          this.fx.start({ 'height': 0, 'opacity': 0 });      
        } else { // hidden
          this.fx.start({ 'height': y, 'opacity': 1 });      
        }
      }.pass(size.size.y, this));
    }, this);
  },
  
  validate: function(event){
    this.failed = false;
  
    $$('input', 'textarea').each(function(el){
      var message = false;
    
      var val = el.getValue().clean();
    
      if (val.length == 0 || val == null){
        message = (el.getTag() == 'textarea') ? "Req'd" : 'Required';
      } else if (el.name == 'email' && !val.test('\\w{1,}[@][\\w\\-]{1,}([.]([\\w\\-]{1,})){1,3}$')){
        message = 'Invalid';
      }
      
      this.error(el, message);
    }, this);
    
    if (this.failed){ event.stop(); }
  },
  
  error: function(el, message){
    if (message){ // add error
      this.failed = true;

      el.focus();
      el.effect('color', { duration: 1000 }).start('#FF0000');
      el.getPrevious().setText(el.name + '. ' + message).effect('color', { duration: 1000 }).start('#FF0000');
    } else {
      el.effect('color', { duration: 1000 }).start('#000000');
      el.getPrevious().setText(el.name + '.').effect('color', { duration: 1000 }).start('#000000');
    }
  }
});

var router = new Class({
  initialize: function(){
    if (window.parent == window){ // projects should be viewed through iframe
      $url = document.URL.split('/');
      $reroute = '?' + $url.pop();
      window.location = $url.join('/') + $reroute;
    }
  }
});

var lightshow = new Class({
  initialize: function(){
    $each(document.links, function(a){
      if (a.rel && a.rel.test(/^lightbox/i)){
        $(a).addEvent('click', function(event){ 
          event.stop();
          window.parent.Lightbox.show(event.target.href, event.target.title); 
        }.bindWithEvent(this));  
      }
    });
  }
});

var resizer = new Class({
  initialize: function(el){
    $ES('iframe').each(function(iframe) {
      iframe.addEvent('load', function(iframe){ this.resize(iframe); }.pass(iframe, this));
    }, this);
  },
  
  resize: function(iframe){
    if ($chk(window.frames[iframe.name].getScrollHeight)){
      var height = window.frames[iframe.name].getScrollHeight();

      iframe.setStyle('height', height);
    }
  }
});

var bubbles = new Class({
  options: {
    bubbles: ['lg', 'md', 'sm'],
    className: 'bubble',
    fps: 18,
    imgdir: 'http://www.electricprism.com/aeron/css/bubbles/',
    lag: .6, // 0 = no lag, 1 = all lag
    offsets: { lg: { x: 40, y: -10 }, md: { x: 28, y: 5 }, sm: { x: 14, y: 5 }},
    z: 99
  },

  initialize: function(el, options){
    if (window.ie6){ return false; }

    this.setOptions(options);
    
    this.bubbles = [];
    this.page = { x: 0, y: 0 };
    
    this.options.bubbles.each(function(bubble, i){
      this[bubble] = new Element('div', { 
        'class': this.options.className + '-' + bubble,
        'styles': { 'position': 'absolute', 'top': 0, 'left': 0, 'visibility': 'hidden', 'zIndex': (this.options.z - i) }      
      }).inject(document.body);
      
      for (var n = 0; n < 20; n++){
        if (n < 10){ n = '0' + n; }

        var frame = bubble + '-' + n + '.png';
        
        // preload all frames
        new Element('img', { src: this.options.imgdir + frame });        
      }
    }, this);
    
    
    var elements = $ES('a[title]');
    
    elements.each(function(el){
      el.addEvent('mousemove', function(event){ this.page = event.page; }.bindWithEvent(this));      
    }, this);
    
    this.tips = new Tips(elements, { 
      'offsets': { x: 28, y: -28 }, 
      'onShow': this.show.bind(this), 
      'onHide': this.hide.bind(this) 
    });    
  },
  
  show: function(){    
    this.tips.toolTip.setStyle('visibility', 'visible');
    
    this.bubbles = this.options.bubbles.copy(); // reset visible bubbles

    this.bubbles.each(function(bubble){ 
      this[bubble].setProperty('f', $random(1, 20));
      this[bubble].setStyle('visibility', 'visible'); 
    }, this);

    $clear(this.timer);
    this.animate();
  },
  
  hide: function(){
    this.tips.toolTip.setStyle('visibility', 'hidden');
    
    this.bubbles.each(function(bubble){ this[bubble].setStyle('visibility', 'hidden'); }, this);

    $clear(this.timer);
  },
  
  animate: function(){
    this.bubbles.each(function(bubble){
      var f = this[bubble].getProperty('f').toInt();
      var f = (f + 1) % 20; // next frame

      this[bubble].setProperty('f', f);

      if (f < 10){ f = '0' + f; }

      var frame = bubble + '-' + f + '.png';

      this[bubble].setStyle('backgroundImage', 'url(' + this.options.imgdir + frame + ')');
    }, this);
    
    this.position();
    
    this.timer = this.animate.delay(Math.round(1000 / this.options.fps), this);  
  },
  
  position: function(){
    var win = {'x': window.getWidth(), 'y': window.getHeight()};
    var scroll = {'x': window.getScrollLeft(), 'y': window.getScrollTop()};
    var prop = {'x': 'left', 'y': 'top'};

    this.bubbles.each(function(bubble, i){
      var tip = {'x': this[bubble].offsetWidth, 'y': this[bubble].offsetHeight};
      
      for (var z in prop){
        var offsets = (this.options.offsets[bubble]) ? this.options.offsets[bubble] : this.options.offsets;
        
        var sp = this[bubble].getStyle(prop[z]).toInt();        
        var ep = ((this.page[z] + offsets[z] + tip[z] - scroll[z]) > win[z]) ? this.page[z] - offsets[z] - tip[z] : this.page[z] + offsets[z];
        var dp = ep - sp;
        
        var mod = 1 - ((i + 1) / this.options.bubbles.length) * this.options.lag;

        this[bubble].setStyle(prop[z], sp + (dp * mod));
      }      
    }, this);
  }
});

bubbles.implement(new Events, new Options);

window.addEvent('domready', function(){
  switch(document.body.id){
    case 'projects':
      new router();
      new lightshow();
      if (!$('fader').faded) $('fader').setStyle('opacity', 0);
      (function(){
      }).delay(50);
      break;
      
    default:
      new pusher();
      new resizer();
      new bubbles();
      new messenger();
      Lightbox.init();

      var a = new Element('a', { 'class': 'download', 'events': { 'click': function(){ window.print(); }}}).setText('Print the curriculum vitae');
      $E('#sidebar ul').adopt(new Element('li').adopt(a));
      var p = $E('p.success');
      if (p){ p.effect('color', { duration: 4000 }).start('#000000'); }
  }
});

window.addEvent('load', function(){
  switch(document.body.id){
    case 'projects':
      $('fader').faded = true;	
      $('fader').setStyle('opacity', 0).effect('opacity', { duration:  1000 }).start(0, 1);
  }
});