var widthWatchDog;

// DEFAULT --------------------------------------------------------------
function InitDefault(){
	widthWatchDog = $(window).width();
	
	// DEV ONLY: set reference grid
	//if( $('.canvas').length ) $(this).griddit({width: 1180, cols: 15, vertical: 18});
	
	//alert($('body.ie7').length);
	//if( $('body.ie7').length > 0 ) {
	//window.location('error_browser.htm');
		
		SetExternalLinks();
	
		$('textarea, #email').defaultValueInput();
	
		app.init();
	
		$('body').css('visibility', 'visible');
		$('#projects').css('visibility', 'visible');
	
}

// APP ----------------------------------------------------------------
var app = function () {																			// APP OBJECT ===================================================================
	
	function init() {
		ui.init();
		news.init();
	}
	
	return {
		init: init
	}
	
}();

var ui = function () {																			// UI OBJECT ===================================================================
	
	var bol_isIos 		= false,
		bol_isIphone	= false,
		$cover			= null;
	
	var nav = function() {
		
		var $nav 			= $('#main-nav ul'),
			$navItems 		= $nav.children('li'),
			$link_info1		= $('#main-nav #link-info'),
			$link_contact	= $('#main-nav #link-contact'),
			$link_contact1	= $('#main-nav #client-list'),
			$info			= $('#info'),
			int_info_h		= $info.outerHeight(),
			$body			= $('body'),
			$html			= $('html'),
			int_duration	= 1000,
			mod 			= 0.75,
			str_easing		= "easeOutQuad";
		
		function init() {
			
			// 'PROJECTS' and 'CONTRIBUTERS' toggle
			$navItems.has('ul')
				.addClass('has-subnav')
				.each(function(){
					
					$(this).children('a')
						.toggle(dosubnav,killsubnav);
					
				})
				
			$('#nav-projects ul a').click(function(e){
				if( !$('#contributer-content').length && !$('#news-archive').length ) {
					e.preventDefault();
					var str_theId = '#' + $(this).attr('href').split('#')[1];
					$('html,body').animate({scrollTop: $(str_theId).offset().top - 36}, int_duration * mod, str_easing);
					window.location.hash = str_theId;
					return false;
				}
			})
			
			// if there is a hash for project linking, - 36 from scrolltop so its not sitting hard up on the browser
			if(window.location.hash) $('html,body').scrollTop( $('html,body').scrollTop() - 36 )
			
			// show contributers list if this is a contributer page
			if( $('.contributer-projects').length ) {
				$('#nav-contributers a:first').trigger('click');
			}else{
				$('#nav-projects a:first').trigger('click');
			}
			
			// 'INFO' actions
			$link_info1.click(function() {
				//$body.stop().animate({scrollTop: 0 }, int_duration*mod, str_easing);
				//$html.stop().animate({scrollTop: 0}, int_duration*mod, str_easing);
				$('html,body').animate({scrollTop: $("#big_header").offset().top + 0}, int_duration * mod, str_easing);
				return false;
			})
			
			// 'CONTACT' actions
			$link_contact.click( function(){
				//int_scroll = $html.height() - $(window).height();
				//$body.stop().animate({scrollTop: int_scroll}, int_duration*mod, str_easing)
				//$html.stop().animate({scrollTop: int_scroll}, int_duration*mod, str_easing)
				$('html,body').animate({scrollTop: $("#copy").offset().top + 0}, int_duration * mod, str_easing);
				return false;
			})
			
			// 'CONTACT' actions
			$link_contact1.click( function(){
				//int_scroll = $html.height() - $(window).height();
				//$body.stop().animate({scrollTop: 6616}, int_duration*mod, str_easing)
				//$html.stop().animate({scrollTop: 6616}, int_duration*mod, str_easing)
				$('html,body').animate({scrollTop: $("#client_list").offset().top + 6}, int_duration * mod, str_easing);
				
				return false;
			})
			
			
		}
		
		function dosubnav() {
			var $subnav 		= $(this).siblings('ul'),
				$subnavItems 	= $subnav.children('li');
			$(this).addClass('active');
			$subnav.slideDown(int_duration, str_easing);
			$subnavItems
				.css('left', -150)
				.stop(true, true)
				.animate({'left': 0 }, 400, str_easing);
		}
		
		function killsubnav() {
			$(this).removeClass('active');
			$(this).siblings('ul').stop(true, true).slideUp(int_duration, str_easing);
		}
		
		function positionInfo(_x) {
			// adjust x if on news archive page
			if( $('#news-archive').length ) _x -= ($info.width() / 2) + 10;
			$info.css({'left':_x, 'top': (0 - int_info_h)});
		}
		
		return {
			init: init,
			positionInfo: positionInfo
		}
		
	}();
	
	var actionnav = function() {
		
		var $actionsLinks	= $('.actions li'),
			$body			= $('body'),
			int_duration	= 1000,
			str_easing		= "easeOutExpo",
			$target			= null,
			$targetMenu		= null,
			$targetMenuItem	= null;
		
		function init(){
			
			// add icons to actions menu
			$actionsLinks
				.children('a')
					.each( function(){ 
						$(this).data('action', $(this).parent().attr('class'))
					})
					.append('<span />')
					//.hover(over,out)
					.click(doAction)
					.end()
				.each( function(){ 
					$(this).data('w', $(this).width())
				})
		}
		
		function over() {
			$(this).children('span')
				.stop()
				.css('top', -13)
				.animate({'top': -17, 'opacity':1 }, int_duration, str_easing);
		}
		
		function out() {
			$(this).children('span')
				.stop()
				.animate({'top': -13, 'opacity':0 }, int_duration, str_easing);
		}
		
		function doAction(){
			
			$targetMenuItem 	= $(this);
			$targetMenu 		= $(this).parents('.actions');
			
			switch( $(this).data('action') ) {
				case 'play':
					//console.log("play");
					break;
				case 'download':
					//console.log("download");
					break;
				case 'lights':
					$target = $(this).parents('.proj-meta').siblings('.viewport').find('.selected');
					var $li = $(this).parents('.proj-meta').parent();
					// console.log("$li.offset().top = " + $li.offset().top);
					$('html,body').animate({scrollTop: $li.offset().top - 72}, int_duration, str_easing);
					
					( !$cover.is(':visible') ) ? lightsOut() : lightsOn();
					return false
					break;
				case 'share':
					var str_id = "http%3A%2F%2F" + window.location.host + '#' + $(this).parents('.proj-meta').parent().attr('id'),
						str_link = 'http://twitter.com/share?url=' + str_id;
					window.open(str_link);
					return false
					break;
				default:
					break;
			}
					
		}
		
		function lightsOut() {
			$target.addClass('lights-off-target');
			$targetMenu.addClass('lights-off-target');
			$targetMenuItem.children('strong').text('on');
			$body.addClass('lights-off');
			//$cover.show();
			$('header, #news').addClass('hidden');
		}
		
		function lightsOn() {
			//$cover.hide();
			$body.removeClass('lights-off');
			$target.removeClass('lights-off-target');
			$targetMenu.removeClass('lights-off-target');
			$targetMenuItem.children('strong').text('off');
			$('header, #news').removeClass('hidden');
		}
		
		// extension method for media items to set which options they show / hide when selected
		// UPDATED: the action nav should probably be proj not item specific. left this here but disabled call to it
		$.fn.checkactions = function() {
			var $actions 		= $(this).parents('.viewport').next().find('.actions li'),
				obj_types		= {
					image: 	["share","lights"],
					video: 	["play","download","share","lights"],
					copy:	["share"]
				}
				str_class		= $(this).attr('class').split(/\s+/)[0],
				int_duration	= 1000,
				str_easing		= "easeOutExpo";

				$actions.each(function(){
					var bol_show = false;
					for( var prop in obj_types[str_class] ) {
						if( $(this).attr('class') == obj_types[str_class][prop] ) bol_show = true;
					}
					(bol_show) ? $(this).stop().animate({'width': $(this).data('w'), 'opacity':1}, int_duration, str_easing) : $(this).stop().animate({'width': 0, 'opacity':0}, int_duration, str_easing);
				});
				
		}
		
		return {
			init: init,
			lightsOn: lightsOn
		}
		
	}();
	
	var contactForm = function() {
		
		var $submit 				= $('#submit'),
			arr_fields				= [ '#message', '#email' ],
			arr_invalidResponses	= ['nope', 'ruh roh', 'nuh uh', 'nein', 'aw hell naw', 'nups', 'negatory', '\’fraid not'];
		
		function init() {
			
			$submit.hover(validate, reset);
			
		}
		
		function validate() {
			var bol_valid = true;
			for (var i=0; i < arr_fields.length; i++) {
				if( !$(arr_fields[i]).valid() ) bol_valid = false;
			};
			if(bol_valid) {
				//doSubmit();
			}else {
				var response = arr_invalidResponses[Math.floor(Math.random()*arr_invalidResponses.length)];
				$submit
					.addClass('error')
					.val(response)
					.bind('click', function(){ return false; });
			}
		}
		
		$.fn.valid = function() {
			var bol_valid 	= true;
			var str_err 	= '#err-' + $(this).attr('id');
			if ( $(this).attr('value') == '' || $(this).attr('value') == $(this).data('defaultValue') ) bol_valid = false;
			if ( !bol_valid ) $(str_err).stop(true, true).fadeIn('fast');
			return bol_valid;
		}
		
		function reset() {
			$submit
				.removeClass('error')
				.val('submit')
				.unbind('click', function(){ return false; });
			$('.ind-error').stop(true, true).fadeOut('fast');
		}
		
		function doSubmit() {
			alert('TODO: submut ut');
		}
		
		return {
			init: init
		}
		
	}();
	
	var projectBrowser = function() {
		
		var $projects 		= $('#projects').children('li'),
			$mediaLists		= $('.project-media'),
			$mediaItems		= $mediaLists.children('li'),
			int_initx		= ($(window).width() / 2) - ( $('#projects .video-js-box:first').outerWidth() / 2 ) - 20,
			int_initx		= ($(window).width() / 2) - ( $('#projects .project-media:first li:first').width() / 2 ) - 20,
			int_duration	= 1000,
			str_easing		= "easeOutExpo",
			resizeTimer		= null,
			bol_isAdmin		= $('#admin-content').length,
			obj_navDim		= {l:$('#main-nav').offset().left, w: $('#main-nav').width()};
		
		function init() {
			
			$(window).scroll(onPageScroll);
			$(window).resize(function() {
				if(!bol_isIos && !bol_isAdmin && (widthWatchDog != $(window).width())) {
					widthWatchDog = $(window).width();
					clearTimeout(resizeTimer);
					resizeTimer = setTimeout(onPageResize, 100);
				}
			});
			
			// left position for projects in iPad (portrait)
			if (bol_isIos) int_initx = 182;
			
			// move info panel to correct x
			if (!bol_isIphone) nav.positionInfo(int_initx);
			
			// append shadows and add data to each media item (li containing an img, a video or copy)
			$mediaItems
				.not('.copy').append('<span class="shadow shadow-l"/><span class="shadow shadow-r"/>')
					.end()
				.each(function(){
					obj_data = {shd_l: $(this).find('.shadow-l'), shd_r: $(this).find('.shadow-r'), transitioning: false}
					$(this).data(obj_data);
				})
				
			// drag behaviour for the media lists
			$mediaLists.each( function(index) {
				var $theList 			= $(this),
					$links 				= $(this).find('a'),
					$lis				= $(this).children('li'),
					$videoTags			= $(this).find('video'),
					bol_moving			= false,
					bol_scrollAllowed	= false,
					$shadows			= $(this).find('.shadow'),
					/* str_moreFragment 	= '<a href="" class="more"><span class="text">show</span><span class="ind ind-more">more</span><span class="ind ind-less">less</span></a>', */
					str_moreFragment 	= '<a href="" class="more"><img src="../images/interface/more_button.png" class="btnMore" /></a>',
					str_infoFragment	= '<div class="info">« click and drag</div>',
					$info				= null,
					obj_morePositions	= { ready: 11, top: -14, bottom: 43 },
					int_popWidth		= 105,
					obj_moreBtn			= {},
					num_selected		= 0,
					num_diff			= 0,
					
					$more				= null,
					$view				= null;
				
				// select first item
				$(this).children('li:first').addClass('selected');
				
				$('.selected')
					.children('img').each(function(){
						if( $(this).hasClass('loader') && $(this).attr('rel') ) {
							$(this)
								.attr('src', $(this).attr('rel') )
								.removeClass('loader')
						}
					})
				
				// set width
				$theList.width( ($lis.filter(':first').outerWidth() + 50) * $lis.length );
				
				// append 'more' expand button & attach functionality
				$(this).parent().append(str_moreFragment);
				var $moreBtn			= $(this).parent().children('.more'),
					bol_isIe			= ( $('.ie6, .ie7, .ie8').length ) ? true : false,
				obj_moreBtn				= {
					$btn				: $moreBtn,
					$view				: $moreBtn.find('.text'),
					$more				: $moreBtn.find('.ind-more'),
					$less				: $moreBtn.find('.ind-less'),
					offset 				: int_initx + 30
				}
				if (bol_isIos) obj_moreBtn.offset = 0;
				if ($lis.length < 2 ) $moreBtn.hide();
				
				obj_moreBtn.$btn
					.css( {'right' : obj_moreBtn.offset, 'padding-right': obj_moreBtn.$more.outerWidth() } )
					
				obj_moreBtn.$view
					.css('margin-left', 0 - obj_moreBtn.$view.outerWidth());
				
				if (!bol_isIos)
				obj_moreBtn.$btn
					.hover(
						function() {
							if(!bol_isIe) obj_moreBtn.$view.stop().animate({'margin-left': 0}, int_duration, str_easing)
						}, function() {
							if(!bol_isIe) obj_moreBtn.$view.stop().animate({'margin-left': 0 - obj_moreBtn.$view.outerWidth()}, int_duration, str_easing)
						})
					.toggle(
						function() {
							
							// animate MORE button
							obj_moreBtn.$more.stop()
								.animate({'top': 36}, int_duration, str_easing)
							obj_moreBtn.$less.stop()
								.animate({'top': 0}, int_duration, str_easing)
							obj_moreBtn.$btn.stop()
								.animate({'padding-right': obj_moreBtn.$less.outerWidth()}, int_duration, str_easing)
							
							// add OPEN class to project li
							$(this).parents('li').addClass('open');
							// and close any other open projects
							$('#projects > li.open').not( $(this).parents('li') )
								.find('.more')
									.trigger('click')
									.trigger('mouseout');
							// SHOW sub items
							$(this).parent().find('ul > li')
								.stop(true, true)
								.fadeTo(int_duration, 1, str_easing)
								.children('img').each(function(){
									if( $(this).hasClass('loader') && $(this).attr('rel') ) {
										$(this)
											.attr('src', $(this).attr('rel') )
											.removeClass('loader')
									}
								})
							/*$('body').addClass('scractive');
							bol_scrollAllowed = true; */
							
							$('#main-nav').animate({opacity: '0.0'}, 400, str_easing);
							
							bol_scrollAllowed = true;
							
							return false;
						}, function() {
							
							// animate MORE button
							obj_moreBtn.$more.stop()
								.animate({'top': 0}, int_duration, str_easing)
							obj_moreBtn.$less.stop()
								.animate({'top': -36}, int_duration, str_easing)
							obj_moreBtn.$btn.stop()
								.animate({'padding-right': obj_moreBtn.$more.outerWidth()}, int_duration, str_easing)
							
							// remove OPEN class to project li
							$(this).parents('li').removeClass('open');
							// HIDE subitems
							$(this).parent().find('ul > li').not('.selected').stop(true, true).fadeTo(int_duration, 0, str_easing);
							
							$('#main-nav').animate({opacity: '1.0'}, 400, str_easing);
							bol_scrollAllowed = false;

							return false;
						}
					)
					
				if(index == 0) obj_moreBtn.$btn.trigger('mouseover');
				
				// append 'click + drag' info indicator to the second item
				if(!bol_isIos) $(this).children('li').eq(1).append(str_infoFragment);
				$info = $(this).find('.info');
				
				$(this)
				.css('left', int_initx )
				.mousedown (function(e){
					
					// check to ensure we are not trying to scroll a playing video (which hijacks controls)
					var $clickTarget 		= $(e.target),
						vidStopScroll 		= false;
					if( $clickTarget.hasClass('.vjs-playing') || $clickTarget.parents('.vjs-playing').length || $clickTarget.hasClass('vjs-play-control') || $clickTarget.hasClass('vjs-big-play-button') ) {
						vidStopScroll = true;
					}
					
					if(bol_scrollAllowed && !vidStopScroll) {
						var x_origin 		= e.pageX,
							x_pos 			= parseInt( $(this).css('left') ),
							num_startTime	= new Date().getTime(),
							$items			= $(this).find('li');
						
						$shadows.stop(true, true).fadeIn(int_duration, str_easing);
						
						// pause any playing videos within the project
						for (var i=0; i < $videoTags.length; i++) {
							if( $('html.video').length ) $videoTags[i].pause();
						};
						
						// hide 'MORE' button
						$moreBtn.stop(true, true).fadeOut(200, str_easing);
						
						//$moreBtn.animate({opacity: '0.0'}, 250);
						
						$info.animate({opacity: '0.0'}, 200, str_easing);
							
						$('body')
							.bind('mousemove', function(e){
								bol_moving 	= true;
								var x_now 	= e.pageX;
								num_diff 	= (x_origin - x_now) * -1;
								$theList.css('left', x_pos + num_diff);
							})
							.bind('mouseup', function(e){
								
								var num_timeNow 		= new Date().getTime(),
									num_moveTime		= num_timeNow - num_startTime,
									num_timeThreshold	= 1000;
								
								$('body')
									.unbind('mousemove')
									.unbind('mouseup')
									.removeClass('disabled');
									
								if(bol_moving) {
									bol_moving = false;
									
									// show 'MORE' button
									$moreBtn.stop(true, true).delay(200).fadeIn(200, str_easing);
									
									//$moreBtn.animate({opacity: '1.0'}, 250);

									
									var $items			= $theList.children('li'),
										dist 			= int_initx - parseInt( $theList.css('left') ),
										int_liWidth 	= $items.eq(0).outerWidth(),
										selected		= null;
										
									// figure out selected - if it's a 'flick' (interaction time is less than num_timeThreshold) then flick to the next one, else work out closest
									if(num_moveTime < num_timeThreshold) {
										( (num_diff * -1) > 0 ) ? selected = num_selected + 1 : selected = num_selected - 1;
									}else{
										selected 		= Math.floor( (dist + (int_liWidth / 2) ) / int_liWidth );
									}
									
									if( selected < 0 ) selected = 0;
									if( selected >= $items.length ) selected = $items.length - 1;
									
									$items
										.removeClass('selected')
										.eq(selected).addClass('selected')
									
									var new_x = int_initx - $theList.find('.selected').position().left;
									$theList.animate({'left': new_x }, int_duration, str_easing, function(){ $shadows.stop(true, true).fadeOut(int_duration, str_easing) });
									
									num_selected = selected;
									
								}
									
								return false;
							})
						return false;
					}
				})
				
			});
			
			// extension method for showing / hiding the drop shadows on items
			/*
			$.fn.checkshadows = function() {
				
				var x = $(this).offset().left;
				if( x > obj_navDim.l && x < (obj_navDim.l + obj_navDim.w) && !$(this).data().transitioning ){
					$(this).data().transitioning = true;
					$(this).data().shd_l.stop().animate({'opacity': 1}, int_duration, str_easing, function(){
						$(this).parent().data().transitioning = false;
					})
				}
				if( (x < obj_navDim.l || x > (obj_navDim.l + obj_navDim.w) ) && $(this).data().shd_l.css('opacity') > 0 && !$(this).data().transitioning ) {
					$(this).data().transitioning = true;
					$(this).data().shd_l.stop().animate({'opacity': 0}, int_duration, str_easing, function(){
						$(this).parent().data().transitioning = false;
					})
				}
				
    			return false;
			}
			*/
			
			function disableLinks() {
				$('a').not('.actions a, .more, #link-info, #link-contact').bind('click', function(){
					return false;
				})
			}
			
			function enableLinks() {
				$('a').not('.actions a, .more, #link-info, #link-contact').unbind('click');
			}
			
			function onPageScroll() {
				
				var $open 		= $('#projects li.open');
				
				// if there is an open project, and user has scrolled it past top of screen, collapse it
				if( $open.length ) {
					if($(window).scrollTop() > $open.offset().top || ( $(window).scrollTop() + $(window).height() ) < $open.offset().top ) $open.find('.more').trigger('click')
				}
				
			}
			
			function onPageResize(){
				// reload page on resize 
				window.location.reload()
			}
			
			
		}
		
		return {
			init: init
		}
		
	}();
	
	var iOs = function() {
		
		var int_duration	= 500,
			str_easing		= "easeOutExpo",
			$mediaLists		= $('.project-media'),
			bol_videoPlayed	= false;
		
		function init() {
			
			//$(window).scroll(onScroll);
			
			// resize videos on orientation change
			window.onorientationchange = function(){
				( window.orientation == 0 ) ? $('video').height(304) : $('video').height(432);
				//alert('hi');
				$mediaLists.each(function(){
					this.style.webkitTransform = 'translate3d(0px, 0px, 0px)';
				})
			}
			
			var projects = document.getElementById('projects')
			
			$mediaLists.each(function(i){
				this.initX 		= 0;
				this.restX 		= 0;
				this.selected 	= 0;
				this.addEventListener("touchstart", touchstart, false);
				this.addEventListener("touchmove", touchmove, false);
				this.addEventListener("touchend", touchend, false);
				this.addEventListener("gesturechange", gesturechange, false);
				
				this.style.webkitTransform = 'translate3d(0px, 0px, 0px)';
				
				if(i < 2) $(this).parent().append( '<div class="nav-cover" />' );
				
			})
			.find('li').show();
			
			enableEventsOnVideo();
			initMore();
			
			if(bol_isIphone) initIphone();
			
		}
		
		function initMore() {
			$('.ind-more').text('swipe for more');
			$('.more').click(function(){
				return false;
			})
		}
		
		function enableEventsOnVideo() {
			$('li.video').append( '<div class="btn-vid-play"></div>' )
			if(!bol_isIphone) {
				$('.btn-vid-play').each(function(){
					this.addEventListener("touchend", function(){
						$(this).hide();
						bol_videoPlayed 	= true;
						var theVideo 		= this.parentNode.getElementsByTagName('video')[0];
						theVideo.button 	= this;
						theVideo.setAttribute('controls', 'controls');
						theVideo.play();
						theVideo.addEventListener("pause", function(){
							$(this).removeAttr('controls');
							$(this.button).show();
						});
						
					}, false);
				})
				$('video').removeAttr('controls');
			}
		}
		
		function touchstart(e){ 
			//e.preventDefault();
			if (e.targetTouches.length != 1) return false;
			this.startX 			= e.targetTouches[0].clientX;
			this.scrollStartTime 	= e.timeStamp;
			this.style.WebkitTransition = 'none';
			
			if(!bol_isIphone) $(this).siblings('.more').hide();
			
			return false;
		}
		
		function touchmove(e){
			//e.preventDefault();
			this.nowX 			= e.targetTouches[0].clientX;
			this.diff 			= (this.startX - this.nowX) * -1;
			
			this.style.webkitTransform = 'translate3d(' + (this.restX + this.diff) + 'px, 0px, 0px)';
			return false;
		}
		
		function touchend(e){

			// load any unloaded item images
			$(this).find('img').each(function(){
				if( $(this).hasClass('loader') && $(this).attr('rel') ) {
					$(this)
						.attr('src', $(this).attr('rel') )
						.removeClass('loader')
				}
			})
			
			var $items				= $(this).children('li'),
				int_liWidth 		= $items.eq(0).outerWidth(),
				int_distFromInit	= this.restX + this.diff,
				int_selected		= Math.floor( ( (int_distFromInit * -1) + (int_liWidth / 2) ) / int_liWidth ),
				animTime 			= 200;
			
			// if it was a short swipe (but not on the video button, assume they're flicking to the next rather than picking selection on position
			this.scrollStopTime 	= e.timeStamp;
			var time 				= this.scrollStopTime - this.scrollStartTime
			if(time < 300 && !bol_videoPlayed) {
				if(this.diff > 0) {
					// right
					int_selected = this.selected - 1;
				}else{
					 // left
					 int_selected = this.selected + 1;
				}
			}
			bol_videoPlayed = false;
			
			if( int_selected < 0 ) int_selected = 0;
			if( int_selected >= $items.length ) int_selected = $items.length - 1;
			
			$items
				.removeClass('selected')
				.eq(int_selected).addClass('selected')
				
			var $selected = $(this).find('.selected');
				
			var new_x = this.initX - $selected.position().left;
			
			this.style.WebkitTransition = '-webkit-transform ' + animTime + 'ms ease-out';
			this.style.webkitTransform 	= 'translate3d(' + new_x + 'px, 0px, 0px)';
			
			this.restX = new_x;
			
			if( $selected.hasClass('copy') ) {
				$selected.addClass('auto-copy');
				$(this).parent().find('.nav-cover').addClass('nav-cover-out');
			}else{
				$(this).find('.copy').removeClass('auto-copy');
				$(this).parent().find('.nav-cover').removeClass('nav-cover-out');
			}
			
			this.selected = int_selected;
			
			//hideShadow($(this));
			
		}
		
		function gesturechange(e) {
			return false;
		}
		
		function initIphone() {
			
			// remove copy <li>'s from DOM
			$('#projects .project-media .copy').remove();
			
			// add a break after email in contact
			$('#contact-details a').after('<br/>');
			
			// iPhone does not allow us to dynamically add / remove the controls element - therefore we need to add / remove the entire video element to allow swipe panning
			$('video').each(function(index){
				
				var $theLi 		= $(this).parents('li:first'),
					$theVideo	= $(this),
					$html		= $theLi.html(),
					$theImg		= null,
					$theButton	= $theLi.find('.btn-vid-play'),
					theVideo 	= this.parentNode.getElementsByTagName('video')[0],
					interval	= null;
				
				$theVideo.remove();
				$theLi.append('<img width="290" src="' + $theVideo.attr('poster') + '" />')
				$theImg = $theLi.find('img');
				
				function startVideo() {
					
					// append the video code, start the video, and set up event listeners
					// the video has to be appended / removed every tie to stop multiple videos overrunning each other and confusing iOs on iPhone
					
					var $theLi = $(this).parents('li:first');
					$theLi.prepend($html);
					theVideo = $theLi.find('video')[0];
					
					theVideo.play();
					theVideo.addEventListener('pause', checkExitFullscreen);
					theVideo.addEventListener('play', stopCheckExitFullscreen);
					
					$theImg.hide();
					
				}
				
				function checkExitFullscreen() {
					// when the video is paused (either using the pause button or by clicking the done button) start checking to see if they've exited fullscreen
					interval = setInterval ( killVideo, 500 );
				}
				
				function stopCheckExitFullscreen() {
					clearInterval ( interval );
				}
				
				function killVideo() {
					// if 'webkitDisplayingFullscreen' is false, they've returned to the main page - remove the video from the DOM due to conditions described above
					if (!theVideo.webkitDisplayingFullscreen) {
						$(theVideo).remove();
						$theImg.show();
					}
				}
				
				$theButton
					.css('z-index', 9999)
					.click(startVideo);
				
			})
			
			
		}
		
		function onScroll() {
			
			//$('header').animate({'top': $(this).scrollTop() + 36 }, int_duration, str_easing)
			
			var dist = $(this).scrollTop();
			$('header')[0].style.WebkitTransition = '-webkit-transform ' + int_duration + 'ms ease-out';
			$('header')[0].style.webkitTransform 	= 'translate3d(0px, ' + dist + 'px, 0px)';
			
		}
		
		return {
			init: init
		}
		
	}();
	
	var video = function(){
		
		function init() {
			
			// add cover to prevent clicking on the video itself (so we can drag-scroll it)
			$('.video').not('html.video').append('<div class="video-cover" />');
			
			// hijack play button to kill the cover also
			$('.vjs-big-play-button')
				.live('click', function(){
					$(this).parent().siblings('.video-cover').hide();
				})
			
		}
		
		return {
			init: init
		}
		
	}();
	
	var onKeyPress = function() {
		
		function init() {
			
			$(window).keydown( function(event) {
				switch(event.keyCode) {
					case 39:
						// right
						return false;
						break;
					case 37:
						// left
						return false;
						break;
					default:
						break;
				}
			});
			
		}
		
		return {
			init: init
		}
		
	}();
	
	function init() {
		
		var deviceAgent 									= navigator.userAgent.toLowerCase();						// check for iOs device
		var agentID 										= deviceAgent.match(/(iphone|ipod|ipad)/);
		if (agentID) bol_isIos 								= true;
		if (deviceAgent.match(/(iphone)/)) bol_isIphone 	= true;
		
		nav.init();
		actionnav.init();
		contactForm.init();
		projectBrowser.init();
		if (agentID) iOs.init();
		$('#projects').append('<div id="cover"/>');
		$cover = $('#cover');
		$cover.css({'width': $(window).width(), 'height': $(window).height()});
		$cover.click( actionnav.lightsOn );
		video.init();
		//onKeyPress.init();
		
		//if( $(window).width() < 1100 ) $('#master').addClass('small-mode');			// check for smaller devices
		
	}
	
	function styleHelper() {
		// if not an ios device
		if( !bol_isIos ) {
			// add scrolly divs
			$('#projects > li > a.img-link').each(function(){
				$(this).append('<span class="peek" style="background: url(' + $(this).find('img:first').attr('src') + ') no-repeat 50% 0; height: ' + $(this).height() + 'px"><span /><span class="bot"/>');
			});
			// check for 1024 resolutions and resize main col for them
			if( $(window).width() < 1100 ) $('#master').addClass('small-mode');
		}
	}
	
	
	return {
		init: init,
		projectBrowser: projectBrowser
	}
	
}();

var news = function () {																			// NEWS OBJECT ===================================================================
	
	var $list 			= $('#news-archive #news'),
		targetUrl 		= '/index.php/home/news_fragment',
		$btnMore		= $('#get-more-news'),
		$loading		= $('#loading-more'),
		loadNo			= 8,
		current			= 0,
		loadAllowed		= true,
		deviceAgent 	= navigator.userAgent.toLowerCase(),
		agentID 		= deviceAgent.match(/(iphone|ipod|ipad)/),
		bol_isIos		= false;
		
	
	function init() {
		
		if (agentID) bol_isIos = true;
		
		if( $list.length ) {
			bind();
			getItems();
		}
	}
	
	function bind() {
		$btnMore.click(getItems);
		$(window).scroll(onScroll);
	}
	
	function getItems() {
		
		$loading.fadeIn();
		
		var queryString = '?startItem=' + current + '&noItems=' + loadNo;
		current += loadNo;
		
		var projectContent = $.ajax({
			url: targetUrl + queryString,
			success: function(html){
				$loading
					.fadeOut();
				$list.append( checkResult(html) );
				$list.eqByRow();
			},
			error: function(){
				error();
			}
		});
		
		return false;
		
	}
	
	function checkResult(frag) {
		var $frag 	= $(frag),
			$items	= $frag.filter('.news');
		
		// Moved this into template
		/*$items.each(function(){
			var internalLink = $(this).find('a:first').attr('href').indexOf('/news');
			if(internalLink > 0) $(this).append('<a href="" class="read-more">See More</a>');
		})*/
		
		if( $items.length < loadNo ) {
			loadAllowed = false;
			$loading
					.text('All news loaded')
					.fadeIn();
		}
		
		return $frag;
	}
	
	function onScroll() {
		
		var metric = $(document).height() - $(window).height();
		if( bol_isIos ) metric -= 60;
		
		if ($(window).scrollTop() >= metric){
			if(loadAllowed) getItems();
		}
	}
	
	function error() {
		//console.log("error getting news items");
	}
	
	return {
		init: init
	}
	
}();

// PLUGINS ------------------------------------------------------------

// UTILS --------------------------------------------------------------
(function($) {
jQuery.fn.griddit = function(options){
	/*
	Purpose: uses Canvas to draw a reference grid over the page, toggled with the ESC key
	usage: $(this).griddit({options});
	*/
	
	// defaults ===========================
	var defaults = {  
		width: 940,
		height: Math.max($(window).height(), $('html').height()),
		cols: 12,
		gutterwidth: 20,
		colColour: "rgba(255,0,0,0.2)",
		vertical: 20
	};
	var options = $.extend(defaults, options);
	
	var left		= ($(window).width() / 2) - (defaults.width / 2);
	var html 		= '<canvas id="grid-cols" width="' + defaults.width + '" height="' + defaults.height + '" style="position: absolute; top: 0; left: ' + left + 'px; z-index: 99;"></canvas>';
	$('body').append(html);
	var canvas 		= document.getElementById("grid-cols");
	var ctx 		= canvas.getContext("2d");
	
	// vertical grid columns ===========================
	var colour;
	var col_w		= ( defaults.width - ((defaults.cols - 1) * defaults.gutterwidth) ) / defaults.cols;
	if( window.console && console.log ) console.log("GRIDDIT column width is " + col_w + "px with a gutterwidth of " + defaults.gutterwidth);
	if( (col_w % 1) == 0) {
		for (var i = 0; i < defaults.cols; i++) {
			colour 							= defaults.colColour;
			if(colour == 'random') colour 	= 'rgba(' + RandRange(0, 255) + ',' + RandRange(0, 255) + ',' + RandRange(0, 255) + ',' + '0.2)';
			ctx.fillStyle 					= colour;
			ctx.fillRect (i * (col_w + defaults.gutterwidth), 0, col_w, defaults.height);
		};
	}else{
		alert('Your grid isn\'t%20a%20nice%20round%20number%20_/index.html');
	}
	
	// horizontal grid lines ===========================
	ctx.strokeStyle 	= colour;
	ctx.lineWidth 		= 1;
	ctx.beginPath();
	ctx.beginPath();
	for (var i = 0; i < (defaults.height / defaults.vertical); i++) {
		var y = (i * defaults.vertical) + 0.5;
		ctx.moveTo(0, y);
		ctx.lineTo(defaults.width, y);
	};
	ctx.stroke();
	
	$(canvas).hide();
	
	$('html').keyup(function(event) {
		if(event.keyCode == 27){
			if( $(canvas).is(':visible') ){
				$(canvas).hide();
			}else{
				$(canvas).show();
			}
		}
	});
	
}
})(jQuery);
  	
(function($) {
jQuery.fn.eqByRow = function(){
	/*
	Purpose: equalise the heights of li's in a list by row
	usage: $('#eq-this-list').eqByRow();
	*/
	var inRow 	= Math.floor( $(this).width() / $(this).children("li:first").width() );
	var items 	= $(this).children('li');
	for (var i = 0; i < ($(items).length / inRow); i++){
		var max 	= 0;
		var start 	= (i * inRow);
		for (var j = start; j < start + inRow; j++){
			if(items[j]){
				if( $($(items)[j]).height() > max ) max = $($(items)[j]).height();
			}
		};
		for (var k = start; k < start + inRow; k++){
			if(items[k]){
				$($(items)[k]).height(max);
			}
		};
	};
}
})(jQuery);

(function($) {
jQuery.fn.biggerClick = function(){
	/*
	Purpose: makes a container 'hot', and binds it click event to go to the location of the first <a>'s href it finds within it
	usage: $('#make-these-hot ul li').biggerClick();
	*/
	$(this).hover(
		function(){
			$(this).addClass("hover");
		},function(){
			$(this).removeClass("hover");
		}
	)
	$(this).click(function(){
		window.location = $(this).find("a:first").attr("href");
	})
}
})(jQuery);

(function($) {
jQuery.fn.defaultValueInput = function(){
	/*for (var i=0; i < $(this).length; i++) {
		$(this[i]).data('defaultValue', $(this[i]).attr('value'));
		$(this[i]).addClass('default-value');
	};
	$(this).focus(function(){
		if( $(this).attr('value') == $(this).data('defaultValue') ){
			$(this).attr('value', '');
			$(this).removeClass('default-value');
		}
	});
	$(this).blur(function(){
		if( $(this).attr('value') == '' || $(this).attr('value') == $(this).data('defaultValue') ){
			$(this).attr('value', $(this).data('defaultValue'));
			$(this).addClass('default-value');
		}
	});*/
}
})(jQuery);

function SetExternalLinks(){
	/*
	Purpose: checks all <a>'s in the doc, if it has a rel attribute of 'external', sets to open in new window
	usage: <a href="http://www.google.com" rel="external">Google</a>
	*/
	$('a[rel=external]').click(function(){ window.open(this.href); return false; });
}

function RandRange(minNum, maxNum) {
	return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
}

// ======================================================================

