/* ------------------------------------------------------------------------
	Class: prettyGallery
	Use: Gallery plugin for jQuery
	Author: Stephane Caron (http://www.no-margin-for-errors.com)
	Version: 1.1
------------------------------------------------------------------------- */

jQuery.fn.prettyGallery = function(settings) {
	settings = jQuery.extend({
		itemsPerPage : 2,
		animationSpeed : 'normal', /* fast/normal/slow */
		navigation : 'top',  /* top/bottom/both */
		of_label: ' of ', /* The content in the page "1 of 2" */
		previous_title_label: 'Previous page', /* The title of the previous link */
		next_title_label: 'Next page', /* The title of the next link */
		previous_label: 'Previous', /* The content of the previous link */
		next_label: 'Next', /* The content of the next link */
		season_name_gal: '',
		loop: false,
		loaded_callback: function(){}
	}, settings);
	return this.each(function(){
		// Global variables needed in multiple functions.	
		var currentIndex = 0;
		var itemHeight = 0;
		var galleryWidth = 0;
		var pageCount = 0;
		var animated = false;
		var $gallery = $(this);
		var ulWidth = 447;
		var $lisCopy = $(this).find('li').clone();
		var itemMargin = 5;
                var currentVisibleImg = {};
		$.fn.reverse = [].reverse; 
		var prettyGalleryPrevious = function(caller) {
                        //console.log('prettyGalleryPrevious');
			if(animated) return; // Make sure not to double animate
			$current = $gallery.find('li:eq('+(currentIndex)+')'); // find current
			$prev = $gallery.find('li:eq('+(currentIndex-1)+')'); // find next
			if ($gallery.find('li:eq('+(currentIndex-3)+')').length < 1) { // si ya pas de prochaine apres la prochaine :
				appendPrevImages(); // ajouter d'autres images 
			};
			if ($current.length!=0 && $prev.length!=0) {
				animated = true;
				moitieCurrent = $current.width()/2 ;
				moitiePrev = $prev.width()/2 ;
				$gallery.find('li').each(function(i){ // for each LI :
					left = parseFloat($(this).css('left')); // get the "left"
					$(this).animate({
						'left': (left+3+(moitiePrev+moitieCurrent))+'px' // animate to the new "left"
					}, function(){
						animated = false;
					});
				});
                                _resizeSideBtns($prev.width());
				_decrementIndex(); // decrement current index
			}	else {
				return false;
			}
		};

		var appendPrevImages = function() {
                        //console.log('appendPrevImages');
			// prendre la width et le "left" du dernier element de la liste :
			$firstLi = $gallery.find('li:first');
			firstWidth = $firstLi.width();
			firstLeft = parseFloat($firstLi.css('left'));
			totalWidthLis = firstLeft;
			// looper dans tous les LI et leur donner un "left" :
			$lisCopy = $lisCopy.clone().reverse();
			$lisCopy.prependTo($gallery); // append les LI au $gallery 
			$("ul.gallery li a").unbind('click');
			$lisCopy.reverse().each(function(i){
				totalWidthLis -= $(this).width() + 3;
				$(this).css({
					'position':'absolute',
					'top':0,
					'left': totalWidthLis // 
				});
				// $('a', $(this)).prettyPhoto(prettyPhotoArgs);
				_incrementIndex();
			});
			// $("ul.gallery li a").prettyPhoto(prettyPhotoArgs);
			settings.loaded_callback();			
		}
		
		var prettyGalleryNext = function(caller) {
                        //console.log('prettyGalleryNext');
			if(animated) return; // Make sure not to double animate
			$current = $gallery.find('li:eq('+(currentIndex)+')'); // find current
			$next = $gallery.find('li:eq('+(currentIndex+1)+')'); // find next
			if ($gallery.find('li:eq('+(currentIndex+3)+')').length < 1) { // si ya pas de prochaine apres la prochaine :
				appendNextImages(); // ajouter d'autres images 
			};
			animated = true;
                        moitieCurrent = $current.width()/2 ;
			moitieNext    = $next.width()/2 ;
			$gallery.find('li').each(function(i){ // for each LI :
				left = parseFloat($(this).css('left')); // get the "left"
				$(this).animate({ 
					'left': (left-3-(moitieNext+moitieCurrent))+'px' // animate to the new "left"
				}, function(){
					animated = false;
				});
			});
                        _resizeSideBtns($next.width());
			_incrementIndex(); // increment current index			
		};
		
                var _resizeSideBtns = function(middleImageWidth) {
                    var newWidth = (ulWidth - middleImageWidth) / 2 ;
                    $gallery.siblings('.gallery_nav_overlay').find('a.galoverlay_prev').css('width',newWidth);
                    $gallery.siblings('.gallery_nav_overlay').find('a.galoverlay_next').css('width',newWidth);
                }

		var appendNextImages = function() {
                        //console.log('appendNextImages');
			// prendre la width et le "left" du dernier element de la liste :
			$lastLi = $gallery.find('li:last');
			lastWidth = $lastLi.width();
			lastLeft = parseFloat($lastLi.css('left'));
			totalWidthLis = lastLeft + lastWidth + 3;
			// looper dans tous les LI et leur donner un "left" :
			$lisCopy = $lisCopy.clone();
			$lisCopy.appendTo($gallery); // append les LI au $gallery 
			$("ul.gallery li a").unbind('click');
			$lisCopy.each(function(i){
				$(this).css({
					'position':'absolute',
					'top':0,
					'left': totalWidthLis // 
				});
				totalWidthLis += $(this).width() + 3;
			});

			settings.loaded_callback();			
		}

		var _formatGallery = function() {
                        //console.log('_formatGallery');
			var marTop = parseFloat($gallery.find('li:first').css('margin-top'));
			var marBtm = parseFloat($gallery.find('li:first').css('margin-bottom'));
			var padTop = parseFloat($gallery.find('li:first').css('padding-top'));
			var padBtm = parseFloat($gallery.find('li:first').css('padding-bottom'));
			itemHeight = $gallery.find('li:first').height() + marTop + marBtm + padTop + padBtm;
			// set l'emplacement de la gallerie :
			$gallery.css({
				'width': galleryWidth,
				'height': itemHeight,
				'overflow': 'hidden',
				'position': 'relative',
				'clear': 'left'
			});	
			var $lisCopy = $gallery.find('li').clone(); // copy the list items 
			$lisCopy.prependTo($gallery); // add them to the beginning of the list
			var $lis = $gallery.find('li'); 
			var widthcount = (ulWidth / 2) - ($($lis[0]).find('img').width() / 2); // initialize widthcount
			var lisNumber = $('li', $gallery).length; // get the number of LIs
			var halfLiWidth = 0;
			$('li', $gallery).each(function(i){ // loop in the first half of items 
			    if (i <= (Math.floor(lisNumber)/2)) {
			        halfLiWidth += $('li:eq('+i+')', $gallery).width(); // add their widths to halfLiWidth variable
			        halfLiWidth += 4; // ... plus the 4px between each
			    }
			});
			currentIndex = (Math.floor(lisNumber)/2) +1; // put the currentIndex at the half of LIs
			/*
				*****ATTENTION, important **************************************************
				IF we have only one image in our gallery, we need to set currentIndex to the appropriate value,
				which is 1 (instead of 2).
				****************************************************************************
			*/
			if (currentIndex==2) { // if we have only one image, the currentIndex will be 2 at this point.
				currentIndex=1; // Set it to 1, otherwise it will NOT work.
			};
			// /important
			
			widthcount-= halfLiWidth; // remove to widthcount the width of the halfLiWidth
			// place the images :
			$gallery.find('li').each(function(i){
				$insideimage = $('img', $(this));
				widthcount += $insideimage.width() + itemMargin;
				$(this).css({
					'position':'absolute',
					'top':0,
					'left': widthcount - $($lis[i]).find('img').width()
				});
			});
			$current = $gallery.find('li:eq('+(currentIndex)+')'); // find current
			var distanceToAdjust = (ulWidth/2) - (($current.width()/2) + parseFloat($current.css('left')));
			$gallery.find('li').each(function(i){
				var left = $(this).css('left');
				$(this).css('left', (parseFloat(left) + distanceToAdjust));
			});
			if ($gallery.find('li:eq('+(currentIndex+2)+')').length < 1) { // if there is no next after the next :
				appendNextImages(); // add more images
			};
			$gallery.wrap('<div class="prettyGallery"></div>').addClass('prettyGallery');

			settings.loaded_callback();			
		};
		
		var _incrementIndex = function() {
			currentIndex++;
			_setCurrentIndexData();
		}
		
		var _decrementIndex = function() {
			currentIndex--;
			_setCurrentIndexData();
		}
		
		var _setCurrentIndexData = function() {
			$gallery.data('currentindex', currentIndex);
		}

		var _displayPaging = function() {
                        //if (window.console) console.log('_displayPaging');
			$cg = $gallery.parents('div.prettyGallery:first'); // The containing gallery

			$cg.find('ul.prettyNavigation span.current').text(currentIndex);
			$cg.find('ul.prettyNavigation span.total').text(pageCount);

			// Make sure all the links are enabled
			$cg.find('ul.prettyNavigation li a').removeClass('disabled');

			// Display the proper nav
			if(currentIndex == 1){
				// Hide the previous button
				$cg.find('ul.prettyNavigation li.prev a').addClass('disabled');
			} else if(currentIndex == pageCount) {
				// Hide the next button
				$cg.find('ul.prettyNavigation li.next a').addClass('disabled');
			};
			_setCurrentIndexData();
		};

		var _applyNav = function() {
                        //if (window.console) console.log('_applyNav');
			var template = '';
                        template +='<div class="gallery_nav_overlay"><a href="#" class="galoverlay_prev">Prev</a><a href="#" class="galoverlay_next">Next</a></div>';
			template +='<ul class="prettyNavigation">';
			template += '<div class="divNavigation"><li class="prev"><a class="season_'+settings.season_name_gal+'" href="#" title="'+settings.previous_title_label+'">'+settings.previous_label+'</a></li><li class="next"><a class="season_'+settings.season_name_gal+'" href="#" title="'+settings.next_title_label+'">'+settings.next_label+'</a></li></div>';
			template += '</ul>';

			switch(settings.navigation){
				case 'top':
					$gallery.before(template);
					break;
				case 'bottom':
					$gallery.after(template);
					break;
				case 'both':
					$gallery.before(template);
					$gallery.after(template);
					break;
			};
			
			// Adjust the nav to the gallery width
                        $overlayNav = $gallery.parent('div.prettyGallery:first').find('div.gallery_nav_overlay');
			$theNav = $gallery.parent('div.prettyGallery:first').find('ul.prettyNavigation');
			galleryBorderWidth = parseFloat($theNav.css('border-left-width')) + parseFloat($theNav.css('border-right-width'));
			$theNav.width(galleryWidth - galleryBorderWidth);
			$theNav.each(function(){
				$(this).find('li:eq(1)').width(galleryWidth - galleryBorderWidth - parseFloat($(this).parent().find('ul.prettyNavigation li:first').width()) - parseFloat($(this).parent().find('ul.prettyNavigation li:last').width()));
			});
                        
			// Apply the functions to the buttons
			$theNav.find('li.prev a').bind('click',function(){
				prettyGalleryPrevious(this);
				return false;
			});

			$theNav.find('li.next a').bind('click',function(){
				prettyGalleryNext(this);
				return false;
			});

                        $overlayNav.find('a.galoverlay_prev').bind('click', function(){
                            $theNav.find('li.prev a').triggerHandler('click');
                            return false;
                        });
                        $overlayNav.find('a.galoverlay_next').bind('click', function(){
                            $theNav.find('li.next a').triggerHandler('click');
                            return false;
                        });
		};
		
		// ALWAYS instanciate the gallery. Even if there is just one item
                // Set the number of pages
                pageCount = Math.ceil($(this).find('li').size() / settings.itemsPerPage);
                // Format the gallery properly
                _formatGallery(); 
                // Build and display the nav
                _applyNav();
        
                // Display the proper paging
                _displayPaging(this);
 
		// if we only have one element, just hide the buttons :
		if($(this).find('li').size() == settings.itemsPerPage) { 
			$('li.prev a').hide();
			$('li.next a').hide();
		}
	});
};

