( function() {
	CKEDITOR.plugins.add( 'news', {
		requires: 'widget',
		init: function(editor) {
            var newsPlugn = this;
            var deletableTags = ['div', 'aside', 'figure', 'p'];
            
            /*editor.widgets.add('newsAntrfile', {
            	editables: {
                    Content: {
                        selector: '.st-part, .st-partwide'
                    }
                },
            	upcast: function( element ) {
                    return element.name == 'div' && (element.hasClass('st-part') || element.hasClass('st-partwide'));
                }
        	});*/
            
            editor.addCommand('deleteLatestDiv', {
            	exec: function(editor) {
            		var selectedElement = editor.getSelection().getStartElement();
            		if (!selectedElement) {
            			return;
            		}
            		
					var elementParents = selectedElement.getParents();
            		var elementParentLatestDiv = null;
            		for (var elementParentIndex in elementParents) {
            			if (deletableTags.indexOf(elementParents[elementParentIndex].getName()) >= 0) {
            			// if (elementParents[elementParentIndex].getName() == 'aside') {
            				elementParentLatestDiv = elementParents[elementParentIndex];
            				break;
            			}
            		}
            		
        			if (!elementParentLatestDiv) {
        				return;
        			}
        			
        			elementParentLatestDiv.remove();
        			editor.focus();
            	}
            });


            if (editor.contextMenu) {
            	editor.addMenuGroup('news');

            	editor.contextMenu.addListener(function(element, selection) {
            		
            		var elementParents = element.getParents();
            		// alert(JSON.stringify(elementParents));
            		var elementParentLatestDiv = null;
            		for (var elementParentIndex in elementParents) {
            			if (deletableTags.indexOf(elementParents[elementParentIndex].getName()) >= 0) {
            			// if (elementParents[elementParentIndex].getName() == 'aside') {
            				elementParentLatestDiv = elementParents[elementParentIndex];
            				break;
            			}
            		}
            		
        			if (elementParentLatestDiv) {

        	            editor.addMenuItems({
        	            	DeleteLatestDiv: {
        	                    label : 'Obriši okvir',
        	                    command : 'deleteLatestDiv',
        	                    group : 'news',
        	                    order : 101
        					}
        	            });

            			return {
            				DeleteLatestDiv: CKEDITOR.TRISTATE_ON
                        };
        			}
                });
        	}
        }
    });
})();
