/**
 * rpPopup
 * Basic popup with form validation options.
 * 
 * OPTIONS
 * 
	modal 						Boolean		false									Click on background to close
	popupWidth					Number		null									Popup Width - Overwrites CSS
	popupHeight					Number   	null									Popup Height - Overwrites CSS
	backgroundOpacity			Number		0.7										Opacity of background
	popupId						String		"rp_popup_cont"							Id of popup
	loader						String		"<img src\"/graphics/rp-popup/ajax_loader.gif\" />"	URL of loader Gif
	content						String		""										URL of the content to load
	validationUrl				String		""										URL of the validation page
	callback					Object
		onOpen					Function	null									Function to call on popup open
		onClose					Function	null									Function to call on popup close
		onError					Function	null									Function to call on validate (error)
		onSuccess				Function	null									Function to call on validate (success)
	inputParentRow				String		".form_row"								Class/id of form input parent
	invalidRowClass				String		"invalid_row"							Class to add to form input parent on error
	errorClass					String		"error"									Class of the error message (for removal)
	closeButton					Object
		id						String		"rp_close_button"						Id of close button
		text					String		"text"									String for close button
		hidden					Boolean		false									Hide/show close button
	hideFlash					Boolean		false									Hides the flash when opened
 *
 * BASIC USAGE
 * 
 * var options = {
		content					: "/form.php",
		validationUrl			: "/form.validation.php",
		callback				: {
			onSuccess		: "/success.php"
		}
	};
	$(".popup").rpPopup(options);													Sets popup to open on click
	$.rpPopup.open(options);														Opens popup straight away
	$.rpPopup.close(callback, hideFlash);											Closes open popup
 * 
 * Response from validation page must follow this format and be in JSON:
 * {
	 	'status' 		: "error",													Error/success
		'errors'		: {															Ids of the inputs with errors
			'name'	: true,
			'email'	: true
		}, 
		'feedback'		: "<p class="error">Error Message</p>"						Feedback to display.
 * }
 * 
 * KNOWN ISSUES/TODO
 *
 * Form must have ID!
 * Change ids when you reload a popup
 */
;(function($) {
	
	$.rpPopup = { 'version' : "0.9.3" };
	
	var $backgroundDiv;
	var $closeButton;
	var $popupCont;
	var popupActive = false;

	// Default options
	$.rpPopup.defaults = {
		modal						: false,
		popupWidth					: null,
		popupHeight					: null,
		backgroundOpacity			: 0.7,
		popupId						: "rp_popup_cont",
		loader						: "<img src=\"/graphics/rp-popup/ajax-loader.gif\" />",
		content						: "",
		validationUrl				: "",
		callback					: {
			onOpen		: null,
			onClose		: null,
			onError		: null,
			onSuccess	: null
		},
		inputParentRow				: ".form_row",
		invalidRowClass				: "invalid_row",
		errorClass					: "error",
		closeButton					: {
			content		: "Close",
			hidden		: false,
			id			: "rp_close_button"
		},
		hideFlash		: false
	};
	
	
	$.fn.rpPopup = function(opts)
	{
		var options = $.extend(true, {}, $.rpPopup.defaults, opts);
		var $this = $(this);
		
		// Click to open
		$this.click(function()
		{	
			openPopup(options);
			return false;
		});

	};
	
	function openPopup(options)
	{
		// Check if a popup is already open
		// If it is, we can just reload the content
		if (!popupActive)
		{
			// Create Items
			$backgroundDiv = $('<div id="rp_popup_background" />')
				.appendTo($(document.body))
				.css({
					 "opacity" : options.backgroundOpacity
				});
			$popupCont = $('<div id="' + options.popupId + '" />')
				.appendTo($(document.body));

			// Background click to close
			$backgroundDiv.click(function()
			{
				if (!options.modal)
					$.rpPopup.close(options.callback.onClose, options.hideFlash);
				return false;
			});
			
			$(window).resize(function() 
			{
				if (popupActive)
				{
					centrePopup(options.popupWidth, options.popupHeight);
				}
			});
			
			// Hide the flash 
			(options.hideFlash) ? $('object, embed').css('visibility', "hidden") : null;
			popupActive = true;
			$backgroundDiv.fadeIn("fast");
			$popupCont.css({
				"display"	: "block",
				"opacity"	: 0
			}).animate({
				opacity		: 1
			}, "fast");
		}
		
		var $loader = $(options.loader);
		$popupCont.html($loader);
		centrePopup(options.popupWidth, options.popupHeight);
			
		if (options.content)
		{
			$popupCont.load(options.content, function(data)
			{
				$closeButton = $('<a id="' + options.closeButton.id + '" href="#">' + options.closeButton.content + '</a>');
				if (!options.closeButton.hidden)
					$closeButton.appendTo($popupCont);
			
				// Close button click
				$closeButton.click(function()
				{
					$.rpPopup.close(options.callback.onClose, options.hideFlash);
					return false;
				});
				
				$closeButton.fadeIn("fast");
				
				var $content = $(data);
				if ($content.find("form").length > 0)
				{
					var $form = $("#" + $content.find("form").attr("id"));
					$form.submit(function(event)
					{
						$content.prepend($loader);
						centrePopup(options.popupWidth, options.popupHeight);
						
						if (options.validationUrl)
						{
							$.post(options.validationUrl, $form.serialize(), function(response){
								// Remove any errors
								$(options.inputParentRow).removeClass(options.invalidRowClass);
								$form.find("." + options.errorClass).remove();
								$loader.remove();
								
								if(response.status == "error") 
								{
                                    if (response.errors)
                                    {
                                        $.each(response.errors, function(key){
                                            $('#' + key).parents(options.inputParentRow).addClass(options.invalidRowClass);
                                        });
                                    }
			
									$form.prepend(response.feedback);
									(options.callback.onError) ? options.callback.onError() : null;
								}
								else
								{
									(options.callback.onSuccess) ? options.callback.onSuccess() : null;
									if (response.feedback)
										$form.before(response.feedback).remove();
								}
								centrePopup(options.popupWidth, options.popupHeight);
								
							}, "json");
						}
						else
						{
							debug("No validationUrl supplied");
						};
						return false;
					});
				}
				centrePopup(options.popupWidth, options.popupHeight);
				(options.callback.onOpen) ? options.callback.onOpen() : null;
			});
		}
		else
		{
			$popupCont.html("<p style=\"background:#fff;padding:10px;width:150px;text-align:center\">No content can be loaded</p>");
			centrePopup(150, 100);
			debug("No content to load");
		}
		
	}
	
	// Opening the popup
	$.rpPopup.open = function(opts)
	{
		var options = $.extend(true, {}, $.rpPopup.defaults, opts);
		openPopup(options);
	}
	
	// Closing the popup
	$.rpPopup.close = function(callBack, hideFlash)
	{
		(hideFlash) ? $('object, embed').css('visibility', "visible") : null;
		if (popupActive)
		{
			popupActive = false;
			$backgroundDiv.fadeOut("fast");
			$popupCont.fadeOut("fast");
			$closeButton.fadeOut("fast", function() {
				$backgroundDiv.remove();
				$popupCont.remove();
				$closeButton.remove();
				(callBack) ? callBack() : null;
			});
		}
	}
	
	// Centering the popup
	centrePopup = function(pW, pH)
	{
		var popupWidth = pW ? parseInt(pW) : $popupCont.children().outerWidth();
		var popupHeight = pH ? parseInt(pH) : $popupCont.children().outerHeight();
		var windowWidth = document.documentElement.clientWidth;
		var windowHeight = document.documentElement.clientHeight;
		
		$popupCont.css({
			"top"		: windowHeight / 2 - popupHeight / 2,
			"left"		: windowWidth / 2 - popupWidth / 2
		});
		// only need force for IE6
		$backgroundDiv.css({
			"height": windowHeight
		});
	}
	
	// Debug - so IE doesn't have a fit
	function debug(value)
	{
		if (window.console && window.console.log)
		{
			console.log(value);
		}
	}

})(jQuery);
