/*
 * AT_lightbox.js - A jQuery Plugin
 * A jQuery plugin for creating Lightboxes.
 *
 * By Andy Tennison (andrew@tennisons.com / http://www.tennisons.com)
 *
 * Version 1.0.1
 * October 14th, 2009
 *
 * Copyright (c) 2009 Andy Tennison
 * Dual licensed under the MIT and GPL licenses.
*/

(function($) {
	$.fn.AT_lightbox = function(options) {
		var opts = $.extend({}, $.fn.AT_lightbox.defaults, options);
		
		$('body').append('<div id="bg"></div><div id="lb"></div><a href="#close" id="lb_close"></a><div id="lb_temp"></div>')	
		var $BG = $('#bg');
		var $LB = $('#lb');
		var mL = parseFloat($LB.css('marginLeft'));
		var $TEMP = $('#lb_temp');
		var title = ' to '+$('h2:first').text();
		var thisLink;
		
		var G = {
			content : ''
		};
		
		$BG.click(function(e){
			e.preventDefault();
			closeLB()
		});
		$(document).keyup(function(e){
		    if (e.keyCode == 27) {
		        closeLB()
		    }
		});

			
		function backButton(){							//function needed as button is dynamically created
			$LB.find('#lb_back').click(function(e){
				e.preventDefault();
				closeLB();
			})
		};
		
		function showLB(){								// show lightbox - animation 
			$BG.fadeIn(200);
			$LB.fadeIn(200);
		};
		
		function closeLB(){
			$BG.hide();
			$LB.empty().hide().attr('style','');
			$TEMP.empty();
			thisLink.focus();
		};
		
		return this.each(function(i){
			var $link = $(this);
			if($('.lb').length){
				$link.append('<span class="lb_view_icon">&nbsp;</span>');
			}
			
			$link.click(function(e){
				e.preventDefault();
				thisLink = $link;

				// set Lightbox elements
				$BG.css({'height':$(document).height(),opacity:0.7});				
				$LB.css({'top':$().scrollTop()+50});
				var href = $link.attr('href');
				var inner;
				
				if(href.match('.jpg') || href.match('.jpeg')){
					alert('link to image - error, should be in page')
				} else if(href.match('#') || href == ''){
					alert('broken link')
				} else if(href.match('.html') || href.match('.htm') || href.match('.xhtml') || href.match('.aspx') || href.match('.php')){
					inner = opts.inner;
					showLB();
					getContent(href,inner);
				};
			});
			
			function getContent(h,i){
				//console.log(h+' / '+i)
				$.ajax({
					url:h,
					success: function(data){
						var content = $(data).find(i).html();
						G.content = content;
						$TEMP.append(content);
						
						var x, y, t, flashPresent;
						var end = 0;
						time(x, y, t, end, flashPresent, content)
					}
				})
			};
			
			// checks content loaded by looking at size
			function time(x, y, t, end, flashPresent, content){
				x = $TEMP.width();
				y = $TEMP.height();

				if(end >= 10){											// if end count = 10 = 10 seconds, stop function
					clearTimeout(t);
					closeLB();
				}else if($TEMP.find(opts.flashName).length){			// if there is a flash video on the page
					//alert('flash on page')
					x = opts.flashVideo_width; 
					y = opts.flashVideo_height;
					flashPresent = true; //use this later to call SWFobject
					clearTimeout(t);
					animate(x,y+40,t,flashPresent,content);
				}else if (x <= opts.minWidth || y <= opts.minHeight) {	// if smaller than default loop
					end=end+1;
					t=setTimeout(time,1000);
				} else {
												// bigger than default stop then animate
					clearTimeout(t);
					if (x >= 940){x=940}
					/*if (y >= $(window).height()-40){y = $(window).height()-140}*/
					animate(x,y,t,flashPresent,content);
				}
			}; // end time()
			
			
			// animates lightbox
			function animate(x,y,t,flashPresent,content){
				
				if($(document).height() < $LB.offset().top+y){
					$BG.css({'height':$LB.offset().top+y +80});
				};

				$LB.animate({width:x, height:y, marginLeft:(-mL-x/2)},200, function(){
					$LB.append('<div id="inner"></div>')
					$LB.find('#inner')
						.css({'opacity':0})
						.append(G.content)
						.append('<a id="lb_back" class="btn" href="#back">Close<span class="tl"></span><span class="tr"></span><span class="bl"></span><span class="br"></span></a>')
						.animate({opacity:1},1000, function(){
							$LB.css({'background':'#fff'})
						});
					
					if(flashPresent){						
						var flashvars = {
							videoUrl: $('#video').find('a').attr('href'),
							//videoUrl: "/media/Flash/seeding1.flv",
							videoTitle: " "
						};
						var params = {};
						var attributes = {};
						swfobject.embedSWF("/media/Flash/HeinzFlashVideoPlayer.swf", "video", opts.flashVideo_width, opts.flashVideo_height, "9.0.0","/media/Flash/expressInstall.swf", flashvars, params, attributes);
					};
					$LB.find('#lb_back').focus();
					backButton();
				})

				// if lightbox i bigger than window, content scolls, otherwise stays center							
				if (y <= $(window).height()-40){
					LBscroll(t)
				}
				
				$('#lb_close').focus(function(){
					//console.log('focus on close. now close')
					closeLB();
				});					
			}; //end animate()
			
			
			// when scrolled, checks if dist to top is same after x secs, then animates, if not counts again.
			function LBscroll(t){
				$(window).scroll(function(){
					var top = $().scrollTop();
					//console.log(top)
					count();
					function count(){
						clearTimeout(t);
						t=setTimeout(checkH,opts.tuneScrollSpeed);
					
						function checkH(){
							if($().scrollTop() == top){
								$LB.animate({top:$().scrollTop()+50},{duration: 600, easing: 'easeOutCubic'})
							}else{
								count();
							}
						};
					};
				});
			}; // end newScroll()
				
		}); // end LB
		
		
	}; // end plugin AT_lightbox


// end of closure
})(jQuery);

$.fn.AT_lightbox.defaults = {
	test: 'test',
	inner: '#primary',
	minWidth: 200,			// min-width of image content - used to check load is complete
	minHeight: 200,			// same for width - only change if loading images smaller than this
	tuneScrollSpeed: 300,	// milliseconds
	flashName:'#video',		// id that is used to load flash through SWFobject
	flashVideo_width: 522,	// width of flash video
	flashVideo_height: 360	// height of flash video
};

