var sliderDelay = 7000;

var position = 0;
var LEFT = true; var RIGHT = false;
var currentDirection = LEFT;
var intervalID = 0;
var enabledOpacity = '1.0';
var disabledOpacity = '0.3';
var width = 640; var height = 100;

function slideView(direction) {
	var size = $('#content div').outerWidth();
	var num = $('#content div').length - 1;
	if (((position >= 0) && (direction == RIGHT)) || ((position <= size * -1 * num) && (direction == LEFT))) return false;
	position += (direction) ? size * -1 : size;

	if (position >= 0)
		$('#leftControl')
					.css("cursor", "default")
					.animate({ opacity: disabledOpacity })
					; else
		$('#leftControl')
					.css("cursor", "pointer")
					.animate({ opacity: enabledOpacity })
				;
	if (position <= size * -1 * num)
		$('#rightControl')
					.css("cursor", "default")
					.animate({ opacity: disabledOpacity })
					; else
		$('#rightControl')
					.css("cursor", "pointer")
					.animate({ opacity: enabledOpacity })
					;
	$('#content').animate({ left: position.toString() + "px" });
	return true;
}

function autoSlide() {
	if (slideView(currentDirection) == false) currentDirection = !currentDirection;
}

$(function() {
	$('#newsAndEventsWidget').prepend('<div id="leftControl"></div>').append('<div id="rightControl"></div>');
	$('#content').empty().load("/news/ .newsItem",
				function() {
					$('#content h2').remove();
					$('#content p br').replaceWith('&nbsp;');
					//$('#content div:even').css("background", "#E9EEF5").css("height", "300px");

					$('#content').css("width", ($('#content div').length * $('#content div').outerWidth()+30) + "px");
					$('#leftControl').animate({ opacity: '0.3' });

					// Fixing the src paths for the images contained in the news items
					$('#content img').each(function() {
						var src = $(this).attr('src').replace('http://www.harrow.ac.uk/', "");
						src = 'http://www.harrow.ac.uk/news/' + src;
						$(this).attr('src', src);
					});

					// Fixing the link paths
					$('#content a').each(function() {
						var href = $(this).attr('href').replace('http://www.harrow.ac.uk/', "");
						href = 'http://www.harrow.ac.uk/news/' + href;
						$(this).attr('href', href);
					});
					
					//$('#content').append('<div class="newsItem">&nbsp;</div>');

					// Creating the buttons for sliding left and right
					$('#leftControl').css('height', height).click(function() {
						slideView(RIGHT);
						clearInterval(intervalID);
					});
					$('#rightControl').css('height', height).click(function() {
						slideView(LEFT);
						clearInterval(intervalID);
					});
				});

	$('#news_and_events_widget').click(function() { clearInterval(intervalID); });
	intervalID = setInterval("autoSlide()", sliderDelay);
});
