/**
 * @file showroom.js
 * @author nikola.ivanov@cocomore.com
 */

var cocomore = cocomore || {};
cocomore.sr = cocomore.sr || {};

cocomore.sr.carousel = function($) {
  // store containers
  var _data =  [];
  
  // store timers, in case one day needed
  var _timers = [];
  
  // init carousels --> add slide timeouts
  var _init = function(selector) {
    $(selector).each(function (i, n) {
      // add reference to next img and make it circular
      var $els = $('div', n);
      $els.not(':first').hide().end().each(function (i, n) {
        $($els.get(i)).data('showroom-next', ((typeof $els.get(i + 1) == 'undefined') ? 0 : i + 1));
      });
      
      // Array.push() returns the next free index
      var id = _data.push(n);
      id--; 
      
      // set slide timers
      if ($els.length > 1) {
        _timers[id] = window.setInterval("cocomore.sr.carousel.slide('"+ id +"')", 5000);
      }
    });
  };
  
  // make the morph
  var _slide = function(id) {
    if (_data[id] != null) {
      var $els = $('div', _data[id]);
      $els.filter(':visible').fadeOut(function() { 
        $($els.get($(this).data('showroom-next'))).fadeIn();
      });
    }
  };
  
  return {
    init: _init,
    slide: _slide
  };
}(jQuery);

Drupal.behaviors.cocomore_sr_carousel = function(context) {
  cocomore.sr.carousel.init('div.showroom-screenshots');
};
