/*!
 * Fancy Gallery v1.4
 *
 * Copyright 2011, Rafael Dery
 *
 * Only for sale at the envato marketplaces
 */
 
;(function($) {
	
	jQuery.fn.fancygallery = function(arg){
			
		//saving options
		var options = $.extend({}, $.fn.fancygallery.defaults, arg);
		
		//global variables
		var albums, album, currentAlbumIndex = -1, currentImageIndex = 0, currentShownImages, $elem;
		
		function init(element) {
			
			$elem = $(element);
			
			albums = $elem.children('div').hide();
			
			if(!options.slideTitle && !options.showTitle) {
				options.titleHeight = 0;
			}
				
			//create previous/next buttons
			if(options.imagesPerPage != 0 ) {
				$elem.append("<a class='fg-prev' href='' title='Previous image stack'></a>").find('.fg-prev').click(function(evt){
					$elem.find('.fg-next').css({'visibility':'visible'});
					loadImages('prev');
					return false;	
				}).hover(
				  function() {
					  $(this).toggleClass('fg-prev-over');
				  },
				  function() {
					  $(this).toggleClass('fg-prev-over');
				  }
				);
				
				$elem.append("<a class='fg-next' href='' title='Next image stack'></a>").find('.fg-next').click(function(evt){
					$elem.find('.fg-prev').css({'visibility':'visible'});
					loadImages('next');
					return false;	
				}).hover(
				  function() {
					  $(this).toggleClass('fg-next-over');
				  },
				  function() {
					  $(this).toggleClass('fg-next-over');
				  }
				);
			}
			
			//create album selecter
			$elem.append("<select class='fg-albumSelecter'></select>");
			$.each($elem.children('div'), function(i, albumItem){
				var selected = albumItem.title == options.selectAlbum ? "selected='selected'" : "";
				$elem.find(".fg-albumSelecter").append("<option value='"+albumItem.title+"' "+selected+">"+albumItem.title+"</option>");
			});
			
			//change handler for album selecter
			$elem.find(".fg-albumSelecter").change(function() {
				//check if new prop method is available(1.6.1)
				if($.isFunction($.prop)) {
					loadAlbum($(this).prop("selectedIndex"));
				}
				else {
					loadAlbum($(this).attr("selectedIndex"));	
				}
				
			});
			
			//hide dropdown when requested
			if(!options.dropdown || albums.length <= 1) {			
				$elem.find(".fg-albumSelecter").hide();
			}
			else {
				$elem.find(".fg-albumSelecter").uniform();
			    $elem.find('.selector').css({'float': 'right', 'margin-bottom': 5});
			}
						
			//add horizontal line under menu
			if(options.divider) {
				$elem.append("<hr class='fg-line' />");
			}
						
			//create holder for the images
			$elem.append("<ul class='fg-thumbHolder clearfix'></ul>");
			
			//first check if gallery has albums
			if(albums.length > 0) {		
				//trigger change event for album selecter
				$elem.find(".fg-albumSelecter").change();
			}
		};
		
		function loadAlbum(index){

			//save current album index
			currentAlbumIndex = index;		
			currentImageIndex = 0;
			
			album = $(albums[currentAlbumIndex]).children('a');
			//console.log(albums[currentAlbumIndex]);
			if(album.length == 0) {
				$elem.find('.fg-thumbHolder').empty().append("<p>This album has no media files!</p>");
				return false;
			}
			
			loadImages('next');
		};
		
		function loadImages(direction){
			//decrease image index when previous button was clicked
			if(direction == 'prev') {
				currentImageIndex -= (options.imagesPerPage + currentShownImages);
			}
			
			//clear the thumb holder
			$elem.find('.fg-thumbHolder').empty();

			var ipp = options.imagesPerPage == 0 ? album.length : options.imagesPerPage
			for(var i=0; i< ipp; ++i){
				var item = album.get(currentImageIndex);
				var image = item.href;
				var thumbnail = $(item).children('img:first').attr('src');
				var title = $(item).children('img:first').attr('title') ? $(item).children('img:first').attr('title') : '';
				var description = $(item).has('span').length ? $(item).children('span:first').html() : '';
				
				//create new thumbnail
				$elem.find('.fg-thumbHolder').append('<li class="fg-listItem" style="width:'+(options.thumbWidth+options.borderThickness*2)+'px; height:'+(options.thumbHeight+options.titleHeight+options.borderThickness*2)+'px; margin: '+options.rowOffset+'px '+options.columnOffset+'px; "><a href="'+item.href+'" title="'+description+'" rel="prettyPhoto['+$elem.attr("id")+']" class="fg-image"><img class="fg-thumb" src="'+thumbnail+'" alt="'+title+'" /></a><span class="fg-title"></span><img src="'+options.shadowImage+'" class="fg-shadow" width='+(options.thumbWidth+options.borderThickness*2)+' /></li>');
				
				var lastListItem = $elem.find('.fg-listItem:last');
				
				if(options.shadowImage == '') {
						lastListItem.children('.fg-shadow').css( 'display', 'none' );
				}

			    if(options.showTitle && title.length) {
					lastListItem.children('.fg-title').text(title).css( 'height', options.titleHeight );
					lastListItem.children('.fg-shadow').css('top', options.thumbHeight + options.titleHeight + options.shadowOffset + options.borderThickness*2);		
				}
				else {
					lastListItem.children('.fg-shadow').css('top', options.thumbHeight + options.shadowOffset + options.borderThickness*2);
				}
									
				//fade in thumb container and add a mouse hover
				lastListItem.hide().fadeIn(500+(i * 200)).hover(
					//mouse over function
					function(){
						var $this = $(this);
						var title = $this.find('.fg-thumb').stop().fadeTo(400, 1).attr('alt');
						if(title == ""|| !options.slideTitle || $this.find('.fg-title').height() > 0) {
							return false;
						}

						if(options.shadowImage != '') {
							$this.find('.fg-shadow').stop().animate({'top': options.thumbHeight + options.titleHeight + options.shadowOffset + options.borderThickness*2}, 200);
						}
						
						var titleSpan = $this.find('.fg-title').empty();				
						$this.find('.fg-title').stop().animate({'height': options.titleHeight}, 200, function(){
							if($.browser.msie && $.browser.version <= 8.0) {
								$this.find('.fg-title').text(title);
							}
							else {
								//fade in each letter of the title
								var spanArray = [];
								for(var i = 0; i < title.length; ++i) {
									titleSpan.append("<span>"+title.charAt(i)+"</span>");
									spanArray.push(titleSpan.find('span:last').hide());
								}
								
								//fade direction
								if(options.textFadeDirection === 'reverse') {
									spanArray.reverse();
								}
								else if(options.textFadeDirection === 'random') {
									spanArray.shuffle();
								}
								for(i in spanArray) {
									$(spanArray[i]).stop().fadeIn(50 * i);
								}
							}			
						});
					},					
					//mouse out function
					function(){
						var $this = $(this);
						var title = $this.find('.fg-thumb').stop().fadeTo(200, options.thumbOpacity).attr('alt');
						if(title == "" || !options.slideTitle) {
							return false;
						}
						$this.find('.fg-title').empty().stop().animate({'height': 0}, 200);	
						if(options.shadowImage != '') {
						    $this.find('.fg-shadow').stop().animate({'top': options.thumbHeight + options.shadowOffset + options.borderThickness*2}, 200);
						}
					}
				);
				
				//scale thumbnail
				var lastImg = $elem.find('.fg-listItem:last .fg-thumb');
				$(lastImg).load(function() {
				  var loadedImg = $(this);
				  if(options.scaleMode == 'prop') {
					  var ratio = options.thumbHeight / options.thumbWidth;
					  if (loadedImg.height() / loadedImg.width() > ratio){
						if (loadedImg.height() > options.thumbHeight){
						  loadedImg.attr('width', Math.round(loadedImg.width()*(options.thumbHeight / loadedImg.height())) );
						  loadedImg.attr('height', options.thumbHeight);
						}
					  } else {
						if (loadedImg.width() > options.thumbHeight){
						  loadedImg.attr('height', Math.round(loadedImg.height()*(options.thumbWidth / loadedImg.width())) );
						  loadedImg.attr('width', options.thumbWidth);
						}
					  }
				  }
				  else if(options.scaleMode == 'stretch') {
					  loadedImg.attr('width', options.thumbWidth);
					  loadedImg.attr('height', options.thumbHeight);	
				  }
				  else {
					  loadedImg.attr('width', options.thumbWidth);
					  loadedImg.wrap("<div style='height:"+options.thumbHeight+"px; overflow:hidden; display:block;'></div>");
				  }
				  
				});
				
				//hide buttons if necessary
				if(currentImageIndex == album.length-1) {
					$elem.find('.fg-next').css({'visibility':'hidden'});
				}
				else {
					$elem.find('.fg-next').css({'visibility':'visible'});
				}
				if(currentImageIndex == 0) {
					$elem.find('.fg-prev').css({'visibility':'hidden'});
				}
				
				//leave loop if image does not exist	
				++currentImageIndex;
				if(currentImageIndex == album.length) {
					break;
				}
			}
			
			//set prettyphoto
			$("a[rel^='prettyPhoto']").prettyPhoto(options.boxOptions);
							
			//set background
			$elem.find('.fg-image').css({
				'background-color': options.backgroundColor,
				'border': options.borderThickness+'px solid '+options.backgroundColor,
				width: options.thumbWidth,
				height: options.thumbHeight
			});
			
			//set thumbnail opacity
			$elem.find('.fg-thumb').fadeTo(0, options.thumbOpacity);
			
			//set background
			$elem.find('.fg-title').css({
				width: options.thumbWidth,
				'background-color': options.backgroundColor,
				'color': options.titleColor,
				'padding': '0px '+options.borderThickness+'px ',
				top: options.thumbHeight+options.borderThickness*2
			});
			
			
			
			//save the numbers of the current shown images
			currentShownImages = currentImageIndex % options.imagesPerPage == 0 ? options.imagesPerPage : currentImageIndex % options.imagesPerPage;
		};
		
		return this.each(function() {init(this)});
	};
	
	//array shuffle
	function arrayShuffle(){
	  var tmp, rand;
	  for(var i =0; i < this.length; i++){
		rand = Math.floor(Math.random() * this.length);
		tmp = this[i]; 
		this[i] = this[rand]; 
		this[rand] = tmp;
	  }
	};
	Array.prototype.shuffle = arrayShuffle;
	
	$.fn.fancygallery.defaults = {
		thumbWidth: 140, //width of the thumbnail
		thumbHeight: 79, //height of the thumbnail
		backgroundColor: '#F5F5F5', //the color of background for each thumbnail
		titleColor: '#383634', //the color of the title
		borderThickness: 3, //the thickness of the border
		shadowOffset: 0, //the offset of the shadow (only for the standard view)
		thumbOpacity: 0.6, //the opacity of each thumbnail in standard view
		titleHeight: 20, //height of the title
		rowOffset: 15, //the offset of the row
		columnOffset: 15, //the offset of the column
		imagesPerPage: 6, //number of thumbnails per page, if 0 all thumbnails of an album will be loaded on the first page
		textFadeDirection: 'normal', //normal, reverse, random
		scaleMode: 'stretch', //prop, stretch, crop
		shadowImage: 'images/fancygallery/shadow.png', //shaodw image url
		selectAlbum: '', //load an album by its title
		dropdown: true, //hide/show dropdown
		divider: true, //hide/show divider (between controls and thumbnails)
		showTitle: false, //show/hide title
		slideTitle: true, //enable title slide
		boxOptions: {} //options for prettyphoto(http://www.no-margin-for-errors.com/projects/prettyPhoto-jquery-lightbox-clone/)	
	};
	
})(jQuery);