var contentElementWidth = 639;
var elementCount = 0;
var contentIndex = 0;
var imageIndex = 0;
var rotateTimeout;
var waitTime = 5000;
var animationTime = 500;
var captionWidth = 320; 
 
$(document).ready(function() {
	
	elementCount = $('.galleryListSet').children('li').length;
	channelNumbersWidth = elementCount * 31;
	channelPanelWidth = captionWidth + channelNumbersWidth; 
	
	$('.galleryListSet').width((elementCount * contentElementWidth)+702);
	$('.galleryListSet').css({'position': 'relative'});
	$('.galleryListSet').append('<li>'+$('.galleryListSet li:eq(0)').html()+'</li>');
	
	$('.channelNumbers a').click(function(e) {
		e.preventDefault();
		navNumber = $(this).html();
	    updateContent(navNumber - 1);
	});
    
    $('.channelSelectorWrapper').css({display: 'block'});
	$('.channelSelectorWrapper').animate({opacity: 1}, 1000, "swing", function() {
	    initGallery();
	});
});

function initGallery() {
	rotateTimeout = setTimeout(function() {
		rotateImage();
	}, waitTime);
};

function updateContent(index) {
    imageIndex = index-1;
    contentIndex = index-1;
    clearTimeout(rotateTimeout);
    rotateImage();
}

function updateText(index) {
    var anchor = $('.galleryListSet li a:eq('+index+')');
    var newLink = $(anchor).attr('href');
    $('.channelBody h2').html($(anchor).attr('title'));
    $('.channelBody p').html($('img', anchor).attr('alt'));
    $('.csFeatureImage img').attr('src', 'admin-resources/image-tools.php?w=83&h=77&c=1&e=0&src=' + $('.thumbSrc', anchor).html());
    $('.channelNumbers a').removeClass('selected');
    $('.csViewMoreBtn').attr('href', newLink);
    $('.csFeatureImage a').attr('href', newLink);
    $('.channelNumbers a:eq('+index+')').addClass('selected');
}

function rotateImage() {
    imageIndex++;
	contentIndex = contentIndex == elementCount-1 ? 0 : contentIndex+1;	
    if(imageIndex == elementCount+1){
        imageIndex = 1;
        $('.galleryListSet').css({right: '0px'});
    }
     $('.galleryListSet').stop(true, true);
     $('.galleryListSet').animate({right: (imageIndex*contentElementWidth)+'px'}, animationTime, "swing");
	 rotateTimeout = setTimeout(function() {
		rotateImage();
	}, waitTime); 
	updateText(contentIndex);
};
