/**
 * jGallery
 * (C) 2011 Sawanna Team (http://sawanna.org)
 */

$.fn.jgallery=function()
{
	jGallery={
		images: null,
		step: null,
		init: function(elem) {
			this.images=new Array();
			$(elem).find('li').each(function(i,v){
				jGallery.images[i]=$(this).html();
			});

			this.draw(elem);
		},
		draw: function(elem) {
			var imgs='';
			
			for (var i in this.images) {
				imgs+='<div class="jgallery-item">'+this.images[i]+'</div>';
			}

			$(elem).replaceWith('<div id="jgallery-zoom-container"><div id="jgallery-left-btn" class="jgallery-btn"></div><div id="jgallery-right-btn" class="jgallery-btn"></div><div id="jgallery-title"></div><img class="jgallery-zoomer" /></div><div id="jgallery"><div id="jgallery-container">'+imgs+'</div></div>');
		
			$('.jgallery-btn').css({opacity:.5});
			$('.jgallery-btn').hover(
				function() { $(this).css({opacity:1}); },
				function() { $(this).css({opacity:.5}); }
			);

			
			$('#jgallery-left-btn').click(this.move_left);
			$('#jgallery-right-btn').click(this.move_right);
			
			this.step=$('#jgallery').find('img:first').width();

			this.bind();
		},
		zoom: function(image) {
			$('.jgallery-zoomer').removeClass('jgallery-show').addClass('jgallery-hide');
			$('#jgallery-zoom-container').append('<img class="jgallery-zoomer jgallery-show" />');
			
			$('.jgallery-show').get(0).src=$(image).get(0).src;
			$('.jgallery-show').css({opacity:0});
			
			$('#jgallery-title').html($(image).attr('alt')).css({
															'display': 'block'	
															});

			$('.jgallery-show').stop(true,true).animate({opacity:1},1500);
			$('.jgallery-hide').animate({opacity:.5},1500,function(){
												$('.jgallery-hide').remove();
											});
			
		},
		move_left: function() {
			$('#jgallery-container').animate({'left':-(jGallery.step)},400,function(){
																			var f=$('#jgallery-container').find('.jgallery-item:first');
																			$(f).clone().appendTo('#jgallery-container');
																			$(f).remove();
																			$('#jgallery-container').css('left',0);
																			jGallery.bind();
																			});
		},
		move_right: function() {
			var f=$('#jgallery-container').find('.jgallery-item:last');
			$(f).clone().prependTo('#jgallery-container');
			$('#jgallery-container').css('left',-(jGallery.step));
			$(f).remove();
			$('#jgallery-container').animate({'left':0},400);
			jGallery.bind();
		},
		bind: function() {
			$('#jgallery-container').find('img').unbind('click');
			$('#jgallery-container').find('img').click(function(){
				jGallery.zoom($(this));
			});
			
			$('.jgallery-item').css({opacity:.5});
			$('.jgallery-item').unbind('hover');
			$('.jgallery-item').hover(
				function() { $(this).css({opacity:1}); },
				function() { $(this).css({opacity:.5}); }
			);
			
			jGallery.zoom($('#jgallery-container').find('img:first'));
		}
	}
	
	jGallery.init($(this));
}

