var contentElementWidth = 460;
var elementCount = 0;
var contentIndex = 0;
var imageIndex = 0;
var rotateTimeout;
var irWaitTime = 5000;
var animationTime = 500;
var captionWidth = 290; 
 
$(document).ready(function() {
	
	elementCount = $('.imageGalleryListSet').children('li').length;
	$('.imageGalleryListSet li').each(function(i) {
	    if(i == 0) {
	        $('#irControls').append('<a href="#" class="selected">'+(i+1)+'</a>');
	    } else {
	        $('#irControls').append('<a href="#">'+(i+1)+'</a>');
	    }
	});
	
	
	var irNavWidth = $('#irControls a').size();
	//console.log(csNavWidth);
	var irControlsWidth = 16 * irNavWidth;
	$('#irControls').css({"width": irControlsWidth});	
	
	$('.imageGalleryListSet').width((elementCount * contentElementWidth)+460);
	$('.imageGalleryListSet').css({'position': 'relative'});
	$('.imageGalleryListSet').append('<li>'+$('.imageGalleryListSet li:eq(0)').html()+'</li>');
	$('#irControls a').click(function(e) {
		e.preventDefault();
		navNumber = $(this).html();
	    updateContent(navNumber - 1);
	});
    
    $('.imageRotatorWrapper').css({display: 'block'});
	$('.imageRotatorWrapper').animate({opacity: 1}, 1000, "swing", function() {
	    initGallery();
	});
	
});

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

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

function rotateImage() {
    imageIndex++;
	contentIndex = contentIndex == elementCount-1 ? 0 : contentIndex+1;
		
    $('#irControls a').removeClass('selected');
    $('#irControls a:eq('+contentIndex+')').addClass('selected');
    if(imageIndex == elementCount+1){
        imageIndex = 1;
        $('.imageGalleryListSet').css({right: '0px'});
    }
     $('.imageGalleryListSet').stop(true, true);
     $('.imageGalleryListSet').animate({right: (imageIndex*contentElementWidth)+'px'}, animationTime, "swing");
	rotateTimeout = setTimeout(function() {
		rotateImage();
	}, irWaitTime);
};
