//*** JS for gallery
function sliderProto (id) {
	this.init = function(id) {
		this.div = $('#gallery_container_'+id);
		this.slider = this.div.find('.slider');
		this.slideshow = false;
		this.showScrollers();
		var current_slider = this;
		this.div.find('.arrow_top').click(
			function() {
				current_slider.Slide('top');
		});
		this.div.find('.arrow_bottom').click(
			function() {
				current_slider.Slide('bottom');
			});
		this.image_container = this.div.find('.galleryImage');

		this.img_old = this.image_container.find('span#img img').get(0);

		this.links = new Array();
		this.alts = new Array();
		this.current_index = 0;
		this.appendImageHandlers();
		this.arrowsHideShow();
		this.checkImgOverflow(this.image_container.find('span#img img').get(0));

	}
	//Навеншиваем хандлеры
	this.appendImageHandlers = function() {
		var current_slider = this;
		//для картинок в слайдере
		this.div.find('ul img').each(
			function() {
				var link = this.parentNode.href;
				current_slider.links.push(this.parentNode.href);
				current_slider.alts.push($(this));
				$(this).click(
					function(index) {
						return function() {
							current_slider.showImage(index);
						}
					} (current_slider.links.length - 1)
				);
				this.parentNode.removeAttribute('href');
			}
		);
		//для отображаемой картинки
		this.image_container.find('#img').click(function(){
			current_slider.nextLink();
		});
		//для стрелок след, пред
		this.image_container.find('#next').click(function(){
			current_slider.nextLink();
		});
		this.image_container.find('#prev').click(function(){
			current_slider.prevLink();
		});
		this.image_container.find('#slideshow').click(function(){
			current_slider.slideShow();
		});
	}
	
	this.slideShow = function(){
		if (this.slideshow == true){
			this.slideshow = false;
			$(this).stopTime('slideshow');
			this.div.find('.galleryImage #slideshow').text('слайдшоу(старт)');
			return;
		}
		this.div.find('.galleryImage #slideshow').text('слайдшоу(стоп)');
		this.slideshow = true;
		var self = this
		var times = this.links.lenght - this.current_index;
		$(this).everyTime(3000,'slideshow', function(){
			self.showImage(self.current_index + 1);
		}, times);
	}
	
	this.nextLink = function(){
		if (this.links.length == this.current_index + 1) {
			return;
		}
			this.showImage(this.current_index + 1);
	}
	this.prevLink = function (){
		if (this.current_index == 0){
			return;
		}
		this.showImage(this.current_index - 1);
	}

	//Функция для прокрутки слайдера к текущей картинке
	
	this.slideToCurrent = function(link_index){
		//Определяем видна ли картинка
		container_height = this.slider.height();
		slider_offset=-(parseInt(this.slider.find('ul').css('top')));//на сколько слайдер поднят вверх		
		i=0;
		img_bottom = 0;
		img_top = 0;

		images = this.slider.find('li');
		while(i <= link_index){
			image = images.get(i);
			img_top = img_bottom;
			img_bottom += $(image).height();
			i++;
		}
		//alert(img_top+" "+img_bottom+"     "+slider_offset+" "+(slider_offset+container_height));
		if ((img_top >= slider_offset) && (img_bottom <= (slider_offset+container_height) )){
			return;
		};
		if(img_top < slider_offset){
			slide_value = img_top;
			raw_slide_value = slide_value;
			
			this.slider.find('ul').animate({top : -slide_value}, 200);
			this.sliderArrowsHideShow(raw_slide_value);			
		}
		if(img_bottom > (slider_offset+container_height)){
			slide_value = img_bottom-container_height;
			raw_slide_value = slide_value;		
	
			this.slider.find('ul').animate({top : -slide_value}, 200);
			this.sliderArrowsHideShow(raw_slide_value);				
		}			
	}
	this.showImage = function(link_index) {	
		var self = this;

		this.slideToCurrent(link_index);

		this.div.find('ul img').css('border','');
		$(this.alts[link_index]).css('border','1px solid white');
		var link = this.links[link_index];
		var alt = this.alts[link_index].attr('alt');
		this.current_index = link_index;
		var img_old = this.img_old;
		//$('#load_marker').text('загрузка');
				
		/*$(img_old).animate({
			opacity:0
		},200, function(){*/
			//img_new = $(img_old).clone;
			//alert(img_new)
			//$(img_old).remove();
			$(img_old).attr('src',link)
			if(($(img_old).width() > 550) && ($(document).width() <= 1100)){
				$(img_old).css('width','550px');
			}
			$(img_old).attr('alt',alt);
			$(".galleryImage p b").text(alt);	
			/*if(($(img_old).width() > 550) && ($(document).width() <= 1100)){
					$(img_old).css('width','550px');
				}
				$(img_old).attr('alt',alt);
				$(".galleryImage p b").text(alt);
				$(img_old).animate({
					opacity:1
				},200, function(){
					$('#load_marker').text('');
					
				});*/
		/*});*/
		this.arrowsHideShow();
	}
	
	this.checkImgOverflow = function(img){
		if($(document).width() < 1100){
			this.slider.css('height','370px');
			this.div.find('.arrow_bottom').css('top','345px')
			if(($(img).width() > 550)){
				$(img).css('width','550px');
			}
		}
		
	}
	this.Slide = function(direction) {//it works!!!
		var offset = this.countOffset(direction);
		//alert(offset);
		var slide_value = (direction=='bottom') ? -offset : offset;
		//
		var raw_slide_value = slide_value;
		//
		var css_top=parseInt(this.slider.find('ul').css('top'));
		var slide_value = css_top + slide_value;
		this.slider.find('ul').animate({top : slide_value}, 300);
		this.sliderArrowsHideShow(raw_slide_value);
	}
	
	this.sliderArrowsHideShow = function(slide_value){
		var slider_height = this.slider.find('ul').height();
		var slider_top = -(parseInt(this.slider.find('ul').css('top')));
		var next_slider_top = slider_top - slide_value;
		var slider_offset = slider_height + slide_value - slider_top;
		if(slider_offset == this.slider.height()){
			$('a.arrow_bottom').css('visibility','hidden');
			$('a.arrow_top').css('visibility','visible');
		}
		else if(next_slider_top == 0){
			$('a.arrow_top').css('visibility','hidden');
			$('a.arrow_bottom').css('visibility','visible');
		}
		else{$('a.arrow_top').css('visibility','visible');$('a.arrow_bottom').css('visibility','visible');}
	}
	this.arrowsHideShow = function(){
		var images_number = this.div.find('ul img').length;
		var current = this.current_index;
		if(images_number == 1){
			$('img#prev').css('visibility','hidden');
			$('img#next').css('visibility','hidden');
		}
		else if (current == 0){
			$('img#prev').css('visibility','hidden');
			$('img#next').css('visibility','visible');
		}
		else if (current == (images_number-1)){
			$('img#prev').css('visibility','visible');
			$('img#next').css('visibility','hidden');
		}
		else {$('img#prev').css('visibility','visible'); $('img#next').css('visibility','visible');}		
	}
	

	this.countOffset = function(dir){
		var container_height = this.slider.height();//высота контейнера слайдера
		var slider_offset=-(parseInt(this.slider.find('ul').css('top')));//на сколько слайдер поднят вверх
		var slider_height = this.slider.find('ul').height(); //высота самого слайдера
		var img_height = 0;
		var full_img_height=0;
		i=0;
		//Считаем высоту картинок полностью помещающихся в видимую часть
		this.slider.find('img').each(function(){
					i++;
					img_height += this.height + 3;
					if (img_height <= (slider_offset+container_height)){
						offset_index = i;
						full_img_height = img_height;
					}
				});
		//в зависимости от направления прокрутки считаем сколько есть места вверху/внизу,
		//в результате возвращаем величинку на которую следует двигать слайдер.
		this.offset_index=0;
		if(dir=="top"){
			free_space = slider_offset
			full_img_height = full_img_height - slider_offset;
			if(free_space>full_img_height){return full_img_height;}else{return free_space;}
		}
		else{
			free_space = slider_height-container_height-slider_offset;
			full_img_height = full_img_height - slider_offset;
			//alert("slider_height = "+slider_height+" container_height = "+container_height+" slider_offset = "+slider_offset+
			//" full_img_height = "+full_img_height+" free_space = "+free_space);

			if(free_space>full_img_height){return full_img_height;}else{return free_space;}
		}
	}
	
	
	this.showScrollers = function() {
		var img_height = 0;
		this.slider.find('img').each(function() {
			img_height += this.height + 3;
		});
		if (img_height < this.slider.height()){
			this.slider.css('height', img_height+"px");
		}
		else{this.div.find('.arrows').css({display:'block'});}
		//}
		//////
		//////
		//if (img_height > container_height) {
			//this.div.find('.arrows').css({display:'block'});
			//this.div.find('a.arrow_top').hide();
		//}
	}
	this.id = id;
	this.init(id);
}



function loadSliders() {
	sliders = {};
	$('.galleryContainer').each(function() {
			var id = this.id.replace(/[^0-9]/g, '');
			sliders[id] = new sliderProto(id);
	});
}
$(window).load(loadSliders);

