var Slideshow = {};
Slideshow.Base = new Class({
  Implements: [Options, Events],
  options: {
    duration: 5000,
    slideClass: 'slideshow-slide',
    onSlideUpdated: function() {},
    onStatusUpdated: function() {}
  },
  
  initialize: function(options) {
    this.setOptions(options);
  },
  
  setup: function() {
    
    this.position = 0;
    this.playing = false;
    this.timer = null;
    
    if(this.frames.length <= 1)
    {
      return;
    }
    
    this.frameSetup();
    
    this.start();
  },
  
  start: function() {
    this.fireEvent('slideUpdated', this.position);
    this.playing = true;
    this.frameBeginEffect();
    this.fireEvent('statusUpdated', this.playing);
  },
  
  next: function() {
    this.goTo((this.position + 1));
  },
  
  back: function() {
    this.goTo((this.position - 1));
  },
  
  goTo: function(frame) {

    if(frame == this.position) return;
    
    this.clearShow();
    
    this.frameOverEffect();
        
    this.position = frame;
    
    if(this.position > (this.frames.length - 1)) {
      this.position = 0;
    }
    
    if(this.position < 0) {
      this.position = (this.frames.length - 1);
    }
    
    this.start();
    
  },
  
  frameSetup: function() {
    this.frames.set('opacity', 0);
    
    this.frames.each(function(frame) {
      frame.set('tween', { onComplete: 
        function() { this.frameFinished(); }.bind(this) });
    }.bind(this));
  },
  
  frameBeginEffect: function() {
    this.frames[this.position].tween('opacity', 1);  
  },
  
  frameOverEffect: function() {
    this.frames[this.position].tween('opacity', 0);
  },
  
  pause: function() {
    this.clearShow();
    this.fireEvent('statusUpdated', this.playing);
  },
  
  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);
    }
  }
});

Slideshow.BackSlider = new Class({
  Extends: Slideshow.Base,
  initialize: function(elm, options) {
    this.parent(options);
    
    this.setup(elm);
  },
  
  setup: function(elm, buffer) {
    
    this.frames = $$('.slide');
    
    this.parent();
    
    this.frames.each(function(elm) { elm.setStyle('display', 'block'); });
  },
    
  frameBeginEffect: function() {
    this.frames[this.position].tween('opacity', 1);  
  },
  
  frameOverEffect: function() {
    this.frames[this.position].tween('opacity', 0);    
  }
  
});

Slideshow.BackSlider.PreloadBGS = function(callback) {
  if(typeof callback == 'undefined') {
    var callback = function() {};
  }
  
  var slideRule = /\.slide\d+/;
  var images = [];
  Object.each(document.styleSheets, function(sheet) {
    
    var rules=sheet.cssRules? sheet.cssRules: sheet.rules
    
    if(!rules) {
      callback();return;
    }
    
    for (i=0; i<rules.length; i++) {
      
      if(slideRule.test(rules[i].selectorText.toLowerCase())) {
        
        var text = (rules[i].cssText) 
          ? rules[i].cssText 
          : rules[i].style.cssText;
          
        var src = text.match(/background-image: *url\(\"(.+)\"\)/);
        if(src && src.length > 0) {
          images.push(src[1]);
        }
      }
    }
  });
  
  var loader = new Element('div');
  loader.setStyle('display', 'none');
  loader.inject(document.body);
  
  var groupItems = [];
  images.each(function(src) {
    var i = new Image();
    groupItems.push($(i));
    i.src = src;
    $(i).inject(loader);
  });
  
  
  var group = new Group(groupItems);
  group.addEvent('load', function() {
    callback();
    loader.destroy();
  });
};

var FeatureTest = {
  defaultCallback: {
    success:function(){},
    fail:function(){}
  },
  backgroundSize: function(callbackObj) {
    var callback = Object.merge(Object.clone(this.defaultCallback), callbackObj);
    var d = FeatureTest.buildTestElm();
    d.addClass('feature-backgroundSize');
    var didit = d.getStyle('background-size');
    d.destroy();
    if(didit && didit!='') { callback.success();return; }
    callback.fail();
    return;
  },
  buildTestElm: function() {
    var d=new Element('div', {styles:{height:'1px','margin-top':'-1px'}});
    d.inject(document.body);
    return d;
  }
};

window.addEvent('domready', function() {
  
  // only called whenever the background size feature detect is not supported
  
  
  function updateSlideDimensions() {
    //var size = $$('.wrapper')[0].getDimensions();
    
    
    $$('.slide img').each(function(elm) {
      
      var slideInfo = JSON.decode(elm.retrieve('info'));
      
      if((window.getWidth() / window.getHeight()) < slideInfo.ratio) {
        elm.removeClass('full-page-wide');
        elm.setStyle('height', window.getHeight() + 'px');
      }
      else
      {
        elm.setStyle('height', 'auto');
        elm.addClass('full-page-wide');
      }
      
    });
  }
  

  new Slideshow.BackSlider();
  
  // Product Image Arrow Rollovers
  (function() {
      
    
    var image = $('bags');
    var arrow = $$('.arrow')[0];
      
    function processCoords(coords) {
      
      var pieces = coords.split(',').map(function(item) { 
        return item.trim().toInt(); 
      });
            
      var c =  {
        left: pieces[0], 
        top: pieces[1], 
        right: pieces[2], 
        bottom: pieces[3]
      };
      
      c.width = (c.right - c.left);
      c.height = (c.bottom - c.top);
      
      return c;
    }
      
    var last_class;  
    $$('.bag').addEvent('mouseover', function() {
      
      var areaCoords = processCoords(this.get('coords'));
      
      if(last_class != '') {
        arrow.removeClass(last_class);
      }
      
      last_class = this.get('rel');
      arrow.addClass(last_class);
      
      // the subtraction of 10 is to account for the size of the arrow itself
      arrow.setStyles({
        left: areaCoords.left + (((areaCoords.right - areaCoords.left)/ 2) - 10) + 'px',
        top: '-30px',
        display: 'block'
      });
      
    
    });
    
    $$('.bag').addEvent('mouseout', function() { arrow.setStyle('display', ''); });
    
  })();
  
  FeatureTest.backgroundSize({
    fail: function() { 
      
      
          
      
      $$('.slide').each(function(slide) {
        var img = slide.getStyle('background-image').match(/url\(([^\)]+)\)/);
        if(img && img.length > 0) {
          img = img[1].replace('"', '');
          img = img.replace('"', '');
          new Element('img', {src: img, alt:''}).inject(slide);
          slide.set('class', 'slide');
        }
      });
      
      $$('.slide img').each(function(elm) { 
        elm.store('info', JSON.encode({
          width: elm.getWidth(), 
          height: elm.getHeight(), 
          ratio: (elm.getWidth() / elm.getHeight())
        }));
      });
      
      updateSlideDimensions();
      
      window.addEvent('resize', function() {
        
        updateSlideDimensions();
        
        
      });
    }
  });
  
});

