$.extend($.ui.dialog.overlay, { create: function(dialog)
	{
  if (this.instances.length === 0) {
    setTimeout(function() {
      if ($.ui.dialog.overlay.instances.length) {
        $(document).bind($.ui.dialog.overlay.events, function(event) {
          var parentDialog = $(event.target).parents('.ui-dialog');
          if (parentDialog.length > 0) {
            var parentDialogZIndex = parentDialog.css('zIndex') || 0;
            return parentDialogZIndex > $.ui.dialog.overlay.maxZ;
          }
          var aboveOverlay = false;
          $(event.target).parents().each(function() {
            var currentZ = $(this).css('zIndex') || 0;
            if (currentZ > $.ui.dialog.overlay.maxZ) {
              aboveOverlay = true;
              return;
            }
          });
          return aboveOverlay;
        });
      }
    }, 1);
    $(document).bind('keydown.dialog-overlay', function(event) {
      (dialog.options.closeOnEscape && event.keyCode && event.keyCode == $.ui.keyCode.ESCAPE && dialog.close(event));
    });
    $(window).bind('resize.dialog-overlay', $.ui.dialog.overlay.resize);
  }
  var $el = $('<div></div>').appendTo(document.body).addClass('ui-widget-overlay').css({
    width: this.width(),
    height: this.height()
  });
  (dialog.options.stackfix && $.fn.stackfix && $el.stackfix());
  this.instances.push($el);
  return $el;
	} 
});


  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: 'ca',
    startupFocus: true,
    removePlugins: 'scayt'
    	/*,
    filebrowserBrowseUrl: '/js/ckeditor/ckfinder/ckfinder.php?type=Images',
    filebrowserUploadUrl: '/uploadfiles'*/
  };



var editor;
var oldContent = "";
function startEditOnline(start) {
    if (start) {
        /*
        $('textelement').each(function(indx,item) {
            $(item).html("<content>" + $(this).html() + "</content>");
        });
        */
        textContainerName = "onlineeditcontainer";
        textContentName = "onlineedittext";
        $(textContainerName).prepend('<img src="/img/ic_edit.png" class="ononlineeditor" style="position:absolute;z-index:100000"/>');

        $('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();

                        //$('#onlineEditorTextArea').ckeditor({});
                        CKEDITOR.config.baseFloatZIndex = 9999999999;


                        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('#textoEditInline').ckeditor(editor_config);


                                /*
                                CKFinder.setupCKEditor(CKEDITOR.instances.textoEditInline,
                                    {
                                        basePath: '/js/ckeditor/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.textoEditInline == null) {
                                                        texto = $("#textoEditInline").val();
                                                    } else {
                                                        texto = CKEDITOR.instances.textoEditInline.getData();
                                                    }
                                                    $("#newText").val(texto);
                                                    sendFormAjaxPost(
                                                        "#editOnlineForm",
                                                        function (data) {
                                                            window.location = window.location;
                                                        }
                                                    );
                                                }
                                            }
                                            );
                                        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.textoEditInline.on(
                                    'change',
                                    function (e) {
                                        parent.find(textContentName).html(CKEDITOR.instances.textoEditInline.getData());
                                        //console.log(CKEDITOR.instances.textoEditInline.getData());
                                    }
                                );
                                

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

                    }
                );
                e.preventDefault();
                return false;
            });
        });
    }
    else {
        $('.ononlineeditor').remove();
    }
}

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

