<commit_before>CKEDITOR.stylesSet.add( 'styling', [
  { name: 'Code', element: 'code' },
  { name: 'Keyboard' , element: 'kbd' }
]);

CKEDITOR.editorConfig = function( config ) {
  // Insert from clipboard should be cleared from formating
  config.forcePasteAsPlainText = true;

  config.extraPlugins = 'highlight_js,youtube';

  config.format_tags = 'p;h1;h2;h3;h4;h5;h6;pre';

  config.stylesSet = 'styling';

  config.extraAllowedContent = 'code(*)'

  config.toolbar = [
    ["Save", "-", "Source"],
    ["Highlight"],
    ["Undo", "Redo"],
    ["Bold",  "Italic",  "Underline",  "Strike",  "-",  "Subscript",  "Superscript", "-", "NumberedList", "BulletedList", "-", "Outdent", "Indent"],
    ["Link", "Unlink"],
    ["Image", "Youtube", "Table"],
    ["Maximize"],
    "/",
    ["Styles", "Format", "FontSize"],
    ["JustifyLeft", "JustifyCenter", "JustifyRight"],
    ["TextColor", "BGColor"]
  ];

  config.filebrowserBrowseUrl = "/ckeditor/attachment_files";
  config.filebrowserFlashBrowseUrl = "/ckeditor/attachment_files";
  config.filebrowserFlashUploadUrl = "/ckeditor/attachment_files";
  config.filebrowserImageBrowseLinkUrl = "/ckeditor/pictures";
  config.filebrowserImageBrowseUrl = "/ckeditor/pictures";
  config.filebrowserImageUploadUrl = "/ckeditor/pictures";
  config.filebrowserUploadUrl = "/ckeditor/attachment_files";

  // Rails CSRF token
  config.filebrowserParams = function(){
    var csrf_token, csrf_param, meta,
    metas = document.getElementsByTagName('meta'),
    params = new Object();

    for ( var i = 0 ; i < metas.length ; i++ ){
      meta = metas[i];
      switch(meta.name) {
        case "csrf-token":
          csrf_token = meta.content;
          break;
        case "csrf-param":
          csrf_param = meta.content;
          break;
        default:
          continue;
      }
    }

    if (csrf_param !== undefined && csrf_token !== undefined) {
      params[csrf_param] = csrf_token;
    }

    return params;
  };

  config.addQueryString = function( url, params ){
    var queryString = [];

    if ( !params ) {
      return url;
    } else {
      for ( var i in params )
        queryString.push( i + "=" + encodeURIComponent( params[ i ] ) );
    }

    return url + ( ( url.indexOf( "?" ) != -1 ) ? "&" : "?" ) + queryString.join( "&" );
  };

  // Integrate Rails CSRF token into file upload dialogs (link, image, attachment and flash)
  CKEDITOR.on( 'dialogDefinition', function( ev ){
    // Take the dialog name and its definition from the event data.
    var dialogName = ev.data.name;
    var dialogDefinition = ev.data.definition;
    var content, upload;

    if (CKEDITOR.tools.indexOf(['link', 'image', 'attachment', 'flash'], dialogName) > -1) {
      content = (dialogDefinition.getContents('Upload') || dialogDefinition.getContents('upload'));
      upload = (content == null ? null : content.get('upload'));

      if (upload && upload.filebrowser && upload.filebrowser['params'] === undefined) {
        upload.filebrowser['params'] = config.filebrowserParams();
        upload.action = config.addQueryString(upload.action, upload.filebrowser['params']);
      }
    }
  });
};<commit_msg>Added comments<commit_after>CKEDITOR.stylesSet.add( 'styling', [
  { name: 'Code', element: 'code' },
  { name: 'Keyboard' , element: 'kbd' }
]);

CKEDITOR.editorConfig = function( config ) {
  // Insert from clipboard should be cleared from formating
  config.forcePasteAsPlainText = true;

  config.extraPlugins = 'highlight_js,youtube';

  config.format_tags = 'p;h1;h2;h3;h4;h5;h6;pre';

  config.stylesSet = 'styling';

  // Allow code tags to have classes
  config.extraAllowedContent = 'code(*)'

  config.toolbar = [
    ["Save", "-", "Source"],
    ["Highlight"],
    ["Undo", "Redo"],
    ["Bold",  "Italic",  "Underline",  "Strike",  "-",  "Subscript",  "Superscript", "-", "NumberedList", "BulletedList", "-", "Outdent", "Indent"],
    ["Link", "Unlink"],
    ["Image", "Youtube", "Table"],
    ["Maximize"],
    "/",
    ["Styles", "Format", "FontSize"],
    ["JustifyLeft", "JustifyCenter", "JustifyRight"],
    ["TextColor", "BGColor"]
  ];

  config.filebrowserBrowseUrl = "/ckeditor/attachment_files";
  config.filebrowserFlashBrowseUrl = "/ckeditor/attachment_files";
  config.filebrowserFlashUploadUrl = "/ckeditor/attachment_files";
  config.filebrowserImageBrowseLinkUrl = "/ckeditor/pictures";
  config.filebrowserImageBrowseUrl = "/ckeditor/pictures";
  config.filebrowserImageUploadUrl = "/ckeditor/pictures";
  config.filebrowserUploadUrl = "/ckeditor/attachment_files";

  // Rails CSRF token
  config.filebrowserParams = function(){
    var csrf_token, csrf_param, meta,
    metas = document.getElementsByTagName('meta'),
    params = new Object();

    for ( var i = 0 ; i < metas.length ; i++ ){
      meta = metas[i];
      switch(meta.name) {
        case "csrf-token":
          csrf_token = meta.content;
          break;
        case "csrf-param":
          csrf_param = meta.content;
          break;
        default:
          continue;
      }
    }

    if (csrf_param !== undefined && csrf_token !== undefined) {
      params[csrf_param] = csrf_token;
    }

    return params;
  };

  config.addQueryString = function( url, params ){
    var queryString = [];

    if ( !params ) {
      return url;
    } else {
      for ( var i in params )
        queryString.push( i + "=" + encodeURIComponent( params[ i ] ) );
    }

    return url + ( ( url.indexOf( "?" ) != -1 ) ? "&" : "?" ) + queryString.join( "&" );
  };

  // Integrate Rails CSRF token into file upload dialogs (link, image, attachment and flash)
  CKEDITOR.on( 'dialogDefinition', function( ev ){
    // Take the dialog name and its definition from the event data.
    var dialogName = ev.data.name;
    var dialogDefinition = ev.data.definition;
    var content, upload;

    if (CKEDITOR.tools.indexOf(['link', 'image', 'attachment', 'flash'], dialogName) > -1) {
      content = (dialogDefinition.getContents('Upload') || dialogDefinition.getContents('upload'));
      upload = (content == null ? null : content.get('upload'));

      if (upload && upload.filebrowser && upload.filebrowser['params'] === undefined) {
        upload.filebrowser['params'] = config.filebrowserParams();
        upload.action = config.addQueryString(upload.action, upload.filebrowser['params']);
      }
    }
  });
};<|endoftext|>


<commit_before>CKEDITOR.editorConfig = function(config) {

  config.extraPlugins = 'ajaxsave,generatepdf,eqneditor,charcount,texttransform,footnote,epigraph,verse,chapter,smallskip,medskip,bigskip';

  /* Char Count Plugin */
  config.maxLength = 0;
  config.maxWords = 0;

  config.font_defaultLabel = 'Courier';
  config.fontSize_defaultLabel = '12px';

  config.keystrokes =
  [
    [ CKEDITOR.ALT + 121 /*F10*/, 'toolbarFocus' ],
    [ CKEDITOR.ALT + 122 /*F11*/, 'elementsPathFocus' ],

    [ CKEDITOR.SHIFT + 121 /*F10*/, 'contextMenu' ],

    [ CKEDITOR.CTRL + 90 /*Z*/, 'undo' ],
    [ CKEDITOR.CTRL + 89 /*Y*/, 'redo' ],
    [ CKEDITOR.CTRL + CKEDITOR.SHIFT + 90 /*Z*/, 'redo' ],

    [ CKEDITOR.CTRL + 76 /*L*/, 'link' ],

    [ CKEDITOR.CTRL + 66 /*B*/, 'bold' ],
    [ CKEDITOR.CTRL + 73 /*I*/, 'italic' ],
    [ CKEDITOR.CTRL + 85 /*U*/, 'underline' ],

    [ CKEDITOR.ALT + 109 /*-*/, 'toolbarCollapse' ]
  ];

  config.toolbar = [
    { name: 'clipboard', items : [ 'Undo','Redo' ] },
    { name: 'editing', items : ['Find','Replace','-','SelectAll','-','SpellChecker', 'Scayt' ] },
    { name: 'links', items : [ 'Anchor' ] },
    { name: 'document', items : [ 'Source' ] },
    { name: 'tools', items : [ 'Maximize', 'ShowBlocks' ] },
    { name: 'plugins', items: [ 'TransformTextToUppercase', 'TransformTextToLowercase', 'TransformTextCapitalize', 'TransformTextSwitcher', '-','CharCount' ] },
    '/',
    { name: 'basicstyles', items : [ 'Bold','Italic','Subscript','Superscript','-','RemoveFormat' ] },
    { name: 'paragraph', items : [ 'NumberedList','BulletedList','-','Outdent','Indent','-','Blockquote','-','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock' ] },
    { name: 'insert', items : [ 'Image','Table','HorizontalRule', 'SpecialChar','EqnEditor', 'FootNote', 'Epigraph', 'Verse', 'Chapter' ] },
    { name: 'colors', items : [ 'TextColor','BGColor' ] },
    { name: 'styles', items : [ 'Format', 'Smallskip', 'Medskip', 'Bigskip' ] }
  ];

  // show save and generate pdf buttons.
  if (CKEDITOR.instances.text_content != undefined){
    config.toolbar[1].items = $.merge(['AjaxSave','GeneratePdf'], config.toolbar[1].items);
  }

  config.language = 'pt-BR';

  /* Filebrowser routes */
  // The location of an external file browser, that should be launched when "Browse Server" button is pressed.
  config.filebrowserBrowseUrl = "/ckeditor/attachment_files";

  // The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Flash dialog.
  config.filebrowserFlashBrowseUrl = "/ckeditor/attachment_files";

  // The location of a script that handles file uploads in the Flash dialog.
  config.filebrowserFlashUploadUrl = "/ckeditor/attachment_files";

  // The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Link tab of Image dialog.
  config.filebrowserImageBrowseLinkUrl = "/ckeditor/pictures";

  // The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Image dialog.
  config.filebrowserImageBrowseUrl = "/ckeditor/pictures";

  // The location of a script that handles file uploads in the Image dialog.
  config.filebrowserImageUploadUrl = "/ckeditor/pictures";

  // The location of a script that handles file uploads.
  config.filebrowserUploadUrl = "/ckeditor/attachment_files";

  // Because of
  config.hideDialogFields = "image:info:htmlPreview";

  config.allowedContent =
      'h1 h2 h3 h4 h5 h6 strong em blockquote ol ul li;' +
      'a(latex-close)[*]; a[!name,!href];' +
      'img(small-intention)[*]; img(medium-intention)[*]; img(big-intention)[*];' +
      'table tr th td caption;' +
      'span(latex-inputbox); span(epigraph-author); span{color,background-color};' +
      'p[align]; p{align,text-align};' +
      'div[!id];' +
      'section(epigraph); section(chapter);' +
      'div(verse); div(smallskip); div(medskip); div(bigskip);';

  // Rails CSRF token
  config.filebrowserParams = function(){
    var csrf_token, csrf_param, meta,
        metas = document.getElementsByTagName('meta'),
        params = new Object();

    for ( var i = 0 ; i < metas.length ; i++ ){
      meta = metas[i];

      switch(meta.name) {
        case "csrf-token":
          csrf_token = meta.content;
          break;
        case "csrf-param":
          csrf_param = meta.content;
          break;
        default:
          continue;
      }
    }

    if (csrf_param !== undefined && csrf_token !== undefined) {
      params[csrf_param] = csrf_token;
    }

    return params;
  };

  config.addQueryString = function( url, params ){
    var queryString = [];

    if ( !params ) {
      return url;
    } else {
      for ( var i in params )
        queryString.push( i + "=" + encodeURIComponent( params[ i ] ) );
    }

    return url + ( ( url.indexOf( "?" ) != -1 ) ? "&" : "?" ) + queryString.join( "&" );
  };

  // Integrate Rails CSRF token into file upload dialogs (link, image, attachment and flash)
  CKEDITOR.on( 'dialogDefinition', function( ev ){
    // Take the dialog name and its definition from the event data.
    var dialogName = ev.data.name;
    var dialogDefinition = ev.data.definition;
    var content, upload;

    if (CKEDITOR.tools.indexOf(['link', 'image', 'attachment', 'flash'], dialogName) > -1) {
      content = (dialogDefinition.getContents('Upload') || dialogDefinition.getContents('upload'));
      upload = (content == null ? null : content.get('upload'));

      if (upload && upload.filebrowser && upload.filebrowser['params'] === undefined) {
        upload.filebrowser['params'] = config.filebrowserParams();
        upload.action = config.addQueryString(upload.action, upload.filebrowser['params']);
      }
    }

    //customize class field for childrens approuch [VIZIR]
    if (dialogName == 'image')
    {
      for (var i in dialogDefinition.contents)
      {
        var contents = dialogDefinition.contents[i];

        if (contents.id == "info")
        {
          var classField = dialogDefinition.contents[3].elements[2];
          dialogDefinition.contents[3].elements[2] = null;

          classField.widths[0] = '100%';
          classField.widths[1] = '0%';
          classField.children[0].label = 'Intenção de tamanho para a imagem publicada';
          classField.children[0].type = 'select';
          classField.children[0].default = 'medium-intention';
          classField.children[0].items = [];
          classField.children[0].items.push(['Imagem com Tamanho Pequeno','small-intention']);
          classField.children[0].items.push(['Imagem com Tamanho Médio','medium-intention']);
          classField.children[0].items.push(['Imagem com Tamanho Grande','big-intention']);
          delete classField.children[1];
          contents.elements.splice(1, 0, classField);
          contents.elements[2].label = 'Legenda da Imagem';
          delete contents.elements[3].children[0].children[0]; //remove the width, heigth, border, etc fields
        }
      }

      dialogDefinition.onLoad = function () {
        var dialog = CKEDITOR.dialog.getCurrent();

        var elem = dialog.getContentElement('info','htmlPreview');
        elem.getElement().hide();

        $(".cke_dialog_ui_select").show();
        $(".cke_dialog_ui_input_select").show();

        $('#cke_50_textInput').attr('disabled','disabled');

        dialog.hidePage('advanced');
      };
    }
  });
};

CKEDITOR.addCss('body { font-family: Courier; font-size: 12px; }');
/*Image Upload Customization*/
CKEDITOR.addCss('.small-intention { zoom: 0.3; -moz-transform: scale(0.3); max-width: 100%;}');
CKEDITOR.addCss('.medium-intention { zoom: 0.6; -moz-transform: scale(0.6); max-width: 100%;}');
CKEDITOR.addCss('.big-intention { zoom: 1; -moz-transform: scale(1); max-width: 100%;}');
/*LaTeX Input Plugin*/
CKEDITOR.addCss('.latex-inputbox { background-color: #73b8f7; cursor: pointer; -webkit-border-radius: 3px; border-radius: 5px; padding: 3px; margin: 3px; margin-left: 5px;}');
CKEDITOR.addCss('.latex-close { cursor: pointer; font-size: 12px; color: #fff; padding: 5px; }');
/*Epigraph Plugin*/
CKEDITOR.addCss('.epigraph { padding-left: 300px; }');
CKEDITOR.addCss('.epigraph-author { display: block; float: right; }');
/*Verse Plugin*/
CKEDITOR.addCss('.verse{ font-style: oblique; background-color: #F5F9FA; }');
/*Chapter Plugin*/
CKEDITOR.addCss('.chapter { background-color: #5e5e5e; color: #fff; }');
CKEDITOR.addCss('.chapter p{ text-align:right; }');
CKEDITOR.addCss('.chapter h3{ font-style: oblique; }');
/*SmallSkip Plugin*/
CKEDITOR.addCss('.smallskip { background-color: #f0f0f0; height: 14px; }');
/*MedSkip Plugin*/
CKEDITOR.addCss('.medskip { background-color: #e0e0e0; height: 28px; }');
/*BigSkip Plugin*/
CKEDITOR.addCss('.bigskip { background-color: #d0d0d0; height: 56px; }');

for (var i in CKEDITOR.instances) {
    (function(i){
        CKEDITOR.instances[i].on('contentDom', function() {
          CKEDITOR.instances[i].document.on('keyup', function(event) {
              var key = event.data.getKey();
              var editor = CKEDITOR.instances[i];
              var content = editor.document.getBody().getHtml();
              if (content.match(/@(.*?)@/) != null){
                var inside = content.match(/@(.*?)@/)[0];
                inside = inside.replace(/@/g,"");
                if (inside.length != 0){
                  content = content.replace(/@(.*?)@/, ""+inside+"× ");
                  editor.document.getBody().setHtml(content);
                }
                var range = editor.createRange();
                range.moveToElementEditEnd( range.root );
                editor.getSelection().selectRanges( [ range ] );
              }
            });
        });

        CKEDITOR.instances[i].on('instanceReady', function() {
          var content = CKEDITOR.instances[i].document.getBody().getHtml();
          content = content.replace(/data-cke-pa-onclick/g, "onclick");
          CKEDITOR.instances[i].document.getBody().setHtml(content);
        });

    })(i);
}
<commit_msg>2.0.2 #14 https://trello.com/c/qKj9E7IH<commit_after>CKEDITOR.editorConfig = function(config) {

  config.extraPlugins = 'latexformater,ajaxsave,generatepdf,eqneditor,charcount,texttransform,footnote,epigraph,verse,chapter,smallskip,medskip,bigskip';

  /* Char Count Plugin */
  config.maxLength = 0;
  config.maxWords = 0;

  config.font_defaultLabel = 'Courier';
  config.fontSize_defaultLabel = '12px';

  config.keystrokes =
  [
    [ CKEDITOR.ALT + 121 /*F10*/, 'toolbarFocus' ],
    [ CKEDITOR.ALT + 122 /*F11*/, 'elementsPathFocus' ],

    [ CKEDITOR.SHIFT + 121 /*F10*/, 'contextMenu' ],

    [ CKEDITOR.CTRL + 90 /*Z*/, 'undo' ],
    [ CKEDITOR.CTRL + 89 /*Y*/, 'redo' ],
    [ CKEDITOR.CTRL + CKEDITOR.SHIFT + 90 /*Z*/, 'redo' ],

    [ CKEDITOR.CTRL + 76 /*L*/, 'link' ],

    [ CKEDITOR.CTRL + 66 /*B*/, 'bold' ],
    [ CKEDITOR.CTRL + 73 /*I*/, 'italic' ],
    [ CKEDITOR.CTRL + 85 /*U*/, 'underline' ],

    [ CKEDITOR.ALT + 109 /*-*/, 'toolbarCollapse' ]
  ];

  config.toolbar = [
    { name: 'clipboard', items : [ 'Undo','Redo' ] },
    { name: 'editing', items : ['Find','Replace','-','SelectAll','-','SpellChecker', 'Scayt' ] },
    { name: 'links', items : [ 'Anchor' ] },
    { name: 'document', items : [ 'Source' ] },
    { name: 'tools', items : [ 'Maximize', 'ShowBlocks' ] },
    { name: 'plugins', items: [ 'TransformTextToUppercase', 'TransformTextToLowercase', 'TransformTextCapitalize', 'TransformTextSwitcher', '-','CharCount' ] },
    '/',
    { name: 'basicstyles', items : [ 'Bold','Italic','Subscript','Superscript','-','RemoveFormat' ] },
    { name: 'paragraph', items : [ 'NumberedList','BulletedList','-','Outdent','Indent','-','Blockquote','-','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock' ] },
    { name: 'insert', items : [ 'Image','Table','HorizontalRule', 'SpecialChar','EqnEditor', 'FootNote', 'Epigraph', 'Verse', 'Chapter' ] },
    { name: 'colors', items : [ 'TextColor','BGColor' ] },
    { name: 'styles', items : [ 'Format', 'Smallskip', 'Medskip', 'Bigskip', 'LatexFormater' ] }
  ];

  // show save and generate pdf buttons.
  if (CKEDITOR.instances.text_content != undefined){
    config.toolbar[1].items = $.merge(['AjaxSave','GeneratePdf'], config.toolbar[1].items);
  }

  config.language = 'pt-BR';

  /* Filebrowser routes */
  // The location of an external file browser, that should be launched when "Browse Server" button is pressed.
  config.filebrowserBrowseUrl = "/ckeditor/attachment_files";

  // The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Flash dialog.
  config.filebrowserFlashBrowseUrl = "/ckeditor/attachment_files";

  // The location of a script that handles file uploads in the Flash dialog.
  config.filebrowserFlashUploadUrl = "/ckeditor/attachment_files";

  // The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Link tab of Image dialog.
  config.filebrowserImageBrowseLinkUrl = "/ckeditor/pictures";

  // The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Image dialog.
  config.filebrowserImageBrowseUrl = "/ckeditor/pictures";

  // The location of a script that handles file uploads in the Image dialog.
  config.filebrowserImageUploadUrl = "/ckeditor/pictures";

  // The location of a script that handles file uploads.
  config.filebrowserUploadUrl = "/ckeditor/attachment_files";

  // Because of
  config.hideDialogFields = "image:info:htmlPreview";

  config.allowedContent =
      'h1 h2 h3 h4 h5 h6 strong em blockquote ol ul li;' +
      'a(latex-close)[*]; a[!name,!href];' +
      'img(small-intention)[*]; img(medium-intention)[*]; img(big-intention)[*];' +
      'table tr th td caption;' +
      'span(latex-inputbox); span(epigraph-author); span{color,background-color};' +
      'p[align]; p{align,text-align};' +
      'div[!id];' +
      'section(epigraph); section(chapter);' +
      'div(verse); div(smallskip); div(medskip); div(bigskip);';

  // Rails CSRF token
  config.filebrowserParams = function(){
    var csrf_token, csrf_param, meta,
        metas = document.getElementsByTagName('meta'),
        params = new Object();

    for ( var i = 0 ; i < metas.length ; i++ ){
      meta = metas[i];

      switch(meta.name) {
        case "csrf-token":
          csrf_token = meta.content;
          break;
        case "csrf-param":
          csrf_param = meta.content;
          break;
        default:
          continue;
      }
    }

    if (csrf_param !== undefined && csrf_token !== undefined) {
      params[csrf_param] = csrf_token;
    }

    return params;
  };

  config.addQueryString = function( url, params ){
    var queryString = [];

    if ( !params ) {
      return url;
    } else {
      for ( var i in params )
        queryString.push( i + "=" + encodeURIComponent( params[ i ] ) );
    }

    return url + ( ( url.indexOf( "?" ) != -1 ) ? "&" : "?" ) + queryString.join( "&" );
  };

  // Integrate Rails CSRF token into file upload dialogs (link, image, attachment and flash)
  CKEDITOR.on( 'dialogDefinition', function( ev ){
    // Take the dialog name and its definition from the event data.
    var dialogName = ev.data.name;
    var dialogDefinition = ev.data.definition;
    var content, upload;

    if (CKEDITOR.tools.indexOf(['link', 'image', 'attachment', 'flash'], dialogName) > -1) {
      content = (dialogDefinition.getContents('Upload') || dialogDefinition.getContents('upload'));
      upload = (content == null ? null : content.get('upload'));

      if (upload && upload.filebrowser && upload.filebrowser['params'] === undefined) {
        upload.filebrowser['params'] = config.filebrowserParams();
        upload.action = config.addQueryString(upload.action, upload.filebrowser['params']);
      }
    }

    //customize class field for childrens approuch [VIZIR]
    if (dialogName == 'image')
    {
      for (var i in dialogDefinition.contents)
      {
        var contents = dialogDefinition.contents[i];

        if (contents.id == "info")
        {
          var classField = dialogDefinition.contents[3].elements[2];
          dialogDefinition.contents[3].elements[2] = null;

          classField.widths[0] = '100%';
          classField.widths[1] = '0%';
          classField.children[0].label = 'Intenção de tamanho para a imagem publicada';
          classField.children[0].type = 'select';
          classField.children[0].default = 'medium-intention';
          classField.children[0].items = [];
          classField.children[0].items.push(['Imagem com Tamanho Pequeno','small-intention']);
          classField.children[0].items.push(['Imagem com Tamanho Médio','medium-intention']);
          classField.children[0].items.push(['Imagem com Tamanho Grande','big-intention']);
          delete classField.children[1];
          contents.elements.splice(1, 0, classField);
          contents.elements[2].label = 'Legenda da Imagem';
          delete contents.elements[3].children[0].children[0]; //remove the width, heigth, border, etc fields
        }
      }

      dialogDefinition.onLoad = function () {
        var dialog = CKEDITOR.dialog.getCurrent();

        var elem = dialog.getContentElement('info','htmlPreview');
        elem.getElement().hide();

        $(".cke_dialog_ui_select").show();
        $(".cke_dialog_ui_input_select").show();

        $('#cke_50_textInput').attr('disabled','disabled');

        dialog.hidePage('advanced');
      };
    }
  });
};

CKEDITOR.addCss('body { font-family: Courier; font-size: 12px; }');
/*Image Upload Customization*/
CKEDITOR.addCss('.small-intention { zoom: 0.3; -moz-transform: scale(0.3); max-width: 100%;}');
CKEDITOR.addCss('.medium-intention { zoom: 0.6; -moz-transform: scale(0.6); max-width: 100%;}');
CKEDITOR.addCss('.big-intention { zoom: 1; -moz-transform: scale(1); max-width: 100%;}');
/*LaTeX Input Plugin*/
CKEDITOR.addCss('.latex-inputbox { background-color: #73b8f7; cursor: pointer; -webkit-border-radius: 3px; border-radius: 5px; padding: 3px; margin: 3px; margin-left: 5px;}');
CKEDITOR.addCss('.latex-close { cursor: pointer; font-size: 12px; color: #fff; padding: 5px; }');
/*Epigraph Plugin*/
CKEDITOR.addCss('.epigraph { padding-left: 300px; }');
CKEDITOR.addCss('.epigraph-author { display: block; float: right; }');
/*Verse Plugin*/
CKEDITOR.addCss('.verse{ font-style: oblique; background-color: #F5F9FA; }');
/*Chapter Plugin*/
CKEDITOR.addCss('.chapter { background-color: #5e5e5e; color: #fff; }');
CKEDITOR.addCss('.chapter p{ text-align:right; }');
CKEDITOR.addCss('.chapter h3{ font-style: oblique; }');
/*SmallSkip Plugin*/
CKEDITOR.addCss('.smallskip { background-color: #f0f0f0; height: 14px; }');
/*MedSkip Plugin*/
CKEDITOR.addCss('.medskip { background-color: #e0e0e0; height: 28px; }');
/*BigSkip Plugin*/
CKEDITOR.addCss('.bigskip { background-color: #d0d0d0; height: 56px; }');

for (var i in CKEDITOR.instances) {
    (function(i){
        CKEDITOR.instances[i].on('contentDom', function() {
          CKEDITOR.instances[i].document.on('keyup', function(event) {
              var key = event.data.getKey();
              var editor = CKEDITOR.instances[i];
              var content = editor.document.getBody().getHtml();
              if (content.match(/@(.*?)@/) != null){
                var inside = content.match(/@(.*?)@/)[0];
                inside = inside.replace(/@/g,"");
                if (inside.length != 0){
                  content = content.replace(/@(.*?)@/, ""+inside+"× ");
                  editor.document.getBody().setHtml(content);
                }
                var range = editor.createRange();
                range.moveToElementEditEnd( range.root );
                editor.getSelection().selectRanges( [ range ] );
              }
            });
        });

        CKEDITOR.instances[i].on('instanceReady', function() {
          var content = CKEDITOR.instances[i].document.getBody().getHtml();
          content = content.replace(/data-cke-pa-onclick/g, "onclick");
          CKEDITOR.instances[i].document.getBody().setHtml(content);
        });

    })(i);
}
<|endoftext|>


<commit_before>//= require ./utils
//= require ./codec

Data.attr = function (type, options) {
    options = options || {};

    var meta = {
        type: type,
        isAttribute: true,
        options: options,
        codec: {
            key: function (key) {
                return key.decamelize();
            },

            decode: function (value) {
                var
                    parts = meta.type.split(':'),
                    type = parts[0],
                    qualifier = parts[1];

                return Data.codec[type].decode(value, qualifier);
            },

            encode: function (instance, attribute) {
                var
                    parts = meta.type.split(':'),
                    type = parts[0],
                    qualifier = parts[1],
                    value = attribute ? instance.get(attribute) : instance;

                return Data.codec[type].encode(value, qualifier);
            }
        }
    };

    return Ember.computed(function(key, value, oldValue) {
        if (arguments.length > 1) {
            var encodedValue = meta.codec.encode(value);
            this._changeAttribute(key, oldValue, encodedValue);
            this.set('_data.' + meta.codec.key(key), encodedValue);
        } else {
            value = this.get('_data.' + meta.codec.key(key));

            if (Ember.isNone(value)) {
                value = options.defaultValue;
            }
            value = meta.codec.decode(value);
        }
        return value;
    }).property('_data').meta(meta);
};

Data.embedded = function (type, options) {
    options = options || {};

    var meta = {
        type: type,
        isAttribute: true,
        options: options,
        codec: {
            key: function (key) {
                return key.decamelize();
            },

            encode: function (instance, attribute) {
                return instance.get(attribute).toJSON();
            }
        }
    };

    return Ember.computed(function(key, value, oldValue) {
        if (arguments.length > 1) {
            this._changeAttribute(key, oldValue, value);
            this.set('_data.' + meta.codec.key(key), value);
        } else {
            value = this.get('_data.' + meta.codec.key(key));

            if (value === undefined) {
                value = options.defaultValue;
            }
            value = Data.getType(type).load(value, {
                _embeddedContainer: this,
                _embeddedAttribute: key
            });
        }
        return value;
    }).property('_data').meta(meta);
};

Data.dynamicAttributable = Ember.Mixin.create({

    defineAttribute: function (key, definition) {
        Ember.defineProperty(this, key, Ember.computed(function (key, newValue, oldValue) {
            var result = newValue;
            if (arguments.length > 1) {
                Ember.set(this._data, key, result);
            } else {
                var decoder = definition.decoder || 'raw';
                result = Ember.get(this._data, key);
                switch (decoder) {
                case 'array':
                    if (Ember.typeOf(result) === 'object') { // fix JQuery serialization or object arrays...
                        var array = [];
                        Ember.keys(result).forEach(function (index) {
                            array[index] = result[index];
                        });
                        result = array;
                    }
                default:
                    // nope
                }
            }
            return result;
        }).property('_data.%@'.fmt(key)));

        if (Ember.isNone(Ember.get(this._data, key))) {
            Ember.set(this._data, key, definition.defaultValue);
        }
    },

    defineAttributes: function (object) {
        Ember.keys(object).forEach(function (key) {
            this.defineAttribute(key, object[key]);
        }, this);
    },

    resetAttributes: function (object) {
        this.set('_data', {});
        if (object) {
            this.defineAttributes(object);
        }
    },

    unknownProperty: function (propertyName) {
        if (this._data.hasOwnProperty(propertyName)) {
            return this._data[propertyName];
        }
    }
});

Data.belongsTo = function (type, options) {
    options = options || {};

    var meta = {
        type: type,
        isRelation: true,
        options: options,
        codec: {
            key: function (key) {
                return Data.belongsToKey(key);
            },

            encode: function (instance, attribute) {
                return instance.get('_data.' + this.key(attribute));
            }
        }
    };

    return Ember.computed(function(key, value, oldValue) {
        if (arguments.length > 1) {
            this.set('_data.' + meta.codec.key(key), value.get('id'));
            this.get('_relationsCache')[key] = value;
            Ember.run.next(this, function () {
                this._replaceRelation(key, oldValue, value);
                this.expireCaches();
            });
        } else {
            var
                type = Data.getType(meta.type),
                id = this.get('_data.' + meta.codec.key(key)),
                parent = meta.options.nested ? this : null,
                relationsCache = this.get('_relationsCache'),
                relation = relationsCache[key];

            if (relation) {
                return relation;
            }
            if (id) {
                relation = type.find(id, parent, { sync: true });
                relation.set('_owner', this);
                relationsCache[key] = relation;
            } else {
                relation = null;
            }
            return relation;
        }
    }).property('_data', '_relationsCache', '_cacheTimestamp').meta(meta);
};

Data.hasMany = function (type, options) {
    options = options || {};

    var meta = {
        type: type,
        isRelation: true,
        options: options,
        codec: {
            key: function (key) {
                return key.decamelize().singularize() + '_ids';
            },

            encode: function (instance, attribute) {
                return instance.get('_data.' + this.key(attribute));
            }
        }
    };

    return Ember.computed(function(key, value, oldValue) {
        if (arguments.length > 1) {
            Ember.assert('SHOULD NOT DO THAT, BRO', false);
        } else {
            var
                meta = this.constructor.metaForProperty(key),
                type = Data.getType(meta.type),
                ids = this.get('_data.' + meta.codec.key(key)),
                parent = meta.options.nested ? this : null,
                params,
                relationsCache = this.get('_relationsCache'),
                relation = relationsCache[key],
                content;

            if (relation) {
                // Ember.Logger.debug('hasMany(%@.%@): use cache'.fmt(type, key));
                return relation;
            }

            if (this.get('isNew')) {
                content = [];
                // Ember.Logger.debug('hasMany(%@.%@): empty set (new)'.fmt(type, key));
            } else {
                if (Ember.isEmpty(ids)) {
                    content = [];
                    // Ember.Logger.debug('hasMany(%@.%@): empty set'.fmt(type, key));
                } else {
                    if (meta.options.nestingParam) {
                        var
                            parts = meta.options.nestingParam.split(':'),
                            param = parts[1] || parts[0],
                            valuePath = parts[1] ? parts[0] : 'id';

                        params = {};
                        params[param] = this.get(valuePath);
                    }

                    content = type.find(ids, parent, { sync: true, params: params });
                    // Ember.Logger.debug('hasMany(%@.%@): retrieve %@'.fmt(type, key, ids));
                }
            }

            relation = Data.ModelArray.create({
                _type: meta.type,
                _owner: this,
                _field: key,
                content: content
            });
            content.forEach(function (record) {
                record.set('_container', relation);
            });
            this.get('_relationsCache')[key] = relation;
            return relation;
        }
    }).property('_data', '_relationsCache', '_cacheTimestamp').meta(meta);
};
<commit_msg>Avoid caching opaque dynamic attribute<commit_after>//= require ./utils
//= require ./codec

Data.attr = function (type, options) {
    options = options || {};

    var meta = {
        type: type,
        isAttribute: true,
        options: options,
        codec: {
            key: function (key) {
                return key.decamelize();
            },

            decode: function (value) {
                var
                    parts = meta.type.split(':'),
                    type = parts[0],
                    qualifier = parts[1];

                return Data.codec[type].decode(value, qualifier);
            },

            encode: function (instance, attribute) {
                var
                    parts = meta.type.split(':'),
                    type = parts[0],
                    qualifier = parts[1],
                    value = attribute ? instance.get(attribute) : instance;

                return Data.codec[type].encode(value, qualifier);
            }
        }
    };

    return Ember.computed(function(key, value, oldValue) {
        if (arguments.length > 1) {
            var encodedValue = meta.codec.encode(value);
            this._changeAttribute(key, oldValue, encodedValue);
            this.set('_data.' + meta.codec.key(key), encodedValue);
        } else {
            value = this.get('_data.' + meta.codec.key(key));

            if (Ember.isNone(value)) {
                value = options.defaultValue;
            }
            value = meta.codec.decode(value);
        }
        return value;
    }).property('_data').meta(meta);
};

Data.embedded = function (type, options) {
    options = options || {};

    var meta = {
        type: type,
        isAttribute: true,
        options: options,
        codec: {
            key: function (key) {
                return key.decamelize();
            },

            encode: function (instance, attribute) {
                return instance.get(attribute).toJSON();
            }
        }
    };

    return Ember.computed(function(key, value, oldValue) {
        if (arguments.length > 1) {
            this._changeAttribute(key, oldValue, value);
            this.set('_data.' + meta.codec.key(key), value);
        } else {
            value = this.get('_data.' + meta.codec.key(key));

            if (value === undefined) {
                value = options.defaultValue;
            }
            value = Data.getType(type).load(value, {
                _embeddedContainer: this,
                _embeddedAttribute: key
            });
        }
        return value;
    }).property('_data').meta(meta);
};

Data.dynamicAttributable = Ember.Mixin.create({

    defineAttribute: function (key, definition) {
        Ember.defineProperty(this, key, Ember.computed(function (key, newValue, oldValue) {
            var result = newValue;
            if (arguments.length > 1) {
                Ember.set(this._data, key, result);
            } else {
                var decoder = definition.decoder || 'raw';
                result = Ember.get(this._data, key);
                switch (decoder) {
                case 'array':
                    if (Ember.typeOf(result) === 'object') { // fix JQuery serialization or object arrays...
                        var array = [];
                        Ember.keys(result).forEach(function (index) {
                            array[index] = result[index];
                        });
                        result = array;
                    }
                default:
                    // nope
                }
            }
            return result;
        }).property('_data', '_data.%@'.fmt(key)).cacheable(false));

        if (Ember.isNone(Ember.get(this._data, key))) {
            Ember.set(this._data, key, definition.defaultValue);
        }
    },

    defineAttributes: function (object) {
        Ember.keys(object).forEach(function (key) {
            this.defineAttribute(key, object[key]);
        }, this);
    },

    resetAttributes: function (object) {
        this.set('_data', {});
        if (object) {
            this.defineAttributes(object);
        }
    },

    unknownProperty: function (propertyName) {
        if (this._data.hasOwnProperty(propertyName)) {
            return this._data[propertyName];
        }
    }
});

Data.belongsTo = function (type, options) {
    options = options || {};

    var meta = {
        type: type,
        isRelation: true,
        options: options,
        codec: {
            key: function (key) {
                return Data.belongsToKey(key);
            },

            encode: function (instance, attribute) {
                return instance.get('_data.' + this.key(attribute));
            }
        }
    };

    return Ember.computed(function(key, value, oldValue) {
        if (arguments.length > 1) {
            this.set('_data.' + meta.codec.key(key), value.get('id'));
            this.get('_relationsCache')[key] = value;
            Ember.run.next(this, function () {
                this._replaceRelation(key, oldValue, value);
                this.expireCaches();
            });
        } else {
            var
                type = Data.getType(meta.type),
                id = this.get('_data.' + meta.codec.key(key)),
                parent = meta.options.nested ? this : null,
                relationsCache = this.get('_relationsCache'),
                relation = relationsCache[key];

            if (relation) {
                return relation;
            }
            if (id) {
                relation = type.find(id, parent, { sync: true });
                relation.set('_owner', this);
                relationsCache[key] = relation;
            } else {
                relation = null;
            }
            return relation;
        }
    }).property('_data', '_relationsCache', '_cacheTimestamp').meta(meta);
};

Data.hasMany = function (type, options) {
    options = options || {};

    var meta = {
        type: type,
        isRelation: true,
        options: options,
        codec: {
            key: function (key) {
                return key.decamelize().singularize() + '_ids';
            },

            encode: function (instance, attribute) {
                return instance.get('_data.' + this.key(attribute));
            }
        }
    };

    return Ember.computed(function(key, value, oldValue) {
        if (arguments.length > 1) {
            Ember.assert('SHOULD NOT DO THAT, BRO', false);
        } else {
            var
                meta = this.constructor.metaForProperty(key),
                type = Data.getType(meta.type),
                ids = this.get('_data.' + meta.codec.key(key)),
                parent = meta.options.nested ? this : null,
                params,
                relationsCache = this.get('_relationsCache'),
                relation = relationsCache[key],
                content;

            if (relation) {
                // Ember.Logger.debug('hasMany(%@.%@): use cache'.fmt(type, key));
                return relation;
            }

            if (this.get('isNew')) {
                content = [];
                // Ember.Logger.debug('hasMany(%@.%@): empty set (new)'.fmt(type, key));
            } else {
                if (Ember.isEmpty(ids)) {
                    content = [];
                    // Ember.Logger.debug('hasMany(%@.%@): empty set'.fmt(type, key));
                } else {
                    if (meta.options.nestingParam) {
                        var
                            parts = meta.options.nestingParam.split(':'),
                            param = parts[1] || parts[0],
                            valuePath = parts[1] ? parts[0] : 'id';

                        params = {};
                        params[param] = this.get(valuePath);
                    }

                    content = type.find(ids, parent, { sync: true, params: params });
                    // Ember.Logger.debug('hasMany(%@.%@): retrieve %@'.fmt(type, key, ids));
                }
            }

            relation = Data.ModelArray.create({
                _type: meta.type,
                _owner: this,
                _field: key,
                content: content
            });
            content.forEach(function (record) {
                record.set('_container', relation);
            });
            this.get('_relationsCache')[key] = relation;
            return relation;
        }
    }).property('_data', '_relationsCache', '_cacheTimestamp').meta(meta);
};
<|endoftext|>


<commit_before>'use strict';

define(["app"], function(app) {

app.directive("drag", ["$rootScope", "$timeout",
  function($rootScope, $timeout) {

  var currentElement, firstOffsetX, firstOffsetY, originalElement;
  var containerId = "content";
  var container = angular.element(document.getElementById(containerId));
  var elements = [];
  var listen = true;

  function calculPosition(evt, useOffsetEvt) {
    var offsetX = firstOffsetX;
    var offsetY = firstOffsetY;
    if(useOffsetEvt == true) {
      offsetX = evt.offsetX;
      offsetY = evt.offsetY;
      firstOffsetX = evt.offsetX;
      firstOffsetY = evt.offsetY;
    }
    return {
      x: (evt.pageX - offsetX),
      y: (evt.pageY - offsetY)
    };
  }

  function isInside(c1, c2) {//c == {x:int, y:int, w:int, h:int}
    return c2.x > c1.x && c2.x+c2.w < c1.x+c1.w &&
      c2.y > c1.y && c2.y+c2.h < c1.y+c1.h;
  }

  function buildCarreMouseEvt(evt) {
    return {
      x: (evt.pageX - evt.offsetX),
      y: (evt.pageY - evt.offsetY),
      w: 100,
      h: 100
    }
  }

  function buildCarreElmt(elmt) {
    return {
      x: elmt.offsetLeft,
      y: elmt.offsetTop,
      w: elmt.clientWidth,
      h: elmt.clientHeight
    }
  }

  container.bind('mousemove', function(evt) {
    $timeout(function() {
      if(currentElement) {
        var position = calculPosition(evt);
        currentElement[0].style.position = "absolute";
        currentElement[0].style.top = position.y+"px";
        currentElement[0].style.left = position.x+"px";
        for(var i=0; i<elements.length && listen == true; i++) {
          var elm = document.getElementById(elements[i].originalId);
          var inside = isInside(buildCarreElmt(elm), buildCarreMouseEvt(evt));
          if(inside &&
            currentElement.dragData.title != elements[i].dragData.title) {
            $rootScope.$broadcast("moveColumnEvent", currentElement.dragData, elements[i].dragData);
            listen = false;
            var oldWidth = currentElement[0].style.width;
            var oldHeight = currentElement[0].style.height;
            currentElement[0].style.width = elm.style.width;
            currentElement[0].style.height = elm.style.height;
            originalElement.style.width = elm.style.width;
            originalElement.style.height = elm.style.height;
            elm.style.width = oldWidth;
            elm.style.height = oldHeight;
            $timeout(function() {
              listen = true;
              var elm2 = document.getElementById(elements[i].originalId);
            }, 1000);
            return;
          }
        }
      }
    }, 0);
  });

  container.bind('mouseup', function(evt) {
    if(currentElement != undefined) {
      document.getElementById(containerId).removeChild(currentElement[0]);
      currentElement = undefined;
      angular.element(originalElement).removeClass("columnDrag");
      $rootScope.$broadcast("dropColumnEvent");
    }
  });

  return {
    restrict: 'A',
    link: function(scope, element, attrs)  {
      scope.dragStyle = attrs["dragstyle"];
      element.bind('mousedown', function(evt) {
        if(currentElement == undefined) {
          var div = document.createElement("div");
          originalElement = document.getElementById(attrs["dragElementId"]);
          div.innerHTML = originalElement.innerHTML;
          div.className = originalElement.className;
          document.getElementById(containerId).appendChild(div);
          currentElement = angular.element(div);
          currentElement.dragData = scope[attrs["drag"]];
          var position = calculPosition(evt, true);
          currentElement[0].style.position = "absolute";
          currentElement[0].style.top = position.y+"px";
          currentElement[0].style.left = position.x+"px";
          currentElement[0].style.width = originalElement.style.width;
          currentElement[0].style.height = originalElement.style.height;
          angular.element(originalElement).addClass("columnDrag");
        }
      });
      attrs.$observe('dragElementId', function(val) {
        if(element.added === undefined) {
          element.added = true;
          var elmt = {
            dragData: scope[attrs["drag"]],
            originalId: val
          };
          elements.push(elmt);
        } else {
          for (var i = 0; i < elements.length; i++) {
            if(elements[i].originalId == val) {
              elements.splice(i, 1);
            }
          };
          var elmt = {
            dragData: scope[attrs["drag"]],
            originalId: val
          };
          elements.push(elmt);
        }
      });
    }
  }

}]);

return app;
});<commit_msg>clean code<commit_after>'use strict';

define(["app"], function(app) {

app.directive("drag", ["$rootScope", "$timeout",
  function($rootScope, $timeout) {

  var currentElement, firstOffsetX, firstOffsetY, originalElement;
  var containerId = "content";
  var container = angular.element(document.getElementById(containerId));
  var elements = [];
  var listen = true;

  function calculPosition(evt, useOffsetEvt) {
    var offsetX = firstOffsetX;
    var offsetY = firstOffsetY;
    if(useOffsetEvt == true) {
      offsetX = evt.offsetX;
      offsetY = evt.offsetY;
      firstOffsetX = evt.offsetX;
      firstOffsetY = evt.offsetY;
    }
    return {
      x: (evt.pageX - offsetX),
      y: (evt.pageY - offsetY)
    };
  }

  function isInside(c1, c2) {//c == {x:int, y:int, w:int, h:int}
    return c2.x > c1.x && c2.x+c2.w < c1.x+c1.w &&
      c2.y > c1.y && c2.y+c2.h < c1.y+c1.h;
  }

  function buildCarreMouseEvt(evt) {
    return {
      x: (evt.pageX - evt.offsetX),
      y: (evt.pageY - evt.offsetY),
      w: 100,
      h: 100
    }
  }

  function buildCarreElmt(elmt) {
    return {
      x: elmt.offsetLeft,
      y: elmt.offsetTop,
      w: elmt.clientWidth,
      h: elmt.clientHeight
    }
  }

  function deleteElement(originalId) {
    console.log("remove", originalId);
    for (var i = 0; i < elements.length; i++) {
      if(elements[i].originalId == originalId) {
        console.log("really remove", originalId);
        return elements.splice(i, 1);
      }
    }
  }

  container.bind('mousemove', function(evt) {
    $timeout(function() {
      if(currentElement) {
        var position = calculPosition(evt);
        currentElement[0].style.position = "absolute";
        currentElement[0].style.top = position.y+"px";
        currentElement[0].style.left = position.x+"px";
        console.log("elements", elements);
        for(var i=0; i<elements.length && listen == true; i++) {
          var elm = document.getElementById(elements[i].originalId);
          if(elm) {//FIXME : remove and fix it !
            var inside = isInside(buildCarreElmt(elm), buildCarreMouseEvt(evt));
            if(inside &&
              currentElement.dragData.title != elements[i].dragData.title) {
              $rootScope.$broadcast("moveColumnEvent", currentElement.dragData, elements[i].dragData);
              listen = false;
              var oldWidth = currentElement[0].style.width;
              var oldHeight = currentElement[0].style.height;
              currentElement[0].style.width = elm.style.width;
              currentElement[0].style.height = elm.style.height;
              originalElement.style.width = elm.style.width;
              originalElement.style.height = elm.style.height;
              elm.style.width = oldWidth;
              elm.style.height = oldHeight;
              $timeout(function() {
                listen = true;
                var elm2 = document.getElementById(elements[i].originalId);
              }, 1000);
              return;
            }
          }
        }
      }
    }, 0);
  });

  container.bind('mouseup', function(evt) {
    if(currentElement != undefined) {
      document.getElementById(containerId).removeChild(currentElement[0]);
      currentElement = undefined;
      angular.element(originalElement).removeClass("columnDrag");
      $rootScope.$broadcast("dropColumnEvent");
    }
  });

  return {
    restrict: 'A',
    link: function(scope, element, attrs)  {
      scope.dragStyle = attrs["dragstyle"];
      element.bind('mousedown', function(evt) {
        if(currentElement == undefined) {
          var div = document.createElement("div");
          originalElement = document.getElementById(attrs["dragElementId"]);
          div.innerHTML = originalElement.innerHTML;
          div.className = originalElement.className;
          document.getElementById(containerId).appendChild(div);
          currentElement = angular.element(div);
          currentElement.dragData = scope[attrs["drag"]];
          var position = calculPosition(evt, true);
          currentElement[0].style.position = "absolute";
          currentElement[0].style.top = position.y+"px";
          currentElement[0].style.left = position.x+"px";
          currentElement[0].style.width = originalElement.style.width;
          currentElement[0].style.height = originalElement.style.height;
          angular.element(originalElement).addClass("columnDrag");
        }
      });
      attrs.$observe('dragElementId', function(val) {
        if(element.added === undefined) {
          element.added = true;
          element.originalId = val;
        } else {
          deleteElement(val);
        }
        var elmt = {
          dragData: scope[attrs["drag"]],
          originalId: val
        };
        elements.push(elmt);
      });
      element.bind("$destroy", function() {
        console.log("DESTROY", element.originalId);
        deleteElement(element.originalId);
      });
    }
  }

}]);

return app;
});<|endoftext|>


<commit_before>$(() => {
  function applySelect2(selector) {
    let $element = $(selector);
    let options = {
      placeholder: '選択してください',
      allowClear: $element.data("select2-allow-clear")
    };
    $element.select2(options);
  }

  function setupOrder($element, target) {
    let orders = $(target).map((_i, el) => {
      return Number($(el).val());
    }).toArray();

    let maxOrder = Math.max(0, ...orders);
    $element.find(target).val(maxOrder + 1);
  }

  applySelect2('select.select2');

  $(document).on('cocoon:after-insert', (e, inserted) => {
    let $element = $(inserted[0]);

    applySelect2($element.find('select.select2'));
    setupOrder($element, '.credit-order-value');
    setupOrder($element, '.categorization-order-value');
  });
});
<commit_msg>Apply select2 for each element properly<commit_after>$(() => {
  function applySelect2(selector) {
    let $elements = $(selector);
    $elements.each((i, e) => {
      let $element = $(e);
      let options = {
        placeholder: '選択してください',
        allowClear: $element.data('select2-allow-clear')
      };
      $element.select2(options);
    })
  }

  function setupOrder($element, target) {
    let orders = $(target).map((_i, el) => {
      return Number($(el).val());
    }).toArray();

    let maxOrder = Math.max(0, ...orders);
    $element.find(target).val(maxOrder + 1);
  }

  applySelect2('select.select2');

  $(document).on('cocoon:after-insert', (e, inserted) => {
    let $element = $(inserted[0]);

    applySelect2($element.find('select.select2'));
    setupOrder($element, '.credit-order-value');
    setupOrder($element, '.categorization-order-value');
  });
});
<|endoftext|>


<commit_before>! function ()
{
  var opt = { fileUpload: '#show-me-the-attachment-button', buttons: ['html'] }

  opt.buttons.add = function (split)
  {
    this.push ('|'); this.push.apply (this, split.split (' ')); return this
  }
  opt.buttons
  .add ('formatting')
  .add ('bold italic underline')
  .add ('unorderedlist orderedlist')
  .add ('outdent indent')
  .add ('video image file link table')
  .add ('alignleft aligncenter alignright justify')
  .add ('horizontalrule')

  $ (function () { $ ('[koi-wysiwyg]').liveQuery (run) })

  function run ()
  {
    var app, $box, $editor, $toolBar
    var $win = $ (window), $textArea = $ (this), $form = $textArea.closest ('form')
    var iFrame, iQuery, iWindow, iDocument, iHead, iBody, iScript, iStyle, iTextArea

    $textArea.hide ().closest ('form').on ('submit', submit)

    iFrame = $ ('').insertAfter ($textArea).load (loadFrame)
    .attr ('src', '/wysiwyg.html?' + Math.random ())
    .attr ('width', '100%')
    .attr ('height', '100%')
    .attr ('frameborder', '0')

    function submit ()
    {
      $editor.find ('img').each (function ()
      {
        var $img = $ (this)
        var src = $img.attr ('src').split ('?')
        var path = src [0]
        var params = src [1]
        var deparams = params ? $.deparam (params) : {}
        if (params)
        {
          for (var dim in { width:true, height:true }) deparams [dim] = parseInt ($img.css (dim))
          $img.attr ('src', path + '?' + $.param (deparams))
        }
        else $img.attr ('style', '');
      })
      if (iTextArea.is (':hidden')) app.syncCode ()
      else app.toggle ()
      $textArea.val ($editor[0].innerHTML)
      //$textArea.val (iTextArea.val ().replace (/(\s* \s*)+/g, ' '))
    }

    function resize ()
    {
      var height = iBody.outerHeight () //+ $toolBar.outerHeight ()
      iFrame.height (height)
    }

    function loadFrame ()
    {
      iWindow   = iFrame.contentWindow ()
      iDocument = iFrame.contentDocument ()

      iHead     = iDocument.getElementsByTagName ('head') [0]
      iBody     = iDocument.getElementsByTagName ('body') [0]

      iTextArea = iDocument.createElement ('textarea')
      iTextArea.value = $textArea.val ()
      iBody.appendChild (iTextArea)

      iStyle       = iDocument.createElement ('link')
      iStyle.rel   = 'stylesheet'
      iStyle.type  = 'text/css'
      iStyle.media = 'screen'
      iStyle.href  = '/assets/koi/jquery/redactor.css'
      iHead.appendChild (iStyle)

      iScript      = iDocument.createElement ('script')
      iScript.type = 'text/javascript'
      iScript.src  = '/assets/koi.js'

      // Handle Script loading
      var done = false;

      // Attach handlers for all browsers
      iScript.onload = iScript.onreadystatechange = function ()
      {
        if (! done && (! this.readyState || this.readyState == 'loaded' || this.readyState == 'complete'))
        {
          done = true
          loadScript ()

          // Handle memory leak in IE:
          iScript.onload = iScript.onreadystatechange = null
          if (iHead && iScript.parentNode) iHead.removeChild (iScript)
        }
      };

      iHead.appendChild (iScript)

      $ (iBody).css ({ padding:0, margin:0 }).on ('click keydown', resize)
      //$ (iScript).load (loadScript)
    }

    function loadScript ()
    {
      iBody = iWindow.$ (iBody)
      iTextArea = iWindow.$ (iTextArea)
      // iScript [0].onload = (load_iScript)

      app = iTextArea.redactor (opt).data ().redactor

      $box = iFrame
      $editor = app.$editor.css ({ minHeight: 200, padding:0, margin:0 })
      $toolBar = app.$toolbar

      var sushiBar = $toolBar.sushi ('css')

      sushiBar.set ({ boxSizing: 'border-box', width:'100%' })

      sushiBar.stopScrolling = function ()
      {
        var boxWidth  = $editor.outerWidth ()
        this.set ({ position:'absolute', zIndex:1, left:0, top:0, width:'100%' })
      }

      sushiBar.startScrolling = function ()
      {
        var boxTop    = $box.offset ().top
        var scrollTop = $win.scrollTop ()
        this.set ({ top: scrollTop - boxTop + 44 })
      }

      sushiBar.isScrolling = function ()
      {
        var boxTop    = $box.offset ().top
        var boxHeight = $box.height ()
        var boxBottom = boxHeight + boxTop - 44 - 32
        var scrollTop = $win.scrollTop ()
        var top       = scrollTop + $toolBar.height ()
        return boxTop < top && top < boxBottom
      }
      sushiBar.stopScrolling ()
      sushiBar.startScrolling ()

      function reposition ()
      {
        sushiBar [sushiBar.isScrolling () ? 'startScrolling' : 'stopScrolling'] ()
      }

      setTimeout (resize)
      setTimeout (reposition)

      $ (window).on ('resize scroll', reposition)

      var __toggle = app.toggle

      app.toggle = function ()
      {
        var scrollTop = $win.scrollTop ()
        __toggle.apply (this, arguments)
        setTimeout (resize)
        $win.scrollTop (scrollTop)
      }

      app.showImage = function ()
      {
        this.saveSelection ()
        $.modal.call (this, '/admin/images/new', function (url)
        {
          this._imageSet ("", true)
        })
      }

      app.showFile = function ()
      {
        this.saveSelection()

        if ($ (this.getParentNode ()).is ('a')) this.showLink ()

        else $.modal.call (this, '/admin/documents/new', function (url)
        {
          var fileName = url.match (/[^\/]+$/).toString () || '...'
          if ($.browser.msie) this.restoreSelection()
          this.execCommand ('inserthtml', "" + fileName + "")
          if (! $.browser.msie) this.showLink ()
        })
      }

      $toolBar.before ($ ('
', { height: '33px' }))
    }
  }

} ()

<commit_msg>Removed cache dodger from wysi.<commit_after>! function ()
{
  var opt = { fileUpload: '#show-me-the-attachment-button', buttons: ['html'] }

  opt.buttons.add = function (split)
  {
    this.push ('|'); this.push.apply (this, split.split (' ')); return this
  }
  opt.buttons
  .add ('formatting')
  .add ('bold italic underline')
  .add ('unorderedlist orderedlist')
  .add ('outdent indent')
  .add ('video image file link table')
  .add ('alignleft aligncenter alignright justify')
  .add ('horizontalrule')

  $ (function () { $ ('[koi-wysiwyg]').liveQuery (run) })

  function run ()
  {
    var app, $box, $editor, $toolBar
    var $win = $ (window), $textArea = $ (this), $form = $textArea.closest ('form')
    var iFrame, iQuery, iWindow, iDocument, iHead, iBody, iScript, iStyle, iTextArea

    $textArea.hide ().closest ('form').on ('submit', submit)

    iFrame = $ ('').insertAfter ($textArea).load (loadFrame)
    .attr ('src', '/wysiwyg.html')
    .attr ('width', '100%')
    .attr ('height', '100%')
    .attr ('frameborder', '0')

    function submit ()
    {
      $editor.find ('img').each (function ()
      {
        var $img = $ (this)
        var src = $img.attr ('src').split ('?')
        var path = src [0]
        var params = src [1]
        var deparams = params ? $.deparam (params) : {}
        if (params)
        {
          for (var dim in { width:true, height:true }) deparams [dim] = parseInt ($img.css (dim))
          $img.attr ('src', path + '?' + $.param (deparams))
        }
        else $img.attr ('style', '');
      })
      if (iTextArea.is (':hidden')) app.syncCode ()
      else app.toggle ()
      $textArea.val ($editor[0].innerHTML)
      //$textArea.val (iTextArea.val ().replace (/(\s* \s*)+/g, ' '))
    }

    function resize ()
    {
      var height = iBody.outerHeight () //+ $toolBar.outerHeight ()
      iFrame.height (height)
    }

    function loadFrame ()
    {
      iWindow   = iFrame.contentWindow ()
      iDocument = iFrame.contentDocument ()

      iHead     = iDocument.getElementsByTagName ('head') [0]
      iBody     = iDocument.getElementsByTagName ('body') [0]

      iTextArea = iDocument.createElement ('textarea')
      iTextArea.value = $textArea.val ()
      iBody.appendChild (iTextArea)

      iStyle       = iDocument.createElement ('link')
      iStyle.rel   = 'stylesheet'
      iStyle.type  = 'text/css'
      iStyle.media = 'screen'
      iStyle.href  = '/assets/koi/jquery/redactor.css'
      iHead.appendChild (iStyle)

      iScript      = iDocument.createElement ('script')
      iScript.type = 'text/javascript'
      iScript.src  = '/assets/koi.js'

      // Handle Script loading
      var done = false;

      // Attach handlers for all browsers
      iScript.onload = iScript.onreadystatechange = function ()
      {
        if (! done && (! this.readyState || this.readyState == 'loaded' || this.readyState == 'complete'))
        {
          done = true
          loadScript ()

          // Handle memory leak in IE:
          iScript.onload = iScript.onreadystatechange = null
          if (iHead && iScript.parentNode) iHead.removeChild (iScript)
        }
      };

      iHead.appendChild (iScript)

      $ (iBody).css ({ padding:0, margin:0 }).on ('click keydown', resize)
      //$ (iScript).load (loadScript)
    }

    function loadScript ()
    {
      iBody = iWindow.$ (iBody)
      iTextArea = iWindow.$ (iTextArea)
      // iScript [0].onload = (load_iScript)

      app = iTextArea.redactor (opt).data ().redactor

      $box = iFrame
      $editor = app.$editor.css ({ minHeight: 200, padding:0, margin:0 })
      $toolBar = app.$toolbar

      var sushiBar = $toolBar.sushi ('css')

      sushiBar.set ({ boxSizing: 'border-box', width:'100%' })

      sushiBar.stopScrolling = function ()
      {
        var boxWidth  = $editor.outerWidth ()
        this.set ({ position:'absolute', zIndex:1, left:0, top:0, width:'100%' })
      }

      sushiBar.startScrolling = function ()
      {
        var boxTop    = $box.offset ().top
        var scrollTop = $win.scrollTop ()
        this.set ({ top: scrollTop - boxTop + 44 })
      }

      sushiBar.isScrolling = function ()
      {
        var boxTop    = $box.offset ().top
        var boxHeight = $box.height ()
        var boxBottom = boxHeight + boxTop - 44 - 32
        var scrollTop = $win.scrollTop ()
        var top       = scrollTop + $toolBar.height ()
        return boxTop < top && top < boxBottom
      }
      sushiBar.stopScrolling ()
      sushiBar.startScrolling ()

      function reposition ()
      {
        sushiBar [sushiBar.isScrolling () ? 'startScrolling' : 'stopScrolling'] ()
      }

      setTimeout (resize)
      setTimeout (reposition)

      $ (window).on ('resize scroll', reposition)

      var __toggle = app.toggle

      app.toggle = function ()
      {
        var scrollTop = $win.scrollTop ()
        __toggle.apply (this, arguments)
        setTimeout (resize)
        $win.scrollTop (scrollTop)
      }

      app.showImage = function ()
      {
        this.saveSelection ()
        $.modal.call (this, '/admin/images/new', function (url)
        {
          this._imageSet ("", true)
        })
      }

      app.showFile = function ()
      {
        this.saveSelection()

        if ($ (this.getParentNode ()).is ('a')) this.showLink ()

        else $.modal.call (this, '/admin/documents/new', function (url)
        {
          var fileName = url.match (/[^\/]+$/).toString () || '...'
          if ($.browser.msie) this.restoreSelection()
          this.execCommand ('inserthtml', "" + fileName + "")
          if (! $.browser.msie) this.showLink ()
        })
      }

      $toolBar.before ($ ('
', { height: '33px' }))
    }
  }

} ()

<|endoftext|>


<commit_before>! function ()
{
  var opt = { fileUpload: '#show-me-the-attachment-button', buttons: ['html'] }

  opt.buttons.add = function (split)
  {
    this.push ('|'); this.push.apply (this, split.split (' ')); return this
  }
  opt.buttons
  .add ('formatting')
  .add ('bold italic underline')
  .add ('unorderedlist orderedlist')
  .add ('outdent indent')
  .add ('video image file link table')
  .add ('alignleft aligncenter alignright justify')
  .add ('horizontalrule')

  $ (function () { $ ('[koi-wysiwyg]').liveQuery (run) })

  function run ()
  {
    var app, $box, $editor, $toolBar
    var $win = $ (window), $textArea = $ (this), $form = $textArea.closest ('form')
    var iFrame, iQuery, iWindow, iDocument, iHead, iBody, iScript, iStyle, iTextArea

    $textArea.hide ().closest ('form').on ('submit', submit)

    iFrame = $ ('').insertAfter ($textArea).load (loadFrame)
    .attr ('src'          , '/wysiwyg.html')
    .attr ('width'        , '100%')
    .attr ('height'       , '100%')
    .attr ('marginheight' , '0')
    .attr ('marginheight' , '0')
    .css  ('borderWidth'  , '0')
    .css  ('borderStyle'  , 'none')

    function submit ()
    {
      $editor.find ('img').each (function ()
      {
        var $img     = $ (this)
        var src      = $img.attr ('src').split ('?')
        var path     = src [0]
        var params   = src [1]
        var deparams = params ? $.deparam (params) : {}
        if (params)
        {
          for (var dim in { width:true, height:true }) deparams [dim] = parseInt ($img.css (dim))
          $img.attr ('src', path + '?' + $.param (deparams))
        }
        else $img.attr ('style', '');
      })
      if (iTextArea.is (':hidden')) app.syncCode ()
      else app.toggle ()
      $textArea.val ($editor[0].innerHTML.replace (/(<[^\/][^>]*>)
/, function ($0, $1) { return $1 })
                                         .replace (/cursor\s*:\s*default;?/, ''))
      //$textArea.val (iTextArea.val ().replace (/(\s* \s*)+/g, ' '))
    }

    function resize_body ()
    {
      iFrame.height ($ (iBody).outerHeight () + $toolBar.outerHeight ())
    }

    var diffo

    function resize_document ()
    {
      if (diffo == null) diffo = $ (iDocument).outerHeight () - $ (iBody).outerHeight ()
      iTextArea.height (app.opts.visual ? $editor.height () : iTextArea [0].scrollHeight)
      iFrame.height ($ (iBody).outerHeight () + diffo)
    }

    function resizer ()
    {
      resize_body (); resizer = resize_document;
    }

    function resize (e)
    {
      resizer (); setTimeout (function () { resizer () })
    }

    function loadFrame ()
    {
      iWindow   = iFrame.contentWindow ()
      iDocument = iFrame.contentDocument ()

      iHead     = iDocument.getElementsByTagName ('head') [0]
      iBody     = iDocument.getElementsByTagName ('body') [0]

      iTextArea = iDocument.createElement ('textarea')
      iTextArea.value = $textArea.val ()
      iBody.appendChild (iTextArea)

      iStyle       = iDocument.createElement ('link')
      iStyle.rel   = 'stylesheet'
      iStyle.type  = 'text/css'
      iStyle.media = 'screen'
      iStyle.href  = '/assets/koi/jquery/redactor.css'
      iHead.appendChild (iStyle)

      iScript      = iDocument.createElement ('script')
      iScript.type = 'text/javascript'
      iScript.src  = '/assets/koi.js'

      // Handle Script loading
      var done = false;

      // Attach handlers for all browsers
      iScript.onload = iScript.onreadystatechange = function ()
      {
        if (! done && (! this.readyState || this.readyState == 'loaded' || this.readyState == 'complete'))
        {
          done = true
          loadScript ()

          // Handle memory leak in IE:
          iScript.onload = iScript.onreadystatechange = null
          if (iHead && iScript.parentNode) iHead.removeChild (iScript)
        }
      }

      iHead.appendChild (iScript)

      $ (iBody).css ({ padding:0, margin:0 }).on ('click keydown', resize)

      //$ (iScript).load (loadScript)
    }

    function loadScript ()
    {
      iBody = iWindow.$ (iBody)
      iTextArea = iWindow.$ (iTextArea)
      // iScript [0].onload = (load_iScript)

      app = iTextArea.redactor (opt).data ().redactor

      $box = iFrame
      $editor = app.$editor.css ({ minHeight: 300, padding:0, margin:0 })
      $toolBar = app.$toolbar

      var sushiBar = $toolBar.sushi ('css')

      sushiBar.set ({ boxSizing: 'border-box', width:'100%' })

      sushiBar.stopScrolling = function ()
      {
        var boxWidth  = $editor.outerWidth ()
        this.set ({ position:'absolute', zIndex:1, left:0, top:0, width:'100%' })
      }

      sushiBar.startScrolling = function ()
      {
        var boxTop    = $box.offset ().top
        var scrollTop = $win.scrollTop ()
        this.set ({ top: scrollTop - boxTop + 43 })
      }

      sushiBar.isScrolling = function ()
      {
        var boxTop    = $box.offset ().top
        var boxHeight = $box.height ()
        var boxBottom = boxHeight + boxTop - 44 - 32
        var scrollTop = $win.scrollTop ()
        var top       = scrollTop + $toolBar.height ()
        return boxTop < top && top < boxBottom
      }
      sushiBar.stopScrolling ()
      sushiBar.startScrolling ()

      function reposition ()
      {
        sushiBar [sushiBar.isScrolling () ? 'startScrolling' : 'stopScrolling'] ()
        setTimeout (function () { sushiBar [sushiBar.isScrolling () ? 'startScrolling' : 'stopScrolling'] () })
      }

      $ (window).ready (function (e)
      {
        resize (e); reposition (e);
        setTimeout (function () { resize (e); reposition (e); })
      })

      $ (window).on ('resize scroll', reposition)

      var __toggle = app.toggle

      app.toggle = function ()
      {
        var scrollTop = $win.scrollTop ()
        __toggle.apply (this, arguments)
        setTimeout (resize)
        $win.scrollTop (scrollTop)
      }

      app.showImage = function ()
      {
        this.saveSelection ()
        $.modal.call (this, '/admin/images/new', function (url)
        {
          this._imageSet ("", true)
        })
      }

      app.showFile = function ()
      {
        this.saveSelection()

        if ($ (this.getParentNode ()).is ('a')) this.showLink ()

        else $.modal.call (this, '/admin/documents/new', function (url)
        {
          var fileName = url.match (/[^\/]+$/).toString () || '...'
          if ($.browser.msie) this.restoreSelection()
          this.execCommand ('inserthtml', "" + fileName + "")
          if (! $.browser.msie) this.showLink ()
        })
      }

      $toolBar.before ($ ('

').css ({ height:'32px' }))
    }
  }

} ()

<commit_msg>Better HTML cleanup for Wysiwyg.<commit_after>! function ()
{
  var opt = { fileUpload: '#show-me-the-attachment-button', buttons: ['html'] }

  opt.buttons.add = function (split)
  {
    this.push ('|'); this.push.apply (this, split.split (' ')); return this
  }
  opt.buttons
  .add ('formatting')
  .add ('bold italic underline')
  .add ('unorderedlist orderedlist')
  .add ('outdent indent')
  .add ('video image file link table')
  .add ('alignleft aligncenter alignright justify')
  .add ('horizontalrule')

  $ (function () { $ ('[koi-wysiwyg]').liveQuery (run) })

  function run ()
  {
    var app, $box, $editor, $toolBar
    var $win = $ (window), $textArea = $ (this), $form = $textArea.closest ('form')
    var iFrame, iQuery, iWindow, iDocument, iHead, iBody, iScript, iStyle, iTextArea

    $textArea.hide ().closest ('form').on ('submit', submit)

    iFrame = $ ('').insertAfter ($textArea).load (loadFrame)
    .attr ('src'          , '/wysiwyg.html')
    .attr ('width'        , '100%')
    .attr ('height'       , '100%')
    .attr ('marginheight' , '0')
    .attr ('marginheight' , '0')
    .css  ('borderWidth'  , '0')
    .css  ('borderStyle'  , 'none')

    function submit ()
    {
      $editor.find ('img').each (function ()
      {
        var $img     = $ (this)
        var src      = $img.attr ('src').split ('?')
        var path     = src [0]
        var params   = src [1]
        var deparams = params ? $.deparam (params) : {}
        if (params)
        {
          for (var dim in { width:true, height:true }) deparams [dim] = parseInt ($img.css (dim))
          $img.attr ('src', path + '?' + $.param (deparams))
        }
        else $img.attr ('style', '');
      })
      if (iTextArea.is (':hidden')) app.syncCode ()
      else app.toggle ()
      $textArea.val ($editor[0].innerHTML.replace (/(<\w[^>]*>)\s*
/gi, function ($0, $1) { return $1 + ' ' })
                                         .replace (/(<\/[^>]*>)\s* /gi, function ($0, $1) { return $1 + ' ' })
                                         .replace (/
\s*<\/p>/gi, '')
                                         .replace (/cursor\s*:\s*default;?/gi, ''))
      //$textArea.val (iTextArea.val ().replace (/(\s* \s*)+/g, ' '))
    }

    function resize_body ()
    {
      iFrame.height ($ (iBody).outerHeight () + $toolBar.outerHeight ())
    }

    var diffo

    function resize_document ()
    {
      if (diffo == null) diffo = $ (iDocument).outerHeight () - $ (iBody).outerHeight ()
      iTextArea.height (app.opts.visual ? $editor.height () : iTextArea [0].scrollHeight)
      iFrame.height ($ (iBody).outerHeight () + diffo)
    }

    function resizer ()
    {
      resize_body (); resizer = resize_document;
    }

    function resize (e)
    {
      resizer (); setTimeout (function () { resizer () })
    }

    function loadFrame ()
    {
      iWindow   = iFrame.contentWindow ()
      iDocument = iFrame.contentDocument ()

      iHead     = iDocument.getElementsByTagName ('head') [0]
      iBody     = iDocument.getElementsByTagName ('body') [0]

      iTextArea = iDocument.createElement ('textarea')
      iTextArea.value = $textArea.val ()
      iBody.appendChild (iTextArea)

      iStyle       = iDocument.createElement ('link')
      iStyle.rel   = 'stylesheet'
      iStyle.type  = 'text/css'
      iStyle.media = 'screen'
      iStyle.href  = '/assets/koi/jquery/redactor.css'
      iHead.appendChild (iStyle)

      iScript      = iDocument.createElement ('script')
      iScript.type = 'text/javascript'
      iScript.src  = '/assets/koi.js'

      // Handle Script loading
      var done = false;

      // Attach handlers for all browsers
      iScript.onload = iScript.onreadystatechange = function ()
      {
        if (! done && (! this.readyState || this.readyState == 'loaded' || this.readyState == 'complete'))
        {
          done = true
          loadScript ()

          // Handle memory leak in IE:
          iScript.onload = iScript.onreadystatechange = null
          if (iHead && iScript.parentNode) iHead.removeChild (iScript)
        }
      }

      iHead.appendChild (iScript)

      $ (iBody).css ({ padding:0, margin:0 }).on ('click keydown', resize)

      //$ (iScript).load (loadScript)
    }

    function loadScript ()
    {
      iBody = iWindow.$ (iBody)
      iTextArea = iWindow.$ (iTextArea)
      // iScript [0].onload = (load_iScript)

      app = iTextArea.redactor (opt).data ().redactor

      $box = iFrame
      $editor = app.$editor.css ({ minHeight: 300, padding:0, margin:0 })
      $toolBar = app.$toolbar

      var sushiBar = $toolBar.sushi ('css')

      sushiBar.set ({ boxSizing: 'border-box', width:'100%' })

      sushiBar.stopScrolling = function ()
      {
        var boxWidth  = $editor.outerWidth ()
        this.set ({ position:'absolute', zIndex:1, left:0, top:0, width:'100%' })
      }

      sushiBar.startScrolling = function ()
      {
        var boxTop    = $box.offset ().top
        var scrollTop = $win.scrollTop ()
        this.set ({ top: scrollTop - boxTop + 43 })
      }

      sushiBar.isScrolling = function ()
      {
        var boxTop    = $box.offset ().top
        var boxHeight = $box.height ()
        var boxBottom = boxHeight + boxTop - 44 - 32
        var scrollTop = $win.scrollTop ()
        var top       = scrollTop + $toolBar.height ()
        return boxTop < top && top < boxBottom
      }
      sushiBar.stopScrolling ()
      sushiBar.startScrolling ()

      function reposition ()
      {
        sushiBar [sushiBar.isScrolling () ? 'startScrolling' : 'stopScrolling'] ()
        setTimeout (function () { sushiBar [sushiBar.isScrolling () ? 'startScrolling' : 'stopScrolling'] () })
      }

      $ (window).ready (function (e)
      {
        resize (e); reposition (e);
        setTimeout (function () { resize (e); reposition (e); })
      })

      $ (window).on ('resize scroll', reposition)

      var __toggle = app.toggle

      app.toggle = function ()
      {
        var scrollTop = $win.scrollTop ()
        __toggle.apply (this, arguments)
        setTimeout (resize)
        $win.scrollTop (scrollTop)
      }

      app.showImage = function ()
      {
        this.saveSelection ()
        $.modal.call (this, '/admin/images/new', function (url)
        {
          this._imageSet ("", true)
        })
      }

      app.showFile = function ()
      {
        this.saveSelection()

        if ($ (this.getParentNode ()).is ('a')) this.showLink ()

        else $.modal.call (this, '/admin/documents/new', function (url)
        {
          var fileName = url.match (/[^\/]+$/).toString () || '...'
          if ($.browser.msie) this.restoreSelection()
          this.execCommand ('inserthtml', "" + fileName + "")
          if (! $.browser.msie) this.showLink ()
        })
      }

      $toolBar.before ($ ('

').css ({ height:'32px' }))
    }
  }

} ()

<|endoftext|>


<commit_before>var roomQuestionList = new QuestionList();

/********** MODEL ***************/

//Question object - this mirrors server/database entry

function Question(q, uId, qId) {
	this.details = q;
	this.votes = 0;
	this.answered = false;
	this.paused = false;
	this.userId = uId;
	this.id = qId;
};

//Question object methods

Question.prototype.upVote = function() {
	this.votes = this.votes + 1;
};

Question.prototype.answer = function() {
	this.answered = true;
};

// Question list object - this is an array of Question Objects
function QuestionList() {
	this.questions = [];
};

//Question list methods
QuestionList.prototype.sort = function() {
  this.questions = _.sortBy(this.questions, function(element){return element.votes;});
};

QuestionList.prototype.addQuestion = function( qObj ) {
	this.questions.push( qObj );
	this.sort();
};

//======= end of model =========//

/********** VIEWS ***************/
/* Answer
/* Question
/* Votes
/* Listeners
/********************************/

//if the question is answerable by the user, add this to the div.
function viewRenderAnswerable(question){
  var myDiv = $('div[data-val=' + question.id + ']');
  var answerableDiv = $("
√
");

  $(myDiv.children()[1]).append(answerableDiv);
}

//render a question
function viewRenderQuestion(question){
  var colors = ["purple", "orange", "red", "blue", "yellow", "green"];
  var outerDiv = $('
');

  var innerDiv = $("
");
  innerDiv.text(question.details);
  innerDiv.css("background", _.sample(colors));

  // build the upvote button & attach it to the inner div
  var upButton = $('
⊕
');
  innerDiv.append(upButton);

  //build the votes div
  var votesDiv = $("
0
");
  innerDiv.append(votesDiv);

  //append the div with the new question.
  outerDiv.append(innerDiv);
  $('div.packery').append(outerDiv);
  pckry.appended( outerDiv[0] );
}

//remove a question from the DOM (aka, it was answered)
function viewRemoveQuestion(question){
  var myDiv = $('div[data-val=' + question.id + ']');
  myDiv.remove();
}

//display how many votes the question has
function viewRenderVotes(question){
  var myDiv = $('div[data-val=' + question.id + ']');
  $(myDiv.children()[1]).html(question.votes);
}

//add a listener to the form to allow new questions to be created
function viewFormListener(){
  var form = $('.question-form');
  var session_id = $('#session_id').text();
  form.submit( function( event ) {
    event.preventDefault();

    //get the question
    var question = $('input.question').val();

    //clear input box now that we have input
    $('input.question').val("");

    //create ajax request with the question and the user_id
    $.ajax({
      url: "/json/questions",
      type: "POST",
      data: { question: {details: question, user_id: session_id}},
      success: controllerUpdateNewQuestion
    });
  });
}

//using delegated listeners for all the little actions
function viewAddDelegatedListeners(){
  $('div.packery').on('click', 'div.upButton', controllerUpVote);
  $('div.packery').on('click', 'div.answerable', controllerAnswer);
};

//======= end of views =========//

/********** CONTROLLER **********/

//called to setup everything on a page refresh
function controllerSetup(){
	$.ajax({
		url: "/json/questions",
		type: "GET",
		success: controllerBuildModel
	});
};

//build the model from a list of unanswered questions returned from the server.
//called only once with the page loads.
function controllerBuildModel(serverResponse){
	var numQuestions = serverResponse[0].questions.length;

	for (var i = 0; i < numQuestions; i++){
		var tempQuestion = new Question(serverResponse[0].questions[i].details, serverResponse[0].questions[i].user_id, serverResponse[0].questions[i].id);
		roomQuestionList.addQuestion(tempQuestion);
		viewRenderQuestion(tempQuestion);
	};
	controllerVoteSetup();
  controllerAnswerableSetup();
};

//setup the votes -
//for every question in the roomQuestionList
//    ask the server how many votes the question has!
function controllerVoteSetup(){
	var numQuestions = roomQuestionList.questions.length;
	for (var i = 0; i < numQuestions; i++){

		$.ajax({
		url: "/json/questions/" + roomQuestionList.questions[i].id + "/getvotes",
		type: "GET",
		data: { question: {id: roomQuestionList.questions[i].id}},
    	success: controllerUpdateVotes
    	});
	};
};

//update the votes - the success handler for the vote ajax request.
//when the votes are updated, sort the roomQuestionList, then render votes.
function controllerUpdateVotes(serverResponse){
	var tempArray = $.map(roomQuestionList.questions, function(question, i) { return question.id });
	var index = $.inArray(serverResponse[0].question.id, tempArray);

	roomQuestionList.questions[index].votes = serverResponse[1].votes;
  roomQuestionList.sort;
	viewRenderVotes(roomQuestionList.questions[index]);
  redisplay();
};

//the hander that accepts the response from sending a new question.
function controllerUpdateNewQuestion(serverResponse){
	tempQuestion = new Question(serverResponse.details, serverResponse.user_id, serverResponse.id);
	roomQuestionList.addQuestion(tempQuestion);
	viewRenderQuestion(tempQuestion);
  viewRenderAnswerable(tempQuestion);
};

//launch an ajax request to the server to upvote a question
function controllerUpVote(){
  var session_id = $('#session_id').text();
  var question_id = $(this.parentElement).data().val;
  var url = "/json/questions/" + question_id + "/vote_up";

  $.ajax({
      url: url,
      type: "POST",
      data: { question: {id: question_id}},
      success: controllerUpdateVotes
    });
}

//ajax request for each question - can the user who is logged in answer it?
function controllerAnswerableSetup(){
  var numQuestions = roomQuestionList.questions.length;
  for (var i = 0; i < numQuestions; i++){

    $.ajax({
    url: "/json/questions/" + roomQuestionList.questions[i].id + "/getanswerable",
    type: "GET",
    data: { question: {id: roomQuestionList.questions[i].id}},
      success: controllerUpdateAnswerable
      });
  };
};

//the server has decided i can answer this - so render an answer button.
function controllerUpdateAnswerable(serverResponse){
  //TODO: dry this up into a helper function aka controllerHelperMap(serverResponse)
  var tempArray = $.map(roomQuestionList.questions, function(question, i) { return question.id });
  var index = $.inArray(serverResponse[0].question.id, tempArray);

  viewRenderAnswerable(roomQuestionList.questions[index]);
};

//when the user clicks on answer, send an ajax request to server.
function controllerAnswer(){
  console.log("this question was just answered!");
  // now go tell the server this question was answered!
  // TODO - this is one level higher than vote because of the nesting
  // that is happening - it shouldn't be.
  var question_id = $(this.parentElement.parentElement).data().val;

  var url = "/json/questions/" + question_id + "/answered";

  $.ajax({
      url: url,
      type: "POST",
      data: { question: {id: question_id}},
      success: controllerUpdateAnswer
    });
};

//when the server comes back, update the model and display
function controllerUpdateAnswer(serverResponse){
  //remove from the model - find it in the model.  then mark it answered
  var tempArray = $.map(roomQuestionList.questions, function(question, i) { return question.id });
  var index = $.inArray(serverResponse[0].question.id, tempArray);
  roomQuestionList.questions[index].answer();

  //remove from the dom
  viewRemoveQuestion(roomQuestionList.questions[index]);
}

//////////////////////////////////////////////////

//////////////////////////////////////////////////

//////////////////////////////////////////////////

function redisplay(){
  //delete this shit.
  elems = pckry.getItemElements();
  for (var i=0; i<elems.length; i++){
    pckry.remove(elems[i]);
  }

  //sort local model
  roomQuestionList.sort();

  //build this shit.
  numberOfQuestions = roomQuestionList.questions.length;
  for(var i=0; i<numberOfQuestions; i++){
    var question = roomQuestionList.questions[i];

    var colors = ["purple", "orange", "red", "blue", "yellow", "green"];
    var outerDiv = $('
');

    var innerDiv = $("
");
    innerDiv.text(question.details);

    if (question.votes > 5) {
      innerDiv.css("background", "red");
    } else if ((question.votes > 3) && (question.votes < 5)) {
      innerDiv.css("background", "yellow");
    } else (question.votes <= 3) {
      innerDiv.css("background", "green");
    };

    // build the upvote button & attach it to the inner div
    var upButton = $('
⊕
');
    innerDiv.append(upButton);

    //build the votes div
    var votesDiv = $("
"+question.votes+"
");
    innerDiv.append(votesDiv);

    //append the div with the new question.
    outerDiv.append(innerDiv);

    $('div.packery').append(outerDiv);
    pckry.prepended( outerDiv );
  };

  //should we remove answerable here?
  //controllerAnswerableSetup();
};

function viewToggleList() {
  $("p").hide();
  $("h1").click(function() {
    $(this).next().slideToggle(300);
  });
}

function timedRefresh(timeoutPeriod) {

  setTimeout("location.reload(true);",timeoutPeriod);
};

window.onload = function(){

	controllerSetup();

	viewFormListener();
	viewAddDelegatedListeners();
  viewToggleList();
  //timedRefresh(20000);

};<commit_msg>i don't know what is happening<commit_after>var roomQuestionList = new QuestionList();

/********** MODEL ***************/

//Question object - this mirrors server/database entry

function Question(q, uId, qId) {
	this.details = q;
	this.votes = 0;
	this.answered = false;
	this.paused = false;
	this.userId = uId;
	this.id = qId;
};

//Question object methods

Question.prototype.upVote = function() {
	this.votes = this.votes + 1;
};

Question.prototype.answer = function() {
	this.answered = true;
};

// Question list object - this is an array of Question Objects
function QuestionList() {
	this.questions = [];
};

//Question list methods
QuestionList.prototype.sort = function() {
  this.questions = _.sortBy(this.questions, function(element){return element.votes;});
};

QuestionList.prototype.addQuestion = function( qObj ) {
	this.questions.push( qObj );
	this.sort();
};

//======= end of model =========//

/********** VIEWS ***************/
/* Answer
/* Question
/* Votes
/* Listeners
/********************************/

//if the question is answerable by the user, add this to the div.
function viewRenderAnswerable(question){
  var myDiv = $('div[data-val=' + question.id + ']');
  var answerableDiv = $("
√
");

  $(myDiv.children()[1]).append(answerableDiv);
}

//render a question
function viewRenderQuestion(question){
  var colors = ["purple", "orange", "red", "blue", "yellow", "green"];
  var outerDiv = $('
');

  var innerDiv = $("
");
  innerDiv.text(question.details);
  innerDiv.css("background", _.sample(colors));

  // build the upvote button & attach it to the inner div
  var upButton = $('
⊕
');
  innerDiv.append(upButton);

  //build the votes div
  var votesDiv = $("
0
");
  innerDiv.append(votesDiv);

  //append the div with the new question.
  outerDiv.append(innerDiv);
  $('div.packery').append(outerDiv);
  pckry.appended( outerDiv[0] );
}

//remove a question from the DOM (aka, it was answered)
function viewRemoveQuestion(question){
  var myDiv = $('div[data-val=' + question.id + ']');
  myDiv.remove();
}

//display how many votes the question has
function viewRenderVotes(question){
  var myDiv = $('div[data-val=' + question.id + ']');
  $(myDiv.children()[1]).html(question.votes);
}

//add a listener to the form to allow new questions to be created
function viewFormListener(){
  var form = $('.question-form');
  var session_id = $('#session_id').text();
  form.submit( function( event ) {
    event.preventDefault();

    //get the question
    var question = $('input.question').val();

    //clear input box now that we have input
    $('input.question').val("");

    //create ajax request with the question and the user_id
    $.ajax({
      url: "/json/questions",
      type: "POST",
      data: { question: {details: question, user_id: session_id}},
      success: controllerUpdateNewQuestion
    });
  });
}

//using delegated listeners for all the little actions
function viewAddDelegatedListeners(){
  $('div.packery').on('click', 'div.upButton', controllerUpVote);
  $('div.packery').on('click', 'div.answerable', controllerAnswer);
};

//======= end of views =========//

/********** CONTROLLER **********/

//called to setup everything on a page refresh
function controllerSetup(){
	$.ajax({
		url: "/json/questions",
		type: "GET",
		success: controllerBuildModel
	});
};

//build the model from a list of unanswered questions returned from the server.
//called only once with the page loads.
function controllerBuildModel(serverResponse){
	var numQuestions = serverResponse[0].questions.length;

	for (var i = 0; i < numQuestions; i++){
		var tempQuestion = new Question(serverResponse[0].questions[i].details, serverResponse[0].questions[i].user_id, serverResponse[0].questions[i].id);
		roomQuestionList.addQuestion(tempQuestion);
		viewRenderQuestion(tempQuestion);
	};
	controllerVoteSetup();
  controllerAnswerableSetup();
};

//setup the votes -
//for every question in the roomQuestionList
//    ask the server how many votes the question has!
function controllerVoteSetup(){
	var numQuestions = roomQuestionList.questions.length;
	for (var i = 0; i < numQuestions; i++){

		$.ajax({
		url: "/json/questions/" + roomQuestionList.questions[i].id + "/getvotes",
		type: "GET",
		data: { question: {id: roomQuestionList.questions[i].id}},
    	success: controllerUpdateVotes
    	});
	};
};

//update the votes - the success handler for the vote ajax request.
//when the votes are updated, sort the roomQuestionList, then render votes.
function controllerUpdateVotes(serverResponse){
	var tempArray = $.map(roomQuestionList.questions, function(question, i) { return question.id });
	var index = $.inArray(serverResponse[0].question.id, tempArray);

	roomQuestionList.questions[index].votes = serverResponse[1].votes;
  roomQuestionList.sort;
	viewRenderVotes(roomQuestionList.questions[index]);
  //redisplay();
};

//the hander that accepts the response from sending a new question.
function controllerUpdateNewQuestion(serverResponse){
	tempQuestion = new Question(serverResponse.details, serverResponse.user_id, serverResponse.id);
	roomQuestionList.addQuestion(tempQuestion);
	viewRenderQuestion(tempQuestion);
  viewRenderAnswerable(tempQuestion);
};

//launch an ajax request to the server to upvote a question
function controllerUpVote(){
  var session_id = $('#session_id').text();
  var question_id = $(this.parentElement).data().val;
  var url = "/json/questions/" + question_id + "/vote_up";

  $.ajax({
      url: url,
      type: "POST",
      data: { question: {id: question_id}},
      success: controllerUpdateVotes
    });
}

//ajax request for each question - can the user who is logged in answer it?
function controllerAnswerableSetup(){
  var numQuestions = roomQuestionList.questions.length;
  for (var i = 0; i < numQuestions; i++){

    $.ajax({
    url: "/json/questions/" + roomQuestionList.questions[i].id + "/getanswerable",
    type: "GET",
    data: { question: {id: roomQuestionList.questions[i].id}},
      success: controllerUpdateAnswerable
      });
  };
};

//the server has decided i can answer this - so render an answer button.
function controllerUpdateAnswerable(serverResponse){
  //TODO: dry this up into a helper function aka controllerHelperMap(serverResponse)
  var tempArray = $.map(roomQuestionList.questions, function(question, i) { return question.id });
  var index = $.inArray(serverResponse[0].question.id, tempArray);

  viewRenderAnswerable(roomQuestionList.questions[index]);
};

//when the user clicks on answer, send an ajax request to server.
function controllerAnswer(){
  console.log("this question was just answered!");
  // now go tell the server this question was answered!
  // TODO - this is one level higher than vote because of the nesting
  // that is happening - it shouldn't be.
  var question_id = $(this.parentElement.parentElement).data().val;

  var url = "/json/questions/" + question_id + "/answered";

  $.ajax({
      url: url,
      type: "POST",
      data: { question: {id: question_id}},
      success: controllerUpdateAnswer
    });
};

//when the server comes back, update the model and display
function controllerUpdateAnswer(serverResponse){
  //remove from the model - find it in the model.  then mark it answered
  var tempArray = $.map(roomQuestionList.questions, function(question, i) { return question.id });
  var index = $.inArray(serverResponse[0].question.id, tempArray);
  roomQuestionList.questions[index].answer();

  //remove from the dom
  viewRemoveQuestion(roomQuestionList.questions[index]);
}

//////////////////////////////////////////////////

//////////////////////////////////////////////////

//////////////////////////////////////////////////

function redisplay(){
  //delete this shit.
  elems = pckry.getItemElements();
  for (var i=0; i<elems.length; i++){
    pckry.remove(elems[i]);
  }

  //sort local model
  roomQuestionList.sort();

  //build this shit.
  numberOfQuestions = roomQuestionList.questions.length;
  for(var i=0; i<numberOfQuestions; i++){
    var question = roomQuestionList.questions[i];

    var colors = ["purple", "orange", "red", "blue", "yellow", "green"];
    var outerDiv = $('
');

    var innerDiv = $("
");
    innerDiv.text(question.details);

    if (question.votes > 5) {
      innerDiv.css("background", "red");
    } else if ((question.votes > 3) && (question.votes < 5)) {
      innerDiv.css("background", "yellow");
    } else (question.votes <= 3) {
      innerDiv.css("background", "green");
    };

    // build the upvote button & attach it to the inner div
    var upButton = $('
⊕
');
    innerDiv.append(upButton);

    //build the votes div
    var votesDiv = $("
"+question.votes+"
");
    innerDiv.append(votesDiv);

    //append the div with the new question.
    outerDiv.append(innerDiv);

    $('div.packery').append(outerDiv);
    pckry.prepended( outerDiv );
  };

  //should we remove answerable here?
  controllerAnswerableSetup();
};

function viewToggleList() {
  $("p").hide();
  $("h1").click(function() {
    $(this).next().slideToggle(300);
  });
}

function timedRefresh(timeoutPeriod) {

  setTimeout(redisplay,timeoutPeriod);
};

window.onload = function(){

	controllerSetup();

	viewFormListener();
	viewAddDelegatedListeners();
  viewToggleList();
  //timedRefresh(30000);

};<|endoftext|>