$(document).ready(function() {

	var totWidth = 0;
	var positions = new Array();
	var photoWidths = new Array();
	var currentPos = 0;
	var changeEvery = 15;

	$('#slides .slide').each(function(i) {

		photoWidths[i] = $(this).width();
		positions[i] = totWidth;
		totWidth += $(this).width();

		if (!$(this).width()) {
			alert("Please, fill in width & height for all your images!");
			return false;
		}

	});

	$('#slides').width(totWidth);

	function autoAdvance() {
		currentPos++;
		if (currentPos > (positions.length - 1)) currentPos = 0;
		scroll();
	}

	var itvl = setInterval(function() { autoAdvance() }, changeEvery * 1000);

	$("#galleryPrevious").click(function() {
		currentPos--;
		if (currentPos < 0) currentPos = positions.length - 1;
		scroll();
		clearInterval(itvl);
	});

	$("#galleryNext").click(function() {
		currentPos++;
		if (currentPos > (positions.length - 1)) currentPos = 0;
		scroll();
		clearInterval(itvl);
	});

	function scroll() {
		var offset;
		if (currentPos == 0) {
			$('#slides').stop().animate({ marginLeft: -(positions[currentPos]) + 'px' }, 450);
		} else {
			if (photoWidths[currentPos] != 920) {
				if (currentPos == (positions.length - 1)) {
					offset = (920 - photoWidths[currentPos]);
				} else {
					offset = (920 - photoWidths[currentPos]) / 2;
				}
				$('#slides').stop().animate({ marginLeft: -(positions[currentPos] - offset) + 'px' }, 450);
			} else {
				$('#slides').stop().animate({ marginLeft: -positions[currentPos] + 'px' }, 450);
			}
		}
	}
});


