/**
 * @author piotr@km-net.pl
 */

(function ($) {
	/**
	 * Wykonywany na elemencie ktory zawiera zbior elemntów <a><img /></a>
	 * @param {Object} dest - element w którym zostanie umieszczone płótno do wyswietlania obrazów
	 */
	$.fn.bounceGallery = function(dest){
		this.destination = dest;

		this.images = [];
		this.canvas = null;
		this.cVisible = false;
		this.timer = null;
		this.timerStart = null;

		this.loadImages = function(){
			
			var anchors = $('a',$(this) );
			var cWidth = $(this.canvas).width();
			for(i=0; i< anchors.length; i++){
				this.images[i] = $('<img src="'+anchors[i]+'"/>');//wczytanie obrazkow do cache'u
				$(this.images[i]).hide();
				$(this.canvas).append(this.images[i]);
			}
		}
		
		this.initMouseEvents = function(){
			obG = this;

			var photos = $(obG).children('a img');

			$(obG).children('a img').mouseover(function(){

				index = $(obG).children('a img').index(this);

				obG.timerStart = setTimeout( function(){
					$(obG.canvas).show();
					$(obG.images[index]).fadeIn();
					var lpos = 0;
					if( !obG.images[index][0].complete ) {
						lpos = 20;
					}else{
						lpos = ( $(obG.canvas).width() / 2 ) - ($(obG.images[index]).width() / 2);
					}
					$(obG.images[index]).css('left',lpos+'px' );

				},300);
				
				clearTimeout(obG.timer);
			}).mouseout(function(){
				
				clearTimeout(obG.timerStart);
				$('img',obG.canvas).fadeOut();
				obG.timer = setTimeout(function(){
					$(obG.canvas).fadeOut();
				},500);
			});

		}
		this.createCanvas = function(){
			$(this.destination).append('<div class="bg-canvas" >');
			this.canvas = $('div.bg-canvas',this.destination);
			$(this.canvas).hide();
		}
		
		this.createCanvas();
		this.loadImages();
		this.initMouseEvents();
		
	}

})(jQuery);

