(function($){
	$.fn.slidey = function(options) {
	
		var settings = {};	
		
		var defaults = {
			rotationSpeed: 	3000,		// The speed of the image rotation
			animSpeed:		500,		// The speed of the transitions
			child: 			'img',		// The type of element which we will be rotating
			controls: 		false,		// Does the slider have controls?
			centerControls:	false,		// Vertically center the controls?
			nextText:		'',			// Text to use for next button
			prevText:		'',			// Text to use for previous button
			hoverPause: 	false,		// Does the slide pause on hover?
			showPosition:	false,		// Do we want positional indicators?
			centerMarkers:	true		// Horizontally center the markers?
		}
		
		// Overwrite the defaults with the provided options (if any)
		settings = $.extend({}, defaults, options);
		
		// jQuery vars
		var	$slider = this,									// The slider parent
			$banners = $slider.children(settings.child), 	// The slides
			$position,										// Marker wrapper
			$markers,										// Markers
			$next,											// Next button
			$previous										// Previous button
		
		// non-jQuery vars
		var paused = false,					// Is the slider currently paused?
			fwd = 0,						// Value indicating next
			back = -1,						// Value indicating previous
			current_slide = 0,				// The currently active slide
			marker_pos = 0,					// The currently active marker
			slide_count = $banners.length, 	// The total number of slides
			first = 0,						// The First slide in the array
			last = slide_count-1,			// The last slide in the array
			next = slide_count,				// value for next
			prev = -1						// value for previous
		
		$($banners[0]).addClass('active');
		// for first image in firt gallery
		//
		

		
		// do things only if there's more than 1 banner
		if($banners[1]) {
		
			// 
			$(window).load(function(){
				// set image container width and height
				var container_width = $('.image_slideshow').width();// 740; 
				var container_height = $('.image_slideshow').height();//560;
				
				// need to create a loop for each element or the function will only apply image centering to the first image
				var image_collection = $('.gallery_container a');
				
				// get image width and height of current element
				var image_width1 = $($banners[0]).outerWidth();
				var image_height1 = $($banners[0]).outerHeight();
				
				// apply new centering for images
				if(image_width1 <= container_width) {
					$($banners[0]).css("left", (container_width - image_width1) / 2 );
				}
				if(image_height1 <= container_height) {
					$($banners[0]).css("top", (container_height - image_height1) / 2 );
				}
				
				// do it all all of them. 
				$.each(image_collection, function(index, value){
								
					// get image width and height of current element
					var image_width = $(value).outerWidth();
					var image_height = $(value).outerHeight();
					console.log(container_width + '-' + image_width);
					
					// apply new centering for images
					if(image_width <= container_width) {
						$(this).css("left", (container_width - image_width) / 2 );
					}
					if(image_height <= container_height) {
						$(this).css("top", (container_height - image_height) / 2 );
					}
					
				});
			});
		
			// Hook me with some positional indicators!	
			if(settings.showPosition){
			
				// Create the parent element and append it to the slider
				$position = $('<ul class="position"></ul>');	
				$position.appendTo($slider);
				
				$.each($banners,function(key,value){
					// for all other images in first gallery (apaft from first) NEED to be centered some how

					$(document).ready(function(){
						// set image container width and height
						var container_width = 740;
						var container_height = 560;
						// get image width and height of current element
						var image_width2 = $(value).outerWidth();
						var image_height2 = $(value).outerHeight();
						
						// apply new centering for images
						if(image_width2 <= container_width) {
							$(this).css("left", (container_width - image_width2) / 2 );
						}
						if(image_height2 <= container_height) {
							$(this).css("top", (container_height - image_height2) / 2 );
						}
					});
				
					$(this).hide();
					key++
					$('<li><span>'+key+'</span></li>').appendTo($position);

					
				});
				//console.log("-" + $position.innerWidth() );
				$($banners[0]).show();
				// Gather all the markers
				$markers = $position.children('li');
			
				// Iterate over the markers and bind a click event to each one
				$.each($markers, function(key,value){
					$(value).click(function(e){
						e.preventDefault();
						slideyGo(key);
					});
				})

				// Horizontally center the markers
				if(settings.centerMarkers){
					offset = ($slider.width() - $position.innerWidth() )/ 2;
					offset = 8;
					$position.css('left', offset);
					//console.log(offset + "-" + $slider.width() + "-" + $position.innerWidth() );
				}

				$($markers[first]).addClass('active');
			}
			
			// Hook up the controls!
			if(settings.controls){
				
				// Create the control elements and append them to the slider
				$next = $('<span id="slidey-next" class="slidey-controls">'+settings.nextText+'</span>');
				$previous = $('<span id="slidey-prev" class="slidey-controls">'+settings.prevText+'</span>');

				$next.appendTo($slider);
				$previous.appendTo($slider);
				
				// Bind click events to the controllers
				$next.click(function(e){
					e.preventDefault();
					slideyGo(next);
				});
				
				$previous.click(function(e){
					e.preventDefault();
					slideyGo(prev);
				});
				
				// Vertically center the controllers
				if(settings.centerControls){
					offset = ($slider.height() - $('#slidey-next').innerHeight()) / 2;
					$next.css('top', offset);
					$previous.css('top', offset);
				}
		
			}
			
			//If pause on hover is enabled, we need to hook that shit up!
			if(settings.hoverPause){
				
				$slider.hover(function(){
					
					if(!paused){
						clearInterval(slideyInterval);
						paused=true;
					}
					
				},function(){
					
					if(paused){
						slideyInterval = setInterval(function(){ slideyGo(next) }, settings.rotationSpeed);
						paused=false;
					}
					
				});
				
			}
			
			//PARTY TIME
			var slideyInterval = setInterval(function(){ slideyGo(next) }, settings.rotationSpeed);
			
			
			var slideyGo = function(move){
				
				if(move != current_slide){
					
					$($banners[current_slide]).animate({opacity: 0.0}, settings.animSpeed, function(){
						$(this).hide();
					});
		
					if (move == next){
						
						// Forza, Slidey!
						
						if(current_slide == last){
							$($banners[first]).show().animate({opacity: 1.0}, settings.animSpeed);
							current_slide=first;
						}
						else{
							$($banners[current_slide+1]).show().animate({opacity: 1.0}, settings.animSpeed);
							current_slide++;
						}
						
					} else if (move == prev){
						
						// Back slidey! Go Back!
						
						if(current_slide == first){
							$($banners[last]).show().animate({opacity: 1.0}, settings.animSpeed);
							current_slide=last;
						}
						else{
							$($banners[current_slide-1]).show().animate({opacity: 1.0}, settings.animSpeed);
							current_slide--;
						}
						
					} else {
						
						// Jump around Slidey! Jump up, jump up and get down!
						$($banners[move]).show().animate({opacity: 1.0}, settings.animSpeed);
						current_slide=move;
						
					}
					
					// update the markers
					if(settings.showPosition){
						$markers.removeClass('active');
						$($markers[current_slide]).addClass('active');
					}
					
				}
				
			}
			function slideleft() {
				slideyGo(next);
			}		

			function slideright() {
				slideyGo(prev);
			}			
		
			// slider AMG!
			// swipe magic
			$('.image_slideshow').swipe({
				threshold: {
					x:100, 
					y:50
				},
				swipeLeft: slideleft,
				swipeRight: slideright
			});
		
		}
		
		return this;
		
	}
})(jQuery);




// create slidehsow thing
$(document).ready(function(){

	// page slideshows
	$('#banner').slidey({
		'rotationSpeed':6000,
		'hoverPause' : true,
		'controls' : true,
		'showPosition' : false,
		'child': 'a'
	});
	
	
	// set up gallery thumbnail scroller
	var thumb_bar_x = 0;
	var thumb_bar_speed = 400;
	var thumb_bar_icon_width = 136;		// length including padding. This is multiplied by the COUNT to figure out the width of the element
	var thumb_bar_step = 5;
	var thumb_bar_limit = $('#project_list_scroller div').length;	// limit it can go to the left (eg -1022px). 0 is the max to the right because it's held in negatives
	
	var thumb_bar_current_pos = 0;
	
	function animate_thumb_scroller(pos) {
		$('#project_list_scroller').animate({
			left: thumb_bar_current_pos * -1 * thumb_bar_icon_width
		}, thumb_bar_speed );
	};
	
	function run_left(){
		$('#project_list_scroll_left').stop();
		if (thumb_bar_current_pos < (thumb_bar_limit - thumb_bar_step)) {
			thumb_bar_current_pos += thumb_bar_step;
			animate_thumb_scroller(thumb_bar_current_pos);
		}
	}
	
	function run_right() {
		$('#project_list_scroll_left').stop();
		if (thumb_bar_current_pos > 0) {
			thumb_bar_current_pos -= thumb_bar_step;
			animate_thumb_scroller(thumb_bar_current_pos);
		}
	}
	
	
	//console.log(thumb_bar_limit);
	
	
	// swipe magic
	$('.project_list_container').swipe({
		threshold: {
			x:100, 
			y:50
		},
		swipeLeft: run_left,
		swipeRight: run_right
	});
	
	$('#project_list_scroll_right').click(run_left);
	$('#project_list_scroll_left').click(run_right);
	
	// changes gallery on screen to id of one linked in ahchor hash in URL
	// eg "#gallery5" will hide the galleries except 5
	var hash = (window.location.hash).replace('#gallery', '');
	if( hash) {
		$('.gallery_container').hide();
		$('#gallery_container_' + hash).show();
	}
	
});

/*
 * jSwipe - jQuery Plugin
 * http://plugins.jquery.com/project/swipe
 * http://www.ryanscherf.com/demos/swipe/
 *
 * Copyright (c) 2009 Ryan Scherf (www.ryanscherf.com)
 * Licensed under the MIT license
 *
 * $Date: 2009-07-14 (Tue, 14 Jul 2009) $
 * $version: 0.1.2
 * 
 * This jQuery plugin will only run on devices running Mobile Safari
 * on iPhone or iPod Touch devices running iPhone OS 2.0 or later. 
 * http://developer.apple.com/iphone/library/documentation/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html#//apple_ref/doc/uid/TP40006511-SW5
 */
(function($) {
	$.fn.swipe = function(options) {
		
		// Default thresholds & swipe functions
		var defaults = {
			threshold: {
				x: 30,
				y: 10
			},
			swipeLeft: function() { alert('swiped left') },
			swipeRight: function() { alert('swiped right') }
		};
		
		var options = $.extend(defaults, options);
		
		if (!this) return false;
		
		return this.each(function() {
			
			var me = $(this)
			
			// Private variables for each element
			var originalCoord = { x: 0, y: 0 }
			var finalCoord = { x: 0, y: 0 }
			
			// Screen touched, store the original coordinate
			function touchStart(event) {
				//console.log('Starting swipe gesture...')
				originalCoord.x = event.targetTouches[0].pageX
				originalCoord.y = event.targetTouches[0].pageY
			}
			
			// Store coordinates as finger is swiping
			function touchMove(event) {
			    event.preventDefault();
				finalCoord.x = event.targetTouches[0].pageX // Updated X,Y coordinates
				finalCoord.y = event.targetTouches[0].pageY
			}
			
			// Done Swiping
			// Swipe should only be on X axis, ignore if swipe on Y axis
			// Calculate if the swipe was left or right
			function touchEnd(event) {
				//console.log('Ending swipe gesture...')
				var changeY = originalCoord.y - finalCoord.y
				if(changeY < defaults.threshold.y && changeY > (defaults.threshold.y*-1)) {
					changeX = originalCoord.x - finalCoord.x
					
					if(changeX > defaults.threshold.x) {
						defaults.swipeLeft()
					}
					if(changeX < (defaults.threshold.x*-1)) {
						defaults.swipeRight()
					}
				}
			}
			
			// Swipe was started
			function touchStart(event) {
				//console.log('Starting swipe gesture...')
				originalCoord.x = event.targetTouches[0].pageX
				originalCoord.y = event.targetTouches[0].pageY

				finalCoord.x = originalCoord.x
				finalCoord.y = originalCoord.y
			}
			
			// Swipe was canceled
			function touchCancel(event) { 
				//console.log('Canceling swipe gesture...')
			}
			
			// Add gestures to all swipable areas
			this.addEventListener("touchstart", touchStart, false);
			this.addEventListener("touchmove", touchMove, false);
			this.addEventListener("touchend", touchEnd, false);
			this.addEventListener("touchcancel", touchCancel, false);
				
		});
	};
})(jQuery);
