/**

	----------------------------------------------------------------------------------------------------
	Accessible News Slider
	----------------------------------------------------------------------------------------------------
	
	Author:
	Brian Reindel
	
	Author URL:
	http://blog.reindel.com

	License:
	Unrestricted. This script is free for both personal and commercial use.

*/

jQuery.fn.accessNews = function(settings) {
	settings = jQuery.extend({
        speed : 'normal',
		slideBy : 2,
		auto: true,
		delay: 4000
    }, settings);
    return this.each(function() {
		jQuery.fn.accessNews.run(jQuery(this), settings);
    });
};
jQuery.fn.accessNews.run = function($this, settings) {
	var ul = jQuery('ul:eq(0)', $this);
	var li = ul.children();
	var interval_id = null;
	if(li.length > settings.slideBy) {
		var $next = jQuery('#next > a', $this);
		var $back = jQuery('#back > a', $this);
		var liWidth = jQuery(li[0]).width();
		var animating = false;
		ul.css('width', (li.length * liWidth));
		$next.click(function() {
			if (interval_id){ clearInterval(interval_id); }
			next_panel();
			return false;
		});
		$back.click(function() {
			if (interval_id){ clearInterval(interval_id); }
			previous_panel();
			return false;
		});
		
		if(settings.auto) {
			interval_id = setInterval(function(){ next_panel(); }, settings.delay);
		}
	}
	
	function next_panel() {
		if(!animating) {
			animating = true;

			next_lis=(parseInt(ul.css('width'))+(parseInt(ul.css('left'))-3*liWidth))/liWidth;
			if(settings.slideBy > next_lis && next_lis > 0) {
				settings.slideBy = next_lis;
			}
			
			offsetLeft = parseInt(ul.css('left')) - (liWidth * settings.slideBy);
			if(next_lis > 0) {

				ul.animate({
					left: offsetLeft
				}, settings.speed, function() {
					animating = false;
				});
			} else {
				animating = false;
				if (interval_id) {
					clearInterval(interval_id);
					interval_id = setInterval(function(){ previous_panel(); }, settings.delay);
				}
			}
		}
	}
	
	function previous_panel() {
		if(!animating) {
			animating = true;
			offsetRight = parseInt(ul.css('left')) + (liWidth * settings.slideBy);
			if(offsetRight + ul.width() <= ul.width()) {
				ul.animate({
					left: offsetRight
				}, settings.speed, function() {
					animating = false;
				});
			} else {
				animating = false;
				if (interval_id) {
					clearInterval(interval_id);
					interval_id = setInterval(function(){ next_panel(); }, settings.delay);
				}
			}
		}
	}
};

