// (c) 2008 Mediaproduct / www.mediaproduct.ru

var Carrousel = {

	image_width : 150,
	image_height: 70,
	element_name: "carrousel",
	element: null,
	list: null,
	list_length: 0,
	offset: 0,
	interval: null,

	init: function(list) {
		if (!document.getElementById || ![].push)
			return;
		Carrousel.element = document.getElementById(Carrousel.element_name);
		if (!Carrousel.element)
			return;
		Carrousel.element.innerHTML = '';
		Carrousel.list = [];
        var div, a, img;
        for (var i=0; i<list.length; i++) {
			div = document.createElement('div');
			with (div.style) {
				position = 'absolute';
				overflow = 'hidden';
				left = (i*Carrousel.image_width)+'px';
				top = '0px';
				width = Carrousel.image_width+'px';
				height = Carrousel.image_height+'px';

			}
			Carrousel.element.appendChild(div);

			a = document.createElement('a');
			a.href = list[i][0];
			a.onmouseover = function(e) { Carrousel.pause(e); }
			a.onmouseout = function(e) { Carrousel.resume(e); }
			div.appendChild(a);

			img = document.createElement('img');
			img.src = list[i][1];
			
			with (img.style) {
				width = Carrousel.image_width+'px';
				height = Carrousel.image_height+'px';
			}
			a.appendChild(img);

	        Carrousel.list.push(div);
	        Carrousel.list_length = Carrousel.list.length;
        }
		Carrousel.start();
	},

	start: function() {
		
		Carrousel.offset = 0;
        Carrousel.interval = setInterval(function() { Carrousel.step(); }, 20);
	},

	pause: function(e) {
        clearInterval(Carrousel.interval);
        Carrousel.interval = null;
	},

	resume: function(e) {
        Carrousel.interval = setInterval(function() { Carrousel.step(); }, 20);
	},

	step: function() {
		Carrousel.move(1);
	},

	swap_left: function() {
		Carrousel.list.push(Carrousel.list.shift());
	},

	swap_right: function() {
		Carrousel.list.unshift(Carrousel.list.pop());
	},

	move: function(offset) {
		if (Math.abs(offset)>=Carrousel.image_width) {
	        for (var i=0, count = Math.abs(Math.floor(offset/Carrousel.image_width)); i<count; i++) {
				if (offset<0)
					Carrousel.swap_left();
				else
					Carrousel.swap_right();
        	}
			offset = offset%Carrousel.image_width;
        }

        Carrousel.offset += offset;
        if (offset<0) {
	        if (Carrousel.offset <= -Carrousel.image_width) {
		        Carrousel.offset = 0;
				Carrousel.swap_left();
	        }
        } else {
	        if (Carrousel.offset > 0) {
		        Carrousel.offset = -Carrousel.image_width;
				Carrousel.swap_right();
	        }
        }

        for (var i=0; i<Carrousel.list_length; i++)
	        Carrousel.list[i].style.left = (i*Carrousel.image_width+Carrousel.offset)+"px";
	}
}

