/* hscroll - jQuery plugin 1.1
 * Revision: $Id: jquery.hscroll.js,v 1.5 2011/04/11 11:59:30 dedukhin Exp $
 */

(function($) {
	function tpl(tmpl, data) { // very simple templating system
		tmpl = tmpl.replace(/({{[^}]+}})/g, function(r) {
			r = r.replace(/[{}]/g, '');
			return data[r] ? data[r] : '';
		});
		return tmpl;
	};
	$.fn.hscroll = function(opts){
		opts = $.extend({
			visible: 2, // just initial value
			keep_visible: false, // whether plugin should keep initial visible items count or should increase for wide screens
			scrollby: 1,
			b_left_class: 'prev',
			b_right_class: 'next',
			data: [],
			tmpl: ''
		}, opts);
		return this.each(function() {
			var $scrollpane = $(this);
			var $b_left = $('.' + opts.b_left_class, $scrollpane.parent());
			var $b_right = $('.' + opts.b_right_class, $scrollpane.parent());
			var idx = 0;
			var $elms = $('li', $scrollpane);
			var elm_width = $elms.first().width();
			var elems_count = opts.data.length;
			var visible = opts.visible;
			var started = 0;

			function start() { // used once to fill in all elements
				var str = '';
				for(var i=0; i<opts.data.length; i++) {
					str += tpl(opts.tmpl, opts.data[i]);
				}
				$scrollpane.html(str);
				$elms = $('li', $scrollpane);
			}

			$b_left.click(function(e) {
				$(this).blur();
				move(-1);
				return false;
			});
			$b_right.click(function(e) {
				$(this).blur();
				move(1);
				return false;
			});
			var move = function(to) {
				if(!started && to) { // we init elements only at the first time and if to != 0 (it is equal to 0 during init and resize)
					start();
					started = 1;
				}
				if(to > 0) { // moving right
					++idx;
				} else if(to < 0) { // moving left
					--idx;
				}
				if(idx <= 0) {
					idx = 0;
					$b_left.addClass('disabled');
				} else if(idx > 0) {
					$b_left.removeClass('disabled');
				}
				if(idx >= elems_count - visible) {
					idx = elems_count - visible;
					$b_right.addClass('disabled');
				} else {
					$b_right.removeClass('disabled');
				}
				if(elems_count <= visible) {
					$b_left.addClass('disabled');
					$b_right.addClass('disabled');
				}
				$elms.each(function(i) {
					var d = '';
					if(i < idx || i > idx + visible - 1) d = 'none';
					$(this).css({'display': d, 'width': (Math.floor(100 / visible) - 1) + '%'});
				});
			};
			if(!opts.keep_visible) {
				$(window).resize(function() {
					var cnt = Math.round($scrollpane.width() / elm_width);
					if(cnt > visible && cnt <= elems_count || cnt < visible && cnt >= opts.visible) {
						visible = cnt;
					}
					move(0);
				});
			}
			move(0); // disable apropriate arrow
		});
	};
})(jQuery);

