/*
	jQuery Done Right plugin
	2008, Paul van Dam
*/

(function($){
$.fn.doneright = function (options) {
	
	var opt = {
		leftButtonId: 'drleft',
		rightButtonId: 'drright',
		spacing: 10
	};

	if (options) $.extend(opt, options);

	return this.each (function () {

		var self = $(this);
		var div = $('>div',self);
		var items = $('>div',div);
		var selfwidth = self.width();

		// determine start/end positions (last item in center)
		var startmargin = (selfwidth/2) - ($('div:first',div).width()/2);
		var endmargin = (selfwidth/2) - ($('div:last',div).width()/2);

		// position elements
		var left = startmargin;
		items.each(function(){
			var w = $(this).width();
			$(this).css('left',left+'px');
			left += w + opt.spacing;
		});

		var leftMax = left - selfwidth + endmargin - opt.spacing;

		// start with currentpage in center
		var cp = $('div#currentpage');
		var cp_width = cp.width();
		var cp_left = parseInt(cp.css('left'));
		var startleft = (-(cp_left-(selfwidth/2-cp_width/2)))+'px';
		div.css('left',startleft);

		// bind events to specified buttons
		$('#'+opt.leftButtonId).mousedown(moveLeft).mouseup(stopMove).mouseout(stopMove)
			.hover(function(){this.src = '/images/left2.gif';},function(){this.src = '/images/left1.gif';});
		$('#'+opt.rightButtonId).mousedown(moveRight).mouseup(stopMove).mouseout(stopMove)
			.hover(function(){this.src = '/images/right2.gif';},function(){this.src = '/images/right1.gif';});

		// bind events to scroll to clicked card and then go to link
		$('a',items.filter(':not(#currentpage)')).click(function(){
			var a = this;
			var l = parseInt($(this).parent().css('left'));
			var w = $(this).width();
			var x = -(l-((selfwidth/2)-(w/2)));
			div.animate({left:x+'px'},1000,function(){
				location.href = a.href;
			});
			return false;
		});

		function moveLeft () {
			var currentLeft = parseInt(div.css('left'));
			div.animate({left:'0px'},(-currentLeft)*3);
		}

		function moveRight () {
			var currentLeft = parseInt(div.css('left'));
			div.animate({left:-leftMax+'px'},(leftMax+currentLeft)*3);
		}

		function stopMove() {
			div.stop();
		}
	});
};
})(jQuery);
