/*
	simple_modal_window v0.1.0
	
	Is what it says it is.
	Created for use with event delegation rather then jQuery
	selector bullshit.
	
	
	Usage
		
		
		include css, jquery, and this plugin
		in your script.js where you do your event delegation:
		
		if(target matches required attributes)
		{
			$.fn.simple_modal_window(target,{delay:200});
			event.preventDefault();	// or whatever else you do
		}
		
		
		Or if you're still using jquery to handle clicks for
		whatever reason, use this inside your jQuery
		document.ready function:
		
		$('whatever you want to click').click(function(event)
		{
			var target = event.target || event.srcElement;
			$.fn.simple_modal_window(target,{delay:200});
			event.preventDefault();	// or whatever else you do
			
		});
		
		
		In your HTML, you need to include a 'rel' attribute
		to tell simple_modal_window what type of data you're
		linking.
		
		Hopefully in the next version it will intelligently
		figure that out, but for the time being a few characters
		wont kill you.
		
		
		In this example, I am matching the .simple_modal_window
		when calling the event:
		
		<a href="http://www.youtube.com/watch?v=DHmYC8a_4cI" class="simple_modal_window" rel="video">a youtube link</a>
		<a href="image.jpg" class="simple_modal_window" rel="image">an image</a>
		<a href="ajax_page.html" class="simple_modal_window" rel="html">an ajax page</a>
		
		At the moment it handles images, ajax pages (i.e. php, html, whatever),
		and vimeo/youtube links (although you need to be careful with these)
		
		
	Parameters
	
	
		delay:	the delay between animating states, in milliseconds
		
		min_top:	the minimum distance the box will position
					itself to the top of the window, in pixels
		
	Additional
	
		
		This plugin is made to use event delegation. It's
		better then attaching 5000 listeners so you should
		learn how to use it.
		
		HTML inline with JavaScript is a bad idea and
		should be avoided. Because of this I've included
		"//i can haz magic here" comments where any inline
		html (which is here in the interest of making this
		a stand alone plugin) is so you can use icanhaz.js
		or whatever other templating thingy to seperate the
		HTML and JavaScript.
		
	
	MIT License,	
	David Lumley	30/06/2011
*/

(function($) {
	$.fn.simple_modal_window = function(target, options) {
		
		$body = $('body');
		$window = $(window);
		$target = $(target);
		
		var defaults = {
			delay			:	500,
			min_top			:	100
		};

		//	Uses backbone's faster method if available because
		//	we need to do this everytime a link is clicked.
		if(typeof _ !== 'undefined' && typeof _.extend === 'function') {
			options = _.extend(defaults, options);
		} else {
			options = $.extend(defaults, options);
		}
		
		var states = {
			simple_modal_mask	:		false,
			simple_modal_loader	:		false,
			simple_modal_window	:		false
		}
		
		var methods = {	
		
			destroy_mask	:	function()	{
				states.simple_modal_mask = false;
				$mask.fadeOut(options.delay, function(){
					$mask.die('click');
					$mask.remove();
				});
				
				if(states.simple_modal_loader) {
					methods.destroy_loader();
				}
				
				if(states.simple_modal_window) {
					methods.destroy_window();
				}
			},
			
			destroy_loader	:	function(instant) {
				states.simple_modal_loader = false;
				if(instant)
				{
					$loader.remove();
				} else {
					$loader.fadeOut(options.delay, function(){
						$loader.remove();
					});
				}
			},
			
			destroy_window	:	function()	{
				states.simple_modal_window = false;
				$modal_window.fadeOut(options.delay, function(){
					$modal_window.find('#simple_modal_close').die('click');
					$modal_window.remove();
				});
			},
			
			handle_keydown	:	function()	{
				if (event.keyCode == 27) methods.destroy_mask(); 
			},
			
			center_object	:	function($object) {
				var top = methods.offset_top($object);
				var left = methods.offset_left($object);
				
				$object.css({
					'top'	:	top,
					'left'	:	left
				});
			},
			
			offset_top		:	function($object) {
				var top = $window.height()/2 - $object.height()/2 + $window.scrollTop();
				if (top < options.min_top) top = options.min_top;
				return top;
			},
			
			offset_left		:	function($object) {
				var left = $window.width()/2 - $object.width()/2;
				return left;
			},
			
			error_content	:	function()	{
				
				//	i can haz magic here
				return	'<p>The request content cannot be loaded.</p><p>Please try again later.</p>'
			},
			
			create_window	:	function(content) {
				methods.destroy_loader(true);
				
				//	i can haz magic here
				_window = ich.simple_modal_window();

				$modal_window = $(_window);
				$body.append($modal_window);
				$modal_window = $('div#simple_modal_window');
				
				$modal_window.find('div#simple_modal_content').html(content);
				methods.center_object($modal_window);
				
				$modal_window.find('img#simple_modal_window_close').live('click', function(){
					methods.destroy_mask();
				});
		
				$modal_window.fadeIn(options.delay);
				states.simple_modal_window = true;
			}
		}
		
		
		//	Prevents the modal window from being created if 
		//	it hasn't been removed yet.
		
		if (!states.simple_modal_mask && !states.simple_modal_loader && !states.simple_modal_window) {	
			states.simple_modal_mask = true;
			
			//	i can haz magic here
			mask = ich.simple_modal_mask();
			$mask = $(mask);
			$body.append($mask);
			$mask = $('#simple_modal_mask');
			$mask.css({'height' :	function(){
								    return Math.max(
							    	    $(document).height(),
								        $(window).height(),
									        /* For opera: */
								        document.documentElement.clientHeight	
								    );
									}
			});
		
			$mask.fadeIn(options.delay);
			
		
			states.simple_modal_loader = true;
			
			//	i can haz magic here
			loader = ich.simple_modal_loader();
			$loader = $(loader);
			$body.append($loader);
			$loader = $('#simple_modal_loader');
		
			$loader.fadeIn(options.delay);
			
			methods.center_object($loader);
		
			$mask.live('click', function(){
				methods.destroy_mask();
			});
			
			
			//	Find the type of content to display
			//	If you want to change window functionality or add content
			//	types, this is the place to do it.
			
			
			
			
			function get_image(target)	{
				var content = "<img src='"+target.href+"' id='simple_modal_window_img'>";
				$caption = $(target).find('.simple_modal_window_caption').html();
				if ($caption.length > 0)
				{
					content+= "<div id='simple_modal_window_caption'>"+$caption+"</div>"
				}
				return content;
			}
			
			function get_video(target)	{
				if (target.href.indexOf("youtube") > 0) {
					var youtube_link = target.href.split("v=");
					var content = '<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/'+youtube_link[1]+'" frameborder="0" allowfullscreen></iframe>';
				} else if (target.href.indexOf("vimeo.com") > 0) {
					var vimeo_link = target.href.split("com/");
					var vimeo_link = vimeo_link[1].split("?");
					var content = '<iframe src="http://player.vimeo.com/video/'+vimeo_link[0]+'?title=0&amp;byline=0&amp;portrait=0" width="400" height="300" frameborder="0"></iframe>';
				} else {
					var content = methods.error_content();
				}
				
				return content;
			}
			
			function get_html(target) {
				
				$.ajax({
					url:	target.href,
					dataType:	'html',
					success:	function(data){
						methods.create_window(data);
						methods.center_object($modal_window);
						
					},
					error:		function(data){
						content = methods.error_content();
						methods.create_window(content);
						methods.center_object($modal_window);
					}
				});
			}
			
			switch($target.attr('rel')) {
				case 'video':	content = get_video(target);
								methods.create_window(content);
								break;
				case 'image':	content = get_image(target);
								methods.create_window(content);
								$modal_window.find('img#simple_modal_window_img').load(function()
								{
									methods.center_object($modal_window);
								});
								break;
								
				case 'html':	get_html(target);
								break;
								
				default:		content = methods.error_content();
								methods.create_window(content);
			}
			
			$(document).keydown(methods.handle_keydown);
		}
	}

})(jQuery);
