<commit_before>/*
        Utlimate Mega Gulpfile
        Jay Salvat
 */

(function () {
    "use strict";

    var pkg     = require("./package.json"),
        del     = require("del"),
        yargs   = require("yargs"),
        exec    = require("exec"),
        fs      = require("fs"),
        gulp    = require("gulp"),
        bump    = require("gulp-bump"),
        header  = require("gulp-header"),
        qunit   = require("gulp-qunit"),
        uglify  = require("gulp-uglifyjs"),
        jshint  = require('gulp-jshint'),
        gutil   = require("gulp-util"),
        zip     = require("gulp-zip"),
        replace = require("gulp-replace"),
        gsync   = require("gulp-sync"),
        sync    = gsync(gulp).sync;

    var version = yargs.argv.type || "patch";

    var settings = {
        banner: {
            content: [
                '/*! ----------------------------------------------------------------------------',
                ' *  <%= pkg.description %>',
                ' *  v<%= pkg.version %> released <%= datetime %>',
                ' *  <%= pkg.homepage %>',
                ' *  Copyright (c) 2010-<%= year %>, Jay Salvat',
                ' *  http://jaysalvat.com/',
                ' *  ----------------------------------------------------------------------------',
                ' *  ccv.js and cascade.js',
                ' *  Copyright (c) 2010-<%= year %>, Liu Liu',
                ' *  http://liuliu.me/',
                ' *  ----------------------------------------------------------------------------',
                ' */',
                '',
            ].join("\n"),
            vars: {
                pkg: pkg,
                datetime: gutil.date("yyyy-mm-dd HH:MM"),
                year: gutil.date("yyyy")
            }
        },
        files: {
            in: [
                './src/cascade.js',
                './src/ccv.js',
                './src/jquery.facedetection.js'
            ],
            out: 'jquery.facedetection'
        },
        enclose: {
            '(typeof jQuery !== "function") ? { fn: {} } : jQuery': '$' // jQuery hack for Worker mode
        }
    };

    var getPackageJson = function () {
        return JSON.parse(fs.readFileSync('./package.json'));
    };

    gulp.task("clean", function (cb) {
        return del([ "./dist" ], cb);
    });

    gulp.task("tmp-clean", function (cb) {
        return del([ "./tmp" ], cb);
    });

    gulp.task("tmp-create", function (cb) {
        return exec("mkdir -p ./tmp", cb);
    });

    gulp.task("tmp-copy", [ "tmp-create" ], function () {
        return gulp.src("./dist/*")
            .pipe(gulp.dest("./tmp"));
    });

    gulp.task("zip", [ "tmp-create" ], function () {
        var filename = settings.files.out + ".zip";

        return gulp.src("./dist/*")
            .pipe(zip(filename))
            .pipe(gulp.dest("./tmp"));
    });

    gulp.task("fail-if-dirty", function (cb) {
        return exec('git diff-index HEAD --', function (err, output) { // err, output, code
            if (err) {
                return cb(err);
            }
            if (output) {
                return cb("Repository is dirty");
            }
            return cb();
        });
    });

    gulp.task("fail-if-not-master", function (cb) {
        exec('git symbolic-ref -q HEAD', function (err, output) { // err, output, code
            if (err) {
                return cb(err);
            }
            if (!/refs\/heads\/master/.test(output)) {
                return cb("Branch is not Master");
            }
            return cb();
        });
    });

    gulp.task("git-tag", function (cb) {
        var message = "v" + getPackageJson().version;

        return exec('git tag ' + message, cb);
    });

    gulp.task("git-add", function (cb) {
        return exec('git add -A', cb);
    });

    gulp.task("git-commit", [ "git-add" ], function (cb) {
        var message = "Build v" + getPackageJson().version;

        return exec('git commit -m "' + message + '"', cb);
    });

    gulp.task("git-pull", function (cb) {
        return exec('git pull origin master', function (err, output, code) {
            if (code !== 0) {
                return cb(err + output);
            }
            return cb();
        });
    });

    gulp.task("git-push", [ "git-commit" ], function (cb) {
        return exec('git push origin master --tags', function (err, output, code) {
            if (code !== 0) {
                return cb(err + output);
            }
            return cb();
        });
    });

    gulp.task("meta", [ "tmp-create" ], function (cb) {
        var  metadata = {
                date: gutil.date("yyyy-mm-dd HH:MM"),
                version: "v" + getPackageJson().version
            },
            json = JSON.stringify(metadata, null, 4);

        fs.writeFileSync("tmp/metadata.json", json);
        fs.writeFileSync("tmp/metadata.js", "__metadata(" + json + ");");

        return cb();
    });

    gulp.task("bump", function () {
        return gulp.src([ "package.json", "bower.json", "facedetection.jquery.json" ])
            .pipe(bump({
                type: version
            }))
            .pipe(gulp.dest("."));
    });

    gulp.task("license", function () {
        return gulp.src([ "./LICENSE.md", "./README.md" ])
            .pipe(replace(/( 2010-)(\d{4})/g, "$1" + gutil.date("yyyy")))
            .pipe(gulp.dest("."));
    });

    gulp.task('lint', function() {
        return gulp.src('./src/jquery.facedetection.js')
            .pipe(jshint())
            .pipe(jshint.reporter('default'));
    });

    gulp.task("test-dev", function () {
        return gulp.src("./tests/test-runner.html")
            .pipe(qunit());
    });

    gulp.task("test-dist", function () {
        return gulp.src("./tests/test-runner-dist.html")
            .pipe(qunit());
    });

    gulp.task("uglify", function () {
        settings.banner.vars.pkg = getPackageJson();

        return gulp.src(settings.files.in)
            .pipe(uglify(settings.files.out + '.min.js', {
                enclose: settings.enclose,
                compress: {
                    warnings: false
                },
                mangle: true,
                outSourceMap: true
            }))
            .pipe(gulp.dest('./dist/'));
    });

    gulp.task("beautify", function () {
        return gulp.src(settings.files.in)
            .pipe(uglify(settings.files.out + '.js', {
                enclose: settings.enclose,
                compress: {
                    warnings: false
                },
                output: {
                    beautify: true
                },
                mangle: false
            }))
            .pipe(gulp.dest('./dist/'));
    });

    gulp.task("header", function () {
        settings.banner.vars.pkg = getPackageJson();

        return gulp.src('./dist/*.js')
            .pipe(header(settings.banner.content, settings.banner.vars ))
            .pipe(gulp.dest('./dist/'));
    });

    gulp.task("gh-pages", function (cb) {
        version = getPackageJson().version;

        exec([  'git checkout gh-pages',
                'rm -rf releases/' + version,
                'mkdir -p releases/' + version,
                'cp -r tmp/* releases/' + version,
                'git add -A releases/' + version,
                'rm -rf releases/latest',
                'mkdir -p releases/latest',
                'cp -r tmp/* releases/latest',
                'git add -A releases/latest',
                'git commit -m "Publish release v' + version + '."',
                'git push origin gh-pages',
                'git checkout -'
            ].join(" && "),
            function (err, output, code) {
                if (code !== 0) {
                    return cb(err + output);
                }
                return cb();
            }
        );
    });

    gulp.task("test", sync([
        "lint",
        "test-dev"
    ],
    "building"));

    gulp.task("build", sync([
        "lint",
        "test-dev",
        "clean",
        "beautify",
        "uglify",
        "header",
        "test-dist"
    ],
    "building"));

    gulp.task("release", sync([
      [ "fail-if-not-master", "fail-if-dirty" ],
        "git-pull",
        "lint",
        "test-dev",
        "bump",
        "license",
        "clean",
        "beautify",
        "uglify",
        "header",
        "test-dist",
        "git-add",
        "git-commit",
        "git-tag",
        "git-push",
        "publish"
    ],
    "releasing"));

    gulp.task("publish", sync([
      [ "fail-if-not-master", "fail-if-dirty" ],
        "tmp-create",
        "tmp-copy",
        "meta",
        "zip",
        "gh-pages",
        "tmp-clean"
    ],
    "publising"));
})();

/*

NOTES
=====

Gh-pages creation
-----------------

git checkout --orphan gh-pages
git rm -rf .
rm -fr
echo "Welcome" > index.html
git add index.html
git commit -a -m "First commit"
git push origin gh-pages
git checkout -

*/
<commit_msg>Test publish gulp task<commit_after>/*  Utlimate Jay Mega Gulpfile */

(function () {
    "use strict";

    var pkg     = require("./package.json"),
        del     = require("del"),
        yargs   = require("yargs"),
        exec    = require("exec"),
        fs      = require("fs"),
        gulp    = require("gulp"),
        bump    = require("gulp-bump"),
        header  = require("gulp-header"),
        qunit   = require("gulp-qunit"),
        uglify  = require("gulp-uglifyjs"),
        jshint  = require('gulp-jshint'),
        gutil   = require("gulp-util"),
        zip     = require("gulp-zip"),
        replace = require("gulp-replace"),
        gsync   = require("gulp-sync"),
        sync    = gsync(gulp).sync;

    var version = yargs.argv.type || "patch";

    var settings = {
        banner: {
            content: [
                '/*! ----------------------------------------------------------------------------',
                ' *  <%= pkg.description %>',
                ' *  v<%= pkg.version %> released <%= datetime %>',
                ' *  <%= pkg.homepage %>',
                ' *  Copyright (c) 2010-<%= year %>, Jay Salvat',
                ' *  http://jaysalvat.com/',
                ' *  ----------------------------------------------------------------------------',
                ' *  ccv.js and cascade.js',
                ' *  Copyright (c) 2010-<%= year %>, Liu Liu',
                ' *  http://liuliu.me/',
                ' *  ----------------------------------------------------------------------------',
                ' */',
                '',
            ].join("\n"),
            vars: {
                pkg: pkg,
                datetime: gutil.date("yyyy-mm-dd HH:MM"),
                year: gutil.date("yyyy")
            }
        },
        files: {
            in: [
                './src/cascade.js',
                './src/ccv.js',
                './src/jquery.facedetection.js'
            ],
            out: 'jquery.facedetection'
        },
        enclose: {
            '(typeof jQuery !== "function") ? { fn: {} } : jQuery': '$' // jQuery hack for Worker mode
        }
    };

    var getPackageJson = function () {
        return JSON.parse(fs.readFileSync('./package.json'));
    };

    gulp.task("clean", function (cb) {
        return del([ "./dist" ], cb);
    });

    gulp.task("tmp-clean", function (cb) {
        return del([ "./tmp" ], cb);
    });

    gulp.task("tmp-create", function (cb) {
        return exec("mkdir -p ./tmp", cb);
    });

    gulp.task("tmp-copy", [ "tmp-create" ], function () {
        return gulp.src("./dist/*")
            .pipe(gulp.dest("./tmp"));
    });

    gulp.task("zip", [ "tmp-create" ], function () {
        var filename = settings.files.out + ".zip";

        return gulp.src("./dist/*")
            .pipe(zip(filename))
            .pipe(gulp.dest("./tmp"));
    });

    gulp.task("fail-if-dirty", function (cb) {
        return exec('git diff-index HEAD --', function (err, output) { // err, output, code
            if (err) {
                return cb(err);
            }
            if (output) {
                return cb("Repository is dirty");
            }
            return cb();
        });
    });

    gulp.task("fail-if-not-master", function (cb) {
        exec('git symbolic-ref -q HEAD', function (err, output) { // err, output, code
            if (err) {
                return cb(err);
            }
            if (!/refs\/heads\/master/.test(output)) {
                return cb("Branch is not Master");
            }
            return cb();
        });
    });

    gulp.task("git-tag", function (cb) {
        var message = "v" + getPackageJson().version;

        return exec('git tag ' + message, cb);
    });

    gulp.task("git-add", function (cb) {
        return exec('git add -A', cb);
    });

    gulp.task("git-commit", [ "git-add" ], function (cb) {
        var message = "Build v" + getPackageJson().version;

        return exec('git commit -m "' + message + '"', cb);
    });

    gulp.task("git-pull", function (cb) {
        return exec('git pull origin master', function (err, output, code) {
            if (code !== 0) {
                return cb(err + output);
            }
            return cb();
        });
    });

    gulp.task("git-push", [ "git-commit" ], function (cb) {
        return exec('git push origin master --tags', function (err, output, code) {
            if (code !== 0) {
                return cb(err + output);
            }
            return cb();
        });
    });

    gulp.task("meta", [ "tmp-create" ], function (cb) {
        var  metadata = {
                date: gutil.date("yyyy-mm-dd HH:MM"),
                version: "v" + getPackageJson().version
            },
            json = JSON.stringify(metadata, null, 4);

        fs.writeFileSync("tmp/metadata.json", json);
        fs.writeFileSync("tmp/metadata.js", "__metadata(" + json + ");");

        return cb();
    });

    gulp.task("bump", function () {
        return gulp.src([ "package.json", "bower.json", "facedetection.jquery.json" ])
            .pipe(bump({
                type: version
            }))
            .pipe(gulp.dest("."));
    });

    gulp.task("license", function () {
        return gulp.src([ "./LICENSE.md", "./README.md" ])
            .pipe(replace(/( 2010-)(\d{4})/g, "$1" + gutil.date("yyyy")))
            .pipe(gulp.dest("."));
    });

    gulp.task('lint', function() {
        return gulp.src('./src/jquery.facedetection.js')
            .pipe(jshint())
            .pipe(jshint.reporter('default'));
    });

    gulp.task("test-dev", function () {
        return gulp.src("./tests/test-runner.html")
            .pipe(qunit());
    });

    gulp.task("test-dist", function () {
        return gulp.src("./tests/test-runner-dist.html")
            .pipe(qunit());
    });

    gulp.task("uglify", function () {
        settings.banner.vars.pkg = getPackageJson();

        return gulp.src(settings.files.in)
            .pipe(uglify(settings.files.out + '.min.js', {
                enclose: settings.enclose,
                compress: {
                    warnings: false
                },
                mangle: true,
                outSourceMap: true
            }))
            .pipe(gulp.dest('./dist/'));
    });

    gulp.task("beautify", function () {
        return gulp.src(settings.files.in)
            .pipe(uglify(settings.files.out + '.js', {
                enclose: settings.enclose,
                compress: {
                    warnings: false
                },
                output: {
                    beautify: true
                },
                mangle: false
            }))
            .pipe(gulp.dest('./dist/'));
    });

    gulp.task("header", function () {
        settings.banner.vars.pkg = getPackageJson();

        return gulp.src('./dist/*.js')
            .pipe(header(settings.banner.content, settings.banner.vars ))
            .pipe(gulp.dest('./dist/'));
    });

    gulp.task("gh-pages", function (cb) {
        version = getPackageJson().version;

        exec([  'git checkout gh-pages',
                'rm -rf releases/' + version,
                'mkdir -p releases/' + version,
                'cp -r tmp/* releases/' + version,
                'git add -A releases/' + version,
                'rm -rf releases/latest',
                'mkdir -p releases/latest',
                'cp -r tmp/* releases/latest',
                'git add -A releases/latest',
                'git commit -m "Publish release v' + version + '."',
                // 'git push origin gh-pages',
                'git checkout -'
            ].join(" && "),
            function (err, output, code) {
                if (code !== 0) {
                    return cb(err + output);
                }
                return cb();
            }
        );
    });

    gulp.task("test", sync([
        "lint",
        "test-dev"
    ],
    "building"));

    gulp.task("build", sync([
        "lint",
        "test-dev",
        "clean",
        "beautify",
        "uglify",
        "header",
        "test-dist"
    ],
    "building"));

    gulp.task("release", sync([
      [ "fail-if-not-master", "fail-if-dirty" ],
        "git-pull",
        "lint",
        "test-dev",
        "bump",
        "license",
        "clean",
        "beautify",
        "uglify",
        "header",
        "test-dist",
        "git-add",
        "git-commit",
        "git-tag",
        "git-push",
        "publish"
    ],
    "releasing"));

    gulp.task("publish", sync([
      [ "fail-if-not-master", "fail-if-dirty" ],
        "tmp-create",
        "tmp-copy",
        "meta",
        "zip",
        "gh-pages",
        "tmp-clean"
    ],
    "publising"));
})();

/*

NOTES
=====

Gh-pages creation
-----------------

git checkout --orphan gh-pages
git rm -rf .
rm -fr
echo "Welcome" > index.html
git add index.html
git commit -a -m "First commit"
git push origin gh-pages
git checkout -

*/
<|endoftext|>


<commit_before>/* ----------
require
---------- */
var bigwheel = require('bigwheel');

/* ----------
create our framework instance
see https://github.com/bigwheel-framework/documentation/blob/master/quickstart.md#bigwheel-quick-start
---------- */
var framework = bigwheel(function() {
	return {
		routes: require('./routes')
	};
});

module.exports = framework;<commit_msg>Update framework.js to support initSection<commit_after>/* ----------
require
---------- */
var bigwheel = require('bigwheel');

/* ----------
create our framework instance
see https://github.com/bigwheel-framework/documentation/blob/master/quickstart.md#bigwheel-quick-start
---------- */
var framework = bigwheel(function() {
	return {
		routes: require('./routes')
	};
});

// if you need a preloader (initSection)
// https://github.com/bigwheel-framework/documentation/blob/master/routes-special.md#initsection
// var framework = bigwheel(function(done) {
// 	done({
// 		overlap: false,
// 		initSection: require('./sections/preloader'),
// 		routes: require('./routes')
// 	});
// });

module.exports = framework;
<|endoftext|>


<commit_before>import React from 'react';
import { render } from 'react-dom';
import endpoint from './endpoint';
import Logo from './react-components/logo.jsx';
import Footer from './react-components/footer.jsx';
import { oauthLogin } from '../common/appId';
import { isEuCountry, showHideEuElements } from '../common/footer-checks';
import GTM from '../common/gtm';
import { load as loadLang, showBanner } from '../common/lang';
import { moveToDeriv } from '../common/utils/utility';
import { get as getStorage, set as setStorage, remove, getTokenList } from '../common/utils/storageManager';
import { createUrl, parseQueryString, serialize } from '../common/utils/tools';
import '../common/binary-ui/dropdown';
import BotLanding from './react-components/bot-landing';
import BinaryLanding from './react-components/binary-landing';

const today = new Date().getTime();
// eslint-disable-next-line one-var
const oneMilliSec = 1000;
const sevenDays = 7;
const oneMinute = 60;
const oneDay = 24;

export const elements = ['#notification-banner', '#main', '#footer', '#header', '#topbar'];
// eslint-disable-next-line one-var
export const bannerToken = getStorage('setDueDateForBanner');

// eslint-disable-next-line arrow-body-style
export const expirationDate = () => {
    return today + oneMilliSec * oneMinute * oneMinute * oneDay * sevenDays;
};

export const calcSetTimeoutValueBanner = expirationDate() - new Date().getTime();

// eslint-disable-next-line import/no-mutable-exports
export let timerForBanner;

const checkifBotRunning = () => {
    if (document.getElementById('runButton').style.display === 'none') {
        return true;
    }
    return false;
};

export const setTimeOutBanner = route => {
    let bannerDisplayed;
    const qs = parseQueryString();
    // eslint-disable-next-line consistent-return
    timerForBanner = setTimeout(() => {
        if (
            (route === 'index' && !!bannerDisplayed === false) ||
            (route === 'views' && checkifBotRunning() === false)
        ) {
            const getDefaultPath = window.location.href.replace('/bot.html', serialize(qs));
            window.location.replace(getDefaultPath);
            renderBanner();
        } else if (
            (route === 'index' && !!bannerDisplayed === true) ||
            (route === 'views' && checkifBotRunning() === true)
        ) {
            remove('setDueDateForBanner');
            setStorage('setDueDateForBanner', expirationDate());
            return false;
        }
    }, calcSetTimeoutValueBanner);
};

const renderBanner = () => {
    let Component, dynamicVar;
    if (window.location.pathname === '/movetoderiv.html') {
        Component = <BinaryLanding />;
        dynamicVar = 'movetoderiv';
    } else {
        Component = <BotLanding />;
        dynamicVar = 'bot-landing';
    }
    render(Component, document.getElementById(dynamicVar));
    // setStorage('setDueDateForBanner', expirationDate());
    elements.map(elem => document.querySelector(elem).classList.add('hidden'));
    document.getElementById(dynamicVar).classList.remove('hidden');
    document.getElementById('bot-main').classList.remove('hidden');
    document.getElementById('topbar').classList.remove('hidden');
    $('.barspinner').hide();
};

// eslint-disable-next-line consistent-return
const renderElements = () => {
    // eslint-disable-next-line one-var, no-unused-vars
    let Component, dynamicVar;
    if (window.location.pathname === '/movetoderiv.html') {
        Component = <BinaryLanding />;
        dynamicVar = 'movetoderiv';
    } else {
        Component = <BotLanding />;
        dynamicVar = 'bot-landing';
    }
    setTimeOutBanner('index');
    $('.barspinner').show();

    if (!bannerToken) {
        if (window.location.href.indexOf('bot.html') === -1) {
            renderBanner();
        }
    } else {
        if (today > bannerToken) {
            remove('setDueDateForBanner');
            renderBanner();
            return false;
        }
        if (window.location.href.indexOf('bot.html') === -1) {
            render(<Logo />, document.getElementById('binary-logo'));
            render(<Footer />, document.getElementById('footer'));
            isEuCountry().then(isEu => showHideEuElements(isEu));
            showBanner();
            $('#shop-url').attr(
                'href',
                createUrl({ subdomain: 'shop', path: 'collections/strategies', isNonBotPage: true })
            );
            elements.map(elem => document.querySelector(elem).classList.remove('hidden'));
            document.getElementById(dynamicVar).classList.add('hidden');
        }
        document.getElementById('bot-main').classList.remove('hidden');
        setTimeout(() => {
            $('.barspinner').hide();
        }, 2000);
    }
};

const loginCheck = () => {
    if (endpoint()) return;
    moveToDeriv();
    if (window.location.href.indexOf('bot.html') === -1) {
        loadLang();
    }
    $('.show-on-load').show();
    if (bannerToken) {
        if (getTokenList().length) {
            if (!window.location.pathname.includes('/bot.html')) {
                window.location.pathname = `${window.location.pathname.replace(/\/+$/, '')}/bot.html`;
            }
            document.getElementById('bot-main').classList.remove('hidden');
        } else {
            oauthLogin(() => {
                $('.barspinner').hide();
                renderElements();
                GTM.init();
            });
        }
    } else {
        setTimeout(() => {
            renderBanner();
        }, 0);
    }
};

loginCheck();
<commit_msg>change the time to 10 min for testing<commit_after>import React from 'react';
import { render } from 'react-dom';
import endpoint from './endpoint';
import Logo from './react-components/logo.jsx';
import Footer from './react-components/footer.jsx';
import { oauthLogin } from '../common/appId';
import { isEuCountry, showHideEuElements } from '../common/footer-checks';
import GTM from '../common/gtm';
import { load as loadLang, showBanner } from '../common/lang';
import { moveToDeriv } from '../common/utils/utility';
import { get as getStorage, set as setStorage, remove, getTokenList } from '../common/utils/storageManager';
import { createUrl, parseQueryString, serialize } from '../common/utils/tools';
import '../common/binary-ui/dropdown';
import BotLanding from './react-components/bot-landing';
import BinaryLanding from './react-components/binary-landing';

const today = new Date().getTime();
// eslint-disable-next-line one-var
const oneMilliSec = 1000;
// will uncomment before production release
// const sevenDays = 7;
// const oneMinute = 60;
// const oneDay = 24;

export const elements = ['#notification-banner', '#main', '#footer', '#header', '#topbar'];
// eslint-disable-next-line one-var
export const bannerToken = getStorage('setDueDateForBanner');

// eslint-disable-next-line arrow-body-style
export const expirationDate = () => {
    return today + oneMilliSec * 600;
};

export const calcSetTimeoutValueBanner = expirationDate() - new Date().getTime();

// eslint-disable-next-line import/no-mutable-exports
export let timerForBanner;

const checkifBotRunning = () => {
    if (document.getElementById('runButton').style.display === 'none') {
        return true;
    }
    return false;
};

export const setTimeOutBanner = route => {
    let bannerDisplayed;
    const qs = parseQueryString();
    // eslint-disable-next-line consistent-return
    timerForBanner = setTimeout(() => {
        if (
            (route === 'index' && !!bannerDisplayed === false) ||
            (route === 'views' && checkifBotRunning() === false)
        ) {
            const getDefaultPath = window.location.href.replace('/bot.html', serialize(qs));
            window.location.replace(getDefaultPath);
            renderBanner();
        } else if (
            (route === 'index' && !!bannerDisplayed === true) ||
            (route === 'views' && checkifBotRunning() === true)
        ) {
            remove('setDueDateForBanner');
            setStorage('setDueDateForBanner', expirationDate());
            return false;
        }
    }, calcSetTimeoutValueBanner);
};

const renderBanner = () => {
    let Component, dynamicVar;
    if (window.location.pathname === '/movetoderiv.html') {
        Component = <BinaryLanding />;
        dynamicVar = 'movetoderiv';
    } else {
        Component = <BotLanding />;
        dynamicVar = 'bot-landing';
    }
    render(Component, document.getElementById(dynamicVar));
    // setStorage('setDueDateForBanner', expirationDate());
    elements.map(elem => document.querySelector(elem).classList.add('hidden'));
    document.getElementById(dynamicVar).classList.remove('hidden');
    document.getElementById('bot-main').classList.remove('hidden');
    document.getElementById('topbar').classList.remove('hidden');
    $('.barspinner').hide();
};

// eslint-disable-next-line consistent-return
const renderElements = () => {
    // eslint-disable-next-line one-var, no-unused-vars
    let Component, dynamicVar;
    if (window.location.pathname === '/movetoderiv.html') {
        Component = <BinaryLanding />;
        dynamicVar = 'movetoderiv';
    } else {
        Component = <BotLanding />;
        dynamicVar = 'bot-landing';
    }
    setTimeOutBanner('index');
    $('.barspinner').show();

    if (!bannerToken) {
        if (window.location.href.indexOf('bot.html') === -1) {
            renderBanner();
        }
    } else {
        if (today > bannerToken) {
            remove('setDueDateForBanner');
            renderBanner();
            return false;
        }
        if (window.location.href.indexOf('bot.html') === -1) {
            render(<Logo />, document.getElementById('binary-logo'));
            render(<Footer />, document.getElementById('footer'));
            isEuCountry().then(isEu => showHideEuElements(isEu));
            showBanner();
            $('#shop-url').attr(
                'href',
                createUrl({ subdomain: 'shop', path: 'collections/strategies', isNonBotPage: true })
            );
            elements.map(elem => document.querySelector(elem).classList.remove('hidden'));
            document.getElementById(dynamicVar).classList.add('hidden');
        }
        document.getElementById('bot-main').classList.remove('hidden');
        setTimeout(() => {
            $('.barspinner').hide();
        }, 2000);
    }
};

const loginCheck = () => {
    if (endpoint()) return;
    moveToDeriv();
    if (window.location.href.indexOf('bot.html') === -1) {
        loadLang();
    }
    $('.show-on-load').show();
    if (bannerToken) {
        if (getTokenList().length) {
            if (!window.location.pathname.includes('/bot.html')) {
                window.location.pathname = `${window.location.pathname.replace(/\/+$/, '')}/bot.html`;
            }
            document.getElementById('bot-main').classList.remove('hidden');
        } else {
            oauthLogin(() => {
                $('.barspinner').hide();
                renderElements();
                GTM.init();
            });
        }
    } else {
        setTimeout(() => {
            renderBanner();
        }, 0);
    }
};

loginCheck();
<|endoftext|>


<commit_before>(function ($) {

    $.fn.serializeFormJSON = function () { //pattern to serialize form as json object
        var self = this,
            json = {},
            push_counters = {},
            patterns = {
                "validate": /^[a-zA-Z][a-zA-Z0-9_]*(?:\[(?:\d*|[a-zA-Z0-9_]+)\])*$/,
                "key": /[a-zA-Z0-9_]+|(?=\[\])/g,
                "push": /^$/,
                "fixed": /^\d+$/,
                "named": /^[a-zA-Z0-9_]+$/
            };

        this.build = function (base, key, value) {
            base[key] = value;
            return base;
        };

        this.push_counter = function (key) {
            if (push_counters[key] === undefined) {
                push_counters[key] = 0;
            }
            return push_counters[key]++;
        };

        $.each($(this).serializeArray(), function () {

            // skip invalid keys
            if (!patterns.validate.test(this.name)) {
                return;
            }

            var k,
                keys = this.name.match(patterns.key),
                merge = this.value,
                reverse_key = this.name;

            while ((k = keys.pop()) !== undefined) {

                // adjust reverse_key
                reverse_key = reverse_key.replace(new RegExp("\\[" + k + "\\]$"), '');

                // push
                if (k.match(patterns.push)) {
                    merge = self.build([], self.push_counter(reverse_key), merge);
                }

                // fixed
                else if (k.match(patterns.fixed)) {
                    merge = self.build([], k, merge);
                }

                // named
                else if (k.match(patterns.named)) {
                    merge = self.build({}, k, merge);
                }
            }

            json = $.extend(true, json, merge);
        });

        return json;
    };
})(jQuery);
var editor = ace.edit("editor");
ace.config.set("packaged", true);
var path = "ace/mode";
ace.config.set("modePath", path);
editor.session.setMode("asp");
editor.setTheme("ace/theme/tomorrow");
editor.setValue("");
editor.resize();
$('[data-toggle="tooltip"]').tooltip(); //active tooltip bootstrap

$(document).ready(function () {
    var a = $('body > form > .container > .layout').layout({ //fix minWidth layout
        center__minWidth: 600,
        east__minSize: 250
    });

    $('.fileinput-upload-button').click(function (e) {
        var fileToLoad = document.getElementById("upload-file").files[0]; //takes the uploaded file
        var reader = new FileReader(); // constructed FileReader
        reader.onload = function (event) {
            var text = event.target.result; //takes content of the file
            require(["ace/ace"], function (ace) {
                var editor = ace.edit("editor");
                editor.setValue(text); //set value of the file in text editor

            });

        };
        reader.readAsText(fileToLoad, "UTF-8"); //access to the file as text

    });
    $('#btn-download').click(function (e) {
        var chose = $('#choise').text(); //returns the value of what to download and place the value of the text editor into a 'text' variable
        if (chose !== "") {
            require(["ace/ace"], function (ace, text) {
                var chose = $('#choise').text();
                var editor = ace.edit("editor");
                if (chose === "Input") {
                    text = editor.getValue();

                } else if (chose === "Output") {
                    text = $('#output').val();
                } else if (chose === "Input & Output") {
                    text = editor.getValue();
                    text += '\n';
                    text += '\n';
                    text += 'Output\n';
                    text += '\n';
                    text += text = $('#output').val();
                }

                var textFileAsBlob = new Blob([text], { // create a new Blob (html5 magic) that conatins the data from your form feild

                    type: 'text/plain'
                });
                var fileNameToSaveAs = "myFile.txt"; // Specify the name of the file to be saved
                var downloadLink = document.createElement("a"); // create a link for our script to 'click'
                downloadLink.download = fileNameToSaveAs; //  supply the name of the file
                window.URL = window.URL || window.webkitURL; // allow code to work in webkit & Gecko based browsers without the need for a if / else block.
                downloadLink.href = window.URL.createObjectURL(textFileAsBlob); // Create the link Object.
                downloadLink.onclick = destroyClickedElement; // when link is clicked call a function to remove it from the DOM in case user wants to save a second file.
                downloadLink.style.display = "none"; // make sure the link is hidden.
                document.body.appendChild(downloadLink); // add the link to the DOM
                downloadLink.click(); // click the new link
            });

        }
    });

    function destroyClickedElement(event) {
        document.body.removeChild(event.target); // remove the link from the DOM
    }
    $('.dropdown-menu-choise').find('a').click(function (e) {
        var concept = $(this).text();
        $('#choise').text(concept); //append to the DOM the choise for download
    });

    $('#input').submit(function (e) {
        e.preventDefault();
        require(["ace/ace"], function (ace) {
            var editor = ace.edit("editor");
            var text = editor.getValue();
            $('#program').val(text); //insert the content of text editor in a hidden input text to serailize

            var form = $('#input').serializeFormJSON();

            $.ajax({
                type: "POST",
                url: "/run",
                data: form,
                dataType: "JSON",
                success: function (response) {
                    $('#output').val(response.model); //append the response in the textarea
                }
            });

        });

    });
    $("#slide").click(function (e) {
        $('.left-panel').toggleClass('left-panel-show'); //add class 'left-panel-show' to increase the width of the left panel
        $('.option-solver > div').toggleClass("hidden show"); //add class to show option components
    });

});

$(document).on('click', '.btn-add-option', function () {
    var row = $(this).closest('.row-option');
    var clone = row.clone(); //clone div .row-option to add another option
    var lenghtClass = $('.opname').length; //count number of classes to correct json format
    $(clone).insertAfter(row);
    var cloneOpname = $(clone).find('.opname');
    if (lenghtClass === 1) {
        $(cloneOpname).prepend('<button type="button" class="btn btn-danger">-</button>'); //append button delete after first options block
    }
    $(clone).find('.form-control-option').attr('name', 'option[' + lenghtClass + '][name]');
    var inputValueClone = $(clone).find('.input-group-value');
    $(inputValueClone).remove(); //remove all input value forms
    clone.find($('.center-btn-value')).remove(); //remove eventually button to add input value
    inputValueClone = '
<button type="button" class="btn btn-info btn-info-value ">Add value</button>
';
    $(clone).find('.option-value').append(inputValueClone); //append only one input value in the new options block

});

$(document).on('click', '.btn-del-option', function () {
    var row = $(this).closest('.row-option');
    row.empty(); //delete option container
    $('.form-control-option').each(function (index) { //iterate over '.form-control-option' classes to change the number of the object options for correct json format
        $(this).attr('name', 'option[' + index + '][name]');

        $(this).closest('.row-option').find('.form-control-value').each(function (index2) { //iterate over '.form-control-value' classes to change the number of the objects value for correct json format
            $(this).attr('name', 'option[' + index + '][value][]');

        });
    });

});

$(document).on('click', '.btn-del-value', function () { //delete input value
    var inputValue = $(this).closest('.input-group-value');
    var closestRow = inputValue.closest('.row-option');
    var lenghtInputValue = closestRow.find('.input-group-value').length; //count number of class '.input-group-value'
    if (lenghtInputValue === 1) //if the lenght of the class is equal to one, append the button to add input value
    {
        closestRow.find('.option-value').append('
<button type="button" class="btn btn-info btn-info-value ">Add value</button>
');
    }
    inputValue.remove(); //remove input value

});

$(document).on('click', '.btn-add', function () {
    addInpuValue($(this));

});

$(document).on('click', '.btn-info-value', function () {
    addInpuValue($(this));
    $(this).closest('.center-btn-value').remove(); // remove button to add input value

});

function addInpuValue(inputClass) {
    var optionValue = $(inputClass).closest('.option-value');
    var tmpName = $(inputClass).closest('.row-option').find('.form-control-option').attr('name');
    var replaceName = tmpName.replace('name', 'value'); //replace 'name' in 'value' for correct json format
    replaceName += '[]';
    var clone = '
<button type="button" class="btn btn-danger btn-del-value">-</button> <input type="text"class="form-control form-control-value" name=' + replaceName + '> <button type="button" class="btn btn-default btn-add">+</button>
';
    $(optionValue).append(clone); //append form input value to the DOM
}<commit_msg>Removed function "require" in script.js<commit_after>(function ($) {

    $.fn.serializeFormJSON = function () { //pattern to serialize form as json object
        var self = this,
            json = {},
            push_counters = {},
            patterns = {
                "validate": /^[a-zA-Z][a-zA-Z0-9_]*(?:\[(?:\d*|[a-zA-Z0-9_]+)\])*$/,
                "key": /[a-zA-Z0-9_]+|(?=\[\])/g,
                "push": /^$/,
                "fixed": /^\d+$/,
                "named": /^[a-zA-Z0-9_]+$/
            };

        this.build = function (base, key, value) {
            base[key] = value;
            return base;
        };

        this.push_counter = function (key) {
            if (push_counters[key] === undefined) {
                push_counters[key] = 0;
            }
            return push_counters[key]++;
        };

        $.each($(this).serializeArray(), function () {

            // skip invalid keys
            if (!patterns.validate.test(this.name)) {
                return;
            }

            var k,
                keys = this.name.match(patterns.key),
                merge = this.value,
                reverse_key = this.name;

            while ((k = keys.pop()) !== undefined) {

                // adjust reverse_key
                reverse_key = reverse_key.replace(new RegExp("\\[" + k + "\\]$"), '');

                // push
                if (k.match(patterns.push)) {
                    merge = self.build([], self.push_counter(reverse_key), merge);
                }

                // fixed
                else if (k.match(patterns.fixed)) {
                    merge = self.build([], k, merge);
                }

                // named
                else if (k.match(patterns.named)) {
                    merge = self.build({}, k, merge);
                }
            }

            json = $.extend(true, json, merge);
        });

        return json;
    };
})(jQuery);
var editor = ace.edit("editor");
ace.config.set("packaged", true);
var path = "ace/mode";
ace.config.set("modePath", path);
editor.session.setMode("asp");
editor.setTheme("ace/theme/tomorrow");
editor.setValue("");
editor.resize();
$('[data-toggle="tooltip"]').tooltip(); //active tooltip bootstrap

$(document).ready(function () {
    var a = $('body > form > .container > .layout').layout({ //fix minWidth layout
        center__minWidth: 600,
        east__minSize: 250
    });

    $('.fileinput-upload-button').click(function (e) {
        var fileToLoad = document.getElementById("upload-file").files[0]; //takes the uploaded file
        var reader = new FileReader(); // constructed FileReader
        reader.onload = function (event) {
            var text = event.target.result; //takes content of the file
                var editor = ace.edit("editor");
                editor.setValue(text); //set value of the file in text editor

        };
        reader.readAsText(fileToLoad, "UTF-8"); //access to the file as text

    });
    $('#btn-download').click(function (e) {
        var chose = $('#choise').text(); //returns the value of what to download and place the value of the text editor into a 'text' variable
        if (chose !== "") {

                if (chose === "Input") {
                    text = editor.getValue();

                } else if (chose === "Output") {
                    text = $('#output').val();
                } else if (chose === "Input & Output") {
                    text = editor.getValue();
                    text += '\n';
                    text += '\n';
                    text += 'Output\n';
                    text += '\n';
                    text += text = $('#output').val();
                }

                var textFileAsBlob = new Blob([text], { // create a new Blob (html5 magic) that conatins the data from your form feild

                    type: 'text/plain'
                });
                var fileNameToSaveAs = "myFile.txt"; // Specify the name of the file to be saved
                var downloadLink = document.createElement("a"); // create a link for our script to 'click'
                downloadLink.download = fileNameToSaveAs; //  supply the name of the file
                window.URL = window.URL || window.webkitURL; // allow code to work in webkit & Gecko based browsers without the need for a if / else block.
                downloadLink.href = window.URL.createObjectURL(textFileAsBlob); // Create the link Object.
                downloadLink.onclick = destroyClickedElement; // when link is clicked call a function to remove it from the DOM in case user wants to save a second file.
                downloadLink.style.display = "none"; // make sure the link is hidden.
                document.body.appendChild(downloadLink); // add the link to the DOM
                downloadLink.click(); // click the new link

        }
    });

    function destroyClickedElement(event) {
        document.body.removeChild(event.target); // remove the link from the DOM
    }
    $('.dropdown-menu-choise').find('a').click(function (e) {
        var concept = $(this).text();
        $('#choise').text(concept); //append to the DOM the choise for download
    });

    $('#input').submit(function (e) {
        e.preventDefault();
            var text = editor.getValue();
            $('#program').val(text); //insert the content of text editor in a hidden input text to serailize

            var form = $('#input').serializeFormJSON();
            console.log(form);
            $.ajax({
                type: "POST",
                url: "/run",
                data: form,
                dataType: "JSON",
                success: function (response) {
                    $('#output').val(response.model); //append the response in the textarea
                }
            });

    });
    $("#slide").click(function (e) {
        $('.left-panel').toggleClass('left-panel-show'); //add class 'left-panel-show' to increase the width of the left panel
        $('.option-solver > div').toggleClass("hidden show"); //add class to show option components
    });

});

$(document).on('click', '.btn-add-option', function () {
    var row = $(this).closest('.row-option');
    var clone = row.clone(); //clone div .row-option to add another option
    var lenghtClass = $('.opname').length; //count number of classes to correct json format
    $(clone).insertAfter(row);
    var cloneOpname = $(clone).find('.opname');
    if (lenghtClass === 1) {
        $(cloneOpname).prepend('<button type="button" class="btn btn-danger">-</button>'); //append button delete after first options block
    }
    $(clone).find('.form-control-option').attr('name', 'option[' + lenghtClass + '][name]');
    var inputValueClone = $(clone).find('.input-group-value');
    $(inputValueClone).remove(); //remove all input value forms
    clone.find($('.center-btn-value')).remove(); //remove eventually button to add input value
    inputValueClone = '
<button type="button" class="btn btn-info btn-info-value ">Add value</button>
';
    $(clone).find('.option-value').append(inputValueClone); //append only one input value in the new options block

});

$(document).on('click', '.btn-del-option', function () {
    var row = $(this).closest('.row-option');
    row.empty(); //delete option container
    $('.form-control-option').each(function (index) { //iterate over '.form-control-option' classes to change the number of the object options for correct json format
        $(this).attr('name', 'option[' + index + '][name]');

        $(this).closest('.row-option').find('.form-control-value').each(function (index2) { //iterate over '.form-control-value' classes to change the number of the objects value for correct json format
            $(this).attr('name', 'option[' + index + '][value][]');

        });
    });

});

$(document).on('click', '.btn-del-value', function () { //delete input value
    var inputValue = $(this).closest('.input-group-value');
    var closestRow = inputValue.closest('.row-option');
    var lenghtInputValue = closestRow.find('.input-group-value').length; //count number of class '.input-group-value'
    if (lenghtInputValue === 1) //if the lenght of the class is equal to one, append the button to add input value
    {
        closestRow.find('.option-value').append('
<button type="button" class="btn btn-info btn-info-value ">Add value</button>
');
    }
    inputValue.remove(); //remove input value

});

$(document).on('click', '.btn-add', function () {
    addInpuValue($(this));

});

$(document).on('click', '.btn-info-value', function () {
    addInpuValue($(this));
    $(this).closest('.center-btn-value').remove(); // remove button to add input value

});

function addInpuValue(inputClass) {
    var optionValue = $(inputClass).closest('.option-value');
    var tmpName = $(inputClass).closest('.row-option').find('.form-control-option').attr('name');
    var replaceName = tmpName.replace('name', 'value'); //replace 'name' in 'value' for correct json format
    replaceName += '[]';
    var clone = '
<button type="button" class="btn btn-danger btn-del-value">-</button> <input type="text"class="form-control form-control-value" name=' + replaceName + '> <button type="button" class="btn btn-default btn-add">+</button>
';
    $(optionValue).append(clone); //append form input value to the DOM
}<|endoftext|>


<commit_before>import { connect } from     'react-redux'

import Results from         '../components/results/results.jsx'

const mapStateToProps = ( state ) => {
    return {
        results: state.default.busStops
    }
}

const RenderBusStopsResults = connect(
    mapStateToProps
)( Results )

export default RenderBusStopsResults
<commit_msg>🚚  init redux render results container<commit_after>import { connect } from     'react-redux'
import Results from         '../components/results/results'

const mapStateToProps = ( state ) => {
    return {
        results: state.positionAroundMe.busStops
    }
}

const RenderBusStopsResults = connect(
    mapStateToProps
)( Results )

export default RenderBusStopsResults
<|endoftext|>


<commit_before>/* Global Variables */
var show_children = true;
var last_search_pos;
/* End of Global varaibles */

/*
  * jQuery Search Widget:
  * Generic code that shows, hides and highlights text in a HTML structure
  * that has been generated by eyedrawconfigload yii command
*/
(function($) {
  "use strict";
  let opts;
  let search_term;
  $.fn.search = function(options) {
    opts = $.extend({}, $.fn.search.defaults, options);
    let $results = $("#results");
    let $parent = $results.parent();
    this.keyup(function() {
      $results.detach();
      search_term = ($(this).val() + "").toLowerCase();
      for (let selector of opts.selectors) {
        const last_level = opts.selectors[0] == selector;
        $results.find(selector).each(function() {
          let $this = $(this);
          let $element = get_element($this);
          const allias = $this.data("allias").toLowerCase();
          if (allias.indexOf(search_term) == -1) {
            $this.html($this.text());
            if (!last_level && $element.children().find("li[style!='display: none;']").length != 0) {
              $element.show();
            } else {
              $element.hide();
            }
          } else {
            const highlighted_string = replace_matched_string($this.text(), search_term);
            $this.html(highlighted_string);
            $element.show();
            if (!last_level) {
              if (show_children == true) {
                $element.children().find("li[style='display: none;']").show();
              }
            }
          }
        });
      }
      $results.find("li[style!='display: none;']").find('.allias').each(function(){
        let $this = $(this);
        const highlighted_alliases = replace_matched_string($this.text(), search_term);
        $this.html(highlighted_alliases);
      });
      $parent.append($results);
    });
    return this;
  };
  $.fn.search.defaults = {
    selectors: [".lvl3", ".lvl2", ".lvl1"],
    ancestor_to_change: 2,
    matched_string_tag: ["", ""]
  };

  function replace_matched_string(old_string, search_term) {
    if (search_term === undefined || search_term === "" || old_string.toLowerCase().indexOf(search_term.toLowerCase()) == -1) {
      return old_string;
    }
    if (old_string === "") {
      return "";
    }
    const match_start = old_string.toLowerCase().indexOf("" + search_term.toLowerCase() + "");
    const match_end = match_start + search_term.length - 1;
    const before_match = old_string.slice(0, match_start);
    const match_text = old_string.slice(match_start, match_end + 1);
    const after_match = old_string.slice(match_end + 1);
    const new_string = before_match + opts.matched_string_tag[0] + match_text + opts.matched_string_tag[1] + replace_matched_string(after_match, search_term);
    return new_string;
  }

  function get_element($this) {
    for (let i = 0; i < opts.ancestor_to_change; i++) {
      $this = $this.parent();
    }
    return $this;
  }
}(jQuery));
/* End of jQuery Search Widget*/

/*
  * Initialisation:
  * Attaches event listeners to the DOM
  * for the IndexSearch Widget
*/
$(document).ready(function(){
  $("#search_bar_right").search();
  $("#search_bar_left").search();
  $("#search_bar_right").focus(function(){
    $('#search_bar_left').val('');
    last_search_pos = "right";
    $('#search_bar_right').trigger("keyup");
    show_results();
  });
  $("#search_bar_left").focus(function(){
    $('#search_bar_right').val('');
    last_search_pos = "left";
    $('#search_bar_left').trigger("keyup");
    show_results();
  });

  $('.result_item, .result_item_with_icon').click(function(){
    //Index has been clicked
    let $this = $(this);
    index_clicked($this);
    hide_results();
  });
  $('body').append('

');
  $('#description_toggle').change(function(){
    if (this.checked) {
      $('.description_icon,.description_note').show();
    } else {
      $('.description_icon,.description_note').hide();
    }
    event.stopPropagation();
  });
  $('#children_toggle').change(function(){
    let current_search_bar = "#search_bar_"+last_search_pos;
    if (this.checked) {
      show_children = true;
      $(current_search_bar).trigger('keyup');
    } else {
      show_children = false;
      $(current_search_bar).trigger('keyup');
    }
    event.stopPropagation();
  });

  $(window).click(function() {
    hide_results();
  });

  $('.switch').click(function(){
    event.stopPropagation();
  });

  $('#results').click(function(){
    event.stopPropagation();
  });
  $('#search_bar_right,#search_bar_left').click(function(){
    event.stopPropagation();
  });
  $('#big_cross').click(function(){
    hide_results();
  });

});
/* End of Initialisation */

/*
  * Auxilary Functions:
  * Frequently used code
*/
function get_controls_id(elementId, position){
  return "#ed_canvas_edit_"+position+"_"+elementId+"_controls";
}

function get_doodle_button(elementId, doodleClassName, position) {
  let doodle_id = "#"+doodleClassName+position+"_"+elementId;
  let $item = $(doodle_id).children();
  return $item;
}

function show_results(){
  var body = document.body,
  html = document.documentElement;
  var height = Math.max( body.scrollHeight, body.offsetHeight,
    html.clientHeight, html.scrollHeight, html.offsetHeight );
    $('#dim_rest').css("height", height);
    $('#dim_rest').show();
    $("body").css("overflow","hidden");
    $("#results").show();
    $(".switch").show();
    $("#description_toggle_label,#children_toggle_label,#search_options").show();
  }

  function hide_results(){
    $('#search_bar_right,#search_bar_left').val('');
    $('#results').scrollTop(0);
    $('#dim_rest').hide();
    $("body").css("overflow","auto");
    $("#results").hide();
    $(".switch").hide();
    $("#description_toggle_label,#children_toggle_label,#search_options").hide();
  }
  /*End of Auxilary Functions*/

  /*
    * Action Code
    * Code that handles what happens when
    * an index is clicked
  */
  /* Promise wrapper for old-style callback method */
  function index_clicked($this){
    let parameters = {};
    parameters["element_name"] = $this.data('elementName');
    parameters["element_id"] = $this.data('elementId');
    parameters["doodle_name"] = $this.data('doodleClassName');
    parameters["property_name"] = $this.data('property');
    //Chains can be made conditional based on content of parameters
    //Guarantees funcion execution order (even for asyncrounous functions)
    click_element(parameters).then(result => click_doodle(result)).then(result => click_property(result)).catch(() => {
      return;
    });
  }

  function click_element(parameters){
    //get side bar item
    let $item = $(".oe-event-sidebar-edit li a:contains("+parameters.element_name+")");
    return click_sidebar_element($item).then(function (){
      return new Promise(function(resolve, reject) {
        //see if parameters are set for doodle
        if (parameters.doodle_name) {
          resolve(parameters);
        } else {
          reject();
        }
      });
    });
  }

  function click_doodle(parameters){
    // TODO: Stop using timeout and instead use Promise on event handlers (canvas ready)
    // is await the solution (canvas ready)?
    return new Promise(function(resolve, reject) {
      setTimeout(function(){
        let dropdown_box_selector = "#eyedrawwidget_"+last_search_pos+"_"+parameters.element_id;
        let $doodle = get_doodle_button(parameters.element_id,parameters.doodle_name,last_search_pos);
        let doodle_name = ED.titles[parameters.doodle_name];
        let $selected_doodle = $(dropdown_box_selector).find("#ed_example_selected_doodle").children().find("option:contains("+doodle_name+")");
        if ($selected_doodle.length == 0) {
          $doodle.trigger("click");
        } else {
          $(dropdown_box_selector).find("#ed_example_selected_doodle").children().find("option").removeAttr('selected');
          $selected_doodle.attr('selected','selected');
          $(dropdown_box_selector).find("#ed_example_selected_doodle").trigger('change');
        }
        //Ensures Promise chains breaks if parameter(s) for next promise are not present
        if (parameters.property_name) {
          resolve(parameters);
        } else {
          reject();
        }
      },800);
    });
  }

  function click_property(parameters){
    return new Promise(function(resolve, reject) {
      let control_id = get_controls_id(parameters.element_id,last_search_pos);
      $(control_id).find("div:contains("+parameters.property_name+")").effect("highlight", {}, 6000);
      /* Breaks the Promise chain as nothing should be called after property,
         based on the current code */
      if (1 == 2) {
        resolve(parameters);
      } else {
        reject();
      }
    });
  }

  function click_sidebar_element($item) {
    return new Promise(function(resolve, reject) {
      event_sidebar.loadClickedItem($item,{},resolve);
    });
  }
  /* End of Promise code*/
<commit_msg>Removed setTimeout and trigger for ED.Checker.onAllReady and addDoodle()<commit_after>/* Global Variables */
var show_children = true;
var last_search_pos;
/* End of Global varaibles */

/*
  * jQuery Search Widget:
  * Generic code that shows, hides and highlights text in a HTML structure
  * that has been generated by eyedrawconfigload yii command
*/
(function($) {
  "use strict";
  let opts;
  let search_term;
  $.fn.search = function(options) {
    opts = $.extend({}, $.fn.search.defaults, options);
    let $results = $("#results");
    let $parent = $results.parent();
    this.keyup(function() {
      $results.detach();
      search_term = ($(this).val() + "").toLowerCase();
      for (let selector of opts.selectors) {
        const last_level = opts.selectors[0] == selector;
        $results.find(selector).each(function() {
          let $this = $(this);
          let $element = get_element($this);
          const allias = $this.data("allias").toLowerCase();
          if (allias.indexOf(search_term) == -1) {
            $this.html($this.text());
            if (!last_level && $element.children().find("li[style!='display: none;']").length != 0) {
              $element.show();
            } else {
              $element.hide();
            }
          } else {
            const highlighted_string = replace_matched_string($this.text(), search_term);
            $this.html(highlighted_string);
            $element.show();
            if (!last_level) {
              if (show_children == true) {
                $element.children().find("li[style='display: none;']").show();
              }
            }
          }
        });
      }
      $results.find("li[style!='display: none;']").find('.allias').each(function(){
        let $this = $(this);
        const highlighted_alliases = replace_matched_string($this.text(), search_term);
        $this.html(highlighted_alliases);
      });
      $parent.append($results);
    });
    return this;
  };
  $.fn.search.defaults = {
    selectors: [".lvl3", ".lvl2", ".lvl1"],
    ancestor_to_change: 2,
    matched_string_tag: ["", ""]
  };

  function replace_matched_string(old_string, search_term) {
    if (search_term === undefined || search_term === "" || old_string.toLowerCase().indexOf(search_term.toLowerCase()) == -1) {
      return old_string;
    }
    if (old_string === "") {
      return "";
    }
    const match_start = old_string.toLowerCase().indexOf("" + search_term.toLowerCase() + "");
    const match_end = match_start + search_term.length - 1;
    const before_match = old_string.slice(0, match_start);
    const match_text = old_string.slice(match_start, match_end + 1);
    const after_match = old_string.slice(match_end + 1);
    const new_string = before_match + opts.matched_string_tag[0] + match_text + opts.matched_string_tag[1] + replace_matched_string(after_match, search_term);
    return new_string;
  }

  function get_element($this) {
    for (let i = 0; i < opts.ancestor_to_change; i++) {
      $this = $this.parent();
    }
    return $this;
  }
}(jQuery));
/* End of jQuery Search Widget*/

/*
  * Initialisation:
  * Attaches event listeners to the DOM
  * for the IndexSearch Widget
*/
$(document).ready(function(){
  $("#search_bar_right").search();
  $("#search_bar_left").search();
  $("#search_bar_right").focus(function(){
    $('#search_bar_left').val('');
    last_search_pos = "right";
    $('#search_bar_right').trigger("keyup");
    show_results();
  });
  $("#search_bar_left").focus(function(){
    $('#search_bar_right').val('');
    last_search_pos = "left";
    $('#search_bar_left').trigger("keyup");
    show_results();
  });

  $('.result_item, .result_item_with_icon').click(function(){
    //Index has been clicked
    let $this = $(this);
    index_clicked($this);
    hide_results();
  });
  $('body').append('

');
  $('#description_toggle').change(function(){
    if (this.checked) {
      $('.description_icon,.description_note').show();
    } else {
      $('.description_icon,.description_note').hide();
    }
    event.stopPropagation();
  });
  $('#children_toggle').change(function(){
    let current_search_bar = "#search_bar_"+last_search_pos;
    if (this.checked) {
      show_children = true;
      $(current_search_bar).trigger('keyup');
    } else {
      show_children = false;
      $(current_search_bar).trigger('keyup');
    }
    event.stopPropagation();
  });

  $(window).click(function() {
    hide_results();
  });

  $('.switch').click(function(){
    event.stopPropagation();
  });

  $('#results').click(function(){
    event.stopPropagation();
  });
  $('#search_bar_right,#search_bar_left').click(function(){
    event.stopPropagation();
  });
  $('#big_cross').click(function(){
    hide_results();
  });

});
/* End of Initialisation */

/*
  * Auxilary Functions:
  * Frequently used code
*/
function get_controls_id(elementId, position){
  return "#ed_canvas_edit_"+position+"_"+elementId+"_controls";
}

function get_doodle_button(elementId, doodleClassName, position) {
  let doodle_id = "#"+doodleClassName+position+"_"+elementId;
  let $item = $(doodle_id).children();
  return $item;
}

function show_results(){
  var body = document.body,
  html = document.documentElement;
  var height = Math.max( body.scrollHeight, body.offsetHeight,
    html.clientHeight, html.scrollHeight, html.offsetHeight );
    $('#dim_rest').css("height", height);
    $('#dim_rest').show();
    $("body").css("overflow","hidden");
    $("#results").show();
    $(".switch").show();
    $("#description_toggle_label,#children_toggle_label,#search_options").show();
  }

  function hide_results(){
    $('#search_bar_right,#search_bar_left').val('');
    $('#results').scrollTop(0);
    $('#dim_rest').hide();
    $("body").css("overflow","auto");
    $("#results").hide();
    $(".switch").hide();
    $("#description_toggle_label,#children_toggle_label,#search_options").hide();
  }
  /*End of Auxilary Functions*/

  /*
    * Action Code
    * Code that handles what happens when
    * an index is clicked
  */
  /* Promise wrapper for old-style callback method */
  function index_clicked($this){
    let parameters = {};
    parameters["element_name"] = $this.data('elementName');
    parameters["element_id"] = $this.data('elementId');
    parameters["doodle_name"] = $this.data('doodleClassName');
    parameters["property_name"] = $this.data('property');
    //Chains can be made conditional based on content of parameters
    //Guarantees funcion execution order (even for asyncrounous functions)
    click_element(parameters).then(result => click_doodle(result)).then(result => click_property(result)).catch(() => {
      return;
    });
  }

  function click_element(parameters){
    //get side bar item
    let $item = $(".oe-event-sidebar-edit li a:contains("+parameters.element_name+")");
    return click_sidebar_element($item).then(function (){
      return new Promise(function(resolve, reject) {
        //see if parameters are set for doodle
        if (parameters.doodle_name) {
          resolve(parameters);
        } else {
          reject();
        }
      });
    });
  }

  function click_doodle(parameters){
    // TODO: Stop using timeout and instead use Promise on event handlers (canvas ready)
    // is await the solution (canvas ready)?
    return new Promise(function(resolve, reject) {
      let ed_canvas = ED.Checker.getInstanceByIdSuffix(last_search_pos+"_"+parameters.element_id);
      ED.Checker.register(ed_canvas);
      ED.Checker.onAllReady(function(){
        let dropdown_box_selector = "#eyedrawwidget_"+last_search_pos+"_"+parameters.element_id;
        let $doodle = get_doodle_button(parameters.element_id,parameters.doodle_name,last_search_pos);
        let doodle_name = ED.titles[parameters.doodle_name];
        let $selected_doodle = $(dropdown_box_selector).find("#ed_example_selected_doodle").children().find("option:contains("+doodle_name+")");
        if ($selected_doodle.length == 0) {
          ed_canvas.addDoodle(parameters.doodle_name);
        } else {
          $(dropdown_box_selector).find("#ed_example_selected_doodle").children().find("option").removeAttr('selected');
          $selected_doodle.attr('selected','selected');
          $(dropdown_box_selector).find("#ed_example_selected_doodle").trigger('change');
        }
        //Ensures Promise chains breaks if parameter(s) for next promise are not present
        if (parameters.property_name) {
          resolve(parameters);
        } else {
          reject();
        }
      });
      //wrap onAllReady in Promise
  });
}

  function click_property(parameters){
    return new Promise(function(resolve, reject) {
      let control_id = get_controls_id(parameters.element_id,last_search_pos);
      $(control_id).find("div:contains("+parameters.property_name+")").effect("highlight", {}, 6000);
      /* Breaks the Promise chain as nothing should be called after property,
         based on the current code */
      if (1 == 2) {
        resolve(parameters);
      } else {
        reject();
      }
    });
  }

  function click_sidebar_element($item) {
    return new Promise(function(resolve, reject) {
      event_sidebar.loadClickedItem($item,{},resolve);
    });
  }
  /* End of Promise code*/
<|endoftext|>


<commit_before>/* function to create popup window */
function popup(mylink){
    if (!window.focus)
        return true;
    var href;
    if (typeof(mylink) == 'string')
       href=mylink;
    else
       href=mylink.href;
    window.open(href, "player", 'width=300,height=100,scrollbars=yes');
    return false;
}

/* Take a string representing a date in the format 2012-04-25 and return
 * a javascript date object representing this date. */
function getDateFromString(time){
    var date = time.split("-");

    if (date.length != 3){
        return null;
    }

    var year = parseInt(date[0], 10);
    var month = parseInt(date[1], 10) -1;
    var day = parseInt(date[2], 10);

    return new Date(year, month, day);

}

function convertSecondsToDaysHoursMinutesSeconds(seconds){
    if (seconds < 0)
        seconds = 0;

    seconds = parseInt(seconds, 10);

    var days = parseInt(seconds / 86400);
    seconds -= days*86400;

    var hours = parseInt(seconds / 3600);
    seconds -= hours*3600;

    var minutes = parseInt(seconds / 60);
    seconds -= minutes*60;

    return {days:days, hours:hours, minutes:minutes, seconds:seconds};
}

/* Takes an input parameter of milliseconds and converts these into
 * the format HH:MM:SS */
function convertToHHMMSS(timeInMS){
	var time = parseInt(timeInMS);

	var hours = parseInt(time / 3600000);
	time -= 3600000*hours;

	var minutes = parseInt(time / 60000);
	time -= 60000*minutes;

	var seconds = parseInt(time / 1000);

	hours = hours.toString();
	minutes = minutes.toString();
	seconds = seconds.toString();

	if (hours.length == 1)
		hours = "0" + hours;
	if (minutes.length == 1)
		minutes = "0" + minutes;
	if (seconds.length == 1)
		seconds = "0" + seconds;
	if (hours == "00")
		return minutes + ":" + seconds;
	else
		return hours + ":" + minutes + ":" + seconds;
}

function convertToHHMMSSmm(timeInMS){
	var time = parseInt(timeInMS);

	var hours = parseInt(time / 3600000);
	time -= 3600000*hours;

	var minutes = parseInt(time / 60000);
	time -= 60000*minutes;

	var seconds = parseInt(time / 1000);
	time -= 1000*seconds;

	var ms = parseInt(time);

	hours = hours.toString();
	minutes = minutes.toString();
	seconds = seconds.toString();
	ms = ms.toString();

	if (hours.length == 1)
		hours = "0" + hours;
	if (minutes.length == 1)
		minutes = "0" + minutes;
	if (seconds.length == 1)
		seconds = "0" + seconds;

	if (ms.length == 3)
		ms = ms.substring(0, 2);
	else if (ms.length == 2)
		ms = "0" + ms.substring(0,1);
	else if (ms.length == 1)
		ms = "00";

	if (hours == "00")
		return minutes + ":" + seconds + "." + ms;
	else
		return hours + ":" + minutes + ":" + seconds+ "." + ms;
}

function convertDateToHHMM(epochTime){
	var d = new Date(epochTime);

	var hours = d.getUTCHours().toString();
	var minutes = d.getUTCMinutes().toString();

	if (hours.length == 1)
		hours = "0" + hours;
	if (minutes.length == 1)
		minutes = "0" + minutes;

	return hours + ":" + minutes;
}

function convertDateToHHMMSS(epochTime){
	var d = new Date(epochTime);

	var hours = d.getUTCHours().toString();
	var minutes = d.getUTCMinutes().toString();
	var seconds = d.getUTCSeconds().toString();

	if (hours.length == 1)
		hours = "0" + hours;
	if (minutes.length == 1)
		minutes = "0" + minutes;
	if (seconds.length == 1)
		seconds = "0" + seconds;
	return hours + ":" + minutes + ":" + seconds;
}

/* Takes in a string of format similar to 2011-02-07 02:59:57,
 * and converts this to epoch/posix time. */
function convertDateToPosixTime(s){

    var datetime = s.split(" ");

    var date = datetime[0].split("-");
    var time = datetime[1].split(":");

	var year = date[0];
	var month = date[1];
	var day = date[2];
	var hour = time[0];
	var minute = time[1];
    var sec = 0;
    var msec = 0;

    if (time[2].indexOf(".") != -1){
        var temp = time[2].split(".");
        sec = temp[0];
        msec = temp[1];
    } else
        sec = time[2];

	return Date.UTC(year, month-1, day, hour, minute, sec, msec);
}

function getFileExt(filename){
    return filename.split('.').pop();
}

function audioStream(){

    if ($("#jquery_jplayer_1").data("jPlayer") && $("#jquery_jplayer_1").data("jPlayer").status.paused != true){
        $('#jquery_jplayer_1').jPlayer('clearMedia');
        $('#jquery_jplayer_1').jPlayer('destroy');
        return;
    }

    var uri = "http://localhost:8000/airtime_128.ogg";
    var ext = getFileExt(uri);

    var media;
    var supplied;
    if (ext == "ogg"){
        media = {oga:uri};
        supplied = "oga";
    } else {
        media = {mp3:uri};
        supplied = "mp3";
    }

    $("#jquery_jplayer_1").jPlayer({
        ready: function () {
            $(this).jPlayer("setMedia", media).jPlayer("play");
        },
        swfPath: "/js/jplayer",
        supplied: supplied
    });
}

function resizeImg(ele, targetWidth, targetHeight){
    var img = $(ele);

    var width = ele.width;
    var height = ele.height;

    // resize img proportionaly
    if( width > height && width > targetWidth){
        var ratio = targetWidth/width;
        img.css("width", targetHeight+"px");
        var newHeight = height * ratio;
        img.css("height", newHeight+"px");
    }else if( width < height && height > targetHeight){
        var ratio = targetHeight/height;
        img.css("height", targetHeight+"px");
        var newWidth = width * ratio;
        img.css("width", newWidth+"px");
    }else if( width == height && width > targetWidth){
        img.css("height", targetHeight+"px");
        img.css("width", targetWidth+"px" );
    }
}

function resizeToMaxHeight(ele, targetHeight){
    var img = $(ele);

    var width = ele.width;
    var height = ele.height;

    // resize img proportionaly
    if( height > targetHeight){
        var ratio = targetHeight/height;
        img.css("height", targetHeight+"px");
        var newWidth = width * ratio;
        img.css("width", newWidth+"px");
    }
}
<commit_msg>CC-3704: No default checked day when creating repeat show<commit_after>/* function to create popup window */
function popup(mylink){
    if (!window.focus)
        return true;
    var href;
    if (typeof(mylink) == 'string')
       href=mylink;
    else
       href=mylink.href;
    window.open(href, "player", 'width=300,height=100,scrollbars=yes');
    return false;
}

/* Take a string representing a date in the format 2012-04-25 and return
 * a javascript date object representing this date. */
function getDateFromString(time){
    var date = time.split("-");

    if (date.length != 3){
        return null;
    }

    var year = parseInt(date[0], 10);
    var month = parseInt(date[1], 10) -1;
    var day = parseInt(date[2], 10);

    if (isNaN(year) || isNaN(month) || isNaN(day)){
        return null;
    }

    return new Date(year, month, day);

}

function convertSecondsToDaysHoursMinutesSeconds(seconds){
    if (seconds < 0)
        seconds = 0;

    seconds = parseInt(seconds, 10);

    var days = parseInt(seconds / 86400);
    seconds -= days*86400;

    var hours = parseInt(seconds / 3600);
    seconds -= hours*3600;

    var minutes = parseInt(seconds / 60);
    seconds -= minutes*60;

    return {days:days, hours:hours, minutes:minutes, seconds:seconds};
}

/* Takes an input parameter of milliseconds and converts these into
 * the format HH:MM:SS */
function convertToHHMMSS(timeInMS){
	var time = parseInt(timeInMS);

	var hours = parseInt(time / 3600000);
	time -= 3600000*hours;

	var minutes = parseInt(time / 60000);
	time -= 60000*minutes;

	var seconds = parseInt(time / 1000);

	hours = hours.toString();
	minutes = minutes.toString();
	seconds = seconds.toString();

	if (hours.length == 1)
		hours = "0" + hours;
	if (minutes.length == 1)
		minutes = "0" + minutes;
	if (seconds.length == 1)
		seconds = "0" + seconds;
	if (hours == "00")
		return minutes + ":" + seconds;
	else
		return hours + ":" + minutes + ":" + seconds;
}

function convertToHHMMSSmm(timeInMS){
	var time = parseInt(timeInMS);

	var hours = parseInt(time / 3600000);
	time -= 3600000*hours;

	var minutes = parseInt(time / 60000);
	time -= 60000*minutes;

	var seconds = parseInt(time / 1000);
	time -= 1000*seconds;

	var ms = parseInt(time);

	hours = hours.toString();
	minutes = minutes.toString();
	seconds = seconds.toString();
	ms = ms.toString();

	if (hours.length == 1)
		hours = "0" + hours;
	if (minutes.length == 1)
		minutes = "0" + minutes;
	if (seconds.length == 1)
		seconds = "0" + seconds;

	if (ms.length == 3)
		ms = ms.substring(0, 2);
	else if (ms.length == 2)
		ms = "0" + ms.substring(0,1);
	else if (ms.length == 1)
		ms = "00";

	if (hours == "00")
		return minutes + ":" + seconds + "." + ms;
	else
		return hours + ":" + minutes + ":" + seconds+ "." + ms;
}

function convertDateToHHMM(epochTime){
	var d = new Date(epochTime);

	var hours = d.getUTCHours().toString();
	var minutes = d.getUTCMinutes().toString();

	if (hours.length == 1)
		hours = "0" + hours;
	if (minutes.length == 1)
		minutes = "0" + minutes;

	return hours + ":" + minutes;
}

function convertDateToHHMMSS(epochTime){
	var d = new Date(epochTime);

	var hours = d.getUTCHours().toString();
	var minutes = d.getUTCMinutes().toString();
	var seconds = d.getUTCSeconds().toString();

	if (hours.length == 1)
		hours = "0" + hours;
	if (minutes.length == 1)
		minutes = "0" + minutes;
	if (seconds.length == 1)
		seconds = "0" + seconds;
	return hours + ":" + minutes + ":" + seconds;
}

/* Takes in a string of format similar to 2011-02-07 02:59:57,
 * and converts this to epoch/posix time. */
function convertDateToPosixTime(s){

    var datetime = s.split(" ");

    var date = datetime[0].split("-");
    var time = datetime[1].split(":");

	var year = date[0];
	var month = date[1];
	var day = date[2];
	var hour = time[0];
	var minute = time[1];
    var sec = 0;
    var msec = 0;

    if (time[2].indexOf(".") != -1){
        var temp = time[2].split(".");
        sec = temp[0];
        msec = temp[1];
    } else
        sec = time[2];

	return Date.UTC(year, month-1, day, hour, minute, sec, msec);
}

function getFileExt(filename){
    return filename.split('.').pop();
}

function audioStream(){

    if ($("#jquery_jplayer_1").data("jPlayer") && $("#jquery_jplayer_1").data("jPlayer").status.paused != true){
        $('#jquery_jplayer_1').jPlayer('clearMedia');
        $('#jquery_jplayer_1').jPlayer('destroy');
        return;
    }

    var uri = "http://localhost:8000/airtime_128.ogg";
    var ext = getFileExt(uri);

    var media;
    var supplied;
    if (ext == "ogg"){
        media = {oga:uri};
        supplied = "oga";
    } else {
        media = {mp3:uri};
        supplied = "mp3";
    }

    $("#jquery_jplayer_1").jPlayer({
        ready: function () {
            $(this).jPlayer("setMedia", media).jPlayer("play");
        },
        swfPath: "/js/jplayer",
        supplied: supplied
    });
}

function resizeImg(ele, targetWidth, targetHeight){
    var img = $(ele);

    var width = ele.width;
    var height = ele.height;

    // resize img proportionaly
    if( width > height && width > targetWidth){
        var ratio = targetWidth/width;
        img.css("width", targetHeight+"px");
        var newHeight = height * ratio;
        img.css("height", newHeight+"px");
    }else if( width < height && height > targetHeight){
        var ratio = targetHeight/height;
        img.css("height", targetHeight+"px");
        var newWidth = width * ratio;
        img.css("width", newWidth+"px");
    }else if( width == height && width > targetWidth){
        img.css("height", targetHeight+"px");
        img.css("width", targetWidth+"px" );
    }
}

function resizeToMaxHeight(ele, targetHeight){
    var img = $(ele);

    var width = ele.width;
    var height = ele.height;

    // resize img proportionaly
    if( height > targetHeight){
        var ratio = targetHeight/height;
        img.css("height", targetHeight+"px");
        var newWidth = width * ratio;
        img.css("width", newWidth+"px");
    }
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

function DocumentObserver(config) {

    "use strict";

    var _document = null;
    var _transport;
    var _imports = {};

    /**
     * Send an event in case that a related doc was added/removed
     *
     * @param {NodeList} nodes DOM nodes that were modified
     * @param {string} action "Added" or "Removed"
     */
    function _onNodesChanged(nodes, action) {
        var i;
        for (i = 0; i < nodes.length; i++) {
            // check for Javascript files
            if (nodes[i].nodeName === "SCRIPT" && nodes[i].src) {
                _transport.send(JSON.stringify({
                    type: 'Script.' + action,
                    src: nodes[i].src
                }));
            }

            // check for stylesheets
            if (nodes[i].nodeName === "LINK" && nodes[i].rel === "stylesheet" && nodes[i].href) {
                _transport.send(JSON.stringify({
                    type: 'Stylesheet.' + action,
                    href: nodes[i].href
                }));
                // TODO: check for @import rules.
                // It seems that node we get from MutationRecord doesn't have the entire information:
                //  - Added stylesheet has import rules (wich give us relative URL) but in Chrome,
                //    the stylesheet to be imported is not yet loaded (sheet=null).
                //  - Removed stylesheet also has sheet=null since it was proabably already removed.
            }
        }
    }

    function _enableListeners() {
        // enable MutationOberver if it's supported
        var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
        if (MutationObserver) {
            var observer = new MutationObserver(function (mutations) {
                mutations.forEach(function (mutation) {
                    if (mutation.addedNodes.length > 0) {
                        _onNodesChanged(mutation.addedNodes, 'Added');
                    }
                    if (mutation.removedNodes.length > 0) {
                        _onNodesChanged(mutation.removedNodes, 'Removed');
                    }
                });
            });
            observer.observe(_document, {
                childList: true,
                subtree: true
            });
        } else {
            // use MutationEvents as fallback
            _document.addEventListener('DOMNodeInserted', function niLstnr(e) {
                this._onNodesChanged([e.target], 'Added');
            });
            _document.addEventListener('DOMNodeRemoved', function nrLstnr(e) {
                this._onNodesChanged([e.target], 'Removed');
            });
        }
    }

    /**
     * Retrieves related documents (external CSS and JS files)
     *
     * @return {{scripts: object, stylesheets: object}} Related scripts and stylesheets
     */
    function related() {

        var rel = {
            scripts: {},
            stylesheets: {}
        };
        var i;
        // iterate on document scripts (HTMLCollection doesn't provide forEach iterator).
        for (i = 0; i < _document.scripts.length; i++) {
            // add only external scripts
            if (_document.scripts[i].src) {
                rel.scripts[_document.scripts[i].src] = true;
            }
        }

        var s, j;
        //traverse @import rules
        var traverseRules = function _traverseRules(sheet, base) {
            var i;
            if (sheet.href && sheet.cssRules) {
                if (rel.stylesheets[sheet.href] === undefined) {
                    rel.stylesheets[sheet.href] = [];
                }
                rel.stylesheets[sheet.href].push(base);
                for (i = 0; i < sheet.cssRules.length; i++) {
                    if (sheet.cssRules[i].href) {
                        traverseRules(sheet.cssRules[i].styleSheet, base);
                    }
                }
            }
        };
        //iterate on document.stylesheets (StyleSheetList doesn't provide forEach iterator).
        for (j = 0; j < document.styleSheets.length; j++) {
            s = document.styleSheets[j];
            traverseRules(s, s.href);
        }
        return rel;
    }

    /**
     * Start listening for events and send initial related documents message.
     *
     * @param {HTMLDocument} document
     * @param {object} transport Live development transport connection
     */
    function start(document, transport) {
        _transport = transport;
        _document = document;
        // start listening to node changes
        _enableListeners();
        // send the current status of related docs.
        _transport.send(JSON.stringify({
            type: "Document.Related",
            related: related()
        }));
    }

    /**
     * Stop listening.
     * TODO currently a no-op.
     */
    function stop() {

    }

    window.addEventListener('load', function () {
        //it assumes transport is already set into the browser
        start(window.document, window._Brackets_LiveDev_Transport);
    });

    window.addEventListener('unload', function () {
        stop();
    });

    return {
        start: start,
        stop: stop,
        related: related
    };
}<commit_msg>change from type to method on DocumentObserver<commit_after>/*
 * Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

function DocumentObserver(config) {

    "use strict";

    var _document = null;
    var _transport;
    var _imports = {};

    /**
     * Send an event in case that a related doc was added/removed
     *
     * @param {NodeList} nodes DOM nodes that were modified
     * @param {string} action "Added" or "Removed"
     */
    function _onNodesChanged(nodes, action) {
        var i;
        for (i = 0; i < nodes.length; i++) {
            // check for Javascript files
            if (nodes[i].nodeName === "SCRIPT" && nodes[i].src) {
                _transport.send(JSON.stringify({
                    method: 'Script.' + action,
                    src: nodes[i].src
                }));
            }

            // check for stylesheets
            if (nodes[i].nodeName === "LINK" && nodes[i].rel === "stylesheet" && nodes[i].href) {
                _transport.send(JSON.stringify({
                    method: 'Stylesheet.' + action,
                    href: nodes[i].href
                }));
                // TODO: check for @import rules.
                // It seems that node we get from MutationRecord doesn't have the entire information:
                //  - Added stylesheet has import rules (wich give us relative URL) but in Chrome,
                //    the stylesheet to be imported is not yet loaded (sheet=null).
                //  - Removed stylesheet also has sheet=null since it was proabably already removed.
            }
        }
    }

    function _enableListeners() {
        // enable MutationOberver if it's supported
        var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
        if (MutationObserver) {
            var observer = new MutationObserver(function (mutations) {
                mutations.forEach(function (mutation) {
                    if (mutation.addedNodes.length > 0) {
                        _onNodesChanged(mutation.addedNodes, 'Added');
                    }
                    if (mutation.removedNodes.length > 0) {
                        _onNodesChanged(mutation.removedNodes, 'Removed');
                    }
                });
            });
            observer.observe(_document, {
                childList: true,
                subtree: true
            });
        } else {
            // use MutationEvents as fallback
            _document.addEventListener('DOMNodeInserted', function niLstnr(e) {
                this._onNodesChanged([e.target], 'Added');
            });
            _document.addEventListener('DOMNodeRemoved', function nrLstnr(e) {
                this._onNodesChanged([e.target], 'Removed');
            });
        }
    }

    /**
     * Retrieves related documents (external CSS and JS files)
     *
     * @return {{scripts: object, stylesheets: object}} Related scripts and stylesheets
     */
    function related() {

        var rel = {
            scripts: {},
            stylesheets: {}
        };
        var i;
        // iterate on document scripts (HTMLCollection doesn't provide forEach iterator).
        for (i = 0; i < _document.scripts.length; i++) {
            // add only external scripts
            if (_document.scripts[i].src) {
                rel.scripts[_document.scripts[i].src] = true;
            }
        }

        var s, j;
        //traverse @import rules
        var traverseRules = function _traverseRules(sheet, base) {
            var i;
            if (sheet.href && sheet.cssRules) {
                if (rel.stylesheets[sheet.href] === undefined) {
                    rel.stylesheets[sheet.href] = [];
                }
                rel.stylesheets[sheet.href].push(base);
                for (i = 0; i < sheet.cssRules.length; i++) {
                    if (sheet.cssRules[i].href) {
                        traverseRules(sheet.cssRules[i].styleSheet, base);
                    }
                }
            }
        };
        //iterate on document.stylesheets (StyleSheetList doesn't provide forEach iterator).
        for (j = 0; j < document.styleSheets.length; j++) {
            s = document.styleSheets[j];
            traverseRules(s, s.href);
        }
        return rel;
    }

    /**
     * Start listening for events and send initial related documents message.
     *
     * @param {HTMLDocument} document
     * @param {object} transport Live development transport connection
     */
    function start(document, transport) {
        _transport = transport;
        _document = document;
        // start listening to node changes
        _enableListeners();
        // send the current status of related docs.
        _transport.send(JSON.stringify({
            method: "Document.Related",
            related: related()
        }));
    }

    /**
     * Stop listening.
     * TODO currently a no-op.
     */
    function stop() {

    }

    window.addEventListener('load', function () {
        //it assumes transport is already set into the browser
        start(window.document, window._Brackets_LiveDev_Transport);
    });

    window.addEventListener('unload', function () {
        stop();
    });

    return {
        start: start,
        stop: stop,
        related: related
    };
}<|endoftext|>