/**
 * JavaScript to run the content builder editor.
 *
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @package clearFusionCMS
 * @copyright Copyright (c) 2014 - 2016 clearFusionCMS. All rights reserved.
 * @link http://clearfusioncms.com
 */

(function() {

	var activeEditor = undefined;

	/**
	 * Setup the content builder editor to convert to/from a popup.
	 *
	 * @param string imageBrowser The path to the image browser or undefined if not used.
	 * @param string fileBrowser The path to the file browser or undefined if not used.
	 * @param string snippetSrc The path to load snippets from.
	 * @param string iconsSrc The path to load icons from.
	 * @param string dialogSrc The path to load the dialogs from.
	 * @param string categories The Array of block categories.
	 * @return fusionLib This object.
	 */
	$.fn.contentbuilderCreate = function(imageBrowser, fileBrowser, snippetSrc, iconsSrc, dialogSrc, categories) {

		// Bind activation click handler to each editor
		return this.each(function() {

			// Copy content from textarea and hide
			var tarea = $('#' + $(this).attr('data-textarea')),
				editor = $(this);

			editor.html(tarea.val());
			tarea.hide();

			// Attach handler to form submit to copy data back to textarea
			$(tarea.get(0).form).submit(function() {
				tarea.val(editor.data('contentbuilder').html());
			});

			// Watch for a click and create editor
			editor.click(function() {
				if(!editor.hasClass('contentbuilderActive')) {
					$('.contentBuilderEditRegion').removeClass('contentbuilderActive');
					editor.addClass('contentbuilderActive');
					activeEditor = editor;
					updateToolbarPosition();

					$('#contentbuilderOverlay').show();
					$('#lnkToolOpen').show().trigger('click');
					$('#rte-toolbar').show();
					$('#contentbuilderClose').show();

					// Replace dialog selector
					$('#ifrHeadings').attr('src', dialogSrc + '?dialog=headings.html');
					$('#ifrFonts').attr('src', dialogSrc + '?dialog=fonts.html');
					$('#ifrFontSize').attr('src', dialogSrc + '?dialog=fontsize.html');
				}
			}).contentbuilder({
				zoom: 1,
				enableZoom: false,
				snippetFile: snippetSrc,
				iconselect: iconsSrc,
				imageselect: imageBrowser,
				fileselect: fileBrowser,
				imageEmbed: false,
				snippetTool: 'left',
				snippetCategories: categories
			});
		});
	};

	function updateToolbarPosition() {
		if(typeof activeEditor !== 'undefined') {

			var appbar = $fl('.appbar'),
				appbarHgt = 0;

			if(appbar.length) {
				appbarHgt = appbar.height() +
					parseInt(appbar.css('padding-top')) +
					parseInt(appbar.css('padding-bottom'));
			}

			var top = activeEditor.offset().top - $(window).scrollTop(),
				tbHeight = parseInt($('#rte-toolbar').css('height'))
				y = Math.max(appbarHgt, top - (tbHeight * 1.5));
			$('#rte-toolbar').css('top', y);
			$('#contentbuilderClose')
				.css('top', Math.max(appbarHgt + tbHeight + 20, top));

			var p = $('*[data-rte-cmd="formatPara"]').position();
			$('#pop-align')
				.css('top', y + 42)
				.css('left', p.left + 'px');

			var p = $('*[data-rte-cmd="removeFormat"]').position();
			$('#pop-list')
				.css('top', y + 42)
				.css('left', p.left + 'px');
		}
	}
	$(window)
		.scroll(updateToolbarPosition)
		.resize(updateToolbarPosition);

	// Catch menu clicks and reclac positions
	$(document).click(function(e) {
		var c = $(e.target).parent().attr('data-rte-cmd');
		if(c == 'align' || c == 'list') {
			updateToolbarPosition();
		}
	});

	$(document).ready(function() {

		// Add overlay to make editor modal
		$('body').append('<div id="contentbuilderOverlay"></div><i class="fa fa-close" id="contentbuilderClose"></i>');

		function closeOverlay() {
			$('#contentbuilderOverlay').hide();
			$('.contentBuilderEditRegion').removeClass('contentbuilderActive');

			// Close editor menus
			if (parseInt($('#divTool').css('left')) >= 0)
				$('#lnkToolOpen').trigger('click');
			$('#rte-toolbar').hide();
			$('#lnkToolOpen').hide();
			$('.row-tool').hide();
			$('#contentbuilderClose').hide();

			// Copy content back to text area
			$fl('#' + activeEditor.attr('data-textarea')).trigger('change');
		}

		$('#contentbuilderOverlay').click(closeOverlay);
		$('#contentbuilderClose').click(closeOverlay);
	});

})();

