// private functions
function debug(o) {
	if(window.console && window.console.log) {
		window.console.log(o);
	}
}

if(typeof jQuery != 'undefined') {
	jQuery.noConflict();
	(function($) {

		// app functions
		var App = {
			
			/**
			* Options
			* @desc General App related options
			*/
			options: {
				active:		'active',
				hover:		'hover',
				disabled:	'disabled',
				crossfade:	1500,
				idle: {
					timeout:		5000,
					fadeIn:			450,
					fadeOut:		1000
				},
				cycle: {
					fx:				'fade',
					delay:			0,
					timeout:		5000,
					speed:			1500,
					speedIn:		1500,
					speedOut:		0,
					startingSlide:	0,
					pause:			true,
					next:			null,
					prev:			null,
					pager:			null,
					prevNextClick:	function(isNext, zeroBasedSlideIndex, slideElement) {
						$(this.next).add(this.prev).children('a').blur();
					},
					pagerClick:		function(zeroBasedSlideIndex, slideElement){
						$(this.pager).children('a').blur();
					},
					before:			function(currSlideElement, nextSlideElement, options, forwardFlag){
						$(this).closest('ul.slideshow').next('ul.cycle-arrows').hide();
					},
					after:			function(currSlideElement, nextSlideElement, options, forwardFlag){
						var $$, $img, $wrap, $arrows;

						$$		= $(this);
						$img	= $$.find('img');
						$wrap	= $$.closest('ul.slideshow');
						$arrows	= $wrap.next('ul.cycle-arrows');

						$wrap.css({width: $img.width(), height: $img.height()});
						$arrows.show();
					}
				},
				carousel: {
					speed:			750,
					auto:			null,
					circular:		false,
					pagination:		false,
					arrows:			true,
					visible:		8,
					scroll:			1,
					start:			0
				},
				jwplayer: {
					autostart:		false,
					screencolor:	'#ffffff',
					flashplayer:	'/video/player.swf',
					skin:			'/video/five/five.xml'
				}
			},

			/**
			* Init
			* @desc Miscellaneous / Common
			*/
			init: function() {
				$('body').addClass('has-jquery');
			},
			
			/**
			* Hover
			* @desc Fixing hover on navigation list items
			*/
			hover: function() {
				var container, image, slideshow,
					sfEls, length, functions,
					container = null;
				
				image		= document.getElementById('image');
				slideshow	= document.getElementById('slideshow');
				
				if(image !== null) {
					container = image;
				}
				if(slideshow !== null) {
					container = slideshow;
				}
				if(container === null) {
					return;
				}

				sfEls		= container.getElementsByTagName('li');
				length		= sfEls.length;
				functions	= {
					mouseover: function() {
						this.className += ' ' + App.options.hover;
					},
					mouseout: function() {
						this.className = this.className.replace(App.options.hover, '');
					}
				};

				for(var i=0; i<length; i++) {
					sfEls[i].onmouseover	= functions.mouseover;
					sfEls[i].onmouseout		= functions.mouseout;
				}
			},

			
			/**
			* Expand
			* @desc Auto-expands textareas to fit the contents as a user types
			* @uses expandable()
			* @see http://brandonaaron.net/code/expandable/docs
			*/
			expandable: function() {
				if(typeof $.fn.expandable !== 'undefined') {
					// add auto-expand to textarea
					$('textarea.expand').expandable({
						duration:	250,
						interval:	750,
						within:		2,
						by:			3
					});				
				}			
			},

			/**
			* Idle Timer
			* @desc Events based on idle time on the website
			* @uses idleTimer()
			* @see http://paulirish.com/2009/jquery-idletimer-plugin/
			*/
			idleTimer: function() {
				if($.idleTimer && $('body').is('.idle')) {
					$.idleTimer(App.options.idle.timeout);

					var $nav = $('#nav');
					$(document).bind('idle.idleTimer active.idleTimer', function(event){
						switch(event.type) {
							case 'idle':
								$nav.fadeOut(App.options.idle.fadeOut, function(){
									$nav.addClass('idle');
								});
								break;
								
							case 'active':
								$nav.fadeIn(App.options.idle.fadeIn).removeClass('idle');
								break;
						}
					});
				}
			},

			/**
			* Slideshow
			* @desc Slideshow
			* @uses idleTimer()
			* @see http://paulirish.com/2009/jquery-idletimer-plugin/
			*/
			slideshow: function() {
				if(typeof images !== 'undefined' && $.fn.cycle) {
					var $slideshow, $ul, $arrows, $hover,
						total, list, li,
						selector;
					
					total	= images.length;
					list	= [];
					li		= 0;

					for(var i=start; i < total; i++) {
						list[li++] = '<li>';
						list[li++] = images[i].img;
						list[li++] = '<h2>';
						list[li++] = images[i].title;
						list[li++] = '</h2>';
						list[li++] = '</li>';
					}
					for(var i=0; i < start; i++) {
						list[li++] = '<li>';
						list[li++] = images[i].img;
						list[li++] = '<h2>';
						list[li++] = images[i].title;
						list[li++] = '</h2>';
						list[li++] = '</li>';
					}
					
					$ul			= $('<ul />').addClass('slideshow').append(list.join(''));
					$slideshow	= $('#slideshow').empty().append($ul);
					selector	= '#' + $slideshow.attr('id') + ' ';						
					$hover		= $slideshow;
					
					// create the arrows
					if($slideshow.is('.arrows') && total > 1) {
						App.options.cycle.next = selector + '.next';
						App.options.cycle.prev = selector + '.previous';
						
						$arrows = $('<ul />').addClass('cycle-arrows');
						
						list = []; li = 0; arrows = ['Previous', 'Next'];
						
						$.each(arrows, function(i, val){
							list[li++] = '<li class="' + val.toLowerCase() + '">';
							list[li++] = '<a href="#' + val.toLowerCase() + '">';
							list[li++] = '<span>';
							list[li++] = val;
							list[li++] = '</span>';
							list[li++] = '</a>';
							list[li++] = '</li>';
						});
						
						$arrows.append(list.join('')).appendTo($slideshow);
						$slideshow.addClass('has-cycle-arrows');
						$hover = $hover.add($arrows.find('li'));
					}
					
					// hover on container and optionally the arrows
					$hover.bind('mouseover.hover mouseout.hover', function(event){
						switch(event.type.toLowerCase()) {
							case 'mouseover':
								$(this).addClass('hover');
								break;
								
							case 'mouseout':
								$(this).removeClass('hover');
								break;
						}
					});

					$slideshow.children('ul.slideshow').cycle(App.options.cycle);
				}
			},

			/**
			* Colour
			* @desc Colour switcher
			* @uses cookie()
			* @see http://plugins.jquery.com/project/cookie
			*/
			colour: function() {
				if($.cookie) {
					var $colour = $('body, #wrapper');
					$('#nav li.colour a').bind('click.colour', function(event){
						var $$, $li, current, goto;
						
						$$	= $(event.target).closest('a');
						$li	= $$.closest('li');
						
						if($li.is('.black')) {
							// currently black, set to white
							current	= 'White';
							goto	= 'Black';
						}
						else if($li.is('.white')) {
							current	= 'Black';
							goto	= 'White';
						}
						
						// set the cookie, change the text, class and href
						$.cookie('colour', current.toLowerCase(), { path: '/' });
						$$.text(goto).attr('href', '?colour=' + goto.toLowerCase());
						$li.add($colour).removeClass(goto.toLowerCase()).addClass(current.toLowerCase());
						
						$$.blur();
						event.preventDefault();
					});
				}
			},

			/**
			* project
			* @desc Loading projects dynamically
			*/
			project: function() {
				var $project, $image, $thumbs,
					$img, $heading, $previous, $next,
					total;
				
				$project	= $('#project');
				$image		= $('#image', $project);
				$thumbs		= $('ul.thumbnails', $project);
				$img		= $('img', $image);
				$heading	= $('h2', $image);
				$previous	= $('ul.cycle-arrows li.previous', $image);
				$next		= $('ul.cycle-arrows li.next', $image);
				total		= $thumbs.children().length;
					
				if($next.find('a').length === 0) {
					$next.wrapInner('<a href="#next" />').hide();
				}
				if($previous.find('a').length === 0) {
					$previous.wrapInner('<a href="#previous" />').hide();
				}
				
				$(document).bind('crossfadeStart crossfadeEnd', function(event){
					switch(event.type) {
						case 'crossfadeStart':
							$previous.add($next).addClass(App.options.disabled);
							break;
							
						case 'crossfadeEnd':
							$(window).trigger('resize');
							$previous.add($next).removeClass(App.options.disabled);
							break;
					}
				});
								
				$('#project').bind('click.project', function(event){
					var $$, $li, $ul, $thumbsLi,
						$thumb,
						href, src, file, index,
						prev, next;
					
					$$			= $(event.target).closest('a');
					$li			= $$.closest('li');
					$ul			= $li.closest('ul');
					href		= $$.attr('href');
					
					if($$.length === 1 && $image.length === 1) {
						
						$$.blur();
						event.preventDefault();
						
						if($ul.is('.cycle-arrows')) {
							// a previous / next link
							$thumbsLi = $thumbs.find('a[href="' + href + '"]').closest('li');
						}
						else {
							$thumbsLi = $li;
						}
						
						if($thumbsLi.is('.' + App.options.active)) {
							return;
						}
						
						index	= $thumbsLi.index();												
						$thumb	= $thumbsLi.find('img');
						alt		= $thumb.attr('alt');
						src		= $thumb.attr('src');
						file	= src.substring(src.lastIndexOf('/'));
						src		= src.replace(file, '/large' + file);
						
						/**
						* @uses crossfade()
						*/
						if($.fn.crossfade && !($.browser.msie && parseInt($.browser.version, 10) === 6)) {
							$image.crossfade({
								animated:	true,
								duration:	App.options.crossfade,
								target:		src,
								callback:	function(o) {
									$thumbsLi.addClass(App.options.active).siblings().removeClass(App.options.active);
									$heading.text(alt);
								}
							});
						}
						else {
							$thumbsLi.addClass(App.options.active).siblings().removeClass(App.options.active);
							$img.attr('src', src).attr('alt', alt).attr('title', alt);
							$heading.text(alt);
						}
						
						if(index === 0) {
							$previous.hide();
						}
						else {
							// change the href
							prev = $thumbsLi.prev().find('a').attr('href');
							$previous.show().find('a').attr('href', prev);
						}
						
						if(index === total - 1) {
							$next.hide();
						}
						else {
							// change the href
							next = $thumbsLi.next().find('a').attr('href');
							$next.show().find('a').attr('href', next);
						}
					}
				});
			},
			
			/**
			* Carousel
			* @desc Scrolling products with previous and next arrows
			* @uses carousel()
			* @uses jCarouselLite()
			* @see http://www.gmarwaha.com/jquery/jcarousellite/
			*/
			carousel: function() {
				if($.fn.carousel && $.fn.jCarouselLite) {
					$('body').addClass('has-carousel');
					
					var $scroller, options;
	
					$scroller	= $('ul.scroller');
					options		= $.extend({}, App.options.carousel, {
						//start:	$scroller.find('li.active').index()
					});
					
					$scroller.carousel(options);
				}
			},
			
			/**
			* Image Fit
			* @desc Fit the image to the browser width / height
			* @uses imageFit()
			*/
			imageFit: function() {
				if($.fn.imageFit) {
					var $image, $slideshow;
					
					$image		= $('#image');
					$slideshow	= $('#content ul.slideshow');
						
					$image.imageFit({
						offset: {
							top:	225,
							left:	0
						},
						callback:	function($li, $img, height, width, o){
							if(height !== 0 && width !== 0) {
								$image.css({height: height, width: width});
							}
						}
					});
					
					$slideshow.children('li').imageFit({
						offset: {
							top:	155,
							left:	0
						},
						callback:	function($li, $img, height, width, o){
							if(height !== 0 && width !== 0) {
								$slideshow.add($li).css({height: height + 30, width: width});
							}
						}
					});
				}
			},

			videoPlayer: function(){
				if($.fn.jwplayer) {
					var $body = $('body').addClass('has-video-player');

					if($body.is('.black')) {
						App.options.jwplayer.screencolor = '#000000';
					}

					$('#video-player').jwplayer(App.options.jwplayer);
				}
				if(typeof VideoJS !== 'undefined') {
					var $body = $('body').addClass('has-video-player');
					VideoJS.setup();
				}
			}
		};

		/**
		* READY!
		* @desc Document ready, load all the app functions
		*/
		jQuery(document).ready(function($) {
			App.init();
			App.expandable();
			App.idleTimer();
			App.colour();
			App.project();
			App.carousel();
			App.slideshow();
			App.imageFit();
			App.videoPlayer();
		});
		
		// IE 6 hover fix
		if(document.all && document.getElementById) {
			window.onload = App.hover;
		}
		
		/**
		 * Cookie plugin
		 * Get the value of a cookie with the given name.
		 *
		 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
		 * Dual licensed under the MIT and GPL licenses:
		 * http://www.opensource.org/licenses/mit-license.php
		 * http://www.gnu.org/licenses/gpl.html
		 */
		jQuery.cookie = function(name, value, options) {
			if (typeof value != 'undefined') { // name and value given, set cookie
				options = options || {};
				if (value === null) {
					value = '';
					options.expires = -1;
				}
				var expires = '';
				if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
					var date;
					if (typeof options.expires == 'number') {
						date = new Date();
						date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
					} else {
						date = options.expires;
					}
					expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
				}
				var path = options.path ? '; path=' + (options.path) : '';
				var domain = options.domain ? '; domain=' + (options.domain) : '';
				var secure = options.secure ? '; secure' : '';
				document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
			} else { // only name given, get cookie
				var cookieValue = null;
				if (document.cookie && document.cookie != '') {
					var cookies = document.cookie.split(';');
					for (var i = 0; i < cookies.length; i++) {
						var cookie = jQuery.trim(cookies[i]);
						// Does this cookie string begin with the name we want?
						if (cookie.substring(0, name.length + 1) == (name + '=')) {
							cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
							break;
						}
					}
				}
				return cookieValue;
			}
		};

	// end of jQuery closure
	})(jQuery);
}
