/* MIT Engineering Ask an Engineer Effects (requires jQuery) */
/* by White Whale Web Services */

$(document).ready(function() {
// Ask an Engineer interaction options:
var panelWidth = 840, // panel width (px)
	edgeWidth = 0.45, // width of hover area on right and left edges for scrolling (portion of frame)
	maxSpeed = 30, // maximum speed (pixels per frame)
	minSpeed = 0.25, // minimum speed (pixels per frame)
	fps = 50, // frames per second
	refreshRate = 100, // how often to listen for a mouse move event
	threshold = 20; // how many pixels does the mouse have to have moved to register the change?

// Hide the welcome text when clicked:
	if(!readCookie('hideWelcome')) {
		$('#content').show();
	}
	$('.browse_questions, #close a, #content').click(function(){
		$('#content').fadeOut(400);
		createCookie('hideWelcome','true',2);
		return false;
	});

// Start prepping:
	var	strip  = $('#strip'),
		layers = [];
// Rearrange the strip elements into layers:
	var category_lists = strip.find('ul'),
		layouts = {},
		i = 0;
	$.each(strip.children(),function() {
		layouts[this.id] = 'layout'+(i++%3); // assign a layout to each
	});
	while(category_lists.children().length) {
		var layer = $('<div id="layer'+layers.length+'" class="layer" />'); // create the layer
		category_lists.each(function() {
			var li = $(this).children().eq(0),
				category = $(this).parents('.panel').attr('id'),
				link = li.find('.question_link a');
			link.attr('href',link.attr('href')+'#category_'+category);
			layer.append('<div class="panel '+category+' '+layouts[category]+'">'+(li.length ? '<div class="question">'+li.html()+'</div>' : '')+'</div>'); // add the question
			li.remove();
		});
		layers.push({element:layer}); // store the layer
	}
	var layer = $('<div id="layer'+layers.length+'" class="layer" />'); // create the layer
	$.each(strip.children(),function() {
		var h2 = $(this).find('h2'),
			category = $(this).attr('id');
		layer.append('<div class="panel '+category+' '+layouts[category]+'"><h2>'+h2.html()+'</h2></div>'); // add the question
	});
	layers.push({element:layer}); // store the layer
	strip.empty();
	$.each(layers,function(key,layer) {
		strip.append(layer.element); // add the layers to the strip
	});
// Set initial positions
	var stripWidth = layers[0].element.children().length*panelWidth,
		frame = $('#frame'),
		frameWidth;
	strip.width(stripWidth+'px'); // set the strip width if incorrect
	$(window).resize(function() { // calculate the hover areas and the strip "center" on resize
		frameWidth = frame.width();
		leftEdge = edgeWidth*frameWidth;
		rightEdge = frameWidth-(edgeWidth*frameWidth);
	}).resize(); // and do it now
	var initialOffset = -1*(stripWidth-frameWidth)/2+panelWidth;
	if(window.location.hash) {
		var start = layers[0].element.find(window.location.hash.replace('#category_','.'));
		if(start.length) {
			initialOffset = -1*layers[0].element.children().index(start)*panelWidth+(frameWidth-panelWidth)/2;	
		}
	}
	$('.layer').css('left',initialOffset+'px');
	for(i=0;i<6;i++) layers[i].offset = initialOffset;	
// Set click actions
	var whiteout = $('<div class="whiteout"/>').appendTo(strip),
		selected = false;
	$('.question h3 a').click(function() {
		var question = $(this).parents('.question'),
			layer = $(this).parents('.layer');
		if(question.hasClass('selected')) return false;
		selected = true;
		var summary = question.find('.summary'),
			fontSize = question.css('font-size'),
			top = question.position().top+'px';
		if(slide) { // if the slide() function is defined (it's undefined for IE6 and mobile browsers), then we center the clicked question
			destination = -1*layer.children().index($(this).parents('.panel'))*panelWidth-question.position().left+230+(frameWidth-460)/2;
			slide(maxSpeed*3); // get it to the center fast
		}
		question.toggleClass('selected')
			.animate({top:'50px',fontSize:'1.2em'},function() {
				summary.slideDown(500);
			});
		if($.browser.msie&&parseFloat($.browser.version)<=8) {
			layer.css('z-index',120); // we need to move the entire layer above the whiteout for IE (<=7)
		}
		whiteout.fadeTo(0,0).show().fadeTo(1000,0.75).one('click',function() {
				question.animate({top:top,fontSize:fontSize},750,function() {
				question.removeAttr('style'); // remove the inline styles, which are often wrong in IE (6-8)
				if($.browser.msie&&parseFloat($.browser.version)<=8) {
					layer.removeAttr('style'); // return the layer to its appropriate position in IE (<=7)
				}
				question.removeClass('selected');
				selected = false;
			});
			summary.slideUp(500);				
			whiteout.stop().fadeOut(500);
		});
		return false;
	});
// Abort if mobile (no mouse) interface
	var agent = navigator.userAgent.toLowerCase();
	if(agent.search('iphone')>-1||agent.search('android')>-1) { // rich mobile browsers version (iPhone & Android)
		$.fx.off = true;
		$('#header,#navigation,#footer').hide();
		frame.css('overflow','visible');
		strip.find('h3 a').attr('href','#');
		$('.layer').css('left',0);
		strip.show();
		return; // abort the rest of the initialization function
	}
// Attach mouseover behavior
	var destination,
		lastPos=-100,
		lastTime=0;
	frame.mousemove(function(e) {
		if(selected) return; // don't do anything if an element is currently selected
		var curPos = e.clientX,
			curTime = new Date().getTime(),
			modifier;
		if(Math.abs(curPos-lastPos)<threshold||curTime-lastTime<refreshRate) return; //  if the mouse has moved less than 20 or less than 100ms have elapsed, don't fire
		lastPos = curPos;
		lastTime = curTime;
		if(curPos<leftEdge) {
			modifier = Math.pow((leftEdge-curPos)/leftEdge,3);
			destination = 0;
		} else if(curPos>rightEdge) {
			modifier = Math.pow((curPos-rightEdge)/(frameWidth-rightEdge),3);
			destination = -1*(stripWidth-frameWidth);
		} else {
			destination = layers[0].offset;
			modifier = 0;
		}
		slide(maxSpeed*modifier+0.5);
	});
// Define per layer speed limit:
	layers[0].speed = 1;
	layers[1].speed = 0.95; 
	layers[2].speed = 0.9;
	layers[3].speed = 0.85;
	layers[4].speed = 0.8;
	layers[5].speed = 0.95;
	var slide = function(speed) {	
		$.each(layers,function(key,layer) {
			clearInterval(layer.animation);
			var direction = destination>layer.offset ? 1 : -1;
			layer.animation = setInterval(function() {
				var distance = Math.abs(destination-layer.offset), // distance remaining
					modifier = Math.pow(distance/stripWidth,0.7), // moderator decelerates as the destination approaches
					step = Math.max(speed*layer.speed*modifier,minSpeed);
				if(distance<=step) { // if the destination is less than the next step
					layer.offset=destination;
					clearInterval(layer.animation);
				} else {
					layer.offset+=step*direction;
				}
				layer.element.css('left',layer.offset+'px');
			},1000/fps);
		});
	};
// And finally, fade in the strip
	strip.fadeIn(1000);
});

/* Cookie functions */
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}