/**
 * 
 */

  var editor_config =
  {
    uiColor: '#949AAA',
    enterMode: CKEDITOR.ENTER_BR,
    height: '300px',
    protectedSource: [/<\?[\s\S]*?\?>/g],
    toolbar:
		        [
				    ['Save', '-', 'Cut', 'Copy', 'PasteText', '-'],
				    ['Undo', 'Redo', 'Find', 'Replace', 'SelectAll', 'RemoveFormat'],
				    ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript'],
				    ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', 'Blockquote'],
				    ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
				    '/',
				    ['Link', 'Unlink', 'Anchor'],
				    ['Image', 'Flash', 'Table', 'HorizontalRule', 'SpecialChar'],
				    ['Styles', 'Format', 'FontSize'],
				    ['TextColor', 'BGColor'],
				    ['Maximize', 'ShowBlocks', 'Source']
		        ],
    language: 'en',
    startupFocus: true,
    removePlugins: 'scayt',
    extraPlugins : 'stylesheetparser',
    contentsCss : '/css/styles.css',
    bodyId: 'bodyCaixaEdicio',
    stylesSet : [],
    filebrowserBrowseUrl: '/js/ckfinder/ckfinder.php?type=Images',
    filebrowserUploadUrl: '/uploadfiles'
  };



var editor;
var oldContent = "";
var start = true;
function startEditOnline(start) {
    if (start) {
    	start = false;
        textContainerName = "#onlineeditcontainer";
        textContentName = "#onlineedittext";
        $(textContainerName).prepend('<img src="/img/edit.png" class="ononlineeditor" style="position:absolute;z-index:1000000000"/>');

        $('img.ononlineeditor').each(function () {
            $el = $(this);

            $el.bind('contextmenu', function (e) {
                var miDialog = $('#popUpOnlineEditorContainer');
                var parent = $(this).parent();
                miDialog.load(
                    $(this).parent().attr('href'),
                    {},
                    function(responseText, textStatus, XMLHttpRequest){
                    	oldContent = parent.find(textContentName).html();
                    	startEditor(miDialog, responseText, textStatus, XMLHttpRequest);
                    }
                );
                e.preventDefault();
                return false;
            });
        });
    }
    else {
        $('.ononlineeditor').remove();
    }
}


function startEditor(miDialog, responseText, textStatus, XMLHttpRequest) {
     CKEDITOR.config.baseFloatZIndex = 9999999999;
     var parent = miDialog.parent();
     miDialog.dialog({
         bgiframe: true,
         autoOpen: true,
         width: 750,
         height: 500,
         zIndex: 99999999,
         modal: false,
         draggable: true,
         resizable: true,
         closeOnEscape: true,
         buttons: {
				Close: function() {
					$( this ).dialog( "close" );
				}
			},
         open: function () {
             $('.ononlineeditor').hide();
             $('iframe').hide();
             $(this).find('#onlineEditorTextArea').ckeditor(editor_config);


             
             CKFinder.setupCKEditor(CKEDITOR.instances.onlineEditorTextArea,
                 {
                     basePath: '/js/ckfinder/',
                     rememberLastFolder: false
                 }
            );
             
             CKEDITOR.plugins.registered['save'] = {
                 init: function (editor) {
                     var command = editor.addCommand(
                         'save',
                         {
                             modes: { wysiwyg: 1, source: 1 },
                             exec: function (editor) {
                                 if (CKEDITOR.instances.onlineEditorTextArea == null) {
                                     texto = $("#onlineEditorTextArea").val();
                                 } else {
                                     texto = CKEDITOR.instances.onlineEditorTextArea.getData();
                                 }
                                 $("#newText").val(texto);
                                 sendFormAjaxPost(
                                     "#editOnlineForm",
                                     function (data) {
                                    	 location.reload(true);
                                     }
                                 );
                             }
                         }
                         );
                     editor.ui.addButton('Save', { label: 'My Save', command: 'save' });
                 }
             };


             CKEDITOR.config.protectedSource.push(/<%[\s\S]*?%>/g);


             CKEDITOR.plugins.add(
                 'onchange',
                 {
                     init: function (editor) {
                         // Test:
                         //		editor.on( 'change', function(e) { console.log(e) });

                         var timer;
                         // Avoid firing the event too often
                         function somethingChanged() {
                             if (timer)
                                 return;

                             timer = setTimeout(function () {
                                 timer = 0;
                                 editor.fire('change');
                             }, editor.config.minimumChangeMilliseconds || 100);
                         }

                         // Set several listeners to watch for changes to the content
                         editor.on('saveSnapshot', function (e) { somethingChanged(); });
                         editor.on('afterUndo', function (e) { somethingChanged(); });
                         editor.on('afterRedo', function (e) { somethingChanged(); });

                         editor.on('contentDom', function () {
                             editor.document.on('keydown', function (event) {
                                 // Do not capture CTRL hotkeys.
                                 if (!event.data.$.ctrlKey && !event.data.$.metaKey)
                                     somethingChanged();
                             });

                             // Firefox OK
                             editor.document.on('drop', function () {
                                 somethingChanged();
                             });
                             // IE OK
                             editor.document.getBody().on('drop', function () {
                                 somethingChanged();
                             });
                         });

                         editor.on('afterCommandExec', function (event) {
                             if (event.data.command.canUndo !== false)
                                 somethingChanged();
                         });


                     } //Init
                 }
             );                                
             
             CKEDITOR.config.extraPlugins = 'onchange';
             
             CKEDITOR.instances.onlineEditorTextArea.on(
                 'change',
                 function (e) {
                     parent.find(textContentName).html(CKEDITOR.instances.onlineEditorTextArea.getData());
                     //console.log(CKEDITOR.instances.onlineEditorTextArea.getData());
                 }
             );
             

             //$(this).find("textarea").ckeditor(editor_config);
         },
         close: function () {
             $('.ononlineeditor').show();
             $('iframe').show();
             parent.find(textContentName).html(oldContent);
             $(this).find("#onlineEditorTextArea").ckeditorGet().destroy();
         }
     });	
}


$(function () {
    $("#editModeOnoff").bind(
        'click',
        function () {
            startEditOnline($(this).attr('checked'));
        }
    );
});

