var refObjBufferArray = [];
var boxIsInit = false;
var test = 0;

function loadContentFrom(pageId){
 	//$.fn.referenceLightBox.test(); 
}

(function($) {
		  	  
		  	  
	/**
	 * $ is an alias to jQuery object
	 */
	$.fn.referenceLightBox = function(settings) {
		
		
		// Settings to configure the jQuery lightBox plugin how you like
		settings = jQuery.extend({
			// Configuration related to overlay
			overlayBgColor: 		'#666',		// (string) Background color to overlay; inform a hexadecimal value like: #RRGGBB. Where RR, GG, and BB are the hexadecimal values for the red, green, and blue values of the color.
			overlayOpacity:			0.8,		// (integer) Opacity value to overlay; inform: 0.X. Where X are number from 0 to 9
 
			// Configuration related to keyboard navigation
			keyToClose:				'c',		// (string) (c = close) Letter to close the jQuery lightBox interface. Beyond this letter, the letter X and the SCAPE key is used to.
			keyToPrev:				'p',		// (string) (p = previous) Letter to show the previous image
			keyToNext:				'n',		// (string) (n = next) Letter to show the next image.
			
			// Don´t alter these variables in any way
			activeItemId:           0,
			preLoadMaxAmount:       1,
			
			// Fading Zeiten			
			fadeInTime:				1000,
			displayTime:			4000,
			fadeOutTime:			1000
			
		},settings);
		
		 
		
		// Caching the jQuery object with all elements matched
		var jQueryMatchedObj = this; // This, in this context, refer to jQuery object
		
		if(settings.autostart == true){
			_initialize();
		}
		
		/**
		 * Initializing the plugin calling the start function
		 *
		 * @return boolean false
		 */
		function _initialize() {  
		test = 0;
			_start(this,jQueryMatchedObj); // This, in this context, refer to object (link) which the user have clicked
			return false; // Avoid the browser following the link
		}
		
		
		/**
		 * Start the jQuery lightBox plugin
		 *
		 * @param object objClicked The object (link) whick the user have clicked
		 * @param object jQueryMatchedObj The jQuery object with all elements matched
		 */
		function _start(objClicked,jQueryMatchedObj) {
			// Hime some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
			$('embed, object, select').css({ 'visibility' : 'hidden' });
			// Call the function to create the markup structure; style some elements; assign events in some elements.
			_set_interface();
			_loadRefPageObj(settings.initId, 0);
		}
		
		
		/**
		 *  Lädt ein neuen HTML String einer Referenzseite
		 */
		function _loadRefPageObj(pageId, preLoadAmount){ 
			
			var isVisible = (preLoadAmount== 0);
			
			// prüfe ob Ergebnis im Cache
			if(refObjBufferArray[pageId] == null){	 
			
			
			    if(isVisible){
			       $('#referenceLightboxLodingScreen').fadeIn('fast');
 				}
				
				$.get(settings.refPageInitUrl, {id:pageId},	function(data){
																
																// Body-innerHTML aus String rausfiltern
																var startPos = data.search(/\<body\>/);
																var endPos   = data.search(/\<\/body\>/);		
																var bodyHTML = data.substring((startPos+6), endPos);
																
																var uidField = ""+bodyHTML.match(/\<fieldset class\=\"uid\"\>.*\<\//); 
																 
																 
																var pageIdCallback = uidField.substring(22, (uidField.length-2));
																
																// Ergebnis cachen
																refObjBufferArray[pageIdCallback] = {htmlString:bodyHTML, prevId:0, nextId:0}; 														
																													
																// falls Limit noch nicht erreicht ist, lade 
																// vorheriges und nächstes Referenzobjekt																
																++preLoadAmount;
																	
																var startPos = 9;
																
																// Preload nächste Referenzseite
																var prevMatchedString = ""+bodyHTML.match(/prevId\=\"~.{0,5}~/);																	
																var prevEndPos   = prevMatchedString.length - 1;
																if(prevEndPos > startPos){
																	var prevId       = prevMatchedString.substring(startPos, prevEndPos);	
																	refObjBufferArray[pageIdCallback].prevId = prevId;																		
																	if(preLoadAmount <= settings.preLoadMaxAmount){
																		_loadRefPageObj(prevId, preLoadAmount);
																	}
																}
																
																// Preload nächste Referenzseite
																var nextMatchedString = ""+bodyHTML.match(/nextId\=\"~.{0,5}~/);																	
																var nextEndPos   = nextMatchedString.length - 1;
																if(nextEndPos > startPos){
																	var nextId       = nextMatchedString.substring(startPos, nextEndPos);	
																	refObjBufferArray[pageIdCallback].nextId = nextId;
																	if(preLoadAmount <= settings.preLoadMaxAmount){
																		_loadRefPageObj(nextId, preLoadAmount);
																	}
																}
																
																
																/// auf Ausgabe schreiben
																_writeNewHTMLContent(pageIdCallback, bodyHTML, isVisible);
													
																return;
															});
			}else{
				
				// auch wenn Objekt in Buffer prüfe ob auch die Nachbarn Preloaded sind
				if(refObjBufferArray[pageId].prevId != 0 && refObjBufferArray[refObjBufferArray[pageId].prevId] == null){
				   _loadRefPageObj(refObjBufferArray[pageId].nextId, (preLoadAmount+1));
				} 
				if(refObjBufferArray[pageId].nextId != 0 && refObjBufferArray[refObjBufferArray[pageId].nextId] == null){
				   _loadRefPageObj(refObjBufferArray[pageId].nextId, (preLoadAmount+1));
				} 
				
				_writeNewHTMLContent(pageId, refObjBufferArray[pageId].htmlString, isVisible);
				
				/*
				if(isVisible){
					// htmlCode existiert schon von früheren Aufruf 
					// her, also nur noch sichbar machen 
					_setHTMLContentVisible(pageId);	
				}*/
			}
	    }
		
		
		/**
		 *  fügt den AjaxContent Wrapper ein neues Referenz-Objekt hinzu
		 */
		function _writeNewHTMLContent(pageId, bodyHTML, isVisible){
			     
				 
				 bodyHTML = bodyHTML.replace(/height\=\"(.*)\" alt/g, "height=\"$1\" style=\"height:$1px;\" alt");
				 
				 				
				// schreibe neues HTML-Objekt
				$('#refLightboxAjaxContent').append('<div id="rlBufferItem_'+pageId+'" class="referenceLightboxBufferItem">'+bodyHTML+'</div>');
							 
			
				// mache neues HTML-Objekt sichbar falls nötig
				if(isVisible){
				  _setHTMLContentVisible(pageId);
				}
		}
		
		
		/**
		 *  blendet das Referenzobjekt mit der übergebenen Id ein und das Alte aus 
		 */
		function _setHTMLContentVisible(pageId){		
			     
				// blende altes Objekt aus
				if(settings.activeItemId){
					$('#rlBufferItem_'+settings.activeItemId).fadeOut('fast',_setVisible(pageId));
				}else{
				   _setVisible(pageId);	
				}
		}
		
		function _setVisible(pageId){
			
			$('#rlBufferItem_'+settings.activeItemId).hide();
			
			settings.activeItemId = pageId;
				if(refObjBufferArray[pageId].prevId != 0){ 				
				    $('#idp'+refObjBufferArray[pageId].prevId).unbind('click');
				    $('#idp'+refObjBufferArray[pageId].prevId).click(function(){  $(this).blur(); _loadRefPageObj(refObjBufferArray[pageId].prevId, 0);  });
				} 
				
				if(refObjBufferArray[pageId].nextId != 0){
				    $('#idn'+refObjBufferArray[pageId].nextId).unbind('click');
					$('#idn'+refObjBufferArray[pageId].nextId).click(function(){  $(this).blur(); _loadRefPageObj(refObjBufferArray[pageId].nextId, 0);  });
				} 
							
				
                _processRefImages(pageId);
				
				$('#referenceLightboxLodingScreen').fadeOut('fast');
 				
				// Blende neues Objekt ein
				if(test > 0){
				   
				}else{
					$('#rlBufferItem_'+pageId).fadeIn('fast');
				}
	    }

		
		
		/**
		 *  zentriert alle Bilder und Animiert sie (Fadings) falls es mehrere sind
		 */
		function _processRefImages(pageId){
			
		           // Bilder mittig ausrichten
				    $('.refImgList img').each(function(){		
													   
													   var height = $(this).css('height');
													   var topValue = -175 + ((548 - height.substring(0,(height.length-2)))/2);
 													   
													   this.style.top = topValue+'px';
													   });				
					
					 
					var listLength = $('#rlBufferItem_'+pageId+" .refImgList img").length; 
					if(listLength != null && listLength > 1){						 				
						  _fadeImages($('#rlBufferItem_'+pageId+" .refImgList img")[0], 0, settings.activeItemId); 
					}else{
						$($('#rlBufferItem_'+pageId+" .refImgList img")[0]).fadeIn( settings.fadeInTime );	
					}
					
					function _fadeImages(domEle, index, currentId){
												   
					   // steige aus Endlosschleife aus wenn neue Bilder geladen wurden
					   if(currentId != settings.activeItemId) return;
					   
					   // eins hochzählen und Reseten falls 
					   // maximum erreicht
					   index = ++index % listLength;
					   
					   $(domEle).fadeIn( settings.fadeInTime );					   
					   setTimeout(function(){						  
						  $(domEle).fadeOut( settings.fadeOutTime, function(){
								 _fadeImages($('#rlBufferItem_'+pageId+" .refImgList img")[index], index, currentId);   
						  });
					   }, settings.displayTime);  
					}		
 
	    }
		
		
		
		/**
		 *  baut das HTML-Gerüst für die ReferenceLightbox auf und blendet sie ein
		 */				
		function _set_interface() {
			
			//if(!boxIsInit){
			   boxIsInit = true;
			   // Apply the HTML markup into body tag
			   $('body').append('<div id="jquery-overlay"></div><div id="jquery-referenceLightbox" align="center"><div id="referenceLightboxContent" align="left"><div id="referenceLightboxLodingScreen"></div><div id="refLightboxCompanyLogo"></div><div id="refLightboxImageBackground"></div><div id="refLightboxCloseBtn"></div><div id="refLightboxAjaxContent"></div></div></div>');	
		       	
				
				// Assigning click events in elements to close overlay
				$('#jquery-overlay').click(function() {
					_finish();									
				});
				
				//$('#referenceLightboxContent').click(function() { console.log('hier'); return false; });
					
	 
				// Assign the _finish function to lightbox-loading-link and lightbox-secNav-btnClose objects
				$('#lightbox-loading-link,#refLightboxCloseBtn').click(function() {
					_finish();
					return false;
				});
			//}
			
			// Get page sizes
			var arrPageSizes = ___getPageSize();
			
			// Style overlay and show it
			$('#jquery-overlay').css({
				backgroundColor:	settings.overlayBgColor,
				opacity:			settings.overlayOpacity,
				width:				arrPageSizes[0],
				height:				arrPageSizes[1]
			}).fadeIn('slow');
			
			
			// Get page scroll
			var arrPageScroll = ___getPageScroll();
			
			
			// Calculate top and left offset for the jquery-lightbox div object and show it
			$('#jquery-referenceLightbox').css({
				top:	arrPageScroll[1] + (arrPageSizes[3] / 8)				
			}).fadeIn('slow');
			
			
		
			
			// If window was resized, calculate the new overlay dimensions
			$(window).resize(function() {
				// Get page sizes
				var arrPageSizes = ___getPageSize();
				// Style overlay and show it
				$('#jquery-overlay').css({
					width:		arrPageSizes[0],
					height:		arrPageSizes[1]
				});
				// Get page scroll
				var arrPageScroll = ___getPageScroll();
				// Calculate top and left offset for the jquery-lightbox div object and show it
				$('#jquery-referenceLightbox').css({
					top:	arrPageScroll[1] + (arrPageSizes[3] / 8)
				});
			});
		}
		
		
		
		/**
		 * Remove jQuery lightBox plugin HTML markup
		 *
		 */
		function _finish() {
			$('#jquery-referenceLightbox').remove();
			$('#jquery-overlay').fadeOut(function() { $('#jquery-overlay').remove(); });
			// Show some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
			$('embed, object, select').css({ 'visibility' : 'visible' });
		}
		
		
		/**
		 / THIRD FUNCTION
		 * getPageSize() by quirksmode.com
		 *
		 * @return Array Return an array with page width, height and window width, height
		 */
		function ___getPageSize() {
			var xScroll, yScroll;
			if (window.innerHeight && window.scrollMaxY) {	
				xScroll = window.innerWidth + window.scrollMaxX;
				yScroll = window.innerHeight + window.scrollMaxY;
			} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
				xScroll = document.body.scrollWidth;
				yScroll = document.body.scrollHeight;
			} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
				xScroll = document.body.offsetWidth;
				yScroll = document.body.offsetHeight;
			}
			var windowWidth, windowHeight;
			if (self.innerHeight) {	// all except Explorer
				if(document.documentElement.clientWidth){
					windowWidth = document.documentElement.clientWidth; 
				} else {
					windowWidth = self.innerWidth;
				}
				windowHeight = self.innerHeight;
			} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
				windowWidth = document.documentElement.clientWidth;
				windowHeight = document.documentElement.clientHeight;
			} else if (document.body) { // other Explorers
				windowWidth = document.body.clientWidth;
				windowHeight = document.body.clientHeight;
			}	
			// for small pages with total height less then height of the viewport
			if(yScroll < windowHeight){
				pageHeight = windowHeight;
			} else { 
				pageHeight = yScroll;
			}
			// for small pages with total width less then width of the viewport
			if(xScroll < windowWidth){	
				pageWidth = xScroll;		
			} else {
				pageWidth = windowWidth;
			}
			arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
			return arrayPageSize;
		};
		
		
		/**
		 / THIRD FUNCTION
		 * getPageScroll() by quirksmode.com
		 *
		 * @return Array Return an array with x,y page scroll values.
		 */
		function ___getPageScroll() {
			var xScroll, yScroll;
			if (self.pageYOffset) {
				yScroll = self.pageYOffset;
				xScroll = self.pageXOffset;
			} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
				yScroll = document.documentElement.scrollTop;
				xScroll = document.documentElement.scrollLeft;
			} else if (document.body) {// all other Explorers
				yScroll = document.body.scrollTop;
				xScroll = document.body.scrollLeft;	
			}
			arrayPageScroll = new Array(xScroll,yScroll);
			return arrayPageScroll;
		};
		
		
		 /**
		  * Stop the code execution from a escified time in milisecond
		  *
		  */
		 function ___pause(ms) {
			var date = new Date(); 
			curDate = null;
			do { var curDate = new Date(); }
			while ( curDate - date < ms);
		 };
		 
		// Return the jQuery object for chaining. The unbind method is used to avoid click conflict when the plugin is called more than once
		return this.unbind('click').click(_initialize);
	};
})(jQuery); // Call and execute the function immediately passing the jQuery object
