/* GROUP FLEXSLIDER INSTRUCTIONS
____________________________________________________________________________________________________ */
// =Jay. Start the Flexslider.
$(window).load(function() {
	if($('body').hasClass('page-template-template-page-web-php')) {
		$('.no-touch .flexslider').flexslider({
			slideshowSpeed: 4000,
			/* =Jay. After the slider has started... */
			start: function(slider) {
				/* =Jay. Stop the slider when clicking a thumb. */
				$('.thumb').click(function(){
					slider.pause();
				});
			}
		});

		$('.no-video .flexslider').flexslider({
			slideshowSpeed: 4000,
			/* =Jay. After the slider has started... */
			start: function(slider) {
				/* =Jay. Stop the slider when clicking a thumb. */
				$('.thumb').click(function(){
					slider.pause();
				});
			}
		});

	} else {
		$('.flexslider').flexslider({
			slideshowSpeed: 4000,
			/* =Jay. After the slider has started... */
			start: function(slider) {
				/* =Jay. Stop the slider when clicking a thumb. */
				$('.thumb').click(function(){
					slider.pause();
				});
			}
		});
	}
});

/* GROUP FITVIDS TARGET
____________________________________________________________________________________________________ */
$(document).ready(function(){
// Target your .container, .wrapper, .post, etc.
	$(".flexslider").fitVids();
});


/* GROUP YOUTUBE MANIPULATION
____________________________________________________________________________________________________ */
/* =Jay. Add ?&wmode=opaque to iframes. */
function changeYoutube() {
	$('iframe').each(function () {

		var that = $(this);
		var href = that.attr('src');

		if (href.search('youtube.com') !== -1) {
			that.attr('src', href + '?&wmode=opaque');
			// code to get id
			var tmp = href.split("?");
			var tmp2 = tmp[0].split("/");
			var ID = tmp2[tmp2.length - 1];
		}
	});
}

$(document).ready(function () {
	changeYoutube();
});

$('.page-template-template-page-web-php .video .flex-caption').before('<div class="touch-message">Touch the play button above to start the video</div>');


/* GROUP YOUTUBE API
____________________________________________________________________________________________________ */
function getFrameID(id) {
	var elem = document.getElementById(id);
	if (elem) {
		if (/^iframe$/i.test(elem.tagName)) return id; //Frame, OK
		// else: Look for frame
		var elems = elem.getElementsByTagName("iframe");
		if (!elems.length) return null; //No iframe found, FAILURE
		for (var i = 0; i < elems.length; i++) {
			if (/^https?:\/\/(?:www\.)?youtube(?:-nocookie)?\.com(\/|$)/i.test(elems[i].src)) break;
		}
		elem = elems[i]; //The only, or the best iFrame
		if (elem.id) return elem.id; //Existing ID, return it
		// else: Create a new ID
		do { //Keep postfixing `-frame` until the ID is unique
			id += "-frame";
		} while (document.getElementById(id));
		elem.id = id;
		return id;
	}
	// If no element, return null.
	return null;
}

// Define YT_ready function.
var YT_ready = (function() {
	var onReady_funcs = [],
		api_isReady = false;
/* @param func function     Function to execute on ready
		 * @param func Boolean      If true, all qeued functions are executed
		 * @param b_before Boolean  If true, the func will added to the first
									 position in the queue*/
	return function(func, b_before) {
		if (func === true) {
			api_isReady = true;
			for (var i = 0; i < onReady_funcs.length; i++) {
				// Removes the first func from the array, and execute func
				onReady_funcs.shift()();
			}
		}
		else if (typeof func === "function") {
			if (api_isReady) func();
			else onReady_funcs[b_before ? "unshift" : "push"](func);
		}
	};
})();
// This function will be called when the API is fully loaded

function onYouTubePlayerAPIReady() {
	YT_ready(true)
}

var players = {};
//Define a player storage object, to enable later function calls,
//  without having to create a new class instance again.
YT_ready(function() {
	$(".fluid-width-video-wrapper").children().each(function() {
		var identifier = this.id;
		var frameID = getFrameID(identifier);
		if (frameID) { //If the frame exists
			players[frameID] = new YT.Player(frameID, {
				events: {
					"onReady": createYTEvent(frameID, identifier),
					"onStateChange": stopCycle
				}
			});
		}
	});
});


// Returns a function to enable multiple events
function createYTEvent(frameID, identifier) {
	return function (event) {
		var player = players[frameID]; // player object
		var the_div = $('#'+identifier).parents();
		the_div.children('.thumb').click(function() {
			var $this = $(this);
			var $body = $('body');
			$this.slideUp().next().addClass('play');

			if($('html').hasClass('no-touch')) {
				if ($this.next().hasClass('play')) {
					player.playVideo();
				}
			}

			/* =Jay. Touch device instructions. */
			$('.play').next().addClass('unhidden');
			setTimeout(function() {
				$('.play').next().fadeOut();
			}, 5000);

			/* =Jay. When visitor clicks next or previous... */
			$('.flex-direction-nav').click(function(){
				$this.slideDown();
				/* =Jay. If the video is playing... */
				if ($this.next().hasClass('play')) {
					player.pauseVideo();
				}
			});
		});
	};
}


/* =Jay. Take from YouTube API Reference document - http://code.google.com/apis/youtube/iframe_api_reference.html#Examples */
/* onStateChange
This event fires whenever the player's state changes. The data property of the event object that the API passes to your event listener function will specify an integer that corresponds to the new player state. Possible data values are:
-1 (unstarted)
0 (ended)
1 (playing)
2 (paused)
3 (buffering)
5 (video cued). */

// Example: function stopCycle, bound to onStateChange
function stopCycle(event) {
	/* =Jay. event.data spits out onStateChange. Using this we can do things with if events. */
	if((event.data)=== 0) {
		$('.no-touch .thumb').slideDown();
	}
}

// Load YouTube Frame API
(function(){ //Closure, to not leak to the scope
  var s = document.createElement("script");
  s.src = "http://www.youtube.com/player_api"; /* Load Player API*/
  var before = document.getElementsByTagName("script")[0];
  before.parentNode.insertBefore(s, before);
})();


/* WORDPRESS STANDARD NAVIGATION ANIMATION
____________________________________________________________________________________________________ */
$(document).ready (function(){
//	nav ul li:hover > ul.css
	$('nav ul li').hover(function(){
		$(this).children('ul')
		.slideDown('fast');
	}, function(){
		$(this).find('ul')
		.slideUp('fast');
	});
});



/* GROUP HOMEPAGE
____________________________________________________________________________________________________ */
$(document).ready (function(){
	var fadeTarget = $('.home #content, .home #social-media')

	$(fadeTarget).hide();
	setTimeout(function() {
		$(fadeTarget).fadeIn();
	}, 1500);
});



/* OUR CLIENTS
____________________________________________________________________________________________________ */
$('#our-clients, #exit').click(function(){
	/* =Jay. Release body width restraint for non-homepages. */
	$('body').toggleClass('body-release');
	$('#white-blanket, #portfolio-overlay').fadeToggle('slow');
	/* =Jay. Needed to hide under the portfolio-overlay. */
	$('nav#contact, nav#our-clients').fadeToggle().toggleClass('underneath');
});

//=Jay. Scroll to top of the page on entering and exiting the client list.
$("#our-clients, #exit").click(function(e) {
	e.preventDefault();
	$('html, body').animate({ scrollTop: $(this.hash)});
});


/* NAVIGATION
____________________________________________________________________________________________________ */
$('#show-nav').click(function(){
	$('nav#standard').fadeToggle();
	$(this).toggleClass('compact');
	$('#nav-text, #nav-arrow').toggleClass('hide');
});

/* PR + MARKETING / BIOG
____________________________________________________________________________________________________ */
/* AUTHOR */
$('#latest-post .author').click(function(){
	if (jQuery.browser.msie && jQuery.browser.version <= 7) {
		$('.biog').fadeToggle();
	} else if ($('#latest-post').hasClass('revealed')) {
		$('.biog, .avatar-wrapper').fadeToggle();
	} else if ($('.avatar-wrapper').css('display') === 'none') {
		$('#latest-post').addClass('revealed');
		$('#latest-post .avatar-wrapper, .biog').fadeToggle();
	} else {
		$('.biog').fadeToggle();
	}
});

/* SERVICES */
/* =Jay. Do some jiggery pokery and add some stuff ready for hiding. */
$('.page-information h2').addClass('reveal');
$('.page-information .reveal').prepend('<span class="hide-toggle">Click to Read About </span>');

$('.reveal').click(function(){
	if (windowWidth < 1024 || (jQuery.browser.msie && jQuery.browser.version < 8)) {
		$('#reveal, .hide-toggle').fadeToggle().toggleClass('expanded');
	}
});

function calculateWidth() {
	windowWidth = $(window).width();
	if (windowWidth >= 1024) {
		$('#reveal').css('display','inherit');
	} else if ($('#reveal').hasClass('expanded')) { /* Do Nothing */ } else {
		$('#reveal').css('display','none');
	}
};

$(document).ready(function() {
    calculateWidth();
});

$(window).resize(function() {
    calculateWidth();
});



/* GROUP GRAPHICS
____________________________________________________________________________________________________ */
/* =Jay. Scroll to link. */
jQuery(document).ready(function($) {
//=Jay. Smooth scroll. Need specific target areas because it disables normal links.
$(".page-template-template-page-graphics-php #content a").click(function(e) {
	e.preventDefault();
	$('html, body').animate({ scrollTop: $(this.hash).offset().top });
});
});



/* CONTACT MAP
____________________________________________________________________________________________________ */
$('#show-map').click(function(){
	$('#map_canvas').fadeToggle();
	$('.toggle').toggleClass('hide');
	/* =Jay. Refresh map shortly after the div has been expanded. */
	setTimeout(function() {
		initialize();
	}, 500);
});

/* NIGHT THEME
____________________________________________________________________________________________________ */
var day = new Date().getDay();
var hours = new Date().getHours();
var minutes = new Date().getMinutes();

$(function(){
	/* =Jay. If it's the weekend then always activate Night. */
	if (day === 6 || day === 0) {
		$('body').addClass('night');
	} else {
		// =Jay. Night Active between 1730 and 930
		if (hours === 17 && minutes >= 30) {
			$('body').addClass('night');
		} else if (hours >= 18 || hours < 9) {
			$('body').addClass('night');
		} else if (hours === 9 && minutes <=30) {
			$('body').addClass('night');
		/* =Jay. Friday */
		} else if (day === 5 && ((hours === 16 && minutes >= 30) || (hours === 17))) {
			$('body').addClass('night');
		}
	}
});

$(document).ready(function(){
	if($('body').hasClass('page-template-template-page-homepage-php') && $('body').hasClass('night')) {
		if (Modernizr.backgroundsize) {
			$('.night.home header h1').fadeIn(10000);
		} else {
			$('.no-backgroundsize .night.home header h1').fadeIn(10000);
		}
	}
});
