/** 
 * Main jQuery document.ready function. It works out which page we're on
 * based on the ID of the body then runs the appropriate function from the
 * ONE object based on that
 *
 * The reason for the ONE object is to make sure that any dodgily written 
 * plugins can't get in the way of the names of our functions/variables.
 *
 * NOTE: Sorry if I've over-commented and am treating you like a n00b - 
 *       thought it would be better to over-comment than to under-comment :)
 */
$(function () {
	// faster than using jQuery to find the ID of <body>, same as doing:
	// $("body").attr("id");
	var body_id = document.body.id;
	
	// work out which section we're in and run the appropriate function
	switch (body_id)
	{
		case 'hello':
			ONE.home();
			break;
		case 'who-we-are':
			ONE.who();
			break;
		case 'come-say-hi':
			ONE.where();
			break;
		case 'what-we-do':
			ONE.what();
			break;
	}

	// finally, run the function for common stuff (like navigation jiggling)
	ONE.common();
});



/**
 * Object to hold all of the functionality for the website. To use one of the 
 * functions from it, use ONE.function_name(); 
 *
 * NOTE: You can only call functions which begin with function_name: function (),
 *       all of the other functions inside these functions are only visible inside
 *       of the 'outer' function. For example, the function 'cock_the_gun' can only
 *       be called from INSIDE the function 'home'. Think of them as local
 *       variables.
 */
var ONE = {

	/**
	 * Functionaliy for the home page. In a nutshell this includes:
	 * 	- code for the animation of the gun (most of the code is for this
	 *  - stuff to animate the lights on party gossip (now obsolete as party gossip
	 *    has gone. Left in incase we need the functionality again)
	 *  - jiggle animation for rollover of 'some client loveliness'
	 *  - carousel action for 'in the studio', 'client loveliness' and (the obsolete)
	 *    party gossip
	 */
	home: function () {
		// variables and utility functions 
		var timer, // used to keep track of what the 'shoot the designer' animation is doing
			bullet_timer, // sme as above
			flashing_lights_timer, // same as above but for party gossip
			flashing_lights_counter=0, // used to work out which gif to use for party gossip animation
			img_preload = [], // array to store images which we need to preload for smooth animation (OLD SKOOL!)

			/**
			 * Add the bullet hole on the main banner. This function is called by 
			 * shoot_the_designer via a setTimeout. 
			 *
			 * After it's run, it will call resuscitate_designer in 5 minutes
			 * which removes the bullet hole and resets some classes.
			 */
			add_bullet_hole = function () {
				document.getElementById('bullet').style.display = 'block';
				setTimeout(resuscitate_designer, 5000);
			},
			
			/**
			 * Makes the gun move backwards and forwards
			 */
			cock_the_gun = function () {
				$("#shooter").animate ({
					marginLeft: '-30px'
				}, 100).animate ({
					marginLeft: '0'
				}, 50);
			},
			
			/**
			 * Main function to start the shooting animation. I think it's best
			 * to comment this line-by-line, so read into the function for more!
			 */
			shoot_the_designer = function () {
				// pre-run indicates that the animation is not currently running.
				// if we don't have that class, the animation is running, so 
				// return straight away
				if (!$(this).hasClass('pre-run')) return;
				
				// use modernizr to work out if we're in a browser which supports
				// CSS transitions or not. If so, use CSS animation and simply add
				// the bullet hole with javascript, otherwise, animate the gun with
				// javascript then add the bullet hole.
				if ($("html").hasClass("no-csstransitions")) {
					// non-css animation 
					cock_the_gun ();
					// add the bullet hole after the gun has fired
					setTimeout (add_bullet_hole, 100);
					
					// stop the animation from running again by removing the pre-run class.
					// (pre-run will be added again by 'resuscitate_designer' via add_bullet_hole)
					setTimeout (function () {$("#banner").removeClass('pre-run');}, 100);
				} else { // use CSS transitions 
					// add bullet hole in 0.4 seconds (after CSS animations have run)
					timer = setTimeout (add_bullet_hole, 400);
					// stop the animation from running again by... (see comment above for full
					// explanation!)
					setTimeout (function () {$("#banner").removeClass('pre-run');}, 1000);
				}
			},
			
			/**
			 * Stop the shot from firing! The way that this works is to simply cancel the 
			 * function which was going to run after the timout (if that makes sense). We
			 * we set a variable to keep track of the timer when we call setTimeout on line 122,
			 * so we can just stop it from running at-all by clearing it. 
			 *
			 * This function is called by $("#banner").mouseOut() (through the hoverIntent plugin)
			 */
			abort_shot = function () {
				if (timer) clearTimeout(timer);
			},
			
			/**
			 * Reset the shoot the designer animation to as if the page has just loaded. This is 
			 * called 5 seconds after the bullet has been shot by a setTimeout in 'add_bullet_hole'.
			 */
			resuscitate_designer = function () {
				$("#banner").addClass ('pre-run');
				$("#bullet").fadeOut(function () {$(this).css({display: 'none'})});
			},
			
			/**
			 * Start the party gossip flashing lights animation. This is made up from 4 gifs
			 */
			start_lights = function () {
				// scary looking thing, but what it does is increments flashing_lights_counter, modulo
				// divides by 4 and adds 1. This gives us a number between 1 and 4.
				var number = (++flashing_lights_counter%2+1);
				// change background image based on var number background-image: url(images/home/new-home/what-we-are-doing-1.gif);
				$("#doing-now-tactical h2").css('background-image', 'url(/wordpress/wp-content/themes/think-create-deliver/images/home/new-home/what-we-are-doing-' + number + '.gif)');
				// call this function again in 0.1 seconds. Use flashing_lights_timer to keep track
				// of the setTimeout so that it can be cancelled to stop the lights
				flashing_lights_timer = setTimeout(arguments.callee, 200);
			},
			
			/**
			 * Stop the party gossip flashing lights animation. 
			 */
			stop_lights = function () {
				// cancel the timeout causing the animation
				clearTimeout(flashing_lights_timer);
				// reset to the original background image
				$("#doing-now-tactical h2").css('background-image', 'url(/wordpress/wp-content/themes/think-create-deliver/images/home/new-home/what-we-are-doing-1.gif)');
			},
			/**
			 * Preload images
			 */
			preload_gossip = function () {
				for (var i = 1; i <= 2; i++) {
					// fake img tag
					var img = document.createElement('img');
					// set src
					img.src = '/wordpress/wp-content/themes/think-create-deliver/images/home/new-home/what-we-are-doing-' + i + '.gif';
					// add to array
					img_preload.push (img);
				}
			};



		/*******************************************************************************************
		********************************************************************************************
		******************************* now to use the functionality! ******************************
		********************************************************************************************
		*******************************************************************************************/


		// start the animation when the user rolls over the main banner.
		$("#banner").hoverIntent ({
				over: shoot_the_designer, // start the animation
				out: abort_shot, // about the animation
				interval: 200 // delay before performing the action
			})
			.click (function () {
				location.href = $(this).find("a").get(0).href; // same as $(...).clickableBlocks()
			}).css({cursor: 'pointer'});

		$("#navigation a.with-children").click( function(e) { e.preventDefault(); } );

		$("#bring-it-on a").fancybox({
			'titleShow'     : false,
			'transitionIn'	: 'elastic',
			'transitionOut'	: 'elastic',
			'easingIn'      : 'easeOutBack',
			'easingOut'     : 'easeInBack'
		});

		$("#strokes").jiggleBackground({distance: 2, speed: 75}); // exactly what it says on the tin
		$("#doing-now-tactical").hover (start_lights, stop_lights); // as you'd expect
		preload_gossip(); // preload images
		
		// this is the code for the carousels.
		$("#gossip ul, #strokes ul, #tactical ul,#new-strokes ul, #doing-now-tactical ul").each (function () {
			var height = 0, // to normalise the hights
				current = 1, // to keep track of the current showing item
				that = this, // so that we can keep track of 'this' inside another function (where 
				             // 'this' means something different.
				width = $(this).width(), // width of the carousel element items
				total = $(this).find('li').css({'width': width}).length, // number of items to scroll

				// this is where the magic lives! 
				scroll = function () {
					next = current+1; // move onto the next item
					if (next > total) { // if next > total, reset next
						next = 1;
					}
					/******* NOTE FOR THE NEXT FEW NOTES:  THESE ELEMENTS ARE POSITION : ABSOLUTE ****
					*******    WITHOUT A BETTER WORD TO USE, I'M USING 'STAGE' TO REPRESENT     ******
					***                               VIEWABLE AREA                               ***/
					// big set of selectors and animations all in one line, but when you understand it,
					// it makes sense ;) Basically, this happens:
					//     - Move the current item left by WIDTH_OF_ELEMENT (moving it off the stage)
					//	      while fading it out. Afterwards, hide it.
					$(that).find('li:nth-child(' + current + ')').animate({left:-width, opacity: 0}, {duration: 500, easing:'easeInOutExpo'}, function () {$(this).hide()});
					// again, big set of selectors, but here goes:
					//     - move the next element to WIDTH_OF_ELEMENT (moving it to the right of the 
					//        stage). Animate it to left: 0 (moving it into the stage) an fade it in.
					$(that).find('li:nth-child(' + next + ')').css({left: width, opacity: 0}).show().animate({left: 0, opacity: 1}, {duration: 500, easing:'easeInOutExpo'});
					
					// update where we are
					current = next;
					
					// call this function again in 10 seconds
					setTimeout(scroll, 10000);
				};
			
			
			
			
			// normalise heights so that the scrolling works as expected
			$(this).find('li').each (function () {
				if ($(this).height() > height) {
					height = $(this).height();
				}
				$(this).css({position:'absolute'});
			});
			$(this).height(height + 50).css({position:'relative'});
			
			// hide anything apart from the currently visible item
			$(this).find('li:not(:first-child)').hide();
			
			// call scroll for the first time in 10 seconds. Afterwards, it'll call itself
			setTimeout(scroll, 10000);
		});
		
	},
	
	/**
	 * functionaliy for the WHO section. In a nutshell:
	 *   - adds in more / less links
	 *   - makes the list slide when you press more / less 
	 */
	who: function () {
		var $more = $('<span class="more_slide"></span>'), // to click to move right
			$less = $('<span class="less_slide"></span>').hide(), // click to move left
			current_page = 0, // current 'page' showing
			width = $("#our-team").width(), // how far should it slide?
			
			
			/**
			 * NOTE: I'll only comment slide_left. slide_right works on the exact same principles,
			 * only in reverse :)
			 */
			// exactly what it says on the tin
			slide_left = function () {
				$more.fadeIn(250); // if we're moving left, there'll ALWAYS be something on the right
				$("#our-team").scrollTo('-=' + width /** move by WIDTH */, { 
					duration: 1000, 
					onAfter: function () {
						current_page--; // animtion complete so update 
						if (current_page <= 0) {
							current_page = 0;
							$less.fadeOut(250);
						}
					},
					easing: 'easeInOutExpo'
				});
			},
			slide_right = function () { // see slide_left - only in reverse ;)
				$less.fadeIn(250);
				$("#our-team").scrollTo('+=' + width, {
					duration: 1000,
					onAfter: function () {
						current_page++;
						if (current_page >= 3) {
							current_page = 3;
							$more.fadeOut(250);
						}
					},
					easing: 'easeInOutExpo'
				});
			}

		/**
		 * Rationale for the next two lines: If people have JS turned off, they can still scroll
		 * left / right with the browser horizonal scrollbar to see everyone. We're just hijacking 
		 * it here to use javascript instead. If we did it all in CSS, people would only be able
		 * to see the first 6 team members without being able to scroll.
		 */
		// removes scrollbars from the div
		$("#our-team").css({'overflow': 'hidden'});
		// add navigation
		$("#our-team").append ($more, $less);
		
		// add functionality
		$more.click (slide_right);
		$less.click (slide_left);
	},
	/**
	 * Not much to do on this page, just jiggle the blocks on rollover :)
	 */
	where: function () {
		$("#twitter a").jiggle({useModernizr:false});
		$("#email a").jiggle({useModernizr:false});
		$("#address a").jiggle({useModernizr:false});
	},
	/**
	 * Very similar to the 'who' page - the same logic appears here as for that page :)
	 */
	what: function () {
		var $more = $('<span class="more_slide"></span>'), // elem we create to move right
			$less = $('<span class="less_slide"></span>').hide(), // elem we create to move left
			$container = $("#things-we-have-slaved-over").wrap('<div class="slider-container" />').parent(),
			number_of_items = $("#things-we-have-slaved-over li").length, // number of items
			current_item = 1, 
			is_animating = false,
			setup_portfolio = function () {
				var height = 0;
				$("#things-we-have-slaved-over li").css({position:'absolute',top:0}).each (function () {
					if ($(this).height() > height)
						height = $(this).height();
				});
				$("#things-we-have-slaved-over").height(height)
				$("#things-we-have-slaved-over li:not(:first-child)").hide();
				$("#container").append($more, $less);
			}, // end steup_portfolio
			next_case_study = function () {
				if (is_animating) return;
				is_animating = true;
				var current = current_item,
					next = current + 1,
					next_anim = next;
				$less.fadeIn();
				if (next >= number_of_items) {
					$more.fadeOut();
				}
				$("#things-we-have-slaved-over li:nth-child(" + current + ")")
					.animate({left:-1057, opacity: 0}, {easing: 'easeInOutExpo', duration: 1000}, function () {$(this).hide();})
				$("#things-we-have-slaved-over li:nth-child(" + next_anim + ")")
					.css({left:1057, opacity: 0}).show()
					.animate({left:0, opacity:1}, {easing: 'easeInOutExpo', duration: 1000});
				current_item = next;
				setTimeout (stopped_animating, 900);
			}, // end next_case_study()
			previous_case_study = function () {
				if (is_animating) return;
				is_animating = true;
				var current = current_item,
					prev = current - 1;
				$more.fadeIn();
				if (prev <= 0) {
					prev = number_of_items;
				}
				if (prev <= 1) {
					$less.fadeOut();
				}
				$("#things-we-have-slaved-over li:nth-child(" + current + ")")
					.animate({left:1057, opacity: 0}, {easing: 'easeInOutExpo', duration: 1000}, function () {$(this).hide();});
				$("#things-we-have-slaved-over li:nth-child(" + prev + ")")
					.css({left:-1057, opacity: 0}).show()
					.animate({left: 0, opacity: 1}, {easing: 'easeInOutExpo', duration: 1000});
				current_item = prev;
				setTimeout (stopped_animating, 900);
			}, // end previous_case_study();
			stopped_animating = function () {
				is_animating = false;
			};
			
			setup_portfolio();
			$more.click (next_case_study);
			$less.click (previous_case_study);
			$(".see-the-site a").jiggle();
	},
	
	/** 
	 * Finally, run everything which is needed by all pages!
	 */
	common: function () {
		$("#navigation a:not(.with-children)").jiggle();
	}
};
