var Placeholder = new Class({
  Implements: [Options, Events],
  options: {
    onFocus: function(){},
    onBlur: function() {},    
    onSupported: function() {} // if browser supports the html5 placeholder attr
  },
  initialize: function(elm, text, options) {
    this.setOptions(options);
    this.elm = $(elm);
    this.text = text;
    
    // Checks if the browser has support for HTML5 input placeholder
    
    if(!Browser.ie) { // fails in IE
      if(Object.keys(new Element('input')).contains('placeholder')) {
        this.elm.set('placeholder', text);
        this.fireEvent('supported', this.elm);
        return; // nothing left to do
      }  
    }
    
    this.elm.addEvent('focus', function() {
      this.action(this, this.text, '', 'focus');
    }.bind(this));
    
    var blur = function() { 
      this.action(null, '', this.text, 'blur'); 
    };
    this.elm.addEvent('blur', blur.bind(this));
    
    blur.call(this);
  },
  action: function(e, match, replace, callback) {
    if(this.elm.get('readonly')) return;
    if(this.elm.get('value') == match) {
      this.elm.set('value', replace);
    }
    this.fireEvent(callback, this.elm);
  }
});


var Slideshow = new Class({
  Implements: [Options, Events],
  options: {
    duration: 5000,
    slideClass: 'slideshow-slide',
    onSlideUpdated: function() {}
  },
  initialize: function(elm, options) {
    this.setOptions(options);
    
    this.elm = $(elm);
    this.position = 0;
    this.playing = false;
    this.timer = null;
    
    
    this.frames = this.elm.getElements('.' + this.options.slideClass);
    
    if(this.frames.length <= 1)
    {
      return;
    }
    
    this.frames.set('opacity', 0);
    
    this.frames.each(function(frame) {
      frame.set('tween', { onComplete: 
        function() { this.frameFinished(); }.bind(this) });
    }.bind(this));
    
    this.start();
    
  },
  start: function() {
    this.fireEvent('slideUpdated', this.position);
    this.playing = true;
    this.frames[this.position].tween('opacity', 1);    
  },
  next: function() {
    this.goTo((this.position + 1));
  },
  back: function() {
    if(this.frames[this.position--]) {
      this.position = this.position.length;
    }
  },
  goTo: function(frame) {

    if(frame == this.position) return;
    
    this.clearShow();
    
    this.frames[this.position].tween('opacity', 0);
        
    this.position = frame;
    
    if(!this.frames[this.position]) {
      this.position = 0;
    }
    
    this.start();
    
  },
  clearShow: function() {
    this.playing = false;
    clearInterval(this.timer);
    clearTimeout(this.timer);
  },
  frameFinished: function() {
    if(this.playing) {
      clearTimeout(this.timer);
      clearInterval(this.timer);
      this.timer = setTimeout(function(){ this.next(); }.bind(this), 
          this.options.duration);
    }
  }
});


