/**
 * @author Ivan Shornicov (paraboom@design.ru)
 * @copyright Art.Lebedev Studio (http://www.artlebedev.ru)
 * @version 0.5 (09.06.2009)
 * @ requires jQuery
 *
 * @modify Denis Khripkov (denisx@design.ru)
 */

/**
 * Позволяет контролировать ползунок у блока с горизонтальным расположением картинок
 * @ type
 */

//var a = 7;
//var b = {path:'/management/directors/'};

var sliderInfo = {path:'false'};

var picSlider = {

	/** Ширина ползунка */
	WIDTH : 12,

	/** Ширина одного большого изображения */
	IMGWIDTH : 148,
	IMGHEIGHT : 221,
	IMGHEIGHTCALC : 237,
//	STARTPOS : [0.997, 0.799, 0.634],
	STARTPOS : [1, 0.87, 0.74, 0.6],
	STARTPOS_delta: [3, 3, 3],
	deltaListFader: 0,
	ImgBorder : 2,

	/** Размер дефолтного шрифта в px */
	EM : 16,

	/**
	 * Функция иницаилизации
	 */
	init :	function(resize){
		this.isResize = false;
		if( resize ){
			this.isResize = resize;
		}
		var that = this;

		this.picList = $('#date_navigation .pic_list');
		this.picListWidth = $('#date_navigation .pic_list').width();
// слайдер короче на 1 фотку
		this.lineLeft = $('#date_navigation .left_fader');
		this.lineLeftMove = this.lineLeft.width() ;
		this.dateController = $('#date_navigation .date_controller');
//		this.lineDelta = round( (this.IMGWIDTH + this.lineLeftMove) / 2 );
		this.lineDelta = this.lineLeftMove;

//		this.dateController.width( this.picListWidth - this.IMGWIDTH );
//		console.log( this.picListWidth , this.dateController.width() );
		this.dateController.css({ 
			'margin-left': round(this.lineDelta / 2),
			'width': this.picListWidth - round(this.lineDelta)
		});
//		console.log( this.picListWidth , this.dateController.width() );

		this.dateControllerWidth = this.dateController.width();
		this.dateControllerOffset = this.dateController.offset().left;


		this.decorate = $("#decorate");

		/** Сам слайдер */
		this.slider = $("#date_slider");

		/** Контейнер где всё это происходит */
		this.container = $("#date_navigation");
		this.containerWidth = this.container.width();
		this.containerOffset = this.container.offset().left;

		/** Список картинок */
		this.dateList = $("#date_list_ul");

		/** Текущий элемент */
		this.lis = $(that.dateList).find("li.picture");
		$(this.lis[0]).addClass("selected");
		this.selectedItem = this.dateList.find("li.selected");

		/** Видимый кусок */
//		var visibleCoords = this.dateListWidth - this.containerWidth;
//		var currentItemOffset = this.selectedItem.offset().left - this.containerOffset;

		/** Список изображений */
		/** Список изображений */
		this.imgList = $("img", this.dateList);
		this.imgWidths = [];
		this.imgList.each(
			function(i){
				that.imgWidths[i] = $(this).attr("width");
			}
		);

		this.currImg = $(this.imgList[0]);
		this.currImgFirst = true;

		this.picDescriptions = $("#pictures_description p");
		this.currentDescriptionNum = 0;
		this.hoverDescriptionNum = 0;

		this.imgPoints = [];
		this.imgPointsDelta = [];

		this.imgList.css("position", "absolute");
//		this.recalculatePoints(0.0001, this.STARTPOS[3]);
		this.recalculateHeights(1);

		this.test = 0;
		this.imgList.each(
			function(){
				that.test += $(this).width();
			}
		);
		this.test += 40;

		this.measurerWidth = $("#inner_measurer").width();

		this.sliderOffset = 0;

		this.sliderMouseOffset = 0;
		this.dateListWidth = this.calculateWidth();

		this.rateDelta = 0;
		this.rate = ((this.dateListWidth - this.containerWidth) / this.containerWidth) + this.rateDelta;

		/** Двигаем всё к текущему элементу */
		this.dateList.css("left",0);
		this.slider.css("left",0);

		this.clicked = false;

		if(this.isResize){
			this.decorate.css(
				{
					width: this.currImg.width()
				}
			);
		}

		this.attachEvents();
		this.recalculateParams();
		this.iTimeFinish = 0; // счетчик пробега ползунка


		this.sliderInfo = 'sliderInfo';
		this.SliderStop = 'true';
//		console.log( 1, sliderInfo.path, this.SliderStop );
		if ( sliderInfo.path !== 'false' ){
			this.SliderStop = getCookie( this.sliderInfo ); // первоначальный пробег
//			console.log( 2, sliderInfo.path, this.SliderStop );
		}
		this.iPlayTime = 2; // сколько раз ползунок будет бегать туда-сюда
//		console.log( 3, sliderInfo.path, this.SliderStop );
		if ( this.SliderStop === '' || this.SliderStop === 'false' ){
//			console.log( 4, sliderInfo.path, this.SliderStop );
			this.firstRun(1); // первый пробег с; 1 вперёд, -1 назад
			if ( sliderInfo.path !== 'false' ){
				setCookieCopy( this.sliderInfo, 'true', sliderInfo.path, 0 );
//				console.log( 5, sliderInfo.path, this.SliderStop );
			}
		}
		/**
		 * Пересчёт параметров слайдера при ресайзе окна или шрифта
		 */
		common.Measurer.setFunc(
			function(){
				that.recalculateParams();
			}
		);

/*
http://gazprom.dev.design.ru/management/board/?mode=preview
*/

	},

	/**
	 * Вычисление ширины списка дат
	 * @return {Number}
	 */
	calculateWidth : function(){
		var that = this;
		/**
		 * Возвращать всё время одну и ту же ширину. Равную ширине всех картинок вначале.
		 */
		return (that.test);
	},

	/**
	 * ==============================================================================================
	 * Пересчёт параметров при ресайзе окна или шрифта
	 */
	recalculateParams : function(){

		this.picListWidth = this.picList.width();
		this.lineLeftMove = this.lineLeft.width() ;

//		this.dateController.width( this.picListWidth - this.IMGWIDTH );
//		this.dateController.width( this.picListWidth );
//		this.lineDelta = round( (this.IMGWIDTH + this.lineLeftMove) / 2 );
		this.lineDelta = this.lineLeftMove;

//		console.log( this.picListWidth , this.lineDelta, this.dateController.width() );

		this.dateController.css({
			'margin-left': round(this.lineDelta/2),
			'width': this.picListWidth - this.lineDelta
		});
//		console.log( this.picListWidth , this.lineDelta, this.dateController.width() );

		this.dateControllerWidth = this.dateController.width();
		this.dateControllerOffset = this.dateController.offset().left;
//		console.log( 3 );


		this.EM = $("#measurer").height();
		var oldContainerWidth = parseInt(this.containerWidth);

		this.dateListWidth = this.calculateWidth();

		this.containerWidth = this.container.width();
		this.containerOffset = this.container.offset().left;

		this.rate = ((this.dateListWidth - this.containerWidth) / this.containerWidth) + this.rateDelta;
		this.sliderOffset = parseInt(this.slider.css("left"));

		var newOffset = this.sliderOffset * (this.containerWidth / oldContainerWidth);

		this.sliderOffset = newOffset;
		var sliderRate = this.sliderOffset / this.containerWidth;
		this.slider.css(
			{
				left: newOffset
			}
		);
		this.dateList.css(
			{
				left: -((this.sliderOffset + this.WIDTH * sliderRate) * this.rate)
			}
		);
		this.recalculateHeights(newOffset, -((newOffset + (this.WIDTH * sliderRate)) * this.rate));
	},
/*
* ==============================================================================================
* */
	recalculateHeights : function(dist, offset){
		var tmp = 0;
		var zoom, obj, h, w, t;
		var delta = 0;
//		console.log( this.imgPoints[0] );
		if ( this.imgPoints[0] ){
//			console.log('1', '===', dist );
			for (var i = 0; i < this.imgList.length; i++){
				obj = $(this.imgList[i]);
				zoom = this.STARTPOS[0]; // 1
				if( !this.isResize ){
					zoom = this.STARTPOS[3]; // 0.6
					if (Math.abs(dist-this.imgPoints[i]) < 350){
//						zoom = -0.0013*(Math.abs(dist-this.imgPoints[i]))+1;
						zoom = -0.001 * (Math.abs( dist - this.imgPoints[i])) + 1;
					}
//					console.log ( i, '  -  ', round(this.imgPoints[i]), round((Math.abs( dist - this.imgPoints[i]))),'  -  ', zoom, '  -  ', tmp );
				}
				w = round(this.imgWidths[i] * zoom);
				h = this.IMGHEIGHT * zoom;
				t = round(this.IMGHEIGHTCALC - h - this.ImgBorder*2 + 1); // - delta
				obj.css(
					{
						width: w,
						height: round(h),
						top: t,
						left: tmp
					}
				);
				tmp += round(this.imgWidths[i] * zoom + this.ImgBorder * 2);
			}
		}else{
//			console.log('2', '===', dist );
			for ( i = 0; i < this.imgList.length; i++){
				obj = $(this.imgList[i]);
				zoom = this.STARTPOS[3]; // 0.6
				if( i < 3 ){
					zoom = this.STARTPOS[i];
					delta = this.STARTPOS_delta[i];
				}
//				console.log ( i, '  -  ', this.imgPoints[i], '  -  ', zoom, '  -  ', tmp );
				w = round(this.imgWidths[i] * zoom);
				h = this.IMGHEIGHT * zoom;
				t = round(this.IMGHEIGHTCALC - h - this.ImgBorder*2 + 1); // - delta
//				console.log ( i, round(this.imgWidths[i]), this.IMGHEIGHT, zoom, h, t );
				obj.css(
					{
						width: w,
						height: round(h),
						top: t,
						left: tmp
					}
				);
				tmp += round(this.imgWidths[i] * zoom + this.ImgBorder * 2);
			}
		}
		this.recalculatePoints(offset, this.STARTPOS[3]);
	},
/*
 * ==============================================================================================
 * смещение zoom 'a каждой фотки относительно zoom сначения, в px
 * ( и зачем-то + на position.left )
 */
	recalculatePoints : function(offset, zoom){
		var that = this;
		var pointRate = this.IMGWIDTH / this.imgList.length;
//		console.log( '-- --', this.IMGWIDTH, this.imgList.length, round(pointRate), round(offset), zoom );
		var a, b, d;
		this.imgList.each(
			function(i){
				a = parseInt($(that.imgList[i]).css("left"));
				b = pointRate * zoom * i;
				d = a + b + offset;
				that.imgPoints[i] = d;
//				console.log( a, '   ', round(b), '   ', round(d) );
			}
		);
//		var c = round((that.dateListWidth - that.dateControllerWidth) / that.dateControllerWidth);
//		console.log( round(that.dateListWidth), round(that.dateControllerWidth), c );
	},
/*
 * ==============================================================================================
 */
	firstRun : function(whereToMove){
//		whereToMove == 1 вправо
//		whereToMove == -1 влево
		var iwhereToMove = whereToMove; 
		var that = this;
		var x = 0;
		var xMax = that.containerWidth - that.WIDTH;
		if ( iwhereToMove === -1 ){
			x = xMax;
			xMax = 0;
		}
//		var delta = -30;
		// больше цифра - больше скорость!
		var delta = round(300 / that.imgList.length) * iwhereToMove;
		var id;
//	   console.log( (that.dateListWidth - that.containerWidth) / that.containerWidth );
//		console.log( that.dateListWidth, that.containerWidth, that.containerWidth );
		function oneIteration() {
			var sliderRate = that.sliderOffset / that.containerWidth;
			that.sliderOffset = x;
			that.slider.css(
				{
					left: x
				}
			);
			var newListOffset = -((x + (that.WIDTH * sliderRate)) * that.rate);
			that.dateList.css(
				{
					left: newListOffset
				}
			);
			for( var i = 0; i < that.imgList.length; i++ ){
				var img = parseInt($(that.imgList[i]).css("left")) + newListOffset;
				var imgw = $(that.imgList[i]).width();
				if(x > img && x < (img + imgw) && i != that.currentDescriptionNum){
					if(that.isResize){
						that.currImgFirst = false;
						that.currImg = $(that.imgList[i]);
						that.decorate.css(
							{
								width: that.imgList[i].width - 6
							}
						);
					}
					$(that.picDescriptions[that.currentDescriptionNum]).removeClass('selected');
					$(that.picDescriptions[i]).addClass('selected');
					that.currentDescriptionNum = i;
				}
			}
			that.recalculateHeights(x, newListOffset);
			x += delta;
			if ( xMax === 0 && x > 0 && x < Math.abs(delta) ){
				x = Math.abs(delta);
			}
			if ( x*iwhereToMove > xMax*iwhereToMove ){
				that.iTimeFinish++;
				clearInterval(id);
				if ( that.iPlayTime > that.iTimeFinish ){
					iwhereToMove *= -1;
					that.firstRun(iwhereToMove);
				}
			}
			return true;
		}

		var delay = 0;
		if ( that.iTimeFinish === 0 ){
			delay = 1000; // первый запуск бегунка - ждём прогрузки картинок
		}
		setTimeout(
			function(){
				id = setInterval(function(){oneIteration()}, 50);
			}, delay
		);

	},
/*
 * ==============================================================================================
 */
	attachEvents : function(){
		var that = this;

		/**
		 * Нажатие на ползунок
		 */
        this.slider.mousedown(
        	function(e){
        		e.preventDefault();
        		that.sliderMouseOffset = e.pageX - that.dateControllerOffset - parseInt(that.slider.css("left"));
				that.clicked = true;
        	}
        );

        /**
         * Движение мышки с нажатым ползунком
         */
		$(document).mousemove(
			function(e){
				if (that.clicked){
					e.preventDefault();
					that.sliderOffset = parseInt(that.slider.css("left"));
					var newOffset = parseInt( e.pageX - that.dateControllerOffset - that.sliderMouseOffset );
					if(newOffset >= 0 && newOffset <= (that.dateControllerWidth - that.WIDTH)){
						var thatimgListlength = 0;
						if ( that.imgList.length > 12 ){ thatimgListlength = that.imgList.length }
						that.rate = (that.dateListWidth - (that.dateControllerWidth - thatimgListlength*2 ) ) / that.dateControllerWidth;
						that.sliderOffset = newOffset;
						that.slider.css({ left: round(newOffset) });
						var newListOffset = -newOffset * that.rate;
						that.dateList.css({ left: round(newListOffset) });
						for(var i = 0; i < that.imgList.length; i++){
							var img = parseInt($(that.imgList[i]).css("left")) + newListOffset;
							var imgw = $(that.imgList[i]).width();
							if( img < newOffset + that.lineDelta/2 && newOffset + that.lineDelta/2 < (img + imgw + that.WIDTH) && i != that.currentDescriptionNum ){
								that.lis.removeClass('selected');
								$(that.lis[i]).addClass('selected');
								$(that.picDescriptions).removeClass('selected');
								$(that.picDescriptions[i]).addClass('selected');
								that.currentDescriptionNum = i;
							}
						}
						if(!that.currImgFirst){
							that.decorate.css({ left: parseInt(that.currImg.css("left")) });
						}
						if(!that.isResize){
							that.recalculateHeights(newOffset, newListOffset);
						}
					}
				}else{
					$(that.picDescriptions).removeClass('selected');
					$(that.picDescriptions[that.currentDescriptionNum]).addClass('selected');
				}
			}
		);

	/**
	 * ====================================================================================
	 * Отпустили ползунок
	 */
	$(document).mouseup(
		function(){
			that.clicked = false;
		}
	);
		/**
		 * ==============================================================================================
		 * Нажатие на "линию"
		 */
        /*this.sliderLine.click(
        	function(e){
				that.sliderMouseOffset = that.WIDTH/2;
				var sliderRate = that.sliderOffset / that.containerWidth;
				var newOffset = parseInt(e.pageX-that.containerOffset-that.sliderMouseOffset);

				if(newOffset > 0 && newOffset < (that.containerWidth - that.WIDTH)){
					that.sliderOffset = newOffset;
					that.slider.css(
						{
							left: newOffset
						}
					);
					var newListOffset = -((newOffset + (that.WIDTH * sliderRate)) * that.rate);
					that.dateList.css(
						{
							left: newListOffset
						}
					);

					that.recalculateHeights(newOffset, newListOffset);
				}
    		}
        );*/

        /**
			* ===================================================================================
		 * Нажатие на фотку
		 */
        this.imgList.click(
        	function(){
        		if (!that.intervalId && !$(this).parent().hasClass("selected")){
	        		var current = $(this);
	        		var count = current.parent().prevAll();

	        		that.lis.removeClass("selected");
	        		current.parent().addClass("selected");

	        		that.selectedItem = current.parent();

	        		var newOffset = that.sliderOffset;
	        		var currentItemOffset = parseInt(current.css("left"));
	        		var sliderRate = that.sliderOffset / that.containerWidth;
					var newListOffset = -((newOffset + (that.WIDTH * sliderRate)) * that.rate);
					var delta = 10;
	        		if (newOffset > currentItemOffset + newListOffset){
	        			delta *= -1;
	        		}

	        		function iteration(){
	        			currentItemOffset = parseInt(current.css("left"));

	        			newOffset += delta;
	        			that.sliderOffset = newOffset;

						sliderRate = that.sliderOffset / that.containerWidth;
						newListOffset = -((newOffset + (that.WIDTH * sliderRate)) * that.rate);

						var leftParam = 0;
						if ( newOffset >= 0 ){
							leftParam = newOffset;
						}
						that.slider.css(
							{
								left: leftParam
							}
						);
						that.dateList.css(
							{
								left: newListOffset
							}
						);
						$(that.picDescriptions).removeClass('selected');
						$(that.picDescriptions[count.length]).addClass('selected');
						that.currentDescriptionNum = count.length;

						that.recalculateHeights(newOffset, newListOffset);
						if (delta > 0 && newOffset > that.imgPoints[count.length]){
							clearInterval(that.intervalId);
							that.intervalId = false;
						}
						if (delta < 0 && newOffset < that.imgPoints[count.length]){
							clearInterval(that.intervalId);
							that.intervalId = false;
						}
	        		}

	        		that.intervalId = setInterval(function(){iteration()}, 5);
        		}
        		else{
        			var link = $(that.picDescriptions[that.currentDescriptionNum]).find("a");
					if(link.length){
						window.location = $(link[0]).attr("href");
					}
        		}
        	}
        );

		this.imgList.mousemove(
        	function(e){
        		if (!that.clicked){
        			e.stopPropagation();
        			var mouseX = e.pageX - that.containerOffset;
					var offset = parseInt(that.dateList.css("left"));

        			for(var i = 0; i < that.imgList.length; i++){
						var img = parseInt($(that.imgList[i]).css("left")) + offset;
						var imgw = $(that.imgList[i]).width();
						if(mouseX > img && mouseX < (img + imgw)){
							if(that.isResize){
								that.currImgFirst = false;
								that.currImg = $(that.imgList[i]);
								that.decorate.css(
									{
										width: that.imgList[i].width - 6
									}
								);
							}
							$(that.picDescriptions).removeClass('selected');
							$(that.picDescriptions[i]).addClass('selected');
							that.hoverDescriptionNum = i;
						}
					}
        		}
        	}
        );
	},

	getSliderInfo : function(){
		var that = this;
		return sliderInfo;
	}

};

/*
 * ==============================================================================================
// основная функция в коде ниже, поэтому для слайдера сделал копию
 */
//function getCookieCopy(cookieName){
//	var ourCookie = document.cookie;
//	var answer;
//	var f = true;
//	if (!ourCookie || ourCookie == ""){
//		answer = '';
//		f = false;
//	}else{
//		ourCookie = ourCookie.split(";");
//		var i = 0;
//		var cookie;
//
//		while( ourCookie.length > i && f ){
//			cookie = ourCookie[i].split("=")[0];
//			if( cookie.charAt(0) == " " ){
//				cookie = cookie.substring(1);
//			}
//			if( cookie == cookieName ){
//				answer = unescape(ourCookie[i].split("=")[1]);
//				f = false;
//			}
//			i++;
//		}
//	}
//	if ( f ){
//		answer = 'false';
//	}
//	return answer;
//}



function round( n ){
	return Math.round( n );
}
