﻿(function($) {
	$.scrollable_scrolls = new Array();
	$.scrollable_options = new Array();

	$.fn.scrollable_setScrollPosition = function(idx) {
		var obj = $.scrollable_scrolls[idx];
		var options = $.scrollable_options[idx];
		if (!obj) {
			return;
		}

		//alert('here with idx = ' + idx);
		var current_position = obj._scroll_position;
		var items = $(options.items, obj);
		if (current_position + options.window_size <= items.length) {
			var params = {};
			if (options.direction == 'rl') {
				var item = $(items.get(items.length - options.window_size - current_position));
				params.left = '-' + item.position().left + 'px';
			}
			else if (options.direction == 'tb') {
				var item = $(items.get(current_position));
				params.top = '-' + item.position().top + 'px';
			}
			else if (options.direction == 'bt') {
				var item = $(items.get(items.length - options.window_size - current_position));
				params.top = '-' + item.position().top + 'px';
			}
			else {
				var item = $(items.get(current_position));
				params.left = '-' + item.position().left + 'px';
			}

			if (current_position > 0) {
				$(obj).animate(params, options.speed, options.easing);
			}
			else {
				$(obj).animate(params, 1, options.easing);
			}

			obj._scroll_position = current_position + 1;
		}
		else {
			obj._scroll_position = 0;
		}
	};

	$.fn.scrollable = function(options) {
		var defaults = {
			direction: 'lr', // lr: left to right, rl: right to left, tb: top to bottom, bt: bottom to top
			duration: 1000, // duration of the visibility
			items: '> div', // item selector
			speed: 'normal',
			easing: 'swing',
			loop: true,
			window_size: 5
		};

		var options = $.extend(defaults, options);
		return this.each(function(obj) {
			var jObj = $(this);
			var idx = $.inArray(jObj, $.scrollable_scrolls);
			if (idx >= 0) {
				$.scrollable_scrolls[idx] = null;
				$.scrollable_options[idx] = null;
			}

			idx = $.scrollable_scrolls.length;
			$.scrollable_scrolls[idx] = jObj;
			$.scrollable_options[idx] = options;
			if (jObj._scroll_var) {
				clearInterval(jObj._scroll_var);
				jObj._scroll_var = null;
			}

			jObj._scroll_position = 0;
			jObj._scroll_var = setInterval('$.fn.scrollable_setScrollPosition(' + idx + ')', options.duration);
			return true;
		});
	};
})(jQuery);
