$(document).ready(function() {
	$('.news_panel').newsPanel();
});

$.fn.newsPanel = function() {
	$(this).each(function() {
		var buttonUp = $(this).find('.news_button_up');
		var buttonDown = $(this).find('.news_button_down');
		var ul = $(this).find('ul');
		var height = ul.height();
		var totalHeight = 0;
		ul.find('li').each(function() { 
			totalHeight += $(this).outerHeight();
		});
		
		$(this).find('.news_button_up, .news_button_down').mousedown(function(e) {
			if (!$(this).find('a').hasClass('inactive')) {
				$(this).find('a').removeClass().addClass('clicked');
			}
		});
		
		$(this).find('.news_button_up, .news_button_down').hover(function() {
			if (!$(this).find('a').hasClass('inactive')) {
				$(this).find('a').removeClass().addClass('hover');
			}
		}, function() {
			if (!$(this).find('a').hasClass('inactive')) {
				$(this).find('a').removeClass().addClass('normal');
			}
		});
		
		var scrollCallback = function() {
			var scrollTop = ul.attr('scrollTop');
			if (scrollTop == 0) {
				buttonUp.find('a').removeClass().addClass('inactive');
			} else {
				if (buttonUp.find('a').hasClass('inactive')) {
					buttonUp.find('a').removeClass().addClass('normal');
				}
			}
			if (scrollTop >= totalHeight - height) {
				buttonDown.find('a').removeClass().addClass('inactive');
			} else {
				if (buttonDown.find('a').hasClass('inactive')) {
					buttonDown.find('a').removeClass().addClass('normal');
				}
			}
		};
		
		buttonUp.click(function() {
			if (!$(this).find('a').hasClass('inactive')) {
				var scrollTop = ul.attr('scrollTop');
				ul.stop().animate({ scrollTop: scrollTop - height }, 400, scrollCallback);
				$(this).find('a').removeClass().addClass('hover');
			}
			return false;
		});
		buttonDown.click(function() {
			if (!$(this).find('a').hasClass('inactive')) {
				var scrollTop = ul.attr('scrollTop');
				ul.stop().animate({ scrollTop: scrollTop + height }, 400, scrollCallback);
				$(this).find('a').removeClass().addClass('hover');
			}
			return false;
		});
	});
};
