
(function ($) {

    $.fn.photoSlider = function (options) {


        var opts = $.extend({}, $.fn.photoSlider.defaults, options);

		var current = 0;


		return this.each(function(){

			var $self = $(this);

			var nbPhotos = $self.find('ul li').length;

			var timer;
			var width = 0;

			init();


			function init () {

				$('#'+opts.nextButton).click (function () {
					if (timer) {
						clearInterval(timer);
					}
					next();
				});
				$('#'+opts.prevButton).click (function () {
					if (timer) {
						clearInterval(timer);
					}
					previous();
				});

                loadImages();

			}

			function loadImages () {
                $self.find('ul li img').load (function () {
                   $(this).addClass('loaded');
                   startDiapo();
                });
            }

            function startDiapo () {
                if ($self.find('ul li img.loaded').size() == nbPhotos) {
                    width = getWidth();
                    selectByN(current);
                    timer = setInterval(next, 5000);
                }
            }

			function selectByN (n) {

				var start = 0;


				$($self.find('ul li')[current]).removeClass ('selected');

				if ($self.find('ul li')[n]) {

					var tempLi = $self.find('ul li')[n];
					$(tempLi).addClass ('selected');

				} else {
					return $(this);
				}

				var prevAll = $self.find('ul li.selected').prevAll ();

				prevAll.each (function () {
					start -= $(this).width() + parseInt($(this).css ('marginRight')) + parseInt($(this).css ('marginLeft'));
				});

				var maxX =  $self.width() - width;

				start = (start <  maxX ? maxX : start);

				current = n;

                if (n == $self.find('ul li').size() - 1) {
                    start -= 20;
                }

				$self.find('ul').animate ({'left' : start}, 1000);

			}

			function next () {

				var tempN = (current + 1 >= nbPhotos ? 0 : current + 1);

				selectByN (tempN);
			}

			function previous () {

				var tempN = (current - 1 < 0 ? nbPhotos - 1 : current - 1);

				selectByN (tempN);
			}

			function getWidth () {

				width = 0;

				$self.find('ul li img').each (function () {
					width += $(this).width() + parseInt($(this).css ('marginRight')) + parseInt($(this).css ('marginLeft'));
				});

				return width;
			}

		});


	}

	$.fn.photoSlider.defaults = {

        nextButton : 'nextButton',
		prevButton : 'prevButton'

    };

})(jQuery);
