var carouselInterval = null;
var carouselIntervalCancel = false;
var msCarouselInterval = 6000;
$(document).ready(function() {

  // assign variables that do not rely on jquery.cycle
  carouselNav = $('#carousel #nav ul');
  navItemWidth = 147; // width + padding + margin + borders
  
  $('#carousel').fadeIn(300);

  $('#carousel').cycle({
      slideExpr: '.slide',
      fx: 'scrollHorz',
      speed: 500,
      timeout: 0,
      pager: carouselNav,
      pagerAnchorBuilder: carouselAnchorBuilder,
      after: resetPlayVideoOverlay
  });
	
	$('#carousel').hover (
		function () {
			carouselAutoplayPause ();
		},
		function () {
			carouselAutoplayStart ();
		}
	);

  // assign variables that rely on jquery.cycle
  navSize = carouselNav.find('li').size(); // .find() checks the dom after jquery.cycle loads, children().size() will not
  navWidth = (carouselNav.children().size() * navItemWidth) - (4 * navItemWidth); // subtract the visible slides from the total length

  $('#prev-slide').click(function() {
	carouselAutoplayStop ()
    carouselNavPrev();
  });

  $('#next-slide').click(function() {
	carouselAutoplayStop ()
    carouselNavNext();
  });

  // Swipe gestures for touch devices
  $("#carousel #slides").touchwipe({
     wipeLeft: function() { $('#carousel').cycle('next') },
     wipeRight: function() { $('#carousel').cycle('prev') },
     min_move_x: 20,
     min_move_y: 20,
     preventDefaultEvents: true
  });

  $("#carousel #nav").touchwipe({
     wipeLeft: function() {
		carouselNavNext();
	},
     wipeRight: function() {
		carouselNavPrev();
	},
     min_move_x: 20,
     min_move_y: 20,
     preventDefaultEvents: true
  });

  $('.play-video-overlay').live('click', function(){
	carouselAutoplayStop ();
    targetvideo = $(this).attr('rel');
    $(this).hide();
    $(this).next('a').children('img').hide();
	$(this).next('a').next('.figcaption').hide();
    // $(this).next('img').hide();
    // $(this).next('img').next('div').hide();
    jwplayer(targetvideo).play();
  });
  
  carouselAutoplayStart ();
});

function carouselAnchorBuilder(idx, slide){
  return $('li:eq(' + (idx) + ') a', carouselNav)
}

function carouselNavNext(){
  $('#prev-slide').show();
  if (carouselNav.position().left > -navWidth) {
    carouselNav.stop(false, true).animate({left : "-=" + navItemWidth + "px"}, "medium", function() {
      if (carouselNav.position().left <= -navWidth) {
        $('#next-slide').hide();
      };
    });
    if (carouselNav.position().left <= -navWidth) {
      carouselNav.stop(false,true).animate({left : "-" + navWidth + "px"}, "slow")
    }
  };
}

function carouselNavPrev(){
  $('#next-slide').show();
  if (carouselNav.position().left < 0) {
    carouselNav.stop(false, true).animate({ left : "+=" + navItemWidth + "px" }, 'medium', function() {
      if (carouselNav.position().left >= 0) {
        $('#prev-slide').hide();
      }
    });
    if (carouselNav.position().left >= 0) {
      carouselNav.stop(false, true).animate({ left : "0px" }, "slow")
    }
  };
}

function resetPlayVideoOverlay() {
  $('#slides .play-video-overlay').show();
  $('#slides img').show();
  $('#slides .figcaption').show();
  if (jwplayer() != null) jwplayer().stop();
}

function hidePlayVideoOverlay() {
  $('#slides .play-video-overlay').hide();
  $('#slides img').hide();
  $('#slides .figcaption').hide();
}

function carouselNextSlide () {
	var nav = $('#nav');
	var ul = $('#nav ul');
	var ulPos = $(ul).position ();
	var navPos = $(nav).position ();
	var navLeft = navPos.left;
	var navRight = navPos.left + $(nav).width();
	var slides = $(ul).children ();
	var ctSlides = $(slides).length;
	if (ctSlides == 0)
		return;
	var slideWidth = $(slides [0]).width ();
	var ixCurrent = -1;
	$(slides).each (function (ix, item) {
		if ($(this).hasClass ('activeSlide'))
			ixCurrent = ix;
	});
	var ixNext = ixCurrent + 1;
	if (ixNext >= ctSlides)
		ixNext = 0;
	var newLeft = 0;
	//dbgCarousel ('ctSlides: ' + ctSlides + ', ixCurrent: ' + ixCurrent + ', ixNext = ' + ixNext);
	if (ixNext > 0) {
		var nextPos = $(slides [ixNext]).position ();
		var nextLeft = nextPos.left + ulPos.left;
		newLeft = parseInt ($(ul).css ('left'));
		//dbgCarousel ('nextLeft: ' + nextLeft + ', navRight: ' + navRight);
		if (nextLeft >= navRight) {
			// go to the next page to the right
			newLeft = (slideWidth * ixNext) * -1;
		}
	}
	
	$(ul).filter(':not(:animated)').animate ({left: newLeft + 'px'}, 400, function () {
		$('#carousel').cycle ('next');
		if (newLeft < 0)
			$('#prev-slide').show();
		else
			$('#prev-slide').hide();
		var lastPos = $(slides [ctSlides-1]).position ();
		var newRight = newLeft + lastPos.left + slideWidth;
		dbgCarousel ('newLeft: ' + newLeft + ', newRight: ' + newRight + ', navRight: ' + navRight);
		if (newRight > navRight)
			$('#next-slide').show();
		else
			$('#next-slide').hide();
	});
}
function carouselAutoplayStart () {
	if (!carouselIntervalCancel)
		carouselInterval = setInterval(carouselNextSlide, msCarouselInterval);
}
function carouselAutoplayPause () {
	if (!carouselIntervalCancel)
		carouselInterval = clearInterval (carouselInterval);
}
function carouselAutoplayStop () {
	carouselInterval = clearInterval (carouselInterval);
	carouselIntervalCancel = true;
}
function carouselAutoplayReset () {
	carouselIntervalCancel = false;
	carouselInterval = setInterval(carouselNextSlide, msCarouselInterval);
}
function dbgCarousel (msg) {
	if (window.console && window.console.log)
		window.console.log (msg);
}

