// remap jQuery to $
(function ($) {})(window.jQuery);

var varenhorst = {
	UA : navigator.userAgent,

	isDesktop : (parseInt($(window).width(), 10) > 640 && parseInt($(window).width(), 10) != screen.width || parseInt($(window).width(), 10) > 1024),

	TSTYLE : null,

	init : function () {
		var that = this;
		this.TSTYLE = that.setTransitionStyle();

		this.menu.init();
		
		that.hideUrlBar();

		that.search.init();
	},

	// Hide URL Bar for iOS
	// http://remysharp.com/2010/08/05/doing-it-right-skipping-the-iphone-url-bar/	
	hideUrlBar : function () {
		/iPhone/.test(this.UA) && !location.hash && setTimeout(function () {
			pageYOffset || window.scrollTo(0, 1);
		}, 1000);
	},
	setTransitionStyle : function () {
		var dStyle = document.body.style,
			that = this;
		return (dStyle.webkitTransition !== undefined) ? "-webkit-transition":
			(dStyle.mozTransition !== undefined) ? "-moz-transition":
			(dStyle.msTransition !== undefined) ? "-ms-transition":
			(dStyle.oTransition !== undefined) ? "-o-transition":
			(dStyle.transition !== undefined) ? "transition":
											null; // nothing doing? then we'll use jQuery animation
	},

	bio : {

		settings : {
			thumbnailSelector : ".bios li",
			sliderSelector : ".slider",
			bioWrapperSelector : ".bioContent",
			colCount : null,
			columns : [],
			bioWidth : 165,
			speed : 400, // how fast do the transitions to happen (in ms)

			// slider variables
			viewPortLeft : null

		},

		init : function () {

			var that = this,
				speed = that.settings.speed,
				tStyle = varenhorst.TSTYLE;

			// setting it and using the result as a condition
			if (tStyle) {
				$(".bios li, .bioText").css(tStyle + "-property", "margin, padding, width, background")
							.css(tStyle + "-duration", speed + "ms")
							.css(tStyle + "-timing-function", "ease");
			} else {

			}

			$(".bios li .bioText").click(function (e) {
				e.preventDefault();
				return false;
			});

			$(".bios li .bioText .close").click(function (e) {
				$(this).parent().parent().click();
			});

			$(".bios li").click(function (e) {
				e.preventDefault();
				// if it's not active...
				if (!($(this).hasClass('active'))) {

					that.activate($(this));

				} else { // if it is active...

					that.deactivate($(this));

				}

				return false;

			});

		}, // end bio.init()
		checkTrailers : function () {
			var that = this;

			// wait till it's moved, then check trailing elements
			setTimeout(function () { 
				if (varenhorst.mySlider) {
					varenhorst.mySlider.findTrailingElements();
				}

			}, that.settings.speed); 
		},
		move : function ($t, direction) {
			var that = this;

			if (varenhorst.TSTYLE) {

				// move it
				$t.removeClass('back forward').addClass(direction);

				// wait till it's moved, then check trailing elements
				that.checkTrailers();

			} else {
				if (varenhorst.mySlider) {
					distance = (direction == 'forward') ? "318px": "-18px";
					$t.animate({
						marginLeft: distance
					}, that.settings.speed, function () {
						varenhorst.mySlider.findTrailingElements(); // now they've moved, check for trailers
					});
				}
			}
		},
		activate : function ($t) {

			var that = this,
			bioPosition = $t.position();// where should the bioText box start?

			// reset to zero
			that.deactivate($('.active'));
			if (varenhorst.mySlider) {

				// find out column number by referencing the array created on init by the slider plugin
				whichCol = jQuery.inArray(bioPosition.left, varenhorst.mySlider.settings.columnLeftValues);

				// if it's not the last image in a row, move everything after it out of the way
				// to make space for the bio
				if ((whichCol + 1) != varenhorst.mySlider.settings.colCount) {
					
					for (var i = whichCol + 1, ln = varenhorst.mySlider.settings.columns.length; i < ln; i++) {
						// columns
						for (var n = 0, lno = varenhorst.mySlider.settings.columns[i].length; n < lno; n++) {
							// rows within the selected column
							that.move(varenhorst.mySlider.settings.columns[i][n], 'forward');
						}
					}
				} else {
					// nothing!
				}
			}

			// check to see if there's enough space for the bio.
			if (varenhorst.mySlider && varenhorst.mySlider.settings.viewPortLeft + $(window).width() < bioPosition.left + 500) {

				// there isn't, so let's move the slide on to make some space.

				varenhorst.mySlider.moveSliderToElement($t);

				$('.prev:hidden').fadeIn();
			}
			if (varenhorst.TSTYLE) {

				$t.addClass('active');
				if (varenhorst.mySlider) {
					$t.children('.bioText').css({
						'height': bioTextMinHeight,
						'top': (0 - bioPosition.top + 18)
					});
				}

			} else {
				if ($('.active').length) { // if there's one open, shut it first
					$t.addClass('active').animate({
						marginRight: -5,
						paddingRight: 18
					}, 0, function () {
						$t.children(".bioText")
							.css('height', bioTextMinHeight)
							.css('top', (0 - bioPosition.top + 18))
							.animate({
								width: 330
							}, 400);
					});
				} else {
					$t.addClass('active')
						.children(".bioText")
						.css('height', bioTextMinHeight)
						.css('top', (0 - bioPosition.top + 18))
						.animate({
							width: 330
						}, 400);
				}
			}
		},

		deactivate : function ($t) {
			var that = varenhorst.bio; 
			$t = $t || $('.active'); // if we're not given something, assume we're shutting everything

			$t.removeClass('active');

			that.move($(".bios li"), 'back');

			if (!varenhorst.TSTYLE) {
				$t.children(".bioText")
				.css("width", "0");

			}
		}
	}, // end bio

	search : {
		init : function () {
			var that = this,
				$mainSearch = $("form.mainSearch");

			$mainSearch.bind('click', varenhorst.search.bindings);

			$('.close-search').click(function () {

				$('body').removeClass('search-active');

				$mainSearch
					.removeClass("active")
					.find('input')
					.removeClass('active');

				setTimeout(function () {
					$("form.mainSearch").bind('click', varenhorst.search.bindings);
				}, 500);

			});

			$("form.mainSearch input.search").focus(function () {

				$(this).addClass('active');

			});

			$("form.mainSearch input.search").blur(function () {
				$(this).removeClass('active');

			});

		},
		focus : function () {

			var event,
				searchElement = document.querySelector('input.search'),
				eventName = 'focus';

			// the following is grabbed from prototype, to see if it's any better at invoking the keyboard	
			if (document.createEvent) {
				event = document.createEvent("HTMLEvents");
				event.initEvent("focus", true, true);
			} else {
				event = document.createEventObject();
				event.eventType = "focus";
			}

			event.eventName = eventName;
			event.memo = { };

			if (document.createEvent) {
				searchElement.dispatchEvent(event);
			} else {
				searchElement.fireEvent(event.eventType, event);
			}

			$('.search').focus();

		},

		bindings : function () {
			var $that = $("form.mainSearch");

			if (!$that.hasClass("active")) {

				if (!varenhorst.TSTYLE) {

					$that.animate({
						right: 46, 
						width: 249
					}, 400, function () {

						$("form.mainSearch input.search").focus();

					});

				} else {

					$('body').addClass('search-active');
					// if you focus immediately, the content get's pushed out of position, and there's no way to return it.
					// also, see http://stackoverflow.com/questions/6866433/focus-not-working-within-settimeout-on-ios/
					setTimeout(varenhorst.search.focus, 600);

				}

				$that
					.unbind('click', varenhorst.search.bindings)
					.addClass("active");

				return false;
			}
		}
	},

	// real nav functions
	menu : {

		init : function () {
			var that = this;

			// bindings
			
			$('.menu-toggle').click(function (e) {
				e.preventDefault();
				// add overlay
				$('header.uber').toggleClass('uberActive');
				
				// open menu items
				if ($('header.uber').hasClass('uberActive')) {
					$("nav ul").eq(1).addClass("active");
					$('.collapsed').removeClass('collapsed');
				} else {
					$("nav ul").eq(1).removeClass("active");
					$('.collapsed').addClass('collapsed');
				}

			});

			$("nav ul a").live('click', function (e) {

				$('.breadcrumb').addClass('active collapsed breadcrumbInactive').removeClass('breadcrumb');

				e.preventDefault();

				var menuCount, oldMenuCount;

				if ($(this).hasClass('top') && !$('.menu-1').length) {

					if ($(this).next().hasClass('active collapsed')) {

						$(this).next().removeClass('collapsed');
						$('header.uber').toggleClass('uberActive');
						$('nav ul').not('.prime').removeClass('active collapsed');

					} else {
				
						$(this)
						.next()
						.toggleClass('active')
						.find('.active')
						.removeClass('active');
						$('header.uber').toggleClass('uberActive');
						$('.collapsed').toggleClass('collapsed');
		
					};

					return false;
				}

				// move backwards in mobile menu only (mobile menu is the only one that has back-button implemented)
				if ($(this).parent().hasClass('back-button')) {

					// close the active menu and remove the back-button element
					$('ul.active')
						.eq(-1)
						.removeClass('active')
						.find('.back-button')
						.remove();

					// make sure the menu we're going to is visisble.
					$('ul.active')
						.eq(-1)
						.removeClass('collapsed');

					// move the menu
					that.checkMenuDepth(true);

					// stop any further activity
					return false;
				}
				if ($(this).parent("li").hasClass("parent")) { // has at least one child UL

					$(this)
						.next()
						.addClass('active') // activate the current menu
						.parent()
						.closest('ul')
						.addClass('collapsed'); // collapse the previous menu

					// mobile menu behaviours
					if (! varenhorst.isDesktop) {

						// move the menu
						that.checkMenuDepth(true);

						// grab a copy of the label, to use as a back button
						var $link = $(this).parents('ul').eq(0).prev().clone();

						//Place it at the top of the new menu
						$('<li />', {
							className: 'back-button'
						}).append($link)
						.insertAfter($('header.uber ul.active').eq(-1).find('.label').eq(0));
					}

					return false;

				} else {

					if ($(this).hasClass("top")) { // home label

						$("nav ul").removeClass('collapsed').removeClass("active");
						$("nav a.top + ul").addClass("active");

						$('.back-button').remove();

						// for the mobile menu 
						that.checkMenuDepth(true);

						return false;

					} else if ($(this).parent().hasClass("label")) { // breadcrumbs

						// for the desktop menu 
						if (varenhorst.isDesktop) {

							$(this)
								.closest("ul.active")
								.toggleClass('collapsed') // toggle the menu below
								.find('ul.active')
								.removeClass('active'); // hide the children menus

						}
						return false;

					} else { // single-target links

						window.location = $(this).attr('href');

					}

				}

			});

		},

		// changes the depth (horizontal position) of the menu. 
		// if animated argument is truth then the move will be animated.
		checkMenuDepth : function (animated) {
			var menuCount = $('.uber nav .active').length - 1;
			if (!animated) {
				$('.uber').addClass('no-animation');
			}
			$('.uber nav').removeClass('menu-0 menu-1 menu-2 menu-3').addClass('menu-' + menuCount);
			if (!animated) {
				$('.uber').removeClass('no-animation');
			}

		}
	
	}
	
};

$(document).ready(function () {

	varenhorst.init();

	// carousel functions
	var winWidth = parseInt($(window).width(), 10),
		screenWidth = screen.width;

	// bio functions
	if ($('.bios').length) { // but only if there is one

		varenhorst.bio.init();

		if (winWidth > 640 && winWidth != screenWidth || screenWidth > 960) { // only initialize the carousel if the window's big enough
			varenhorst.mySlider = new arbitraryCarousel();
			varenhorst.mySlider.init('#slider', {
				itemSelector : 'li',
				modulus : 3,
				slideControlsContainerSelector : 'body',
				callbacks : {
					// Before we do anything, let's close any open bios, it's going to make life easier.
					// This isn't essential, but if a bio is open and to the left of the viewport, 
					// opening one on the right causes issues
					onMoveStart: varenhorst.bio.deactivate
				}
				//, initialSlide : 1 // set initial slider to whatever you want, maybe grab this from a hash / history state
			});
		}

	} else if (
		winWidth > 640 && winWidth != screenWidth && $('.slidewrap').length || 
		screenWidth > 960 && $('.slidewrap').length
		) { // everything else

		varenhorst.mySlider = new arbitraryCarousel();
		varenhorst.mySlider.init('.slidewrap', {
			itemSelector : '.slide',
			modulus : 1,
			slideControlsContainerSelector : 'body'
			//, initialSlide : 1 // set initial slider to whatever you want, maybe grab this from a hash / history state
		});
	}



// swipe events (depends on plugin)

	$('.slidewrap').wipetouch({
		allowDiagonal: true,
		wipeLeft:			function (result) { if (varenhorst.mySlider) { varenhorst.mySlider.moveSlider('forward'); }},
		wipeRight:			function (result) { if (varenhorst.mySlider) { varenhorst.mySlider.moveSlider('backward'); }},
		wipeTopLeft:		function (result) { if (varenhorst.mySlider) { varenhorst.mySlider.moveSlider('forward'); }},
		wipeBottomLeft:		function (result) { if (varenhorst.mySlider) { varenhorst.mySlider.moveSlider('forward'); }},
		wipeTopRight:		function (result) { if (varenhorst.mySlider) { varenhorst.mySlider.moveSlider('backward'); }},
		wipeBottomRight:	function (result) { if (varenhorst.mySlider) { varenhorst.mySlider.moveSlider('backward'); }}
	});
});

$(window).load(function () {

	var winWidth = parseInt($(window).width(), 10),
		screenWidth = screen.width;

	if (varenhorst.isDesktop) {

		$('a.primaryState').click().removeClass('primaryState');

		bioTextMinHeight = $(".bios").height();

		flexHeight = $(".vbox .flexContent").height();

		/* by contrast, this appears to work reliably, and it's pretty ;) */
/*
		$(".vbox div.slidewrap li.slide").not('.textSlide').each(function (i) {
			var that = this;

			setTimeout(function () {
				$(that).addClass('slide-visible').find('img').css('height', (flexHeight - 27)).css('width', 'auto');
			}, i * 100);
		});
*/

	} else { // "mobile" styles

		$(".vbox div.slidewrap li.slide").not('.textSlide').each(function (i) {
			var that = this;
			setTimeout(function () {
				$(that).addClass('slide-visible').find('img').addClass('slide-visible').css('height', "auto").css('width', winWidth + 'px');
			}, i * 100);
		});
	}

});
		// wait till all images have a width before calculating their positions.
		$('.slidewrap').imagesLoaded( function() {
			if (Modernizr.flexbox) {
				var flexHeight = $(".vbox .flexContent").height();
			} else {
				var flexHeight =  parseInt($(window).height() - $('header').height() - $('footer.uber').height(), 10);
			}

			$(".vbox div.slidewrap li.slide").not('.textSlide').each(function (i) {
				var that = this;
				setTimeout(function () {
					var totalImgWidth = 0,
						$slider = $('.slider');
					$(that).addClass('slide-visible')
						.find('img')
						.css({
							'height': (flexHeight - 57),
							'width': 'auto'});
					$('img', $slider).each(function () {
							totalImgWidth += parseFloat($(this).width()) + 100;
						});
					totalImgWidth += 20;
					if ($slider.length && totalImgWidth > parseFloat($slider.width())) {
						$slider.css('width', totalImgWidth + "px");
					}
				}, i * 100);
			});
		});
$(window).resize(function () {
	var winWidth = parseInt($(window).width(), 10),
		screenWidth = screen.width,
		totalImgWidth = 0,
		$slider = $('.slider');

	if (winWidth > 640 && winWidth != screenWidth || winWidth >= 1024 ) {

		if (Modernizr.flexbox) {
			flexHeight = $(".vbox .flexContent").height();
		} else {
			flexHeight =  parseInt($(window).height() - $('header').height() - $('footer.uber').height(), 10);
		}
		

		$(".vbox div.slidewrap li.slide img").css({
			'height': (flexHeight - 52),
			'width': 'auto'
		}).each(function () {
			totalImgWidth += parseFloat($(this).width()) + 100;
		});
		totalImgWidth += 20;
		if ($slider.length && totalImgWidth > parseFloat($slider.width())) {
			$slider.css('width', totalImgWidth + "px");
		}

	} else { // "mobile" styles
		$(".vbox div.slidewrap li.slide img").css({
			'height': "auto",
			'width': winWidth + 'px'
		});
	}
});
