$(document).ready(function() {

	if($('.tab').length > 0){
		var cube = new MagicCube($('.magic-cube'),  $('.magic-cube .side'));
		
		var first = $('.tab:first'),
		first_id = first.attr('id').split('tab_',2)[1];
		
		targetElements(first_id).addClass('active');
		
		// add events to show on click
		$('.tab a').click(function(e) {
			e.preventDefault();
			var slide_id = $(this).parent().attr('id').split('tab_',2)[1];
			
			if($(this).parent().hasClass('active')) return;

			targetElements().removeClass('active');
			targetElements(slide_id).addClass('active');
			
			// heading
			cube.activateSide($('#target_heading_'+slide_id).get(0));
		});
		
	}
	
	function targetElements(target_id){
		if(target_id){
			return $('#target_'+ target_id +
			' , #tab_' + target_id +
			' , #target_heading_'+target_id);
		} else {
			return $('.target, .tab, .target-heading');	
		}
	}
	
	
	// cube and sides parameters are expected to be jQuery objects.
	function MagicCube(cube, sides){
		var sideIndecies = {},
		self = this,
		use3d = Modernizr.csstransforms3d,
		degrees = {top:-90, middle:0, bottom:90},
		positions = {top:"-100%", middle:"0%", bottom: "100%"},
		activeSide = $(sides.get(0)),
		// Elements are at their original pixel-based screen sizes when z=0
		// so we translate the whole cube on the z axis by the distance between the
		// origin and the closest point on the front-facing side.
		// this way, the forward facing side is always at z=0
		half_height = cube.height()/2;

		this.moveToPosition = function(side, position, animate){
			// Rotate then translate away from the origin to form the sides of a box.
			if(use3d){
				side.toggleClass('animate', animate === true);
				side.css('-webkit-transform', 'rotateX('+degrees[position]+'deg) translate3d(0,0,'+half_height+'px)');
			}	else {
				var func = animate ? 'animate' : 'css';
				side[func]({top: positions[position]}, 700, 'swing');
			}
		}
		
		this.activateSide = function(side){
			var $side = $(side);

			if(false && activeSide)
				activeSide.addClass('animate');
			
			if (use3d){
				this.moveToPosition($side, 'bottom', false);

				setTimeout(function(){
					self.moveToPosition(activeSide, 'top', true);
					self.moveToPosition($side, 'middle', true);
					activeSide = $side;
				},0);
			} else {
				
				// if no 3d, set position then use opacity fade rather than moveToPosition animation
				this.moveToPosition(activeSide, 'middle', false);
				this.moveToPosition($side, 'middle', false);
				$side.css({opacity:0});

				setTimeout(function(){
					activeSide.animate({opacity:0});
					$side.animate({opacity:1});
					activeSide = $side;
				},0);
			}
		}
		
		sides.each(function(index, side){
			var $side = $(side);
			self.moveToPosition($side, index==0 ? 'middle' : 'bottom', false);
		})
		
		activeSide = $(sides.get(0));
	}
	
	// Show sides
	$('.magic-cube div img').fadeIn();
	
});

