/**
 * @author Sergey Chikuyonok (serge.che@gmail.com)
 * @link http://chikuyonok.ru
 */
var olympic_countdown = (function(){
	/** @type {Date} Дата начала олимпиады */
	var till_dt,
		/** @type {Date} Дата начала отсчёта */
		start_dt,
		
		to_minutes = 60 * 1000,
		to_hours = 60 * to_minutes,
		to_days = 24 * to_hours,
		
		/** Время анимации, мс */
		anim_time = 500,
		
		/** @type {Function} Функция, вызываемая после завершения отсчета */
		finish_callback,
		
		strings = {
			days: ['день', 'дня', 'дней'],
			hours: ['час', 'часа', 'часов'],
			minutes: ['минута', 'минуты', 'минут'],
			seconds: ['секунда', 'секунды', 'секунд']
		},
		/** @type {jQuery} */
		sections;
		
	function padNumber(num) {
		return (num < 10) ? '0' + num : String(num);
	}
	
	function rightWord(num, words) {
		/** Последняя цифра */
		var num_str = String(num);
		var last = Number(num_str.charAt(num_str.length - 1)),
			result;
			
		num %= 100;
		if(num >= 5 && num <= 20)
			result = words[2];
		else {
			switch(last) {
				case 1:  result = words[0]; break;
				case 2:
				case 3:
				case 4:  result = words[1]; break;
				default: result = words[2]; break;
			}
		}
		
		return result;
	}
	
	function getNumElem(section) {
		return jQuery(section).find('.bem-olympic-num');
	}
	
	function getCaptionElem(section) {
		return jQuery(section).find('.bem-olympic-num-caption');
	}
	
	/**
	 * Обновляет секцию с цифрой
	 * @param {Element} section
	 * @param {Number} value
	 * @param {String[]} words
	 */
	function updateSection(section, value, words) {
		var mover = getNumElem(section);
		if (parseInt(mover.text(), 10) != value) {
			var h = mover.height();
			var new_mover = mover
				.clone()
				.css({top: -h})
				.text(padNumber(value)) 
				.insertBefore(mover);
			
				
			//getCaptionElem(section).text(rightWord(value, words));
			
			mover.animate({top: h}, anim_time, 'olympic_swap', function(){
				mover.remove();
			});
			
			new_mover.animate({top: 0}, anim_time, 'olympic_swap');
		}
	}
	
	/**
	 * Обновляет секцию с цифрой без анимации
	 * @param {Element} section
	 * @param {Number} value
	 * @param {String[]} words
	 */
	function updateSectionNoAnim(section, value, words) {
		getNumElem(section).text(padNumber(value));
		//getCaptionElem(section).text(rightWord(value, words));
	}
	
	function tick(no_animation) {
		start_dt.setTime(start_dt.getTime() + 1000);
		var time_delta = till_dt - start_dt,
			days_left = Math.floor(time_delta / to_days),
			hours_left = Math.floor((time_delta -= days_left * to_days) / to_hours),
			minutes_left = Math.floor((time_delta -= hours_left * to_hours) / to_minutes),
			seconds_left = Math.floor((time_delta -= minutes_left * to_minutes) / 1000);
		
		if (parseInt(days_left) == 0) 
		{
			sections[0].style.display = 'none';
			jQuery('.bem-olympic-section3').hide();
		}
		
		if (days_left + hours_left + minutes_left + seconds_left) 
		{
			if (parseInt(days_left) > 0) updateSection(sections[0], days_left, strings.days);
			updateSection(sections[1], hours_left, strings.hours);
			updateSection(sections[2], minutes_left, strings.minutes);
			updateSection(sections[3], seconds_left, strings.seconds);
			
			setTimeout(tick, 1000);
		} else if (finish_callback) {
			// наступила дата олимпиады
			finish_callback();
		}
	}
	
	// добавляем анимационных функций в jQuery
	jQuery.extend(jQuery.easing, {
		olympic_swap: function (x, t, b, c, d) {
			return(t==d) ? b+c : c * 1.001 *(-Math.pow(2, -10 * t/d) + 1) + b;
		}
	});
	
	function finish_callback()
	{
		jQuery('#timeleft_td').html(jQuery('#timefinished').val());
	}
		
	return {
		/**
		 * Инициализация счётчика
		 * @param {Date|Number} till_date Время начала олимпиады (дата или 
		 * количество милисекунд)
		 * @param {Date|Number} [start_date] Текущая дата
		 */
		init: function(till_date, start_date) {
			if (typeof(till_date) == 'number') {
				till_dt = new Date(till_date);
			} else {
				till_dt = till_date;
			}
			
			
			if (!start_date)
				start_dt = new Date;
			else if (typeof(start_date) == 'number')
				start_dt = new Date(start_date);
			else
				start_dt = start_date;
				
			sections = jQuery('.bem-olympic-section');
			tick(true);
		},
		
		/**
		 * Устанавливает callback-функцию, которая вызывается при наступлении
		 * нужной даты
		 * @param {Function} fn
		 */
		setFinishCallback: function(fn) {
			finish_callback = fn;
		}
	}
})();