var PhotoRotator = new Class({
  
  Implements: [Options, Events],

  initialize: function(target,options)
  {
  
      
      this.target = target;
      
      this.photos = Array;
      this.setOptions(options);
      this.numPhotos = 0;
      this.index = 0;
      this.setSpinner();
      this.loadJson();
      
      

                  
  },
  
  setSpinner: function()
  {
    this.target.addClass('spinner');
  
  },

  loadJson: function()
  {
        var jsonRequest = new Request.JSON({url: this.options.jsonurl, 
            onComplete: function(result){
                          $each(result['photos'],function(n,index){
                                 this.photos[index] = new Element('img').set('src', '/'+this.options.imagepath+n);
                                 this.numPhotos++;  
                          }.bind(this)); 
                          this.prepare();
                        }.bind(this)
            }).post({'imagepath' : this.options.imagepath});
  },
  
  
  prepare: function()
  {
        $('aar').fade('in');
        this.foreground = new Element('div', {'styles' : {'position' : 'absolute', 'top' : '0px','z-index' : '30'}}).set('id','PhotoRotator_foreground');
        this.background = new Element('div', {'styles' : {'position' : 'absolute', 'top' : '0px','z-index' : '10'}}).set('id','PhotoRotator_background');
        this.foreground.inject(this.target,'bottom');         
        this.background.inject(this.target,'bottom');
        
        
        this.photos[this.index].inject(this.background);
        //this.photos[this.index].inject(this.foreground);
        this.fadeIn.delay(100,null,this.background);
        this.nextPhoto.bind(this).periodical(5000);
  },
  
  fadeIn: function(element)
  {
    element.fade('in');

  
  },
  
  nextPhoto: function ()
  {     
        this.background.setStyle('z-index','30');
        this.foreground.setStyle('z-index','10');
        this.foreground.empty();
        
        this.nextImage = this.getNextImage()
        this.nextImage.inject(this.foreground);
        
        //this.background.fade('out'); hieronder met duration
        this.background.get('tween', {property: 'opacity', duration: 'long'}).start(0);
        this.setBackground.bind(this).delay(2000);
  },
  
  setBackground: function()
  {
      this.background.empty();
      this.nextImage.inject(this.background);
      this.background.setStyle('z-index','10');
      this.foreground.setStyle('z-index','30');
      this.background.fade('show');
  },
  
  getNextImage: function()
  {
        this.index++;
        if(this.index == this.numPhotos) this.index = 0;
        return this.photos[this.index];
  }
    
})

