﻿
$('document').ready( function(){
	
	$("img[rel]").each(function(){
		
		var url = $(this).attr("rel");				
		$(this).wrap('<a rel="gallery" href="' + url + '"></a>');
		
	})
	
	$("a[rel]").fancybox({
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'titlePosition' 	: 'over',
		'titleFormat'       : function(title, currentArray, currentIndex, currentOpts) {
		    return '<span id="fancybox-title-over">Image ' +  (currentIndex + 1) + ' / ' + currentArray.length + '</span>';
		}
	});
	Gallery.init();
	
})

var Gallery = new function()
{
	
	this.image_size = 960;
	this.curent = 0;
	this.count = 3;
	
	this.slide_time = 500;
	this.title_speed = 100;
	
	this.busy = false;
	
	this.leftbutton = 'div#btn_left';
	this.rightbutton = 'div#btn_right';
	this.container = 'ul#container';
	this.title_block = 'div#gallery_title';
	this.image_list = 'ul#container';
	
	this.event = 'div.event';
	this.event_title = 'img';
	this.event_title = 'div.title';
	
	this.data = Array();
	this.events = Array();

	this.title = '';
	this.postion = 0;
	
	this.injected = false;
	this.curent_event;
	this.loadedImages = 0 ;
	
	
	// Возвращает текущий объект
	this.curentObj = function()
	{
		return this.data[this.curent];
	}

	this.curentObj = function()
	{
		return this.data[this.curent];
	}
	
	// Производит инъекцию картинки и прокрутку к ней
	this.inject = function(event){
		
		
		if (this.injected | this.busy | this.curent_event == event.id) return;

		// Хак на случай если индектируемый эвент уже есть в слайдере
		if (this.events[$(event).children("a").children("img").attr('eventid')] != undefined)
		{
			if (this.curent == this.events[$(event).children("a").children("img").attr('eventid')]) return;
			this.curent_before_inject = this.curent;
			this.slideTo(this.events[$(event).children("a").children("img").attr('eventid')], 500);
			this.injected = true;
			return;
		}
		
		this.injected = true;
		
		this.curent_event = event.id;
		
		this.curent_before_inject = this.curent;
		
		var obj = new Object;
		obj.title = $(event).children("a").children("img").attr('title');
		obj.image = $(event).children("a").children("img").attr('rel');
		obj.position = 4
		
 		this.data[this.count()]  = obj;
		
		$("img#event_banner").attr('src',obj.image);

		this.slideTo(this.count());

		
	}
	
	
	// Производит откат к предыдущей картинке и удаление добавленной
	this.reject = function(){
		
		if (!this.injected | this.busy) return;
		
		this.slideTo(this.curent_before_inject);
		this.injected = false;	
		this.curent_event = -1;
		
	}

	
	this.count = function(){
		return this.data.length -1;
	}
	
	this.init = function()
	{
		if($(this.image_list).attr('id') == null) return;
		
		this.prepareGui();
		
		this.startLoading();
		
		
	}

	// Запустить загрузку изображений
	this.startLoading = function ()
	{
		this.beforeLoadAnimation();

		$.getJSON('/ajax/gallery', this.finishLoading);
		
	}
	
	// Запускается по окончании загркузки
	this.finishLoading = function(data)
	{
		
		Gallery.load(data)
		
	}
	
	// Загрузка списка изображений
	this.load = function(data)
	{
		
		
		this.data = data;
		
		
		
		for (i =0;i<this.count();i++)
		{	
			if (this.data[i].eventid != undefined){
				this.events[this.data[i].eventid] = i;
			}
			
			$('<li><img class="banner" rel="' + i + '" onload="Gallery.imageLoaded();" src="' + this.data[i].image + '" id="banner_' + i + '" /></li>').appendTo(this.image_list);
			
			if (this.data[i].url && this.data[i].url != ""){
				$("img#banner_" + i).css("cursor","pointer");
				$("img#banner_" + i).bind("click", function(){
					
					window.location.href = Gallery.data[$(this).attr('rel')].url;
				});
			}
			
		}
		$('<li><img id="event_banner" class="banner" src="" /></li>').appendTo(this.image_list);
		
		
	}
	
	// Счетчик загруженных изображений
	this.imageLoaded = function(event){
		
		this.loadedImages = this.loadedImages + 1;
		
		$(this.title_block).html("Загрузка " + this.loadedImages + " из " + this.count() + "...");
		
		if (this.loadedImages == this.count()){
			this.afterLoadAnimation();
		}
		
		
	}
	
	// Анимация перед загркузкой
	this.beforeLoadAnimation = function()
	{
		$(this.container).hide();
		$(this.container).fadeTo(0,0);
	}
	
	// Анимация после загрузки
	this.afterLoadAnimation = function()
	{
		$(this.container).show();
		$(this.container).fadeTo(1000,1);
		//$(this.title_block).hide();
		this.showtitle()
		//this.slideshow()
		//Gallery.slideTo(this.count()-1,1000);
		
	}
	
	// Привязка событий к кнопкам
	this.prepareGui = function()
	{
		
		$(this.rightbutton).click(function(){
			Gallery.slideNext();
		});
		
		$(this.leftbutton).click(function(){
			Gallery.slidePrevious();
		});

		
		 // Инъекция событий в слайдер 
		$(this.event).bind("mouseenter", function(){
			//Gallery.inject(this);
		});
		
		$(this.event).bind("mouseleave", function(){
			//Gallery.reject(this);
		});
		
		//setTimeout("Gallery.slideshow()","10000");
		
		
	}
	

	
	// Переход к правой картинке
	this.slideNext = function()
	{
		if (this.curent+1 < this.count()) this.slideTo(this.curent+1);
		
	}
	
	// Переход к левой картинке
	this.slidePrevious = function()
	{

		if (this.curent > 0) this.slideTo(this.curent-1);
		
	}
	
	// Переход к картинке с заданным номером
	this.slideTo = function(target,time)
	{
		
		var shift; 
		shift = 0 - (target - this.curent);
 
		this.curent = target;
		
		this.slideToPix(shift * this.image_size,time);
		
		
	}
	
	// Переход к заданое число пикселов
	this.slideToPix = function(pix,time)
	{
		
		var slide_time;

		this.hidetitle();
		
		
		slide_time = this.slide_time;
		
		if (time != null)
		{
			slide_time = time;
		}

		
		
		this.busy = true;
		$(this.container).animate(
				  {
					  marginLeft: '+=' + pix
				  },
				  slide_time, 
				  function(){
					  Gallery.busy = false;
				  }		    
		);
		Gallery.busy = false;
		Gallery.showtitle();
		
		
	}
	
	
	// Вывод, сопутствующего картинке текста в заданном положении
	this.showtitle = function()
	{
		
		var position ;
		
		position = this.curentObj().position;
		
		if (this.curentObj().position == 4){
			position = Math.floor(Math.random()*4)
		}

		if (this.curentObj().title != ''){
			$(this.title_block).html(this.curentObj().title);
	
			$(this.title_block).removeClass()
			$(this.title_block).addClass("d" + position);		
			
			$(this.title_block).fadeTo(1000,1);
		}
		
	}
	
	// Скрытие сопутствующего картинке текста
	this.hidetitle = function()
	{
		$(this.title_block).fadeTo(0,0);
	}
	
	this.slideshow = function()
	{
		//alert("1")
		
		rand = position = Math.floor(Math.random()* this.count())
		this.slideTo(rand, this.slide_time*5) 
		
		//setTimeout("Gallery.slideshow()","10000");
		
	}
}

