var overlay = function(){
	var overlayOpacity 			= 0.8;
	var contentType				= 'html'; 		
	var contentBackground		= 'none';
	
	var preCallback				= null; 
	var postCallback			= null;
	
	var overlayMargin			= 50;
	var isSubOverlay 			= false;		
	
	return {
		showOverlay : function( options ) {
			var backgroundOpacity =  ( options && options.backgroundOpacity )  ?
				parseFloat( options.backgroundOpacity ) : overlayOpacity;
			overlayOpacity = backgroundOpacity;
			
			//	ukrywanie selectow i flashy - 
			f.objects.hide();
			//$('object:visible, select:visible').hide().data('ukryty', true);
			
			//	tworzenie dwoch glownych elementow, tla oraz kontenera na content.
			var foBackground = $('<div/>').attr('id','fboxBackground').css({
					'opacity' : backgroundOpacity , 'filter' : 'alpha(opacity='+backgroundOpacity*100+')',
					'filter': 'progid:DXImageTransform.Microsoft.Alpha(opacity='+backgroundOpacity*100+')',
					'background':'#000', 'text-align':'center',
					'position':'fixed','top':'0', 'left':'0',
					'width':'100%', 'height':'100%',
					'display':'none', 'z-index':'500'
				});
			var foContent;
			if (contentType=='ajax') foContent = $('<div/>').attr('id','fboxContent_ajax').css();
			else foContent = $('<div/>').attr('id','fboxContent').css();

			if ( options ) {
				if ( options.width ) {
					foContent.width( options.width );
				}
				if ( options.height ) {
					foContent.height( options.height );
				}
			}
				
			$('body').append(foBackground).append(foContent);
			//	generowanie standardowych linków do zamykania overlaya (top)
			var navbars = $('<div/>');
			if ( options ) {
				if ( options.closeButton == 'both' || options.closeButton == 'top' ) {
					foContent.append($('<p class="navbar"><a href="#" class="overlayClose">zamknij X</a></p>'));
				}
			}
			//	dodajemy container dla zawartosci overlaya
			foContent.append( $('<div id="fboxContentContainer"></div>') );
			//	generowanie standardowych linków do zamykania overlaya (bottom)
			if ( options ) {
				if ( options && options.closeButton == 'both' || options.closeButton == 'bottom' ) {
					foContent.append($('<p class="footbar"><a href="#" class="overlayClose">zamknij X</a></p>'));
				}
			}
			this.addCSSforIE();
			//$('#ov', foBackground).fadeIn();
			//alert('showe?');
			$('#fboxBackground').fadeIn();
			foContent.show();
			
			
			//	zamykanie escapem
			$(document).keyup(function(e) {
				if ( e.keyCode == 27 ) {
					overlay.close();
				}
			});
			
		},
		append : function (obj, objToShow, options ) {
			_self = this;
			if ( options ) {
				preCallback = options.preCallback || null;
				postCallback = options.postCallback || null;
			}
			$(obj).click(function() {
				preCallback ? preCallback.call(this) : null ; 
				var id = '';
				var href = '';
				if ( typeof objToShow == 'undefined' || objToShow == 'default' || objToShow === null ) {
					href = this.href;
					var G = new RegExp('.*\.jpg|\.jpeg|\.gif[\?]{0,1}.*','g');
					if ( G.test(href) ){
						contentType = 'img';
					} else if ( href.indexOf('#')+1 ) {
						id = href.slice( href.indexOf('#') );
						contentType = 'html';
					} else {
						//	unknown type.
						//alert('unknown type');
						overlay.close();
						return false;
					}
				} else if ( objToShow == 'ajax' ) {
					href = this.href;
					contentType = 'ajax';
				} else {
					id = objToShow;
					contentType = 'html';
				}
				
				if ( options && options.subOverlay ) {
					isSubOverlay = true;
				} else {
					isSubOverlay = false;
					_self.showOverlay(options);		
				}
				var fboxContent = $('#fboxContent');
				var output = fboxContent.find('#fboxContentContainer');
				
				//	ustawienia tla według contentu 
				if ( contentType == 'html' || contentType == 'ajax' ) {
					contentBackground = 'none';
				} else if ( contentType == 'img' ) {
					contentBackground = '#ffffff';
				}
				
				var fboxContent;
				if(contentType=='ajax') fboxContent = $('#fboxContent_ajax');
				else  fboxContent= $('#fboxContent');
				var output = fboxContent.find('#fboxContentContainer');
				
				if ( contentType == 'img' ) {
					_self.showLoading();
					var img = new Image();
					$(img).load(function(){
						var p = $('<p class="image"></p>');
						p.append( $(this) ).width(this.width).height(this.height);
						output.empty().append(p);			//	podmieniamy content, bo bylo wczesniej pokazane ladowanie
						_self.showContent(this.width, this.height);
					}).attr('src', href);
				} else if ( contentType == 'html' ) {
					$(id).clone().addClass('fboxID_'+id.slice(1)).appendTo(output).show();
					_self.showContent();
				} else if ( contentType == 'ajax' ) {
					_self.showLoading();
					$.ajax({
						type: "GET",
						url: href,
						dataType: 'html',
						async: true,
						success: function(data) {
							output.empty().append(data);		//	podmieniamy content, bo bylo wczesniej pokazane ladowanie
							_self.showContent();
						}, 
						error: function(XMLHttpRequest, textStatus, errorThrown) {
							_self.close();
							throw new Error('Błąd ładowania overlay Ajax. URL = "'+href+'", \nXMLHttpRequest = '+XMLHttpRequest+'\ntextStatus = '+textStatus+'\nerrorThrown = '+errorThrown);
						}
					});
				}
				
				return false;
			});
		},
		showContent : function(_width, _height) {
		/**
		 *		Metoda pokazuje konkretną zawartoście na warstwie overlaya.
		 *		Używana wewnętrznie.
		 */
			var fboxContent = $('#fboxContent, #fboxContent_ajax');
			var output = fboxContent.find('#fboxContentContainer');

			var scrollTop = 0;
			if ( typeof $(window).scrollTop == "function" ) {
				scrollTop = $(window).scrollTop();
			}
			var scrollLeft = 0;
			if ( typeof $(window).scrollLeft == "function" ) {
				scrollLeft = $(window).scrollLeft();
			}
			var width = fboxContent.width();
			var height = fboxContent.height() + overlayMargin*2;
			if ( _width ) width = _width;
			if ( _height ) height = _height + overlayMargin*2;
				
			//alert(' width : '+width+'\n height : '+height+'\n _width: '+_width+'\n _height : '+_height);
			var posLeft = parseInt(parseInt( Math.floor(($(window).width() - width)/2) + scrollLeft));
			var posTop = 0;
			
			var widthVisibleArea = ( $(window).width() > $('body').width() ) ? $(window).width() : $('body').width();
			//	sprawdzic czy jest scrollTop
			$('#fboxBackground').width(widthVisibleArea+window.scrollbarWidth);

			if ( height >  $(window).height() ) {
				//	jesli content jest wiekszy niz wysokosc okna
				//	zmieniamy wysokosc tla, aby caly content byl nad tlem.
				$('#fboxBackground').height(parseInt(height+scrollTop));
				//alert('new height of background: '+parseInt(height+scrollTop));
				//	pozycja pionowa contentu ustawiana jest z marginesem gornym od gornej krawedzi okna
				posTop = parseInt(parseInt( overlayMargin + scrollTop));
			} else {
				//	jesli content jest mniejszy niz okno
				//	ustaw wysokosc tla -> wysokosc okna/body, aby pokrylo cala wyswietlana strone 
				var newHeight = ( ( $(window).height() > $('body').height() ) ? $(window).height() : $('body').height() ) + window.scrollbarHeight;
				$('#fboxBackground').height(newHeight);
				//alert('new height of background (window/body) : \nwindow: '+ $(window).height()+'\nbody: '+$('body').height()+'\n newHeight = '+newHeight);
				//	jesli zawartosc overlaya jest mniejsza od wielkkosci okna -> pozycja pionowa ustawiona na srodku okna
				posTop = Math.floor(($(window).height() - height) /2 )+ scrollTop+overlayMargin;
			}
			//alert('position : top = '+posTop+' left = '+posLeft );
			var top = posTop +'px';
			var left = posLeft +'px';
			fboxContent.css( { 'top':top, 'left':left } );
			this.addCSSforIE();
			
			/*
			//	TUTAJ NIE DZIALA PO ID, bo to jest kopiowane clone()   i wtedy w DOMie sa dwa id, nie jeden... 
			//	sprobowac dopisac zdarzenia do sklonowanego elementu
			//	sprobowac dopisac zdarzenia do sklonowanego elementu lub nadac mu inne id na podstawie pierwowzoru, np time()

			if ( typeof events != 'undefined' && events ) {
				var ileEventow = events.length;
				for (var i=0; i<ileEventow; i++) {
					if ( events[i][0] && events[i][1] ) {
						fboxContent.find(events[i][0]).click( function(num, ev){		// przetestowac wyszukiwanie w fboxContent po ID i innych tez.
							return function() {
								ev[num][1].call(externalLink);
							};
						}(i, events));
					}
				}
			}
			
*/
			/*	'lapanie' przycisk zamknij	*/
			$('.fboxZamknij, .overlayClose').click( function() {
				_self.close();
				return false;
			});
			
			_self.append( output.find('.overlay') , 'default', { subOverlay: true });
			_self.append( output.find('.overlayAjax'), 'ajax', { subOverlay: true } );
			_self.append( output.find('.overlay_ajax'), 'ajax', { subOverlay: true } );
		},
		showLoading: function() {
			/** 
			 *		Metoda pokazuje informacje o ladowaniu overlaya.. 
			 */
			$('#fboxContentContainer').append( $('<p class="overlayLoading">Ładowanie...</p>') );
			this.showContent();
		},
		addCSSforIE : function() {
		/**
		 *		Metoda dodaje style dla IE.
		 *		Używana wewnętrznie.
		 */
			if (jQuery.browser.msie) {
				if ( parseInt(jQuery.browser.version) == 6 ) {
					$('body').css({'height':'auto'});
					$('#fboxBackground').css({
						'position' : 'absolute', 'top': '0', 'left': '0'
					});
				}
				if ( parseInt(jQuery.browser.version) == 7 ) {
					//alert('7');
					var fboxBackground = $('#fboxBackground').get(0);
					$('#fboxBackground').css({
						'background':'none',
						'-ieh:' : fboxBackground.parsed ? 0 : (
							objTmp = document.createElement('div'),
							objTmp.id = 'ov',
							fboxBackground.parentNode.insertBefore(objTmp, fboxBackground),
							fboxBackground.parsed = 1
						)
					});
					//alert('parsed? '+fboxBackground.parsed);
					if ( fboxBackground.parsed == 1 ) {
						$('#ov').css({
							'position':'fixed','left': '0','top':'0',
							'width':'100%','height':'100%',
							'background-color':'#000',
							'filter': 'progid:DXImageTransform.Microsoft.Alpha(opacity='+overlayOpacity*100+')'
						}).hide().fadeIn();
						fboxBackground.parsed = 2;
					}
			
				}
			}
		},
		close : function() {
		/**
		 *		Metoda zamykająca warstwę i chowająca jej zawartość.
		 *		Używana wewnętrznie.
		 */
			if (contentType=='ajax') 
				$('#fboxContent_ajax').remove();
			else 
				$('#fboxContent').remove();
			$('#fboxBackground, #ov').fadeOut( function() {
				$('#fboxBackground').css('background','#fff');		// zeby w operze nie zostawał ślad tła    
				$('#fboxBackground, #ov').height('0').remove();
				f.objects.show();
			});
			postCallback ? postCallback.call() : null;
		}
	}
}();

$( function () {
	overlay.append('.overlay', 'default');
	overlay.append('.overlayAjax', 'ajax' );
	overlay.append('.overlay_ajax', 'ajax' );
	overlay.append('.overlay_button', 'default', { closeButton: 'top' });
});
