var contentElementWidth = 636;
var elementCount = 0;
var contentIndex = 1;
var imageIndex = 1;
var rotateTimeout;
var waitTime = 5000;
var animationTime = 500;
var captionWidth = 190; 
 
$(document).ready(function() {
	
	elementCount = $('.galleryListSet').children('li').length;
	//channelNumbersWidth = elementCount * 31;
	//channelPanelWidth = captionWidth + channelNumbersWidth; 
	
	$('.galleryListSet').width((elementCount * contentElementWidth)+(contentElementWidth*2));
	$('.galleryListSet').css({'position': 'relative', 'right':'636px'});
	$('.galleryListSet').append('<li style="background-image:url('+$('.galleryListSet li:eq(0)').children('span').html()+');">'+$('.galleryListSet li:eq(0)').html()+'</li>');
	$('.galleryListSet').prepend('<li style="background-image:url('+$('.galleryListSet li:eq('+(elementCount-1)+')').children('span').html()+');">'+$('.galleryListSet li:eq('+(elementCount-1)+')').html()+'</li>');
	
	$('.link-next').click(function(e) {
		e.preventDefault();
		//navNumber = $(this).html();
	    updateContent(imageIndex);
	});
	
	$('.link-prev').click(function(e) {
		e.preventDefault();
		//navNumber = $(this).html();
	    updateContent(imageIndex-2);
	});
    
    $('.gallery-box').css({display: 'block'});
	$('.gallery-box').animate({opacity: 1}, 1000, "swing", function() {
	    initGallery();
	});
});

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

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

function updateText(index) {
    var anchor = $('.galleryListSet li a:eq('+index+')');
    var newLink = $(anchor).attr('href');
    var newText = $(anchor).text();
    $('.gal-text-holder').html('<a href="'+newLink+'"><span>'+newText+'</span></a>');
}

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