﻿(function($) {
	if (!$.scrollable) {
		$.scrollable = new Object();
		$.scrollable.scrolls = new Array();
		$.scrollable.options = new Array();
		$.scrollable.scroll_ids = new Array();
	}

	$.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.attr('vnh_scroller'), $.scrollable.scroll_ids);
			if (idx >= 0) {
				try {
					var oldInterval = $.scrollable.scrolls[idx]._scroll_var;
					if (oldInterval) {
						clearInterval(oldInterval);
					}
				}
				catch (e) { }
				$.scrollable.scrolls[idx] = null;
				$.scrollable.options[idx] = null;
				$.scrollable.scroll_ids[idx] = null;
			}

			idx = $.scrollable.scrolls.length;
			jObj.attr('vnh_scroller', idx + '');
			$.scrollable.scrolls[idx] = jObj;
			$.scrollable.options[idx] = options;
			$.scrollable.scroll_ids[idx] = idx + '';
			if (jObj._scroll_var) {
				clearInterval(jObj._scroll_var);
				jObj._scroll_var = null;
			}

			jObj._scroll_position = 0;
			jObj._scroll_var = setInterval('$j.fn.scrollable.setScrollPosition(' + idx + ')', options.duration);
			return true;
		});
	};

	$.fn.scrollable.setScrollPosition = function(idx) {
		var obj = $.scrollable.scrolls[idx];
		var options = $.scrollable.options[idx];
		if (!obj) {
			return;
		}

		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;
		}
	};
})(jQuery);