var contentElementWidth = 820;
var elementCount = 0;
var contentIndex = 0;
var imageIndex = 1;
var rotateTimeout;
var waitTime = 8000;
var animationTime = 500;
var captionWidth = 190; 
var slideWrapperLength = 0;

 
$(document).ready(function() {
	
	elementCount = $('#slideWrapper').children('div').length;
	slideWrapperLength = contentElementWidth + (elementCount * contentElementWidth);
	$('#slideWrapper .slide').each(function(i) {
	    if(i == 0) {
	        $('#csControls').append('<a href="#" class="selected">'+(i+1)+'</a>');
	    } else {
	        $('#csControls').append('<a href="#">'+(i+1)+'</a>');
	    }
	});
	
	var csNavWidth = $('#csControls a').size();
	var csControlsWidth = 14 * csNavWidth;
	$('#csControls').css({"width": csControlsWidth});	
	
	$('#slideWrapper').width((elementCount * (contentElementWidth+1))+1700);
	$('#slideWrapper').css({'position': 'relative', 'right': contentElementWidth});
	$('#slideWrapper').append('<div class="slide generated-slide">'+$('#slideWrapper div:eq(0)').html()+'</div>');
	$('#slideWrapper').prepend('<div class="slide generated-slide">'+$('#slideWrapper div:eq('+(elementCount-1)+')').html()+'</div>');
	$('#csControls a').click(function(e) {
		e.preventDefault();
		navNumber = $(this).html();
	    updateContent(navNumber);
	});
    
    $('#csCanvas').css({display: 'block'});
	/*$('#csCanvas').animate({opacity: 1}, 1000, "easeOutExpo", function() {
	    
	});*/
	setTimeout('initGallery()' , 1000)
	
	var browserName=navigator.appName; 
	var browserVer=parseInt(navigator.appVersion); 
	if ((browserName!="Microsoft Internet Explorer" && browserVer!=6)) {
		$("#slideWrapper").touchwipe({
		    wipeLeft: function() {
		    	updateContent(imageIndex + 1);
		    },
		    wipeRight: function() {
		    	updateContent(imageIndex - 1);
		    },
		    min_move_x: 20,
		    preventDefaultEvents: true
		}); 
	}
});

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

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

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


