/**
 * jQuery popupBox plugin
 * This jQuery plugin was inspired and based on Lightbox 2 by Lokesh Dhakar (http://www.huddletogether.com/projects/lightbox2/)
 * and adapted to me for use like a plugin from jQuery.
 * @name jquery-popupbox-0.1.js
 * @author Geert De Baets - http://www.geertdebaets.be
 * @version 0.1
 * @date December 25, 2010
 * @category jQuery plugin
 * @copyright (c) 2010 Geert De Baets(www.geertdebaets.be)
 */

// Offering a Custom Alias suport - More info: http://docs.jquery.com/Plugins/Authoring#Custom_Alias
(function($) {
	/**
	 * $ is an alias to jQuery object
	 *
	 */
	$.fn.popupBox = function(settings) {
		// Settings to configure the jQuery popupBox plugin how you like
		settings = jQuery.extend({
			// Configuration related to overlay
			overlayBgColor: 		'#000',		// (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 container content
			containerBorderSize:	10,			// (integer) If you adjust the padding in the CSS for the container, #popupbox, you will need to update this value
			containerResizeSpeed:	400		// (integer) Specify the resize duration of container content. These number are miliseconds. 400 is default.
		},settings);
		// Caching the jQuery object with all elements matched
		var jQueryMatchedObj = this; // This, in this context, refer to jQuery object
		/**
		 * Initializing the plugin calling the start function
		 *
		 * @return boolean false
		 */
		function _initialize() {
			_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 popupBox 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.
			
			if (objClicked.target){
				var targetImage = $('<img />').attr('src', objClicked.target + '?random=' + (new Date()).getTime());
				targetImage.load(function(){
					var targetWidth = targetImage[0].width + 40;
					var targetHeight = targetImage[0].height + 40;
					_set_interface(targetWidth,targetHeight);
					
					
					_set_popup_title(objClicked.title);
					if (objClicked.target){
						_set_popup_size(targetImage[0].width, targetImage[0].height);
					}
					_set_popup_text(objClicked.href, false);
			
					$('#jquery-popupbox').show();
				});
			}else{
				_set_interface(0,0);
				
				_set_popup_title(objClicked.title);

				_set_popup_size(600,600);

				_set_popup_text(objClicked.href, true);
				
				$('#jquery-popupbox').show();
			}
			
		}
		
		function _set_popup_size(w,h) {
				var targetHeight = h + 60;
				var targetWidth = w + 40;
				
				var containerBox = $('#popupbox');
				var popupbox_table = $('#popupbox_table');
				popupbox_table.width(targetWidth);
				// de height wordt later wel terug overschreven door _set_popup_text
				containerBox.height(targetHeight);
				containerBox.width(targetWidth);
		}
		

		function _set_popup_title(title) {
			var containerTitle = $('#popup_box_title');
			containerTitle[0].innerHTML = title;
		}
		
		function _set_popup_text(pageURL, setHeight) {
			var container = $('#popupbox-content');
			
			$.ajax({ 
				url: pageURL, 
				type: 'GET',
				context: document.body, 
				success: function(data){
					if (data){
						container[0].innerHTML = data;
						if (setHeight == true){
							var height = container.innerHeight();
							var containerBox = $('#popupbox');
							containerBox.height(height + 20);
						}
						
						// Activate links with class "standard"
						$('.standard').click(function(){
					    	window.open(this.href);
					    }); 
					}
		      }
			});
			
		}
		
		function _set_interface(targetWidth, targetHeight) {
			// Apply the HTML markup into body tag
			$('body').append('<div id="jquery-overlay"></div><div id="jquery-popupbox"><div id="popupbox" class="grey_border"><div style="height: 20px; background-image: url(\'images/menu_normal.gif\'); border:1px solid #042F5A; border-width:0px 0px 1px 0px;"><table id="popupbox_table" cellpadding="0" cellspacing="0" border="0"><tr><td id="popup_box_title" class="font8 popup_title" style="padding-left: 10px; padding-top: 2px;">test</td><td width="17" align="right"><img src="images/close_button.gif" id="popupbox-close-button" style="cursor: pointer;padding-right: 3px;" border="0"></td></tr></table></div><div id="popupbox-content"></div></div></div>');	
			// Get page sizes
			var arrPageSizes = ___getPageSize();
			// Style overlay and show it
			
			var extraHeight = 0;
			var overlayHeight = arrPageSizes[1];
			
			if (targetHeight > 0){
				var neededHeight = arrPageSizes[3] / 10 + targetHeight + 220;
				if (screen.height < neededHeight){
					extraHeight = neededHeight - screen.height;
				}
				if (extraHeight > 0){
					overlayHeight = arrPageSizes[1] + extraHeight;
				}
			}
			$('#jquery-overlay').css({
				backgroundColor:	settings.overlayBgColor,
				opacity:			settings.overlayOpacity,
				width:				arrPageSizes[0],
				height:				overlayHeight
			}).fadeIn();
			// Get page scroll
			var arrPageScroll = ___getPageScroll();
			// Calculate top and left offset for the jquery-popupbox div object and show it
			
			var positieLeft = arrPageScroll[0];
			if (targetWidth > 0){
				var screenWidth = screen.width;
				var whiteSpace = screenWidth - targetWidth;
				positieLeft = arrPageScroll[0] + (whiteSpace / 2);
			}
			
			$('#jquery-popupbox').css({
				top:	arrPageScroll[1] + (arrPageSizes[3] / 10),
				left:	positieLeft
			});
			// Assigning click events in elements to close overlay
			$('#jquery-overlay, #jquery-popupbox').click(function() {
				_finish();									
			});
			$('#popupbox').click(function() {
				return false;
			});
			// Assign the _finish function to popupbox-loading-link and popupbox-secNav-btnClose objects
			$('#popupbox-close-button').click(function() {
				_finish();
				return false;
			});
			// 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-popupbox div object and show it
				$('#jquery-popupbox').css({
					top:	arrPageScroll[1] + (arrPageSizes[3] / 10),
					left:	arrPageScroll[0]
				});
			});
		}
		/**
		 * Remove jQuery popupBox plugin HTML markup
		 *
		 */
		function _finish() {
			$('#jquery-popupbox').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
