/**
 * 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($) {

	$.fn.PHPLightBox = function(settings) {
		settings = jQuery.extend({
			PHPlb_margin:		30, // margin around the lightbox
			overlayColour:		'#000', // overlay colour
			overlayOpacity:		0.8, // opacity of the overlay (0 to 1)
			positionOnResize:	true, // allows phplightbox repositioning on resize (true|false)
			loadingGif:			'/js/ajax-loader.gif', // path to the loading image
			// PHP handlers
			imageHandler:		'/js/image.php', // path to the image php handler
			swfHandler:			'/js/swf.php' // path to the flash php handler
			
			// NOTE: All paths to files are relative to the HTML calling the PHPLightBox. 
		},settings);
		
		var jQueryMatchedObj = this;
		var IEversion;
		
		function _initialize() {
			_showBox(this,jQueryMatchedObj);
			return false;
		}
		
		function _showBox(objClicked, jQueryMatchedObj){
			// overlay on the body
			_setInterface();
			
			// set some starting css rules
			$('#PHPlb_inner').css({padding:settings.PHPlb_margin + "px", opacity:0, display:"inline"});
			
			// 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);
			}
			
			// this might be a bit extreme but it prevents losing the
			// top half of the box on resizing...
			if( settings.positionOnResize ){
				$(window).resize(_positionBox);
			}
			
			
			
			$('#PHPlb_overlay').css({opacity:0, display:"block"}).animate({opacity:.8},250, function(){
				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
					url = src;
					data = null;
				}
				var ajaxCall = $.ajax({
					type: "POST",
					url:url,
					data: data,
					success: function(msg){
						$('#PHPlb_content').html(msg).find('img').preload({
							onFinish:function(){
								_showContent();
							}
						});
					}, 
					error: function(msg){
						$('#PHPlb_content').html('<h3>Sorry, unable to fetch content</h3>');
						_showContent();
					}
				});
				// bind close event
				$('#PHPlb_overlay, #PHPlb_outer, #PHPlb_inner, #PHPlb_close, #PHPlb_content').click(function(e){
					ajaxCall.abort();
					e.stopPropagation();
					if( $(this).attr("id") == 'PHPlb_content' ) return false;
					_hideBulge();
					return false;
				});
				
			});
			
			function _setInterface(){
				if( $('#PHPlb_overlay').length < 1 ){
					$('body').append('<div id="PHPlb_overlay" style="display:none"><img id="PHPlb_loader" src="' + settings.loadingGif + '" alt="Loading..." /></div><div id="PHPlb_outer"><div id="PHPlb_inner"><a id="PHPlb_close" href="#">close</a><div id="PHPlb_content"><!-- // --></div></div></div>');
					// apply styles to the box and overlay... There might be more soon!
					$('#PHPlb_overlay').css({ backgroundColor:settings.overlayColour });
				}
				
			};
			
			function _positionBox(){
				
				var width = $('#PHPlb_inner').width() + settings.PHPlb_margin*2;
				var windowWidth = $(window).width();
				var height = $('#PHPlb_inner').height() + settings.PHPlb_margin*2;
				var windowHeight = $(window).height();
				var yScroll = parseInt($(window).scrollTop());
				var xScroll = parseInt($(window).scrollLeft());
				if( IEversion < 7 !== false ){
					_fixIE();
				}
				
				$('#PHPlb_outer').css({left:xScroll+"px", top:yScroll+"px"});
				
				if( height >= windowHeight && $('#PHPlb_inner').hasClass('PHPlb_floating_vt') ) {
					$('#PHPlb_inner').css({marginTop:"0", top:"0"}).removeClass('PHPlb_floating_vt');
				}
				if( height <= windowHeight && !$('#PHPlb_inner').hasClass('PHPlb_floating_vt') ) {
					var top = parseInt((windowHeight / 2) + yScroll);
					var yOffset = parseInt(height / 2);
					$('#PHPlb_inner').css({top:"50%", marginTop:"-"+yOffset+"px"}).addClass('PHPlb_floating_vt');
				}
				if( width >= windowWidth && $('#PHPlb_inner').hasClass('PHPlb_floating_hz') ) {
					$('#PHPlb_inner').css({marginLeft:"0", left:"0"}).removeClass('PHPlb_floating_hz');
				}
				if( width <= windowWidth && !$('#PHPlb_inner').hasClass('PHPlb_floating_hz') ) {
					var xOffset = parseInt(width / 2);
					$('#PHPlb_inner').css({left:"50%", marginLeft:"-"+xOffset+"px"}).addClass('PHPlb_floating_hz');
				}
				return true;
			}
			
			function _showContent(){				
				if( _positionBox() ) {
					$('#PHPlb_loader').fadeOut('fast');
					$('#PHPlb_inner').animate({opacity:1}, 250);
				}
			};
			
			function _hideBulge(e){
				// hide the box
				$('#PHPlb_outer').fadeOut(250, function(){
					$('#PHPlb_overlay').fadeOut(250, function(){
						$('#PHPlb_overlay, #PHPlb_outer').remove();
					});
				});
				// destroy window-bound events
				$(window).unbind("resize",_positionBox).unbind("scroll",_fixIE);
				// restore hidden elements
				$('embed, object, select').removeClass("PHPlb_hidden");
				$('body').removeClass('IEfullOverlay');
			};
			
			function _fixIE(){
				$('body').addClass('IEfullOverlay');
				$('#PHPlb_overlay').css({width:$(window).width()+"px", position:"absolute", top:$(window).scrollTop()+"px", left:$(window).scrollLeft()+"px"});
				$('#PHPlb_outer').css({width:$(window).width()+"px", height:$(window).height()+"px"});
			}
		};
				
		return this.unbind('click').click(_initialize);
		
	};
})(jQuery);


///////////////////////////////////////////////////////
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////

