/**
 * TinyMCE pop-up editor.
 * 
 * Allow the editor to place small pop-ups inside the text.
 * 
 * Requirements
 * 
 * - Custom TinyMCE block formatting style (.popup)
 * 
 * - Each .popup element must contain one <a name="mypopup"> anchor
 * 
 * - These anchors can be referred document interlinks as as <a href="#mypopup">
 *
 * - Each pop-up will have <button> of CSS class popup-close-button automatically created
 *  
 * 
 * @author Mikko Ohtamaa <mikko@mfabrik.com>
 * 
 * @copyright 2010 mFabrik Research Oy
 * 
 * http://mfabrik.com
 * 
 */


// Declare namespace
popup = {};

// List of <a name="anchorname"> anchors inside the pop-up blocks
popup.names = [];

// Name -> jQuery object mapping of pop-up HTML elements
popup.targets = {};


// Some settings
// You can dynamically override them in a custom <script> initializer 

// Which CSS selector we use to look-up pop-ups
popup.popupSelector = ".popup";

// Which CSS class will be used for automatically generated close buttons
popup.closeButtonClass = "popup-close-button";

// Label to the close button
popup.closeButtonLabel = "X";


/**
 * Our internal debug logger.
 * 
 * @param {Object} msg
 */
popup.log = function(msg) {
	if(window.console) {
		console.log(msg);
	}
}

popup.resolveAnchors = function() {
	jQuery(popup.popupSelector + " a").each(function() {
	       var a = jQuery(this);
	       var name = a.attr("name").toLowerCase();
	       popup.names.push(name);	
	       popup.targets[name] = a.parent();
	});

    popup.log("Found " + popup.names.length + " pop-up blocks");
}

/**
 * Apply onclick handler to links pointing to pop-ups to open the pop-up instead.
 * 
 * Check if link refers to internal pop up and if it does,
 * fix its onclick.
 */
popup.installSpecialLinkHandlers = function() {
	
	var installed = 0;
	
	jQuery("a").each(function() {
		var a = jQuery(this);
                var i = 0;
		for(i=0; i<popup.names.length; i++) {
			
			var href = a.attr("href");
                        
			// Make sure this is a pointing link
			if (href) {
				// do case-insensitive link target comparison
				var target = popup.names[i];
						
				href = href.toLowerCase();
				//popup.log(a.attr("href") + " " + target);
				
				if (href == "#" + target) {
					var popupElement = popup.targets[target]; 
					popup.installHandler(a, popupElement, target);
					installed++;
				}
			}
		}
	});
	
	popup.log("Installed " + installed + " click handlers");
}

/**
 * Click callback to perform the actual pop-up opening.
 */
popup.openPopUp = function(clicked, popUpElem, popUpName) {
	
	// Clear all existing pop-ups
	jQuery(".popup").hide();
	
	// Move the referred pop-up below the element
	popUpElem.detach();
	
	// Resolve meaningful parent where we can
	// attach the pop-up
	var parents = clicked.parents();

	var goodParent = null;
	var goodSibling = null;
	
	popup.log(clicked);
	
	// List of tags under which we can attach block elements
	var goodTagNames = ["table"];
	
	// Helper function to check the tag against known good block elements
	function isGoodTagName(name) {
		var i;
		name = name.toLowerCase();
		for(i=0; i<goodTagNames.length; i++) {
			if(name == goodTagNames[i]) {
				return true;
			}
		}
		return false;
	}
	
	
	
	for(var i=0; i<parents.length;i++) {
		var parent = parents[i];

		if(isGoodTagName(parent.tagName)) {
			popup.log("Good parent:" + parent);
                        goodSibling = parent;
			break;			
		}
		
	}
	
	goodSibling = jQuery(goodSibling);
	
	popUpElem.insertAfter(goodSibling);
	
	// Make pop-up visible
	popUpElem.slideDown();
}

/**
 * Click callback for pop-up close button
 * 
 */
popup.closePopUp = function() {
	
	// Select all open pop-ups 
	var popups = jQuery(popup.popupSelector);
	
	popups.slideUp();
}

/**
 * Create Close button to the pop-up window if none exists.
 * 
 * For the editor person convenience we do not create close buttons
 * individually for each pop-up element in TinyMCE, but 
 * automatically generate them for all pop-ups during the initializatio.
 * 
 * @param {Object} popUp jQuery object for pop-up window elements 
 */
popup.installCloseButtons = function() {
	
	var popups = jQuery(popup.popupSelector);
	
	var button = jQuery("<button>", { "class" : popup.closeButtonClass});	
	
	button.text(popup.closeButtonLabel);
	
	// Element which closes floats inside the pop-up
	var floatCloser = jQuery("<div>", { "style" : "clear: both"});

	// Append button to each pop-up box
	// It will be at the top
	popups.prepend(button);
	
	// This will take care of that our floating close button does not cause
	// havoc on the page 
	popups.append(floatCloser);
	
	// Then install close handlers
	jQuery("." + popup.closeButtonClass).click(popup.closePopUp);
}

/**
 * Fix link onclick
 */
popup.installHandler = function(clicker, popUp, popUpName) {
		
    // closures FTW
	clicker.click(function() {
	    popup.openPopUp(clicker, popUp, popUpName);
		return false;
	});
}

/**
 * Install pop-up jQuery code and event handlers.
 * 
 * Provided as a separate method if you want to run this in  a custom initialization point
 * (not document.ready)
 */
popup.bootstrap = function() {
    popup.resolveAnchors();	
	popup.installSpecialLinkHandlers();
	popup.installCloseButtons();
	
}
/**
 * Perform DOM fix when the DOM content has been loaded
 */
jQuery(document).ready( function() {
	popup.bootstrap();
});

