/**
 * jQuery PHPLightBox plugin
 * @name jquery.phplightbox-0.1.js
 * @author Fred Marecesche - http://durfordeath.co.uk
 * @version 0.1
 * @date 16/05/2009
 * @category jQuery plugin
 * @license MIT
 * @copyright (c) 2009 Fred Marecesche, http://durfordeath.co.uk
 *	
 *	Permission is hereby granted, free of charge, to any person obtaining
 *	a copy of this software and associated documentation files (the
 *	"Software"), to deal in the Software without restriction, including
 *	without limitation the rights to use, copy, modify, merge, publish,
 *	distribute, sublicense, and/or sell copies of the Software, and to
 *	permit persons to whom the Software is furnished to do so, subject to
 *	the following conditions:
 *	
 *	The above copyright notice and this permission notice shall be
 *	included in all copies or substantial portions of the Software.
 *	
 *	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *	EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *	MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 *	NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 *	LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 *	OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 *	WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 * @example Visit http://durfordeath.co.uk/phplightbox
 */
;

(function($) {

	var instance = 1;

	$.fn.PHPLightBox = function(settings) {
		settings = jQuery.extend({
			minMargin:			30, // minimum margin around the lightbox
			marginTop:			false, // if set to an integer, the box will position itself to the top of the document rather than try to center itself
			overlayColour:		'#000', // overlay colour
			overlayOpacity:		0.8, // opacity of the overlay (0 to 1)
			positionOnResize:	false, // allows phplightbox repositioning on resize (true|false)
			loadingGif:			'img/loading.gif', // path to the loading image
			
			// PHP handlers
			imageHandler:		'php/image.php', // path to the image php handler
			swfHandler:			'php/swf.php', // path to the flash php handler
			
			autoLoad:			false, // if autoload is enabled, the plugin will kick in on page load and show the url provided
			onlyHide:			false, // when set to true, the lightbox only gets hidden rather than completely removed.
			extraClose:			'.close' // comma-separated list of selectors for extra close buttons
			
			// NOTE: All paths to files are relative to the HTML calling the PHPLightBox. 
		},settings);
		
		
		
		var jQueryMatchedObj = this;
		//var rel = instance;
		var IEversion;
		
		var Exists = new Array();
		
		function _initialize() {
			if( $(this).attr('href') != '#' ){
				_showBox(this);
			}
			return false;
		}
		
		function _showBox(objClicked){
			if( !objClicked.showingLB ){
				var rel = instance;
				instance++;
			} else {
				var rel = objClicked.showingLB;
			}
			
			var PHPoverlay;
			var PHPloader;
			var PHPouter;
			var PHPinner;
			var PHPclose;
			var PHPcontent;
			var ajaxCall;
			
			_setInterface();
			
			// this might be a bit extreme but it prevents losing the
			// top half of the box on resizing...
			if( settings.positionOnResize ){
				$(window).resize(_positionBox);
			}
			
			PHPoverlay.css({backgroundColor:settings.overlayColour, opacity:0, display:"block"}).animate({opacity:settings.overlayOpacity},250, function(){
				
				// set some starting css rules
				PHPinner.css({padding:settings.minMargin + "px", opacity:0, display:"inline"});
				// only populate the lightbox if needed
				if( PHPcontent.html() == '<!-- {empty} -->' ){					
					
					// no need to process this very useful bit if the box isn't used...
					var IE = navigator.userAgent.match(/MSIE\ ([0-9])/);
					IEversion = IE != null ? IE[1] : 666;
					if(  IEversion < 7 !== false ){
						_fixIE();
						$('embed, object, select').addClass("PHPlb_hidden");
						// bit extreme maybe, calling it on every scroll?
						// ah well, it's only for IE6 users!
						$(window).scroll(_fixIE);
					}					
					
					// let's put some content in there...
					var type = "POST";
					var url;
					var data;
					var src = $(objClicked).attr('href');
					
					// prevent anchor links to start box
					if( src.match(/#/) ) return false;
					
					if( src.match(/(.*)\.swf/) != null ){ // flash file
						url = settings.swfHandler;
						data = "src=" + escape(src) + "&title=" + $(objClicked).attr('title');
					} else if( src.match(/(.*)\.(jpg|jpeg|png|gif)/) != null ){ // image
						url = settings.imageHandler;
						data = "src=" + src + "&title=" + $(objClicked).attr('title');
					} else { // HTML or PHP
						// some browsers do not like using post for HTML files...
						if( src.match(/(.*)\.(html|htm|php)/) != null ) type = "GET";
						url = src;
						data = null;
					}
					
					ajaxCall = $.ajax({
						type: type,
						url:url,
						data: data,
						success: function(msg){
							PHPcontent.html(msg);
							_preloadImages(PHPinner,function(){
								if( _positionBox() ){
									_showContent();
									_bindClose();
								}
							});
						}, 
						error: function(msg){
							PHPcontent.html('<h3>Sorry, unable to fetch content</h3>');
							if( _positionBox() ){
								_showContent();
								_bindClose();
							}
						}
					});
					
				} else {
					if( _positionBox() ){
						_showContent();
						// close event should already be bound if lightbox already exists...
					}
				}
			});
			
			function _setInterface(){
				
				if( !objClicked.showingLB ){
					//instance++;
					$('body').append('<div class="PHPlb_overlay" rel="' + rel + '" style="display:none"><img class="PHPlb_loader" src="' + settings.loadingGif + '" alt="Loading..." rel="' + rel + '" /></div><div class="PHPlb_outer" rel="' + rel + '"><div class="PHPlb_inner" rel="' + rel + '"><a class="PHPlb_close" href="#" rel="' + rel + '">close</a><div class="PHPlb_content" rel="' + rel + '"><!-- {empty} --></div></div></div>');
					
					objClicked.showingLB = rel;
				}
				
				// let's put some variable names on each element of the lightbox
				PHPoverlay = $('.PHPlb_overlay[rel=' + rel + ']');
				PHPloader	= $('> .PHPlb_loader', PHPoverlay);
				PHPouter	= $('.PHPlb_outer[rel=' + rel + ']');
				PHPinner	= $('> .PHPlb_inner', PHPouter);
				PHPclose	= $('> .PHPlb_close', PHPinner);
				PHPcontent	= $('> .PHPlb_content', PHPinner);
			};
			
			function _positionBox(){
			
				
				PHPouter.css({display:"block"});
				var yScroll = parseInt($(window).scrollTop());
				var xScroll = parseInt($(window).scrollLeft());
				PHPouter.css({left:xScroll+"px", top:yScroll+"px"});
				
				if( IEversion < 7 !== false ){
					_fixIE();
				}
				
				if( settings.marginTop ){
					PHPinner.css({marginTop:"0", top:settings.marginTop + "px"});
				} else {
					var height = parseInt(PHPinner.height() + (settings.minMargin*2));
					var windowHeight = PHPouter.height();
					
					if( height >= windowHeight ) {
						PHPinner.css({marginTop:"0", top:"0"});
					}
					if( height <= windowHeight ) {
						var yOffset = parseInt(height / 2);
						PHPinner.css({top:"50%", marginTop:"-"+yOffset+"px"});
					}
				}
				
				var width = parseInt(PHPinner.width() + (settings.minMargin*2));
				var windowWidth = PHPouter.width();
				
				if( width >= windowWidth ) {
					PHPinner.css({marginLeft:"0", left:"0"});
				}
				if( width <= windowWidth ) {
					var xOffset = parseInt(width / 2);
					PHPinner.css({left:"50%", marginLeft:"-"+xOffset+"px"});
				}
				return true;
			};
			
			function _showContent(){
				
					PHPloader.fadeOut('fast');
					PHPinner.animate({opacity:1}, 250);
				
			};
			
			function _hideBulge(e){
				// hide the box
				$('.PHPlb_outer[rel=' + e + ']').fadeOut(250, function(){
					$('.PHPlb_overlay[rel=' + e + ']').fadeOut(250, function(){
						if( !settings.onlyHide ){
							$('.PHPlb_outer[rel=' + e + ']').remove();
							$('.PHPlb_overlay[rel=' + e + ']').remove();
							objClicked.showingLB = false;
							
						} else {
							$('.PHPlb_inner[rel=' + e + ']').attr("style","");
						}
					});
				});
				// destroy window-bound events
				$(window).unbind("resize",_positionBox).unbind("scroll",_fixIE);
				// restore hidden elements
				$('embed, object, select').removeClass("PHPlb_hidden");
				$('body').removeClass('IEfullOverlay');
			};
			
			function _bindClose(){
				// add the rel attribute to the close button(s)
				if( settings.extraClose ){
					PHPcontent.find(settings.extraClose).each(function(){
						$(this).attr('rel',rel).addClass('PHPlb_extraclose');
					});
				}
				
				// bind close event
				$('.PHPlb_overlay[rel=' + rel + '], .PHPlb_outer[rel=' + rel + '], .PHPlb_inner[rel=' + rel + '], .PHPlb_content[rel=' + rel + '], .PHPlb_close[rel=' + rel + '], .PHPlb_extraclose[rel=' + rel + ']').bind("click", function(e){
					e.stopPropagation();
					if( !$(this).hasClass('PHPlb_content') ) {
						ajaxCall.abort();
						_hideBulge( $(this).attr('rel') );
						return false;
					}
				});
			};
			
			function _preloadImages(element, callback){
	
				if( !element ) return false;
				
				var allImages = $(element).find('img');
				var numOfImg = allImages.length;
				var imgProcessed = 0;
				if( allImages.length > 0 ){
					allImages.each(function(){
				
						var source = $(this).attr('src');
						var img = new Image;
						$(img).load(function(){
							imgProcessed++;
							if( imgProcessed >= numOfImg ){
								return callback();
							};
						});
						$(img).attr('src',source);
						
					});
				} else {
					return callback();
				}
			};
			
			function _fixIE(){
				$('body').addClass('IEfullOverlay');
				PHPoverlay.css({width:$(window).width()+"px", position:"absolute", top:$(window).scrollTop()+"px", left:$(window).scrollLeft()+"px"});
				PHPouter.css({width:$(window).width()+"px", height:$(window).height()+"px"});
			};
		};
		
		if( settings.autoLoad ){
			$(document).ready(function(){
				_showBox(jQueryMatchedObj);
			});
		};
		
		return this.unbind('click').click(_initialize);
		
	};
})(jQuery);


///////////////////////////////////////////////////////
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////

