//	 the plugin script
(function($) {

	//	the static elements
	var parent, siblings = [], thisPos, element = {}, visible = false;
	
	//	the defaults
	$.intervene = {
		defaults: {
			
			overlayOpacity: 	0.5,
			interveneOpacity: 	0.9,
			arrowOpacity: 		0.9,
			inSpeed:			250,
			outSpeed:			250,
			show:				'click',
			hide:				'',
			title:				'',
			content:			'',
			url:				'',
			width:				400,
			height:				400,
			useArrows:			true,
			didShow:			function(){}		//	callback
		}
	};
	
	$.fn.extend({
		intervene: function(options) {
			var settings = $.extend({},
				$.intervene.defaults,
				options);
			
			//	initialize	
			init(settings);

			return this.each(function() {
			
				if( settings.show == 'now' ) {
					show(settings);
				}
				
				//	do something for each
				$(this).bind(settings.show, function() {
				
					parent = $(this);
					
					//	populate the siblings array with all
					//	elements with the same rel of parent
					//	this includes parent (to determine position)
					var parentRel = $(parent).attr('rel');
					if( parentRel != "intervene" && parentRel != '' ) {
					
						var siblingsCount = 0;
						siblings = new Array();
						$('a').each(function() {
							if( $(this).attr('rel') == parentRel ) {
								siblings[siblingsCount] = $(this);
								siblingsCount ++;
							}
						});
					} else {
						siblings = new Array();
					}
				
					//	do intervention...
					show(settings);
					return false;
					
				});
				
				if( settings.hide != '' ) {
					$(this).bind(settings.hide, function() {
						//	hide intervention
						hide(settings);
					});
				}
				
			});

		}
	});
	
	//	create the tooltip originally
	function init(settings) {
	
		//if the tooltip exists, don't initialize
		if( element.intervene )
			return;
		
		//	create all the necessary elements, append & hide	
		element.intervene 	= $('<div id="intervene"></div>').appendTo(document.body);								//	popup
		element.close 		= $('<a href="#/close" id="interveneClose">close</a>').appendTo(element.intervene);		//	close btn
		element.arrows		= $('<div id="interveneArrows"><a href="#left" id="interveneLeftArrow">Left</a><a href="#right" id="interveneRightArrow">Right</a></div>').
			appendTo(document.body);																				//	the arrow holder
			element.leftArrow = $('#interveneLeftArrow', element.arrows);											//	the left arrow
			element.rightArrow = $('#interveneRightArrow', element.arrows);											//	the right arrow
		element.loader 		= $('<div id="interveneLoader"></div>').appendTo(element.intervene);					//	loader icon
		element.content 	= $('<div id="interveneContent"></div>').appendTo(element.intervene);					//	content
		element.overlay 	= $('<div id="interveneOverlay"></div>').appendTo(document.body);						//	overlay
		element.offscreen 	= $('<div id="interveneOffscreen"></div>').appendTo(document.body);						//	secret section
		
		//	bind both scrolling and resizing to move the overlay
		//	and the close button
		$(window).bind('resize', windowDidResize);
		$(window).bind('scroll', windowDidScroll);
		$(element.close).bind('click',function() {
			hide(settings);
			return false;
		});
		
		//	close if they click the overlay
		$(element.overlay).bind('click',function() {
			hide(settings);
			return false;
		});
		
		//	set the padding of the off screen element
		$(element.offscreen).css({
			padding: $(element.intervene).css('padding')
		});
		
		//	bind the arrows
		$(element.leftArrow).bind('click',function() {
			$(element.content).animate({opacity: 0},settings.outSpeed);
			$(element.close).animate({opacity: 0},settings.outSpeed);
			$(element.arrows).animate({opacity: 0},settings.outSpeed);
			$(siblings[thisPos - 1]).click();
			return false;
		});
		
		$(element.rightArrow).bind('click',function() {
			$(element.content).animate({opacity: 0},settings.outSpeed);
			$(element.close).animate({opacity: 0},settings.outSpeed);
			$(element.arrows).animate({opacity: 0},settings.outSpeed);
			$(siblings[thisPos + 1]).click();
			return false;
		});
	}
	
	function windowDidResize() {
		if( visible ) {
			//	resize the overlay
			$(element.overlay).css({height: $(window).height(), width: $(window).width(), top: $(window).scrollTop()});
			//	reposition the intervention
			centerIntervention();
			
		}
	}
	
	function windowDidScroll() {
		if( visible ) {
			//	reposition the top
			$(element.overlay).css({top:$(window).scrollTop()});
			//	reposition the intervention
			centerIntervention();
		}
	}
	
	function resizeOverlay() {
		if( visible ) {
			windowDidResize();
			windowDidScroll();
		}
	}
	
	function centerIntervention() {
		var width = $(element.intervene).width();
		var height = $(element.intervene).height();
		var topOffset = ( $(window).height() / 2 ) - ( $(element.intervene).height() / 2 ) + $(window).scrollTop();
		var leftOffset = ( $(window).width() / 2 ) - ( $(element.intervene).width() / 2 );
		
		var padding = parseInt( $(element.arrows).css('padding-right').replace('px','') );
				
		$(element.intervene).css({top:topOffset, left:leftOffset});
		$(element.arrows).css({ top: topOffset, left: leftOffset - $(element.leftArrow).width(), width: $(element.intervene).width() + ($(element.leftArrow).width() + $(element.rightArrow).width() ) +  padding });
	}
	
	function show(settings) {
		
		//	set to visible or the resizing won't work
		visible = true;
		
		$(element.content).css({ display: 'block' });
		$(element.close).css({ display: 'block' });
		$(element.intervene).css({ display: 'block' });
		$(element.overlay).css({ display: 'block' });
		$(element.arrows).css({display: 'block'});
		
		//	resize the overlay by triggering the 
		//	scroll / resize events
		resizeOverlay();
			
		//	start by animating the overlay	
		$(element.overlay).animate({ opacity: settings.overlayOpacity }, settings.inSpeed,function() {
			centerIntervention();
			
			$(element.intervene).animate({
				opacity: settings.interveneOpacity
			}, settings.inSpeed, function() {
				
				//	show the loader gif
				$(element.loader).css({ display: 'block'});
				$(element.loader).animate({ opacity: 1.0}, settings.inSpeed);
				
				var href;
				
				//	loading the content
				if( $(parent).attr('href') != '' )
					href = $(parent).attr('href');
				
				//	if we're just doing a simple message
				if( settings.content != '' ) {
					
					$(element.offscreen).html(settings.content);
					resizeAndShow(settings);
				
				//	we're loading ajax content
				} else if( settings.url != '' || ( href != '' ) ) {
				
					var url;
					
					//	if its an a, we can use the href
					if( $(parent).attr('href') != '' )
						url = $(parent).attr('href');
					
					//	unless they've specified a different url
					if( settings.url != '' )
						url = settings.url;
					
					//	is it an image?
					if( url.match('.jpg|.gif|.png|.bmp$') ) {
						var img = new Image();
						img.src = $(parent).attr('href');
						
						$(img).load(function(e) {
							$(element.offscreen).html('<img src="'+$(parent).attr('href')+'" />');
							resizeAndShow(settings);
						});
					
					//	it's just content
					} else {
					
						$.ajax({
							url:	url,
							success:function(html) {
								$(element.offscreen).html(html);
								resizeAndShow(settings);
							}
						});
					}
				}
			});	
		});
	}
	
	function resizeAndShow(settings) {
		
		var content = $(element.offscreen).html();
				
		//	get the dimensions of that offscreen element
		var newWidth = $(element.offscreen).width();
		var newHeight = $(element.offscreen).height();
		
		//	now we animate the intervention to the new height and new width	
		var interveneOffset = $(element.intervene).offset();
		var topOffset = ( $(window).height() / 2 ) - (newHeight / 2) + $(window).scrollTop();
		
		//	hide the loader gif
		$(element.loader).animate({ opacity: 0}, settings.inSpeed);
		
		//	animate the height
		$(element.intervene).animate({ height: newHeight, top: topOffset}, settings.inSpeed, function() {
		    
		    //	animate the width
		    var leftOffset = ( $(window).width() / 2) - (newWidth / 2);
		    
		    $(element.intervene).animate({width: newWidth, left: leftOffset}, settings.inSpeed, function() {
		    	
		    	//	now add and show the contents
		    	$(element.content).html(content);
		    	$(element.offscreen).html('');
		    	$(element.content).animate({ opacity: 1.0}, settings.inSpeed,function() {
		    		$(element.close).animate({ opacity: 1.0},settings.inSpeed);
		    		
		    		var interventionOffset = $(element.intervene).offset();
		    		var padding = parseInt( $(element.arrows).css('padding-right').replace('px','') );
		    		
		    		//	and finally, show the arrows
		    		
		    		//	do we need the arrows?
		    		if(siblings.length > 1 || !settings.useArrows) {
		    			
		    			for(var i=0; i<siblings.length; i++) {
		    				if( siblings[i].get(0) == $(parent).get(0) ) {
		    					thisPos = i;
		    				}
		    			}
		    			
		    			//	set the left arrow	    			
		    			if( thisPos <= 0 ) 
		    				$(element.leftArrow).css({display:'none'});
		    			else
		    				$(element.leftArrow).css({opacity:settings.arrowOpacity, display: 'block'});
		    			
		    			//	set the right arrow	
		    			if( thisPos >= siblings.length - 1 )
		    				$(element.rightArrow).css({display:'none'});
		    			else
		    				$(element.rightArrow).css({opacity:settings.arrowOpacity, display: 'block'});
		    		
		    			//	animate the arrows
		    			$(element.arrows).css({ top: interventionOffset.top, left: interventionOffset.left - $(element.leftArrow).width(), width: $(element.intervene).width() + ($(element.leftArrow).width() + $(element.rightArrow).width() ) +  padding });
		    			$(element.arrows).animate({opacity: settings.arrowOpacity}, settings.inSpeed);
		    		} else {
		    			$(element.arrows).css({display:'none'});
		    		}
		    		$(element.loader).css({ display: 'none'});
					settings.didShow.call(this);
		    	});
		    });
		});
	}
	
	function hide(settings) {
		$(element.content).animate({opacity: 0},settings.outSpeed);
		$(element.close).animate({opacity: 0},settings.outSpeed);
		$(element.intervene).animate({opacity: 0},settings.outSpeed);
		$(element.arrows).animate({opacity:0},settings.outSpeed);
		$(element.overlay).animate({opacity: 0},settings.outSpeed, function() {
			$(element.content).css({ display: 'none' });
			$(element.close).css({ display: 'none' });
			$(element.intervene).css({ display: 'none' });
			$(element.overlay).css({ display: 'none' });
			$(element.arrows).css({display: 'none'});
		});
	}
		
}) (jQuery);

//	apply the intervention easily
function applyIntervene() {
	$('a').each(function() {
		var rel = $(this).attr('rel');
		if( rel.match('intervene') ) {
			$(this).intervene();
		}
	});
}
//	do an easy alert using the intervene
function interveneAlert( content ) {
	$(document).intervene({
		show:	'now',
		content:content
	});
}
