/**
 * @author Ivan Shornicov (paraboom@design.ru)
 * @copyright Art.Lebedev Studio (http://www.artlebedev.ru)
 * @version 0.2 (20.04.2009)
 * @ requires jQuery
 */

/*var dateSlider = (function(){

	var myObj = this.myObj = function(){
		return {

		}
	}()

	function init() {


	}

	$(function(){
		init();
	})


	return {

	}
})();*/

/**
 * Позволяет контролировать ползунок у блока с горизонтальным расположением дат
 * @ type
 */

var dateSlider = {

	/** Ширина ползунка */
	WIDTH : 12,

	/** Размер дефолтного шрифта в px */
	EM : 16,

	/**
	 * Функция инициализации
	 */
	init : function(){
		var that = this;

		/** Сам слайдер */
		this.slider = $("#date_slider");
		this.sliderLine = $(".date_controller");
		this.line = $(".line");
		this.disabled = false;

		/** Контейнер где всё это происходит */
		this.container = $("#date_navigation:not(.pic_slider_full, .pic_slider)");

		/** Список дат */
		this.dateList = $("#date_list_ul");

		this.measurerWidth = $("#inner_measurer").width();

		this.containerWidth = this.container.width();
		this.containerOffset = this.container.offset().left;

		this.sliderOffset = parseInt(this.slider.css("left"));

		this.sliderMouseOffset = 0;
		this.dateListWidth = this.calculateWidth();

		this.rate = (this.dateListWidth - this.containerWidth) / this.containerWidth;

		/** Двигаем всё к текущему элементу */
		this.selectedItem = this.dateList.find("li.selected");

		var visibleCoords = this.dateListWidth - this.containerWidth;
		var currentItemOffset = this.selectedItem.offset().left - this.containerOffset;
		currentItemOffset += -(this.containerWidth / 2) +(this.selectedItem.width() / 2) + 10;

		if(currentItemOffset > visibleCoords){
			this.dateList.css({ left: -(this.dateListWidth-this.containerWidth)});
			this.slider.css({
				left: this.containerWidth - this.WIDTH
			});
		}
		else{
			if(currentItemOffset > 0){
				this.dateList.css({ left: -(currentItemOffset)	});
			}

			if(currentItemOffset/this.rate < 0){
				this.slider.css({
					left: 0
				});
			}
			else if(currentItemOffset/this.rate > this.dateListWidth){
				this.slider.css({
					left: this.dateListWidth - this.WIDTH
				});
			}
			else{
				this.slider.css({
					left: currentItemOffset/this.rate
				});
			}
		}

		if(this.dateListWidth < this.containerWidth){
			this.slider.addClass("disabled");
			this.slider.css({
					left: 0
				});
			this.dateList.css({ left: 0	});
			this.line.addClass("disabled_line");
			this.disabled = true;
		}

		this.clicked = false;

		this.attachEvents();

		/**
		 * Пересчёт параметров слайдера при ресайзе окна или шрифта
		 */
		common.Measurer.setFunc(
			function(){
				that.recalculateParams();
			}
		);
	},

	/**
	 * Вычисление ширины списка дат
	 * @return {Number}
	 */
	calculateWidth : function(){
		var that = this;
		var lastLI = $("li:last",this.container);

		var tmpWidth = 0;
		var li = $("li",this.container);
		li.each(function(){
			tmpWidth += $(this).width() + 13;
			if($(this).hasClass('year')){tmpWidth += 1}
		});
		return (tmpWidth);
	},

	/**
	 * Пересчёт параметров при ресайзе окна или шрифта
	 */
	recalculateParams : function(){
		this.EM = $("#measurer").height();
		var oldConatainerWidth = this.containerWidth;

		this.dateListWidth = this.calculateWidth();

		this.containerWidth = this.container.width();
		this.containerOffset = this.container.offset().left;

		if(this.dateListWidth > this.containerWidth){
			if(this.disabled){
				this.slider.removeClass("disabled");
				this.line.removeClass("disabled_line");
				this.disabled = false;
			}
			this.rate = (this.dateListWidth - this.containerWidth) / this.containerWidth;
			this.sliderOffset = parseInt(this.slider.css("left"));
			var newOffset = this.sliderOffset * (this.containerWidth / oldConatainerWidth);
//			newOffset = (newOffset > this.containerWidth - this.WIDTH) ? this.containerWidth - this.WIDTH : newOffset;
			if ( newOffset > this.containerWidth - this.WIDTH ){
				newOffset = this.containerWidth - this.WIDTH;
			}
			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)
				}
			);
		}
		else{
			this.slider.addClass("disabled");
			this.line.addClass("disabled_line");
			this.disabled = true;
		}
	},

    attachEvents : function(){
		var that = this;

		/**
		 * Нажатие на ползунок
		 */
        this.slider.mousedown(
        	function(e){
        		e.preventDefault();
        		e.stopPropagation();
        		that.sliderMouseOffset = e.pageX - that.containerOffset - parseInt(that.slider.css("left"));
				that.clicked = true;
        	}
        );

        /**
         * Движение мышки с нажатым ползунком
         */
		$(document).mousemove(
			function(e){
				if (that.clicked && !that.disabled){
					e.preventDefault();
					that.sliderOffset = parseInt(that.slider.css("left"));
					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
							}
						);
					}
				}
			}
		);

		/**
		 * Отпустили ползунок
		 */
		$(document).mouseup(
        	function(){
				that.clicked = false;
        	}
        );

		/**
		 * Нажатие на "линию"
		 */
        this.sliderLine.mousedown(
        	function(e){
        		if (!that.disabled){
					that.sliderMouseOffset = that.WIDTH/2;
					var sliderRate = that.sliderOffset / that.containerWidth;
					var newOffset = parseInt(e.pageX-that.containerOffset-6);
					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
							}
						);
					}
        		}
    		}
        );
	}
};