/*
	Supersized - Fullscreen Slideshow jQuery Plugin
	Version 3.1.3
	www.buildinternet.com/project/supersized
	
	By Sam Dunn / One Mighty Roar (www.onemightyroar.com)
	Released under MIT License / GPL License
*/

(function($){

	var iOS = false;
	var hc = false;
	var update = false;
	//Add in Supersized elements
	$(document).ready(function() {
		$('body').prepend('<div id="supersized-loader"></div>').prepend('<div id="supersized"></div>');
				// kill preloader for anything other than homepage
		if (document.location.href.indexOf("#") != -1){
			$('#supersized-loader').hide();
		}

	});
	
	if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) {
		// console.log("ios found");
		iOS = true;
	}
	if (navigator.userAgent.match(/iPad/i))
	{
		var ua = $.browser;
		if (parseInt(ua.version.slice(0,3)) < 533)
		{
			update = true;
		}
	}
	//Resize image on ready or resize
	$.supersized = function( options ) {
		
		//Default settings
		var settings = {
			
			//Functionality
			slideshow               :   1,		//Slideshow on/off
			autoplay				:	1,		//Slideshow starts playing automatically
			start_slide             :   1,		//Start slide (0 is random)
			random					: 	0,		//Randomize slide order (Ignores start slide)
			slide_interval          :   5000,	//Length between transitions
			transition              :   1, 		//0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left
			transition_speed		:	750,	//Speed of transition
			new_window				:	1,		//Image links open in new window/tab
			pause_hover             :   0,		//Pause slideshow on hover
			keyboard_nav            :   1,		//Keyboard navigation on/off
			performance				:	1,		//0-Normal, 1-Hybrid speed/quality, 2-Optimizes image quality, 3-Optimizes transition speed // (Only works for Firefox/IE, not Webkit)
			image_protect			:	1,		//Disables image dragging and right click with Javascript
			image_path				:	'img/', //Default image path
			
			//Size & Position
			min_width		        :   0,		//Min width allowed (in pixels)
			min_height		        :   0,		//Min height allowed (in pixels)
			vertical_center         :   1,		//Vertically center background
			horizontal_center       :   1,		//Horizontally center background
			fit_portrait         	:   0,		//Portrait images will not exceed browser height
			fit_landscape			:   0,		//Landscape images will not exceed browser width  
			
			//Components
			navigation              :   1,		//Slideshow controls on/off
			thumbnail_navigation    :   0,		//Thumbnail navigation
			slide_counter           :   1,		//Display slide numbers
			slide_captions          :   1,	//Slide caption (Pull from "title" in slides array)
			blurred: 0
    	};
		
		//Default elements
		var element = $('#supersized');		//Supersized container
		var pauseplay = '#pauseplay';		//Pause/Play
		
		//Combine options with default settings
		if (options) {
			var options = $.extend(settings, options);	//Pull from both defaults and supplied options
		}else{
			var options = $.extend(settings);			//Only pull from default settings		
		}
		
		//General slideshow variables
		var inAnimation = false;					//Prevents animations from stacking
		var isPaused = false;						//Tracks paused on/off
		var image_path = options.image_path;		//Default image path for navigation control buttons
		
		//Determine starting slide (random or defined)
		if (options.start_slide){
			var currentSlide = options.start_slide - 1;	//Default to defined start slide
		}else{
			var currentSlide = Math.floor(Math.random()*options.slides.length);	//Generate random slide number
		}
		
		//If links should open in new window
		var linkTarget = options.new_window ? ' target="_blank"' : '';
		
		//Set slideshow quality (Supported only in FF and IE, no Webkit)
		if (options.performance == 3){
			element.addClass('speed'); 		//Faster transitions
		} else if ((options.performance == 1) || (options.performance == 2)){
			element.addClass('quality');	//Higher image quality
		}
		
		//Shuffle slide order if needed		
		if (options.random){
			arr = options.slides;
			for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);	//Fisher-Yates shuffle algorithm (jsfromhell.com/array/shuffle)
		    options.slides = arr;
		}
		
		/***Load initial set of images***/

		if (options.slides.length > 1){
			//Set previous image
			currentSlide - 1 < 0  ? loadPrev = options.slides.length - 1 : loadPrev = currentSlide - 1;	//If slide is 1, load last slide as previous
			//var imageLink = (options.slides[loadPrev].url) ? "href='" + options.slides[loadPrev].url + "'" : "";
			$("<img/>").attr("src", options.slides[loadPrev].images[0].image).appendTo(element).wrap('<div class="slide"></div>');
			
		}
		
		//Set current image
		//imageLink = (options.slides[currentSlide].url) ? "href='" + options.slides[currentSlide].url + "'" : "";
		$("<img/>").attr("src", options.slides[currentSlide].images[0].image).appendTo(element).wrap('<div class="activeslide slide"></div>');

		
		if (options.slides.length > 1){
			//Set next image
			currentSlide == options.slides.length - 1 ? loadNext = 0 : loadNext = currentSlide + 1;	//If slide is last, load first slide as next
			imageLink = (options.slides[loadNext].url) ? "href='" + options.slides[loadNext].url + "'" : "";
			$("<img/>").attr("src", options.slides[loadNext].images[0].image).appendTo(element).wrap('<div class="slide"></div>');

		}
		$('<div class="video-player"><div class="video-wrapper"></div></div>').appendTo(".slide");
  //   function addEvent(element, eventName, callback) {
  //     if (element.addEventListener) {
  //         element.addEventListener(eventName, callback, false);
  //     }
  //     else {
  //         element.attachEvent(eventName, callback, false);
  //     }
  // }

		// $(options.slides[currentSlide].images[0].video).appendTo(element.find(".activeslide").find(".video-wrapper"));
		
	//	<iframe id="player_1" src="http://player.vimeo.com/video/7100569?api=1&amp;player_id=player_1" width="540" height="304" frameborder="0"></iframe>
		// $f("player_1").addEvent('ready', function() {console.log("player ready")});

		/***End load initial images***/

		
		if (options.slideshow && options.slides.length > 1) 
		{
			$('#supersized-loader').css("height", $(window).height());
			// $('#supersized-loader').hide('clip', { direction: 'vertical' }, 1000).delay(500);
		}
		element.hide();					//Hide image to be faded in
		$('#controls-wrapper').hide();	//Hide controls to be displayed
		$("#navigation").hide();

		$(document).ready(function() {
			$(window).bind('orientationchange', refresh);
				if (update)
				{
					$('#supersized-loader').css('background-image', 'url(img/update.jpg)');
					$("#supersized-loader").append("<a id='update-ios' href='http://www.apple.com/uk/ios/' alt='Update your iOS'>update</a>");
					$("#supersized-loader").append("<a id='send-mail' href='mailto:contact@campaigndesign.co.uk ?Subject=Contact%20from%20Website%20'>send email</a>");
				}
				else
				{
				if (options.slideshow && options.slides.length > 1){
				$('#supersized-loader').delay(1500).fadeOut("slow", function() {

					if (document.location.href.indexOf("#") == -1){
						
						$('<div id="line-loader-inner"></div>').appendTo($('body')).wrap('<div id="line-loader"></div>');
						
						$('#line-loader-inner').animate({'width': '100%'}, 500, function() {
							$('#line-loader-inner').fadeOut("fast", function() {
								$('#line-loader').remove();
								$('#supersized-loader').remove();
							});
							element.fadeIn('slow');				
							$('#controls-wrapper').fadeIn("slow");	
							$("#navigation").fadeIn("slow", function() {
							$('<div id="video-wrapper"><div id="video"></div></div>').appendTo($("body"));
							$("#video").html(options.slides[currentSlide].images[0].video);
								if (iOS) (options.slides[currentSlide].images[0].video) ? $("#navigation").css("left", 0) : $("#navigation").css("left", -9999);
							$("#title").html(options.slides[currentSlide].title);
							$('#caption').html(unescape(options.slides[currentSlide].content));
							Cufon.replace('#title');
							if (iOS) $("#ios-nav-help").fadeIn("slow");
							});
							refresh();
						})
					}
					else {
						element.fadeIn('slow');				
						$('#controls-wrapper').fadeIn("slow");	
						$("#navigation").fadeIn("slow", function() {
						$('<div id="video-wrapper"><div id="video"></div></div>').appendTo($("body"));
						$("#video").html(options.slides[currentSlide].images[0].video);
							if (iOS) (options.slides[currentSlide].images[0].video) ? $("#navigation").css("left", 0) : $("#navigation").css("left", -9999);
						if (iOS) $("#ios-nav-help").fadeIn("slow");
						$("#title").html(options.slides[currentSlide].title);
						$('#caption').html(unescape(options.slides[currentSlide].content));
						//Cufon.refresh("#title")
						Cufon.replace('#title');
						});
						refresh();
					}
				});
			}
			else
			{
				$('#supersized-loader').hide();
				//	element.css({"z-index": "-999"});
				element.show();
				$("#video-wrapper").remove();
				refresh();
			
			}
			}	
		
			
			if (iOS)
			{
				hc = true;
				str = (hc) ? "ON" : "OFF";
			//	console.log(" hardware accelaration is "+str);
				// $("#longer").append('<a href="#" id="hc-toggle">HARDWARE ACCELERATION IS ON</a>');
				// var str = "on";
				// $("#hc-toggle").click(function() {
				// 	hc = !hc;
				// 	str = (hc) ? "ON" : "OFF";
				// 	$(this).html("HARDWARE ACCELERATION IS "+str)
				// })
				
			}
			
			// bind orientation event for ipad and iphone
			//$(window).bind('orientationchange', refresh);

			
				//Resize background image
			
			$('body').swipe({
					     swipeLeft: function() { $('#nextslide').trigger('click');  },
					     swipeRight: function() { $('#prevslide').trigger('click'); },
					});
					
		
		
		//	$('#supersized').click( function() {console.log("should trigger next slide");$('#nextslide').trigger('click')})
			// if (options.slide_captions) 
			// {
			// $("#title").html(options.slides[currentSlide].title);
			// $('#caption').html(unescape(options.slides[currentSlide].content))
			// 
			// }
			
			if (!(options.navigation)) $('#navigation').hide();	//Display navigation
			

			
			//Start slideshow if enabled
			if (options.slideshow && options.slides.length > 1){
			
				
			buildSubnav();
			
			var pageLink = $("#menu-last").attr("href").toString(); // cache
			var newLink = pageLink.substring(0, pageLink.search("backTo="))+"backTo="+options.slides[currentSlide].id;
			$("#menu-last").attr("href", newLink);
			
				//Navigation controls
				if (options.navigation){
				
					$('#navigation a').click(function(){  
   						$(this).blur();  
   						return false;  
   					});
					
					//Next button clicked
				    $('#nextslide').click(function() {
				    
				    	if(inAnimation) return false;		//Abort if currently animating
				    	
					    nextslide();		//Go to next slide
					    
					    return false;
					    
				    });
				    
				    //If next slide button is image
				    if ($('#nextslide').attr('src')){
				    	
					    $('#nextslide').mousedown(function() {
						   	$(this).attr("src", image_path + "arrow-right-glow.png");
						});
						$('#nextslide').mouseup(function() {
						    $(this).attr("src", image_path + "arrow-right.png");
						});
						$('#nextslide').mouseout(function() {
						    $(this).attr("src", image_path + "arrow-right.png");
						});
				    
				    }
				    
				    //Previous button clicked
				    $('#prevslide').click(function() {
				    
				    	if(inAnimation) return false;		//Abort if currently animating
				    	
					    prevslide();		//Go to previous slide
					   
					    
					    return false;
					    
				    });
					
					//If previous slide button is image
					if ($('#prevslide').attr('src')){
										
						$('#prevslide').mousedown(function() {
						    $(this).attr("src", image_path + "arrow-left-glow.png");
						});
						$('#prevslide').mouseup(function() {
						    $(this).attr("src", image_path + "arrow-left.png");
						});
						$('#prevslide').mouseout(function() {
						    $(this).attr("src", image_path + "arrow-left.png");
						});
					
					}
				    
				}	//End navigation controls
				
			}	//End slideshow options
			
		});
		$(window).load(function() {
			//Cufon.refresh("#title");
			resizenow();
		})
				
		//Keyboard Navigation
		if (options.keyboard_nav){
		
			$(document.documentElement).keydown(function (event) {
				
				if ((event.keyCode == 37) || (event.keyCode == 40)) { //Left Arrow or Down Arrow
					if ($('#prevslide').attr('src')) $('#prevslide').attr("src", image_path + "arrow-left-glow.png");		//If image, change back button to active
				} else if ((event.keyCode == 39) || (event.keyCode == 38)) { //Right Arrow or Up Arrow
					if ($('#nextslide').attr('src')) $('#nextslide').attr("src", image_path + "arrow-right-glow.png");	//If image, change next button to active
				}
				
			});
			
			$(document.documentElement).keyup(function (event) {
			
				
				if ((event.keyCode == 37) || (event.keyCode == 40)) { //Left Arrow or Down Arrow
					
					if ($('#prevslide').attr('src')) $('#prevslide').attr("src", image_path + "arrow-left.png");	//If image, change back button to normal
					
					if(inAnimation) return false;		//Abort if currently animating
					    	
					prevslide();		//Go to previous slide
					
					if(!(isPaused)) slideshow_interval = setInterval(nextslide, options.slide_interval);	//If not paused, resume slideshow
					
					return false;
				
				} else if ((event.keyCode == 39) || (event.keyCode == 38)) { //Right Arrow or Up Arrow
					
					if ($('#nextslide').attr('src')) $('#nextslide').attr("src", image_path + "arrow-right.png");	//If image, change next button to normal
					
					if(inAnimation) return false;		//Abort if currently animating
					    	
				    nextslide();		//Go to next slide
				    
				   
				    return false;
				
				} 
			
			});
		}
		
				
		//Adjust image when browser is resized
		$(window).resize(function(){
    		resizenow();
		});
		function refresh()
		{
			 
				resizenow();
				var orient;
				var currentWidth = window.innerWidth;
				if (iOS)
				{
						var orient = ((orientation == "90") || (orientation == "-90")) ? "landscape" : "profile";
							if(navigator.userAgent.match(/iPhone/i))
							{
								if (orient == "landscape")
								{
								//	$("#viewport").attr("content", "width=480 height=535 initial-scale=0.5, maximum-scale=0.5, user-scalable=no" )
								$("#viewport").attr("content", "width=480 height=362 initial-scale=0.75, maximum-scale=0.75, user-scalable=no" )
								}
								else
								{
									// $("#viewport").attr("content", "width=320 height=832 initial-scale=0.5, maximum-scale=0.5, user-scalable=no" )
									 $("#viewport").attr("content", "width=320 height=564 initial-scale=0.75, maximum-scale=0.75, user-scalable=no" )
								}
								// console.log("iphone set scale to .5");
							}
						//console.log("orientation = "+orientation +" "+orient);
						$("body").attr("class", orient);
						//console.log("orientation = "+$("body").attr("orient"));
						window.setTimeout(function() {this.scrollTo(0,1)}, 100);
				}
			
						
		}
		
		//Adjust image size
		function resizenow() {
			// console.log("resizenow() called ! ");
			return element.each(function() {
								  	
								  		var t = $('img', element);
								  		
								  		//Resize each image seperately
								  		$(t).each(function(){
								  		
											var ratio = ($(this).height()/$(this).width()).toFixed(2);	//Define image ratio
											thisSlide = $(this);
											
											//Gather browser size
											var browserwidth = $(window).width();
											var browserheight = $(window).height();
											var offset;
											
											/**Resize image to proper ratio**/
											
											// if ((browserheight <= options.min_height) && (browserwidth <= options.min_width)){	//If window smaller than minimum width and height
											// 
											// 	if ((browserheight/browserwidth) > ratio){
											// 		options.fit_landscape && ratio <= 1 ? resizeWidth(true) : resizeHeight(true);	//If landscapes are set to fit
											// 	} else {
											// 		options.fit_portrait && ratio > 1 ? resizeHeight(true) : resizeWidth(true);		//If portraits are set to fit
											// 	}
											// 
											// } else if (browserwidth <= options.min_width){		//If window only smaller than minimum width
											// 
											// 	if ((browserheight/browserwidth) > ratio){
											// 		options.fit_landscape && ratio <= 1 ? resizeWidth(true) : resizeHeight();	//If landscapes are set to fit
											// 	} else {
											// 		options.fit_portrait && ratio > 1 ? resizeHeight() : resizeWidth(true);		//If portraits are set to fit
											// 	}
											// 	
											// } else if (browserheight <= options.min_height){	//If window only smaller than minimum height
											// 
											// 	if ((browserheight/browserwidth) > ratio){
											// 		options.fit_landscape && ratio <= 1 ? resizeWidth() : resizeHeight(true);	//If landscapes are set to fit
											// 	} else {
											// 		options.fit_portrait && ratio > 1 ? resizeHeight(true) : resizeWidth();		//If portraits are set to fit
											// 	}
											// 
											// } else {	//If larger than minimums
											// 
												if ((browserheight/browserwidth) > ratio){
													
														(options.fit_landscape) ? resizeWidth() : resizeHeight();
												} 
												else
												{
													(options.fit_portrait) ? resizeHeight() : resizeWidth();
													// resizeHeight();
												}
												
												// if ((browserheight/browserwidth) > ratio){
												// 	
												// 	options.fit_landscape && ratio <= 1 ? resizeWidth() : resizeHeight();	//If landscapes are set to fit
												// } else {
												// 	options.fit_portrait && ratio > 1 ? resizeHeight() : resizeWidth();		//If portraits are set to fit
												// }
						
					// }
					
					/**End Image Resize**/
					
					
					/**Resize Functions**/
					
					function resizeWidth(minimum){
						if (minimum){	//If minimum height needs to be considered
							if(thisSlide.width() < browserwidth || thisSlide.width() < options.min_width ){
								if (thisSlide.width() * ratio >= options.min_height){
									thisSlide.width(options.min_width);
						    		thisSlide.height(thisSlide.width() * ratio);
						    	}else{
						    		resizeHeight();
						    	}
						    }
						}else{
							if (options.min_height >= browserheight && !options.fit_landscape){	//If minimum height needs to be considered
								if (browserwidth * ratio >= options.min_height || (browserwidth * ratio >= options.min_height && ratio <= 1)){	//If resizing would push below minimum height or image is a landscape
									thisSlide.width(browserwidth);
									thisSlide.height(browserwidth * ratio);
								} else if (ratio > 1){		//Else the image is portrait
									thisSlide.height(options.min_height);
									thisSlide.width(thisSlide.height() / ratio);
								} else if (thisSlide.width() < browserwidth) {
									thisSlide.width(browserwidth);
						    		thisSlide.height(thisSlide.width() * ratio);
								}
							}else{	//Otherwise, resize as normal
								thisSlide.width(browserwidth);
								thisSlide.height(browserwidth * ratio);
							}
						}
					};
					
					function resizeHeight(minimum){
						if (minimum){	//If minimum height needs to be considered
							if(thisSlide.height() < browserheight){
								if (thisSlide.height() / ratio >= options.min_width){
									thisSlide.height(options.min_height);
									thisSlide.width(thisSlide.height() / ratio);
								}else{
									resizeWidth(true);
								}
							}
						}else{	//Otherwise, resized as normal
							if (options.min_width >= browserwidth){	//If minimum width needs to be considered
								if (browserheight / ratio >= options.min_width || ratio > 1){	//If resizing would push below minimum width or image is a portrait
									thisSlide.height(browserheight);
									thisSlide.width(browserheight / ratio);
								} else if (ratio <= 1){		//Else the image is landscape
									thisSlide.width(options.min_width);
						    		thisSlide.height(thisSlide.width() * ratio);
								}
							}else{	//Otherwise, resize as normal
								thisSlide.height(browserheight);
								thisSlide.width(browserheight / ratio);
							}
						}
					};
					
					/**End Resize Functions**/
					
					
					//Horizontally Center
					if (options.horizontal_center){
						$(this).css('left', (browserwidth - $(this).width())/2);
					}
					
					//Vertically Center
					if (options.vertical_center){
						$(this).css('top', (browserheight - $(this).height())/2);
					}
					
				});
				
				//Basic image drag and right click protection
				// if (options.image_protect){
				// 	
				// 	$('img', element).bind("contextmenu",function(){
				// 		return false;
				// 	});
				// 	$('img', element).bind("mousedown",function(){
				// 		return false;
				// 	});
				// 
				// }
				
				return false;
				
			});
		};
	
		
		//Next slide
		function nextslide() {
			
			if(inAnimation) return false;		//Abort if currently animating
				else inAnimation = true;		//Otherwise set animation marker
				$("#video").html("");
		 // $("#video-player iframe").attr("src", "");
		// $("#video-player").remove();
		$("#ios-nav-help").hide();
			// $('#panelopen').fadeTo("fast", 0.1);
		   
		    var slides = options.slides;	//Pull in slides array
			
			var currentslide = element.find('.activeslide');		//Find active slide
			currentslide.removeClass('activeslide');				//Remove active class
			
		    if ( currentslide.length == 0 ) currentslide = element.find('div:last');	//If end of set, note this is last slide
		    var nextslide = currentslide.next().length ? currentslide.next() : element.find('div:first');
			var prevslide = nextslide.prev().length ? nextslide.prev() : element.find('div:last');
			//nextslide.find("img").attr("src", options.slides[currentslide].images[0].image);
			//Update previous slide
			$('.prevslide').removeClass('prevslide');
			prevslide.addClass('prevslide');
			
			//Get the slide number of new slide
			currentSlide + 1 == slides.length ? currentSlide = 0 : currentSlide++;
			
			//If hybrid mode is on drop quality for transition
			if (options.performance == 1) element.removeClass('quality').addClass('speed');	
			
			/**** Image Loading ****/
			
			//Load next image
			loadSlide = false;
			
			currentSlide == slides.length - 1 ? loadSlide = 0 : loadSlide = currentSlide + 1;	//Determine next slide
			//imageLink = (options.slides[loadSlide].url) ? "href='" + options.slides[loadSlide].url + "'" : "";	//If link exists, build it
			$("<img/>").attr("src", options.slides[loadSlide].images[0].image).appendTo(element).wrap("<div class='slide'></div>");	//Append new image
			// $('<div class="video-player"><div class="video-wrapper"></div></div>').appendTo(".slide:last");

			
			currentslide.prev().remove(); //Remove Old Image
			

		    
    nextslide.hide().addClass('activeslide');	//Update active slide
		// element.find('.activeslide').find('.video-wrapper').show();

						if (iOS && hc)
						{
							// console.log("using webkit animation");
							
							// standard webkit
							//nextslide.css({left : $(window).width()}).show().webkitanimate({ left:0 }, options.transition_speed, function(){ afterAnimation(); });
							//currentslide.webkitanimate({ left: -$(window).width() }, options.transition_speed );
							//nextslide.css({"z-index":0});
							nextslide.css({"-webkit-transform": "translateX("+$(window).width()+"px)"}).show();
							nextslide.anim3D(0, options.transition_speed, function(){ afterAnimation(); });
							currentslide.anim3D(-$(window).width(), options.transition_speed);
							
						}
						else
						{
							// console.log("using DOM animation");
							nextslide.css({left : $(window).width()}).show().animate({ left:0 }, options.transition_speed, function(){ afterAnimation(); });
							currentslide.animate({ left: -$(window).width() }, options.transition_speed );
						}
				
  
		}
		
		
		//Previous Slide
		function prevslide() {
		
			if(inAnimation) return false;		//Abort if currently animating
				else inAnimation = true;		//Otherwise set animation marker
				$("#video").html("");
			// $("#video-player iframe").attr("src", "");
			// $("#video-player").remove();
			$("#ios-nav-help").hide();
			// $('#panelopen').fadeTo("fast", 0.1);
			// $('#slidecontent').fadeTo("fast", 0.1);
			
			var slides = options.slides;	//Pull in slides array
	
			var currentslide = element.find('.activeslide');		//Find active slide
			currentslide.removeClass('activeslide');				//Remove active class
			
		    if ( currentslide.length == 0 ) currentslide = $(element).find('div:first');	//If end of set, note this is first slide
		    var nextslide =  currentslide.prev().length ? currentslide.prev() : $(element).find('div:last');
			var prevslide =  nextslide.next().length ? nextslide.next() : $(element).find('div:first');
			//nextslide.find("img").attr("src", options.slides[prevThumb].images[0].image)
			// prevslide.find("img").attr("src", options.slides[currentslide].images[0].image);
			//Update previous slide
			$('.prevslide').removeClass('prevslide');
			prevslide.addClass('prevslide');
					
			//Get current slide number
			currentSlide == 0 ?  currentSlide = slides.length - 1 : currentSlide-- ;
			
			//If hybrid mode is on drop quality for transition
			if (options.performance == 1) element.removeClass('quality').addClass('speed');	
					
			/**** Image Loading ****/
			
			//Load next image
			loadSlide = false;
			currentSlide - 1 < 0  ? loadSlide = slides.length - 1 : loadSlide = currentSlide - 1;	//Determine next slide
			//imageLink = (options.slides[loadSlide].url) ? "href='" + options.slides[loadSlide].url + "'" : "";	//If link exists, build it
			$("<img/>").attr("src", options.slides[loadSlide].images[0].image).prependTo(element).wrap("<div class='slide'></div>");	//Append new image
			// $('<div class="video-player"><div class="video-wrapper"></div></div>').appendTo(".slide:first");
			
			currentslide.next().remove(); //Remove Old Image
			
			

			
		nextslide.hide().addClass('activeslide');	//Update active slide
		// element.find('.activeslide').find('.video-wrapper').show();

						if (iOS && hc)
						{
						//	console.log("using webkit animation");
							//nextslide.css({left : -$(window).width()}).show().webkitanimate({ left:0 }, options.transition_speed, function(){ afterAnimation(); });
							//currentslide.webkitanimate({ left: $(window).width()}, options.transition_speed );
						//	currentslide.css({"z-index":0});
							nextslide.css({"-webkit-transform": "translateX("+-$(window).width()+"px)"}).show();
							nextslide.anim3D(0, options.transition_speed, function(){ afterAnimation(); });
							currentslide.anim3D($(window).width(), options.transition_speed );
						}
						else
						{
						//	console.log("using dom animation");
							nextslide.css({left : -$(window).width()}).show().animate({ left:0 }, options.transition_speed, function(){ afterAnimation(); });
							currentslide.animate({ left: $(window).width() }, options.transition_speed );
						}
		}
		
		//After slide animation
		function afterAnimation() {
			// UPDATE location hash
			//console.log("anim finsihed");
			location.hash = "project-"+options.slides[currentSlide].id;
			inAnimation = false; 
			
			// $('<div class="video-player"><div class="video-wrapper"></div></div>').appendTo(".slide");
			
			var pageLink = $("#menu-last").attr("href").toString(); // cache
			var newLink = pageLink.substring(0, pageLink.search("backTo="))+"backTo="+options.slides[currentSlide].id;
			$("#menu-last").attr("href", newLink);
			
		
			// $("#video-player").hide();
			
			currentSlide - 1 < 0  ? loadPrev = options.slides.length - 1 : loadPrev = currentSlide - 1;
			var prevImg = element.find('div.slide:first').find('img');
			var prevVid = $('<div class="video-player"><div class="video-wrapper"></div></div>').appendTo(element.find('div.slide:first'));
			
			prevImg.attr('src', options.slides[loadPrev].images[0].image);			
			//prevVid.find(".video-wrapper").html(options.slides[loadPrev].images[0].video);
			
			//$(options.slides[loadPrev].images[0].video).appendTo(prevVid);
			// prevVid.hide();
			//console.log("afteranim prev video = "+options.slides[loadPrev].images[0].video);
			
			currentSlide == options.slides.length - 1 ? loadNext = 0 : loadNext = currentSlide + 1;
			
			var nextImg = element.find('div.slide:last').find('img');
			var nextVid = $('<div class="video-player"><div class="video-wrapper"></div></div>').appendTo(element.find('div.slide:last'));
			
			nextImg.attr('src', options.slides[loadNext].images[0].image);
			//nextVid.find(".video-wrapper").html(options.slides[loadNext].images[0].video);
			
			$("#video").html(options.slides[currentSlide].images[0].video);
			//$("#player_1").attr("src", "http://player.vimeo.com/video/22642240?api=1&player_id=player_2");
			if (iOS) (options.slides[currentSlide].images[0].video) ? $("#navigation").css("left", 0) : $("#navigation").css("left", -9999);
			buildSubnav();
			//Update captions
		    if (options.slide_captions){
					// if (currentSlide ==0)	{
					// 				 $("#controls-wrapper").hide() ;
					// 				} 
					// 				else
					// 				{
					// 					$("#controls-wrapper").show() ;
					// 				}
						
					if 	(options.slides[currentSlide].title) 
					{
						$("#title").html(options.slides[currentSlide].title);
						Cufon.refresh("#title");
					}
					else
					{
						$('#title').html('');
					}
					// (options.slides[currentSlide].content) ? $('#slidecontent').showHtml(options.slides[currentSlide].content,300, function() {$('#panelopen').fadeTo("fast", 1.0)}) : $('#slidecontent').html('');
					if (iOS)
					{
						(options.slides[currentSlide].content) ? $('#caption').html(unescape(options.slides[currentSlide].content)) : $('#caption').html('<p></p>');
					}
					else
					{
						(options.slides[currentSlide].content) ? $('#caption').showHtml(unescape(options.slides[currentSlide].content),300) : $('#caption').html('<p></p>');
					}
					
		    }
				// add video
			//if (options.slides[currentSlide].images[0].video) 
			// {
				 //$(options.slides[currentSlide].images[0].video).appendTo(element.find(".activeslide").find())
			
			// }
			//If hybrid mode is on swap back to higher image quality
			if (options.performance == 1){
		    	element.removeClass('speed').addClass('quality');
			}
			
			resizenow();
			
		}
		function buildSubnav()
		{
			$('#subnav').html("");
			if (options.slides[currentSlide].images.length > 1)
			{

				for (var i=0; i < options.slides[currentSlide].images.length; i++)
				{
				
				// var linkText = (options.slides[currentSlide].images[i].video) ? "VIEW VIDEO" : (i+1).toString();
					var linkText = (i+1).toString();
	
					var linkEl = $('<a href="#" class="'+i+'" id="project-'+options.slides[currentSlide].id+'-slide-'+i+'">'+linkText+'</a>');
					$('#subnav').append(linkEl);
					$('#subnav a:first').css({"color":"#fff"});

					Cufon.refresh("#subnav");

					linkEl.click(function() {
					if ($(this).css("color") == "#fff" || $(this).css("color") == "rgb(255, 255, 255)") return false;
					
					// console.log($(this).css("color"));
						$('#subnav a').css({"color":"#aaa"});
						$(this).css({"color":"#fff"});
						
						// $("#video-player iframe").attr("src", "");
						//$("#video-player").remove();
						var id = parseInt($(this).attr("class"));

						Cufon.refresh("#subnav");
						//console.log("change slide of project "+options.slides[currentSlide].id+' to '+$(this).html());
						var currentImg = element.find('.activeslide').find('img');
						// if (iOS && hc)
						// {
						// 
						// 	// console.log("IOS opacity");
						// 	currentImg.one("load",resizenow );
						// 	currentImg.one("load", function() { currentImg.css("opacity",1);});
						// 
						// 	currentImg.css({ "-webkit-transition-property": "opacity",
						// 	                      "-webkit-transition-duration": "200ms",
						// 						"-webkit-transition-timing-function": "linear"});
						// 	window.setTimeout(function(x,y) {
						// 	 	              	x.css(y);
						// 										window.setTimeout(function(a) {
						// 											a.attr('src', options.slides[currentSlide].images[id].image);
						// 										},500, x);
						// 	 	            	},100, currentImg, {"opacity": 0}); 
						// }
						// else
						// {
							
							currentImg.one("load",resizenow );
							currentImg.one("load", function() {
															// console.log("next image loaded");
															currentImg.fadeIn("fast", function() {
															$("#video").html(options.slides[currentSlide].images[id].video);
																if (iOS) (options.slides[currentSlide].images[id].video) ? $("#navigation").css("left", 0) : $("#navigation").css("left", -9999);
															//element.find('.activeslide').find('.video-wrapper').empty();
															//element.find('.activeslide').find('.video-wrapper').html(options.slides[currentSlide].images[id].video);
															// $(options.slides[currentSlide].images[id].video).appendTo(element.find('.activeslide').find('.video-wrapper'));
															//	$(options.slides[currentSlide].images[id].video).prependTo($(".activeslide")).wrap('<div id="video-player"><div id="video-wrapper"></div></div>');
															});
	
							});
							currentImg.fadeOut("fast", function() {
							currentImg.attr('src', options.slides[currentSlide].images[id].image);

						});
						// }

						return false;
					})
				}

			}
		}
	};

		
})(jQuery);


