(function($){
	
	var opts;
	var el;
	var bodyOverflow;
	var thumbsScrollCount; 
	var thumbsActIndex;
	
	$.fn.fiplajtbox = function(options){
		var date = new Date();
		//debug.log('==========================');
		//debug.log(' :: fiplajtbox :: STARTED ' + date.getFullYear()+'.'+date.getMonth()+'.'+date.getDate()+', '+date.getHours()+':'+date.getMinutes()+':'+date.getSeconds()+':'+date.getMilliseconds());
		
		opts = $.extend({}, $.fn.fiplajtbox.defaults, options);
		opts.windowSize = getWindowSize();
		opts.thumbsWidth = opts.thumbsSize*146;
		opts.fixedThumbsWidth = opts.JSONimgs.length*146;
		opts.showImage--;
		opts.defaultContainerHeight = 521;
		
		return this.each(function(i){
			el = this
			init();
		})
	}
	
	$.fn.fiplajtbox.defaults = {
		galleryTitle: 'fiplajtbox gallery',
		JSONimgs: false,
		thumbsSize: 7,
		maxGalleryHeight: 846,
		thumbsScrollSpeed: 500,
		showImage: 1
	}
	/*
	 * inicjalizacja galerii
	 */
	function init(){
		//debug.log(' :: fiplajtbox :: started init()');
		bodyOverflow = $('body').css('overflow');
		//alert(bodyOverflow);
		thumbsActIndex = 1;
		if( opts.JSONimgs != false ){
			$('body').css({ overflow: 'hidden' });
			
			$(el)
				.append('<div class="fiplajtbox-wrapper"></div>');
			$('.fiplajtbox-wrapper', el)
				.append('<div class="fiplajtbox-container"></div>');
			$('.fiplajtbox-container', el)
				.append('<div class="fiplajtbox-title"><h1>Galeria - '+opts.galleryTitle+'</h1><a class="fiplajtbox-close" href="#"></a></div>')
				.append('<div class="fiplajtbox-nav"><h2>zdjęcie <strong class="fiplajtbox-image-number">1</strong> z <strong class="fiplajtbox-image-count">'+opts.JSONimgs.length+'</strong></h2><div class="fiplajtbox-nav-buttons"><a class="fiplajtbox-image-prev" href="#prev"></a><a class="fiplajtbox-image-next" href="#next"></a></div></div>')
				.append('<div class="fiplajtbox-image"><img id="fiplajtbox-img" src="" alt="" title=""/></div>')
				.append('<div class="fiplajtbox-description"><p></p></div>')
				.append('<div class="fiplajtbox-thumbs"></div>');
			$('.fiplajtbox-thumbs', el)
				.append('<div class="fiplajtbox-thumbs-prev"><a class="off" href="#prev"></a></div>')
				.append('<div class="fiplajtbox-thumbs-list-wrap"><ul class="fiplajtbox-thumbs-list"></ul></div>')
				.append('<div class="fiplajtbox-thumbs-next"><a ' + (opts.JSONimgs.length<=opts.thumbsSize?'class="off" ':'') + 'href="#next"></a></div>');
			$('.fiplajtbox-thumbs-list-wrap')
				.css({
					width: opts.thumbsWidth + 'px'
				})
			$('.fiplajtbox-thumbs-list')
				.css({
					width: opts.fixedThumbsWidth + 'px'
				})
				.each(function(i){
					for(var i=0; i<opts.JSONimgs.length; i++){
						$(this).append('<li class="fiplajtbox-thumb'+(i>opts.thumbsSize-1?' fiplajtbox-thumb-hidden':i==opts.showImage?' fiplajtbox-thumb-active':'')+'" id="fiplajtbox-thumb-'+i+'" style="background-image:url('+opts.JSONimgs[i].thumburl+')"><a href="'+opts.JSONimgs[i].url+'" title="'+opts.JSONimgs[i].title+'" rel="'+opts.JSONimgs[i].description+'"></a></li>');
					}
				});
			
			thumbsScrollCount = Math.ceil(opts.fixedThumbsWidth / opts.thumbsWidth);

			selectImg( $('.fiplajtbox-thumb a').eq(opts.showImage), true );
			
			resizeImgContainer();
			$(window).resize(function(){ opts.windowSize = getWindowSize(); resizeImgContainer(); });
			
			$('.fiplajtbox-image-next').click(function(){ switchImg('next'); return false; });
			$('.fiplajtbox-image-prev').click(function(){ switchImg('prev'); return false; });			
			$('.fiplajtbox-thumb a').click(function(){ selectImg(this); return false; });			
			$('.fiplajtbox-thumbs-next a').click(function(){ scrollThumbs('next'); return false; });			
			$('.fiplajtbox-thumbs-prev a').click(function(){ scrollThumbs('prev'); return false; });			
			$('.fiplajtbox-close').click(function(){ close(); return false; });

		}
		//debug.log(' :: fiplajtbox :: ended init()');
	}
	
	/*
	 * zmiana rozmiaru boksa z obrazkiem
	 */
	function resizeImgContainer(){
		//debug.log(' :: fiplajtbox :: started resizeImgContainer()');
		var tmpHeight = 400;
		var tmpPaddingRight = 12;
		//alert( opts.windowSize.height + '\n' + $('.fiplajtbox-container').height() )
		if( opts.windowSize.height < opts.defaultContainerHeight ){//$('.fiplajtbox-container').height()+1 ){
			tmpHeight = opts.windowSize.height - $('.fiplajtbox-title').height() - $('.fiplajtbox-nav').height() - $('.fiplajtbox-description').height() - $('.fiplajtbox-thumbs').height();
			//var tpr = parseInt($('.fiplajtbox-image').css('padding-right').replace(/px/i, ''));
			tmpPaddingRight += (opts.windowSize.width-getScrollbarWidth()-$('.fiplajtbox-container').width())/2 + getScrollbarWidth();
			//alert( opts.windowSize.width + '\n' + $('body').width() + '\n' + $('.fiplajtbox-image').width() + '\n' + $('.fiplajtbox-container').width() )
		}
		var imgn = new Image();
		imgn.src = $('.fiplajtbox-thumb-active a').attr('href');//$('.fiplajtbox-image img').attr('src');
		//debug.log(' :: fiplajtbox :: resizeImgContainer : imgn.src = ' + $('.fiplajtbox-thumb-active a').attr('href') );
		//debug.log(' :: fiplajtbox :: resizeImgContainer : imgnHeight = ' + imgn.height);
		$('.fiplajtbox-image')
			.css({
				height: tmpHeight + 'px',
				paddingRight: tmpPaddingRight + 'px',
				overflowY: imgn.height > tmpHeight || imgn.height == 0 ? 'auto' : 'hidden'
			})
			.children('img')
				.css({
					marginTop: imgn.height==0 ? 0 : imgn.height < 400 ? (( $('.fiplajtbox-image').height() - imgn.height)/2 ) + 'px' : 0
				});
		var containerHeight = $('.fiplajtbox-container').height();
		$('.fiplajtbox-container').css({
			marginTop: '-'+(containerHeight/2)+'px'
		});
		//debug.log(' :: fiplajtbox :: ended resizeImgContainer()');
	}
	/*
	 * zamknięcie i "likwidacja" galerii
	 */
	function close(){
		//debug.log(' :: fiplajtbox :: started close()');
		//$('body').css({ overflow: bodyOverflow });
		$('body').css({ overflow: 'auto' });
		$('.fiplajtbox-wrapper').remove();
		//debug.log(' :: fiplajtbox :: ended close()');
		var date = new Date();
		//debug.log(' :: fiplajtbox :: ENDED ' + date.getFullYear()+'.'+date.getMonth()+'.'+date.getDate()+', '+date.getHours()+':'+date.getMinutes()+':'+date.getSeconds()+':'+date.getMilliseconds());
		//debug.log('==========================');
	}
	
	/*
	 * wybór obrazka
	 */
	function selectImg(img, startup){
		//debug.log(' :: fiplajtbox :: started selectImg(img='+img+', startup='+startup+')');
		var imgParent = $(img).parent('.fiplajtbox-thumb');
		$('.fiplajtbox-thumb').removeClass('fiplajtbox-thumb-active');
		imgParent.addClass('fiplajtbox-thumb-active');

		var imgn = new Image();
		imgn.src = $(img).attr('href');
		$('.fiplajtbox-image img').attr({
			src: $(img).attr('href'),
			title: $(img).attr('title'),
			alt: $(img).attr('title')
		})

		$('.fiplajtbox-image img').css({
			marginTop: imgn.height==0 ? 0 : imgn.height < 400 ? (( $('.fiplajtbox-image').height() - imgn.height)/2 ) + 'px' : 0
		});
		
		if( imgParent.next('.fiplajtbox-thumb').length == 0 ){
			$('.fiplajtbox-image-next').addClass('off');
		}else if( 
			$('.fiplajtbox-image-next').hasClass('off') ){ $('.fiplajtbox-image-next').removeClass('off'); 
		}
		if( imgParent.prev('.fiplajtbox-thumb').length == 0 ){
			$('.fiplajtbox-image-prev').addClass('off');
		}else if( 
			$('.fiplajtbox-image-prev').hasClass('off') ){ $('.fiplajtbox-image-prev').removeClass('off'); 
		}
		
		var imgNumber = parseInt(getItemNumber(imgParent))+1;
		var newThumbsIndex = Math.ceil(imgNumber/opts.thumbsSize);
		var mode = newThumbsIndex < thumbsActIndex ? 'prev' : 'next';
		var condition = mode == 'next' ? imgNumber > opts.thumbsSize*thumbsActIndex : imgNumber < opts.thumbsSize*(thumbsActIndex-1)+1;
		if( condition ){
			if( startup ){
				var tmpDuration = opts.thumbsScrollSpeed;
				opts.thumbsScrollSpeed = 0;
			}
			while( thumbsActIndex != newThumbsIndex ){
				scrollThumbs(mode);
			}
			if(startup) opts.thumbsScrollSpeed = tmpDuration;
		}
		
		update({
			title: $(img).attr('title'),
			description: $(img).attr('rel'),
			imgIndex: parseInt( getItemNumber( $(img).parent() ) ) + 1 
		});
		//debug.log(' :: fiplajtbox :: ended selectImg()');
		
	}
	
	/*
	 * kolejne/poprzednie zdjęcie
	 */
	function switchImg(mode){
		//debug.log(' :: fiplajtbox :: started switchImg(mode='+mode+')');
		var newImg = mode == 'next' ? $('.fiplajtbox-thumb-active').next('.fiplajtbox-thumb') : $('.fiplajtbox-thumb-active').prev('.fiplajtbox-thumb') ;
		if( newImg.length == 1 ){
			selectImg( $('a', newImg) );
		}
		//debug.log(' :: fiplajtbox :: ended switchImg()');
	}
	
	/*
	 * kolejne/poprzednie miniaturki (skok o tyle, ile jest w pasku miniaturek)
	 */
	function scrollThumbs(mode,duration){
		//debug.log(' :: fiplajtbox :: started scrollThumbs(mode='+mode+', duration='+duration+')');
		var condition = mode == 'next' ? thumbsActIndex < thumbsScrollCount : thumbsActIndex > 1 ;
		if( condition ){
			$('.fiplajtbox-thumbs-list').animate({
				left: (mode=='next'?'-':'+')+'=' + opts.thumbsWidth + 'px'
			},{
				queue: true, 
				duration: opts.thumbsScrollSpeed,
				complete: function(){
				}
			});
			thumbsActIndex = mode == 'next' ? thumbsActIndex+1 : thumbsActIndex-1 ;
			condition = mode == 'next' ? thumbsScrollCount : 1;
			if( thumbsActIndex == condition ){
				$('.fiplajtbox-thumbs-'+mode+' a').addClass('off');
			}
			$('.fiplajtbox-thumbs-'+(mode=='next'?'prev':'next')+' a').removeClass('off');
		}
		//debug.log(' :: fiplajtbox :: ended scrollThumbs()');
	}
	
	/*
	 * w przypadku zmiany obrazka, aktualizacja tytułu, opisu i numeru zdjęcia
	 */
	function update(metaData){
		//debug.log(' :: fiplajtbox :: started update(metaData='+metaData+')');
		$('.fiplajtbox-image-number').text(metaData.imgIndex);
		$('.fiplajtbox-description p').text(metaData.description);
		//$('.fiplajtbox-title h1').text(metaData.title);
		//debug.log(' :: fiplajtbox :: ended update()');
	}
	
})(jQuery);
