(function() { 

// QueryString parser
var QS = {
  
  parseQS: function() {
    this.items = {};
    var qs = location.search.substr(1).split('&');
    for(var i=0, pair; i<qs.length; i++) {
      pair = qs[i].split('=');
      this.items[pair[0]] = pair[1];
    }
  }, // parseQS
  
  get: function(k) {
    if(typeof this.items=='undefined') {
      this.parseQS();
    }
    return this.items[k];
  } // get

}; // QS

// Carousel
var Carousel = function(carousel, visible, playSpeed) {

  var that = this;

  this.running = null;
  this.playSpeed = 5000;
  this.lastVisible = 1;
  this.currentIndex = 1;
  this.lastIndex = 1;
  this.elemIndex = null;
  this.slideMoreDest = null;
  this.elemTotal = 1;
  this.state = { current: null, first: null, last: null };
  this.rotator = { shift: 0, interval: null };

  this.inner = { elem: null, elemWidth: 0 };

  this.nav = {};
  this.controls = {};
  this.slides = {};

  this.slideUrl = '';
  this.nextSlideReady = false;

  this.getSlides = function() {
	var elem = this.inner.elem;
	var slides = $(elem).find('.slide-entity');

	var count = slides.length;
	this.slides.last = $(slides[count-1]);

	if(count>0) {
	  var width = slides[0].offsetWidth;

	  // set inner width
	  elem.elemWidth = width * (count+1);
	  elem.style.width = elem.elemWidth + 'px';

	  // add ids just for the hell of it
	  for(var i=0; i<count; i++) {
		slides[i].setAttribute('id', 'item-' + (i+1));
	  }
	  this.slides.elemWidth = width;
	}
	this.slides.count = count;
	this.getNextSlide();
  }; // this.getSlides

  this.getNextSlide = function() {
	var getSlide = function(data, status) {
	  if(status==='success') {
		var elem = $(that.inner.elem);
		that.slides.last.after(data);

		var slides = elem.find('.slide-entity');
		that.slides.last = that.slides.last.next();
		var count = slides.length;
		that.slides.last.attr('id', 'item-' + count);

		elem.css( { 'width': count*that.slides.elemWidth } );
		that.nextSlideReady = true;
		that.slides.count = count;
	  }
	}; // getSlide 

	if(this.slides.count<this.elemTotal) {
	  this.lastIndex += 1;
	  $.get(this.slideUrl, { 'slide': this.lastIndex }, getSlide );
	}
  }; // this.getNextSlide

  this.activateCarouselNav = function(carousel, tag) {
	var controls = carousel.slideshow.find('.buttons ' + tag);
	var count = controls.length;
	if(count>0) {
	  for(var i=0, control, controlName; i<count; i++) {
		control = controls[i];
		control.style.display = 'block';
		controlName = control.innerHTML;
		this.controls[controlName] = control;
		if(controlName==='Play') {
		  $(control).click(function(e) {
			e.preventDefault();
			if(!that.running) {
			  $(that.controls.Next).click();
			}
			that.play();
		  });
		}
		else {
		  $(control).click(function(e) {
			e.preventDefault();
			if(typeof e.originalEvent!=='undefined') {
			  that.pause();
			}
			var v = this.innerHTML=='Previous' ? -1 : 1;
			this.slideMore = $('.slide-more');
			this.slideMore.fadeTo(100, 0);
			$('.viewAllRoomFurniture').fadeTo(100, 0);
			$('.dropdownContainer').fadeTo(100, 0);
			that.rotateCarousel(v);

			// queue up the next slide
			if(v>0) {
			  that.getNextSlide();
			}
		  }); // *control click
		}
	  }
	}
	this.rotator.shift = this.inner.elem.offsetLeft - this.slides.elemWidth;
  };  // this.activateCarouselNav

  this.rotateCarousel = function(v) {
	v = v ? v : 1;
	var rotator = this.rotator;

	if(!rotator.interval) {
	  var increment = v*25;
	  var elem = this.inner.elem;

	  var slides = this.slides.elems;
	  var first = slides[0];
	  var last = slides[slides.length-1];
	  var startPos = elem.offsetLeft;
	  // var shift = Math.abs(startPos - this.nav.elemWidth + this.slides.elemWidth);
	  var endPos = startPos + rotator.shift;

	  // shift left (previous)
	  if(increment<0) {
		elem.style.left = (startPos + endPos) + 'px';
		elem.insertBefore(last, first);
		endPos = startPos;
	  }

	  var shiftCarousel = function() {        
		var currentPos = elem.offsetLeft;
		if((increment>0 && currentPos<=endPos) || (increment<0 && currentPos>=endPos)) {
		  clearInterval(rotator.interval);
		  rotator.interval = null;
		  elem.style.left = startPos + 'px';
		  // shift right (next) 
		  if(increment>0) {
			elem.appendChild(first);
		  }
		  that.setCurrent();
		}
		else {
		  elem.style.left = (currentPos - increment) + 'px';
		}
	  }; // shiftCarousel

	  rotator.interval = setInterval(shiftCarousel, 5);
	}
  }; // this.rotateCarousel

  this.setCurrent = function() {
	var slides = $(this.inner.elem).find('.slide-entity');
	if(this.currentSlide) {
	  this.currentSlide.removeClass('current');
	}
	this.currentSlide = $(slides[this.lastVisible]);
	this.currentSlide.addClass('current');
	this.slides.elems = slides;
	
	$(this.slideMoreDest).html(this.currentSlide.find('.slide-more-source:first').html());
	this.slideMore = $('.slide-more');	
	this.slideMore.fadeTo('normal', 1);
	$('.viewAllRoomFurniture').fadeTo('normal', 1);
	$('.dropdownContainer').fadeTo('normal', 1);

	// set slideshow controller values
	var n = Number(this.currentSlide.attr('id').replace('item-' ,''));
	this.controls.Previous.href = this.pageUrl + '&slide=' + (n-1);
	this.controls.Next.href = this.pageUrl + '&slide=' + (n+1);
	this.controls.Play.href = this.pageUrl + '&slide=' + (n+1) + '&refresh=true';
	this.elemIndex.text(n);
	this.currentIndex = n;

  }; // this.setCurrent

  this.play = function() {
	var startCarousel = function() {
	  $(that.controls.Next).click();
	}; //startCarousel

	if(this.running) {
	  this.pause();
	}    
	else {
	  $(this.controls.Play).addClass('pause');
	  this.running = setInterval(startCarousel, this.playSpeed);
	}
  }; // this.play

  this.pause = function() {
	clearInterval(this.running);
	this.running = null;
	$(this.controls.Play).removeClass('pause');
  }; // this.pause

  this.autoStart = function() {
	var as = null;
	if(that.nextSlideReady) {
	   clearTimeout(as);
	   as = null;
	   that.play();
	 }
	 else {
	   as = setTimeout(that.autoStart, 100);
	 }
  }; // this.start

  this._init = function(carousel, visible, playSpeed) {
	visible = visible ? visible : 1;
	carousel.slideshow = $('.slideshow');
	if(carousel.slideshow.hasClass('piece-slideshow')) {
		this.pageUrl = '?categoryID=' + QS.get('categoryID');
		this.slideUrl = '/Services/pieceSlideshow.ashx' + this.pageUrl;
	}
	else {
		this.pageUrl = '?roomID=' + QS.get('roomID');
		this.slideUrl = '/Services/roomSlideshow.ashx' + this.pageUrl;
	}
	this.slideMoreDest = $('.slide-more-dest');
	this.elemIndex = $('.entityIndex');
	var totalElems = Number($('.entityTotal:first').text());
	this.elemTotal = isNaN(totalElems) ? 1 : totalElems;
	this.lastVisible = Math.floor(visible/2);
	this.inner.elem = $(carousel).find('.carousel-slides')[0];
	this.getSlides();
	if(this.slides.count>0) {
	  this.activateCarouselNav(carousel, 'a');
	  // var outerWidth = (this.slides.elemWidth * visible);
	  var outerWidth = 932; // JSK: setting this manually, because the calculator isn't functioning right in Safari
	  carousel.style.width = outerWidth + 'px';
	  this.setCurrent();
	  if(playSpeed) {
		this.playSpeed = playSpeed;
		this.autoStart();
	  }
	}
	$(carousel).removeClass('accessible');    
  }; // this._init 

  this._init(carousel, visible, playSpeed);

}; // CarouselObj

 
var activateCarousels = function() {
  var carouselHolder = {};
  var carousels = $('.carousel');
  for(var i=0, carouselsLen=carousels.length, carousel, visible; i<carouselsLen; i++) {
    carousel = carousels[i];
    visible = Number(carousel.className.replace(/.*visible-([1-9][0-9]?).*/, '$1'));
    visible = !(isNaN(visible)) ? visible : 1;
    var cID = carousel.id ? carousel.id : 'carousel-' + i;
    // playSpeed for use with auto-start
    // var playSpeed = 8000;
    carouselHolder[cID] = new Carousel(carousel, visible);
  }
  if(typeof window.LANE!=='undefined') {
  	window.LANE.carousels = carouselHolder;
  }
}; // activateCarousels

$(document).ready(function() {
  activateCarousels();
});

})();