
// Cache phrases used in this file
window.vBulletin = window.vBulletin || {};
window.vBulletin.phrase = window.vBulletin.phrase || {};
window.vBulletin.phrase.precache = window.vBulletin.phrase.precache || [];
window.vBulletin.phrase.precache = $.merge(window.vBulletin.phrase.precache, [
	'wrap_x_tags'
]);

window.vBulletin.options = window.vBulletin.options || {};
window.vBulletin.options.precache = window.vBulletin.options.precache || [];
window.vBulletin.options.precache = $.merge(window.vBulletin.options.precache, [
	'hvcheck'
]);

// vBulletin ckeditor namespace
vBulletin.ckeditor = vBulletin.ckeditor || {};

if (jQuery.type(window.vBulletin.smilieInfo) === "undefined")
{
	var initSmiley = {'name' : "", 'dash' : ''};
}
else
{
	var initSmiley = {'name' : "Smiley", 'dash' : '-'};
}

// Uncomment the following to force plugins to refresh during development
//CKEDITOR.timestamp = (new Date()).valueOf();

// definitions of the ckeditor toolbars
// these are used by the editorDefinitions
CKEDITOR.config.toolbar_vBulletinFull = [
	[ /*"EnhancedSource", "-",*/ "RemoveFormat", "-", "PasteText", "PasteFromWord", "-", "Font", "FontSize", "-", "TextColor", "-", initSmiley.name, initSmiley.dash, /*"Attach", "-",*/ "Undo", "Redo" ],
	"\/",
	[ "Bold", "Italic", "Underline" ], [ "JustifyLeft", "JustifyCenter", "JustifyRight" ], [ "NumberedList", "BulletedList", "Outdent", "Indent" ], [ "Link", "Email", "Unlink"/*, "Image", "Video"*/ ], [ "Quote" ], [ "Code", "Html", "Php" ],
	"\/",
	[ "Table", "TableProperties", "DeleteTable", "-", "InsertRowBefore", "InsertRowAfter", "DeleteRow", "-", "InsertColumnBefore", "InsertColumnAfter", "DeleteColumn", "-", "Subscript", "Superscript", "HorizontalRule" ]
];
CKEDITOR.config.toolbar_vBulletinMinimal = [
	["RemoveFormat"], [ "Bold", "Italic", "Underline" ]
];
CKEDITOR.config.toolbar_vBulletinBare = [];

// basic ckeditor config options
CKEDITOR.config.baseHref = pageData.baseurl + '/';
//CKEDITOR.config.smiley_images // The file names for the smileys to be displayed.

// The base path used to build the URL for the smiley images.
CKEDITOR.config.smiley_path = pageData.baseurl_core + '/';

CKEDITOR.config.enterMode = CKEDITOR.ENTER_BR;
// we don't want quotes, dashes, etc to be converted to entities
CKEDITOR.config.entities = false;

CKEDITOR.config.height = '100px'; // default height for the editor to expand to when clicked
CKEDITOR.config.width = '100%';

// the global default vBulletin configuration for ckeditor,
// the toolbar
vBulletin.ckeditor.config = {
	toolbar: 'vBulletinMinimal',
	customConfig: '',
	toolbarCanCollapse: false,
	resize_dir: 'vertical',
	removePlugins: 'about,elementspath,contextmenu,smiley',
	extraPlugins: 'vbsmiley,vbwrapbuttons',
	pluginPath : pageData.baseurl + '/js/ckeplugins/'
	//parsetype: 'nonforum'
};


// @todo change this
//config.vbulletin = {};
//config.vbulletin.securitytoken = '';

// make sure extra plugins are loaded if they aren't already
var plugins = vBulletin.ckeditor.config.extraPlugins.split(',');
for (var i = 0; i < plugins.length; i++)
{
	console.log(plugins[i]);
	try
	{
		if (!CKEDITOR.plugins.get(plugins[i]))
		{
			console.log('Ckeditor: Plugin Loaded: ' + pageData.baseurl + '/js/ckeplugins/' + plugins[i] + '/plugin.js');
			CKEDITOR.plugins.addExternal(plugins[i], vBulletin.ckeditor.config.pluginPath + plugins[i] + '/', 'plugin.js')
		}
	}
	catch(e){} // keep loading the remaining plugins
}


/*
 * To create a new editor, define one here by adding a new element to this object.
 *
 * The element key should be the editor ID, which is the same as the HTML id attribute
 * on the textarea or HTML element to be replaced by the ckeditor.
 *
 * The element value should be an object containing "toolbar" and "callback". The toolbar
 * is a named toolbar created previously as CKEDITOR.config.toolbar_ToolbarName. The
 * callback is a function that receives the editor ID and the ckeditor instance, and is
 * called after the ckeditor is created.
 */
vBulletin.ckeditor.editorDefinitions =
{
	// an editor with no toolbar-- used in the channel and conversation widgets
	'ckeditor-bare':
	{
		'toolbar' : 'vBulletinBare',
		'callback' : function(editorId, ckeditorInstance)
		{
		}
	},
	// an editor with no toolbar-- used in the channel and conversation widgets for the video tab
	'ckeditor-bare-video':
	{
		'toolbar' : 'vBulletinBare',
		'callback' : function(editorId, ckeditorInstance)
		{
		}
	},
	// an editor with no toolbar-- used in the channel and conversation widgets for the poll tab
	'ckeditor-bare-poll':
	{
		'toolbar' : 'vBulletinBare',
		'callback' : function(editorId, ckeditorInstance)
		{
		}
	},
	'ckeditor-bare-poll-edit':
	{
		'toolbar' : 'vBulletinBare',
		'callback' : function(editorId, ckeditorInstance)
		{
		}
	},
	// an editor with no toolbar-- used in the channel and conversation widgets for the video tab
	'ckeditor-bare-link':
	{
		'toolbar' : 'vBulletinBare',
		'callback' : function(editorId, ckeditorInstance)
		{
		}
	},
	//editor when in Edit Conversation mode
	'ckeditor-bare-edit':
	{
		'toolbar' : 'vBulletinBare',
		'callback' : function(editorId, ckeditorInstance)
		{
		}
	},
	//editor when in Edit Video Conversation mode
	'ckeditor-bare-video-edit':
	{
		'toolbar' : 'vBulletinBare',
		'callback' : function(editorId, ckeditorInstance)
		{
		}
	},
	//editor when in Edit Video Conversation mode
	'ckeditor-bare-link-edit':
	{
		'toolbar' : 'vBulletinBare',
		'callback' : function(editorId, ckeditorInstance)
		{
		}
	},
	//editor for creating Gallery
	'ckeditor-bare-gallery':
	{
		'toolbar' : 'vBulletinBare',
		'callback' : function(editorId, ckeditorInstance)
		{
		}
	},
	//editor when in Edit Gallery Conversation mode
	'ckeditor-bare-gallery-edit':
	{
		'toolbar' : 'vBulletinBare',
		'callback' : function(editorId, ckeditorInstance)
		{
		}
	},
	//editor for creating Gallery
	'ckeditor-bare-mediagallery':
	{
		'toolbar' : 'vBulletinBare',
		'callback' : function(editorId, ckeditorInstance)
		{
		}
	},
	//editor when in Edit Gallery Conversation mode
	'ckeditor-bare-mediagallery-edit':
	{
		'toolbar' : 'vBulletinBare',
		'callback' : function(editorId, ckeditorInstance)
		{
		}
	},
	// an editor with full toolbars-- used when clicking 'advanced editor' when creating a conversation
	'ckeditor-advanced':
	{
		'toolbar' : 'vBulletinFull',
		'callback' : function(editorId, ckeditorInstance)
		{
		}
	},
	// the editor used when clicking 'go advanced'
	'ckeditor-advanced-edit':
	{
		'toolbar' : 'vBulletinFull',
		'callback' : function(editorId, ckeditorInstance)
		{
		}
	},
	// an editor with full toolbars-- used when editing signatures
	'ckeditor-signature':
	{
		'toolbar' : 'vBulletinFull',
		'callback' : function(editorId, ckeditorInstance)
		{
		}
	}
};
vBulletin.ckeditor.editorDefinitions['ckeditor-bare-mediavideo'] = vBulletin.ckeditor.editorDefinitions['ckeditor-bare-video'];
vBulletin.ckeditor.editorDefinitions['ckeditor-bare-mediavideo-edit'] = vBulletin.ckeditor.editorDefinitions['ckeditor-bare-video-edit'];

// ckeditor instances
vBulletin.ckeditor.instances = {};

/**
 * Initializes the auto title functionality-- where the title is initially
 * generated from the text as you type it into the editor
 *
 * @param	editor ID
 * @param	ckeditor instance
 */
vBulletin.ckeditor.initAutoTitle = function(editorId, ckeditorInstance)
{
	var $form = $('#' + editorId).closest('form');
	var $titleEl = $form.find('input[name="title"]')
		.add('textarea[name="title"]', $form)
		.add('input[name="gallery_title"]', $form)
		.first();

	if ($titleEl.length == 1)
	{
		var previousAutoTitle = '';
		var autoUpdateTitle = function()
		{
			var autoTitle = $.trim($('<div>' + ckeditorInstance.getData() + '</div>').text()).substr(0, 50);
			if ($titleEl.val() == '' || $titleEl.val() == previousAutoTitle)
			{
				$titleEl.val(autoTitle);
				previousAutoTitle = autoTitle;
			}
		};

		ckeditorInstance.on('key', function()
		{
			window.setTimeout(autoUpdateTitle, 0);
		});
	}
};

/**
 * set focus on the title when first loaded
 *
 * @param	editor ID
 * @param	ckeditor instance
 */
vBulletin.ckeditor.initFocusTitle = function(editorId, ckeditorInstance)
{
	var $form = $('#' + editorId).closest('form');
	var $etitle = $form.find('input[name="title"]')
		.add('textarea[name="title"]', $form)
		.add('input[name="gallery_title"]', $form)
		.first();

	if ($etitle.length == 1)
	{
		$etitle.focus();
		console.log('Ckeditor: Focus on title for editor: {0}'.format(editorId));
	}
	else
	{
		ckeditorInstance.focus();
		console.log('Ckeditor: Focus on editor for editor: {0}'.format(editorId));
	}

};

/**
 * Attempts to maintain content and titles when switching between editors/content types
 * in the content entry box
 *
 * @param	New editor ID
 * @param	New ckeditor instance
 */
vBulletin.ckeditor.maintainContent = function(editorId, ckeditorInstance)
{
	console.log('Ckeditor: maintainContent');

	var getTitleElementFromEditorId = function(editorId)
	{
		var $form = $('#' + editorId).closest('form');
		return $form.find('input[name="title"]')
			.add('textarea[name="title"]', $form)
			.add('input[name="gallery_title"]', $form)
			.first();
	};

	$('#' + editorId).closest('.content-entry-box').find('textarea[name="text"]').each(function()
	{
		var sourceEditorId = $(this).attr('id');

		// skip the editor we're creating
		if (sourceEditorId == editorId)
		{
			return true; // continue
		}

		if (vBulletin.ckeditor.editorExists(sourceEditorId))
		{
			// copy editor content
			var editorContent = vBulletin.ckeditor.getEditor(sourceEditorId).getData();
			vBulletin.ckeditor.destroyEditor(sourceEditorId);
			$('#' + sourceEditorId).val('');
			vBulletin.ckeditor.convertToBasicEditor(sourceEditorId);
			ckeditorInstance.insertHtml(editorContent);

			// copy title
			var $sourceTitleEl = getTitleElementFromEditorId(sourceEditorId);
			if ($sourceTitleEl.length)
			{
				getTitleElementFromEditorId(editorId).val($sourceTitleEl.val());
				$sourceTitleEl.val('');
			}

			// copy prefix
			var $sourcePrefixEl = $('#' + sourceEditorId).closest('form').find('select.prefixid');
			var $prefixEl = $('#' + editorId).closest('form').find('select.prefixid');
			if ($prefixEl.length && $sourcePrefixEl.length)
			{
				$prefixEl.selectBox('value', $sourcePrefixEl.selectBox('value'));
				$sourcePrefixEl.selectBox('value', '');
			}

			return false; // break
		}
	});
};

/**
 * Converts an editor from a "bare" editor to an "advanced" editor
 *
 * @param	string		Editor ID
 */
vBulletin.ckeditor.convertToAdvancedEditor = function(editorId)
{
	var editorContent = vBulletin.ckeditor.getEditor(editorId).getData();
	var newEditorId = 'ckeditor-advanced-edit';

	if (editorId == newEditorId)
	{
		return; // already advanced
	}

	// return any previous instances of the advanced editor to basic
	vBulletin.ckeditor.convertToBasicEditor(newEditorId);

	vBulletin.ckeditor.destroyEditor(editorId);

	// change to new id & save old id
	$('#' + editorId).data('old-id', editorId).attr('id', newEditorId);

	vBulletin.ckeditor.initEditor(newEditorId, {
		success: function(editorId)
		{
			vBulletin.ckeditor.getEditor(editorId).insertHtml(editorContent);
		}
	});
}

/**
 * Converts an editor from an "advanced" editor back to a "basic" editor
 *
 * @param	string		Editor ID
 */
vBulletin.ckeditor.convertToBasicEditor = function(editorId)
{
	if (editorId != 'ckeditor-advanced-edit')
	{
		return;
	}

	var $editor = $('#' + editorId);
	if ($editor.length < 1)
	{
		return;
	}

	var oldId = $editor.data('old-id');
	if (oldId)
	{
		vBulletin.ckeditor.destroyEditor(editorId);
		$editor.attr('id', oldId);
	}
};

vBulletin.ckeditor.initHumanVerification = function(editorId, editorInstance)
{
	if (vBulletin.options.get('hvcheck') & 2)
	{
		vBulletin.ckeditor.doInitHumanVerification(editorId);
		editorInstance.on('focus', function () {
			// remove any old HV images and create a new one for this editor.
			vBulletin.ckeditor.doInitHumanVerification(editorId);
		});
	}
}

vBulletin.ckeditor.doInitHumanVerification = function(editorId)
{
	var form = $('#' + editorId).closest('form'),
		humanverify = $('.humanverify', form);

	if (humanverify.length)
	{
		return true;
	}

	// Don't need HV in edit form
	if (form.closest('.edit-post').length > 0)
	{
		return true;
	}

	// Remove all other human verifications
	$('div.humanverify').remove();

	$.ajax({
		url:pageData.baseurl + '/index.php/ajax/render/humanverify',
		type:'POST',
		data:({action: 'post'}),
		dataType:'json',
		success:function(result)
		{
			console.log('/index.php/ajax/render/humanverify');
			if (result && !result.errors)
			{
				if (form.closest('.edit-post').length > 0)
				{
					return true;
				}
				humanverify = $('.humanverify', form);
				if (humanverify.length)
				{
					humanverify.remove();
				}
				$('.action-buttons', form).before(result);
			}
			else
			{
				console.log('/index.php/ajax/render/humanverify successful, but response was not valid: ' + JSON.stringify(result));
				openAlertDialog({
					'title':vBulletin.phrase.get('error'),
					'message':vBulletin.phrase.get('invalid_server_response_please_try_again'),
					'iconType':'error',
					'onAfterClose':function(){
						$deleteDialog.dialog('close');
					}
				});
			}
		},
		error:function(xhr, statusText, error){
			console.log('/index.php/ajax/render/humanverify failed, error: ' + error);
			openAlertDialog({
				'title':vBulletin.phrase.get('error'),
				'message':vBulletin.phrase.get('error_loading_delete_form_x', xhr.status),
				'iconType':'error',
				'onAfterClose':function(){
					$deleteDialog.dialog('close');
				}
			});
		}
	});
}

/**
 * Initializes a ckeditor instance; Should only be called from vBulletin.ckeditor.initEditor()
 *
 * @param	string		Editor ID
 * @param	function	Callback function to be executed after the editor is initialized (optional)
 */
vBulletin.ckeditor.doInitEditor = function(editorId, callbackFunc)
{
  if (CKEDITOR.env.mobile && !CKEDITOR.env.isCompatible)
  {
    console.log("Ckeditor: Not supported on this mobile device");
    vBulletin.ckeditor.hideLoadingDialog(editorId);
    return;
  }


	console.log('Ckeditor: Initializing editor: {0}'.format(editorId));

	if (vBulletin.ckeditor.eventRegistered(editorId, 'beforeInit'))
	{
		for (index in vBulletin.ckeditor.registeredEvents[editorId]['beforeInit'])
		{
			vBulletin.ckeditor.registeredEvents[editorId]['beforeInit'][index]();
		}
	}

	// ensure that this editor has been defined
	if (typeof vBulletin.ckeditor.editorDefinitions[editorId] == 'undefined')
	{
		console.log('The editor ({0}) is not defined. Please create the editor definition in vBulletin.ckeditor.editorDefinitions near the top of ckeditor.js.'.format(editorId));

		return;
	}

	if (vBulletin.ckeditor.editorExists(editorId))
	{
		console.log('The editor ({0}) already exists. Destroy to allow recreation.'.format(editorId));
		vBulletin.ckeditor.destroyEditor(editorId);
		//vBulletin.ckeditor.hideLoadingDialog(editorId);
		//return;
	}

	if ($('#' + editorId).is(':visible'))
	{
		$('#' + editorId).val('');
	}

	vBulletin.ckeditor.config.toolbar = vBulletin.ckeditor.editorDefinitions[editorId].toolbar;

	$('#' + editorId).ckeditor(function()
	{
		// work around an IE8 bug where the editor is not sized correctly
//		var container = this.getResizable();
//		this.resize(container.$.offsetWidth || 0, container.$.offsetHeight || 0);

		// hide the loading dialog
		vBulletin.ckeditor.hideLoadingDialog(editorId);

		// set up auto titles
//		vBulletin.ckeditor.initAutoTitle(editorId, this); // Disabled, VBV947.

		// call the specific callback for this editor ID
		vBulletin.ckeditor.editorDefinitions[editorId].callback(editorId, this);

		// save this ckeditor instance
		vBulletin.ckeditor.instances[editorId] = this;

		// work around an IE8 bug where the editor is set to read only be default
		// The try/catch block is to fix a ckeditor issue in IE8. See VBV-302.
		try {
			this.setReadOnly(false);
		}
		catch(err) {
			this.setReadOnly(false);
		}

		// maintain content when switching between editors
		// this applies to editor content, titles, and prefixes
		vBulletin.ckeditor.maintainContent(editorId, this);

		// focus the editor
//		this.focus(); // Disabled, VBV947.
		vBulletin.ckeditor.initFocusTitle(editorId, this); // Focus on title if empty, VBV947.

		vBulletin.ckeditor.initHumanVerification(editorId, this);

		console.log('Ckeditor: Editor initialized: {0}'.format(editorId));
		//CKEDITOR.on('instanceReady', function(event) { alert("Foo"); });

		// call the user-supplied callback
		if (typeof callbackFunc == 'function')
		{
			return callbackFunc.apply(this, [editorId]);
		}

	}, vBulletin.ckeditor.config);

	if ($('#' + editorId).closest('form').length > 0)
	{
		$('#' + editorId).closest('form').attr('ck-editorid', editorId);
	}

	console.log('Added editorId "' + editorId + '" to form');

	if (vBulletin.ckeditor.eventRegistered(editorId, 'afterInit'))
	{
		for (index in vBulletin.ckeditor.registeredEvents[editorId]['afterInit'])
		{
			vBulletin.ckeditor.registeredEvents[editorId]['afterInit'][index]();
		}
	}
};

/**
 * Determines whether or not the given editor instance exists (has been initialized)
 *
 * @param	string	Editor ID
 *
 * @return	bool
 */
vBulletin.ckeditor.editorExists = function(editorId)
{
	return (typeof vBulletin.ckeditor.instances[editorId] != 'undefined' && vBulletin.ckeditor.instances[editorId]);
};

/**
 * Returns an editor instance if it exists
 *
 * @param	string	Editor ID
 *
 * @return	object|null
 */
vBulletin.ckeditor.getEditor = function(editorId)
{
	return vBulletin.ckeditor.editorExists(editorId) ? vBulletin.ckeditor.instances[editorId] : null;
};

/**
 * Destroys an editor instance (use this instead of the ckeditor destroy method)
 *
 * @param	string 	Editor ID
 *
 * @return 	bool	true if destroyed, false if not
 */
vBulletin.ckeditor.destroyEditor = function(editorId)
{
	console.log('Ckeditor: Destroying editor: {0}'.format(editorId));

	if (vBulletin.ckeditor.editorExists(editorId))
	{
		// call the ckeditor method
		// @todo -- we could pass the noUpdate param for the ckeditor destroy method
		// if it turns out to be needed.
		try
		{
			vBulletin.ckeditor.getEditor(editorId).destroy();
		}
		catch (e){}

		// make sure our instance handle is gone
		vBulletin.ckeditor.instances[editorId] = null;

		return true;
	}
	else
	{
		console.warn('Ckeditor: Not destroyed, because editor {0} does not exist.'.format(editorId));
	}

	return false;
};

/**
 * Fixes for CKEditor display in iOS devices (responsive)
 *
 * Attach an event handler that will be called every time a
 * ckeditor instance is ready.
 */
CKEDITOR.on('instanceReady', function(event) {
  var editor = event.editor;

  /* If we're in webkit, we set the iframe's display to none and then
   * back to block, to trigger appropriate resizing so that the CKEditor
   * does not extend beyond the boundaries of its container.
   */
  if (CKEDITOR.env.webkit) {
    var iframe = document.getElementById('cke_contents_' + editor.name).firstChild;

    if (parseInt(editor.config.width) < 310) {
      iframe.style.display = 'none';
      iframe.style.display = 'block';
    }

    /**
     * If it's an iOS device, we have to go one step further and scroll
     * the window inside the iframe, as currently mobile WebKit browsers
     * are cutting off half of the first line of any text that exists
     * in the editor. (Fixes VBV-2093)
     */
    if ('ontouchstart' in document.documentElement) {
      iframe.contentWindow.scrollTo(0,10);
    }
  }
});
