var current = 0;

function setImageUrl() {
    current = carousel.scrollable().getPageIndex() * 3;
    $('.items li img').slice(current, current + 3).each(function() {
        swapItemDescAndSrc($(this));
	});
}

function swapItemDescAndSrc(currentItem) {
    var itemImgLink = currentItem.attr('longdesc');
    currentItem.attr('src', itemImgLink);
   
}

function carouselSmallSetup(){
	var i = 1;
	$('.items li').each(function(){
		$(this).addClass('number' + i);
		i++;
	});
	var currentSpan = $('.media-wrapper p span.current');
	currentSpan.text('1');
}

function initCarouselSmallInfo() {

	var carouselConf = carousel.scrollable();
	var total = carouselConf.getSize();
	var totalSpan = $('.media-wrapper p span.total');
	var currentSpan = $('.media-wrapper p span.current');
	var mainImage = $('.media-wrapper img');
	var caption = $('.media-wrapper p span.caption');
    
	totalSpan.text(total);

	$('.items li').each(function(){
	    $(this).click(function(){
			
			thumb = $(this).children('img:first');
			src = thumb.attr('src');
			
			//jpgRemoved = src.substring(0, src.indexOf('.jpg'));								
			//largeSrc = jpgRemoved + '-large.jpg';													
			
			alt = thumb.attr('alt');
			posClass = $(this).attr('class');
			
			pos = parseInt(posClass.match(/\d+/)[0], 10);
			mainImage.attr('src', src);																
			caption.text(alt);
			currentSpan.text(pos); 
		});
	})
}

function initCarouselSmall (scrollableDiv){
	carousel = $(scrollableDiv);

	$('.items li img').each(function() {
	    var imgSrc = $(this).attr('src');
	    $(this).attr('longdesc', imgSrc);
	});
	
	$('.items li img').slice(4).each(function() { 
	    $(this).removeAttr('src');
	});

	$(carousel).scrollable({
	    vertical: true,
	    next: 'p.bottom',
	    prev: 'p.top',
	    size: 3,
	    onSeek: function() {
	        initCarouselSmallInfo();
	        setImageUrl();

	    }
	});
}

function renderCarousel (scrollableDiv){    
    if ($(scrollableDiv).length == 0) { return false; }
    return true;
}
	
$(function(){
	var scrollableDiv = '.news-feature .scrollable';
	if (!renderCarousel(scrollableDiv)) { return; }
	carouselSmallSetup();
	initCarouselSmall(scrollableDiv);
	initCarouselSmallInfo();
});

