/**
 * @author Sergey Chikuyonok (serge.che@gmail.com)
 * @link http://chikuyonok.ru
 */$(function(){
	var is_animating = false,
		cur_section = -1,
		sections = $('#content .section'),
		max_font_size = 1.7,
		expanded_props = {
			width: '70%',
			paddingRight: '15%'
		},
		default_props = {
			width: '', 
			paddingRight: ''
		},
		anim_opt = {
			time: 0.8, 
			transition: 'easeinoutcubic'
		};
		
	/**
	 * @param {jQuery} elem
	 */
	function measureProps(elem) {
		var w = elem.width();
		return {
			width: w,
			paddingRight: elem[0].offsetWidth - w
		};
	}
	
	/**
	 * @param {jQuery} section
	 * @param {Object} props
	 * @param {Function} callback
	 */
	function animateSection(section, props, callback) {
		// замеряем текущие и новые размеры размеры
		var old_values = measureProps(section);
		section.css(props);
		var new_values = measureProps(section);
		
		is_animating = true;
		$t( section.css(old_values) ).tween(new_values, anim_opt, {
			onComplete: function() {
				is_animating = false;
				section.css(props);
				if (callback)
					callback();
			}
		});
	}
	
	function animateFontSize(elem, from, to) {
		$t(elem, anim_opt).percent({
			font_size: function(val){
				elem.css('font-size', (from + (to - from) * val) + 'em')
			}
		});
	}
	
	function expandFirstSection() {
		sections.eq(1).css('margin-right', '-100%');
		animateSection(sections.eq(0), expanded_props);
		animateFontSize(sections.eq(0), 1, max_font_size);
		cur_section = 0;
	}

	function collapseFirstSection() {
		animateSection(sections.eq(0), default_props, function() {
			sections.eq(1).css('margin-right', '');
		});
		animateFontSize(sections.eq(0), max_font_size, 1);
		cur_section = -1;
	}
	
	function expandSecondSection() {
		var section = sections.eq(0);
		$t(section).tween({
			marginLeft: -section.width(),
			onComplete: function(){
				section.css('margin-left', '-40%');
			}
		}, anim_opt);
		
		animateSection(sections.eq(1), expanded_props);
		animateFontSize(sections.eq(1), 1, max_font_size);
		cur_section = 1;
	}
	
	function collapseSecondSection() {
		var section = sections.eq(0);
		section.css('margin-left', -section.width());
		$t(section).tween({marginLeft: 0}, anim_opt);
		
		animateSection(sections.eq(1), default_props);
		animateFontSize(sections.eq(1), max_font_size, 1);
		cur_section = -1;
	}
	
	sections.click(function(){
		if (!is_animating) {
			switch (cur_section) {
				case 0:
					collapseFirstSection();
					break;
				case 1:
					collapseSecondSection();
					break;
				default:
					if (sections.index(this) == 1) 
						expandSecondSection();
					else
						expandFirstSection();
			}
		}
	});
});