(function($) {
	$.fn.gallery = function(settings) {
		
		settings = jQuery.extend({
			currentImageIndex : 0,
			images : []
		}, settings);
		
		var selectedImages = this;
		
		__start(selectedImages);
		
		this.click(function() {
			var pat = /_(\d+)$/;
			settings.currentImageIndex = this.id.match(pat)[1];
			__setNewImage();
		});
		
		function __start(_sImages) {
			for(var i = 0;i<_sImages.length;i++) {
				settings.images.push(new Array(_sImages[i].src, _sImages[i].title));
			}
			__setNewImage();
			$('.gallery_main_container > .left > a').bind('click', __prevImage);
			$('.gallery_main_container > .right > a').bind('click', __nextImage);
		}
		
		function __setNewImage() {
			var _newImage = new Image();
			_image = settings.images[settings.currentImageIndex];
			_newImage.src = _image[0];
			if($('.gallery_main_container > .image > a > img').length > 0) {
				$('.gallery_main_container > .image > a > img').fadeOut(200).parent('.gallery_main_container .image a').remove();
			}
			$('.gallery_main_container > .image').append('<a><img title=" '+_image[1]+' " class ="hide" src="'+_newImage.src+'"></a>');
			$('.gallery_main_container > .image > a').lightBox();
			__setNewHref(_newImage.src);
			__setInterface(_newImage);
		}
		
		function __setNewHref (_src) {
			var pattern = /thumb\/(.*)/;
			var match = _src.match(pattern);
			$('.gallery_main_container > .image > a').attr('href', $('input.dirname').val()+'/'+match[1]);
		}
		
		function __setInterface(_image) {
			var _width = _image.width;
			var _height = _image.height;
			while(_width > 560 || _height > 220) {
				if(_width > 560 && _height <= 220) {
					var rat = 560 / _width;
					_width = 560;
					_height = Math.round(_height * rat);
				} else if((_width > 560 && _height > 220) || (_width <= 560 && _height > 220)) {
					var rat = 220 / _height;
					_height = 220;
					_width = Math.round(_width * rat);
				}
			}
			$('.gallery_main_container').css({
				width: _width+42+'px',
				'margin-left': Math.round((600-(_width+42))/2)
			}).find('.nav').css({
				'margin-top': Math.round((_height-20)/2)+'px'
			});
			$('.gallery_main_container').find('.image').css({
				width: _width+'px'
			}).find('img').attr({
				width: _width,
				height: _height
			}).fadeIn(200);
			var offset = $('img#galleryThumbnail_'+settings.currentImageIndex).position();
			$('.gallery_thumbnails').animate({scrollLeft: offset.left}, 200);
		}
		
		function __nextImage() {
			if((settings.images.length-1) > settings.currentImageIndex)
				settings.currentImageIndex = (parseInt(settings.currentImageIndex)+1);
			else
				settings.currentImageIndex = 0;
			__setNewImage();
		}
		
		function __prevImage() {
			if(settings.currentImageIndex > 0)
				settings.currentImageIndex = (parseInt(settings.currentImageIndex)-1);
			else
				settings.currentImageIndex = (parseInt(settings.images.length)-1);
			__setNewImage();
		}
	}
})(jQuery);
