<commit_before>jQuery(function($) {

    // Add AJAX submit handler for each editable form.
    $('.editable-form').submit(function() {
        var form = $(this);
        var loading = $('#editable-loading');
        var showError = function(msg) {
            if (msg) {
                msg = ': ' + msg;
            } else {
                msg = '';
            }
            alert('An error occurred' + msg);
            loading.hide();
            form.show();
        };
        loading.css({
            top: ($(window).height() - loading.height()) / 2 + $(window).scrollTop() + "px",
            left: ($(window).width() - loading.width()) / 2 + $(window).scrollLeft() + "px"
        });
        form.hide();
        loading.show();
        if (typeof tinyMCE != "undefined" ) {
            tinyMCE.triggerSave();
        }
        form.ajaxSubmit({success: function(data) {
            if (data && data != '') {
                showError(data);
            } else {
                location.reload();
            }
        }, error: function() {
            showError();
        }});
        return false;
    })

    // Iterate through each of the editable areas and set them up.
    var realign = function() {
        $.each($('.editable-original'), function(i, editable) {
            editable = $(editable);
            // Position the editable area's edit link.
            var link = editable.next('.editable-link');
            link.offset({top: editable.offset().top,
                left: editable.offset().left - link.outerWidth() - 1});
            // Apply the editable area's overlay handler.
            var expose = {color: '#333', loadSpeed: 200, opacity: 0.9};
            var overlay = {expose: expose, closeOnClick: true, close: ':button', left: 'center', top: 'center'};
            link.overlay(overlay);
            // Position the editable area's highlight.
            var highlight = link.next('.editable-highlight')
            highlight.css({
                width: editable.width(),
                height: editable.height()
            });
            highlight.offset({top: editable.offset().top, left: editable.offset().left});
        });
    };

    realign();

    // Show/hide the editable area's highlight when mousing over/out the of
    // the edit link.
    $('.editable-link').hover(function(e) {
        $(this).next('.editable-highlight').css('visibility', 'visible');
    }, function(e) {
        $(this).next('.editable-highlight').css('visibility', 'hidden');
    });

    $('body, .editable-original').on('resize', function(e) {
        realign();
    });

    // Add the toolbar HTML and handlers.
    var cookie = 'mezzanine-admin-toolbar';
    var at = ('; ' + document.cookie).indexOf('; ' + cookie + '=');
    var closed = false;
    if (at > -1) {
        closed = document.cookie.substr(at +
            cookie.length + 1).split(';')[0];
    }
    $(window.__toolbar_html).appendTo('body');
    $('#editable-toolbar-toggle').click(function() {
        var toggle = $(this);
        var links = $('.editable-link');
        var toolbar = $('#editable-toolbar *[id!=editable-toolbar-toggle]');
        if (toggle.text() == '<<') {
            toggle.text('>>');
            toolbar.hide();
            links.css('visibility', 'hidden');
            document.cookie = cookie + '=1; path=/';
        } else {
            toggle.text('<<');
            toolbar.show();
            links.css('visibility', 'visible');
            document.cookie = cookie + '=; path=/';
        }
        return false;
    });
    $('#editable-toolbar-logout').click(function() {
        $('#editable-toolbar').submit();
        return false;
    });

    $('#editable-toolbar').fadeIn('slow');
    if (!closed) {
        $('#editable-toolbar-toggle').click();
    }

});
<commit_msg>Fixed the CKEditor integration into front-end mezzanine editing<commit_after>jQuery(function($) {

    // Add AJAX submit handler for each editable form.
    $('.editable-form').submit(function() {
        var form = $(this);
        var loading = $('#editable-loading');
        var showError = function(msg) {
            if (msg) {
                msg = ': ' + msg;
            } else {
                msg = '';
            }
            alert('An error occurred' + msg);
            loading.hide();
            form.show();
        };
        loading.css({
            top: ($(window).height() - loading.height()) / 2 + $(window).scrollTop() + "px",
            left: ($(window).width() - loading.width()) / 2 + $(window).scrollLeft() + "px"
        });
        form.hide();
        loading.show();
        if (typeof tinyMCE != "undefined" ) {
            tinyMCE.triggerSave();
        }
        $('textarea.django-ckeditor').each(function() {
			var $textarea = $(this);
			$textarea.val(CKEDITOR.instances[$textarea.attr('name')].getData());
        });
        form.ajaxSubmit({success: function(data) {
            if (data && data != '') {
                showError(data);
            } else {
                location.reload();
            }
        }, error: function() {
            showError();
        }});
        return false;
    });

    // Iterate through each of the editable areas and set them up.
    var realign = function() {
        $.each($('.editable-original'), function(i, editable) {
            editable = $(editable);
            // Position the editable area's edit link.
            var link = editable.next('.editable-link');
            link.offset({top: editable.offset().top,
                left: editable.offset().left - link.outerWidth() - 1});
            // Apply the editable area's overlay handler.
            var expose = {color: '#333', loadSpeed: 200, opacity: 0.9};
            var overlay = {expose: expose, closeOnClick: true, close: ':button', left: 'center', top: 'center'};
            link.overlay(overlay);
            // Position the editable area's highlight.
            var highlight = link.next('.editable-highlight');
            highlight.css({
                width: editable.width(),
                height: editable.height()
            });
            highlight.offset({top: editable.offset().top, left: editable.offset().left});
        });
    };

    realign();

    // Show/hide the editable area's highlight when mousing over/out the of
    // the edit link.
    $('.editable-link').hover(function(e) {
        $(this).next('.editable-highlight').css('visibility', 'visible');
    }, function(e) {
        $(this).next('.editable-highlight').css('visibility', 'hidden');
    });

    $('body, .editable-original').on('resize', function(e) {
        realign();
    });

    // Add the toolbar HTML and handlers.
    var cookie = 'mezzanine-admin-toolbar';
    var at = ('; ' + document.cookie).indexOf('; ' + cookie + '=');
    var closed = false;
    if (at > -1) {
        closed = document.cookie.substr(at +
            cookie.length + 1).split(';')[0];
    }
    $(window.__toolbar_html).appendTo('body');
    $('#editable-toolbar-toggle').click(function() {
        var toggle = $(this);
        var links = $('.editable-link');
        var toolbar = $('#editable-toolbar *[id!=editable-toolbar-toggle]');
        if (toggle.text() == '<<') {
            toggle.text('>>');
            toolbar.hide();
            links.css('visibility', 'hidden');
            document.cookie = cookie + '=1; path=/';
        } else {
            toggle.text('<<');
            toolbar.show();
            links.css('visibility', 'visible');
            document.cookie = cookie + '=; path=/';
        }
        return false;
    });
    $('#editable-toolbar-logout').click(function() {
        $('#editable-toolbar').submit();
        return false;
    });

    $('#editable-toolbar').fadeIn('slow');
    if (!closed) {
        $('#editable-toolbar-toggle').click();
    }

});
<|endoftext|>


<commit_before>var gutil = require('gulp-util');
var through = require('through2');

/**
 * The parameters for this function has grown during development.
 * Eventually, this function will need to be reorganized.
 */
//  subModule, extendsRoot, externalUsingBabylon, noBabylonInit
module.exports = function (varName, config) {
    return through.obj(function (file, enc, cb) {
        config = config || {};
        if (typeof varName === 'string') {
            varName = {
                name: varName,
                module: varName
            }
            if (varName.name === 'BABYLON') {
                varName.module = 'babylonjs';
            }
        }
        if (!config.dependencies) {
            if (config.subModule || config.extendsRoot) {
                config.dependencies = [
                    {
                        name: "BABYLON",
                        module: "babylonjs",
                        optional: false
                    }
                ]
            }
        }

        function moduleExportAddition(varName) {

            let dependenciesDefinition = `var amdDependencies = [];`;
            let functionVariables = '';
            let requireText = '';
            let amdText = '';
            let afterInitText = '';
            if (config.dependencies) {
                config.dependencies.forEach(dep => {
                    if (functionVariables) functionVariables += ',';
                    functionVariables += dep.name;
                    requireText += `        ${dep.optional ? ' try { ' : ''} ${dep.name} = ${dep.name} || require("${dep.module}"); ${dep.optional ? ' } catch(e) {} ' : ''}
`;
                    amdText += `        ${dep.optional ? ' if(require.specified && require.specified("' + dep.module + '"))' : ''} amdDependencies.push("${dep.module}");
`;
                    dependenciesDefinition += `
    var ${dep.name} = root.${dep.name};`;
                    afterInitText += `  ${dep.name} = ${dep.name} || this.${dep.name};
`
                });

            }

            let base = config.subModule ? 'BABYLON' : varName.name;

            return `\n\n(function universalModuleDefinition(root, factory) {
    ${dependenciesDefinition}
    if(typeof exports === 'object' && typeof module === 'object') {
${requireText}
        module.exports = factory(${functionVariables});
    } else if(typeof define === 'function' && define.amd) {
${amdText}
        define("${varName.module}", amdDependencies, factory);
    } else if(typeof exports === 'object') {
${requireText}
        exports["${varName.module}"] = factory(${functionVariables});
    } else {
        root["${base}"]${(config.subModule && !config.extendsRoot) ? '["' + varName.name + '"]' : ''} = factory(${functionVariables});
    }
})(this, function(${functionVariables}) {
${afterInitText}
${String(file.contents)}
    ${varName.name === 'BABYLON' || varName.name === 'INSPECTOR' ? `
var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
globalObject["${varName.name}"] = ${varName.name};
//backwards compatibility
if(typeof earcut !== 'undefined') {
    globalObject["Earcut"] = {
        earcut: earcut
    };
}` : ''}

    return ${base}${(config.subModule && !config.extendsRoot) ? '.' + varName.name : ''};
});
`;
        }

        var extendsAddition =
            `var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
`;

        var decorateAddition = `var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
`;

        if (file.isNull()) {
            cb(null, file);
            return;
        }

        if (file.isStream()) {
            //streams not supported, no need for now.
            return;
        }

        try {
            if (config.externalUsingBabylon) {
                file.contents = new Buffer(String('').concat(moduleExportAddition(varName)));
            } else {
                let pretext = '';
                file.contents = new Buffer(decorateAddition.concat(new Buffer(extendsAddition.concat(String('')).concat(moduleExportAddition(varName)))));
            }
            this.push(file);
        } catch (err) {
            this.emit('error', new gutil.PluginError('gulp-add-module-exports', err, { fileName: file.path }));
        }
        cb();
    });
};
<commit_msg>this will fix the node execution context issue<commit_after>var gutil = require('gulp-util');
var through = require('through2');

/**
 * The parameters for this function has grown during development.
 * Eventually, this function will need to be reorganized.
 */
//  subModule, extendsRoot, externalUsingBabylon, noBabylonInit
module.exports = function (varName, config) {
    return through.obj(function (file, enc, cb) {
        config = config || {};
        if (typeof varName === 'string') {
            varName = {
                name: varName,
                module: varName
            }
            if (varName.name === 'BABYLON') {
                varName.module = 'babylonjs';
            }
        }
        if (!config.dependencies) {
            if (config.subModule || config.extendsRoot) {
                config.dependencies = [
                    {
                        name: "BABYLON",
                        module: "babylonjs",
                        optional: false
                    }
                ]
            }
        }

        function moduleExportAddition(varName) {

            let dependenciesDefinition = `var amdDependencies = [];`;
            let functionVariables = '';
            let requireText = '';
            let amdText = '';
            let afterInitText = '';
            if (config.dependencies) {
                config.dependencies.forEach(dep => {
                    if (functionVariables) functionVariables += ',';
                    functionVariables += dep.name;
                    requireText += `        ${dep.optional ? ' try { ' : ''} ${dep.name} = ${dep.name} || require("${dep.module}"); ${dep.optional ? ' } catch(e) {} ' : ''}
`;
                    amdText += `        ${dep.optional ? ' if(require.specified && require.specified("' + dep.module + '"))' : ''} amdDependencies.push("${dep.module}");
`;
                    dependenciesDefinition += `
    var ${dep.name} = root.${dep.name} || this.${dep.name};`;
                    afterInitText += `  ${dep.name} = ${dep.name} || this.${dep.name};
`
                });

            }

            let base = config.subModule ? 'BABYLON' : varName.name;

            return `\n\n(function universalModuleDefinition(root, factory) {
    ${dependenciesDefinition}
    if(typeof exports === 'object' && typeof module === 'object') {
${requireText}
        module.exports = factory(${functionVariables});
    } else if(typeof define === 'function' && define.amd) {
${amdText}
        define("${varName.module}", amdDependencies, factory);
    } else if(typeof exports === 'object') {
${requireText}
        exports["${varName.module}"] = factory(${functionVariables});
    } else {
        root["${base}"]${(config.subModule && !config.extendsRoot) ? '["' + varName.name + '"]' : ''} = factory(${functionVariables});
    }
})(this, function(${functionVariables}) {
${afterInitText}
${String(file.contents)}
    ${varName.name === 'BABYLON' || varName.name === 'INSPECTOR' ? `
var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
globalObject["${varName.name}"] = ${varName.name};
//backwards compatibility
if(typeof earcut !== 'undefined') {
    globalObject["Earcut"] = {
        earcut: earcut
    };
}` : ''}

    return ${base}${(config.subModule && !config.extendsRoot) ? '.' + varName.name : ''};
});
`;
        }

        var extendsAddition =
            `var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
`;

        var decorateAddition = `var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
`;

        if (file.isNull()) {
            cb(null, file);
            return;
        }

        if (file.isStream()) {
            //streams not supported, no need for now.
            return;
        }

        try {
            if (config.externalUsingBabylon) {
                file.contents = new Buffer(String('').concat(moduleExportAddition(varName)));
            } else {
                let pretext = '';
                file.contents = new Buffer(decorateAddition.concat(new Buffer(extendsAddition.concat(String('')).concat(moduleExportAddition(varName)))));
            }
            this.push(file);
        } catch (err) {
            this.emit('error', new gutil.PluginError('gulp-add-module-exports', err, { fileName: file.path }));
        }
        cb();
    });
};
<|endoftext|>


<commit_before>
const quodyssey = require('./quodyssey')
const hostname = process.env.SERVER_HOSTNAME || 'quovadis.gienah.uberspace.de'
const port = process.env.SERVER_PORT || 80
const quiz = quodyssey(hostname, port)
let lastPrintedRound = -1
const nextRoundBtn = document.querySelector('#next-round-btn')

initUI()
initQuiz()

function initUI() {
  nextRoundBtn.addEventListener('click', advanceRound)
}

function showRound(question) {
  console.log(question)
  const round = question.round
  quiz.getNextQuestion().then(showRound)
  document.querySelector('#server-round').textContent = round

  const timeoutMs = Math.max(100, question.end.getTime() - (new Date()).getTime())

  console.log("Showing result after: " + timeoutMs)

  setTimeout(function() {
    if(round > lastPrintedRound) {
      quiz.getResultForQuiz(round).then(function (result) {
        const par = document.createElement('p')
        par.textContent = `Round ${round} result for quiz player: ${JSON.stringify(result)}`
        document.querySelector('body').appendChild(par)
      })
      quiz.getResultForNonQuiz(round).then(function (result) {
        const par = document.createElement('p')
        par.textContent = `Round ${round} result for action player: ${JSON.stringify(result)}`
        document.querySelector('body').appendChild(par)
      })

      lastPrintedRound = round

      nextRoundBtn.disabled = false
    }
  }, timeoutMs + 100)
}

function initQuiz () {
  quiz.start().then(function(res) {
    document.querySelector('#roomcode-text').textContent = res.gameId
    nextRoundBtn.disabled = false
  })
}

function advanceRound () {
  quiz.nextRound()
  quiz.getQuestion().then(showRound)
  nextRoundBtn.disabled = true
}
<commit_msg>Made question showing a little more robust<commit_after>
const quodyssey = require('./quodyssey')
const hostname = process.env.SERVER_HOSTNAME || 'quovadis.gienah.uberspace.de'
const port = process.env.SERVER_PORT || 80
const quiz = quodyssey(hostname, port)
let lastPrintedRound = -1
const nextRoundBtn = document.querySelector('#next-round-btn')

initUI()
initQuiz()

function initUI() {
  nextRoundBtn.addEventListener('click', advanceRound)
}

function showRound(question) {
  console.log(question)
  const round = question.round
  quiz.getNextQuestion().then(showRound)
  document.querySelector('#server-round').textContent = round

  const timeoutMs = Math.max(100, question.end.getTime() - (new Date()).getTime())

  console.log("Showing result after: " + timeoutMs)

  setTimeout(function() {
    if(round > lastPrintedRound) {
      quiz.getResultForQuiz(round).then(function (result) {
        const par = document.createElement('p')
        par.textContent = `Round ${round} result for quiz player: ${JSON.stringify(result)}`
        document.querySelector('body').appendChild(par)
      })
      quiz.getResultForNonQuiz(round).then(function (result) {
        const par = document.createElement('p')
        par.textContent = `Round ${round} result for action player: ${JSON.stringify(result)}`
        document.querySelector('body').appendChild(par)
      })

      lastPrintedRound = round

      nextRoundBtn.disabled = false
    }
  }, timeoutMs + 100)
}

function initQuiz () {
  quiz.start().then(function(res) {
    document.querySelector('#roomcode-text').textContent = res.gameId
    nextRoundBtn.disabled = false
  })
}

function advanceRound () {
  quiz.nextRound()

  setTimeout(function() {
    quiz.getQuestion().then(showRound)
  }, 50);

  nextRoundBtn.disabled = true
}
<|endoftext|>


<commit_before>//
// This file is the default config file and
// contains common configuration data for all environments.
//
// You can overwrite specific settings by just creating
// the corresponding block in your environment config file, ie:
//
//   // config/local.js
//
//   module.exports = {
//     //
//     // Database
//     //
//     database: {
//       connection: {
//         database: 'my-app-db'
//       }
//     }
//   }
//
module.exports = {
  //
  // Server
  //
  server: {
    port: 3000,
    router: {
      stripTrailingSlash: true
    },
    routes: {
      cors: true
    }
  },

  //
  // API URL
  //
  apiUrl: 'http://localhost:3000',

  //
  // Node runtime settings
  //
  node: {
    debugPort: 5858
  },

  //
  // Database
  //
  database: {
    connection: {
      database: 'todo'    // @changeme
    }
  },

  //
  // Logging
  //
  logging: {
    console: {
      prettyPrint: true,
      colorize: true,
      silent: false,
      timestamp: true
    }
  }
}
<commit_msg>Set settings back<commit_after>//
// This file is the default config file and
// contains common configuration data for all environments.
//
// You can overwrite specific settings by just creating
// the corresponding block in your environment config file, ie:
//
//   // config/local.js
//
//   module.exports = {
//     //
//     // Database
//     //
//     database: {
//       connection: {
//         database: 'my-app-db'
//       }
//     }
//   }
//
module.exports = {
  //
  // Server
  //
  server: {
    port: 3000,
    router: {
      stripTrailingSlash: true
    },
    routes: {
      cors: true
    }
  },

  //
  // API URL
  //
  apiUrl: 'http://localhost:3000',

  //
  // Node runtime settings
  //
  node: {
    debugPort: 5858
  },

  //
  // Database
  //
  database: {
    connection: {
      database: 'my-database-name'    // @changeme
    }
  },

  //
  // Logging
  //
  logging: {
    console: {
      prettyPrint: true,
      colorize: true,
      silent: false,
      timestamp: true
    }
  }
}
<|endoftext|>


<commit_before>

window.onload = function() {
  //alert('hey hey hey');
  statusReport('hey hey hey!');

  var name = prompt('What is your name?');
  var favDrink = prompt('Who is your favorite actor');

  var contentContainer =
  document.getElementById('content');

  contentContainer.innerHTML = name + ' wants ' + character + ' to play them in the movie about their life at General Assembly';
}

function statusReport(message){
  console.log(message);
  return message;
}
<commit_msg>added longer madlib<commit_after>window.onload = function() {
  //alert('hey hey hey');
  statusReport('hey hey hey!');

  var name = prompt('What is your name?');
  var favdrink = prompt('What is your favorite drink?');
  var favcolor = prompt('What is your favorite color?');
  var favday = prompt('What is your favorite day of the week?');
  var snuggly = prompt('Name something soft and cuddly');

  var contentContainer =
  document.getElementById('content');

  contentContainer.innerHTML = ' Once upon a time there was a person named ' + name + ' they enjoyed taking baths in ' + favdrink + ' before they took on the day. ' +
name + ' wore ' + favcolor + ' underwear outside their pants every ' + favday + ' it helped them cope with their fear of ' +
snuggly +'.' + ' The end.';
}

function statusReport(message){
  console.log(message);
  return message;
}
<|endoftext|>


<commit_before>'use strict';

/*
See EXAMPLE_ENV for setting env vars
*/

// construct HTTP referrer lookup
let referrerNames = process.env.REFERRER_NAMES.split(',');
let referrers = {};
for (let referrerName of referrerNames) {
  let key = referrerName.trim();
  let referrerKey = referrerNames['REFERRER_' + key + '_URL'];
  referrers[referrerKey] = {
    errorRedirect: referrerNames['REFERRER_' + key + '_ERROR_REDIRECT'],
    successRedirect: referrerNames['REFERRER_' + key + '_SUCCESS_REDIRECT'],
    secret: referrerNames['REFERRER_' + key + '_JWT_SECRET'],
    issuer: referrerNames['REFERRER_' + key + '_ISSUER']
  };
}

module.exports = {
  port: process.env.PORT,
  websiteRootAddress: process.env.WEBSITE_ROOT_URL,
  sessionSecret: process.env.SESSION_SECRET,
  sslPort: process.env.SSL_PORT,
  sslKey: process.env.SSL_KEY,
  sslCert: process.env.SSL_CERT,
  jwt: {
    expiresInMinutes: 1440 // 24 hours
  },

  // List passport-compatible providers installed and setup.
  // Note: callbackURL is set and determined by the app.
  // Link your "sign in with" button to http(s)://[athu host]/auth/[provider name]
  providers: {
    google: {
      clientID: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
      Strategy: require('passport-google-oauth').OAuth2Strategy,
      scope: ['profile'],
      /* authenticate: 'google-oauth2' // set when passport authenticate name is different */
    },
  },
  // generated from above, see EXAMPLE_ENV for setting env vars
  referrers
};
<commit_msg>referrer fix<commit_after>'use strict';

/*
See EXAMPLE_ENV for setting env vars
*/

// construct HTTP referrer lookup
let referrerNames = process.env.REFERRER_NAMES.split(',');
let referrers = {};
for (let referrerName of referrerNames) {
  let key = referrerName.trim();
  let referrerKey = referrerNames['REFERRER_' + key + '_URL'];
  referrers[key] = {
    errorRedirect: referrerNames['REFERRER_' + key + '_ERROR_REDIRECT'],
    successRedirect: referrerNames['REFERRER_' + key + '_SUCCESS_REDIRECT'],
    secret: referrerNames['REFERRER_' + key + '_JWT_SECRET'],
    issuer: referrerNames['REFERRER_' + key + '_ISSUER']
  };
}

module.exports = {
  port: process.env.PORT,
  websiteRootAddress: process.env.WEBSITE_ROOT_URL,
  sessionSecret: process.env.SESSION_SECRET,
  sslPort: process.env.SSL_PORT,
  sslKey: process.env.SSL_KEY,
  sslCert: process.env.SSL_CERT,
  jwt: {
    expiresInMinutes: 1440 // 24 hours
  },

  // List passport-compatible providers installed and setup.
  // Note: callbackURL is set and determined by the app.
  // Link your "sign in with" button to http(s)://[athu host]/auth/[provider name]
  providers: {
    google: {
      clientID: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
      Strategy: require('passport-google-oauth').OAuth2Strategy,
      scope: ['profile'],
      /* authenticate: 'google-oauth2' // set when passport authenticate name is different */
    },
  },
  // generated from above, see EXAMPLE_ENV for setting env vars
  referrers
};
<|endoftext|>


<commit_before>/// <reference path="typescriptServices.js" />
(function () {

    var editorCM;
    var camlCM;
    var tsServiceShim;
    var tsHost;
    var loadingData;
    var haveViewFields;
    var tooltipLastPos;

    function init() {

        initCamlJsEditor();
        initCamlXmlViewer();

        initTypeScriptService();

        loadingData = false;
        haveViewFields = false;
        setBadge(0);
        var select = document.getElementById("select-list");
        select.style.display = 'none';
        select.onchange = function () { compileCAML(editorCM); };

        if (window.chrome && chrome.tabs)
            initChromeIntegration();

        g_queryViewFields = window.g_queryViewFields || {};
        g_viewFieldsForList = window.g_viewFieldsForList || {};
        g_listFieldsByType = window.g_listFieldsByType || {};

        compileCAML(editorCM);

    }

    function initCamlJsEditor() {

        editorCM = CodeMirror.fromTextArea(document.getElementById("editor"), {
            lineNumbers: true,
            matchBrackets: true,
            mode: "text/typescript"
        });
        editorCM.setSize(null, "100%");
        if (localStorage["editorText"])
            editorCM.setValue(localStorage["editorText"]);
        editorCM.on("change", compileCAML);

        tooltipLastPos = { line: -1, ch: -1 };
        editorCM.on("cursorActivity", function () {
            if (editorCM.getCursor().line != tooltipLastPos.line || editorCM.getCursor().ch < tooltipLastPos.ch) {
                $('.tooltip').remove();
            }
        });

    }

    function initCamlXmlViewer() {

        camlCM = CodeMirror.fromTextArea(document.getElementById("caml"), {
            readOnly: true,
            mode: "text/xml"
        });
        camlCM.setSize(null, "100%");

    }

    function initTypeScriptService() {

        var tsFactory = new TypeScript.Services.TypeScriptServicesFactory();
        var tsVersion = 1;
        var camljs_d_ts_contents = "";
        var camljs_d_ts_length = 0;
        tsHost = {
            log: function (message) { console.log("tsHost: " + message); },
            information: function (message) { console.log("tsHost: " + message); },
            getCompilationSettings: function () { return "{ \"noLib\": true }"; },
            getScriptFileNames: function () { return "[\"camljs-console.ts\"]" },
            getScriptSnapshot: function (fn) {
                var snapshot = TypeScript.ScriptSnapshot.fromString(camljs_d_ts_contents + editorCM.getValue());
                return {
                    getText: function (s, e) { return snapshot.getText(s, e); },
                    getLength: function () { return snapshot.getLength(); },
                    getLineStartPositions: function () { return "[" + snapshot.getLineStartPositions().toString() + "]" },
                    getTextChangeRangeSinceVersion: function (version) { return null; }
                };
            },
            getScriptVersion: function (fn) { return tsVersion; },
            scriptChanged: function () { tsVersion++; },
            getScriptIsOpen: function (fn) { return true; },
            getLocalizedDiagnosticMessages: function () { return ""; },
            getCancellationToken: function () { return null; },
            getScriptByteOrderMark: function () { return ""; },
            getLibLength: function () { return camljs_d_ts_length; },
        };

        var client = new XMLHttpRequest();
        client.open('GET', 'Scripts/typings/camljs/camljs.d.ts');
        client.onreadystatechange = function () {
            if (client.readyState != 4)
                return;
            camljs_d_ts_contents = client.responseText;
            camljs_d_ts_length = camljs_d_ts_contents.length;
            tsServiceShim = tsFactory.createLanguageServiceShim(tsHost);
        }
        client.send();

    }

    function initChromeIntegration() {

        chrome.runtime.onConnect.addListener(function (port) {
            port.onMessage.addListener(livePreviewMessageListener);
        });

        chrome.tabs.executeScript({
            file: 'Scripts/livePreview.js'
        });
    }

    function updateLivePreview(query) {

        var select = document.getElementById("select-list");
        var listId = select.options[select.selectedIndex].value;
        if (window.chrome && chrome.tabs && listId != "") {

            localStorage["selectedListId"] = listId;
            loadingData = true;
            document.getElementById("loading").style.display = '';
            if (query.indexOf('<View>') != 0 && query.indexOf('<View ') != 0) {
                var viewFieldsString = "";
                if (window.g_viewFieldsForList[listId]) {
                    viewFieldsString += "<ViewFields>";
                    for (var j = 0; j < window.g_viewFieldsForList[listId].length; j++)
                        viewFieldsString += '<FieldRef Name="' + window.g_viewFieldsForList[listId][j] + '" />';
                    viewFieldsString += "</ViewFields>";
                }
                query = "<View>" + viewFieldsString + "<Query>" + query + "</Query></View>";
                g_queryViewFields[listId] = null;
            }
            else {

                g_queryViewFields[listId] = [];
                var viewFields = $(query).find("viewfields fieldref");
                for (var j = 0; j < viewFields.length; j++)
                {
                    g_queryViewFields[listId].push(viewFields[j].attributes["name"].value);
                }
            }
            chrome.tabs.executeScript({
                code: "RequestCamlJsLivePreviewData('" + listId + "', '" + query + "');"
            });
        }

    }

    function livePreviewMessageListener(msg)
    {
        if (msg.type == "lists") {
            setupListsDropdown(msg.lists);
        }
        else if (msg.type == "fieldsInfo") {
            rememberFieldsInfo(msg.fieldsInfo);

            if (localStorage["selectedListId"])
                compileCAML(editorCM);
        }
        else if (msg.type == "items") {
            setBadge(msg.items.length);
            haveViewFields = window.g_viewFieldsForList[localStorage["selectedListId"]];

            document.getElementById("live-preview").innerHTML = generateItemsHtml(msg.items);
            document.getElementById("loading").style.display = 'none';
        }
        else if (msg.type == "error") {
            document.getElementById("live-preview").innerHTML = msg.error;
            document.getElementById("loading").style.display = 'none';
        }
    }

    function setupListsDropdown(lists)
    {
        var select = document.getElementById("select-list");
        while (select.childNodes.length > 1) {
            select.removeChild(select.childNodes[1]);
        }
        for (var i = 0; i < lists.length; i++) {
            var option = document.createElement("option");
            option.value = lists[i].id;
            option.innerHTML = lists[i].title;
            select.appendChild(option);

            if (option.value == localStorage["selectedListId"])
                option.selected = true;
        }
        select.style.display = '';
        if (!loadingData)
            document.getElementById("loading").style.display = 'none';

    }

    function rememberFieldsInfo(fieldsInfo) {
        for (var i = 0; i < fieldsInfo.length; i++) {
            var viewFields = fieldsInfo[i].viewFields;

            var docIconIndex = viewFields.indexOf("DocIcon");
            if (docIconIndex > -1)
                viewFields.splice(docIconIndex, 1);

            for (var j = 0; j < viewFields.length; j++) {
                if (viewFields[j] == "LinkTitle" || viewFields[j] == "LinkTitleNoMenu" || viewFields[j] == "LinkDiscussionTitle")
                    viewFields[j] = "Title";
                if (viewFields[j] == "LinkFilename" || viewFields[j] == "LinkFilenameNoMenu")
                    viewFields[j] = "FileLeafRef";
            }

            window.g_viewFieldsForList[fieldsInfo[i].id] = viewFields;

            var fieldsByOriginalType = fieldsInfo[i].listFieldsByType;
            var fieldsByType = {};
            for (var type in fieldsByOriginalType) {
                var fType = type;
                if (type == "Guid" || type == "Note" || type == "Computed" || type == "ModStat" || type == "ContentTypeId" || type == "TargetTo" || type == "File")
                    fType = "Text";
                if (type == "TaxonomyFieldType")
                    fType = "Lookup";
                if (type == "TaxonomyFieldTypeMulti")
                    fType = "LookupMulti";
                if (type == "RatingCount" || type == "ThreadIndex" || type == "Likes")
                    fType = "Integer";
                if (type == "AverageRating")
                    fType = "Number";
                if (type == "Attachments")
                    fType = "Boolean";

                if (!fieldsByType[fType])
                    fieldsByType[fType] = [];

                for (var k = 0; k < fieldsByOriginalType[type].length; k++)
                    fieldsByType[fType].push(fieldsByOriginalType[type][k]);

            }

            window.g_listFieldsByType[fieldsInfo[i].id] = fieldsByType;
        }
    }

    function generateItemsHtml(items) {
        var html = "Rows returned: " + items.length + "";
        if (haveViewFields) {
            var viewFields = window.g_queryViewFields[localStorage["selectedListId"]];
            if (!viewFields || viewFields.length == 0)
                viewFields = window.g_viewFieldsForList[localStorage["selectedListId"]];
            html += "
";
            html += "

";
            for (var j = 0; j < viewFields.length; j++) {
                html += "" + viewFields[j] + "	";
            }
            html += "

";
            html += "
";
            for (var i = 0; i < items.length; i++) {
                html += "
";
                for (var j = 0; j < viewFields.length; j++) {
                    html += "" + items[i][viewFields[j]] + "	";
                }
                html += "
";
            }
            html += "

";
        }
        else {
            html += "
";
            for (var i = 0; i < items.length; i++) {
                html += "
" + items[i].Title + "
";
            }
            html += "
";
        }
        return html;

    }

    function setBadge(n) {
        var badge = document.getElementById("badge");
        if (n == 0)
            badge.style.display = 'none';
        else {
            badge.style.display = '';
            badge.innerHTML = n;
        }
    }

    function showAutoCompleteDropDown(cm, changePosition)
    {
        var scriptPosition = tsHost.getLibLength() + cm.indexFromPos(changePosition) + 1;
        var completions = tsServiceShim.languageService.getCompletionsAtPosition('camljs-console.ts', scriptPosition, true);

        if (completions == null)
            return;

        $('.tooltip').remove();

        var list = [];
        for (var i = 0; i < completions.entries.length; i++) {
            var details = tsServiceShim.languageService.getCompletionEntryDetails('camljs-console.ts', scriptPosition, completions.entries[i].name)
            list.push({
                text: completions.entries[i].name,
                displayText: completions.entries[i].name,
                typeInfo: details.type,
                kind: completions.entries[i].kind,
                docComment: details.docComment,
                className: "autocomplete-" + completions.entries[i].kind,
                livePreview: false
            });
            var fieldType = completions.entries[i].name.replace('Field', '');
            if (fieldType == "Url")
                fieldType = "URL";
            var listId = localStorage["selectedListId"];
            if (listId && g_listFieldsByType[listId] && g_listFieldsByType[listId][fieldType]) {
                var availableFields = g_listFieldsByType[listId][fieldType];
                for (var f_i = 0; f_i < availableFields.length; f_i++) {
                    list.push({
                        text: completions.entries[i].name + '("' + availableFields[f_i] + '")',
                        displayText: completions.entries[i].name + '("' + availableFields[f_i] + '")',
                        typeInfo: details.type,
                        kind: completions.entries[i].kind,
                        docComment: "Test a condition against the '" + availableFields[f_i] + "' field.",
                        className: "autocomplete-livePreview",
                        livePreview: true
                    });
                }
            }
        }

        list.sort(function (l, r) {
            if (l.displayText > r.displayText) return 1;
            if (l.displayText < r.displayText) return -1;
            return 0;
        });

        cm.showHint({
            completeSingle: false,
            hint: function (cm) {
                var cur = cm.getCursor();
                var token = cm.getTokenAt(cur);
                var completionInfo = null;
                var show_words = [];
                if (token.string == ".") {
                    for (var i = 0; i < list.length; i++) {
                        if (list[i].livePreview == false)
                            show_words.push(list[i]);
                    }

                    completionInfo = { from: cur, to: cur, list: show_words };
                }
                else {
                    for (var i = 0; i < list.length; i++) {
                        if (list[i].text.toLowerCase().indexOf(token.string.toLowerCase()) > -1)
                            show_words.push(list[i]);
                    }
                    completionInfo = {
                        from: CodeMirror.Pos(cur.line, token.start),
                        to: CodeMirror.Pos(cur.line, token.end),
                        list: show_words
                    };
                }

                var tooltip;
                CodeMirror.on(completionInfo, "select", function (completion, element) {
                    $('.tooltip').remove();
                    $(element).tooltip({
                        html: true,
                        title: '
' + completion.typeInfo + '
' + '
' + completion.docComment.replace('\n', '
') + '
',
                        trigger: 'manual', container: 'body', placement: 'right'
                    });
                    $(element).tooltip('show');
                });
                CodeMirror.on(completionInfo, "close", function () {
                    $('.tooltip').remove();
                });

                return completionInfo;
            }
        });

    }

    function showFunctionTooltip(cm, changePosition) {

        $('.tooltip').remove();

        var scriptPosition = tsHost.getLibLength() + cm.indexFromPos(changePosition) + 1;
        var signature = tsServiceShim.languageService.getSignatureAtPosition("camljs-console.ts", scriptPosition);

        if (signature) {
            tooltipLastPos = changePosition;
            var cursorCoords = cm.cursorCoords();
            var domElement = cm.getWrapperElement();

            $(domElement).data('bs.tooltip', false).tooltip({
                html: true,
                title: '
' + signature.formal[0].signatureInfo + '
' + '
' + signature.formal[0].docComment.replace('\n', '
') + '
',
                trigger: 'manual', container: 'body', placement: 'bottom'
            });
            $(domElement).off('shown.bs.tooltip').on('shown.bs.tooltip', function () {
                $('.tooltip').css('top', cursorCoords.bottom + "px").css('left', cursorCoords.left + "px")
            });
            $(domElement).tooltip('show');
        }
    }

    function compileCAML(cm, changeObj) {

        localStorage["editorText"] = cm.getValue();

        if (changeObj && changeObj.text.length == 1 && (changeObj.text[0] == '.' || changeObj.text[0] == ' '))
        {
            tsHost.scriptChanged();
            showAutoCompleteDropDown(cm, changeObj.to);
            return;
        }
        else if (changeObj && changeObj.text.length == 1 && (changeObj.text[0] == '(' || changeObj.text[0] == ','))
        {
            tsHost.scriptChanged();
            showFunctionTooltip(cm, changeObj.to);
            return;
        }
        else if (changeObj && changeObj.text.length == 1 && changeObj.text[0] == ')')
        {
            $('.tooltip').remove();
        }

        try {
            eval(cm.getValue());
            camlCM.setValue(vkbeautify.xml(query));
            updateLivePreview(query);
        }
        catch (err) {
            console.log("evaluation error");
            camlCM.setValue("");
            document.getElementById("live-preview").innerHTML = '';
            loadingData = false;
        }
    }

    init();

})();<commit_msg>Added autocompletion for viewfields<commit_after>/// <reference path="typescriptServices.js" />
(function () {

    var editorCM;
    var camlCM;
    var tsServiceShim;
    var tsHost;
    var loadingData;
    var haveViewFields;
    var tooltipLastPos;

    function init() {

        initCamlJsEditor();
        initCamlXmlViewer();

        initTypeScriptService();

        loadingData = false;
        haveViewFields = false;
        setBadge(0);
        var select = document.getElementById("select-list");
        select.style.display = 'none';
        select.onchange = function () { compileCAML(editorCM); };

        if (window.chrome && chrome.tabs)
            initChromeIntegration();

        g_queryViewFields = window.g_queryViewFields || {};
        g_viewFieldsForList = window.g_viewFieldsForList || {};
        g_listFieldsByType = window.g_listFieldsByType || {};

        compileCAML(editorCM);

    }

    function initCamlJsEditor() {

        editorCM = CodeMirror.fromTextArea(document.getElementById("editor"), {
            lineNumbers: true,
            matchBrackets: true,
            mode: "text/typescript"
        });
        editorCM.setSize(null, "100%");
        if (localStorage["editorText"])
            editorCM.setValue(localStorage["editorText"]);
        editorCM.on("change", compileCAML);

        tooltipLastPos = { line: -1, ch: -1 };
        editorCM.on("cursorActivity", function () {
            if (editorCM.getCursor().line != tooltipLastPos.line || editorCM.getCursor().ch < tooltipLastPos.ch) {
                $('.tooltip').remove();
            }
        });

    }

    function initCamlXmlViewer() {

        camlCM = CodeMirror.fromTextArea(document.getElementById("caml"), {
            readOnly: true,
            mode: "text/xml"
        });
        camlCM.setSize(null, "100%");

    }

    function initTypeScriptService() {

        var tsFactory = new TypeScript.Services.TypeScriptServicesFactory();
        var tsVersion = 1;
        var camljs_d_ts_contents = "";
        var camljs_d_ts_length = 0;
        tsHost = {
            log: function (message) { console.log("tsHost: " + message); },
            information: function (message) { console.log("tsHost: " + message); },
            getCompilationSettings: function () { return "{ \"noLib\": true }"; },
            getScriptFileNames: function () { return "[\"camljs-console.ts\"]" },
            getScriptSnapshot: function (fn) {
                var snapshot = TypeScript.ScriptSnapshot.fromString(camljs_d_ts_contents + editorCM.getValue());
                return {
                    getText: function (s, e) { return snapshot.getText(s, e); },
                    getLength: function () { return snapshot.getLength(); },
                    getLineStartPositions: function () { return "[" + snapshot.getLineStartPositions().toString() + "]" },
                    getTextChangeRangeSinceVersion: function (version) { return null; }
                };
            },
            getScriptVersion: function (fn) { return tsVersion; },
            scriptChanged: function () { tsVersion++; },
            getScriptIsOpen: function (fn) { return true; },
            getLocalizedDiagnosticMessages: function () { return ""; },
            getCancellationToken: function () { return null; },
            getScriptByteOrderMark: function () { return ""; },
            getLibLength: function () { return camljs_d_ts_length; },
        };

        var client = new XMLHttpRequest();
        client.open('GET', 'Scripts/typings/camljs/camljs.d.ts');
        client.onreadystatechange = function () {
            if (client.readyState != 4)
                return;
            camljs_d_ts_contents = client.responseText;
            camljs_d_ts_length = camljs_d_ts_contents.length;
            tsServiceShim = tsFactory.createLanguageServiceShim(tsHost);
        }
        client.send();

    }

    function initChromeIntegration() {

        chrome.runtime.onConnect.addListener(function (port) {
            port.onMessage.addListener(livePreviewMessageListener);
        });

        chrome.tabs.executeScript({
            file: 'Scripts/livePreview.js'
        });
    }

    function updateLivePreview(query) {

        var select = document.getElementById("select-list");
        var listId = select.options[select.selectedIndex].value;
        if (window.chrome && chrome.tabs && listId != "") {

            localStorage["selectedListId"] = listId;
            loadingData = true;
            document.getElementById("loading").style.display = '';
            if (query.indexOf('<View>') != 0 && query.indexOf('<View ') != 0) {
                var viewFieldsString = "";
                if (window.g_viewFieldsForList[listId]) {
                    viewFieldsString += "<ViewFields>";
                    for (var j = 0; j < window.g_viewFieldsForList[listId].length; j++)
                        viewFieldsString += '<FieldRef Name="' + window.g_viewFieldsForList[listId][j] + '" />';
                    viewFieldsString += "</ViewFields>";
                }
                query = "<View>" + viewFieldsString + "<Query>" + query + "</Query></View>";
                g_queryViewFields[listId] = null;
            }
            else {

                g_queryViewFields[listId] = [];
                var viewFields = $(query).find("viewfields fieldref");
                for (var j = 0; j < viewFields.length; j++)
                {
                    g_queryViewFields[listId].push(viewFields[j].attributes["name"].value);
                }
            }
            chrome.tabs.executeScript({
                code: "RequestCamlJsLivePreviewData('" + listId + "', '" + query + "');"
            });
        }

    }

    function livePreviewMessageListener(msg)
    {
        if (msg.type == "lists") {
            setupListsDropdown(msg.lists);
        }
        else if (msg.type == "fieldsInfo") {
            rememberFieldsInfo(msg.fieldsInfo);

            if (localStorage["selectedListId"])
                compileCAML(editorCM);
        }
        else if (msg.type == "items") {
            setBadge(msg.items.length);
            haveViewFields = window.g_viewFieldsForList[localStorage["selectedListId"]];

            document.getElementById("live-preview").innerHTML = generateItemsHtml(msg.items);
            document.getElementById("loading").style.display = 'none';
        }
        else if (msg.type == "error") {
            document.getElementById("live-preview").innerHTML = msg.error;
            document.getElementById("loading").style.display = 'none';
        }
    }

    function setupListsDropdown(lists)
    {
        var select = document.getElementById("select-list");
        while (select.childNodes.length > 1) {
            select.removeChild(select.childNodes[1]);
        }
        for (var i = 0; i < lists.length; i++) {
            var option = document.createElement("option");
            option.value = lists[i].id;
            option.innerHTML = lists[i].title;
            select.appendChild(option);

            if (option.value == localStorage["selectedListId"])
                option.selected = true;
        }
        select.style.display = '';
        if (!loadingData)
            document.getElementById("loading").style.display = 'none';

    }

    function rememberFieldsInfo(fieldsInfo) {
        for (var i = 0; i < fieldsInfo.length; i++) {
            var viewFields = fieldsInfo[i].viewFields;

            var docIconIndex = viewFields.indexOf("DocIcon");
            if (docIconIndex > -1)
                viewFields.splice(docIconIndex, 1);

            for (var j = 0; j < viewFields.length; j++) {
                if (viewFields[j] == "LinkTitle" || viewFields[j] == "LinkTitleNoMenu" || viewFields[j] == "LinkDiscussionTitle")
                    viewFields[j] = "Title";
                if (viewFields[j] == "LinkFilename" || viewFields[j] == "LinkFilenameNoMenu")
                    viewFields[j] = "FileLeafRef";
            }

            window.g_viewFieldsForList[fieldsInfo[i].id] = viewFields;

            var fieldsByOriginalType = fieldsInfo[i].listFieldsByType;
            var fieldsByType = {};
            for (var type in fieldsByOriginalType) {
                var fType = type;
                if (type == "Guid" || type == "Note" || type == "Computed" || type == "ModStat" || type == "ContentTypeId" || type == "TargetTo" || type == "File")
                    fType = "Text";
                if (type == "TaxonomyFieldType")
                    fType = "Lookup";
                if (type == "TaxonomyFieldTypeMulti")
                    fType = "LookupMulti";
                if (type == "RatingCount" || type == "ThreadIndex" || type == "Likes")
                    fType = "Integer";
                if (type == "AverageRating")
                    fType = "Number";
                if (type == "Attachments")
                    fType = "Boolean";

                if (!fieldsByType[fType])
                    fieldsByType[fType] = [];

                for (var k = 0; k < fieldsByOriginalType[type].length; k++)
                    fieldsByType[fType].push(fieldsByOriginalType[type][k]);

            }

            window.g_listFieldsByType[fieldsInfo[i].id] = fieldsByType;
        }
    }

    function generateItemsHtml(items) {
        var html = "Rows returned: " + items.length + "";
        if (haveViewFields) {
            var viewFields = window.g_queryViewFields[localStorage["selectedListId"]];
            if (!viewFields || viewFields.length == 0)
                viewFields = window.g_viewFieldsForList[localStorage["selectedListId"]];
            html += "
";
            html += "

";
            for (var j = 0; j < viewFields.length; j++) {
                html += "" + viewFields[j] + "	";
            }
            html += "

";
            html += "
";
            for (var i = 0; i < items.length; i++) {
                html += "
";
                for (var j = 0; j < viewFields.length; j++) {
                    html += "" + items[i][viewFields[j]] + "	";
                }
                html += "
";
            }
            html += "

";
        }
        else {
            html += "
";
            for (var i = 0; i < items.length; i++) {
                html += "
" + items[i].Title + "
";
            }
            html += "
";
        }
        return html;

    }

    function setBadge(n) {
        var badge = document.getElementById("badge");
        if (n == 0)
            badge.style.display = 'none';
        else {
            badge.style.display = '';
            badge.innerHTML = n;
        }
    }

    function showCodeMirrorHint(cm, list) {
        list.sort(function (l, r) {
            if (l.displayText > r.displayText) return 1;
            if (l.displayText < r.displayText) return -1;
            return 0;
        });

        cm.showHint({
            completeSingle: false,
            hint: function (cm) {
                var cur = cm.getCursor();
                var token = cm.getTokenAt(cur);
                var completionInfo = null;
                var show_words = [];
                if (token.string == ".") {
                    for (var i = 0; i < list.length; i++) {
                        if (list[i].livePreview == false)
                            show_words.push(list[i]);
                    }

                    completionInfo = { from: cur, to: cur, list: show_words };
                }
                else if (token.string == "," || token.string == "(") {

                    completionInfo = { from: cur, to: cur, list: list };

                }
                else {
                    for (var i = 0; i < list.length; i++) {
                        if (list[i].text.toLowerCase().indexOf(token.string.toLowerCase()) > -1)
                            show_words.push(list[i]);
                    }

                    completionInfo = {
                        from: CodeMirror.Pos(cur.line, token.start),
                        to: CodeMirror.Pos(cur.line, token.end),
                        list: show_words
                    };
                }

                var tooltip;
                CodeMirror.on(completionInfo, "select", function (completion, element) {
                    $('.tooltip').remove();
                    if (completion.typeInfo) {
                        $(element).tooltip({
                            html: true,
                            title: '
' + completion.typeInfo + '
' + '
' + completion.docComment.replace('\n', '
') + '
',
                            trigger: 'manual', container: 'body', placement: 'right'
                        });
                        $(element).tooltip('show');
                    }
                });
                CodeMirror.on(completionInfo, "close", function () {
                    $('.tooltip').remove();
                });

                return completionInfo;
            }
        });
    }

    function showAutoCompleteDropDown(cm, changePosition)
    {
        var scriptPosition = tsHost.getLibLength() + cm.indexFromPos(changePosition) + 1;
        var completions = tsServiceShim.languageService.getCompletionsAtPosition('camljs-console.ts', scriptPosition, true);

        if (completions == null)
            return;

        $('.tooltip').remove();

        var list = [];
        for (var i = 0; i < completions.entries.length; i++) {
            var details = tsServiceShim.languageService.getCompletionEntryDetails('camljs-console.ts', scriptPosition, completions.entries[i].name)
            list.push({
                text: completions.entries[i].name,
                displayText: completions.entries[i].name,
                typeInfo: details.type,
                kind: completions.entries[i].kind,
                docComment: details.docComment,
                className: "autocomplete-" + completions.entries[i].kind,
                livePreview: false
            });
            var fieldType = completions.entries[i].name.replace('Field', '');
            if (fieldType == "Url")
                fieldType = "URL";
            var listId = localStorage["selectedListId"];
            if (listId && g_listFieldsByType[listId] && g_listFieldsByType[listId][fieldType]) {
                var availableFields = g_listFieldsByType[listId][fieldType];
                for (var f_i = 0; f_i < availableFields.length; f_i++) {
                    list.push({
                        text: completions.entries[i].name + '("' + availableFields[f_i] + '")',
                        displayText: completions.entries[i].name + '("' + availableFields[f_i] + '")',
                        typeInfo: details.type,
                        kind: completions.entries[i].kind,
                        docComment: "Test a condition against the '" + availableFields[f_i] + "' field.",
                        className: "autocomplete-livePreview",
                        livePreview: true
                    });
                }
            }
        }

        showCodeMirrorHint(cm, list);

    }

    function showFunctionTooltip(cm, changePosition) {

        $('.tooltip').remove();

        var scriptPosition = tsHost.getLibLength() + cm.indexFromPos(changePosition) + 1;
        var signature = tsServiceShim.languageService.getSignatureAtPosition("camljs-console.ts", scriptPosition);

        if (signature) {

            if (signature.actual.currentParameter != -1
                && !signature.actual.currentParameterIsTypeParameter
                && signature.formal[signature.activeFormal].parameters[signature.actual.currentParameter].name == "viewFields")
            {
                var listId = localStorage["selectedListId"];
                var list = [];
                for (var t in g_listFieldsByType[listId])
                {
                    for (var i = 0; i < g_listFieldsByType[listId][t].length; i++)
                    {
                        list.push({
                            text: "\"" + g_listFieldsByType[listId][t][i] + "\"",
                            displayText: g_listFieldsByType[listId][t][i],
                            className: "autocomplete-livePreview",
                            livePreview: true
                        });
                    }
                }
                showCodeMirrorHint(cm, list);
                return;
            }

            tooltipLastPos = changePosition;
            var cursorCoords = cm.cursorCoords();
            var domElement = cm.getWrapperElement();

            $(domElement).data('bs.tooltip', false).tooltip({
                html: true,
                title: '
' + signature.formal[0].signatureInfo + '
' + '
' + signature.formal[0].docComment.replace('\n', '
') + '
',
                trigger: 'manual', container: 'body', placement: 'bottom'
            });
            $(domElement).off('shown.bs.tooltip').on('shown.bs.tooltip', function () {
                $('.tooltip').css('top', cursorCoords.bottom + "px").css('left', cursorCoords.left + "px")
            });
            $(domElement).tooltip('show');
        }
    }

    function compileCAML(cm, changeObj) {

        localStorage["editorText"] = cm.getValue();

        if (changeObj && changeObj.text.length == 1 && (changeObj.text[0] == '.' || changeObj.text[0] == ' '))
        {
            tsHost.scriptChanged();
            showAutoCompleteDropDown(cm, changeObj.to);
            return;
        }
        else if (changeObj && changeObj.text.length == 1 && (changeObj.text[0] == '(' || changeObj.text[0] == ','))
        {
            tsHost.scriptChanged();
            showFunctionTooltip(cm, changeObj.to);
        }
        else if (changeObj && changeObj.text.length == 1 && changeObj.text[0] == ')')
        {
            $('.tooltip').remove();
        }

        try {
            eval(cm.getValue());
            camlCM.setValue(vkbeautify.xml(query));
            updateLivePreview(query);
        }
        catch (err) {
            console.log("evaluation error");
            camlCM.setValue("");
            document.getElementById("live-preview").innerHTML = '';
            loadingData = false;
        }
    }

    init();

})();<|endoftext|>


<commit_before>$.extend($.ui.sortable.prototype, {
   _uiHash: function(inst) {
      var self = inst || this;

      /* cms-addition:
       * return the sortable-plugin-object as self */
      return {
         helper: self.helper,
         placeholder: self.placeholder || $([]),
         position: self.position,
         absolutePosition: self.positionAbs, //deprecated
         offset: self.positionAbs,
         item: self.currentItem,
         sender: inst ? inst.element : null,
         self: self
      };
   },
   _mouseStop: function(event, noPropagation) {

      if (!event)
         return;

      //If we are using droppables, inform the manager about the drop
      if ($.ui.ddmanager && !this.options.dropBehaviour)
         $.ui.ddmanager.drop(this, event);

      if (this.options.revert) {
         var self = this;
         var cur;

         /* cms-addition:
          * in case the placeholder is hidden use the initial offset for reverting */
         if (self.placeholder.css('display') == 'none') {
            cur = self.cmsStartOffset;
         } else {
            cur = self.placeholder.offset();
         }

         self.reverting = true;

         $(this.helper).animate({
            left: cur.left - this.offset.parent.left - self.margins.left + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollLeft),
            top: cur.top - this.offset.parent.top - self.margins.top + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollTop)
         }, parseInt(this.options.revert, 10) || 500, function() {
            self._clear(event);
         });
      } else {
         this._clear(event, noPropagation);
      }

      return false;

   },
   _intersectsWithPointer: function(item) {

      var isOverElementHeight = $.ui.isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height), isOverElementWidth = $.ui.isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width), isOverElement = isOverElementHeight && isOverElementWidth;

      /* cms-addition:
       *  verify if item parent matches the container the pointer intersect with */
      var isOverElementOld = isOverElement;

      if (isOverElement) {
         isOverElement = false;
         for (var i = this.containers.length - 1; i >= 0; i--) {
            if (this._intersectsWith(this.containers[i].containerCache)) {
               if (this.containers[i].element[0] == item.item.parent().get(0)) {
                  isOverElement = true;
                  break;
               }
            }
         }
      }

      if (!isOverElement)
         return false;

      var verticalDirection = this._getDragVerticalDirection(), horizontalDirection = this._getDragHorizontalDirection();

      return this.floating ? (((horizontalDirection && horizontalDirection == "right") || verticalDirection == "down") ? 2 : 1) : (verticalDirection && (verticalDirection == "down" ? 2 : 1));

   }
})

/**
 * Application entry point.
 */
$('document').ready(function() {

   // TODO: may be it is better to load the toolbar after successfully loading the data
   $('.cms-item a.ui-icon').live('click', cms.toolbar.toggleAdditionalInfo);
   cms.toolbar.addToolbar();
   $('.cms-item-list div.cms-additional div').jHelperTip({
      trigger: 'hover',
      source: 'attribute',
      attrName: 'alt',
      topOff: -30,
      opacity: 0.8,
      live: true
   });

   cms.data.loadAllData(function(ok) {
      if (ok) {
         cms.data.fillContainers();
         cms.toolbar.resetNewList();
         if (!cms.data.allowEdit) {
            if (cms.data.lockedBy) {
               alert('You can\'t edit this page. It is locked by the user "' + cms.data.lockedBy + '"');
            } else {
               alert('You do not have the necessary permissions to edit this page.');
            }
            var $buttons = $(cms.util.makeCombinedSelector(['Move', 'Delete', 'Add', 'New', 'Favorites', 'Recent'], 'button[name="%"]'));
            $buttons.unbind('click').unbind('mouseover').css('color', '#aaaaaa');
            if (cms.data.lockedBy) {
               $buttons.attr('alt', 'Page locked by ' + cms.data.lockedBy);
               $buttons.jHelperTip({
                  trigger: "hover",
                  source: "attribute",
                  attrName: "alt",
                  autoClose: true
               });
            }
         }
         $(document).trigger("cms-data-loaded");

      } else {
            // TODO
      }
   });
});
<commit_msg>Fixed issue with favorite-dropzone on large pages.<commit_after>$.extend($.ui.sortable.prototype, {
   _uiHash: function(inst) {
      var self = inst || this;

      /* cms-addition:
       * return the sortable-plugin-object as self */
      return {
         helper: self.helper,
         placeholder: self.placeholder || $([]),
         position: self.position,
         absolutePosition: self.positionAbs, //deprecated
         offset: self.positionAbs,
         item: self.currentItem,
         sender: inst ? inst.element : null,
         self: self
      };
   },
   _mouseStop: function(event, noPropagation) {

      if (!event)
         return;

      //If we are using droppables, inform the manager about the drop
      if ($.ui.ddmanager && !this.options.dropBehaviour)
         $.ui.ddmanager.drop(this, event);

      if (this.options.revert) {
         var self = this;
         var cur;

         /* cms-addition:
          * in case the placeholder is hidden use the initial offset for reverting */
         if (self.placeholder.css('display') == 'none') {
            cur = self.cmsStartOffset;
         } else {
            cur = self.placeholder.offset();
         }

         self.reverting = true;

         $(this.helper).animate({
            left: cur.left - this.offset.parent.left - self.margins.left + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollLeft),
            top: cur.top - this.offset.parent.top - self.margins.top + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollTop)
         }, parseInt(this.options.revert, 10) || 500, function() {
            self._clear(event);
         });
      } else {
         this._clear(event, noPropagation);
      }

      return false;

   },
   _intersectsWithPointer: function(item) {

      var isOverElementHeight = $.ui.isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height), isOverElementWidth = $.ui.isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width), isOverElement = isOverElementHeight && isOverElementWidth;

      /* cms-addition:
       *  verify if item parent matches the container the pointer intersect with */
      var isOverElementOld = isOverElement;

      if (isOverElement) {
         isOverElement = false;
         for (var i = this.containers.length - 1; i >= 0; i--) {
            if (this._intersectsWith(this.containers[i].containerCache)) {
               if (this.containers[i].element[0] == item.item.parent().get(0)) {
                  isOverElement = true;
                  break;
               }
            }
         }
      }

      if (!isOverElement)
         return false;

      var verticalDirection = this._getDragVerticalDirection(), horizontalDirection = this._getDragHorizontalDirection();

      return this.floating ? (((horizontalDirection && horizontalDirection == "right") || verticalDirection == "down") ? 2 : 1) : (verticalDirection && (verticalDirection == "down" ? 2 : 1));

   },
   _refreshItems: function(event) {
        /*
         * cms-addition:
         * the arrays this.containers and queries are filled in a different order to avoid problems with favorites-dropzone
         */
        this.items = [];
        this.containers = [];
        var items = this.items;
        var self = this;
        var queries = [];
        var connectWith = this._connectWith();

        if(connectWith) {
            for (var i = connectWith.length - 1; i >= 0; i--){
                var cur = $(connectWith[i]);
                for (var j = cur.length - 1; j >= 0; j--){
                    var inst = $.data(cur[j], 'sortable');
                    if(inst && !inst.options.disabled) {
                        queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element[0], event, { item: this.currentItem }) : $(inst.options.items, inst.element), inst]);
                        this.containers.push(inst);
                    }
                };
            };
        }else{
            this.containers = [this];
            queries = [[$.isFunction(this.options.items) ? this.options.items.call(this.element[0], event, { item: this.currentItem }) : $(this.options.items, this.element), this]];
        }

		for (var i = queries.length - 1; i >= 0; i--) {
			var targetData = queries[i][1];
			var _queries = queries[i][0];

			for (var j=0, queriesLength = _queries.length; j < queriesLength; j++) {
				var item = $(_queries[j]);

				item.data('sortable-item', targetData); // Data for target checking (mouse manager)

				items.push({
					item: item,
					instance: targetData,
					width: 0, height: 0,
					left: 0, top: 0
				});
			};
		};

	}
})

/**
 * Application entry point.
 */
$('document').ready(function() {

   // TODO: may be it is better to load the toolbar after successfully loading the data
   $('.cms-item a.ui-icon').live('click', cms.toolbar.toggleAdditionalInfo);
   cms.toolbar.addToolbar();
   $('.cms-item-list div.cms-additional div').jHelperTip({
      trigger: 'hover',
      source: 'attribute',
      attrName: 'alt',
      topOff: -30,
      opacity: 0.8,
      live: true
   });

   cms.data.loadAllData(function(ok) {
      if (ok) {
         cms.data.fillContainers();
         cms.toolbar.resetNewList();
         if (!cms.data.allowEdit) {
            if (cms.data.lockedBy) {
               alert('You can\'t edit this page. It is locked by the user "' + cms.data.lockedBy + '"');
            } else {
               alert('You do not have the necessary permissions to edit this page.');
            }
            var $buttons = $(cms.util.makeCombinedSelector(['Move', 'Delete', 'Add', 'New', 'Favorites', 'Recent'], 'button[name="%"]'));
            $buttons.unbind('click').unbind('mouseover').css('color', '#aaaaaa');
            if (cms.data.lockedBy) {
               $buttons.attr('alt', 'Page locked by ' + cms.data.lockedBy);
               $buttons.jHelperTip({
                  trigger: "hover",
                  source: "attribute",
                  attrName: "alt",
                  autoClose: true
               });
            }
         }
         $(document).trigger("cms-data-loaded");

      } else {
            // TODO
      }
   });
});
<|endoftext|>


<commit_before>// ==UserScript==
// @name        999dice rain alert
// should work with script/tamper/violent monkeys, other userscript tools
// ==/UserScript==

if (location.hostname == 'www.999dice.com') {

	function soundz() {
		window.audio = {};
		audio["alert"] = new Audio();
		audio["alert"].src = "https://cdn.rawgit.com/hamboning/999dice-toys/master/codec.wav";
		window.audio["alert"].play();
		return false;
	}

	$("#ChatTabChatContainer").bind("DOMSubtreeModified",function(){
		el = $(this);

		lastmsg = el.children().last('.ChatText').text();
		BtcRainButton = el.children().last('.ChatText').find('.TextButton').text();

		checkRain = (/BTC/i.test(BtcRainButton));
		soundtest = (/Ancient Psychic Tandem War Elephant/i.test(lastmsg));

		if (( checkRain ) || ( soundtest ))
			{ soundz(); }
	});
}
<commit_msg>Update rain-alert.js<commit_after>// ==UserScript==
// @name        999dice rain alert
// should work with script/tamper/violent monkeys, other userscript tools
// ==/UserScript==

if (location.hostname == 'www.999dice.com') {

	function soundz() {
		window.audio = {};
		audio["alert"] = new Audio();
		audio["alert"].src = "https://cdn.rawgit.com/hamboning/999dice-toys/master/codec.wav";
		window.audio["alert"].play();
		return false;
	}

	window['last_button'] = null;

	$("#ChatTabChatContainer").bind("DOMSubtreeModified",function(){
		el = $(this);

		lastmsg = el.children().last('.ChatText').text();
		var crtButton = el.children().last('.ChatText').find('.TextButton');
		BtcRainButton = crtButton.text();

		checkRain = (/BTC/i.test(BtcRainButton));
		soundtest = (/Ancient Psychic TandeasdasdElephant/i.test(lastmsg));

		if ((( checkRain ) || ( soundtest )) && (crtButton.get(0) != window['last_button']))
			{
				window['last_button'] = crtButton.get(0);
				soundz();
			}
	});
}
<|endoftext|>


<commit_before>import { GetFormattedTime, GetSecondsFromHMS } from "../../utils/time.js";
import { PolygonEditor } from "./polygon-editor.js";

class AnnotationGUI {

    constructor(annotator){
        this.annotator = annotator;

        this.Create();

        this.open = false;

        //Hide the container
        this.isVisible = false;
        this.$container.hide();

        this.polyEditor = new PolygonEditor(this.annotator);

        this.annotator.$container.on("OnPolygonEditingEnded", () => {
            this.SetVisible(true);
        });

    }

    GetTagsQuery(){
        return {
            url: this.annotator.tagsURL,
            dataType: 'json',
            delay: 250,
            cache: true,
            processResults: function (data) {
                // Parse the labels into the format expected by Select2
                let tags = [];
                let index = 1;
                for(let term of data["terms"]){
                    tags.push({
                        id: index,
                        text: term["rdfs:label"]
                    });
                    index++;
                }
                return {
                    results: tags
                };
            }
        }
    }

    Create(){
        this.$container = $("

").appendTo(this.annotator.player.$container);
        this.$postToolbar = $("

").appendTo(this.$container);
        this.$postToolbar.css("margin-bottom", "5px");
        this.$postToolbar2 = $("

").appendTo(this.$container);
        this.$postToolbar2.css("margin-bottom", "5px");
        this.$postToolbar3 = $("

").appendTo(this.$container);

        this.$postToolbar.append($("

").css("flex-grow", 1).css("order", 0));

        // Make title div
        let $titleDiv = $("

");
        this.$titleLabel = $("
Create Annotation
").appendTo($titleDiv);
        this.RegisterElement($titleDiv, this.$postToolbar, -10);

        // Make "Start time" label and field
        let $timeStartContainer = $('

');
        let $timeStartLabel = $('Start Time:').appendTo($timeStartContainer);
        this.$timeStartField = $('<input type="text" name="time-start" id="time-start" value="">').appendTo($timeStartContainer);
        this.$timeStartField.width(50);
        this.$timeStartField.css("font-family", "Courier, monospace");
        this.$timeStartField.addClass("ui-widget ui-widget-content ui-corner-all");
        this.$timeStartField.attr('title', "Start time (hh:mm:ss)");
        this.RegisterElement($timeStartContainer, this.$postToolbar, -3);

        // Make "End time" label and field
        let $timeEndContainer = $('

');
        let $timeEndLabel = $('End Time:').appendTo($timeEndContainer);
        this.$timeEndField = $('<input type="text" name="time-end" id="time-end" value="0">').appendTo($timeEndContainer);
        this.$timeEndField.width(50);
        this.$timeEndField.css("font-family", "Courier, monospace");
        this.$timeEndField.addClass("ui-widget ui-widget-content ui-corner-all");
        this.$timeEndField.attr('title', "End time (hh:mm:ss)");
        this.RegisterElement($timeEndContainer, this.$postToolbar, -2);

        // Make "Edit polygon" button
        let $editPolyButton = $("<button>Edit Polygon</button>").button({
            icon: "fa fa-pencil",
            showLabel: false
        }).click(() => {
            this.SetVisible(false);
            this.polyEditor.BeginEditing();
        });
        $editPolyButton.attr('title', "Edit polygon");
        this.RegisterElement($editPolyButton, this.$postToolbar, -1);

        // Make delete button
        this.$deleteButton = $("<button>Delete Annotation</button>").button({
            icon: "fa fa-bomb",
            showLabel: false
        });
        this.$deleteButton.css("margin-right", "15px");
        this.$deleteButton.attr('title', "Delete annotation");
        this.$deleteButton.click(() => {
            this.annotator.server.DeleteAnnotation(this.originalAnnotation, () => {
                this.Close();
            });
        });
        this.RegisterElement(this.$deleteButton, this.$postToolbar, 1, 'flex-end');

        // Make cancel button
        let $cancelButton = $("<button>Cancel Annotation Editing</button>").button({
            icons: {primary: 'fa fa-remove'},
            showLabel: false
        });
        $cancelButton.attr('title', "Cancel annotation editing");
        $cancelButton.addClass("annotator-cancel-button");
        $cancelButton.click(() => {
            this.Close();
        });
        this.RegisterElement($cancelButton, this.$postToolbar, 2, 'flex-end');

        // Make "Submit Annotation" button
        let $submitButton = $("<button>Submit Annotation</button>").button({
            icons: {primary: 'fa fa-check'},
            showLabel: false
        });
        $submitButton.attr('title', "Save annotation to database");
        $submitButton.addClass("annotator-confirm-button");
        $submitButton.click(() => {
            this.CommitAnnotationToServer(() => {
                this.Close();
            });
        });
        this.RegisterElement($submitButton, this.$postToolbar, 3, 'flex-end');

        // Make tags field
        this.$tagsField = $('<select class="form-control" multiple="multiple"></select>');
        this.$tagsField.width("100%");
        this.RegisterElement(this.$tagsField, this.$postToolbar2, -1);
        this.$tagsField.select2({
            tags: true,
            placeholder: "Tags",
            ajax: this.GetTagsQuery(),
            selectOnBlur: true,
            // Allow manually entered text in drop down.
            createTag: function (params) {
                return {
                    id: params.term,
                    text: params.term,
                    newOption: true
                }
            }
        });
        // Add custom class for bringing the dropdown to the front (fullscreen fix)
        this.$tagsField.data('select2').$dropdown.addClass("select2-dropdown-annotator");

        // Make annotation text field
        this.$textField = $('<textarea type="text" name="anno-text" id="anno-text" value="" placeholder="Text">');
        this.$textField.width("100%");
        this.$textField.addClass("ui-widget ui-widget-content ui-corner-all");
        this.$textField.attr('title', 'Annotation text');
        this.$textField.css("flex-grow", 2);
        this.RegisterElement(this.$textField, this.$postToolbar3, -1);

        //this.$container.hide();
    }

    RegisterElement($element, $container, order, justification = 'flex-start'){
        $element.css('order', order);
        $element.css('align-self', justification);
        // Sets grow [shrink] [basis]
        //$element.css('flex', '0 0 auto');
        $container.append($element);
    }

    SetVisible(isVisible, duration = 0){

        //console.log(isVisible + " " + duration);
        if(isVisible){
            this.$container.fadeTo(duration, 1.0);
        } else {
            this.$container.stop(true, true);
            this.$container.fadeTo(duration, 0.0);
        }
        this.isVisible = isVisible;

    }

    ToggleOpen(){

        if(this.open){
            this.Close();
        } else {
            this.Open();
        }

    }

    Open(){
        this.SetVisible(true);
        this.open = true;
        this.polyEditor.Done();
        // Disable autofading when the gui is visible
        this.annotator.player.SetAutoFade(false);
    }

    Close(){
        this.SetVisible(false);
        this.open = false;
        this.polyEditor.Done();
        // Re-enable autofading when the gui is hidden
        this.annotator.player.SetAutoFade(true);
        this.$container.trigger("OnGUIClosed");
    }

    ToggleVisible(){
        this.SetVisible(!this.isVisible, 0);
    }

    BeginEditing(annotation = null){
        // Open the GUI if it isn't already
        this.Open();

        //console.log(annotation);

        if(annotation == null){
            // Populate fields if no annotation is given
            this.editMode = false;
            this.$titleLabel.text("Create Annotation");
            this.$deleteButton.button("disable");

            console.log("Populated with template data");
            this.$timeStartField.val(GetFormattedTime(this.annotator.player.videoElement.currentTime));
            this.$timeEndField.val(GetFormattedTime(this.annotator.player.videoElement.duration));
            this.$textField.val("");
            this.$tagsField.val("").trigger("change");

            this.polyEditor.InitPoly();
        }
        else{
            // Populate the fields from the annotation
            this.editMode = true;
            this.$titleLabel.text("Edit Annotation");
            this.$deleteButton.button("enable");

            this.originalAnnotation = annotation;
            console.log(annotation);

            console.log("Populated from an existing annotation");
            this.$timeStartField.val(GetFormattedTime(annotation.data.beginTime / 1000));
            this.$timeEndField.val(GetFormattedTime(annotation.data.endTime / 1000));
            this.$textField.val(annotation.data.text);
            this.$tagsField.val("").trigger("change");

            for(let tag of annotation.data.tags){
                this.$tagsField.append("<option value='"+tag+"' selected>"+tag+"</option>");
                this.$tagsField.trigger("change");
            }

            this.polyEditor.InitPoly(annotation.data["pointsArray"]);

        }
        //this.newPolyPoints = [];
        //this.breadcrumbs = [];
    }

    ParseTags(){

    }

    CommitAnnotationToServer(callback){
        if(this.editMode){
            console.log("Sending edited annotation to server...");
            this.annotator.server.EditAnnotation(callback);
        }
        else{
            console.log("Sending new annotation to server...");
            this.annotator.server.PostAnnotation(callback);
        }
    }

    GetAnnotationObject(){

        // Extract tag text from tags field
        let tags = this.$tagsField.select2("data").map((item) => { return item.text; });

        let obj = {}
        obj.data = {
            text: this.$textField.val(),
            beginTime: Math.round(GetSecondsFromHMS(this.$timeStartField.val()) * 1000),
            endTime: Math.round(GetSecondsFromHMS(this.$timeEndField.val()) * 1000),
            pointsArray: this.polyEditor.GetJSON(),
            tags: tags
        }

        if (this.originalAnnotation != null){
            obj.metadata = this.originalAnnotation.metadata;
        }
        else{
            obj.metadata = {
                //id: "",
                location: this.annotator.player.videoElement.currentSrc
                //title: ""
            }

        }

        return obj;
    }

}

export { AnnotationGUI };<commit_msg>Reorganize<commit_after>import { GetFormattedTime, GetSecondsFromHMS } from "../../utils/time.js";
import { PolygonEditor } from "./polygon-editor.js";

class AnnotationGUI {

    constructor(annotator){
        this.annotator = annotator;

        this.Create();

        this.open = false;

        //Hide the container
        this.isVisible = false;
        this.$container.hide();

        this.polyEditor = new PolygonEditor(this.annotator);

        this.annotator.$container.on("OnPolygonEditingEnded", () => {
            this.SetVisible(true);
        });

    }

    Create(){
        this.$container = $("

").appendTo(this.annotator.player.$container);
        this.$postToolbar = $("

").appendTo(this.$container);
        this.$postToolbar.css("margin-bottom", "5px");
        this.$postToolbar2 = $("

").appendTo(this.$container);
        this.$postToolbar2.css("margin-bottom", "5px");
        this.$postToolbar3 = $("

").appendTo(this.$container);

        this.$postToolbar.append($("

").css("flex-grow", 1).css("order", 0));

        // Make title div
        let $titleDiv = $("

");
        this.$titleLabel = $("
Create Annotation
").appendTo($titleDiv);
        this.RegisterElement($titleDiv, this.$postToolbar, -10);

        // Make "Start time" label and field
        let $timeStartContainer = $('

');
        let $timeStartLabel = $('Start Time:').appendTo($timeStartContainer);
        this.$timeStartField = $('<input type="text" name="time-start" id="time-start" value="">').appendTo($timeStartContainer);
        this.$timeStartField.width(50);
        this.$timeStartField.css("font-family", "Courier, monospace");
        this.$timeStartField.addClass("ui-widget ui-widget-content ui-corner-all");
        this.$timeStartField.attr('title', "Start time (hh:mm:ss)");
        this.RegisterElement($timeStartContainer, this.$postToolbar, -3);

        // Make "End time" label and field
        let $timeEndContainer = $('

');
        let $timeEndLabel = $('End Time:').appendTo($timeEndContainer);
        this.$timeEndField = $('<input type="text" name="time-end" id="time-end" value="0">').appendTo($timeEndContainer);
        this.$timeEndField.width(50);
        this.$timeEndField.css("font-family", "Courier, monospace");
        this.$timeEndField.addClass("ui-widget ui-widget-content ui-corner-all");
        this.$timeEndField.attr('title', "End time (hh:mm:ss)");
        this.RegisterElement($timeEndContainer, this.$postToolbar, -2);

        // Make "Edit polygon" button
        let $editPolyButton = $("<button>Edit Polygon</button>").button({
            icon: "fa fa-pencil",
            showLabel: false
        }).click(() => {
            this.SetVisible(false);
            this.polyEditor.BeginEditing();
        });
        $editPolyButton.attr('title', "Edit polygon");
        this.RegisterElement($editPolyButton, this.$postToolbar, -1);

        // Make delete button
        this.$deleteButton = $("<button>Delete Annotation</button>").button({
            icon: "fa fa-bomb",
            showLabel: false
        });
        this.$deleteButton.css("margin-right", "15px");
        this.$deleteButton.attr('title', "Delete annotation");
        this.$deleteButton.click(() => {
            this.annotator.server.DeleteAnnotation(this.originalAnnotation, () => {
                this.Close();
            });
        });
        this.RegisterElement(this.$deleteButton, this.$postToolbar, 1, 'flex-end');

        // Make cancel button
        let $cancelButton = $("<button>Cancel Annotation Editing</button>").button({
            icons: {primary: 'fa fa-remove'},
            showLabel: false
        });
        $cancelButton.attr('title', "Cancel annotation editing");
        $cancelButton.addClass("annotator-cancel-button");
        $cancelButton.click(() => {
            this.Close();
        });
        this.RegisterElement($cancelButton, this.$postToolbar, 2, 'flex-end');

        // Make "Submit Annotation" button
        let $submitButton = $("<button>Submit Annotation</button>").button({
            icons: {primary: 'fa fa-check'},
            showLabel: false
        });
        $submitButton.attr('title', "Save annotation to database");
        $submitButton.addClass("annotator-confirm-button");
        $submitButton.click(() => {
            this.CommitAnnotationToServer(() => {
                this.Close();
            });
        });
        this.RegisterElement($submitButton, this.$postToolbar, 3, 'flex-end');

        // Make tags field
        this.$tagsField = $('<select class="form-control" multiple="multiple"></select>');
        this.$tagsField.width("100%");
        this.RegisterElement(this.$tagsField, this.$postToolbar2, -1);
        this.$tagsField.select2({
            tags: true,
            placeholder: "Tags",
            ajax: this.GetTagsQuery(),
            selectOnBlur: true,
            // Allow manually entered text in drop down.
            createTag: function (params) {
                return {
                    id: params.term,
                    text: params.term,
                    newOption: true
                }
            }
        });
        // Add custom class for bringing the dropdown to the front (fullscreen fix)
        this.$tagsField.data('select2').$dropdown.addClass("select2-dropdown-annotator");

        // Make annotation text field
        this.$textField = $('<textarea type="text" name="anno-text" id="anno-text" value="" placeholder="Text">');
        this.$textField.width("100%");
        this.$textField.addClass("ui-widget ui-widget-content ui-corner-all");
        this.$textField.attr('title', 'Annotation text');
        this.$textField.css("flex-grow", 2);
        this.RegisterElement(this.$textField, this.$postToolbar3, -1);

        //this.$container.hide();
    }

    RegisterElement($element, $container, order, justification = 'flex-start'){
        $element.css('order', order);
        $element.css('align-self', justification);
        // Sets grow [shrink] [basis]
        //$element.css('flex', '0 0 auto');
        $container.append($element);
    }

    SetVisible(isVisible, duration = 0){

        //console.log(isVisible + " " + duration);
        if(isVisible){
            this.$container.fadeTo(duration, 1.0);
        } else {
            this.$container.stop(true, true);
            this.$container.fadeTo(duration, 0.0);
        }
        this.isVisible = isVisible;

    }

    ToggleOpen(){

        if(this.open){
            this.Close();
        } else {
            this.Open();
        }

    }

    Open(){
        this.SetVisible(true);
        this.open = true;
        this.polyEditor.Done();
        // Disable autofading when the gui is visible
        this.annotator.player.SetAutoFade(false);
    }

    Close(){
        this.SetVisible(false);
        this.open = false;
        this.polyEditor.Done();
        // Re-enable autofading when the gui is hidden
        this.annotator.player.SetAutoFade(true);
        this.$container.trigger("OnGUIClosed");
    }

    ToggleVisible(){
        this.SetVisible(!this.isVisible, 0);
    }

    BeginEditing(annotation = null){
        // Open the GUI if it isn't already
        this.Open();

        //console.log(annotation);

        if(annotation == null){
            // Populate fields if no annotation is given
            this.editMode = false;
            this.$titleLabel.text("Create Annotation");
            this.$deleteButton.button("disable");

            console.log("Populated with template data");
            this.$timeStartField.val(GetFormattedTime(this.annotator.player.videoElement.currentTime));
            this.$timeEndField.val(GetFormattedTime(this.annotator.player.videoElement.duration));
            this.$textField.val("");
            this.$tagsField.val("").trigger("change");

            this.polyEditor.InitPoly();
        }
        else{
            // Populate the fields from the annotation
            this.editMode = true;
            this.$titleLabel.text("Edit Annotation");
            this.$deleteButton.button("enable");

            this.originalAnnotation = annotation;
            console.log(annotation);

            console.log("Populated from an existing annotation");
            this.$timeStartField.val(GetFormattedTime(annotation.data.beginTime / 1000));
            this.$timeEndField.val(GetFormattedTime(annotation.data.endTime / 1000));
            this.$textField.val(annotation.data.text);
            this.$tagsField.val("").trigger("change");

            for(let tag of annotation.data.tags){
                this.$tagsField.append("<option value='"+tag+"' selected>"+tag+"</option>");
                this.$tagsField.trigger("change");
            }

            this.polyEditor.InitPoly(annotation.data["pointsArray"]);

        }
        //this.newPolyPoints = [];
        //this.breadcrumbs = [];
    }

    CommitAnnotationToServer(callback){
        if(this.editMode){
            console.log("Sending edited annotation to server...");
            this.annotator.server.EditAnnotation(callback);
        }
        else{
            console.log("Sending new annotation to server...");
            this.annotator.server.PostAnnotation(callback);
        }
    }

    GetAnnotationObject(){

        // Extract tag text from tags field
        let tags = this.$tagsField.select2("data").map((item) => { return item.text; });

        let obj = {}
        obj.data = {
            text: this.$textField.val(),
            beginTime: Math.round(GetSecondsFromHMS(this.$timeStartField.val()) * 1000),
            endTime: Math.round(GetSecondsFromHMS(this.$timeEndField.val()) * 1000),
            pointsArray: this.polyEditor.GetJSON(),
            tags: tags
        }

        if (this.originalAnnotation != null){
            obj.metadata = this.originalAnnotation.metadata;
        }
        else{
            obj.metadata = {
                //id: "",
                location: this.annotator.player.videoElement.currentSrc
                //title: ""
            }

        }

        return obj;
    }

    GetTagsQuery(){
        return {
            url: this.annotator.tagsURL,
            dataType: 'json',
            delay: 250,
            cache: true,
            processResults: function (data) {
                // Parse the labels into the format expected by Select2
                let tags = [];
                let index = 1;
                for(let term of data["terms"]){
                    tags.push({
                        id: index,
                        text: term["rdfs:label"]
                    });
                    index++;
                }
                return {
                    results: tags
                };
            }
        }
    }

}

export { AnnotationGUI };<|endoftext|>