dojo.require("dijit.form.Button");

dojo.addOnLoad(function() {
	var tWidth = initSlideshow();
	dojo.style('Slideshow', 'width', tWidth);
	setInterval(nextSlide, 5000);
});

// Get this out of the global namespace
var theShow = new Array();

function initSlideshow() {
	// Initialize total widths and margins
	var tWidth		= 0;
	var tMargins	= 0;
	var totalWidth	= 0;
	var imageHeight	= 0;

	// Cycle through all images and get the width and add them all up, including the right margin.
	theShow = dojo.query('#Slideshow div').forEach(function(node, index, arr) {
		tWidth += dojo.style(node, 'width');
		tMargins += dojo.style(node, 'marginRight');
		imageHeight = dojo.style(node, 'height');
		if(imageHeight <= 300) {
			var diff = (dojo.style('Slideshow', 'height') - imageHeight) / 2;
			dojo.style(node, 'marginTop', diff + 'px');
		}
	});

	// Make the last slide to the second slide and the second-to-last slide to the first slide.
	// There must be a more eloquent structure than brute force.
	var secondSlide = dojo.query(theShow[theShow.length - 1]).orphan();
	dojo.query('#Slideshow').adopt(secondSlide, 1);
	theShow.unshift(theShow.pop());
	var firstSlide = dojo.query(theShow[theShow.length - 1]).orphan();
	theShow.unshift(theShow.pop());
	dojo.query('#Slideshow').adopt(firstSlide, 	1);

	// Set the full length of the Slideshow div
	totalWidth = tWidth + tMargins - dojo.style('Slideshow', 'paddingLeft');
	dojo.style('Slideshow', 'width', totalWidth - 200 + 'px');
	var fullLength = dojo.style(theShow[0], 'width') + dojo.style(theShow[0], 'marginRight') + dojo.style(theShow[1], 'width') + dojo.style(theShow[1], 'marginRight') + (dojo.style(theShow[2], 'width') / 2);
	var viewport = dojo.style('Viewport', 'width');
	var offset = fullLength - (viewport / 2);
	dojo.style('Slideshow', 'left', (-offset - dojo.style('Slideshow', 'paddingLeft')) + 'px');
}

function nextSlide() {
	var slideshow = dojo.byId('Slideshow');
	var zeroOffset = dojo.style(theShow[0], 'width') + dojo.style(theShow[0], "marginRight") + dojo.style('Slideshow', 'paddingLeft');
	// How much do I need to move to center the next image?	
	var distance = (dojo.style(theShow[2], 'width') / 2) + dojo.style(theShow[2], "marginRight") + (dojo.style(theShow[3], 'width') / 2);
	var newPadding = zeroOffset - distance;
	var firstSlide = dojo.query(theShow[0]).orphan();
	theShow.push(theShow.shift());
	dojo.query('#Slideshow').adopt(firstSlide, 'last');
	dojo.style(dojo.byId('Slideshow'), "paddingLeft", zeroOffset + 'px');
	dojo.animateProperty({
		node: slideshow,
		duration: 500,
		properties: {
			paddingLeft: newPadding
		}
	}).play();
}
