/**
 * Product description.
 *
 * Requires Prototype 1.6.
 */

var SECS_FOR_CROSSFADE   = 0.5;
var gFetchExtraViewsPath = null;

function getCurrentImage() {
  return $('photoZone').select('img.photoView').find(function(img) { return img.visible(); });
}

function initCarousel() {
  var visibleThumbs = 4, thumbWidth = 68;
  var base = $('carousel');
  if (!base) return;
  var list = base.down('ul'), item = list.down('li');
  var width = list.select('li').length * thumbWidth;
  list.setStyle('width: ' + width + 'px; height: ' + item.getStyle('height') + ';');
  var carousel = new UI.Carousel(base, {
    previousButton: '.nav.previous', nextButton: '.nav.next', direction: 'horizontal'
  });
  gCar = carousel;
  base.select('.nav').invoke('observe', 'click', function(e) {
    e.stop();
    this.blur();
  });

  var container = $('photoZone');
  if (!container || !gFetchExtraViewsPath) return;
  
  function bindCarouselThumbnails() {
    var currentEffect = null;
    $('carousel').down('.container').observe('click', function(e) {
      var trigger = e.findElement('a');
      if (!trigger) return;
      e.stop();
      trigger.blur();
      if (currentEffect) return;
      var opts = { duration: SECS_FOR_CROSSFADE };
      var activeView = getCurrentImage();
      var newId = trigger.id.split('_').last();
      var otherView = $('view_' + newId);
      if (!activeView || !otherView || activeView == otherView) return;
      document.fire('ui:imageChanging', { id: newId });
      activeView.fade(opts);
      currentEffect = Effect.Appear(otherView, Object.extend(Object.clone(opts), {
        afterFinish: function() { currentEffect = null; }
      }));
    });
  }

  new Ajax.Updater(container, gFetchExtraViewsPath, {
    method: 'get', insertion: 'bottom', onSuccess: bindCarouselThumbnails
  });
} // initCarousel

document.observe('dom:loaded', function() {
  initCarousel();
  bindDateSync('edtReqArrival', 'edtReqDeparture', { offset: 1 });
  bindDateSync('edtReqDeparture', 'edtReqArrival', { offset: -1, onlyBlank: true });
});
