/**
*	A script that autoloads CKEditor for all textareas with the class ckeditor
*/

if( typeof dojo === 'undefined' ){ alert( 'Dojo is not available. CKEditor will not load' ); }

dojo.addOnLoad(function(){
	var CKEditorFields = dojo.query( '.ckeditor-field' );
	
	if( CKEditorFields.length > 0 ){ CKEditorFields.forEach( initCKEditor ) }
});

function initCKEditor( CKEditorField ){

	var editor = CKEDITOR.replace( CKEditorField, {
	skin : 'kama',
		filebrowserUploadUrl: document.location.pathname.split('.nsf')[0] + '.nsf/ckupload?CreateDocument'
		
	
	} );
	
	// When the editor is clicked, override the upload control ( renameCKUpload is in JS Header)
	
	editor.on( 'afterCommandExec', renameCKUpload );
	
}

/*
 * Adds an event listener to Image and URL-button
 * Replace the field name of the upload-control with a valid Domino field-name
 */
function renameCKUpload( eventObject ){

	var eventType = eventObject.data.name;
	
	// Only deal with Image, Link, ImageButton and Flash dialogs
	var eventTypeCheck = eventType + ',';	
	if( 'image,link,imagebutton,flash,'.indexOf( eventTypeCheck ) === -1 ){ return }
	
	// Find and change the upload control so that it works with Domino
	renameFileUpload();
		
	function renameFileUpload(){
		//Poll for the upload-iframe/field
		var iframes = document.getElementsByTagName( 'iframe' );
		var dialogFrame, dialogDoc;
		for( var i=0, len = iframes.length; i < len; i++ ){
			if( iframes[i].id.indexOf( 'fileInput' ) > 0 ){
				dialogFrame = iframes[i];
				dialogDoc = dialogFrame.contentWindow.document;
				break;
			}
		}
				
		if( !(dialogFrame && dialogDoc.forms.length === 1) ){ setTimeout( renameFileUpload, 1000 ); return; }
		var replicaId = Application.replicaId.toLowerCase();
			
		//Unique identifier snapped from HTML-source of the ckupload-form

		var body = '%%File.' + replicaId + '.05F544959C371427442578160018E134.$Body.0.70';

		//The upload-dialog-iframe is added as the last node to document.body
		//The field-name of the upload is NewFile. Replace that with a valid Domino field-name
		dialogDoc.forms[0].upload.name = body;
		
				
	}
}
