var player;

$(document).ready(function() {
	/*var ev = new timetableListener(eventsData);
	ev.init();*/
	player = new SlideShow(data);
	player.init();
});

SlideShow = function(data) {
	var self = this;
	this.data = data;
	this.images = new ImagesMap(this);
	this.isOn = false;
	this.timeout = null;
	this.interval = 5000;
	this.autoStartInterval = 15000;
	this.current = -1;
	this.screen = $('#player_screen');
	this.previews;
	this.previewsInner = $('#player_previews_scroll div');
	this.icoWidth = 70;
	this.icoHeight = 36;
	this.icoMarginLeft = 10;
	this.scrollOpt = {
		'scrollbarHeight'	: 5,
		'scrollbarMargin'	: 0,
		'showArrows'		: false,
		'dragMinWidth'		: 53,
		'dragMaxWidth'		: 53,
		'reset'				: true
	};
	this.scrollOffset = ($('#player_previews').width() - self.icoWidth - self.icoMarginLeft)/2;
	this.scrollStep = 60;
	this.scrollTimeout = null;
	this.scrollInterval = 500;
	this.scrollIsOn = false;
	this.text = $('#player_text');
	this.isIE = navigator.appName.toLowerCase().indexOf('microsoft') > -1;
	this.cashImagesTimeout = null;
	this.cashImagesInterval = 100;
	this.loaderImg = '/images/ajax-loader.gif';
	
	/**
	* Инициализация
	*/
	this.init = function() {
		this.cashImages();
		this.start();
		$('#player_frame').click(function() {
			if (self.data[self.current]) window.location.href = self.data[self.current].url;
		});
	}
	
	/**
	* Загрузка изображений
	*/
	this.cashImages = function(indx) {
		var i = (isNaN(indx)) ? 0 : parseInt(indx, 10);
		
		if ((i >= 0)&&(i < this.data.length)) {
			var newImg = new Image();
			newImg.key = this.data[i].img;
			newImg.onload = function() {
				self.images.set(this.key, this);
			};
			newImg.src = this.data[i].img;
			
			var newIco = new Image();
			newIco.key = this.data[i].img;
			newIco.indx = i;
			newIco.onload = function() {
				self.images.set(this.key, this, true);
			};
			newIco.src = this.data[i].ico;
			
			if (i < this.data.length - 1) {
				clearTimeout(this.cashImagesTimeout);
				this.cashImagesTimeout = setTimeout(function() {
					self.cashImages(++i);
				}, this.cashImagesInterval);
			}
		}
	}
	
	/**
	* Запуск слайдшоу
	*/
	this.start = function() {
		this.isOn = true;
		this.next();
	}
	
	/**
	* Смена кадра
	*/
	this.next = function() {
		if (this.isOn) {
			var end = this.data.length;
			var start = (this.current < end - 1) ? this.current + 1 : 0;
			for (var i=start, l=end; i<l; i++) {
				if (this.images.ready(this.data[i].img)) {
					this.show(this.data[i]);
					break;
				}
			}
		
			clearTimeout(this.timeout);
			this.timeout = setTimeout(function() {
				self.next();
			}, this.interval);
		}
	}
	
	/**
	* Показ слайда
	*/
	this.show = function(data) {
		if (data != self.data[self.current]) {
			this.text.hide();
			this.screen.fadeOut('slow', function() {
				self.screen.css('background-image', 'url(' + self.images.get(data.img).src + ')');
				self.screen.fadeIn();
				self.text.html(data.text);
				if (self.isIE) self.text.show();
				else self.text.fadeIn();
				if (self.current >= 0) self.images.get(self.data[self.current].img, true).className = '';
				self.images.get(data.img, true).className = 'cur';
				self.current = self.images.get(data.img, true).indx;
			});
		}
	}
	
	/**
	* Добавление превьюшки
	*/
	this.addPreview = function(ico) {
		ico.onclick = function() {
			self.show(self.data[this.indx]);
			self.stop();
			if (self.images.imagesCount == self.data.length)  {
				self.previews.scrollTo(this.scrollTo);
			}
			clearTimeout(self.timeout);
			self.timeout = setTimeout(function() {
				self.start();
			}, self.autoStartInterval);
		};
		this.previewsInner.append(ico);
		if (this.images.imagesCount === 1) ico.style.marginLeft = '0';
		else ico.style.marginLeft = this.icoMarginLeft + 'px';
	}
	
	/**
	* Остановка слайдшоу
	*/
	this.stop = function() {
		this.isOn = false;
		clearTimeout(this.timeout);
	}
	
	/**
	* Подключение скроллинга
	*/
	this.enableScroll = function() {
		this.previews = $('#player_previews_scroll');
		this.previews.jScrollHorizontalPane(this.scrollOpt);
		this.previews = $('#player_previews_scroll')[0];
		var test = document.getElementById('player_prev');
		if (test == null) {
			var previewBox = $('#player_previews');
			var scrollPrev = $('<div id="player_prev"></div>');
			var scrollNext = $('<div id="player_next"></div>');
			previewBox.prepend(scrollNext).prepend(scrollPrev);
			scrollPrev.mouseover(function() {
				self.startScroll(-self.scrollStep);
			});
			scrollPrev.mouseout(function() {
				self.stopScroll();
			});
			scrollNext.mouseover(function() {
				self.startScroll(self.scrollStep);
			});
			scrollNext.mouseout(function() {
				self.stopScroll();
			});
		}
	}
	
	/**
	* Авто скроллинг
	*/
	this.autoScroll = function(step) {
		if (this.scrollIsOn && !isNaN(step)) {
			var leftStr = this.previews.style.left;
			var left = parseInt(leftStr.substring(0, leftStr.length - 2), 10);
			if (!isNaN(left)) {
				this.previews.scrollTo(-left + step);
				clearTimeout(this.scrollTimeout);
				this.scrollTimeout = setTimeout(function() {
					self.autoScroll(step);
				}, this.scrollInterval);
			}
		}
	}
	
	/**
	* Старт скроллинг
	*/
	this.startScroll = function(step) {
		this.scrollIsOn = true;
		this.autoScroll(step);
	}
	
	/**
	* Стоп скроллинг
	*/
	this.stopScroll = function() {
		this.scrollIsOn = false;
		clearTimeout(this.scrollTimeout);
	}
	
	/**
	* Загрузка нового набора картинок
	*/
	this.loadImages = function(newData) {
		this.stop();
		this.data = newData;
		this.current = -1;
		this.images = new ImagesMap(this);
		this.text.hide();
		this.screen.fadeOut('slow', function() {
			self.screen.show();
			var pScroll = $('<div id="player_previews_scroll"></div>');
			self.previewsInner = $('<div></div>');
			pScroll.append(self.previewsInner);
			$('#player_previews').empty().append(pScroll);
			self.showProgress();
			self.init();
		});
	}
	
	/**
	* Прогресс
	*/
	this.showProgress = function() {
		this.screen.css('background-image', 'url(' + self.loaderImg + ')');
	}

}

/**
* Хранилище изображений
*/
ImagesMap = function(player) {
	this.images = {};
	this.player = player;
	this.transparentGifURL = '../img/0.gif';
	this.imagesCount = 0;
	
	/**
	* Добавление изображения в коллекцию
	*/
	this.set = function(key, img, isIco) {
		//if (img instanceof Image) {
			if (key && ((typeof key).toLowerCase() == 'string') && (key.length > 0)) {
				if (!defined(this.images[key])) this.images[key] = {};
				var record = this.images[key];
				if (!!isIco) {
					record.ico = img;
					record.ready = defined(record.img);
				} else {
					record.img = img;
					record.ready = defined(record.ico);
				}
				if (record.ready) {
					this.imagesCount++;
					var ico = new Image(this.player.icoWidth, this.player.icoHeight);
					ico.src = this.transparentGifURL;
					ico.style.backgroundImage = 'url(' + record.ico.src + ')';
					ico.indx = record.ico.indx;
					ico.scrollTo = (this.imagesCount - 1)*(this.player.icoWidth + this.player.icoMarginLeft) - this.player.icoMarginLeft - this.player.scrollOffset;
					record.ico = ico;
					this.player.addPreview(ico);					
					if (this.imagesCount == this.player.data.length) this.player.enableScroll();
				}
				return true;
			} else return false;
		//} else return false;
	}
	
	/**
	* Проверка готовности данных
	*/
	this.ready = function(key) {
		if (key && ((typeof key).toLowerCase() == 'string') && (key.length > 0) && defined(this.images[key])) {
			return this.images[key].ready;
		} else return false;
	}
	
	/**
	* Возвращение картинки
	*/
	this.get = function(key, isIco) {
		return (!!isIco) ? this.images[key].ico : this.images[key].img;
	}
}