/*
 * jQuery Gallery
 * Copyright (c) 2010 Dmitry (php-coder.ru) <diminapochta@gmail.com>
 */
(function($){
	var pattern = /\.(jpg|jpeg|JPG|gif|GIF|png)$/g;
	function control(position, numberOfSlides){
		if(position==0){ $('#leftControl').hide() } else{ $('#leftControl').show() }
			  if(position==numberOfSlides-1){ $('#rightControl').hide() } else{ $('#rightControl').show() }
	}
	function gallery(obj, nn){
			var html = '';
            $("a", obj).each(function(n){
				url = $(this).attr("href");
				if(url.search(pattern) != -1){
					html += '<td class="slide"><div><img src="'+url+'"></div></td>';
				}
			});
            $('<div id="gallery"><table class="box"><tr><td class="left"></td><td class="center"><div id="slideshow"><div id="slidesContainer"><table id="slideInner"><tr>'+html+'</tr></table></div></div></td><td class="right"></td></tr></table></div>').appendTo("body");
			$("#gallery").css({"width":document.body.scrollWidth, "height":document.body.scrollHeight});
			w = (window.innerWidth ? window.innerWidth : (document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.offsetWidth));
    		h = (window.innerHeight ? window.innerHeight : (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.offsetHeight));
			$("#gallery .box").css({"left":Math.ceil((w/2)-400 + document.body.scrollLeft), "top":Math.ceil((h/2)-320 + document.body.scrollTop)});
			$(".box").click(function(){
				return false;
			});
			$("#gallery").click(function(){
				$('#gallery').remove();
				return false;
			});
            var slides = $('.slide');
		  	var currentPosition = nn;
		  	var slideWidth = 700;
		  	var numberOfSlides = slides.length;
		  	if(currentPosition>0){
            	control(currentPosition, numberOfSlides);
			    $('#slideInner').css({
			      	'marginLeft' : slideWidth*(-currentPosition)
			    });
		  	}
		  	$('#slidesContainer').css('overflow', 'hidden');
		  	$('#slideInner').css('width', slideWidth * numberOfSlides);

		  	$('#gallery .left').append('<span class="control" id="leftControl"></span>');
			$('#gallery .right').append('<span class="control" id="rightControl"></span>');
			control(currentPosition, numberOfSlides);
			$('.control').bind('click', function(){
				currentPosition = ($(this).attr('id')=='rightControl') ? currentPosition+1 : currentPosition-1;
			    control(currentPosition, numberOfSlides);
			    $('#slideInner').animate({
			      	'marginLeft' : slideWidth*(-currentPosition)
			    });
			});
			return false;
		}
	$.fn.gallery = function(){
		return this.each(function(){
			var obj = $(this);
			$("a", this).each(function(n){
				var nn = n;
				url = $(this).attr("href");
				if(url.search(pattern) != -1){
					$(this).click(function(){
						return gallery(obj, nn);
					});
				}
			});
		});
	}
})(jQuery);

