/*
**	Happyslide ~ jQuery Document
**	Version 3.0, latest update 2011-03-17
**	
**	Created by HappyFejs Design ~ Sebastian Andersson
**	http://www.happyfejs.se/
******************************************************
**	Copyright (c) 2011 HappyFejs Design
To do
Implement left/right key
******************************************************
******************************************************/
(function($){
	$.happyslide = function(options) {
		var defaults = { 
			activeSlide : 0,//Startslide, 0 is the first one
			slideSpeed : 800,//Speed of the slider change.
			slideTimeout : 8000,//Time between slide change if autoSlide it set to true.
			autoSlide : true,//Boolean, true will make the slideshow to auto change and false will force the user to change self .
			pauseOnHover: false,
			slideFunction : "fadePara",//String variable, "slidePara", "fadePara" or "fade".
			pageView : true,
			numThumbs : 6,//Number of displayed thumbs if pageView is set to true
			imageMaxWidth : $("ul.fade li .image").width(), //If specified image width in other case it will be the original size of the image.
			thumbMaxWidth: 147,
			thumbMaxHeight : 130,
			thumbHolderWidth: 0,
			thumbHodlerHeight:0,
			autoHeight: true,
			contentHeight:400,
			enableKeys:true,
			useHash:true,
			fullScreenImage:false,
			timebar:false,
			imagePlacement:"left",
			navArrows:false,
		    centerImage:false,
			verticalAlign:false
	  	};
		
		//Needed variables, don't change this
	 	var opts = $.extend(defaults, options);
		var slides = new Array();
		var pages = 0;
		var activePage = 9999;
		var timer;
		var imgAddresses = [];
		var enableChange = true;

		/* The script will not run if no li objects exist in the ul with class fade
		----------------------------------------------------------------------------------------------------*/
		if ($('ul.fade li').length) {

			/* Adds scripts for sliding function if slideFunction is set to slidePara
			----------------------------------------------------------------------------------------------------*/
			if(opts.slideFunction == "slidePara"){
				var script = document.createElement('script');
				script.src = 'http://gsgd.co.uk/sandbox/jquery/easing/jquery.easing.1.3.js';
				script.type = 'text/javascript';
				document.getElementsByTagName('head')[0].appendChild(script);
				var script = document.createElement('script');
				script.src = 'http://gsgd.co.uk/sandbox/jquery/easing/jquery.easing.compatibility.js';
				script.type = 'text/javascript';
				document.getElementsByTagName('head')[0].appendChild(script);	
			}
			
			/* Puts the caption to the right of the image
			----------------------------------------------------------------------------------------------------
			Doesn't work in IE
			if(opts.imagePlacement == "right"){
				$("ul.fade li .image").css({"left":""+opts.imageMaxWidth+"px"});
			}else{
				$("ul.fade li .caption").css({"left":""+opts.imageMaxWidth+"px"});
			}*/

			/*Set active slide if hash exist*/
			if(opts.useHash == true){
				if(location.hash){
					opts.activeSlide = parseFloat(location.hash.replace("#", ""));
				}	
			}
			/* Adds a navigation content to the document if there is none
			----------------------------------------------------------------------------------------------------*/
			if ($('ul.fade-nav').length == 0) {
				$('.fade-content').append('<ul class="fade-nav"> </ul>');
			}

			$('ul.fade li').each(function(index) {
				slides[index] = $(this).attr('id').replace("slide", "");
				$("li#slide" + slides[index]).hide();			
				if(opts.slideFunction == "slidePara"){
					/* Puts the content out of stage if slideFunction is set to slidePara
					----------------------------------------------------------------------------------------------------*/
					$("li#slide" + slides[index] + " .image").css({"left":"-600px", "opacity":"0"});
					$("li#slide" + slides[index] + " .caption").css({"left":"-280px", "opacity":"0"});				
				}else if(opts.slideFunction == "fadePara"){
					$("li#slide" + slides[index] + " .image").css({"opacity":"0"});
					$("li#slide" + slides[index] + " .caption").css({"opacity":"0"});	
				}else if(opts.slideFunction == "fade"){
					$("li#slide" + slides[index] + " *").css({"opacity":"0"});
				}
				
				/* Adds navigation li objects if it's fewer than the ul.fade li objects
				----------------------------------------------------------------------------------------------------*/
				
				if ($('ul.fade-nav li').length <= index && $('ul.fade li').length > 1) {
					var addLi = "<li class=\"cirkle\" id="+ "tab" + index + "> </li>";
					$('.fade-nav').append(addLi);
				}
			});
			
			if(opts.pageView){		
				/* This will run if no ul.page-nav object exist in the document to add a page-navigation if
				/* pageView is set to true and there is more li objects than the variable numThumbs.
				----------------------------------------------------------------------------------------------------*/
				if ($('ul.page-nav').length == 0) {
					if ($('.navigation-content').length == 0) {
						$('.fade-content').append('<ul class="page-nav"> </ul>');
					}else{
						$('.navigation-content').append('<ul class="page-nav"> </ul>');
					}
					
					for(var i=0;($('ul.fade-nav li').length/opts.numThumbs)>i;i++){
							pages = pages + 1;
							var addLi = "<li id="+ "pageTab" + i + "> </li>";
							$('.page-nav').append(addLi);
							$('.navigation-content ul.page-nav').css({"max-width":(i+1)*18});
					}
				}
			}
			/* This will resize the thumb image and keep it's aspect ratio
			----------------------------------------------------------------------------------------------------*/
			$('ul.fade-nav li.picture .image img').css({"max-width":""+opts.thumbMaxWidth+"px","max-height":""+opts.thumbMaxHeight+"px"});
			var container = $('ul.fade-nav li.picture .image img');
			/*container.width((container > opts.thumbMaxWidth)? ""+opts.thumbMaxWidth+"px" : "auto"); 
			container.height((container > opts.thumbMaxHeight)? ""+opts.thumbMaxHeight+"px" : "auto");*/
			if(opts.thumbHolderWidth == 0){
				$('ul.fade-nav li.picture').css({"width":opts.thumbMaxWidth,"text-align":"center"});
			}else{
				$('ul.fade-nav li.picture').css({"width":opts.thumbHolderWidth,"text-align":"center"});
			}
			if(opts.thumbHolderHeight == 0){
				$('ul.fade-nav li.picture .image').css({"height":opts.thumbMaxHeight});
			}else{
				$('ul.fade-nav li.picture .image').css({"height":opts.thumbHolderHeight});
			}
			
			/* This will resize the big image and keep it's aspect ratio
			----------------------------------------------------------------------------------------------------*/
			$('.fade-content ul.fade li .image img').css({"max-width":""+opts.imageMaxWidth+"px"});
			var container = $('.fade-content ul.fade li .image img');
			container.width((container > opts.imageMaxWidth)? ""+opts.imageMaxWidth+"px" : "auto");
			
			/* Eventhandler for the page and tab links
			----------------------------------------------------------------------------------------------------*/
				$('ul.fade-nav li').click(function(){
					if(enableChange != false){
						changeSlide(opts.activeSlide, opts.activeSlide = parseFloat($(this).attr("id").replace("tab", "")));
					}
				});
				$('ul.page-nav li').click(function(){
					if(enableChange != false){
						changeSlide(opts.activeSlide, opts.activeSlide = (opts.numThumbs*parseFloat($(this).attr("id").replace("pageTab", ""))));
					}
				});

			
			/* Enables the arrow keys
			----------------------------------------------------------------------------------------------------*/
			if(opts.enableKeys && $('ul.fade li').length > 1){
					$(document).keydown(function(e){
						if (e.keyCode == 39) { 
							changeSlide(opts.activeSlide, opts.activeSlide + 1);
							return false;
						}
						if (e.keyCode == 37) { 	
							changeSlide(opts.activeSlide, opts.activeSlide - 1);
							return false;
						}
						if (e.keyCode == 38) { 
							if(enableChange != false){
								changeSlide(opts.activeSlide, opts.activeSlide = (opts.numThumbs*(activePage+1)));
								return false;
							}
						}
						if (e.keyCode == 40) {
							if(enableChange != false){
								changeSlide(opts.activeSlide, opts.activeSlide = (opts.numThumbs*(activePage-1)));
								return false;
							}
						}
					});
			}
			
			/* If pauseOnHover and autoSlide is set to true this will pause the slideshow when hover the content
			----------------------------------------------------------------------------------------------------*/
			if(opts.pauseOnHover && $('ul.fade li').length > 1	){
				$('ul.fade').mouseover(function(){
					clearTimeout(timer);
				});
				$('ul.fade').mouseout(function(){
					if(opts.autoSlide){
						timer = setTimeout(function(){changeSlide(opts.activeSlide, opts.activeSlide + 1)}, opts.slideTimeout);
					}		
				});
			}
			
			/* If pageView is set to true and there is more thumbs than numThumb the event handler for the
			/* page arrows will run here
			----------------------------------------------------------------------------------------------------*/
			if(pages > 1){
					$('a.pageNav.next').click(function(){
						if(enableChange != false){
							changeSlide(opts.activeSlide, opts.activeSlide = (opts.numThumbs*(activePage+1)));
							
						}
					});
					$('a.pageNav.prev').click(function(){
						if(enableChange != false){
							changeSlide(opts.activeSlide, opts.activeSlide = (opts.numThumbs*(activePage-1)));
						}
					});
					$("a.pageNav.next").mouseover(function () {
						$('ul.fade-nav.pics').css('background-position', '0 -400px');
						$("a.pageNav.next").animate({"opacity":100},300);
					});
					$("a.pageNav.next").mouseout(function () {
						$('ul.fade-nav.pics').css('background-position', '0 0px');
						$("a.pageNav.next").animate({"opacity":0},300);
					});
					$("a.pageNav.prev").mouseover(function () {
						$('ul.fade-nav.pics').css('background-position', '0 -200px');
						$("a.pageNav.prev").animate({"opacity":100},300);
					});
					$("a.pageNav.prev").mouseout(function () {
						$('ul.fade-nav.pics').css('background-position', '0 0px');
						$("a.pageNav.prev").animate({"opacity":0},300);
					});

			}else{
				$('ul.page-nav').hide();	
			}
			if(opts.navArrows){
				$('a.slideNav.next').click(function(){
					if(enableChange != false){
							changeSlide(opts.activeSlide, opts.activeSlide + 1);
							return false;
					}
				});
				$('a.slideNav.prev').click(function(){
					if(enableChange != false){
							changeSlide(opts.activeSlide, opts.activeSlide - 1);
							return false;
					}
				});
			}
			/* This will put the alt attribute in an array of images with the class loading witch should include the source of 
			/* the image, the src attribute should be empty or include a preload image. Later on this will be used for loading 
			/* the images in correct order.
			----------------------------------------------------------------------------------------------------*/
			$('img.loading').each(function(index) {
				imgAddresses[index] = this.alt;
			});
			delayThumbs();		
		}
		window.colorboxOpen = function(){
			clearTimeout(timer);
		}
		window.colorboxClose = function(){
			if(opts.autoSlide){
				timer = setTimeout(function(){changeSlide(opts.activeSlide, opts.activeSlide + 1)}, opts.slideTimeout);
			}		
		}
		
		function delayThumbs() {
			/* Sets the activeImage witch should be the first one to be loaded and displayed first, it's also
			/* load the 4 next images after that one.
			----------------------------------------------------------------------------------------------------*/
			for(i=0;i<5;i++) {
				var source = $('ul.fade li#slide' + slides[(opts.activeSlide+i)] + ' .image img').attr('alt');
				$('ul.fade li#slide' + slides[(opts.activeSlide+i)] + ' .image img').attr('src', source);
			}
			
			/* This will forse the navigation content down when the image is loaded if autoHeight
			----------------------------------------------------------------------------------------------------*/
			if(opts.autoHeight){
				$('ul.fade li#slide' + slides[(opts.activeSlide)] + ' .image img').load(function() {
					var slideHeight = $("li#slide" + slides[opts.activeSlide] + " .image").height();
					if($("li#slide" + slides[opts.activeSlide] + " .caption").height() > slideHeight) {
						var slideHeight = $("li#slide" + slides[opts.activeSlide] + " .caption").height();
					}
					$(".fade-content ul.fade").animate({"height":slideHeight},{duration:opts.slideSpeed});
				});
			}else{
				$(".fade-content ul.fade").animate({"height":opts.contentHeight},{duration:opts.slideSpeed});
			}
			/* This will load the rest of the images with the class loading
			----------------------------------------------------------------------------------------------------*/
			pics=$('img.loading');
			for(c=0;c<pics.length;c++) {
				pics[c].src=imgAddresses[c];
				pics[c].alt="";
			}
			
			/* And at last, display the content
			----------------------------------------------------------------------------------------------------*/
			changeSlide(9999, opts.activeSlide);
		}
		function resizeImage(image){
			var aspectRatio = $("li#slide" + image + " .fullScreenImage").width() / $("li#slide" + image + " .fullScreenImage").height();
			if (($(window).width() / $(window).height()) < aspectRatio ) {
				$("li#slide" + image + " .fullScreenImage").removeClass('bgheight');
				$("li#slide" + image + " .fullScreenImage").removeClass('bgwidth');	
				$("li#slide" + image + " .fullScreenImage").addClass('bgheight');
				var marginLeft =  $("li#slide" + image + " .fullScreenImage").width() - $(window).width();
				marginLeft = "-" + marginLeft/2 + "px";
				$("li#slide" + image + " .fullScreenImage").css({"margin-left":marginLeft});
			}else{
				$("li#slide" + image + " .fullScreenImage").removeClass('bgheight');
				$("li#slide" + image + " .fullScreenImage").removeClass('bgwidth');	
				$("li#slide" + image + " .fullScreenImage").addClass('bgwidth');
				var marginTop =  $("li#slide" + image + " .fullScreenImage").height() - $(window).height();
				marginTop = "-" + marginTop/2 + "px";
				$("li#slide" + image + " .fullScreenImage").css({"margin-top":marginTop});
			}	
		}
		function centerImage(image){
		    /* This will center the image horizontal
		    ----------------------------------------------------------------------------------------------------*/
		    /*NOT FINISHED*/
		    /*var marginLeft = ($("ul.fade").width() - $("li#slide" + image).width())/2;
		    $("li#slide" + image).css({"margin-left":marginLeft+"px"});*/
		    var imageMarginLeft = ($("li#slide" + image).width() - $("li#slide" + image + " img").width())/2;
		    $("li#slide" + image + " img").css({"left":imageMarginLeft+"px", "right":imageMarginLeft+"px"});

		}
		function verticalAlign(image){
		    /* This will center the image vertical
		    ----------------------------------------------------------------------------------------------------*/
		    /*NOT FINISHED*/
		    /*var marginLeft = ($("ul.fade").width() - $("li#slide" + image).width())/2;
		    $("li#slide" + image).css({"margin-left":marginLeft+"px"});*/
		    var imageMarginTop = ($("li#slide" + image).height() - $("li#slide" + image + " img").height())/2;
		    $("li#slide" + image + " img").css({"top":imageMarginTop+"px"});

		}
		function changeSlide(prevSlide, nextSlide){
			if(prevSlide != nextSlide && enableChange == true){
				if(opts.autoSlide){
					clearTimeout(timer);
				}
				enableChange = false;
				opts.activeSlide = nextSlide;
				
				if(nextSlide >= slides.length){
					nextSlide = 0;	
					opts.activeSlide = 0;
				}
				if(nextSlide < 0){
					nextSlide = slides.length-1;	
					opts.activeSlide = slides.length-1;
				}
				if(opts.autoSlide){
					clearTimeout(timer);
					var next = opts.activeSlide + 1;
					if($('ul.fade li').length > 1){
						timer = setTimeout(function(){changeSlide(nextSlide, opts.activeSlide + 1)}, opts.slideTimeout);
					}
					if(opts.timebar == true){
						$(".timebar").remove();
						if ($('.timebar').length == 0) {
							$('body').append('<div class="timebar"> </div>');
							$(".timebar").css({"height":"3px","width":"0px","background":"#F7B939","position":"fixed","bottom":"0","left":"0","z-index":"999"});
						}
						$(".timebar").animate({"width":"100%"},opts.slideTimeout-100);
					}
				}
				$("li#slide" + slides[nextSlide]).css({"visibility":"visible"});
				if(opts.slideFunction == "fade"){
					$("li#slide" + slides[nextSlide]).show();
					$("li#slide" + slides[prevSlide] + " *").animate({"opacity":0},opts.slideSpeed);
					$("li#slide" + slides[nextSlide] + " *").animate({"opacity":1},{
						duration:opts.slideSpeed,
						complete:function	(){
							$("li#slide" + slides[prevSlide]).hide();
							enableChange = true;
							if(jQuery.browser.msie)
								$(this).get(0).style.removeAttribute('filter');

						}
					});
					if(opts.fullScreenImage){
						//Resize the image when it's loaded
						$("li#slide" + slides[nextSlide] + " .fullScreenImage").load(function() {
							resizeImage(slides[nextSlide]);
						});
						resizeImage(slides[nextSlide]);				
					}
				    
				    if(opts.centerImage){
						if ($.browser.msie){
							$('ul.fade li#slide' + slides[nextSlide] + ' img').ready(function(){
							centerImage(slides[nextSlide]);
							});
						}else{
							 $('ul.fade li#slide' + slides[nextSlide] + ' img').load(function(){
							centerImage(slides[nextSlide]);
							 });
						}    
						centerImage(slides[nextSlide]);				
				    }
					if(opts.verticalAlign){
						if ($.browser.msie){
							$('ul.fade li#slide' + slides[nextSlide] + ' img').ready(function(){
								verticalAlign(slides[nextSlide]);
							});
						}else{
							 $('ul.fade li#slide' + slides[nextSlide] + ' img').load(function(){
								verticalAlign(slides[nextSlide]);
							 });
						}    
						verticalAlign(slides[nextSlide]);				
				    }
					
				}else if(opts.slideFunction == "fadePara"){
					$("li#slide" + slides[nextSlide]).show();
					$("li#slide" + slides[prevSlide] + " .caption").animate({"opacity":0},opts.slideSpeed-400);
					$("li#slide" + slides[prevSlide] + " .image").delay(opts.slideSpeed-500).animate({"opacity":0},opts.slideSpeed);
					$("li#slide" + slides[nextSlide] + " .image").delay((opts.slideSpeed-500)).animate({"opacity":1},opts.slideSpeed);
					$("li#slide" + slides[nextSlide] + " .caption").delay(((opts.slideSpeed*2)-200)).animate({"opacity":1},{
						duration:opts.slideSpeed-400,
						complete:function	(){
							$("li#slide" + slides[prevSlide]).hide();
							enableChange = true;
							if(jQuery.browser.msie)
								$(this).get(0).style.removeAttribute('filter');
						}
					});
				}else if(opts.slideFunction == "slidePara"){
					$("li#slide" + slides[nextSlide]).show();
					$("li#slide" + slides[prevSlide] + " .image").animate({
						left: opts.imageMaxWidth + 90,
						opacity: 0,
						easing:"easeInBack"
					}, {
						duration: opts.slideSpeed,
						complete: function() {
							$("li#slide" + slides[prevSlide] + " .image").css("left",-600);
						}
					});
					$("li#slide" + slides[prevSlide] + " .caption").delay(300).animate({
						left: opts.imageMaxWidth + 90,
						opacity: 0,
						easing:"easeInBack"
					}, {
						duration: opts.slideSpeed,
						complete: function() {
							$("li#slide" + slides[prevSlide] + " .caption").css("left",-220);
						}
					});
					$("li#slide" + slides[nextSlide] + " .image").delay(500).animate({"left":0, "opacity":1},{duration:1200, easing:"easeOutBack"});
					$("li#slide" + slides[nextSlide] + " .caption").delay(700).animate({
						"left":opts.imageMaxWidth, "opacity":1},{
							duration:1200, 
							easing:"easeOutBack", complete: function(){
								enableChange = true;	
							}});
				};
				$("li#tab" + prevSlide).removeClass("active");
				$("li#tab" + nextSlide).addClass("active");
				if(opts.pageView){
					var activePageTemp = (nextSlide/opts.numThumbs) + '';
						activePageTemp = activePageTemp.slice(0,1);
						activePageTemp = parseFloat(activePageTemp);
					if(activePageTemp != activePage){
						if(activePage != 9999){
							$('ul.fade-nav li').fadeOut(500);
						}else{
							$('ul.fade-nav li').hide();
						}
						$("li#pageTab" + activePage).removeClass("active");
						$("li#pageTab" + activePageTemp).addClass("active");
						for(var index=(activePageTemp)*opts.numThumbs; index < ((activePageTemp+1)*opts.numThumbs);index++){
							$('ul.fade-nav li#tab'+index).css({"visibility":"visible"});
							$('ul.fade-nav li#tab'+index).delay(1000).fadeIn(2000);	
						}	
					
					}
					activePage = activePageTemp;
				}else{
					if(activePage == 9999){
						activePage = 1;
						$('ul.fade-nav li').hide();
						$('ul.fade-nav li').css({"visibility":"visible"});
						$('ul.fade-nav li').fadeIn(2000);
					}
				}
				$('ul.fade-nav li.empty').show();
					if(opts.autoHeight){
					var slideHeight = $("li#slide" + slides[nextSlide] + " .image").height();
					if($("li#slide" + slides[nextSlide] + " .caption").height() > slideHeight) {
						var slideHeight = $("li#slide" + slides[nextSlide] + " .caption").height();
					}
					$(".fade-content ul.fade").animate({"height":slideHeight},{duration:opts.slideSpeed});
				}
				if(opts.useHash == true){
					window.location = "#" + nextSlide;
				}
			}	
		}
	}
})(jQuery);
