

CKEDITOR.plugins.add( 'SFEditorChanges', {
	
	init: function(editor) {
		
		var element = document.getElementById(editor.name);
		var form = element.form;
		
		// IE workaround.
		var attached = false;

		// Required a parent form.
		if(form) {

			var changed = false;

			// Restore from storage.
			if(editor.config.storageName && window.localStorage) {
				var data = window.localStorage.getItem(editor.config.storageName);
				if(data) {
					editor.addCommand('SFEditorChangesCommand', {
						exec: function() {
							editor.loadSnapshot(data);
							changed = true;
						}
					});
					editor.ui.addButton('SFEditorChanges', {
						label:   'Restore unsaved changes',
						command: 'SFEditorChangesCommand',
						icon:    '/global_files/icons/fugue/pin--arrow.png'
					});
				}
			}
			
			// Document gets submitted, discard change.
			form.addEventListener("submit", function() {
				if(editor.config.storageName && window.localStorage) {
					if(editor.config.storageKeep == 'no') {
						window.localStorage.removeItem(editor.config.storageName);
					} else if (changed) {
						window.localStorage.setItem(editor.config.storageName, snapshot);
					}
				}
				changed = false;
			});

			// Guard on unload.
			window.onbeforeunload = function(e) {
				if(changed) {
					if(editor.config.storageName && window.localStorage) {
						var snapshot = editor.getSnapshot();
						if(snapshot != "<p><br></p>" && snapshot != "<br>") {
							window.localStorage.setItem(editor.config.storageName, snapshot);
						}
					} else {
						return "Document has been modified, discard changes?";
					}
				}
				return undefined;
			}

			// Track editor changes.
			editor.on('change', function() {
				changed = true;
			});
		}
	}
});


