'use strict';

(function($){
	
$.fn.gallery =function(options) {
	var defaults = {
		current: 0,
		classes: '',
	};
	
	var maxHeight,
		$arrowContain,
		$rightArrow,
		$leftArrow;
	function addArrow () {
		$arrowContain = $('<div>').css({
						'position': 'absolute',
						'width': '100%',
						'top': maxHeight/2,
						'font-size': '30px' 
								  })
						.appendTo('.gallery');
								  
		
		$rightArrow = $('<a>').append('<span class="glyphicon glyphicon-chevron-right">')
							  .addClass('pull-right')
							  .appendTo($arrowContain);
		
		$leftArrow = $('<a>').append('<span class="glyphicon glyphicon-chevron-left">')
							  .attr({'href': '#'})
							  .css({'left': 300+'px'})
							  .appendTo($arrowContain);
	}
	return this.each(function(){
		var $gallery = $(this),
			$galleryItems = $gallery.children();
			
		var $currentItem = $('.current', $gallery),
			next;
		options = $.extend(defaults, options)
		$gallery.addClass('gallery').addClass(options.classes);
		$galleryItems.addClass('gallery-item');
		$galleryItems.eq(options.current).addClass('current');
		$gallery.attr('tabindex', 0);
		maxHeight = $galleryItems.height();
		$gallery.height(maxHeight + 'px');
		addArrow();
		$rightArrow.on('click',function(){
			var $currentItem = $('.current', $gallery);
			next= $currentItem.index() + 1;
			if (next === $galleryItems.length) next = 0;
				$galleryItems.removeClass('current')
							 .eq(next)
							 .addClass('current');
		});
		$leftArrow.on('click',function(){
			var $currentItem = $('.current', $gallery);
			next= $currentItem.index() - 1;
			if (next < 0) next = $galleryItems.length - 1;
				$galleryItems.removeClass('current')
							 .eq(next)
							 .addClass('current');
		});
		$gallery.on('keyup', function(event){
			
			var $currentItem = $('.current', $gallery);
			// var next;
			if (event.which === 39) {
				next = $currentItem.index() + 1;
				if (next === $galleryItems.length) next = 0;
				$galleryItems.removeClass('current')
							 .eq(next)
							 .addClass('current');
			} else if (event.which === 37) {
				next = $currentItem.index() - 1;
				if (next < 0) next = $galleryItems.length - 1;
				$galleryItems.removeClass('current')
							 .eq(next)
							 .addClass('current');
			}
		});
	});
};
})(jQuery);