<commit_before>/**
 * Copyright 2014 IBM Corp. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

/**
 * Anonymous function, to use as a wrapper
 */
(function() {

  // GLOBAL VARIABLES
  var taClient = null;
  var themeChanged = false;
  var profileChanged = false;

  /**
   * Smooth scroll to any DOM element
   * @param  {String} DOM element
   */
  function jumpTo(h) {
    $('html, body').animate({
        scrollTop: $(h).offset().top
    }, 500);
  }

  function createDom(elem, map, parent) {
    var e = document.createElement(elem);
    for (var k in map) {
      e[k] = map[k];
    }
    if (parent) {
      parent.appendChild(e);
    }
    return e;
  }

  function assertNotTrue(cond, message) {
    if (!cond) {
      throw message;
    }
  }

  /**
   * Wrapper around the API
   */
  function loadTradeoffAnalytics(profile, themeName, callback, errCallback) {
    taClient = new TradeoffAnalytics({
      dilemmaServiceUrl: 'demo',
      customCssUrl: 'https://ta-cdn.mybluemix.net/modmt/styles/' + themeName + '.css',
      profile: profile,
      errCallback: errCallback
    }, 'taWidgetContainer');

    taClient.start(callback);
  }

  function showTradeoffAnalytcsWidget(problem) {
    taClient.show(problem, onResultsReady, onResultSelection);
  }

  function destroyTradeoffAnalytcsWidget(callback) {
    taClient.destroy(callback);
  }

  /**
   * Resizes the widget based on the parent DOM element size
   */
  function resizeToParent() {
    taClient.resize();
  }

  function onPageReady() {
    $('.analyze').show();
    $('.loading').hide();
  }

  function onPageLoad() {
    loadTradeoffAnalytics('basic', 'watson', onPageReady, onError);
    loadSelectedProblem();
    loadProfile('basic');
    loadTheme('watson');
  }

  function onProblemChanged() {
    var tableParent = document.getElementById('tablePlaceHolder');
    while (tableParent.childElementCount > 0) {
      tableParent.removeChild(tableParent.childNodes[0]);
    }
    try {
      var problem = JSON.parse($('.problemText').val());
      assertNotTrue(problem, 'Empty Problem');
      assertNotTrue($.isArray(problem.columns), 'Invalid problem columns');
      assertNotTrue($.isArray(problem.options), 'Invalid problem options');

      createOptionsTable(problem, tableParent);
    } catch (err) {
      onError({error:'JSON parsing error'});
    }
  }

  function loadSelectedProblem() {
    var path = 'problems/' + $('.problems').val();
    $.getJSON(path, function(data) {
      $('.problemText').val(JSON.stringify(data, null, 2)).change();
    });
  }

  function createOptionsTable(problem, parent) {
    var table = createDom('table', {}, parent);
    var tr = createDom('tr', {}, table);
    createDom('th', {
      innerHTML: 'Id'
    }, tr);
    createDom('th', {
      innerHTML: 'Name'
    }, tr);

    problem.columns.forEach(function(c) {
      var th = createDom('th', {
        className: c.is_objective ? c.goal === 'MIN' ? 'minimize' : 'maximize' : 'info'
      }, tr);
      var iconClassName = c.is_objective ? c.goal === 'MIN' ? 'legendIconMin' : 'legendIconMax' : 'legendIconNone';
      createDom('span', {
        className: 'legendIcon ' + iconClassName
      }, th);
      createDom('span', {
        innerHTML: c.full_name
      }, th);
    });
    problem.options.forEach(function(op, i) {
      var tr = createDom('tr', {
        className: i % 2 ? 'odd' : 'even'
      }, table);
      createDom('td', {
        innerHTML: op.key
      }, tr);
      createDom('td', {
        innerHTML: op.name
      }, tr);
      problem.columns.forEach(function(c) {
        createDom('td', {
          innerHTML: op.values[c.key] || 0
        }, tr);
      });
    });
    return table;
  }

  /**
   * Hack to hide the .result DOM element, we can't use $().hide()
   * Because FF doesn't support that if there is an iframe involve
   */
  function hideResults() {
    $('.viz').addClass('result');
  }

  /**
   * Show the .result DOM element
   */
  function showResults() {
    $('.viz').removeClass('result');
  }

  function onAnalyzeClick() {
    $('.analyze').hide();
    $('.loading').show();
    $('.decisionArea').hide();

    $('.errorArea').hide();
    hideResults();

    var problemJson = getJsonFromElement($('.problemText'));
    if (!problemJson)
      return;

    var featuresJson = getJsonFromElement($('.featuresText'));
    if (!featuresJson)
      return;

    recreateWidgetIfNeeded(function() {
      showTradeoffAnalytcsWidget(problemJson);
    });

  }

  function onResultsReady() {
    $('.analyze').show();
    $('.loading').hide();

    showResults();
    resizeToParent();
    onPageReady();
    jumpTo('#taWidgetContainer');
  }

  function onResultSelection(selection) {
    onRestore();
    if (selection) {
      $('.decisionArea').show();
      $('.decisionText').text(selection.name);
      jumpTo('.decisionArea');
    } else {
      $('.decisionText').text('');
      $('.decisionArea').hide();
    }
  }

  function getJsonFromElement(element) {
    var elementJson = null;
    try{
      elementJson = JSON.parse(element.val());
    } catch(e) {
      element.css('border','1px solid red');
      onError({error: 'JSON is malformed.'});
      return elementJson;
    }
    element.css('border','1px solid grey');
    $('.errorArea').hide();
    return elementJson;
  }

  function toggleTable() {
    if (!getJsonFromElement($('.problemText')))
      return;

    var hidden = $('.tableArea').is(':hidden');
    if (hidden) {
      $('.tableArea').show();
      $('.problemArea').hide();
      $('.viewTable').text('View / Edit JSON');
    } else {
      $('.tableArea').hide();
      $('.problemArea').show();
      $('.viewTable').text('Back to Table');
    }
    $('.problems').focus();
  }

  function toggleAdvance() {
    var hide = $('.showAdvance').val() === 'no';
    if (hide) {
      $('.advancedArea').hide();
    } else {
      $('.advancedArea').show();
    }
  }

  function onError(error) {
    var errorMsg = 'Error processing the request.';
    $('.errorMsg').text(error ? JSON.stringify(error, null, 4) : errorMsg);
    $('.errorArea').show();
    onPageReady();
  }

  window.onerror = onError;

  function onMaximize() {
    $('#taWidgetContainer').addClass('fullsize');
    $(document.documentElement).addClass('noScroll');

    window.onkeyup = function(key) {
      if (key.keyCode === 27) onRestore();
    };

    resizeToParent();
  }

  function onRestore() {
    window.onkeyup = null;
    $('#taWidgetContainer').removeClass('fullsize');
    $(document.documentElement).removeClass('noScroll');
    resizeToParent();
    jumpTo('#taWidgetContainer');
  }

  function loadProfile(profileName) {
    $.get('advanced/profiles/' + profileName, function(data) {
      $('#featuresText').val(data);
    });
  }

  function onProfileChanged() {
    profileChanged = true;
    var profileName = $('.profiles').val();
    if (profileName === 'custom') {
      profileName = 'basic';
      $('.featuresText').removeAttr('readonly');
    } else {
      $('.featuresText').attr('readonly','readonly');
    }
    loadProfile(profileName);
  }

  function onFeaturesChange() {
    profileChanged = true;
  }

  function onThemeChanged() {
    loadTheme($('#themes').val());
    themeChanged = true;
  }

  function loadTheme(themeName) {
    $.get('advanced/themes/' + themeName + '.less', function(data) {
      $('#themeText').val(data);
    });
  }

  function recreateWidgetIfNeeded(callback) {
    if (profileChanged) {
      var profile;
      if ($('.showAdvance').val() === 'no') {
        profile = 'basic';
      } else {
        var selectedProfile = $('.profiles').val();
        profile = (selectedProfile === 'custom') ? JSON.parse($('#featuresText').val()) : selectedProfile;
      }
    }

    if (themeChanged || profileChanged) {
      var themeName = $('#themes').val() || 'basic';
      if (taClient) {
        destroyTradeoffAnalytcsWidget(function() {
          loadTradeoffAnalytics(profile, themeName, callback, onError);
        });
      }
    } else {
      callback();
    }
    themeChanged = false;
    profileChanged = false;
  }

  // On page load
  $(document).ready(onPageLoad);

  // Problem events
  $('.problems').change(loadSelectedProblem);
  $('.problemText').change(onProblemChanged);
  $('.viewTable').click(toggleTable);

  // Advance customization events
  $('.showAdvance').change(toggleAdvance);
  $('.profiles').change(onProfileChanged);
  $('.themes').change(onThemeChanged);
  //$('.featuresText').change(onFeaturesChange());

  // Visualization events
  $('.maximize').click(onMaximize);

  // Analyze button
  $('.analyze').click(onAnalyzeClick);

})();<commit_msg>Update index.js<commit_after>/**
 * Copyright 2014 IBM Corp. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

/**
 * Anonymous function, to use as a wrapper
 */
(function() {

  // GLOBAL VARIABLES
  var taClient = null;
  var themeChanged = false;
  var profileChanged = false;

  /**
   * Smooth scroll to any DOM element
   * @param  {String} DOM element
   */
  function jumpTo(h) {
    $('html, body').animate({
        scrollTop: $(h).offset().top
    }, 500);
  }

  function createDom(elem, map, parent) {
    var e = document.createElement(elem);
    for (var k in map) {
      e[k] = map[k];
    }
    if (parent) {
      parent.appendChild(e);
    }
    return e;
  }

  function assertNotTrue(cond, message) {
    if (!cond) {
      throw message;
    }
  }

  /**
   * Wrapper around the API
   */
  function loadTradeoffAnalytics(profile, themeName, callback, errCallback) {
    taClient = new TradeoffAnalytics({
      dilemmaServiceUrl: 'demo',
      customCssUrl: 'https://ta-cdn.mybluemix.net/modmt/styles/' + themeName + '.css',
      profile: profile,
      errCallback: errCallback
    }, 'taWidgetContainer');

    taClient.start(callback);
  }

  function showTradeoffAnalytcsWidget(problem) {
    taClient.show(problem, onResultsReady, onResultSelection);
  }

  function destroyTradeoffAnalytcsWidget(callback) {
    taClient.destroy(callback);
  }

  /**
   * Resizes the widget based on the parent DOM element size
   */
  function resizeToParent() {
    taClient.resize();
  }

  function onPageReady() {
    $('.analyze').show();
    $('.loading').hide();
  }

  function onPageLoad() {
    loadTradeoffAnalytics('basic', 'watson', onPageReady, onError);
    loadSelectedProblem();
    loadProfile('basic');
    loadTheme('watson');
  }

  function onProblemChanged() {
    var tableParent = document.getElementById('tablePlaceHolder');
    while (tableParent.childElementCount > 0) {
      tableParent.removeChild(tableParent.childNodes[0]);
    }
    try {
      var problem = JSON.parse($('.problemText').val());
      assertNotTrue(problem, 'Empty Problem');
      assertNotTrue($.isArray(problem.columns), 'Invalid problem columns');
      assertNotTrue($.isArray(problem.options), 'Invalid problem options');

      createOptionsTable(problem, tableParent);
    } catch (err) {
      onError({error:'JSON parsing error'});
    }
  }

  function loadSelectedProblem() {
    var path = 'problems/' + $('.problems').val();
    $.getJSON(path, function(data) {
      $('.problemText').val(JSON.stringify(data, null, 2)).change();
    });
  }

  function createOptionsTable(problem, parent) {
    var table = createDom('table', {}, parent);
    var tr = createDom('tr', {}, table);
    createDom('th', {
      innerHTML: 'Id'
    }, tr);
    createDom('th', {
      innerHTML: 'Name'
    }, tr);

    problem.columns.forEach(function(c) {
      var th = createDom('th', {
        className: c.is_objective ? c.goal === 'MIN' ? 'minimize' : 'maximize' : 'info'
      }, tr);
      var iconClassName = c.is_objective ? c.goal === 'MIN' ? 'legendIconMin' : 'legendIconMax' : 'legendIconNone';
      createDom('span', {
        className: 'legendIcon ' + iconClassName
      }, th);
      createDom('span', {
        innerHTML: c.full_name
      }, th);
    });
    problem.options.forEach(function(op, i) {
      var tr = createDom('tr', {
        className: i % 2 ? 'odd' : 'even'
      }, table);
      createDom('td', {
        innerHTML: op.key
      }, tr);
      createDom('td', {
        innerHTML: op.name
      }, tr);
      problem.columns.forEach(function(c) {
        createDom('td', {
          innerHTML: op.values[c.key] || 0
        }, tr);
      });
    });
    return table;
  }

  /**
   * Hack to hide the .result DOM element, we can't use $().hide()
   * Because FF doesn't support that if there is an iframe involve
   */
  function hideResults() {
    $('.viz').addClass('result');
  }

  /**
   * Show the .result DOM element
   */
  function showResults() {
    $('.viz').removeClass('result');
  }

  function onAnalyzeClick() {
    $('.analyze').hide();
    $('.loading').show();
    $('.decisionArea').hide();

    $('.errorArea').hide();
    hideResults();

    var problemJson = getJsonFromElement($('.problemText'));
    if (!problemJson)
      return;

    var featuresJson = getJsonFromElement($('.featuresText'));
    if (!featuresJson)
      return;

    recreateWidgetIfNeeded(function() {
      showTradeoffAnalytcsWidget(problemJson);
    });

  }

  function onResultsReady() {
    $('.analyze').show();
    $('.loading').hide();

    showResults();
    resizeToParent();
    onPageReady();
    jumpTo('#taWidgetContainer');
  }

  function onResultSelection(selection) {
    onRestore();
    if (selection) {
      $('.decisionArea').show();
      $('.decisionText').text(selection.name);
      jumpTo('.decisionArea');
    } else {
      $('.decisionText').text('');
      $('.decisionArea').hide();
    }
  }

  function getJsonFromElement(element) {
    var elementJson = null;
    try{
      elementJson = JSON.parse(element.val());
    } catch(e) {
      element.css('border','1px solid red');
      onError({error: 'JSON is malformed.'});
      return elementJson;
    }
    element.css('border','1px solid grey');
    $('.errorArea').hide();
    return elementJson;
  }

  function toggleTable() {
    if (!getJsonFromElement($('.problemText')))
      return;

    var hidden = $('.tableArea').is(':hidden');
    if (hidden) {
      $('.tableArea').show();
      $('.problemArea').hide();
      $('.viewTable').text('View / Edit JSON');
    } else {
      $('.tableArea').hide();
      $('.problemArea').show();
      $('.viewTable').text('Back to Table');
    }
    $('.problems').focus();
  }

  function toggleAdvance() {
    var hide = $('.showAdvance').val() === 'no';
    if (hide) {
      $('.advancedArea').hide();
    } else {
      $('.advancedArea').show();
    }
  }

  function onError(error) {
    var errorMsg = 'Error processing the request.';
    if (error) {
      try {
        errorMsg = JSON.stringify(error, null, 4);
      } catch (e) {
        // a complex object - can't be converted to json, take it's string representation
        errorMsg = error;
      }
    }

    $('.errorMsg').text(errorMsg);
    $('.errorArea').show();
    onPageReady();
    jumpTo(".errorArea");
  }

  window.onerror = onError;

  function onMaximize() {
    $('#taWidgetContainer').addClass('fullsize');
    $(document.documentElement).addClass('noScroll');

    window.onkeyup = function(key) {
      if (key.keyCode === 27) onRestore();
    };

    resizeToParent();
  }

  function onRestore() {
    window.onkeyup = null;
    $('#taWidgetContainer').removeClass('fullsize');
    $(document.documentElement).removeClass('noScroll');
    resizeToParent();
    jumpTo('#taWidgetContainer');
  }

  function loadProfile(profileName) {
    $.get('advanced/profiles/' + profileName, function(data) {
      $('#featuresText').val(data);
    });
  }

  function onProfileChanged() {
    profileChanged = true;
    var profileName = $('.profiles').val();
    if (profileName === 'custom') {
      profileName = 'basic';
      $('.featuresText').removeAttr('readonly');
    } else {
      $('.featuresText').attr('readonly','readonly');
    }
    loadProfile(profileName);
  }

  function onFeaturesChange() {
    profileChanged = true;
  }

  function onThemeChanged() {
    loadTheme($('#themes').val());
    themeChanged = true;
  }

  function loadTheme(themeName) {
    $.get('advanced/themes/' + themeName + '.less', function(data) {
      $('#themeText').val(data);
    });
  }

  function recreateWidgetIfNeeded(callback) {
    if (profileChanged) {
      var profile;
      if ($('.showAdvance').val() === 'no') {
        profile = 'basic';
      } else {
        var selectedProfile = $('.profiles').val();
        profile = (selectedProfile === 'custom') ? JSON.parse($('#featuresText').val()) : selectedProfile;
      }
    }

    if (themeChanged || profileChanged) {
      var themeName = $('#themes').val() || 'basic';
      if (taClient) {
        destroyTradeoffAnalytcsWidget(function() {
          loadTradeoffAnalytics(profile, themeName, callback, onError);
        });
      }
    } else {
      callback();
    }
    themeChanged = false;
    profileChanged = false;
  }

  // On page load
  $(document).ready(onPageLoad);

  // Problem events
  $('.problems').change(loadSelectedProblem);
  $('.problemText').change(onProblemChanged);
  $('.viewTable').click(toggleTable);

  // Advance customization events
  $('.showAdvance').change(toggleAdvance);
  $('.profiles').change(onProfileChanged);
  $('.themes').change(onThemeChanged);
  //$('.featuresText').change(onFeaturesChange());

  // Visualization events
  $('.maximize').click(onMaximize);

  // Analyze button
  $('.analyze').click(onAnalyzeClick);

})();
<|endoftext|>


<commit_before>var gulp = require('gulp');
var server = require('karma').server;

/**
 * Run test once and exit
 */
gulp.task('karma', function (done) {
  server.start({
    configFile: '../../../karma.conf.js',
    singleRun: false
  }, done);
});<commit_msg>removed karma (not needed since I'm going to launch karma by typing 'karma start karma.conf.js' in the CLI)<commit_after><|endoftext|>


<commit_before>CKEDITOR.dtd.$removeEmpty.span = 0;
CKEDITOR.dtd.$removeEmpty.i = 0;

CKEDITOR.editorConfig = function( config ) {
    config.toolbar = [
        { name: 'styles', items: [ 'Format', 'Styles', 'Font', 'FontSize' ] },
        { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ], items: [ 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat' ] },
        { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'bidi' ], items: [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'BidiLtr', 'BidiRtl', 'Language' ] },
        { name: 'align', groups: [ 'align' ], items: [ 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock' ] },
        { name: 'links', items: [ 'Link', 'Unlink', 'Anchor' ] },
        { name: 'insert', items: [ 'Image', 'oembed', 'Table', 'HorizontalRule', 'PageBreak', 'Iframe' ] },
        { name: 'colors', items: [ 'TextColor', 'BGColor' ] },
        { name: 'tools', items: [ 'Maximize', 'ShowBlocks', 'Source' ] },
    ];

    // Remove some buttons provided by the standard plugins, which are
    // not needed in the Standard(s) toolbar.
    config.removeButtons = 'Underline';

    config.entities = false;

    // Set the most common block elements.
    config.format_tags = 'p;h1;h2;h3;h4;h5;h6;pre';

    config.extraPlugins = 'image2,codemirror,clipboard,panelbutton,oembed,justify,showblocks,div';
    config.removePlugins = 'image';

    config.height = 500;
    config.contentsCss = ['/css/public.css', '/components/ckeditor/custom.css'];
    config.allowedContent = true;

    // codemirror
    config.codemirror = {
        theme: 'twilight'
    }

    // Language
    config.language = $('html').attr('lang');

    // Simplify the dialog windows.
    config.removeDialogTabs = 'image:Link;link:advanced;link:send';

    // File browser
    config.filebrowserBrowseUrl = '/admin/files?view=filepicker';
    config.filebrowserImageBrowseUrl = '/admin/files?type=i&view=filepicker';

};

CKEDITOR.on('dialogDefinition', function (event) {
    var editor = event.editor;
    var dialogDefinition = event.data.definition;
    var dialogName = event.data.name;

    var cleanUpFuncRef = CKEDITOR.tools.addFunction(function () {
        $('#filepicker-iframe').remove();
        $('html, body').removeClass('noscroll');
    });

    var tabCount = dialogDefinition.contents.length;
    for (var i = 0; i < tabCount; i++) {
        var browseButton = dialogDefinition.contents[i].get('browse');

        if (browseButton !== null) {
            browseButton.hidden = false;
            browseButton.onClick = function (dialog, i) {
                editor._.filebrowserSe = this;
                var iframe = $('<iframe id="filepicker-iframe" class="filepicker-iframe"/>').attr({
                    src: '/admin/files?view=filepicker' + // Change it to wherever  Filemanager is stored.
                        '&CKEditorFuncNum=' + CKEDITOR.instances[event.editor.name]._.filebrowserFn +
                        '&CKEditorCleanUpFuncNum=' + cleanUpFuncRef +
                        '&langCode=en' +
                        '&CKEditor=' + event.editor.name
                });

                $('body').append(iframe);
                $('html, body').addClass('noscroll');
            }
        }
    }
});
<commit_msg>CKEditor config<commit_after>CKEDITOR.dtd.$removeEmpty.span = 0;
CKEDITOR.dtd.$removeEmpty.i = 0;

CKEDITOR.editorConfig = function( config ) {
    config.toolbar = [
        { name: 'styles', items: [ 'Format', 'Styles', 'Font', 'FontSize' ] },
        { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ], items: [ 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat' ] },
        { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'bidi' ], items: [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'BidiLtr', 'BidiRtl', 'Language' ] },
        { name: 'align', groups: [ 'align' ], items: [ 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock' ] },
        { name: 'links', items: [ 'Link', 'Unlink', 'Anchor' ] },
        { name: 'insert', items: [ 'Image', 'oembed', 'Table', 'HorizontalRule', 'PageBreak', 'Iframe' ] },
        { name: 'colors', items: [ 'TextColor', 'BGColor' ] },
        { name: 'tools', items: [ 'Maximize', 'ShowBlocks', 'Source' ] },
    ];

    // Remove some buttons provided by the standard plugins, which are
    // not needed in the Standard(s) toolbar.
    config.removeButtons = 'Underline';

    config.entities = false;

    // Set the most common block elements.
    config.format_tags = 'p;h1;h2;h3;h4;h5;h6;pre';

    config.extraPlugins = 'image2,codemirror,clipboard,panelbutton,oembed,justify,showblocks,div';
    config.removePlugins = 'image';

    config.height = 500;
    config.contentsCss = ['/css/public.css', '/components/ckeditor/custom.css'];
    config.allowedContent = true;

    // codemirror
    config.codemirror = {
        theme: 'twilight'
    }

    // Language
    config.language = $('html').attr('lang');

    // Simplify the dialog windows.
    config.removeDialogTabs = 'image:Link;link:advanced;link:send';

    // File browser
    config.filebrowserBrowseUrl = '/admin/files?view=filepicker';
    config.filebrowserImageBrowseUrl = '/admin/files?type=i&view=filepicker';

};

CKEDITOR.on('dialogDefinition', function (event) {
    var editor = event.editor;
    var dialogDefinition = event.data.definition;
    var dialogName = event.data.name;

    var cleanUpFuncRef = CKEDITOR.tools.addFunction(function () {
        $('#filepicker')
            .removeClass('filepicker-modal-open')
            .data('CKEditorCleanUpFuncNum', 0)
            .data('CKEditorFuncNum', 0);
        $('html, body').removeClass('noscroll');
    });

    var tabCount = dialogDefinition.contents.length;
    for (var i = 0; i < tabCount; i++) {
        var browseButton = dialogDefinition.contents[i].get('browse');

        if (browseButton !== null) {
            browseButton.hidden = false;
            browseButton.onClick = function (dialog, i) {
                editor._.filebrowserSe = this;
                $('#filepicker')
                    .addClass('filepicker-modal-open')
                    .data('CKEditorCleanUpFuncNum', cleanUpFuncRef)
                    .data('CKEditorFuncNum', CKEDITOR.instances[event.editor.name]._.filebrowserFn);
                $('html, body').addClass('noscroll');
            }
        }
    }
}); // dialogDefinition

<|endoftext|>


<commit_before>import gulp from "gulp";
import path from "path";
import util from "gulp-util";
import config from "../config";
import server from "gulp-express";

import {javaScriptPipeline} from "./javascript";
import {htmlPipeline} from "./html";
import {lessPipeline} from "./less";
import {contentPipeline} from "./staticContent";

import chokidar from "chokidar";

import multimatch from "multimatch";

function handleFile(file, globs, pipeline, cb) {
    var result = multimatch(file, globs);
    if (result.length == 0) return;

    util.log(
        util.colors.green('File ' + file + ': ') +
        util.colors.magenta(path.basename(file))
    );

    try {
        var stream = gulp.src(file, {base:config.paths.distributionDir});
        pipeline(stream, cb);
    } catch (ex) {
        util.log(ex);
    }
}

let watchTask = (cb) => {
    console.log("Start Watching");

    let watcher = chokidar.watch(`${config.paths.sourceDir}/.`, {
        persistent: true,
        ignored: `${config.paths.distributionDir}/**/*`,
        ignoreInitial: true,
        awaitWriteFinish: {
            stabilityThreshold: 200,
            pollInterval: 100
        }
    });

    let fileHandling = (file) => {
        handleFile(file, config.paths.html, htmlPipeline, cb);
        handleFile(file, config.paths.less, lessPipeline, cb);
        handleFile(file, config.paths.content, contentPipeline, cb);
        handleFile(file, config.paths.javascript, javaScriptPipeline, cb);
    };

    watcher
        .on("change", fileHandling)
        .on("add", fileHandling)
        .on("unlink", (file) => {
            // delete
        });
};

gulp.task("watch-noserve", cb => {
    serve = false;
    watchTask(cb);
});

gulp.task("watch", watchTask);<commit_msg>Fixing the base dir to be sourceDir<commit_after>import gulp from "gulp";
import path from "path";
import util from "gulp-util";
import config from "../config";
import server from "gulp-express";

import {javaScriptPipeline} from "./javascript";
import {htmlPipeline} from "./html";
import {lessPipeline} from "./less";
import {contentPipeline} from "./staticContent";

import chokidar from "chokidar";

import multimatch from "multimatch";

function handleFile(file, globs, pipeline, cb) {
    var result = multimatch(file, globs);
    if (result.length == 0) return;

    util.log(
        util.colors.green('File ' + file + ': ') +
        util.colors.magenta(path.basename(file))
    );

    try {
        var stream = gulp.src(file, {base:config.paths.sourceDir});
        pipeline(stream, cb);
    } catch (ex) {
        util.log(ex);
    }
}

let watchTask = (cb) => {
    console.log("Start Watching");

    let watcher = chokidar.watch(`${config.paths.sourceDir}/.`, {
        persistent: true,
        ignored: `${config.paths.distributionDir}/**/*`,
        ignoreInitial: true,
        awaitWriteFinish: {
            stabilityThreshold: 200,
            pollInterval: 100
        }
    });

    let fileHandling = (file) => {
        handleFile(file, config.paths.html, htmlPipeline, cb);
        handleFile(file, config.paths.less, lessPipeline, cb);
        handleFile(file, config.paths.content, contentPipeline, cb);
        handleFile(file, config.paths.javascript, javaScriptPipeline, cb);
    };

    watcher
        .on("change", fileHandling)
        .on("add", fileHandling)
        .on("unlink", (file) => {
            // delete
        });
};

gulp.task("watch-noserve", cb => {
    serve = false;
    watchTask(cb);
});

gulp.task("watch", watchTask);<|endoftext|>


<commit_before>
var activity = Backbone.Model.extend({

    render: function(element) {
    	if (!element) return raphaelActivity;
    	var i = 10;
    	var raphaelActivity = RaphaelElement.rect(element.cx, element.cy, 100, 60, 4);
        this.set({element: raphaelActivity});

        var raphaelText = RaphaelElement.text(element.cx + 50, element.cy + 30, element.value).attr({fill: '#383838', "font-size": 16});
       // this.set({text: raphaelText});
       // raphaelText.drag(move, dragger, up);

        var color = Raphael.getColor();
        raphaelActivity.attr({fill: color, stroke: color, "fill-opacity": 0, "stroke-width": 2, cursor: "move"});
        raphaelActivity.drag(move, dragger, up);

        function get(){
        	return raphaelActivity;
        }

        return raphaelActivity;
    },

    save: function(attributes, options) {
      var elem = this.get("element");
      this.set({cx: elem.attr("x")});
	  this.set({cy: elem.attr("y")});
      var that = this;
      var attrs = ["element"];
      _.each(attrs, function(attr){
        that.unset(attr);
      });
      Backbone.Model.prototype.save.call(this, attributes, options);
      this.set({element: elem});
    }

});

var start = Backbone.Model.extend({

    render: function(element) {
        var start = RaphaelElement.circle(element.cx, element.cy, 20);
        this.set({element: start});
        var color = Raphael.getColor();
        start.attr({fill: color, stroke: color, "fill-opacity": 1, "stroke-width": 2, cursor: "move"});
        //start.drag(move, dragger, upStart);

		var raphaelText = RaphaelElement.text(element.cx, element.cy, element.value).attr({fill: '#383838', "font-size": 16, cx: element.cx, cy: element.cy});
		//raphaelText.drag(moveText, startText);

		var set = RaphaelElement.set();
		set.push(start);
		set.push(raphaelText);

    	var ox = 0;
    	var oy = 0;
    	var dragging = false;

    	set.mousedown(function(event) {
    		ox = event.screenX;
   	 		oy = event.screenY;
   	 		set.attr({
        		opacity: .5
    		});
    		dragging = true;
		});

    	$(document).mousemove(function(event) {
    		if (dragging) {
        		set.translate(event.screenX - ox, event.screenY - oy);
       	 		ox = event.screenX;
        		oy = event.screenY;
        		for (var i = connections.length; i--; ) {
            		RaphaelElement.connection(connections[i]);
        		}
        		RaphaelElement.safari();
    		}
		});

    	set.mouseup(function(event) {
    		dragging = false;
    		set.attr({
        		opacity: 1
    		});
		});

    },

    save: function(attributes, options) {
      var elem = this.get("element");
      this.set({cx: elem.attr("cx")});
	  this.set({cy: elem.attr("cy")});
      var that = this;
      var attrs = ["element"];
      _.each(attrs, function(attr){
        that.unset(attr);
      });
      Backbone.Model.prototype.save.call(this, attributes, options);
      this.set({element: elem});
    }
});

var relation = Backbone.Model.extend({

    render: function(element) {
	  function getBackboneModelById(id) {
	    if(ActivityElements.get(id) != null) return ActivityElements.get(id);
	    else if(StartElements.get(id) != null) return StartElements.get(id);
	    else if(EndElements.get(id) != null) return EndElements.get(id);
	    else if(SwimlaneElements.get(id) != null) return SwimlaneElements.get(id);
	    else if(GatewayElements.get(id) != null) return GatewayElements.get(id);
	  };

       var relation = connections.push(RaphaelElement.connection(
       		getBackboneModelById(this.get("startId")).get("element"),
        	getBackboneModelById(this.get("endId")).get("element"),
        	"#000")
        );

        this.set({element: relation});

        var color = Raphael.getColor();
    }
});

var end = Backbone.Model.extend({

    render: function(element) {
        var end = RaphaelElement.circle(element.cx, element.cy, 20);
        this.set({element: end});

        var color = Raphael.getColor();
        end.attr({fill: color, stroke: color, "fill-opacity": 0, "stroke-width": 2, cursor: "move"});
        end.drag(move, dragger, up);
    },

    save: function(attributes, options) {
      var elem = this.get("element");
      this.set({cx: elem.attr("cx")});
	  this.set({cy: elem.attr("cy")});
      var that = this;
      var attrs = ["element"];
      _.each(attrs, function(attr){
        that.unset(attr);
      });
      Backbone.Model.prototype.save.call(this, attributes, options);
      this.set({element: elem});
    }
});

var swimlane = Backbone.Model.extend({

    render: function(element) {
        var swimlane = RaphaelElement.rect(element.cx, element.cy, 500, 300, 1);
        var swimlaneNameBox = RaphaelElement.rect(element.cx, element.cy, 25, 300, 1);
        var swimlaneNameText = RaphaelElement.text(element.cx, element.cy, element.value).attr({fill: "#000000", "font-size": 18}).transform('t12,150r270');
        this.set({element: swimlane});
        swimlane.attr({stroke: "#000", "stroke-width": 2});
        swimlane.drag(resize_move, resize_start);
        swimlane.toBack();
    }
});

var gateway = Backbone.Model.extend({

	render: function(element) {

		var gateway = RaphaelElement.path('M' + element.cx + ',' + element.cy + 'L' + (element.cx-50) + ',' + (element.cy+50) + 'L' + (element.cx) + ',' + (element.cy+100) + 'L' + (element.cx+50) + ',' + (element.cy+50) + 'Z');
		this.set({element: gateway});
		var color = Raphael.getColor();
		gateway.attr({fill: color, stroke: color, "fill-opacity": 0, "stroke-width": 2, cursor: "move"});
		gateway.drag(movePath, dragger, up);

	},

	save: function(attributes, options) {
      var elem = this.get("element");
      this.set({cx: elem.getBBox().x + elem.getBBox().width/2});
	  this.set({cy: elem.getBBox().y});
      var that = this;
      var attrs = ["element"];
      _.each(attrs, function(attr){
        that.unset(attr);
      });
      Backbone.Model.prototype.save.call(this, attributes, options);
      this.set({element: elem});
    }
});

var element = Backbone.Model.extend({

});

var AllElementsList = Backbone.Collection.extend({

	model: element,
	url: 'http://morning-fjord-4117.herokuapp.com/element'
});

var ActivityList = Backbone.Collection.extend({
    model: activity,
    url: 'http://morning-fjord-4117.herokuapp.com/activity'
});

var StartList = Backbone.Collection.extend({
    model: start,
    url: 'http://morning-fjord-4117.herokuapp.com/start'
});

var EndList = Backbone.Collection.extend({
    model: end,
    url: 'http://morning-fjord-4117.herokuapp.com/end'
});

var SwimlaneList = Backbone.Collection.extend({
    model: swimlane,
    url: 'http://morning-fjord-4117.herokuapp.com/swimlane'
});

var GatewayList = Backbone.Collection.extend({
	model: gateway,
	url: 'http://morning-fjord-4117.herokuapp.com/gateway'
});

var RelationList = Backbone.Collection.extend({
	model: relation,
	url: 'http://morning-fjord-4117.herokuapp.com/relation',

       render: function(){
         for (var i=0; i<this.length; i++){
            var relation = this.get(i);

            connections.push(RaphaelElement.connection(StartElements.at(0).get("element"), ActivityElements.at(0).get("element"), "#000"));
         }
       },

       makeRelations: function(){

       }
});

function post_to_url(path, params, method) {
    method = method || "post"; // Set method to post by default, if not specified.

    // The rest of this code assumes you are not using a library.
    // It can be made less wordy if you use one.
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    for(var key in params) {
        if(params.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
         }
    }

    document.body.appendChild(form);
    form.submit();
};

function newActivity() {
	activity = new activity();
	view = new activityView({model: activity});
	activity.save();
	activityElements.push(activity);
};

function newStart() {
	start = new start();
	view = new startView({model: start});
	start.save();
	startElements.push(start);
};

function newEnd() {
	end = new end();
	view = new endView({model: end});
	end.save();
	endElements.push(end);
};

function newGateway() {
	gateway = new gateway();
	view = new gatewayView({model: gateway});
	gateway.save();
	gatewayElements.push(gateway);
};

function newRelation() {
	relation = new relation();
	view = new relationView({model: relation});
	relation.save();
	relationElements.push(relations);
};
<commit_msg>commit<commit_after>
var activity = Backbone.Model.extend({

    render: function(element) {
    	if (!element) return raphaelActivity;
    	var i = 10;
    	var raphaelActivity = RaphaelElement.rect(element.cx, element.cy, 100, 60, 4);
        this.set({element: raphaelActivity});

        var raphaelText = RaphaelElement.text(element.cx + 50, element.cy + 30, element.value).attr({fill: '#383838', "font-size": 16});
       // this.set({text: raphaelText});
       // raphaelText.drag(move, dragger, up);

        var color = Raphael.getColor();
        raphaelActivity.attr({fill: color, stroke: color, "fill-opacity": 0, "stroke-width": 2, cursor: "move"});
        raphaelActivity.drag(move, dragger, up);

        function get(){
        	return raphaelActivity;
        }

        return raphaelActivity;
    },

    save: function(attributes, options) {
      var elem = this.get("element");
      this.set({cx: elem.attr("x")});
	  this.set({cy: elem.attr("y")});
      var that = this;
      var attrs = ["element"];
      _.each(attrs, function(attr){
        that.unset(attr);
      });
      Backbone.Model.prototype.save.call(this, attributes, options);
      this.set({element: elem});
    }

});

var start = Backbone.Model.extend({

    render: function(element) {
        var start = RaphaelElement.circle(element.cx, element.cy, 20);
        this.set({element: start});
        var color = Raphael.getColor();
        start.attr({fill: color, stroke: color, "fill-opacity": 1, "stroke-width": 2, cursor: "move"});
        //start.drag(move, dragger, upStart);

		var raphaelText = RaphaelElement.text(element.cx, element.cy, element.value).attr({fill: '#383838', "font-size": 16, cx: element.cx, cy: element.cy});
		//raphaelText.drag(moveText, startText);

		var set = RaphaelElement.set();
		set.push(start);
		set.push(raphaelText);

    	var ox = 0;
    	var oy = 0;
    	var dragging = false;

    	set.mousedown(function(event) {
    		ox = event.screenX;
   	 		oy = event.screenY;
   	 		set.attr({
        		opacity: .5
    		});
    		dragging = true;
		});

    	$(document).mousemove(function(event) {
    		if (dragging) {
        		set.translate(event.screenX - ox, event.screenY - oy);
       	 		ox = event.screenX;
        		oy = event.screenY;
        		for (var i = connections.length; i--; ) {
            		RaphaelElement.connection(connections[i]);
        		}
        		RaphaelElement.safari();
    		}
		});

    	set.mouseup(function(event) {
    		dragging = false;
    		set.attr({
        		opacity: 1
    		});
		});

    },

    save: function(attributes, options) {
      var elem = this.get("element");
      this.set({cx: elem.attr("cx")});
	  this.set({cy: elem.attr("cy")});
      var that = this;
      var attrs = ["element"];
      _.each(attrs, function(attr){
        that.unset(attr);
      });
      Backbone.Model.prototype.save.call(this, attributes, options);
      this.set({element: elem});
    }
});

var relation = Backbone.Model.extend({

    render: function(element) {
	  function getBackboneModelById(id) {
	    if(ActivityElements.get(id) != null) return ActivityElements.get(id);
	    else if(StartElements.get(id) != null) return StartElements.get(id);
	    else if(EndElements.get(id) != null) return EndElements.get(id);
	    else if(SwimlaneElements.get(id) != null) return SwimlaneElements.get(id);
	    else if(GatewayElements.get(id) != null) return GatewayElements.get(id);
	  };

       var relation = connections.push(RaphaelElement.connection(
       		getBackboneModelById(this.get("startId")).get("element"),
        	getBackboneModelById(this.get("endId")).get("element"),
        	"#000")
        );

        this.set({element: relation});

        var color = Raphael.getColor();
    }
});

var end = Backbone.Model.extend({

    render: function(element) {
        var end = RaphaelElement.circle(element.cx, element.cy, 20);
        this.set({element: end});

        var color = Raphael.getColor();
        end.attr({fill: color, stroke: color, "fill-opacity": 0, "stroke-width": 2, cursor: "move"});
        end.drag(move, dragger, up);
    },

    save: function(attributes, options) {
      var elem = this.get("element");
      this.set({cx: elem.attr("cx")});
	  this.set({cy: elem.attr("cy")});
      var that = this;
      var attrs = ["element"];
      _.each(attrs, function(attr){
        that.unset(attr);
      });
      Backbone.Model.prototype.save.call(this, attributes, options);
      this.set({element: elem});
    }
});

var swimlane = Backbone.Model.extend({
   //set resizing doesnt work yet
    render: function(element) {
        var swimlane = RaphaelElement.rect(element.cx, element.cy, 500, 300, 1);
        var swimlaneNameBox = RaphaelElement.rect(element.cx, element.cy, 25, 300, 1);
        var swimlaneNameText = RaphaelElement.text(element.cx, element.cy, element.value).attr({fill: "#000000", "font-size": 18}).transform('t12,150r270');
        this.set({element: swimlane});
        swimlane.attr({stroke: "#000", "stroke-width": 2});
      //  swimlane.drag(resize_move, resize_start);
        swimlane.toBack();

        var set = RaphaelElement.set();
		set.push(swimlane);
		set.push(swimlaneNameBox);
		set.drag(resize_move, resize_start);
		//swimlane.toBack();
    }
});

var gateway = Backbone.Model.extend({

	render: function(element) {

		var gateway = RaphaelElement.path('M' + element.cx + ',' + element.cy + 'L' + (element.cx-50) + ',' + (element.cy+50) + 'L' + (element.cx) + ',' + (element.cy+100) + 'L' + (element.cx+50) + ',' + (element.cy+50) + 'Z');
		this.set({element: gateway});
		var color = Raphael.getColor();
		gateway.attr({fill: color, stroke: color, "fill-opacity": 0, "stroke-width": 2, cursor: "move"});
		gateway.drag(movePath, dragger, up);

	},

	save: function(attributes, options) {
      var elem = this.get("element");
      this.set({cx: elem.getBBox().x + elem.getBBox().width/2});
	  this.set({cy: elem.getBBox().y});
      var that = this;
      var attrs = ["element"];
      _.each(attrs, function(attr){
        that.unset(attr);
      });
      Backbone.Model.prototype.save.call(this, attributes, options);
      this.set({element: elem});
    }
});

var element = Backbone.Model.extend({

});

var AllElementsList = Backbone.Collection.extend({

	model: element,
	url: 'http://morning-fjord-4117.herokuapp.com/element'
});

var ActivityList = Backbone.Collection.extend({
    model: activity,
    url: 'http://morning-fjord-4117.herokuapp.com/activity'
});

var StartList = Backbone.Collection.extend({
    model: start,
    url: 'http://morning-fjord-4117.herokuapp.com/start'
});

var EndList = Backbone.Collection.extend({
    model: end,
    url: 'http://morning-fjord-4117.herokuapp.com/end'
});

var SwimlaneList = Backbone.Collection.extend({
    model: swimlane,
    url: 'http://morning-fjord-4117.herokuapp.com/swimlane'
});

var GatewayList = Backbone.Collection.extend({
	model: gateway,
	url: 'http://morning-fjord-4117.herokuapp.com/gateway'
});

var RelationList = Backbone.Collection.extend({
	model: relation,
	url: 'http://morning-fjord-4117.herokuapp.com/relation',

       render: function(){
         for (var i=0; i<this.length; i++){
            var relation = this.get(i);

            connections.push(RaphaelElement.connection(StartElements.at(0).get("element"), ActivityElements.at(0).get("element"), "#000"));
         }
       },

       makeRelations: function(){

       }
});

function post_to_url(path, params, method) {
    method = method || "post"; // Set method to post by default, if not specified.

    // The rest of this code assumes you are not using a library.
    // It can be made less wordy if you use one.
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    for(var key in params) {
        if(params.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
         }
    }

    document.body.appendChild(form);
    form.submit();
};

function newActivity() {
	activity = new activity();
	view = new activityView({model: activity});
	activity.save();
	activityElements.push(activity);
};

function newStart() {
	start = new start();
	view = new startView({model: start});
	start.save();
	startElements.push(start);
};

function newEnd() {
	end = new end();
	view = new endView({model: end});
	end.save();
	endElements.push(end);
};

function newGateway() {
	gateway = new gateway();
	view = new gatewayView({model: gateway});
	gateway.save();
	gatewayElements.push(gateway);
};

function newRelation() {
	relation = new relation();
	view = new relationView({model: relation});
	relation.save();
	relationElements.push(relations);
};
<|endoftext|>


<commit_before>module.exports = (GULP, PLUGINS, NODE_MODULES, REVISION) => {
    return function (callback)
    {
        PLUGINS.livereload.listen();

        GULP.watch([
            process.env.SRC + '/resources/**',
            '!' + process.env.SRC + '/resources/**/stylesheets/**/*.scss',
            '!' + process.env.SRC + '/resources/**/*.twig',
            '!' + process.env.SRC + '/resources/main/images/layout/svg-sprite/**/*.svg',
            '!' + process.env.SRC + '/resources/main/images/layout/sprite/**/*.png',
            '!' + process.env.SRC + '/resources/**/javascripts/**/*.js'
        ], ['sync']);

        GULP.watch([
            process.env.SRC + '/resources/**/stylesheets/**/*.scss',
            process.env.SUBMODULES_PATH + '/**/stylesheets/**/*.scss'
        ], ['stylesheets']);

        GULP.watch([
            process.env.SRC + '/resources/**/*.twig',
            process.env.SUBMODULES_PATH + '/**/*.twig'
        ], ['twig']);

        GULP.watch([
            process.env.SRC + '/resources/main/images/layout/svg-sprite/**/*.svg'
        ], ['svgstore']);

        GULP.watch([
            process.env.SRC + '/resources/main/images/layout/sprite/**/*.png'
        ], ['spritesmith']);

        GULP.watch([
            process.env.SRC + '/resources/**/javascripts/**/*.js',
            process.env.SUBMODULES_PATH + '/**/javascripts/**/*.js'
        ], ['javascripts']);
    }
}<commit_msg>Run sass at watch<commit_after>module.exports = (GULP, PLUGINS, NODE_MODULES, REVISION) => {
    return function (callback)
    {
        PLUGINS.livereload.listen();

        GULP.watch([
            process.env.SRC + '/resources/**',
            '!' + process.env.SRC + '/resources/**/stylesheets/**/*.scss',
            '!' + process.env.SRC + '/resources/**/*.twig',
            '!' + process.env.SRC + '/resources/main/images/layout/svg-sprite/**/*.svg',
            '!' + process.env.SRC + '/resources/main/images/layout/sprite/**/*.png',
            '!' + process.env.SRC + '/resources/**/javascripts/**/*.js'
        ], ['sync']);

        GULP.watch([
            process.env.SRC + '/resources/**/stylesheets/**/*.scss',
            process.env.SUBMODULES_PATH + '/**/stylesheets/**/*.scss'
        ], ['sass']);

        GULP.watch([
            process.env.SRC + '/resources/**/*.twig',
            process.env.SUBMODULES_PATH + '/**/*.twig'
        ], ['twig']);

        GULP.watch([
            process.env.SRC + '/resources/main/images/layout/svg-sprite/**/*.svg'
        ], ['svgstore']);

        GULP.watch([
            process.env.SRC + '/resources/main/images/layout/sprite/**/*.png'
        ], ['spritesmith']);

        GULP.watch([
            process.env.SRC + '/resources/**/javascripts/**/*.js',
            process.env.SUBMODULES_PATH + '/**/javascripts/**/*.js'
        ], ['javascripts']);
    }
}<|endoftext|>


<commit_before>/**
 * Copyright (C) 2011 Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

var wikiSidebar;
(function() {
  var hideEditCalendarEventForm = function(redirect) {
    $("#full_calendar_event").show();
    $("#edit_calendar_event_form").hide();
    $("#edit_calendar_event_form textarea").editorBox('destroy');
    if(wikiSidebar) {
      wikiSidebar.hide();
      $("#sidebar_content").show();
    }
    if($("#edit_calendar_event_form").hasClass('new_event')) {
      location.href = $(".calendar_url").attr('href');
    }
  };
  var editCalendarEventForm = function() {
    $("#full_calendar_event").hide();
    var data = $("#full_calendar_event").getTemplateData({
      textValues: ['start_at_date_string', 'start_at_time_string', 'end_at_time_string', 'title', 'all_day', 'all_day_date']
    });
    if(data.description == "No Content") {
      data.description = "";
    }
    data.start_date = data.start_at_date_string;
    data.start_date = $("#full_calendar_event .start_at_date_string").attr('title');
    data.start_time = data.start_at_time_string;
    data.end_time = data.end_at_time_string;
    if(data.all_day == 'true') {
      if(data.all_day_date) {
        data.start_date = data.all_day_date;
      }
      data.start_time = '';
      data.end_time = '';
    }
    $("#edit_calendar_event_form").fillFormData(data, {object_name: 'calendar_event'});
    $("#edit_calendar_event_form").show();
    $("#edit_calendar_event_form textarea").editorBox();
    if(wikiSidebar) {
      wikiSidebar.attachToEditor($("#edit_calendar_event_form").find("textarea:first"));
      wikiSidebar.show();
      $("#sidebar_content").hide();
    }
  };
  $(document).ready(function() {
    if(wikiSidebar) {
      wikiSidebar.init();
    }
    $(".date_field").date_field();
    $(".time_field").time_field();
    $(".delete_event_link").click(function(event) {
      event.preventDefault();
      $("#full_calendar_event_holder").confirmDelete({
        message: "Are you sure you want to delete this event?",
        url: $(this).attr('href'),
        success: function() {
          $(this).fadeOut('slow');
          location.href = $(".calendar_url").attr('href');
        }
      });
    });
    $(".switch_full_calendar_event_view").click(function(event) {
      event.preventDefault();
      $("#calendar_event_description").editorBox('toggle');
    });
    $(".edit_calendar_event_link").click(function(event) {
      event.preventDefault();
      editCalendarEventForm();
    });
    $("#edit_calendar_event_form .cancel_button").click(function(event) {
      hideEditCalendarEventForm(true);
    });
    $("#edit_calendar_event_form").formSubmit({
      object_name: 'calendar_event',
      processData: function(data) {
        data['calendar_event[start_at]'] = $.datetime.process(data.start_date + " " + data.start_time);
        data['calendar_event[end_at]'] = $.datetime.process(data.start_date + " " + data.end_time);
        data['calendar_event[description]'] = $(this).find("textarea").editorBox('get_code');
        $("#full_calendar_event_holder").fillTemplateData({
          data: data,
          htmlValues: ['description']
        });
        return data;
      },
      beforeSubmit: function(data) {
        hideEditCalendarEventForm();
        $("#full_calendar_event_holder").loadingImage();
      },
      success: function(data) {
        var calendar_event = data.calendar_event;
        var start_at = $.parseFromISO(calendar_event.start_at);
        var end_at = $.parseFromISO(calendar_event.end_at);
        calendar_event.start_at_date_string = start_at.date_formatted;
        calendar_event.start_at_time_string = start_at.time_formatted;
        calendar_event.end_at_time_string = end_at.time_formatted;
        if(Date.parse(calendar_event.all_day_date)) {
          calendar_event.all_day_date = Date.parse(calendar_event.all_day_date).toString("MMM d, yyyy");
        } else {
          calendar_event.all_day_date = '';
        }
        $("#full_calendar_event_holder").find(".from_string,.to_string,.end_at_time_string").showIf(calendar_event.end_at && calendar_event.end_at != calendar_event.start_at);
        $("#full_calendar_event_holder").find(".at_string").showIf(!calendar_event.end_at || calendar_event.end_at == calendar_event.start_at);
        $("#full_calendar_event_holder").find(".not_all_day").showIf(!calendar_event.all_day);
        $("#full_calendar_event_holder").loadingImage('remove');
        $("#full_calendar_event_holder").fillTemplateData({
          data: calendar_event,
          htmlValues: ['description']
        });
        $("#full_calendar_event_holder .start_at_date_string").attr('title', calendar_event.start_at_date_string);
        $(this).find("textarea").editorBox('set_code', calendar_event.description);
        var month = null, year = null;
        if(calendar_event.start_at) {
          year = calendar_event.start_at.substring(0, 4);
          month = calendar_event.start_at.substring(5, 7);
        }
        var calendar_url = $(".base_calendar_url").attr('href');
        var split = calendar_url.split(/#/);
        var anchor = split[1], base_url = split[0];
        var json = {}
        try{
          json = JSON.parse(anchor);
        } catch(e) {
          json = {};
        }
        if(month && year) {
          json.month = month;
          json.year = year;
        }
        $(".calendar_url").attr('href', base_url + "#" + encodeURIComponent(JSON.stringify(json)));
        if($("#full_calendar_event_holder").hasClass('editing')) {
          location.href = $(".calendar_url").attr('href');
        }
      },
      error: function(data) {
        $("#full_calendar_event_holder").loadingImage('remove');
        $(".edit_calendar_event_link:first").click();
        $("#edit_calendar_event_form").formErrors(data);
      }
    });
    setTimeout(function() {
      if($("#full_calendar_event_holder").hasClass('editing')) {
        $(".edit_calendar_event_link:first").click();
      }
    }, 500);
    $(document).fragmentChange(function(event, hash) {
      if(hash == "#edit") {
        $(".edit_calendar_event_link:first").click();
      }
    });
    $.scrollSidebar();
  });
})();
<commit_msg>fix calendar event xhr being canceled by window.location<commit_after>/**
 * Copyright (C) 2011 Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

var wikiSidebar;
jQuery(function($) {
  var $full_calendar_event        = $("#full_calendar_event"),
      $edit_calendar_event_form   = $("#edit_calendar_event_form"),
      $full_calendar_event_holder = $("#full_calendar_event_holder");

  function hideEditCalendarEventForm(redirect) {
    $full_calendar_event.show();
    $edit_calendar_event_form.hide()
      .find("textarea").editorBox('destroy');
    if (wikiSidebar) {
      wikiSidebar.hide();
      $("#sidebar_content").show();
    }
    if (redirect && $edit_calendar_event_form.hasClass('new_event')) {
      window.location.href = $(".calendar_url").attr('href');
    }
  };
  function editCalendarEventForm() {
    $full_calendar_event.hide();
    var data = $full_calendar_event.getTemplateData({
      textValues: ['start_at_date_string', 'start_at_time_string', 'end_at_time_string', 'title', 'all_day', 'all_day_date']
    });
    if (data.description == "No Content") {
      data.description = "";
    }
    data.start_date = data.start_at_date_string;
    data.start_date = $("#full_calendar_event .start_at_date_string").attr('title');
    data.start_time = data.start_at_time_string;
    data.end_time = data.end_at_time_string;
    if (data.all_day == 'true') {
      if (data.all_day_date) {
        data.start_date = data.all_day_date;
      }
      data.start_time = '';
      data.end_time = '';
    }
    $edit_calendar_event_form
      .fillFormData(data, {object_name: 'calendar_event'})
      .show()
        .find("textarea").editorBox();
    if (wikiSidebar) {
      wikiSidebar.attachToEditor($edit_calendar_event_form.find("textarea:first"));
      wikiSidebar.show();
      $("#sidebar_content").hide();
    }
  };

  if (wikiSidebar) {
    wikiSidebar.init();
  }
  $(".date_field").date_field();
  $(".time_field").time_field();
  $(".delete_event_link").click(function(event) {
    event.preventDefault();
    $("#full_calendar_event_holder").confirmDelete({
      message: "Are you sure you want to delete this event?",
      url: $(this).attr('href'),
      success: function() {
        $(this).fadeOut('slow');
        window.location.href = $(".calendar_url").attr('href');
      }
    });
  });
  $(".switch_full_calendar_event_view").click(function() {
    $("#calendar_event_description").editorBox('toggle');
    return false;
  });
  $(".edit_calendar_event_link").click(function() {
    editCalendarEventForm();
    return false;
  });
  $edit_calendar_event_form.find(".cancel_button").click(function() {
    hideEditCalendarEventForm(true);
    return false;
  });
  $edit_calendar_event_form.formSubmit({
    object_name: 'calendar_event',
    processData: function(data) {
      data['calendar_event[start_at]'] = $.datetime.process(data.start_date + " " + data.start_time);
      data['calendar_event[end_at]'] = $.datetime.process(data.start_date + " " + data.end_time);
      data['calendar_event[description]'] = $(this).find("textarea").editorBox('get_code');
      $full_calendar_event_holder.fillTemplateData({
        data: data,
        htmlValues: ['description']
      });
      return data;
    },
    beforeSubmit: function(data) {
      hideEditCalendarEventForm();
      $full_calendar_event_holder.loadingImage();
    },
    success: function(data) {
      var calendar_event = data.calendar_event,
          start_at       = $.parseFromISO(calendar_event.start_at),
          end_at         = $.parseFromISO(calendar_event.end_at),
          parsedDate     = Date.parse(calendar_event.all_day_date);

      calendar_event.start_at_date_string = start_at.date_formatted;
      calendar_event.start_at_time_string = start_at.time_formatted;
      calendar_event.end_at_time_string = end_at.time_formatted;
      calendar_event.all_day_date = parsedDate || '';

      $full_calendar_event_holder.find(".from_string,.to_string,.end_at_time_string").showIf(calendar_event.end_at && calendar_event.end_at != calendar_event.start_at);
      $full_calendar_event_holder.find(".at_string").showIf(!calendar_event.end_at || calendar_event.end_at == calendar_event.start_at);
      $full_calendar_event_holder.find(".not_all_day").showIf(!calendar_event.all_day);
      $full_calendar_event_holder
        .loadingImage('remove')
        .fillTemplateData({
          data: calendar_event,
          htmlValues: ['description']
        });
      $full_calendar_event_holder.find(".start_at_date_string").attr('title', calendar_event.start_at_date_string);
      $(this).find("textarea").editorBox('set_code', calendar_event.description);
      var month = null, year = null;
      if (calendar_event.start_at) {
        year = calendar_event.start_at.substring(0, 4);
        month = calendar_event.start_at.substring(5, 7);
      }
      var calendar_url = $(".base_calendar_url").attr('href'),
          split = calendar_url.split(/#/),
          anchor = split[1],
          base_url = split[0],
          json = {};

      try{
        json = JSON.parse(anchor);
      } catch(e) {
        json = {};
      }
      if (month && year) {
        json.month = month;
        json.year = year;
      }
      $(".calendar_url").attr('href', base_url + "#" + $.encodeToHex(JSON.stringify(json)));

      if ($full_calendar_event_holder.hasClass('editing')) {
        window.location.href = $(".calendar_url").attr('href');
      }
    },
    error: function(data) {
      $full_calendar_event_holder.loadingImage('remove');
      $(".edit_calendar_event_link:first").click();
      $edit_calendar_event_form.formErrors(data);
    }
  });
  setTimeout(function() {
    if ($full_calendar_event_holder.hasClass('editing')) {
      $(".edit_calendar_event_link:first").click();
    }
  }, 500);
  $(document).fragmentChange(function(event, hash) {
    if (hash == "#edit") {
      $(".edit_calendar_event_link:first").click();
    }
  });
  $.scrollSidebar();

});
<|endoftext|>


<commit_before>function ModelSearcher(){

	// URL for JSON that lists categories in the form [{"name":"Agricultrure","id":4074},{"name":"Agriculture","id":2558}]
	this.listService = "";

	// URL for JSON that lists categories in a hierachy (see ModelSearch.createTreeFromArray() for details)
	this.treeService = "";

	// A script on the same subdomain. When a URL is appended to this string, the resulting URL should return the original URL's content.
	// The proxy can be bypassed by using service URLs that don't begin with "http" (and are thus on the subdomain and don't need a proxy)
	this.proxy = "";

	// The id attribute of the div which contains all of DOM elements for this
	this.divId = "";

	// The jQuery-wrapped DOM element of the div which contains all of DOM elements for this
	this.div = null;

	// The name, label, and style attributes of the hidden field in which the selected ID(s) will be entered
	this.fieldName = "searcher_id_input";
	this.fieldLabel = "";
	this.fieldStyle = "padding:3px";

	// Another method of adding objects (instead of using services)
	this.objectList = null;

	// A JS array of the object(s) which should be selected in the form [{id: '2594', name: 'animals'}]
	this.selectedObjects = null;

	// The jQuery-wrapped DOM element of the hidden input which stores the selected ID(s)
	this.hiddenIdInput = null;

	// The jQuery-wrapped DOM element of the autocomplete text field input
	this.autocompleteInput = null;

	// Whether or not a tree (and the accompanying tree link) should be used
	this.hasTree = true;

	// Whether the user can select only one category from the tree (if present) or select multiple categories
	this.singleSelectionTree = false;

	// The id attribute of the div which contains the tree popup
	this.treePopupId = null;

	// The jQuery-wrapped DOM element of the div which contains the tree popup
	this.treePopup = null;

	// The jQuery-wrapped DOM element that lists the names selected from the tree
	this.treeNames = null;

	// The jQuery-wrapped DOM element that removes the names selected from the tree
	this.treeRemove = null;

	this.treeHtml = null;

	this.cRowSelector = '#characteristic-row';
	this.bRowID = 'bin';
	this.binItemTemplate = '{content} ';

	// See the attribute documentation above for explanations of these arguments
	this.init = function(divId, listService, treeService, options){
		var that = this,
			root_topics = document.getElementById('root_topics'),
			$tRem = jQuery('.tree-remove');

		this.listService = listService;
		this.treeService = treeService;
		if(typeof(options.fieldName) != "undefined")			{ this.fieldName = options.fieldName; }
		if(typeof(options.fieldLabel) != "undefined")			{ this.fieldLabel = options.fieldLabel; }
		if(typeof(options.selectedObjects) != "undefined")		{ this.selectedObjects = options.selectedObjects; }
		if(typeof(options.hasTree) != "undefined")				{ this.hasTree = options.hasTree; }
		if(typeof(options.singleSelectionTree) != "undefined")	{ this.singleSelectionTree = options.singleSelectionTree; }
		if(typeof(options.proxy) != "undefined")				{ this.proxy = options.proxy; }
		this.divId = divId;
		this.div = jQuery('#'+divId);
		this.autocompleteInput = jQuery('#searcher_autocomplete');
		this.hiddenIdInput = jQuery('#searcher_id_input');

		// Request the service through a proxy if it's not local
		if(this.listService.substr(0,4) == 'http'){
			this.listService = this.proxy+this.listService;
		}
		if(this.treeService.substr(0,4) == 'http'){
			this.treeService = this.proxy+this.treeService;
		}

		jQuery.getJSON(this.listService, function(data){
			that.autocompleteInput.unautocomplete().autocomplete(data, {
				matchContains: true,
				mustMatch: true,
				max: 20,
				formatItem: that.autocompleteFormatItem,
				formatMatch: that.autocompleteFormatMatch,
				formatResult: that.autocompleteFormatItem,
				multiple: true
			});
			that.autocompleteInput.result(that.autocompleteCallback);
			that.objectList = {};
			for(var i in data){
				that.objectList[data[i].id] = data[i];
			}
		});
		if(this.selectedObjects && this.selectedObjects.length == 1){
			this.autocompleteInput.val(this.selectedObjects[0].name);
			this.hiddenIdInput.val(this.selectedObjects[0].id);
		}
		if(this.hasTree){
			this.treePopupId = this.divId+"_model_searcher_tree_popup";
			this.treeLoading = this.div.find('.tree-loading');
		}

		$tRem.unbind('click'); // this and below have to be separate because live can't be chained
		$tRem.live('click', function(){
			var $selection = jQuery(this).closest('.tree-names'),
				$target = $selection.siblings().length ? $selection : $selection.closest('tr');

			$selection.fadeOut( function(){
				var id = this.id.replace('bin_item_',''),
					regex = new RegExp('(^|,)' + id + '(,|$)'),
					val = that.hiddenIdInput[0].value;

				$target.remove();
				that.hiddenIdInput[0].value = val.replace(regex, ',');
				that.checkAnnotationState();
			});
			return false;
		});

		if ( root_topics && root_topics.value != 'All' ) jQuery('#browse_link').unbind('click').show().click(function(){that.activatePopup()});
	};

	this.activatePopup = function() {
		var thisModelSearcher = this;
		if(window['activeTree'] == this.treeService ){
			jQuery('#'+this.treePopupId).show();
		}else{
			var $test = jQuery('#tree-loader-img'),
				$img = $test.length ?
								$test.show() :
								jQuery("").insertAfter('#browse_link');
			jQuery.getJSON(this.treeService, function(data){
				thisModelSearcher.treeHtml = thisModelSearcher.createTreeFromArray(data.category ? data.category.categories : data.categories);
				thisModelSearcher.loadPopup();
				thisModelSearcher.treeHtml = null;
				data = null;
				window['activeTree'] = thisModelSearcher.treeService;
				$img.hide();
			});
		}
		return false;
	}

	this.loadPopup = function(){
		var that = this;
		this.treePopup = jQuery().draggablePopup({
			id: that.treePopupId,
			header: '',
			content: '',
			footer: '',
			width: 500,
			closeWith: 'hide'
		});
		var content = '

'+
			'
Please select one or more feature types from the list below.

'+
			'For each type, click on the left box to select the type and its subcategories; '+
			'click on the right box to select only the type without its subcategories.

'+
			'<form method="get" action="">'+
			'
'+
			that.treeHtml+
			'
'+
			'
<input type="submit" value="Select" /> <input type="button" value="Cancel" onclick="jQuery(this).parents(\'.draggable-popup:first\').hide(); return false;" />'+
			'</form>'+
			'
'
			;
		that.treePopup.setContent(content);
		that.treePopup.div.checkTree({ onExpand: function( $parent ) {$parent.siblings().find('.expanded').click()}});
		that.treePopup.div
			.find('form:first').submit(function(){
				var ids = [];

				jQuery(this).find(':checkbox:checked').each(function(){
					var label_name = jQuery(this).siblings('label').attr('name');
					if(label_name.indexOf('record_') == 0){
						ids.push(label_name.substring(7));
					}
				});
				if (ids.length) that.addValue( ids );
				jQuery('#'+that.treePopupId).hide();
				return false;
			});

		// For large trees, keeping this in memory can cause performance issues, so we'll set it to null
		// and use thisModelSearcher.treePopupId when we need it.
		that.treePopup = null;
	};

	this.addValue = function( ids ) {
		var that = this,
			i,
			names = [],
			ids = ids || [],
			test = document.getElementById(that.bRowID),
			$bRow = test ? $(test) : jQuery("

").insertAfter(jQuery(that.cRowSelector)).find('#' + that.bRowID);

		for(i in ids){
			if ( !document.getElementById('bin_item_' + ids[i]) ) {
				that.selectedObjects.push(that.objectList[ids[i]]);
				names.push(
					that.binItemTemplate
						.replace('{content}', that.objectList[ids[i]].name)
						.replace('{id}', ids[i])
				);
			}
		}
		that.hiddenIdInput[0].value += ',' + ids.join(',');
		$bRow.append(names.join(''));
		that.autocompleteInput.val('');
		this.checkAnnotationState();
	}

	this.checkAnnotationState = function() {
		if ( jQuery('.tree-names').length > 1 ) {
			jQuery('#mobj').find('input[id*=string_value], input[id*=numeric_value]').attr('disabled', 'disabled').closest('tr').fadeOut();
		} else {
			jQuery('.annotation').fadeIn().find('#media_category_association_string_value, #media_category_association_numeric_value').removeAttr('disabled');
		}
	}

	this.resetFields = function(){
		this.autocompleteInput.val('');
		this.hiddenIdInput.val('');
		if(this.hasTree){
			this.treeNames.html('');
			this.treeRemove.hide();
			jQuery('#'+this.treePopupId).hide();
		}
	};

	this.autocompleteFormatItem = function(item, i, max){
		return jQuery.trim(item.name);
	};

	this.autocompleteFormatMatch = function(item, i, max){
		return jQuery.trim(item.name);
	};

	this.autocompleteFormatResult = function(item, i, max){
		return item.id;
	};
	var thisModelSearcher = this;
	this.autocompleteCallback = function(event, data, formatted) {
		if(data){
			thisModelSearcher.addValue([data.id])
		}else{
			//thisModelSearcher.hiddenIdInput.val('');
		}

		//thisModelSearcher.treeNames.html('');
		// thisModelSearcher.treeRemove.hide();
		return false;
	};

	this.createTreeFromArray = function(arr){
		var html = '';
		if(arr && arr.category){
			html += '
';
			if(arr.category && arr.category[0]){
				for(var i in arr.category) {
					html += '
';
					html += '<input type="checkbox" class="toggle">'+arr.category[i].title+'';
					if(arr.category[i].categories){
						html += this.createTreeFromArray(arr.category[i].categories);
					}
					html += '
';
				}
			}else if(arr.category){
				html += '
';
				html += '<input type="checkbox" class="toggle">'+arr.category.title+'';
				if(arr.category.categories){
					html += this.createTreeFromArray(arr.category.categories);
				}
				html += '
';
			}
			html += '
';
		}
		return html;
	}

};

function reinit() {
	var el = document.getElementById('root_topics'),
		id = el.value,
		label = el.options[el.selectedIndex].text,
		searcher = undefined;

	if ( id == 'All' ) {
		all_searcher();
	} else {
		searcher = new ModelSearcher();
		tmb_options['hasTree'] = true;
		tmb_options['fieldLabel'] = label;
		searcher.init( tmb_div, list_url.replace('{id}', id), all_url.replace('{id}', id), tmb_options);
	}
};<commit_msg>fixing model-searcher for feature types admin<commit_after>function ModelSearcher(){

	// URL for JSON that lists categories in the form [{"name":"Agricultrure","id":4074},{"name":"Agriculture","id":2558}]
	this.listService = "";

	// URL for JSON that lists categories in a hierachy (see ModelSearch.createTreeFromArray() for details)
	this.treeService = "";

	// A script on the same subdomain. When a URL is appended to this string, the resulting URL should return the original URL's content.
	// The proxy can be bypassed by using service URLs that don't begin with "http" (and are thus on the subdomain and don't need a proxy)
	this.proxy = "";

	// The id attribute of the div which contains all of DOM elements for this
	this.divId = "";

	// The jQuery-wrapped DOM element of the div which contains all of DOM elements for this
	this.div = null;

	// The name, label, and style attributes of the hidden field in which the selected ID(s) will be entered
	this.fieldName = "searcher_id_input";
	this.fieldLabel = "";
	this.fieldStyle = "padding:3px";

	// Another method of adding objects (instead of using services)
	this.objectList = null;

	// A JS array of the object(s) which should be selected in the form [{id: '2594', name: 'animals'}]
	this.selectedObjects = null;

	// The jQuery-wrapped DOM element of the hidden input which stores the selected ID(s)
	this.hiddenIdInput = null;

	// The jQuery-wrapped DOM element of the autocomplete text field input
	this.autocompleteInput = null;

	// Whether or not a tree (and the accompanying tree link) should be used
	this.hasTree = true;

	// Whether the user can select only one category from the tree (if present) or select multiple categories
	this.singleSelectionTree = false;

	// The id attribute of the div which contains the tree popup
	this.treePopupId = null;

	// The jQuery-wrapped DOM element of the div which contains the tree popup
	this.treePopup = null;

	// The jQuery-wrapped DOM element that lists the names selected from the tree
	this.treeNames = null;

	// The jQuery-wrapped DOM element that removes the names selected from the tree
	this.treeRemove = null;

	this.treeHtml = null;

	this.cRowSelector = '#characteristic-row';
	this.bRowID = 'bin';
	this.binItemTemplate = '{content} ';

	// See the attribute documentation above for explanations of these arguments
	this.init = function(divId, listService, treeService, options){
		var that = this,
			root_topics = document.getElementById('root_topics'),
			$tRem = jQuery('.tree-remove');

		this.listService = listService;
		this.treeService = treeService;
		if(typeof(options.fieldName) != "undefined")			{ this.fieldName = options.fieldName; }
		if(typeof(options.fieldLabel) != "undefined")			{ this.fieldLabel = options.fieldLabel; }
		if(typeof(options.selectedObjects) != "undefined")		{ this.selectedObjects = options.selectedObjects; }
		if(typeof(options.hasTree) != "undefined")				{ this.hasTree = options.hasTree; }
		if(typeof(options.singleSelectionTree) != "undefined")	{ this.singleSelectionTree = options.singleSelectionTree; }
		if(typeof(options.proxy) != "undefined")				{ this.proxy = options.proxy; }
		this.divId = divId;
		this.div = jQuery('#'+divId);
		this.autocompleteInput = jQuery('#searcher_autocomplete');
		this.hiddenIdInput = jQuery('#searcher_id_input');

		// Request the service through a proxy if it's not local
		if(this.listService.substr(0,4) == 'http'){
			this.listService = this.proxy+this.listService;
		}
		if(this.treeService.substr(0,4) == 'http'){
			this.treeService = this.proxy+this.treeService;
		}

		jQuery.getJSON(this.listService, function(data){
			that.autocompleteInput.unautocomplete().autocomplete(data, {
				matchContains: true,
				mustMatch: true,
				max: 20,
				formatItem: that.autocompleteFormatItem,
				formatMatch: that.autocompleteFormatMatch,
				formatResult: that.autocompleteFormatItem,
				multiple: true
			});
			that.autocompleteInput.result(that.autocompleteCallback);
			that.objectList = {};
			for(var i in data){
				that.objectList[data[i].id] = data[i];
			}
		});
		if(this.selectedObjects && this.selectedObjects.length == 1){
			this.autocompleteInput.val(this.selectedObjects[0].name);
			this.hiddenIdInput.val(this.selectedObjects[0].id);
		}
		if(this.hasTree){
			this.treePopupId = this.divId+"_model_searcher_tree_popup";
			this.treeLoading = this.div.find('.tree-loading');
		}

		$tRem.unbind('click'); // this and below have to be separate because live can't be chained
		$tRem.live('click', function(){
			var $selection = jQuery(this).closest('.tree-names'),
				$target = $selection.siblings().length ? $selection : $selection.closest('tr');

			$selection.fadeOut( function(){
				var id = this.id.replace('bin_item_',''),
					regex = new RegExp('(^|,)' + id + '(,|$)'),
					val = that.hiddenIdInput[0].value;

				$target.remove();
				that.hiddenIdInput[0].value = val.replace(regex, ',');
				that.checkAnnotationState();
			});
			return false;
		});

		if ( root_topics && root_topics.value != 'All' ) jQuery('#browse_link').unbind('click').show().click(function(){that.activatePopup()});
	};

	this.activatePopup = function() {
		var thisModelSearcher = this;
		if(window['activeTree'] == this.treeService ){
			jQuery('#'+this.treePopupId).show();
		}else{
			var $test = jQuery('#tree-loader-img'),
				$img = $test.length ?
								$test.show() :
								jQuery("").insertAfter('#browse_link');
			jQuery.getJSON(this.treeService, function(data){
				thisModelSearcher.treeHtml = thisModelSearcher.createTreeFromArray(data.category ? data.category.categories : data.categories);
				thisModelSearcher.loadPopup();
				thisModelSearcher.treeHtml = null;
				data = null;
				window['activeTree'] = thisModelSearcher.treeService;
				$img.hide();
			});
		}
		return false;
	}

	this.loadPopup = function(){
		var that = this;
		this.treePopup = jQuery().draggablePopup({
			id: that.treePopupId,
			header: '',
			content: '',
			footer: '',
			width: 500,
			closeWith: 'hide'
		});
		var content = '

'+
			'
Please select one or more feature types from the list below.

'+
			'For each type, click on the left box to select the type and its subcategories; '+
			'click on the right box to select only the type without its subcategories.

'+
			'<form method="get" action="">'+
			'
'+
			that.treeHtml+
			'
'+
			'
<input type="submit" value="Select" /> <input type="button" value="Cancel" onclick="jQuery(this).parents(\'.draggable-popup:first\').hide(); return false;" />'+
			'</form>'+
			'
'
			;
		that.treePopup.setContent(content);
		that.treePopup.div.checkTree({ onExpand: function( $parent ) {$parent.siblings().find('.expanded').click()}});
		that.treePopup.div
			.find('form:first').submit(function(){
				var ids = [];

				jQuery(this).find(':checkbox:checked').each(function(){
					var label_name = jQuery(this).siblings('label').attr('name');
					if(label_name.indexOf('record_') == 0){
						ids.push(label_name.substring(7));
					}
				});
				if (ids.length) that.addValue( ids );
				jQuery('#'+that.treePopupId).hide();
				return false;
			});

		// For large trees, keeping this in memory can cause performance issues, so we'll set it to null
		// and use thisModelSearcher.treePopupId when we need it.
		that.treePopup = null;
	};

	this.addValue = function( ids ) {
		var that = this,
			i,
			names = [],
			ids = ids || [],
			test = document.getElementById(that.bRowID),
			$bRow = test ? $(test) : jQuery("

").insertAfter(jQuery(that.cRowSelector)).find('#' + that.bRowID);

		for(i in ids){
			if ( !document.getElementById('bin_item_' + ids[i]) ) {
				that.selectedObjects.push(that.objectList[ids[i]]);
				names.push(
					that.binItemTemplate
						.replace('{content}', that.objectList[ids[i]].name)
						.replace('{id}', ids[i])
				);
			}
		}
		that.hiddenIdInput[0].value += (document.getElementById('root_topics') ? ',' : '') + ids.join(',');
		$bRow.append(names.join(''));
		if (document.getElementById('root_topics')) that.autocompleteInput.val('');
		this.checkAnnotationState();
	}

	this.checkAnnotationState = function() {
		if ( jQuery('.tree-names').length > 1 ) {
			jQuery('#mobj').find('input[id*=string_value], input[id*=numeric_value]').attr('disabled', 'disabled').closest('tr').fadeOut();
		} else {
			jQuery('.annotation').fadeIn().find('#media_category_association_string_value, #media_category_association_numeric_value').removeAttr('disabled');
		}
	}

	this.resetFields = function(){
		this.autocompleteInput.val('');
		this.hiddenIdInput.val('');
		if(this.hasTree){
			this.treeNames.html('');
			this.treeRemove.hide();
			jQuery('#'+this.treePopupId).hide();
		}
	};

	this.autocompleteFormatItem = function(item, i, max){
		return jQuery.trim(item.name);
	};

	this.autocompleteFormatMatch = function(item, i, max){
		return jQuery.trim(item.name);
	};

	this.autocompleteFormatResult = function(item, i, max){
		return item.id;
	};
	var thisModelSearcher = this;
	this.autocompleteCallback = function(event, data, formatted) {
		if(data){
			thisModelSearcher.addValue([data.id])
		}else{
			thisModelSearcher.hiddenIdInput.val('');
		}

		//thisModelSearcher.treeNames.html('');
		// thisModelSearcher.treeRemove.hide();
		return false;
	};

	this.createTreeFromArray = function(arr){
		var html = '';
		if(arr && arr.category){
			html += '
';
			if(arr.category && arr.category[0]){
				for(var i in arr.category) {
					html += '
';
					html += '<input type="checkbox" class="toggle">'+arr.category[i].title+'';
					if(arr.category[i].categories){
						html += this.createTreeFromArray(arr.category[i].categories);
					}
					html += '
';
				}
			}else if(arr.category){
				html += '
';
				html += '<input type="checkbox" class="toggle">'+arr.category.title+'';
				if(arr.category.categories){
					html += this.createTreeFromArray(arr.category.categories);
				}
				html += '
';
			}
			html += '
';
		}
		return html;
	}

};

function reinit() {
	var el = document.getElementById('root_topics'),
		searcher = undefined;

	if (el) {
		var	id = el.value,
			label = el.options[el.selectedIndex].text;
	} else {
		var id = label = '';
	}

	if ( id == 'All' ) {
		all_searcher();
	} else {
		searcher = new ModelSearcher();
		tmb_options['hasTree'] = true;
		tmb_options['fieldLabel'] = label;
		searcher.init( tmb_div, list_url.replace('{id}', id), all_url.replace('{id}', id), tmb_options);
	}
};<|endoftext|>