/*

##	Around Feb 23rd, Jon Dale wrote this.
##	Helped along by Mumford & Sons, and a good
##  dose of Smoky mountain Organic Roast.


*/

$(document).ready(function() {
	
	
	/* VARIABLES
	
	////////////////////////////////////// */
	
	var toggleTimer;
	var timerInterval;
	var ctr;
	var objNum = 0;
	var lineNum = 0;
	var basicNum = 0;
	var complexNum = 0;
	var delay = 100;
	var startX = null;
	var startY = null;
	var firstRun = true;
	var clicked = false;
	var paused = false;
	var aboutLoad = false;
	var workLoad = false;
	var canvasSupport;
	
	

	
	
	/* GENERAL
	
	////////////////////////////////////// */
	
	// hide text to avoid typkit flash
	$('section p').css('visibility', 'hidden');
	
	// support canvas?
  canvasSupport = !!document.createElement('canvas').getContext;
	
	// enable controls if js enabled
	if(canvasSupport) { $('#eraseCanvas, #info, #playPause').show(); }
	if(!canvasSupport) { $('#alt-message').css({'display' : 'block'}); $('body').addClass('no-canvas'); }
	
	
	// update info panel
	function updateInfo(basicNum, lineNum, complexNum) {
		$('#info-circles span').html(basicNum);
		$('#info-lines span').html(lineNum);
		$('#info-wheels span').html(complexNum);
	}
	
	
	// returns greeting, based on client's time.
	function getGreeting() {
	
		var now = new Date();
		var crntHr;
		crntHr = now.getHours();
		
		if(crntHr >= 0 && crntHr < 12) {
			return "Good morning";
		} else if (crntHr >= 12 && crntHr < 18) {
			return "Good afternoon";
		} else {
			return "Good evening";
		}
		
	}
	
	
	// Twitter link
	$('#twitter').click(function(evt){
			evt.preventDefault();
			newwindow=window.open($(this).attr('href'),$(this).attr('id'),'height=540,width=430');
	});
	
	
	
	
	/* INTERACTION FUNCTIONS (navigating site)
	
	////////////////////////////////////// */
	
	$('#home-about, #home-work').click(function(evt){
		evt.preventDefault();
		
		_gaq.push(['_trackEvent', 'navigation', evt.target.id]);
		
		// determine which section to load, which to hide.
		showHideSection(evt.target.id);
		
		// change canvas to content state
		changeToContentState();
		
	});
	
	
	// Revert back to the home state
	$('#go-home, h1 a').click(function(evt) {
		evt.preventDefault();
	
		$('#section-dynamic').fadeOut(400, function(){});
		
		// home transition
		$('#section-home').delay(600).fadeIn();
		
		// animate logo
		$('h1').delay(500).animate({marginLeft: '-38px'}, 300);
		
		_gaq.push(['_trackEvent', 'navigation', 'nav back home']);
				
	});
	
	// handle section clicks
	$('#go-about, #go-work').click(function(evt){
		evt.preventDefault();
		
		// determine which section to load, which to hide.
		showHideSection(evt.target.id);
		
	});
	
	
	// determine which section to show, and which to hide
	function showHideSection(section) {
		
		if(section == 'go-about' || section == 'home-about') {
			
			$('#article-work').hide();
			$('#go-about').addClass('navFocus');
			$('#go-work').removeClass('navFocus');
			$('#article-about > h2 > span').html(getGreeting());
			$('#article-about').fadeIn();
			//handlePageLoad('about');
			
		} else if (section == 'go-work' || section == 'home-work') {
		
			$('#article-about').hide();
			$('#go-work').addClass('navFocus');
			$('#go-about').removeClass('navFocus');
			$('#article-work').fadeIn();
			//handlePageLoad('work');
			
		}
				
	}
	
	
	// Change to content state
	function changeToContentState(evt) {
		
		// home transition
		$('#section-home').fadeOut();
		
		// fade page menu in.
		$('#section-dynamic').delay(600).fadeIn();
		
		// animate logo
		$('h1').animate({marginLeft: '-400px'}, 300);
		
	}
	
	// load section
	function handlePageLoad(section) {

		if(section == 'about') {
			
			_gaq.push(['_trackEvent', 'navigation', 'nav about']);
			
			if(!aboutLoad) {
				$('#loading').fadeIn();
				$.ajax({
				  url: "inc/about.php",
				  success: function(data){
				  	aboutLoad = true;
				  	
				  	// fade out loading message and slideup
				  	$('#loading').delay(200).fadeTo(300, 0, function(){
				  			$(this).slideUp();
				  	});
				  	
				    $('#article-about').append(data);
				    $('#article-about > h2 > span').html(getGreeting());
				    $('#article-about').fadeIn();
				  }
				});
			} else {
				$('#article-about').fadeIn();
			}			
		} else if(section == 'work') {
			
			_gaq.push(['_trackEvent', 'navigation', 'nav work']);
			
			if(!workLoad) {
				$('#loading').fadeIn();
				$.ajax({
				  url: "inc/work.php",
				  success: function(data){
				  	workLoad = true;
				  	
				  	// fade out loading message and slideup
				  	$('#loading').fadeTo(300, 0, function(){
				  			$(this).slideUp();
				  	});
				  	
				    $('#article-work').append(data).fadeIn();
				  }
				});
			} else {
				$('#article-work').fadeIn();
			}
			
		}
		
	
	}
	
	
	// show/hide aside in work section
	
	$(document).delegate('#article-work .info', 'click', function(evt){
		evt.preventDefault();
		var txt = ($(this).parent().next().is(":visible")) ? 'info' : 'close';
		$(this).parent().next().slideToggle();
		$(this).parent().next().show();
		$(this).html(txt);
		
		var project = $(this).prev().prev().prev().html();
		
		_gaq.push(['_trackEvent', 'interface', 'show project info', project]);
		
	});
	
	
	
	
	/* INTERACTION FUNCTIONS (drawing aspect)
	
	////////////////////////////////////// */
	
	
	// on mouse move, track when mouse stops and draw circle.
	
	$(document).mousemove(function(evt) {		
		
		if(!paused && canvasSupport) {
		
			
			// update info
			updateInfo(basicNum, lineNum, complexNum);
			
			var onmousestop = function() {
				toggle = true;
				
				// if stopped, draw line
				
				var scrollAmt = $(document).scrollTop();
				drawLine(evt.pageX, (evt.pageY - scrollAmt));
				timerInterval = setInterval(countStopTime, 100);
			};
			
			// clear stoppage time counter.
			clearInterval(timerInterval);
			
			
			// if mouse had stopped, draw circle. Specify whether a click had occurred too.
			if(ctr > 0) {
			
				// if no mouse click
				if(!clicked) {
					drawBasicCircle(startX, startY, ctr);
				}
				
				clicked = false;
			}
			ctr = 0;
			
			// clear mouse stop timer
			clearTimeout(toggleTimer);
			
			// start timer to see if mouse paused for delay period. If it is, call the onmousestop function.
			toggleTimer = setTimeout(onmousestop, delay);
		}
	
	});
	
	
	
	
	$('body').click(function(evt) {
	
	/*
		when the document receives a click, draw a different type of circle. no specific reason, just because.
	
		ok, if post-design-justification is needed, it's pretext is threefold:
	
		- to create visual interest by introducing a different, but consistent aesthetic shape.
		- to empower the user by enabling them to strategically place different circles on the canvas.
		- selfishly, for me to experiment with the canvas drawing tools to create a different shape.
	*/
	
		//if(evt.target.id != 'eraseCanvas' && !paused && evt.target.tagName != 'a') {
		
		
		if(canvasSupport && !paused && evt.target.tagName != 'A') {
			
			clicked = true;
			var scrollAmt = $(document).scrollTop();

			// draw new circle and get element id.
			var circId = drawComplexCircle(evt.pageX, (evt.pageY - scrollAmt));
			
			// in a few milliseconds, rotate.
			setTimeout(function (){ addRotateClass(circId) }, 100);
			
		}
	});
	
	// simply add rotate class
	function addRotateClass(id) {
		$('#obj-'+id).addClass('rotateCircle');
	}
	
	
	// simple increment for "time".
	
	function countStopTime() {
		ctr ++;
	}
	
	
	// erase canvas 
	
	$('#eraseCanvas').click(function(evt) {
			evt.preventDefault();
			
			if(!$(this).hasClass('disabled')) {
				
				_gaq.push(['_trackEvent', 'interface', 'erase canvas', objNum]);
				
				clicked = true;
				
				$('#stage-basic').empty();
				$('#stage-complex').empty();
				
				updateInfo(0, 0, 0);
				
				clearTimeout(toggleTimer);
				
				ctr = 0;
				objNum = 0;
				basicNum = 0;
				lineNum = 0;
				complexNum = 0;
				startX = null;
				startY = null;
				firstRun = true;
			}
		
	});
	
	
	// toggle play pause
	$('#playPause').toggle(function(){
		
		if(!$(this).hasClass('disabled')) {			
			
			_gaq.push(['_trackEvent', 'interface', 'pause', objNum]);
			
			paused = true;
			clearTimeout(toggleTimer);
			clearTimeout(timerInterval);
			ctr = 0;
			
			$(this).addClass('playIcon');
			$(this).attr('title', 'Start drawing.');
		}
		
	}, function() {
		
		if(!$(this).hasClass('disabled')) {
			
			_gaq.push(['_trackEvent', 'interface', 'play']);
			
			paused = false;
			$(this).removeClass('playIcon');
			$(this).attr('title', 'Pause drawing.');
		}
	});
	
	
	// handle info click.
	$('#info').toggle(function(){
		
		if(!$(this).hasClass('disabled')) {
		
			_gaq.push(['_trackEvent', 'interface', 'info', objNum]);
		
			var offset = $(this).offset();
			var xLoc = $(window).width() - (offset.left + 52);
			$('#infoPanel').css({'right' : xLoc+'px'});
			
			$('#infoPanel').fadeIn();
			$(this).addClass('closeIcon');
			$(this).attr('title', 'Close stats.');
		}
		
	}, function(){
		if(!$(this).hasClass('disabled')) {
			$('#infoPanel').fadeOut();
			$(this).removeClass('closeIcon');
			$(this).attr('title', 'Get the stats.');
		}
	});
	
	


	
	
	/* DRAWING FUNCTIONS
	
	////////////////////////////////////// */	
	
	
	// draw basic circle when mouse stopped.
	
	function drawBasicCircle(x, y, time) {
		
		_gaq.push(['_trackEvent', 'drawing', 'circle', 'basic']);
		
		var circleRadius = (time > 400) ? 400 : time;
		
		// increment created element for reference.
		objNum++;
		basicNum++;
		
		var w = $(window).width();
		var h = $(window).height();
		
		// make new canvas element, set width, height. Setting width & height to window width & height.
		$('#stage-basic').append('<canvas class="art" id="obj-'+objNum+'" width="'+(circleRadius*2)+'" height="'+(circleRadius*2)+'"></canvas>');
		
		// position
		$('#obj-'+objNum).css({'left' : (x-circleRadius)+'px', 'top' : (y-circleRadius)+'px'});
		
		// context
		var ctx = $('#obj-'+objNum)[0].getContext('2d');
		
		// draw circle
		ctx.fillStyle = "rgba(62, 72, 82, 0.1)";
		ctx.beginPath();
		ctx.arc(circleRadius, circleRadius, circleRadius, 0, Math.PI*2, true);
		ctx.closePath();
		ctx.fill();
		
	}
	
	
	// draw line to join all user mouse interactions.
	
	function drawLine(x, y) {
		
		// misses the first one, for no point to join the line from.
		if(!firstRun) {
			
			_gaq.push(['_trackEvent', 'drawing', 'line']);
			
			// increment created element for reference.
			objNum++;
			lineNum++;
			
			var w = $(window).width();
			var h = $(window).height();
			
			// make new canvas element, set width, height. Setting width & height to window width & height.
			$('#stage-basic').append('<canvas class="art" id="obj-'+objNum+'" width="'+w+'" height="'+h+'"></canvas>');
			
			// context			
			var ctx = $('#obj-'+objNum)[0].getContext('2d');
		
			ctx.strokeStyle = "rgba(62, 72, 82, 0.1)";
			ctx.beginPath();
			ctx.moveTo(startX, startY);
			ctx.lineTo(x, y);
			ctx.stroke();
			
		} else {
			firstRun = false;
		}
				
		startX = x;
		startY = y;
		
	}
	
	
	
	// draw complex circle, triggered with stage click.
	
	function drawComplexCircle(x, y) {
		
		_gaq.push(['_trackEvent', 'drawing', 'circle', 'complex']);
		
		var circleRadius = 52;
		var tickRadius = 70;
		
		// increment created element for reference.
		objNum++;
		complexNum++;
		
		// make new canvas element, set width, height
		$('#stage-complex').append('<canvas class="art complex" id="obj-'+objNum+'" width="'+(tickRadius*2)+'" height="'+(tickRadius*2)+'"></canvas>');
		
		// position
		$('#obj-'+objNum).css({'left' : (x-tickRadius)+'px', 'top' : (y-tickRadius)+'px'});
		
		var ctx = $('#obj-'+objNum)[0].getContext('2d');
		
		ctx.strokeStyle = "rgba(74, 157, 216, 0.3)";
		
		var rotationInc = Math.PI/36;		
		rot = rotationInc;
		
		// draw spokes
		for(var i=1; i<=72; i++) {
			x1 = tickRadius + (tickRadius - 10) * Math.cos(rot);
			y1 = tickRadius + (tickRadius - 10) * Math.sin(rot);
			x2 = tickRadius + (tickRadius) * Math.cos(rot);
			y2 = tickRadius + (tickRadius) * Math.sin(rot);
			
			ctx.beginPath();
			ctx.moveTo(x1, y1);
			ctx.lineTo(x2, y2);
			ctx.stroke();
			
			rot += rotationInc;
		}
		
		// draw faded inner circle
		ctx.fillStyle = "rgba(127, 186, 228, 0.2)";
		ctx.beginPath();
		ctx.arc((circleRadius+18), (circleRadius+18), circleRadius, 0, Math.PI*2, true);
		ctx.fill();
		
		// draw filled inner circle
		ctx.fillStyle = "rgba(127, 186, 228, 1)";
		ctx.beginPath();
		ctx.arc((circleRadius+18), (circleRadius+18), 4, 0, Math.PI*2, true);
		ctx.fill();
		
		// draw stroked inner circle
		ctx.fillStyle = "rgba(127, 186, 228, 1)";
		ctx.beginPath();
		ctx.arc((circleRadius+18), (circleRadius+18), (circleRadius/6), 0, Math.PI*2, true);
		ctx.stroke();
		
		return objNum;
		
	}
	
	
	
});
