jQuery(function($){
	function Timeout(fn, interval, scope, args) {
	    scope = scope || window;
	    var self = this;
	    var wrap = function(){
	        self.clear();
	        fn.apply(scope, args || arguments);
	    }
	    this.id = setTimeout(wrap, interval);
	}
	Timeout.prototype.id = null
	Timeout.prototype.cleared = false;
	Timeout.prototype.clear = function () {
	    clearTimeout(this.id);
	    this.cleared = true;
	    this.id = null;
	};
	
	function startTimer() {
		if (!timer || timer.cleared) {
			timer = new Timeout(nextSlide, pause);
		}
		
	};
	
	function stopTimer() {
		if (timer && !timer.cleared) {
			timer.clear();
		}	
	}
	
	
	var bgCount = $('.imagefield-field_slideshow').length;
	var autoCycle = $('#portfolio-project').length ? false : true; //don't autocycle on portfolio, but autocycle on homepage
	var curSlide = 0;
	var prevSlide = -1;
	var pause = 5000; //for auto-cyclicng
	var speed = 1500; //milliseconds
	var timer;
	
	// Info-boxes
	$('.activator').hover(
		function(){
			var ind = $('.activator').index($(this));
			var section = $('.index-section:eq('+ind+')');
			openSection(section);
		}, function(){
			
		});
	
	
	function openSection(section) {
		var ind = $('.index-section').index(section),
			activator = $('.activator:eq('+ind+')');
		
		activator.hide();
		stopTimer();
		$('.index-section.expanded').each(function(){
			closeSection($(this));
		});
		section.addClass('expanded');
		$('.panel-content', section).show('fast');
	}
	
	function closeSection(section) {
		var ind = $('.index-section').index(section),
			activator = $('.activator:eq('+ind+')');
		
		$('.panel-content', section).hide('fast', function(){
			section.removeClass('expanded');
			activator.show();
			if ($('.index-section.expanded').length == 0 && autoCycle) {
				startTimer();
			}
		});
	}
	
	$('.index-section, .port-section').hover(function(){
		if (!$(this).hasClass('expanded')) {
			openSection($(this));
		}
	}, function(){
		closeSection($(this));
	});

	
	$('.index-section a.arrow, .port-section a.arrow').click(function(e){
		e.preventDefault();
		closeSection($(this).parent());
	})
	
	//----- Info-boxes end
	
	if (bgCount) {		
		$('body').prepend('<div id="bg-container"></div>');
		
		var element = $('#bg-container');
		
		// For pre-loading images
		var tempImg = $(new Image());
		
		$('.imagefield-field_slideshow').each(function(){
		  // Pre-load image so the browser caches it
		  tempImg.attr('src', $(this).attr('src'));
		  
			var block = $('<div class="bg-block"></div>');
			$(this).clone().removeClass('imagefield-field_slideshow').appendTo(block);
			element.append(block);
			var parent = $(this).parent();
			if (parent.is('a')) {
				parent.click(function(e){
					e.preventDefault();
					if(!$(this).hasClass('active')){
						prevSlide = curSlide;
						curSlide = $(this).closest('ul').children().index($(this).parent());
						cycleTo(curSlide);
					}
				});
			};
		});
		
		$(window).resize(function(){
			resizeUpdate();
		});
		
		$('.bg-block').css('top', '100%');
		$('.bg-block').eq(0).css('top', '0');
		
		if (autoCycle) {
			startTimer();
			//setTimeout (nextSlide, pause);
		};
		
		$('#prev').click(function(){	
			previousSlide();
		});
		
		$('#next').click(function(){
			nextSlide();
		});
		
		if ($('.port-nav').length) {
			$('.port-nav li:first a').addClass('active');
		};
		
	};
	
	$(window).load(function(){
		resizeUpdate();
	});
	
	function nextSlide() {
		prevSlide = curSlide;
		curSlide++;
		curSlide = (bgCount == curSlide) ? 0 : curSlide;
		
		cycleTo(curSlide);
		
		if (autoCycle) {
			stopTimer();
			startTimer();
		};
		
		if ($('.port-nav').length) {
			
		};
	}
	
	function previousSlide() {
		prevSlide = curSlide;
		curSlide--;
		curSlide = (0 > curSlide) ? bgCount-1 : curSlide;
		cycleTo(curSlide);
		
		if (autoCycle) {
			stopTimer();
			startTimer();
		};
		
		if ($('.port-nav').length) {
			
		};
	}
	
	function cycleTo(ind){
		var block = $('.bg-block').eq(ind);
		var img = $('img', block);
		var prevBlock = $('.bg-block').eq(prevSlide);
		var prevImg = $('img', prevBlock);
		var browserHalf = $(window).height() / 1.3;
		var prevImgTop = prevImg.data('top');
		var imgTop = img.data('top');
		
		if (Modernizr.csstransforms && !$.browser.msie) {//Use css transform if possible (works in FF3.5, chrome, opera, safari)
			
			block.css('top', '100%');
			prevBlock.css('top', '0');
			setTransform(img, -browserHalf + 'px');
			
			$({stepper: 0}).animate({stepper: 100}, {
				duration: speed,
				step: function(){
					var now = this.stepper;
					setTransform(prevBlock, '-'+now+'%');
					setTransform(prevImg, (browserHalf * now / 100) + 'px');
					setTransform(block, '-'+now+'%');
					setTransform(img, (-browserHalf * (100 - now) / 100) + 'px');
				},
				complete: function() {
					setTransform(prevBlock, '-100%');
					setTransform(block, '-100%');
					setTransform(img, '0px');
					setTransform(prevImg, 0);
				}
			})
		} else {	//For IE and other browsers animating css property
			block.css('top', '100%');
			img.css('top',  (imgTop - browserHalf)+'px');
			block.animate({'top': "0%"}, speed);
			img.animate({'top': imgTop+"px"}, speed);
			prevBlock.animate({'top': "-100%"}, speed);
			prevImg.animate({'top': (prevImgTop + browserHalf)+"px"}, speed);
		};
		
		$('#nav-counter .slide-number').text(curSlide+1);
		
		if ($('.port-nav').length) {
			$('.port-nav a.active').removeClass('active');
			$('a', '.port-nav li:eq('+curSlide+')').addClass('active');
		};
		

	}
	
	function setTransform(element, value) {
		if (Modernizr.csstransforms3d) {
			element.css({
				'-moz-transform' : 'translate3d(0, '+value+', 0)',
				'-webkit-transform' : 'translate3d(0, '+value+', 0)',
				'-o-transform' :'translate3d(0, '+value+', 0)',
				'-ms-transform' :'translate3d(0, '+value+', 0)',
				'transform' :'translate3d(0, '+value+', 0)'
			});
		} else {
			element.css({
				'-moz-transform' : 'translateY('+value+')',
				'-webkit-transform' : 'translateY('+value+')',
				'-o-transform' : 'translateY('+value+')',
				'-ms-transform' :'translateY('+value+')',
				'transform' : 'translateY('+value+')'
			});
		}
		
	}
	
	function resizeUpdate() {
		return element.each(function() {
	  	
	  		var t = $('img', element);
	  		
	  		//Resize each image seperately
	  		$(t).each(function(){
	  		
				var ratio = ($(this).attr('height')/$(this).attr('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/browserwidth) > ratio){
					resizeHeight();	
				} else {
					resizeWidth();
				}
				
				/**End Image Resize**/
				
				
				/**Resize Functions**/
				
				function resizeWidth(){
							thisSlide.width(browserwidth);
							thisSlide.height(browserwidth * ratio);
				};
				
				function resizeHeight(minimum){

							thisSlide.height(browserheight);
							thisSlide.width(browserheight / ratio);
				};
				
				/**End Resize Functions**/
				
				$(this).css('left', (browserwidth - $(this).width())/2);
				$(this).css('top', (browserheight - $(this).height())/2);
				
				//Storing coordinates for animations
				$(this).data('left', (browserwidth - $(this).width())/2);
				$(this).data('top', (browserheight - $(this).height())/2);
			});
			
			//Basic image drag and right click protection
			$('img', element).bind("contextmenu",function(){
				return false;
			});
			$('img', element).bind("mousedown",function(){
				return false;
			});
			
			
			return false;
			
		});
	};
});



