if (typeof(ASPERITY) == 'undefined') {
	ASPERITY	= {};
	ASPERITY.UI	= {};
}

ASPERITY.UI.Promo	= function()
{
	var scrollplane;
	var scroller;
	var totalitems = 0;
	var itemwidth = 0;
	var totalwidth = 0;
	var view = 0;
	
	var init	= function() {
		if ( $('#promo #scroller').length > 0 ) {
		$('#promo #scroller').wrapInner('<div id="scrollwindow"><div id="scrollplane"></div></div>');
		scrollplane = $('#scrollplane');
		scroller = $('#scroller');
		
		scroller
			.append('<a href="#" id="promo-prev" rel="previous"><img src="/img/promo-scroll-left.gif" alt="Previous" /></a>')
			.append('<a href="#" id="promo-next" rel="next"><img src="/img/promo-scroll-right.gif" alt="Next" /></a>');
			
		//$('#promo-next, #promo-prev').hide();
		
		$.get('/_ajax/promo/', {path: window.location.pathname}, function(data){
					
			$('#scrollplane ul').empty().append(data).after('<div class="clear"></div>');

			totalitems = scrollplane.find('li').length;
			var item = scrollplane.find('li:first');
			itemwidth = parseInt(item.outerWidth(true), 10);		
			totalwidth = (totalitems) * itemwidth;	
				
			if (totalwidth < 960) totalwidth = 960;	
			scrollplane.css('width', totalwidth+10);
									
			if (scrollplane.height() > 125) {
				$('#promo, #scroller, #scroller li').css('height', scrollplane.height());
			}
				
			$('#promo-next').click(function(e){
				e.preventDefault();
				var currentLeft = parseInt(scrollplane.css('left').replace('px', ''), 10);
				var newLeft = currentLeft - scroller.width();
				
				if ((0-totalwidth) >= newLeft) {
					newLeft = 0;
					view	= 0;
				}else{
					view++;
				}
				scrollplane.animate({left: newLeft});
			});
			
			
			$('#promo-prev').click(function(e){
				e.preventDefault();
				var currentLeft = parseInt(scrollplane.css('left').replace('px', ''), 10);
				var newLeft = currentLeft + scroller.width();
			
				if (newLeft > 0) {
					var adjustment = 0;
					if (totalitems % 4 == 0) adjustment = -1;
					newLeft = 0 - (Math.floor(totalitems / 4)+adjustment)*(itemwidth*4);
				}
						
				scrollplane.animate({left: newLeft});;
			});
			
		});
		
		/*
		scroller.hover(function(){
			$('#promo-next, #promo-prev').fadeIn();
		}, function(){
			$('#promo-next, #promo-prev').fadeOut();
		});
		*/
		}
		
	};
	
	return {
		init: init
	};
	
}();

jQuery(function($) { ASPERITY.UI.Promo.init(); });