/*global window,document,jQuery */
/*!
 * rgCarousel: a jQuery Plugin
 * @author: Mike Hins (rouge marketing)
 * @url: 
 * @documentation: 
 * @published: 2011-09-02
 * @updated: 2011-09-02
 * @license Creative Commons Attribution Non-Commercial Share Alike 3.0 Licence
 *		   http://creativecommons.org/licenses/by-nc-sa/3.0/
 */
(function ($) {
    $.rgCarousel = function (el, options) {
        var base = this;
        base.$el = $(el);
        base.el = el;
        base.$el.data('rgCarousel', base);        
        base.settings = {
            scroll: 2,
            thumbHeight: 90,
            duration: 1000,
			easing:'easeInOutQuad',
			lightboxOptions : {},
			showAllPictures:false // for the lightbox to show all the galleries pictures at the same time
        };
        if (options) {
            $.extend(base.settings, options);
        }
        base.init = function () {			
            			
			// scrolling direction prev || next
            base._direction;
			
			// number of available images in the viewport
            base._numOfVisibleImages;
			
			// total number of images
            base._numOfImages;
			
			// height of the viewport
            base.$windowHeight;
			
			// wrapping each <ul> inside a container div
            base.$el = base.$el.wrap('<div class="rgCarousel-container" />');
			
			// wrapping each <ul> inside the viewport
            base.$el = base.$el.wrap('<div class="rgCarousel-viewPort"/>');
			
			// reference to the container
            base.$container = base.$el.parent().parent().closest('.rgCarousel-container');
			
			// reference to the viewport
            base.$window = base.$container.find('.rgCarousel-viewPort');
			
			// add previous button
            base.$container.append('<a href="" class="rgCarousel-prev-btn" />');
			
			// add next button
            base.$container.append('<a href="" class="rgCarousel-next-btn" />');
			
			// reference to the previous button
            base.$prevBtn = base.$container.find('.rgCarousel-prev-btn');
			
			// reference to the next button
            base.$nextBtn = base.$container.find('.rgCarousel-next-btn');
			
			// index of the first visible image
            base.currIndex = 0;
			
			// object to hold some datas
            base._ulObj = {
                width: 0,
                itemPosition: [],
                itemWidth: []
            };
			
			// we hide the previous button at the beginning
            base.$prevBtn.hide();
			
			// get the sizes 
            base.getULInfos();
			
			// reference to the viewport width
            base.$windowWidth = base.$window.outerWidth(true);
			
			// we adjust the height of the window according to the height of the <li> items
            base.$window.css({
                height: base.$windowHeight
            });
						
			// if the window width => <div class="rgCarousel-viewPort"> width is smaller than the <ul> width
			// if there is enough images to scroll
			if(base.$windowWidth < base._ulObj.width)
			{				
				// when the prev button is cliked
	            base.$prevBtn.click(
    	        function (e) {
        	        e.preventDefault();
				
					// set the current scrolling direction
                	base._direction = "prev";
				
					// animate the gallery
             	   base.move();
        	    });
			
				// when the prev button is cliked
        	    base.$nextBtn.click(
	
				function (e) {
					e.preventDefault();
	
					// set the current scrolling direction				
					base._direction = "next";
					
					// animate the gallery
					base.move();
				});
			
				// adjust the prev button y position
				base.$prevBtn.css({
					top: (base.$container.outerHeight(true) - base.$prevBtn.outerHeight(true)) / 2
				})
				
				// adjust the next button y position			
				base.$nextBtn.css({
					top: (base.$container.outerHeight(true) - base.$nextBtn.outerHeight(true)) / 2
				})
			}else{
				base.$prevBtn.hide();
				base.$nextBtn.hide();
			}
			// feature / bug ... show lightbox of all the pictures of all galleries or just the current gallery
			base._lb = !base.settings.showAllPictures ? base.$container.find('.rgLightBox') : $('.rgLightBox');
			
			// default custom lightbox settings
			var lbPath 		= base.settings.lightboxOptions.path ? base.settings.lightboxOptions.path : '';
			var lbBGOver	= base.settings.lightboxOptions.overlayBgColor ? base.settings.lightboxOptions.overlayBgColor : '#000';
			var lbBGOpa		= base.settings.lightboxOptions.overlayOpacity ? base.settings.lightboxOptions.overlayOpacity : 0.7;
			var lbSpeed		= base.settings.lightboxOptions.containerResizeSpeed ? base.settings.lightboxOptions.containerResizeSpeed : 500;
			var lbText		= base.settings.lightboxOptions.txtImage ? base.settings.lightboxOptions.txtImage : 'Image';
			var lbTxtOf		= base.settings.lightboxOptions.txtOf ? base.settings.lightboxOptions.txtOf : '/';
			
			base._lb.lightBox({
				imageLoading: lbPath + 'images/lightbox-ico-loading.gif',
                imageBtnPrev: lbPath + 'images/lightbox-btn-prev.gif',
                imageBtnNext: lbPath + 'images/lightbox-btn-next.gif',
                imageBtnClose: lbPath + 'images/lightbox-btn-close.gif',
                imageBlank: lbPath + 'images/lightbox-blank.gif',
				overlayBgColor: lbBGOver,
				overlayOpacity: lbBGOpa,
				containerResizeSpeed: lbSpeed,
				txtImage: lbText,
				txtOf: lbTxtOf
            });
        }
		
        base.move = function () {
			// width of the visible images
			var viewportImagesWidth = 0;
				
			// incrementator
			var n = 0;
			for (var x = 0; x < base._numOfImages; x++) {
				n++;
			
				// we add the width of each image
				viewportImagesWidth += base._ulObj.itemWidth[base.currIndex + x];
			
				// till it exceed the viewport width
				if (viewportImagesWidth >= base.$windowWidth) {
					base._numOfVisibleImages = n;
					break;
				}
            }
			// if the gallery is not moving
            if (!base.$el.is(':animated')) {
				
				// if the next button has been click
                if (base._direction == 'next' ){ 
					
					// we adjust the index of the first picture
                    base.currIndex += base.settings.scroll;
					
					// we show the previous button if it's not already visible
                    base.$prevBtn.not(':visible').show();
					
					// if the position of the <ul> is less or equal to the viewport width					
                    if (base.$el.position().left <= -(base._ulObj.width - base.$windowWidth - (base._ulObj.itemWidth[base._numOfImages-1] * 2))){
						
						// we hide the next button
                        base.$nextBtn.fadeOut();
						
						// we move the gallery to the end
                        base.$el.animate({'left': -(base.$el.outerWidth(true) - base.$windowWidth) }, { duration : base.settings.duration, easing:base.settings.easing});
						
                        return;
						
                    } else {
						
						// we show the next button if it's not already visible
                        base.$nextBtn.not(':visible').show();
						
						// we move the gallery to it next position
						base.$el.animate({'left': -base._ulObj.itemPosition[base.currIndex]}, { duration : base.settings.duration, easing:base.settings.easing});
                    }
                }
				
				// if the prev button has been click
                if (base._direction == 'prev') {
					
                    // we show the next button if it's not already visible
                    base.$nextBtn.not(':visible').show();
					
					// we adjust the index of the first picture
                    base.currIndex -= base.settings.scroll;
					
					// if the first picture in the window ( viewport ) is the first image of the gallery
                    if (base.currIndex <= 0) {
						
						// hide the prev button
                        base.$prevBtn.fadeOut();
						
						// set the index of the first image to 0
                        base.currIndex = 0;
                    }
					
					// we move the gallery to it previous position
                    base.$el.animate({'left': -base._ulObj.itemPosition[base.currIndex]}, { duration : base.settings.duration, easing:base.settings.easing});
                }
            }
        }
		
		// adjust the size of the window
        base.getULInfos = function () {
			
			// we set the first image position to 0
            base._ulObj.itemPosition[0] = 0;
			
			// go throught each <li>
            base.$el.find('li').each(function (i, el) {
				
				// reference to the current image
                var img = $(el).find('img');
				
				// we resize the image
                img.css({
                    'height': base.settings.thumbHeight,
                    'width': 'auto'
                });
				
				// Etienne todo
                var lImageSrc = img.attr('src');
                lImageSrc = lImageSrc.replace(/\h=75/g, "h=400");
                var a = '<a class="rgLightBox" href="' + lImageSrc + '" />';
				// we need a anchor tag around the image for the lightbox
                
				//var a = '<a class="rgLightBox" href="' + img.attr('src') + '" />';
				
				// wrap it
                img.wrap(a);
				
				// get the margin and padding of the <li>
                var paddMarg = $(el).outerWidth(true) - $(el).width();
				
				// reference to the window height
                base.$windowHeight = $(el).outerHeight(true);
				
				// get the new image total width
                var elW = paddMarg + img.outerWidth(true);
				
				// we find the width of the window ( viewport )
                base._ulObj.width += elW;
				
				// we retrieve the position of each image
                base._ulObj.itemPosition[i + 1] = base._ulObj.width;
				
				// we stock the width of each image into an array
                base._ulObj.itemWidth[i] = elW;
            })
						
			// house keeping we do not need the last element of that array
			base._ulObj.itemPosition.pop();
			
			// set the total number of images
            base._numOfImages = base.$el.find('li').size();
			
			// set the <ul> width
            base.$el.width(base._ulObj.width + 1);
        };
		
		base.$el.show();
    }
    $.fn.rgCarousel = function (method) {
        var args = Array.prototype.slice.call(arguments, 1);		
        return this.each(function () {
            var obj = $(this).data('rgCarousel');
            if (!obj && typeof (method) === 'string') {
                obj = (new $.rgCarousel(this));
                obj.init();
            }
            if (obj && obj[method] && method !== 'init') {
                obj[method].apply(this, args);
            } else if (typeof (method) === 'object' || !method) {
                if (!obj) {
                    obj = (new $.rgCarousel(this, method));
                    obj.init();
                }
            } else {
                $.error('Plugin method not found: ' + method);
            }
        });
    };
})(jQuery);
