<commit_before>$( document ).ready(function() {
    $(".button-collapse").sideNav();
});

function hideall(){
	$('.content-div').hide();
	document.body.innerHTML += "

"
}
<commit_msg>Centered horizontally<commit_after>$( document ).ready(function() {
    $(".button-collapse").sideNav();
});

function hideall(){
	$('.content-div').hide();
	document.body.innerHTML += "

"

}
<|endoftext|>


<commit_before>'use strict';

Handlebars.registerHelper('lc', function(text) {
    return text ? text.toLowerCase() : '';
});

function generateCards() {
    var url      = $('#url').val();
    var ids      = $('#ids').val().split(/\s*,\s*/).filter(function(id) {return id.match(/^\d+$/)});
    var template = Handlebars.compile( $('#cards-template').html() );

    if (!url || !ids.length) {
        alert('Check fields');
        return;
    }

    prepareTemplateData(url, ids).then(function(data) {
        $('#cards').html( template(data) );
    });
}

function init() {
    $('#submit').click(generateCards);
}

function prepareTemplateData(url, ids) {
    var api = new RedmineAPI({ url: url });

    var issuesPromises = ids.map(function(id) {
        return api.getIssueById(id);
    } );

    return Promise.all(issuesPromises).then(function(issues) {
        return { issues: splitArray(issues,2) };
    }).catch(console.error);
}

function splitArray(array, step) {
    var newArray = [];

    for (var i = 0; i < array.length; i+= step) {
        var newSubArray = [];

        for (var j = i; j < i+step; j++) {
            if (j>array.length) break;

            newSubArray.push(array[j]);
        };

        newArray.push(newSubArray);
    }

    return newArray;
}<commit_msg>Autosave last used redmine url in localstorage<commit_after>'use strict';

Handlebars.registerHelper('lc', function(text) {
    return text ? text.toLowerCase() : '';
});

function generateCards() {
    var url      = $('#url').val();
    var ids      = $('#ids').val().split(/\s*,\s*/).filter(function(id) {return id.match(/^\d+$/)});
    var template = Handlebars.compile( $('#cards-template').html() );

    if (!url || !ids.length) {
        alert('Check fields');
        return;
    }

    localStorage.redmineURL = url;

    prepareTemplateData(url, ids).then(function(data) {
        $('#cards').html( template(data) );
    });
}

function init() {
    $('#url').val( localStorage.redmineURL || '' );
    $('#submit').click(generateCards);
}

function prepareTemplateData(url, ids) {
    var api = new RedmineAPI({ url: url });

    var issuesPromises = ids.map(function(id) {
        return api.getIssueById(id);
    } );

    return Promise.all(issuesPromises).then(function(issues) {
        return { issues: splitArray(issues,2) };
    }).catch(console.error);
}

function splitArray(array, step) {
    var newArray = [];

    for (var i = 0; i < array.length; i+= step) {
        var newSubArray = [];

        for (var j = i; j < i+step; j++) {
            if (j>array.length) break;

            newSubArray.push(array[j]);
        };

        newArray.push(newSubArray);
    }

    return newArray;
}<|endoftext|>


<commit_before>// @formatter:off
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

//ga('create', 'UA-9183424-2', 'auto');
ga('create', '##', 'auto');
ga('set', 'checkProtocolTask', function(){}); // Removes failing protocol check. See: http://stackoverflow.com/a/22152353/1958200
ga('require', 'displayfeatures');
ga('send', 'pageview', '/pages/background.html');
// @formatter:on

ga('send', 'event', 'extension_version', chrome.app.getDetails().version);

function handleUpgrade() {
    var previousVersion = localStorage['version'],
        currentVersion = chrome.app.getDetails().version;

    if (currentVersion != previousVersion) {
        if (typeof previousVersion == 'undefined') {
            // New installation
        } else {
            // Upgrade

            if (previousVersion.substr(0, 1) == '1') {
                SaveFormFillerOptions(FormFillerDefaultOptions());
            }
            else {
                var options = GetFormFillerOptions();

                if (options.triggerClickEvents === undefined) {
                    options.triggerClickEvents = false;
                }

                if (options.ignoreFieldsWithContent === undefined) {
                    options.ignoreFieldsWithContent = false;
                }

                if (options.passwordSettings.mode === undefined) {
                    var random = options.passwordSettings.random === true;
                    options.passwordSettings.mode = random ? 'random' : 'defined';
                }

                if (options.enableContextMenu === undefined) {
                    options.enableContextMenu = true;
                }

                if (options.fieldMatchSettings === undefined) {
                    options.fieldMatchSettings = {
                        matchLabel: false,
                        matchId: true,
                        matchName: true,
                        matchClass: true
                    };
                }

                SaveFormFillerOptions(options);
            }
        }
    }

    localStorage['version'] = currentVersion;
}

handleUpgrade();
CreateContextMenus();

chrome.browserAction.onClicked.addListener(function () {
    ga('send', 'event', 'extension_button', 'click');
    chrome.tabs.executeScript(null, { code: 'if (window.formFiller) { window.formFiller.fillAllInputs(); }', allFrames: true })
});

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    if (request == 'getOptions') {
        sendResponse({options: GetFormFillerOptions()});
    }
});

chrome.contextMenus.onClicked.addListener(function (info, tab) {
    if (info.menuItemId === 'all') {
        ga('send', 'event', 'extension_context_menu', 'fill_all_inputs');
        chrome.tabs.executeScript(null, { code: 'if (window.formFiller) { window.formFiller.fillAllInputs(); }', allFrames: true })
    }
    if (info.menuItemId === 'form') {
        ga('send', 'event', 'extension_context_menu', 'fill_this_form');
        chrome.tabs.executeScript(null, { code: 'if (window.formFiller) { window.formFiller.fillThisForm(); }', allFrames: true })
    }
    if (info.menuItemId === 'input') {
        ga('send', 'event', 'extension_context_menu', 'fill_this_input');
        chrome.tabs.executeScript(null, { code: 'if (window.formFiller) { window.formFiller.fillThisInput(); }', allFrames: true })
    }
});

//Shortcut listner
chrome.commands.onCommand.addListener(function(command) {
    ga('send', 'event', 'extension_button', 'shortcut');
    chrome.tabs.executeScript(null, { code: 'if (window.formFiller) { window.formFiller.fillAllInputs(); }', allFrames: true })
});
<commit_msg>Little refactor, looks better..<commit_after>// @formatter:off
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

//ga('create', 'UA-9183424-2', 'auto');
ga('create', '##', 'auto');
ga('set', 'checkProtocolTask', function(){}); // Removes failing protocol check. See: http://stackoverflow.com/a/22152353/1958200
ga('require', 'displayfeatures');
ga('send', 'pageview', '/pages/background.html');
// @formatter:on

ga('send', 'event', 'extension_version', chrome.app.getDetails().version);

function handleUpgrade() {
    var previousVersion = localStorage['version'],
        currentVersion = chrome.app.getDetails().version;

    if (currentVersion != previousVersion) {
        if (typeof previousVersion != 'undefined') {// If not new instalation then upgrade

            if (previousVersion.substr(0, 1) == '1') {
                SaveFormFillerOptions(FormFillerDefaultOptions());
            }
            else {
                var options = GetFormFillerOptions();

                if (options.triggerClickEvents === undefined) {
                    options.triggerClickEvents = false;
                }

                if (options.ignoreFieldsWithContent === undefined) {
                    options.ignoreFieldsWithContent = false;
                }

                if (options.passwordSettings.mode === undefined) {
                    var random = options.passwordSettings.random === true;
                    options.passwordSettings.mode = random ? 'random' : 'defined';
                }

                if (options.enableContextMenu === undefined) {
                    options.enableContextMenu = true;
                }

                if (options.fieldMatchSettings === undefined) {
                    options.fieldMatchSettings = {
                        matchLabel: false,
                        matchId: true,
                        matchName: true,
                        matchClass: true
                    };
                }

                SaveFormFillerOptions(options);
            }
        }
    }

    localStorage['version'] = currentVersion;
}

handleUpgrade();
CreateContextMenus();

chrome.browserAction.onClicked.addListener(function () {
    ga('send', 'event', 'extension_button', 'click');
    chrome.tabs.executeScript(null, { code: 'if (window.formFiller) { window.formFiller.fillAllInputs(); }', allFrames: true })
});

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    if (request == 'getOptions') {
        sendResponse({options: GetFormFillerOptions()});
    }
});

chrome.contextMenus.onClicked.addListener(function (info, tab) {
    if (info.menuItemId === 'all') {
        ga('send', 'event', 'extension_context_menu', 'fill_all_inputs');
        chrome.tabs.executeScript(null, { code: 'if (window.formFiller) { window.formFiller.fillAllInputs(); }', allFrames: true })
    }
    if (info.menuItemId === 'form') {
        ga('send', 'event', 'extension_context_menu', 'fill_this_form');
        chrome.tabs.executeScript(null, { code: 'if (window.formFiller) { window.formFiller.fillThisForm(); }', allFrames: true })
    }
    if (info.menuItemId === 'input') {
        ga('send', 'event', 'extension_context_menu', 'fill_this_input');
        chrome.tabs.executeScript(null, { code: 'if (window.formFiller) { window.formFiller.fillThisInput(); }', allFrames: true })
    }
});

//Shortcut listner
chrome.commands.onCommand.addListener(function(command) {
    ga('send', 'event', 'extension_button', 'shortcut');
    chrome.tabs.executeScript(null, { code: 'if (window.formFiller) { window.formFiller.fillAllInputs(); }', allFrames: true })
});
<|endoftext|>


<commit_before>
		function createPlanet() {

			var planetgeometry	= new THREE.IcosahedronGeometry(2, 4);
			var material	= new THREE.MeshLambertMaterial(
							{map: THREE.ImageUtils.loadTexture("images/TEWworld.jpg")});
			var mesh	= new THREE.Mesh( planetgeometry, material );
			scene.add( mesh );

			var atmopheregeometry	= new THREE.IcosahedronGeometry(2.05 , 4);
			var atmospherematerial	= new THREE.MeshLambertMaterial({
				map: THREE.ImageUtils.loadTexture("images/clouds.png"),
				color: 0xFFFFFF,
				transparent: true,
				//opacity: 1.0
				} );
			var atmospheremesh	= new THREE.Mesh( atmopheregeometry, atmospherematerial );
			scene.add( atmospheremesh );
			var hexgeometry	= new THREE.IcosahedronGeometry(2.01, 4);

			setHexUVs(hexgeometry);
			var material	= new THREE.MeshLambertMaterial({
				map: THREE.ImageUtils.loadTexture("images/hex02.png"),
				color: 0xFFFFFF,
				transparent: true,
				opacity: 0.2
				});
			var mesh	= new THREE.Mesh( hexgeometry, material );
			scene.add( mesh );

		}

		function drawSkyBox()  {

			var stargeometry = new THREE.IcosahedronGeometry(500 , 3);
			var starmaterial	= new THREE.MeshBasicMaterial({
				map: THREE.ImageUtils.loadTexture("images/MilkyWay.jpg"),
				side: THREE.BackSide,
				//color: 0xFFFFFF,
				//transparent: true,
				opacity: 1.0
				} );
			var starmesh	= new THREE.Mesh( stargeometry, starmaterial );
			scene.add( starmesh );

			return starmesh;
		}

		function createMoon() {

			var planetgeometry	= new THREE.IcosahedronGeometry(0.7, 4);
			var material	= new THREE.MeshLambertMaterial(
							{map: THREE.ImageUtils.loadTexture("images/moons/tethys.jpg")});
			var moonmesh	= new THREE.Mesh( planetgeometry, material );
			moonmesh.position.x = 15;
			moonmesh.position.y = 2;
			scene.add( moonmesh );

			var atmopheregeometry	= new THREE.IcosahedronGeometry(0.71 , 4);
			var atmospherematerial	= new THREE.MeshLambertMaterial({
				map: THREE.ImageUtils.loadTexture("images/clouds.png"),
				color: 0xFFFFFF,
				transparent: true,
				//opacity: 1.0
				} );
			var atmospheremesh	= new THREE.Mesh( atmopheregeometry, atmospherematerial );
			scene.add( atmospheremesh );
			var hexgeometry	= new THREE.IcosahedronGeometry(0.71, 4);

			setHexUVs(hexgeometry);
			var material	= new THREE.MeshLambertMaterial({
				map: THREE.ImageUtils.loadTexture("images/hex02.png"),
				color: 0xFFFFFF,
				transparent: true,
				opacity: 0.2
				});
			var moonmesh	= new THREE.Mesh( hexgeometry, material );
			moonmesh.position.x = 15;
			moonmesh.position.y = 2;

			scene.add( moonmesh );

		}

		function lights() {

			var light	= new THREE.DirectionalLight( 0xffffff );
			light.position.set( 450, 0, 0).normalize();
			scene.add( light );

		}

<commit_msg>Abstracted the createPlanet function<commit_after>
			function createPlanet(size) {

			var planetgeometry	= new THREE.IcosahedronGeometry(2, 4);
			var material	= new THREE.MeshLambertMaterial(
					{map: THREE.ImageUtils.loadTexture("images/TEWworld.jpg")});
			var mesh	= new THREE.Mesh( planetgeometry, material );
			//Scale the object to the size variable
			mesh.scale.x = size;
			mesh.scale.y = size;
			mesh.scale.z = size;
			scene.add( mesh );

			var atmopheregeometry	= new THREE.IcosahedronGeometry(2.05 , 4);
			var atmospherematerial	= new THREE.MeshLambertMaterial({
				map: THREE.ImageUtils.loadTexture("images/clouds.png"),
				color: 0xFFFFFF,
				transparent: true,
				//opacity: 1.0
				} );
			var atmospheremesh	= new THREE.Mesh( atmopheregeometry, atmospherematerial );
			//Scale the object to the size variable
			atmospheremesh.scale.x = size + 0.05;
			atmospheremesh.scale.y = size + 0.05;
			atmospheremesh.scale.z = size + 0.05;

			scene.add( atmospheremesh );
			var hexgeometry	= new THREE.IcosahedronGeometry(2.01, 4);

			setHexUVs(hexgeometry);
			var material	= new THREE.MeshLambertMaterial({
				map: THREE.ImageUtils.loadTexture("images/hex02.png"),
				color: 0xFFFFFF,
				transparent: true,
				opacity: 0.4
				});
			var hexmesh	= new THREE.Mesh( hexgeometry, material );
			hexmesh.scale.x = size + 0.05;
			hexmesh.scale.y = size + 0.05;
			hexmesh.scale.z = size + 0.05;

			scene.add( hexmesh );

		}

		function drawSkyBox()  {

			var stargeometry = new THREE.IcosahedronGeometry(500 , 3);
			var starmaterial	= new THREE.MeshBasicMaterial({
				map: THREE.ImageUtils.loadTexture("images/MilkyWay.jpg"),
				side: THREE.BackSide,
				//color: 0xFFFFFF,
				//transparent: true,
				opacity: 1.0
				} );
			var starmesh	= new THREE.Mesh( stargeometry, starmaterial );
			scene.add( starmesh );

			return starmesh;
		}

		function createMoon() {

			var planetgeometry	= new THREE.IcosahedronGeometry(0.7, 4);
			var material	= new THREE.MeshLambertMaterial(
							{map: THREE.ImageUtils.loadTexture("images/moons/tethys.jpg")});
			var moonmesh	= new THREE.Mesh( planetgeometry, material );
			moonmesh.position.x = 15;
			moonmesh.position.y = 2;
			scene.add( moonmesh );

			var atmopheregeometry	= new THREE.IcosahedronGeometry(0.71 , 4);
			var atmospherematerial	= new THREE.MeshLambertMaterial({
				map: THREE.ImageUtils.loadTexture("images/clouds.png"),
				color: 0xFFFFFF,
				transparent: true,
				//opacity: 1.0
				} );
			var atmospheremesh	= new THREE.Mesh( atmopheregeometry, atmospherematerial );
			scene.add( atmospheremesh );
			var hexgeometry	= new THREE.IcosahedronGeometry(0.71, 4);

			setHexUVs(hexgeometry);
			var material	= new THREE.MeshLambertMaterial({
				map: THREE.ImageUtils.loadTexture("images/hex02.png"),
				color: 0xFFFFFF,
				transparent: true,
				opacity: 0.2
				});
			var moonmesh	= new THREE.Mesh( hexgeometry, material );
			moonmesh.position.x = 15;
			moonmesh.position.y = 2;

			scene.add( moonmesh );

		}

		function lights() {

			var light	= new THREE.DirectionalLight( 0xffffff );
			light.position.set( 450, 0, 0).normalize();
			scene.add( light );

		}

<|endoftext|>


<commit_before>var socket = undefined
var userName = undefined

function getUserName() {
    if (userName) return userName
    userName = document.getElementById( 'userName' ).value
    return userName
}

function message(obj) {
    var el = document.createElement('p')
      , chat = document.getElementById( 'chat' )

    if ('announcement' in obj) {
        el.innerHTML = '' + esc(obj.announcement) + ''
    }
    else if ('message' in obj) {
        var vals = obj.message
        el.innerHTML = '' + esc(vals.userName) + ': ' + esc(vals.message)
    }
    chat.appendChild(el)
    chat.scrollTop = 1000000
}

function send() {
    var val = document.getElementById('text').value
      , nameVal = getUserName()
      , userName = (nameVal === '') ? 'Default' : nameVal

    socket.send({ event : 'user_message', message : {'userName' : userName, 'message' : val} })
    message({ event : 'user_message', message : {'message': val, userName: 'you' } })
    document.getElementById('text').value = ''
}

function esc(msg) {
    return String(msg).replace(/</g, '<').replace(/>/g, '>')
}

function sendUserName() {
    var userName = getUserName()
    socket.send({ event : 'user_connected', userName : userName, announcement : userName + " entered the chat room." })
}

function setUp() {
    var port = document.getElementById( 'tePort' ).value
    socket = new io.Socket(null, {port: parseInt( port, 10 ) || 80, rememberTransport: false})
    socket.connect()
    socket.on('message', function(obj) {
        if (obj.event === 'user_error_duplicate') {
            message(obj)
            // send user back to login page with message.
            window.location.href = '/?error=dupe'
            return
        }
        if ('buffer' in obj) {
            document.getElementById('form').style.display='block'
            document.getElementById('chat').innerHTML = ''

            for (var i in obj.buffer) {
                message(obj.buffer[i])
            }
        }
        else {
            message(obj)
        }
    })

    sendUserName()
}

document.addEventListener( "DOMContentLoaded", setUp, false)
<commit_msg>Change for "userName".<commit_after>var socket = undefined

function getUserName() {
    return document.getElementById( 'userName' ).value
}

function message(obj) {
    var el = document.createElement('p')
      , chat = document.getElementById( 'chat' )

    if ('announcement' in obj) {
        el.innerHTML = '' + esc(obj.announcement) + ''
    }
    else if ('message' in obj) {
        var vals = obj.message
        el.innerHTML = '' + esc(vals.userName) + ': ' + esc(vals.message)
    }
    chat.appendChild(el)
    chat.scrollTop = 1000000
}

function send() {
    var val = document.getElementById('text').value
      , nameVal = getUserName()
      , userName = (nameVal === '') ? 'Default' : nameVal

    socket.send({ event : 'user_message', message : {'userName' : userName, 'message' : val} })
    message({ event : 'user_message', message : {'message': val, userName: 'you' } })
    document.getElementById('text').value = ''
}

function esc(msg) {
    return String(msg).replace(/</g, '<').replace(/>/g, '>')
}

function sendUserName() {
    var userName = getUserName()
    socket.send({ event : 'user_connected', 'userName' : userName, announcement : userName + " entered the chat room." })
}

function setUp() {
    var port = document.getElementById( 'tePort' ).value
    socket = new io.Socket(null, {port: parseInt( port, 10 ) || 80, rememberTransport: false})
    socket.connect()
    socket.on('message', function(obj) {
        if (obj.event === 'user_error_duplicate') {
            message(obj)
            // send user back to login page with message.
            window.location.href = '/?error=dupe'
            return
        }
        if ('buffer' in obj) {
            document.getElementById('form').style.display='block'
            document.getElementById('chat').innerHTML = ''

            for (var i in obj.buffer) {
                message(obj.buffer[i])
            }
        }
        else {
            message(obj)
        }
    })

    sendUserName()
}

document.addEventListener( "DOMContentLoaded", setUp, false)
<|endoftext|>


<commit_before>function bbs(n) {
    // Blum Bluh Shub CSPRNG
    var p = 3181331; // prime
    var q = 943756159; // prime
    var x = Math.floor(Math.random() * Math.pow(2,32)); // seed
    var a = new Uint32Array(n);

    // I'm not confident this will work. Untested.
    for(i=n; i--;} {
        if (x%(p*q) == 1 && (x != 0 || x != 1)) {
            a[a.length] = Math.pow(x,2)%(p*q);
        } else {
            bbs();
        }
    }

    return a;
}

function make_key() {
    var text = "";
    var possible =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
    random_array = new Uint32Array(22);

    // Make some attempt at preferring a strong CSPRNG first
    if (window.crypto && window.crypto.getRandomValues) {
        // Desktop Chrome 11.0, Firefox 21.0, Opera 15.0, Safari 3.1
        // Mobile Chrome 23, Firefox 21.0, iOS 6
        window.crypto.getRandomValues(random_array);
    }
    else if (window.msCrypto && window.msCrypto.getRandomValues) {
        // IE 11
        window.msCrypto.getRandomValues(random_array);
    }
    else {
        // Android browser, IE Mobile, Opera Mobile, older desktop browsers
        for(i=22; i--;) {
            random_array[i] = Math.floor(Math.random() * Math.pow(2, 32));
        }

    }

    for(i=22; i--;) {
        text += possible.charAt(Math.floor(random_array[i] % possible.length));
    }

    return text;
}

function please_wait() {
    span = document.getElementById('progress');
    span.style.visibility = 'visible';
}

function validate_form() {
    if(document.getElementById('paste').value == "") {
        alert("You need to enter a message.");
        return false;
    }
    else {
        please_wait();
        setTimeout(function(){},0);
        validate_token(fingerprint);
        return true;
    }
}
<commit_msg>speed up the bbs() function greatly by taking the check out of the loop<commit_after>function bbs(n) {
    // Blum Bluh Shub CSPRNG
    var p = 3181331; // prime
    var q = 943756159; // prime
    var s = Math.floor(Math.random() * Math.pow(2,32)); // seed
    var a = new Uint32Array(n);

    if (s%(p*q) != 1 || s == 0 || s == 1) {
        bbs();
    }

    // I'm not confident this will work. Untested.
    for(i=n; i--;} {
        a[a.length] = Math.pow(s,2)%(p*q);
    }

    return a;
}

function make_key() {
    var text = "";
    var possible =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
    random_array = new Uint32Array(22);

    // Make some attempt at preferring a strong CSPRNG first
    if (window.crypto && window.crypto.getRandomValues) {
        // Desktop Chrome 11.0, Firefox 21.0, Opera 15.0, Safari 3.1
        // Mobile Chrome 23, Firefox 21.0, iOS 6
        window.crypto.getRandomValues(random_array);
    }
    else if (window.msCrypto && window.msCrypto.getRandomValues) {
        // IE 11
        window.msCrypto.getRandomValues(random_array);
    }
    else {
        // Android browser, IE Mobile, Opera Mobile, older desktop browsers
        for(i=22; i--;) {
            random_array[i] = Math.floor(Math.random() * Math.pow(2, 32));
        }

    }

    for(i=22; i--;) {
        text += possible.charAt(Math.floor(random_array[i] % possible.length));
    }

    return text;
}

function please_wait() {
    span = document.getElementById('progress');
    span.style.visibility = 'visible';
}

function validate_form() {
    if(document.getElementById('paste').value == "") {
        alert("You need to enter a message.");
        return false;
    }
    else {
        please_wait();
        setTimeout(function(){},0);
        validate_token(fingerprint);
        return true;
    }
}
<|endoftext|>


<commit_before>/*
   Copyright 2014 Nebez Briefkani
   floppybird - main.js

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

var debugmode = false;

var states = Object.freeze({
   SplashScreen: 0,
   GameScreen: 1,
   ScoreScreen: 2
});

var currentstate;

var gravity = 0.25;
var velocity = 0;
var position = 180;
var rotation = 0;
var jump = -4.6;
var flyArea = $("#flyarea").height();

var score = 0;
var highscore = 0;

var pipeheight = 90;
var pipewidth = 52;
var pipes = new Array();

var replayclickable = false;

//sounds
var volume = 30;
var soundJump = new buzz.sound("assets/sounds/sfx_wing.ogg");
var soundScore = new buzz.sound("assets/sounds/sfx_point.ogg");
var soundHit = new buzz.sound("assets/sounds/sfx_hit.ogg");
var soundDie = new buzz.sound("assets/sounds/sfx_die.ogg");
var soundSwoosh = new buzz.sound("assets/sounds/sfx_swooshing.ogg");
buzz.all().setVolume(volume);

//loops
var loopGameloop;
var loopPipeloop;

$(document).ready(function() {
   if(window.location.search == "?debug")
      debugmode = true;
   if(window.location.search == "?easy")
      pipeheight = 200;

   //get the highscore
   var savedscore = getCookie("highscore");
   if(savedscore != "")
      highscore = parseInt(savedscore);

   //start with the splash screen
   showSplash();
});

function getCookie(cname)
{
   var name = cname + "=";
   var ca = document.cookie.split(';');
   for(var i=0; i<ca.length; i++)
   {
      var c = ca[i].trim();
      if (c.indexOf(name)==0) return c.substring(name.length,c.length);
   }
   return "";
}

function setCookie(cname,cvalue,exdays)
{
   var d = new Date();
   d.setTime(d.getTime()+(exdays*24*60*60*1000));
   var expires = "expires="+d.toGMTString();
   document.cookie = cname + "=" + cvalue + "; " + expires;
}

function showSplash()
{
   currentstate = states.SplashScreen;

   //set the defaults (again)
   velocity = 0;
   position = 180;
   rotation = 0;
   score = 0;

   //update the player in preparation for the next game
   $("#player").css({ y: 0, x: 0});
   updatePlayer($("#player"));

   soundSwoosh.stop();
   soundSwoosh.play();

   //clear out all the pipes if there are any
   $(".pipe").remove();
   pipes = new Array();

   //make everything animated again
   $(".animated").css('animation-play-state', 'running');
   $(".animated").css('-webkit-animation-play-state', 'running');

   //fade in the splash
   $("#splash").transition({ opacity: 1 }, 2000, 'ease');
}

function startGame()
{
   currentstate = states.GameScreen;

   //fade out the splash
   $("#splash").stop();
   $("#splash").transition({ opacity: 0 }, 500, 'ease');

   //update the big score
   setBigScore();

   //debug mode?
   if(debugmode)
   {
      //show the bounding boxes
      $(".boundingbox").show();
   }

   //start up our loops
   var updaterate = 1000.0 / 60.0 ; //60 times a second
   loopGameloop = setInterval(gameloop, updaterate);
   loopPipeloop = setInterval(updatePipes, 1400);

   //jump from the start!
   playerJump();
}

function updatePlayer(player)
{
   //rotation
   rotation = Math.min((velocity / 10) * 90, 90);

   //apply rotation and position
   $(player).css({ rotate: rotation, top: position });
}

function gameloop() {
   var player = $("#player");

   //update the player speed/position
   velocity += gravity;
   position += velocity;

   //update the player
   updatePlayer(player);

   //create the bounding box
   var box = document.getElementById('player').getBoundingClientRect();
   var origwidth = 34.0;
   var origheight = 24.0;

   var boxwidth = origwidth - (Math.sin(Math.abs(rotation) / 90) * 8);
   var boxheight = (origheight + box.height) / 2;
   var boxleft = ((box.width - boxwidth) / 2) + box.left;
   var boxtop = ((box.height - boxheight) / 2) + box.top;
   var boxright = boxleft + boxwidth;
   var boxbottom = boxtop + boxheight;

   //if we're in debug mode, draw the bounding box
   if(debugmode)
   {
      var boundingbox = $("#playerbox");
      boundingbox.css('left', boxleft);
      boundingbox.css('top', boxtop);
      boundingbox.css('height', boxheight);
      boundingbox.css('width', boxwidth);
   }

   //did we hit the ground?
   if(box.bottom >= $("#land").offset().top)
   {
      playerDead();
      return;
   }

   //have they tried to escape through the ceiling? :o
   var ceiling = $("#ceiling");
   if(boxtop <= (ceiling.offset().top + ceiling.height()))
      position = 0;

   //we can't go any further without a pipe
   if(pipes[0] == null)
      return;

   //determine the bounding box of the next pipes inner area
   var nextpipe = pipes[0];
   var nextpipeupper = nextpipe.children(".pipe_upper");

   var pipetop = nextpipeupper.offset().top + nextpipeupper.height();
   var pipeleft = nextpipeupper.offset().left - 2; // for some reason it starts at the inner pipes offset, not the outer pipes.
   var piperight = pipeleft + pipewidth;
   var pipebottom = pipetop + pipeheight;

   if(debugmode)
   {
      var boundingbox = $("#pipebox");
      boundingbox.css('left', pipeleft);
      boundingbox.css('top', pipetop);
      boundingbox.css('height', pipeheight);
      boundingbox.css('width', pipewidth);
   }

   //have we gotten inside the pipe yet?
   if(boxright > pipeleft)
   {
      //we're within the pipe, have we passed between upper and lower pipes?
      if(boxtop > pipetop && boxbottom < pipebottom)
      {
         //yeah! we're within bounds

      }
      else
      {
         //no! we touched the pipe
         playerDead();
         return;
      }
   }

   //have we passed the imminent danger?
   if(boxleft > piperight)
   {
      //yes, remove it
      pipes.splice(0, 1);

      //and score a point
      playerScore();
   }
}

//Handle space bar
$(document).keydown(function(e){
   //space bar!
   if(e.keyCode == 32)
   {
      //in ScoreScreen, hitting space should click the "replay" button. else it's just a regular spacebar hit
      if(currentstate == states.ScoreScreen)
         $("#replay").click();
      else
         screenClick();
   }
});

//Handle mouse down OR touch start
if("ontouchstart" in window)
   $(document).on("touchstart", screenClick);
else
   $(document).on("mousedown", screenClick);

function screenClick()
{
   if(currentstate == states.GameScreen)
   {
      playerJump();
   }
   else if(currentstate == states.SplashScreen)
   {
      startGame();
   }
}

function playerJump()
{
   velocity = jump;
   //play jump sound
   soundJump.stop();
   soundJump.play();
}

function setBigScore(erase)
{
   var elemscore = $("#bigscore");
   elemscore.empty();

   if(erase)
      return;

   var digits = score.toString().split('');
   for(var i = 0; i < digits.length; i++)
      elemscore.append("");
}

function setSmallScore()
{
   var elemscore = $("#currentscore");
   elemscore.empty();

   var digits = score.toString().split('');
   for(var i = 0; i < digits.length; i++)
      elemscore.append("");
}

function setHighScore()
{
   var elemscore = $("#highscore");
   elemscore.empty();

   var digits = highscore.toString().split('');
   for(var i = 0; i < digits.length; i++)
      elemscore.append("");
}

function setMedal()
{
   var elemmedal = $("#medal");
   elemmedal.empty();

   if(score < 10)
      //signal that no medal has been won
      return false;

   if(score >= 10)
      medal = "bronze";
   if(score >= 20)
      medal = "silver";
   if(score >= 30)
      medal = "gold";
   if(score >= 40)
      medal = "platinum";

   elemmedal.append('');

   //signal that a medal has been won
   return true;
}

function playerDead()
{
   //stop animating everything!
   $(".animated").css('animation-play-state', 'paused');
   $(".animated").css('-webkit-animation-play-state', 'paused');

   //drop the bird to the floor
   var playerbottom = $("#player").position().top + $("#player").width(); //we use width because he'll be rotated 90 deg
   var floor = flyArea;
   var movey = Math.max(0, floor - playerbottom);
   $("#player").transition({ y: movey + 'px', rotate: 90}, 1000, 'easeInOutCubic');

   //it's time to change states. as of now we're considered ScoreScreen to disable left click/flying
   currentstate = states.ScoreScreen;

   //destroy our gameloops
   clearInterval(loopGameloop);
   clearInterval(loopPipeloop);
   loopGameloop = null;
   loopPipeloop = null;

   //mobile browsers don't support buzz bindOnce event
   if(isIncompatible.any())
   {
      //skip right to showing score
      showScore();
   }
   else
   {
      //play the hit sound (then the dead sound) and then show score
      soundHit.play().bindOnce("ended", function() {
         soundDie.play().bindOnce("ended", function() {
            showScore();
         });
      });
   }
}

function showScore()
{
   //unhide us
   $("#scoreboard").css("display", "block");

   //remove the big score
   setBigScore(true);

   //have they beaten their high score?
   if(score > highscore)
   {
      //yeah!
      highscore = score;
      //save it!
      setCookie("highscore", highscore, 999);
   }

   //update the scoreboard
   setSmallScore();
   setHighScore();
   var wonmedal = setMedal();

   //SWOOSH!
   soundSwoosh.stop();
   soundSwoosh.play();

   //show the scoreboard
   $("#scoreboard").css({ y: '40px', opacity: 0 }); //move it down so we can slide it up
   $("#replay").css({ y: '40px', opacity: 0 });
   $("#scoreboard").transition({ y: '0px', opacity: 1}, 600, 'ease', function() {
      //When the animation is done, animate in the replay button and SWOOSH!
      soundSwoosh.stop();
      soundSwoosh.play();
      $("#replay").transition({ y: '0px', opacity: 1}, 600, 'ease');

      //also animate in the MEDAL! WOO!
      if(wonmedal)
      {
         $("#medal").css({ scale: 2, opacity: 0 });
         $("#medal").transition({ opacity: 1, scale: 1 }, 1200, 'ease');
      }
   });

   //make the replay button clickable
   replayclickable = true;
}

$("#replay").click(function() {
   //make sure we can only click once
   if(!replayclickable)
      return;
   else
      replayclickable = false;
   //SWOOSH!
   soundSwoosh.stop();
   soundSwoosh.play();

   //fade out the scoreboard
   $("#scoreboard").transition({ y: '-40px', opacity: 0}, 1000, 'ease', function() {
      //when that's done, display us back to nothing
      $("#scoreboard").css("display", "none");

      //start the game over!
      showSplash();
   });
});

function playerScore()
{
   score += 1;
   //play score sound
   soundScore.stop();
   soundScore.play();
   setBigScore();
}

function updatePipes()
{
   //Do any pipes need removal?
   $(".pipe").filter(function() { return $(this).position().left <= -100; }).remove()

   //add a new pipe (top height + bottom height  + pipeheight == flyArea) and put it in our tracker
   var padding = 80;
   var constraint = flyArea - pipeheight - (padding * 2); //double padding (for top and bottom)
   var topheight = Math.floor((Math.random()*constraint) + padding); //add lower padding
   var bottomheight = (flyArea - pipeheight) - topheight;
   var newpipe = $('

');
   $("#flyarea").append(newpipe);
   pipes.push(newpipe);
}

var isIncompatible = {
   Android: function() {
   return navigator.userAgent.match(/Android/i);
   },
   BlackBerry: function() {
   return navigator.userAgent.match(/BlackBerry/i);
   },
   iOS: function() {
   return navigator.userAgent.match(/iPhone|iPad|iPod/i);
   },
   Opera: function() {
   return navigator.userAgent.match(/Opera Mini/i);
   },
   Safari: function() {
   return (navigator.userAgent.match(/OS X.*Safari/) && ! navigator.userAgent.match(/Chrome/));
   },
   Windows: function() {
   return navigator.userAgent.match(/IEMobile/i);
   },
   any: function() {
   return (isIncompatible.Android() || isIncompatible.BlackBerry() || isIncompatible.iOS() || isIncompatible.Opera() || isIncompatible.Safari() || isIncompatible.Windows());
   }
};<commit_msg>Add new boilerplate code for demo<commit_after>/*
   Copyright 2014 Nebez Briefkani
   floppybird - main.js

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

var debugmode = false;

var states = Object.freeze({
   SplashScreen: 0,
   GameScreen: 1,
   ScoreScreen: 2
});

var currentstate;

var gravity = 0.25;
var velocity = 0;
var position = 180;
var rotation = 0;
var jump = -4.6;
var flyArea = $("#flyarea").height();

var score = 0;
var highscore = 0;

var pipeheight = 90;
var pipewidth = 52;
var pipes = new Array();

var replayclickable = false;

//sounds
var volume = 30;
var soundJump = new buzz.sound("assets/sounds/sfx_wing.ogg");
var soundScore = new buzz.sound("assets/sounds/sfx_point.ogg");
var soundHit = new buzz.sound("assets/sounds/sfx_hit.ogg");
var soundDie = new buzz.sound("assets/sounds/sfx_die.ogg");
var soundSwoosh = new buzz.sound("assets/sounds/sfx_swooshing.ogg");
buzz.all().setVolume(volume);

//loops
var loopGameloop;
var loopPipeloop;

// Variables for multiplayer
var playerId = getDeviceId();
var accessManager;
var syncClient;
var playersMap;
var flyarea = document.getElementById('flyarea');

$(document).ready(function() {

  if(window.location.search == "?debug")
     debugmode = true;
  if(window.location.search == "?easy")
     pipeheight = 200;

  //get the highscore
  var savedscore = getCookie("highscore");
  if(savedscore != "")
     highscore = parseInt(savedscore);

  //start with the splash screen
  showSplash();
});

// Creates a new div for a bird on the screen. Returns this div.
function createBird() {
  var div = document.createElement('div');
  div.id = item.key;
  div.className = 'bird animated';
  div.style.left = `${Math.floor(Math.random() * 600)}px`;
  return div;
}

function getCookie(cname)
{
   var name = cname + "=";
   var ca = document.cookie.split(';');
   for(var i=0; i<ca.length; i++)
   {
      var c = ca[i].trim();
      if (c.indexOf(name)==0) return c.substring(name.length,c.length);
   }
   return "";
}

function setCookie(cname,cvalue,exdays)
{
   var d = new Date();
   d.setTime(d.getTime()+(exdays*24*60*60*1000));
   var expires = "expires="+d.toGMTString();
   document.cookie = cname + "=" + cvalue + "; " + expires;
}

function showSplash()
{
   currentstate = states.SplashScreen;

   //set the defaults (again)
   velocity = 0;
   position = 180;
   rotation = 0;
   score = 0;

   //update the player in preparation for the next game
   $("#player").css({ y: 0, x: 0});
   updatePlayer($("#player"));

   soundSwoosh.stop();
   soundSwoosh.play();

   //clear out all the pipes if there are any
   $(".pipe").remove();
   pipes = new Array();

   //make everything animated again
   $(".animated").css('animation-play-state', 'running');
   $(".animated").css('-webkit-animation-play-state', 'running');

   //fade in the splash
   $("#splash").transition({ opacity: 1 }, 2000, 'ease');
}

function startGame()
{
   currentstate = states.GameScreen;

   //fade out the splash
   $("#splash").stop();
   $("#splash").transition({ opacity: 0 }, 500, 'ease');

   //update the big score
   setBigScore();

   //debug mode?
   if(debugmode)
   {
      //show the bounding boxes
      $(".boundingbox").show();
   }

   //start up our loops
   var updaterate = 1000.0 / 60.0 ; //60 times a second
   loopGameloop = setInterval(gameloop, updaterate);
   loopPipeloop = setInterval(updatePipes, 1400);

   //jump from the start!
   playerJump();
}

function updatePlayer(player)
{
   //rotation
   rotation = Math.min((velocity / 10) * 90, 90);

   //apply rotation and position
   $(player).css({ rotate: rotation, top: position });
}

function gameloop() {
   var player = $("#player");

   //update the player speed/position
   velocity += gravity;
   position += velocity;

   //update the player
   updatePlayer(player);

   //create the bounding box
   var box = document.getElementById('player').getBoundingClientRect();
   var origwidth = 34.0;
   var origheight = 24.0;

   var boxwidth = origwidth - (Math.sin(Math.abs(rotation) / 90) * 8);
   var boxheight = (origheight + box.height) / 2;
   var boxleft = ((box.width - boxwidth) / 2) + box.left;
   var boxtop = ((box.height - boxheight) / 2) + box.top;
   var boxright = boxleft + boxwidth;
   var boxbottom = boxtop + boxheight;

   //if we're in debug mode, draw the bounding box
   if(debugmode)
   {
      var boundingbox = $("#playerbox");
      boundingbox.css('left', boxleft);
      boundingbox.css('top', boxtop);
      boundingbox.css('height', boxheight);
      boundingbox.css('width', boxwidth);
   }

   //did we hit the ground?
   if(box.bottom >= $("#land").offset().top)
   {
      playerDead();
      return;
   }

   //have they tried to escape through the ceiling? :o
   var ceiling = $("#ceiling");
   if(boxtop <= (ceiling.offset().top + ceiling.height()))
      position = 0;

   //we can't go any further without a pipe
   if(pipes[0] == null)
      return;

   //determine the bounding box of the next pipes inner area
   var nextpipe = pipes[0];
   var nextpipeupper = nextpipe.children(".pipe_upper");

   var pipetop = nextpipeupper.offset().top + nextpipeupper.height();
   var pipeleft = nextpipeupper.offset().left - 2; // for some reason it starts at the inner pipes offset, not the outer pipes.
   var piperight = pipeleft + pipewidth;
   var pipebottom = pipetop + pipeheight;

   if(debugmode)
   {
      var boundingbox = $("#pipebox");
      boundingbox.css('left', pipeleft);
      boundingbox.css('top', pipetop);
      boundingbox.css('height', pipeheight);
      boundingbox.css('width', pipewidth);
   }

   //have we gotten inside the pipe yet?
   if(boxright > pipeleft)
   {
      //we're within the pipe, have we passed between upper and lower pipes?
      if(boxtop > pipetop && boxbottom < pipebottom)
      {
         //yeah! we're within bounds

      }
      else
      {
         //no! we touched the pipe
         playerDead();
         return;
      }
   }

   //have we passed the imminent danger?
   if(boxleft > piperight)
   {
      //yes, remove it
      pipes.splice(0, 1);

      //and score a point
      playerScore();
   }
}

//Handle space bar
$(document).keydown(function(e){
   //space bar!
   if(e.keyCode == 32)
   {
      //in ScoreScreen, hitting space should click the "replay" button. else it's just a regular spacebar hit
      if(currentstate == states.ScoreScreen)
         $("#replay").click();
      else
         screenClick();
   }
});

//Handle mouse down OR touch start
if("ontouchstart" in window)
   $(document).on("touchstart", screenClick);
else
   $(document).on("mousedown", screenClick);

function screenClick()
{
   if(currentstate == states.GameScreen)
   {
      playerJump();
   }
   else if(currentstate == states.SplashScreen)
   {
      startGame();
   }
}

function playerJump()
{
   velocity = jump;
   //play jump sound
   soundJump.stop();
   soundJump.play();
}

function setBigScore(erase)
{
   var elemscore = $("#bigscore");
   elemscore.empty();

   if(erase)
      return;

   var digits = score.toString().split('');
   for(var i = 0; i < digits.length; i++)
      elemscore.append("");
}

function setSmallScore()
{
   var elemscore = $("#currentscore");
   elemscore.empty();

   var digits = score.toString().split('');
   for(var i = 0; i < digits.length; i++)
      elemscore.append("");
}

function setHighScore()
{
   var elemscore = $("#highscore");
   elemscore.empty();

   var digits = highscore.toString().split('');
   for(var i = 0; i < digits.length; i++)
      elemscore.append("");
}

function setMedal()
{
   var elemmedal = $("#medal");
   elemmedal.empty();

   if(score < 10)
      //signal that no medal has been won
      return false;

   if(score >= 10)
      medal = "bronze";
   if(score >= 20)
      medal = "silver";
   if(score >= 30)
      medal = "gold";
   if(score >= 40)
      medal = "platinum";

   elemmedal.append('');

   //signal that a medal has been won
   return true;
}

function playerDead()
{
   //stop animating everything!
   $(".animated").css('animation-play-state', 'paused');
   $(".animated").css('-webkit-animation-play-state', 'paused');

   //drop the bird to the floor
   var playerbottom = $("#player").position().top + $("#player").width(); //we use width because he'll be rotated 90 deg
   var floor = flyArea;
   var movey = Math.max(0, floor - playerbottom);
   $("#player").transition({ y: movey + 'px', rotate: 90}, 1000, 'easeInOutCubic');

   //it's time to change states. as of now we're considered ScoreScreen to disable left click/flying
   currentstate = states.ScoreScreen;

   //destroy our gameloops
   clearInterval(loopGameloop);
   clearInterval(loopPipeloop);
   loopGameloop = null;
   loopPipeloop = null;

   //mobile browsers don't support buzz bindOnce event
   if(isIncompatible.any())
   {
      //skip right to showing score
      showScore();
   }
   else
   {
      //play the hit sound (then the dead sound) and then show score
      soundHit.play().bindOnce("ended", function() {
         soundDie.play().bindOnce("ended", function() {
            showScore();
         });
      });
   }
}

function showScore()
{
   //unhide us
   $("#scoreboard").css("display", "block");

   //remove the big score
   setBigScore(true);

   //have they beaten their high score?
   if(score > highscore)
   {
      //yeah!
      highscore = score;
      //save it!
      setCookie("highscore", highscore, 999);
   }

   //update the scoreboard
   setSmallScore();
   setHighScore();
   var wonmedal = setMedal();

   //SWOOSH!
   soundSwoosh.stop();
   soundSwoosh.play();

   //show the scoreboard
   $("#scoreboard").css({ y: '40px', opacity: 0 }); //move it down so we can slide it up
   $("#replay").css({ y: '40px', opacity: 0 });
   $("#scoreboard").transition({ y: '0px', opacity: 1}, 600, 'ease', function() {
      //When the animation is done, animate in the replay button and SWOOSH!
      soundSwoosh.stop();
      soundSwoosh.play();
      $("#replay").transition({ y: '0px', opacity: 1}, 600, 'ease');

      //also animate in the MEDAL! WOO!
      if(wonmedal)
      {
         $("#medal").css({ scale: 2, opacity: 0 });
         $("#medal").transition({ opacity: 1, scale: 1 }, 1200, 'ease');
      }
   });

   //make the replay button clickable
   replayclickable = true;
}

$("#replay").click(function() {
   //make sure we can only click once
   if(!replayclickable)
      return;
   else
      replayclickable = false;
   //SWOOSH!
   soundSwoosh.stop();
   soundSwoosh.play();

   //fade out the scoreboard
   $("#scoreboard").transition({ y: '-40px', opacity: 0}, 1000, 'ease', function() {
      //when that's done, display us back to nothing
      $("#scoreboard").css("display", "none");

      //start the game over!
      showSplash();
   });
});

function playerScore()
{
   score += 1;
   //play score sound
   soundScore.stop();
   soundScore.play();
   setBigScore();
}

function updatePipes()
{
   //Do any pipes need removal?
   $(".pipe").filter(function() { return $(this).position().left <= -100; }).remove()

   //add a new pipe (top height + bottom height  + pipeheight == flyArea) and put it in our tracker
   var padding = 80;
   var constraint = flyArea - pipeheight - (padding * 2); //double padding (for top and bottom)
   var topheight = Math.floor((Math.random()*constraint) + padding); //add lower padding
   var bottomheight = (flyArea - pipeheight) - topheight;
   var newpipe = $('

');
   $("#flyarea").append(newpipe);
   pipes.push(newpipe);
}

var isIncompatible = {
   Android: function() {
   return navigator.userAgent.match(/Android/i);
   },
   BlackBerry: function() {
   return navigator.userAgent.match(/BlackBerry/i);
   },
   iOS: function() {
   return navigator.userAgent.match(/iPhone|iPad|iPod/i);
   },
   Opera: function() {
   return navigator.userAgent.match(/Opera Mini/i);
   },
   Safari: function() {
   return (navigator.userAgent.match(/OS X.*Safari/) && ! navigator.userAgent.match(/Chrome/));
   },
   Windows: function() {
   return navigator.userAgent.match(/IEMobile/i);
   },
   any: function() {
   return (isIncompatible.Android() || isIncompatible.BlackBerry() || isIncompatible.iOS() || isIncompatible.Opera() || isIncompatible.Safari() || isIncompatible.Windows());
   }
};

function getDeviceId() {
  return 'browser-' +
    'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
      return v.toString(16);
    });
}
<|endoftext|>


<commit_before>$(function() {

	function get_series_data(data) {
		// append value after each label
		for (var i = 0; i < data.signal.length; ++i) {
			data.signal[i].label = data.signal[i].label + " = 0";
		}

		return data.signal;
	}

	var clear_status = false;
	var number_of_signal = 200;
	var connection_status = false;
	var plot = null;

	function init_draw(data) {

		plot = $.plot('#signal-plot', data, {
			series: {
				lines: { show: true, lineWidth: 1.5 },
				shadowSize: 0 },
			crosshair: { mode: "x" },
			grid: { hoverable: true, autoHighlight: false },
			xaxis: { show: false },
			yaxis: { min: -36000, max: 36000 },
			legend: { position: "sw" }
		});

	}

    // Websocket connection
    var ws = new WebSocket("ws://localhost:8888/ws");

    ws.onmessage = function (evt) {

		if (plot == null) {
			var data = JSON.parse(evt.data);
			data = get_series_data(data);
			init_draw(data);
		}

		if (!connection_status && !clear_status) {
			return;
		}

		var data = JSON.parse(evt.data);
		data = get_series_data(data);
		// set data for plot
		plot.setData(data);
		// redraw graph
		plot.draw();
		// uplate legend
		uplate_legend();

		clear_status = false;
	};

	var legends = $('#signal-plot .legendLabel');

	var latest_pos = null;
	var update_legend_timeout = null;

	function uplate_legend() {
		update_legend_timeout = null;
		var pos = latest_pos;

		var axes = plot.getAxes();

		if (pos.x < axes.xaxis.min || pos.x > axes.xaxis.max ||
			pos.y < axes.yaxis.min || pos.y > axes.yaxis.max) {
			return;
		}

		var dataset = plot.getData();

		for (var i = 0; i < dataset.length; ++i) {
			var series = dataset[i];

			var idx = Math.floor(pos.x);

			var p1 = series.data[idx], p2 = series.data[idx + 1];
			var ret = null;

			ret = (p1 == null) ? p2[1] : p1[1];
			var new_label = series.label.replace(/=.*/, "= " + ret);
			legends.eq(i).text(new_label);
		}
	};

	$('#signal-plot').bind("plothover", function (event, pos, iten) {
		latest_pos = pos;
		if (!update_legend_timeout) {
			update_legend_timeout = setTimeout(uplate_legend, 50);
		}
	});

	$('#clear-btn').click(function () {
		ws.send("clear");
		clear_status = true;
	});

	$('#status-btn').click(function () {
		// close connection
		if ($(this).hasClass('active')) {
			$(this).removeClass('active');
			$(this).empty();
			$(this).append("");
			connection_status = false;
			ws.send("pause");
		}
		// open connection
		else {
			$(this).addClass('active');
			$(this).empty();
			$(this).append("");
			connection_status = true;
			ws.send("play");
		}
	});

});
<commit_msg>make toggle effect of filter button work<commit_after>$(function() {

	function get_series_data(data) {
		// append value after each label
		for (var i = 0; i < data.signal.length; ++i) {
			data.signal[i].label = data.signal[i].label + " = 0";
		}

		return data.signal;
	}

	var clear_status = false;
	var number_of_signal = 200;
	var connection_status = false;
	var moving_average_status = false;
	var plot = null;

	function init_draw(data) {

		plot = $.plot('#signal-plot', data, {
			series: {
				lines: { show: true, lineWidth: 1.5 },
				shadowSize: 0 },
			crosshair: { mode: "x" },
			grid: { hoverable: true, autoHighlight: false },
			xaxis: { show: false },
			yaxis: { min: -36000, max: 36000 },
			legend: { position: "sw" }
		});

	}

    // Websocket connection
    var ws = new WebSocket("ws://localhost:8888/ws");

    ws.onmessage = function (evt) {

		if (plot == null) {
			var data = JSON.parse(evt.data);
			data = get_series_data(data);
			init_draw(data);
		}

		if (!connection_status && !clear_status) {
			return;
		}

		var data = JSON.parse(evt.data);
		data = get_series_data(data);
		// set data for plot
		plot.setData(data);
		// redraw graph
		plot.draw();
		// uplate legend
		uplate_legend();

		clear_status = false;
	};

	var legends = $('#signal-plot .legendLabel');

	var latest_pos = null;
	var update_legend_timeout = null;

	function uplate_legend() {
		update_legend_timeout = null;
		var pos = latest_pos;

		var axes = plot.getAxes();

		if (pos.x < axes.xaxis.min || pos.x > axes.xaxis.max ||
			pos.y < axes.yaxis.min || pos.y > axes.yaxis.max) {
			return;
		}

		var dataset = plot.getData();

		for (var i = 0; i < dataset.length; ++i) {
			var series = dataset[i];

			var idx = Math.floor(pos.x);

			var p1 = series.data[idx], p2 = series.data[idx + 1];
			var ret = null;

			ret = (p1 == null) ? p2[1] : p1[1];
			var new_label = series.label.replace(/=.*/, "= " + ret);
			legends.eq(i).text(new_label);
		}
	};

	$('#signal-plot').bind("plothover", function (event, pos, iten) {
		latest_pos = pos;
		if (!update_legend_timeout) {
			update_legend_timeout = setTimeout(uplate_legend, 50);
		}
	});

	$('#clear-btn').click(function () {
		ws.send("clear");
		clear_status = true;
	});

	$('#status-btn').click(function () {
		// close connection
		if ($(this).hasClass('active')) {
			$(this).removeClass('active');
			$(this).empty();
			$(this).append("");
			connection_status = false;
			ws.send("pause");
		}
		// open connection
		else {
			$(this).addClass('active');
			$(this).empty();
			$(this).append("");
			connection_status = true;
			ws.send("play");
		}
	});

	$('#moving-average-filter').click(function () {
		if ($(this).hasClass('active')) {
			$(this).removeClass('active');
			moving_average_status = false;
		}
		else {
			$(this).addClass('active');
			moving_average_status = true;
		}
	});

});
<|endoftext|>


<commit_before>var App = {};

App.templates = {};

function getTmpl(name) {
  if(!App.templates[name]) {
    App.templates[name] = swig.compile($('#' + name).html(), {templateName: name});
  }
  return App.templates[name];
}

var Collection = Backbone.Collection.extend({

  initialize: function() {
    this.on('sync', function() {
      this.synced = true;
    }, this);
  },

  onSync: function(cb) {
    if(this.synced === true) {
      cb(this);
    } else {
      this.on('sync', cb);
    }
  }

});

App.Users = Collection.extend({
  url: 'http://localhost:8080/users'
});

App.Posts = Collection.extend({
  url: 'http://localhost:8080/posts'
});

App.Tags = Collection.extend({
  url: 'http://localhost:8080/tags'
});

App.Region = Backbone.View.extend({

  el: '#content',

  setContent: function(view) {
    this.$el.empty().append(view.$el);
  }

});

App.ListView = Backbone.View.extend({

  tagName: 'div',

  templateName: 'list',

  events: {
    'click .edit': 'onClick',
    'click .delete': 'onDelete',
    'click .quick-check': 'onQuickCheck'
  },

  initialize: function initialize(options) {
    this.name = options.name;
    this.columns = options.columns;
    this.collection = options.collection;
    this.tmpl = getTmpl(this.templateName);
  },

  render: function render() {
    var context = {
      'name': this.name,
      'columns': this.columns,
      'lines': this.collection.toJSON()
    };
    var html = this.tmpl(context);
    this.$el.empty().html(html);
  },

  selected: function selected() {
    var inputs = this.$el.find('.select');
    return _.chain(inputs)
      .filter(function(input) {
        return input.checked === true;
      })
      .map(function(input) {
        return parseInt($(input).data('id'), 10);
      })
      .value();
  },

  get: function(id) {
    return this.$el.find('[data-id="' + id + '"]');
  },

  onClick: function onClick(e) {
    var el = $(e.currentTarget).parent();
    App.router.navigate('posts/' + el.data('id'), {trigger: true});
  },

  onDelete: function() {
    this.trigger('delete', this.selected());
    return false;
  },

  onQuickCheck: function onQuickCheck(e) {
    var el = $(e.currentTarget);
    var id = el.data('id');
    var attribute = el.data('attribute');
    var checked = el.prop('checked');

    var model = this.collection.get(id);
    model.set(attribute, checked);
    model.save();
  }

});

App.FormView = Backbone.View.extend({

  tagName: 'form',

  Text: function(name, attributes) {
    return this.make('textarea', _.extend({name: name}, attributes));
  },

  String: function(name, attributes) {
    return this.make('input', _.extend({type: 'text', name: name}, attributes));
  },

  Boolean: function(name, attributes) {
    return this.make('input', _.extend({type: 'checkbox', name: name}, attributes));
  },

  initialize: function(options) {
    _.each(options.fields, this.render, this);
  },

  render: function(options, name) {
    var line = this.make('p');
    var label = this.make('label', {'for': name}, options.label);
    var input = this[options.type.name](name, options.attributes || {});
    $(line).append(label, input);
    this.$el.append(line);
  },

  getField: function(key) {
    return this.$el.find('[name="' + key + '"]');
  },

  load: function(model) {
    _.each(model.attributes, function(value, key) {
      var field = this.getField(key);
      if(typeof value === 'boolean') {
        field.prop('checked', value);
      } else {
        field.val(value);
      }
    }, this);
  }

});

App.MenuView = Backbone.View.extend({

  el: '#menu',

  unselectAll: function unselectAll() {
    this.$el.find('a').each(function(i, link) {
      $(link).removeClass('active');
    });
  },

  select: function select(hash) {
    this.unselectAll();
    this.$el.find('a[href="#' + hash + '"]').addClass('active');
  }

});

App.Router = Backbone.Router.extend({

  routes: {
    "posts":       "posts",
    "posts/:slug": "posts",
    "tags":        "tags",
    "tags/:slug":  "tags",
    "users":       "users",
    "users/:slug": "users"
  },

  initialize: function() {
    App.posts.fetch();
    App.tags.fetch();
    App.users.fetch();
  },

  posts: function(id) {
    if(id) {
      App.posts.onSync(function() {
        App.postForm.load(App.posts.get(id));
        App.region.setContent(App.postForm);
      });
    } else {
      App.region.setContent(App.postsView);
    }
  },

  tags: function(id) {
    if(id) {
      App.tags.onSync(function() {
        App.tagForm.load(App.tags.get(id));
        App.region.setContent(App.tagForm);
      })
    } else {
      App.region.setContent(App.tagsView);
    }
  },

  users: function(id) {
    if(id) {
      App.users.onSync(function() {
        App.userForm.load(App.users.get(id));
        App.region.setContent(App.userForm);
      });
    } else {
      App.region.setContent(App.usersView);
    }
  }

});

$(function() {
  var content = $('#content');

  function onResized() {
    content.css('height', document.height);
  }

  App.users = new App.Users();
  App.posts = new App.Posts();
  App.tags = new App.Tags();
  App.router = new App.Router();
  App.region = new App.Region();

  App.postForm = new App.FormView({
    fields: {
      title: {type: String, label: 'Title'},
      body: {type: Text, label: 'Body'},
      published: {type: Boolean, label: 'Published'}
    }
  });

  App.userForm = new App.FormView({
    fields: {
      username: {type: String, label: 'Username'},
      password: {type: String, label: 'Password', attributes: {'type': 'password'}},
      firstname: {type: String, label: 'First name'},
      lastname: {type: String, label: 'Last name'},
      email: {type: String, label: 'Email'},
      isStaff: {type: Boolean, label: 'Is staff'}
    }
  });

  App.tagForm = new App.FormView({
    fields: {
      title: {type: String, label: 'Title'}
    }
  });

  App.menuView = new App.MenuView;

  App.postsView = new App.ListView({
    collection: App.posts,
    name: 'posts',
    columns: [
      {'label': 'Title', 'value': 'title'},
      {'label': 'Created at', 'value': 'createdAt', 'type': 'date'},
      {'label': 'Published', 'value': 'published', 'type': 'bool'}
    ]
  });

  App.tagsView = new App.ListView({
    collection: App.tags,
    name: 'tags',
    columns: [
      {'label': 'Title', 'value': 'title'},
      {'label': 'Created at', 'value': 'createdAt', 'type': 'date'}
    ]
  });

  App.usersView = new App.ListView({
    collection: App.users,
    name: 'users',
    columns: [
      {'label': 'Username', 'value': 'username'},
      {'label': 'Created at', 'value': 'createdAt', 'type': 'date'},
      {'label': 'Is staff', 'value': 'isStaff', 'type': 'bool'}
    ]
  });

  App.router.on('all', function(route) {
   App.menuView.select(route.split(':')[1]);
  });

  App.users.on('sync', function(collection) {
    App.usersView.render();
    App.usersView.on('delete', function(ids) {
      ids.forEach(function(id) {
        collection.get(id).destroy();
      });
    });
  });

  App.users.on('destroy', function(model) {
    var view = App.usersView.get(model.id);
    view.remove();
  });

  App.posts.on('sync', function(collection) {
    App.postsView.render();
    App.postsView.on('delete', function(ids) {
      ids.forEach(function(id) {
        collection.get(id).destroy();
      });
    });
  });

  App.posts.on('destroy', function(model) {
    var view = App.postsView.get(model.id);
    view.remove();
  });

  App.tags.on('sync', function(collection) {
    App.tagsView.render();
    App.tagsView.on('delete', function(ids) {
      ids.forEach(function(id) {
        collection.get(id).destroy();
      });
    });
  });

  App.tags.on('destroy', function(model) {
    var view = App.tagsView.get(model.id);
    view.remove();
  });

  onResized();
  window.onresize = onResized;
  Backbone.history.start();
});<commit_msg>Fixed template<commit_after>var App = {};

App.templates = {};

function getTmpl(name) {
  if(!App.templates[name]) {
    App.templates[name] = swig.compile($('#' + name).html(), {templateName: name});
  }
  return App.templates[name];
}

var Collection = Backbone.Collection.extend({

  initialize: function() {
    this.on('sync', function() {
      this.synced = true;
    }, this);
  },

  onSync: function(cb) {
    if(this.synced === true) {
      cb(this);
    } else {
      this.on('sync', cb);
    }
  }

});

App.Users = Collection.extend({
  url: 'http://localhost:8080/users'
});

App.Posts = Collection.extend({
  url: 'http://localhost:8080/posts'
});

App.Tags = Collection.extend({
  url: 'http://localhost:8080/tags'
});

App.Region = Backbone.View.extend({

  el: '#content',

  setContent: function(view) {
    this.$el.empty().append(view.$el);
  }

});

App.ListView = Backbone.View.extend({

  tagName: 'div',

  templateName: 'list',

  events: {
    'click .edit': 'onClick',
    'click .delete': 'onDelete',
    'click .quick-check': 'onQuickCheck'
  },

  initialize: function initialize(options) {
    this.name = options.name;
    this.columns = options.columns;
    this.collection = options.collection;
    this.tmpl = getTmpl(this.templateName);
  },

  render: function render() {
    var context = {
      'name': this.name,
      'columns': this.columns,
      'lines': this.collection.toJSON()
    };
    var html = this.tmpl(context);
    this.$el.empty().html(html);
  },

  selected: function selected() {
    var inputs = this.$el.find('.select');
    return _.chain(inputs)
      .filter(function(input) {
        return input.checked === true;
      })
      .map(function(input) {
        return parseInt($(input).data('id'), 10);
      })
      .value();
  },

  get: function(id) {
    return this.$el.find('[data-id="' + id + '"]');
  },

  onClick: function onClick(e) {
    var el = $(e.currentTarget).parent();
    App.router.navigate('posts/' + el.data('id'), {trigger: true});
  },

  onDelete: function() {
    this.trigger('delete', this.selected());
    return false;
  },

  onQuickCheck: function onQuickCheck(e) {
    var el = $(e.currentTarget);
    var id = el.data('id');
    var attribute = el.data('attribute');
    var checked = el.prop('checked');

    var model = this.collection.get(id);
    model.set(attribute, checked);
    model.save();
  }

});

App.FormView = Backbone.View.extend({

  tagName: 'form',

  Text: function(name, attributes) {
    return this.make('textarea', _.extend({name: name}, attributes));
  },

  String: function(name, attributes) {
    return this.make('input', _.extend({type: 'text', name: name}, attributes));
  },

  Boolean: function(name, attributes) {
    return this.make('input', _.extend({type: 'checkbox', name: name}, attributes));
  },

  initialize: function(options) {
    var title = this.make('h1', {}, options.name);
    var submit = this.make('input', {type: 'submit'});

    this.$el.append(title);
    _.each(options.fields, this.render, this);
    this.$el.append(submit);
  },

  render: function(options, name) {
    var line = this.make('p');
    var label = this.make('label', {'for': name}, options.label);
    var input = this[options.type.name](name, options.attributes || {});

    $(line).append(label, input);
    this.$el.append(line);
  },

  getField: function(key) {
    return this.$el.find('[name="' + key + '"]');
  },

  load: function(model) {
    _.each(model.attributes, function(value, key) {
      var field = this.getField(key);
      if(typeof value === 'boolean') {
        field.prop('checked', value);
      } else {
        field.val(value);
      }
    }, this);
  }

});

App.MenuView = Backbone.View.extend({

  el: '#menu',

  unselectAll: function unselectAll() {
    this.$el.find('a').each(function(i, link) {
      $(link).removeClass('active');
    });
  },

  select: function select(hash) {
    this.unselectAll();
    this.$el.find('a[href="#' + hash + '"]').addClass('active');
  }

});

App.Router = Backbone.Router.extend({

  routes: {
    "posts":       "posts",
    "posts/:slug": "posts",
    "tags":        "tags",
    "tags/:slug":  "tags",
    "users":       "users",
    "users/:slug": "users"
  },

  initialize: function() {
    App.posts.fetch();
    App.tags.fetch();
    App.users.fetch();
  },

  posts: function(id) {
    if(id) {
      App.posts.onSync(function() {
        App.postForm.load(App.posts.get(id));
        App.region.setContent(App.postForm);
      });
    } else {
      App.region.setContent(App.postsView);
    }
  },

  tags: function(id) {
    if(id) {
      App.tags.onSync(function() {
        App.tagForm.load(App.tags.get(id));
        App.region.setContent(App.tagForm);
      })
    } else {
      App.region.setContent(App.tagsView);
    }
  },

  users: function(id) {
    if(id) {
      App.users.onSync(function() {
        App.userForm.load(App.users.get(id));
        App.region.setContent(App.userForm);
      });
    } else {
      App.region.setContent(App.usersView);
    }
  }

});

$(function() {
  var content = $('#content');

  function onResized() {
    content.css('height', document.height);
  }

  App.users = new App.Users();
  App.posts = new App.Posts();
  App.tags = new App.Tags();
  App.router = new App.Router();
  App.region = new App.Region();

  App.postForm = new App.FormView({
    name: 'Posts',
    fields: {
      title: {type: String, label: 'Title'},
      body: {type: Text, label: 'Body'},
      published: {type: Boolean, label: 'Published'}
    }
  });

  App.userForm = new App.FormView({
    name: 'Users',
    fields: {
      username: {type: String, label: 'Username'},
      password: {type: String, label: 'Password', attributes: {'type': 'password'}},
      firstname: {type: String, label: 'First name'},
      lastname: {type: String, label: 'Last name'},
      email: {type: String, label: 'Email'},
      isStaff: {type: Boolean, label: 'Is staff'}
    }
  });

  App.tagForm = new App.FormView({
    name: 'Tags',
    fields: {
      title: {type: String, label: 'Title'}
    }
  });

  App.menuView = new App.MenuView;

  App.postsView = new App.ListView({
    collection: App.posts,
    name: 'posts',
    columns: [
      {'label': 'Title', 'value': 'title'},
      {'label': 'Created at', 'value': 'createdAt', 'type': 'date'},
      {'label': 'Published', 'value': 'published', 'type': 'bool'}
    ]
  });

  App.tagsView = new App.ListView({
    collection: App.tags,
    name: 'tags',
    columns: [
      {'label': 'Title', 'value': 'title'},
      {'label': 'Created at', 'value': 'createdAt', 'type': 'date'}
    ]
  });

  App.usersView = new App.ListView({
    collection: App.users,
    name: 'users',
    columns: [
      {'label': 'Username', 'value': 'username'},
      {'label': 'Created at', 'value': 'createdAt', 'type': 'date'},
      {'label': 'Is staff', 'value': 'isStaff', 'type': 'bool'}
    ]
  });

  App.router.on('all', function(route) {
   App.menuView.select(route.split(':')[1]);
  });

  App.users.on('sync', function(collection) {
    App.usersView.render();
    App.usersView.on('delete', function(ids) {
      ids.forEach(function(id) {
        collection.get(id).destroy();
      });
    });
  });

  App.users.on('destroy', function(model) {
    var view = App.usersView.get(model.id);
    view.remove();
  });

  App.posts.on('sync', function(collection) {
    App.postsView.render();
    App.postsView.on('delete', function(ids) {
      ids.forEach(function(id) {
        collection.get(id).destroy();
      });
    });
  });

  App.posts.on('destroy', function(model) {
    var view = App.postsView.get(model.id);
    view.remove();
  });

  App.tags.on('sync', function(collection) {
    App.tagsView.render();
    App.tagsView.on('delete', function(ids) {
      ids.forEach(function(id) {
        collection.get(id).destroy();
      });
    });
  });

  App.tags.on('destroy', function(model) {
    var view = App.tagsView.get(model.id);
    view.remove();
  });

  onResized();
  window.onresize = onResized;
  Backbone.history.start();
});<|endoftext|>


<commit_before>var currentRate,
    currentSubIndex,
    editSub,
    firstScriptTag,
    nextSub,
    player,
    prevSub,
    rateIndex,
    rates,
    re = /=(.+)/,
    startCaption,
    sub,
    subtitleChangeInterval,
    subtitles,
    tag,
    timeEnd,
    timeStart,
    urlValue,
    videoData,
    videoDuration,
    videoID = '';

function onYouTubeIframeAPIReady() {
  player = new YT.Player('player', {
    height: '340',
    width: '560',
    videoId: videoID,
    playerVars: {
      'cc_load_policy': 1,
      'controls': 0
    },
    events: {
      'onReady': onPlayerReady,
    }
  });
}

function onPlayerReady(event) {
  rates = player.getAvailablePlaybackRates();
  currentRate = player.getPlaybackRate();
  rateIndex = rates.indexOf(currentRate);
  subtitleChangeInterval = setInterval(subtitleRefresh, 100);
  console.log(player.getDuration());
  $.getJSON('/video/youtube' + videoID, function(data) {
    videoData = data;
    subtitles = videoData.captions;
    $('.search-bar').hide();
    $('.main-button').hide();
    $('.shortcuts').fadeIn();
    $('.video-main').show();
    $('#player').show();
    $('#current-player-time').show();
    $('#overlay').show();
    $('#subtitles').show();
    // if (subtitles.length > 0) {
    $('.sub-prev').show();
    $('.sub-edit').show();
    $('.sub-next').show();
    $('.prev-head').show();
    $('.edit-head').show();
    $('.next-head').show();
    event.target.playVideo();
    // }
    // else {
    //   $('.transcription-area').show();
    //   $('.transcription-box').val(videoData.transcript);
    //   event.target.playVideo();
    // }
  });

  $('.sub-edit').focus(function() {
    player.pauseVideo();
  });
}

function pauseVideo() {
  if (player.getPlayerState() === 1) {
    player.pauseVideo();
  }
  else {
    player.playVideo();
  }
}

function slowdownVideo() {
  if (rateIndex > 0) {
    player.setPlaybackRate(rates[rateIndex-1]);
    rateIndex -= 1;
  }
}

function speedupVideo() {
  if (rateIndex < rates.length -1) {
    player.setPlaybackRate(rates[rateIndex+1]);
    rateIndex += 1;
  }
}

function rewindVideo() {
  player.seekTo((player.getCurrentTime()-2), true);
  player.playVideo();
  console.log(player.getCurrentTime());
}

function forwardVideo() {
  player.seekTo((player.getCurrentTime()+2), true);
  player.playVideo();
  console.log(player.getCurrentTime());
}

Mousetrap.bind('ctrl+1', pauseVideo);
Mousetrap.bind('ctrl+4', slowdownVideo);
Mousetrap.bind('ctrl+5', speedupVideo);
Mousetrap.bind('ctrl+2', rewindVideo);
Mousetrap.bind('ctrl+3', forwardVideo);
Mousetrap.bind('ctrl+shift+s', saveCaption);
Mousetrap.bind('ctrl+shift+a', addCaption);
Mousetrap.bind('ctrl+shift+d', deleteCaption);

function subtitleRefresh() {
  console.log(player.getCurrentTime());
  $('#player-time').text(parseFloat(player.getCurrentTime()).toFixed(2));

  if (player.getPlayerState() === 1) {
    if (player.getCurrentTime() > (subtitles[subtitles.length-1].start + subtitles[subtitles.length-1].dur)) {
      $('.sub-edit').val('');
      $('.edit-start').val('');
      $('.edit-end').val('');
      $('.sub-next').val('');
      $('.next-start').val('');
      $('.next-end').val('');
      $('.sub-prev').val(subtitles[subtitles.length-1].value);
      $('.prev-start').val(subtitles[subtitles.length-1].start);
      $('.prev-end').val(subtitles[subtitles.length-1].start + subtitles[subtitles.length-1].dur);
      $('#subtitles h3').text('');
      return false;
    }

    if (player.getCurrentTime() < subtitles[0].start) {
      $('.sub-edit').val('');
      $('.edit-start').val('');
      $('.edit-end').val('');
      $('.sub-next').val(subtitles[0].value);
      $('.next-start').val(subtitles[0].start);
      $('.next-end').val(subtitles[0].start + subtitles[0].dur);
      $('.sub-prev').val('');
      $('.prev-start').val('');
      $('.prev-end').val('');
      return false;
    }
    for (sub in subtitles) {
      timeStart = subtitles[sub].start;
      timeEnd = subtitles[sub].start + subtitles[sub].dur;

      if (player.getCurrentTime() >= timeStart && player.getCurrentTime() <= timeEnd) {
        currentSubIndex = sub;
        editSub = subtitles[sub];
        prevSub = subtitles[parseInt(sub)-1];
        nextSub = subtitles[parseInt(sub)+1];
        console.log(currentSubIndex);
        if (nextSub && prevSub) {
          $('#subtitles h3').text(editSub.value);
          $('.sub-edit').val(editSub.value);
          $('.edit-start').val(editSub.start);
          $('.edit-end').val(editSub.start + editSub.dur);
          $('.sub-next').val(nextSub.value);
          $('.next-start').val(nextSub.start);
          $('.next-end').val(nextSub.start + nextSub.dur);
          $('.sub-prev').val(prevSub.value);
          $('.prev-start').val(prevSub.start);
          $('.prev-end').val(prevSub.start + prevSub.dur);
          return false;
        }
        else if (!prevSub && !nextSub) {
          $('#subtitles h3').text(editSub.value);
          $('.sub-edit').val(editSub.value);
          $('.edit-start').val(editSub.start);
          $('.edit-end').val(editSub.start + editSub.dur);
          $('.sub-next').val('');
          $('.next-start').val('');
          $('.next-end').val('');
          $('.sub-prev').val('');
          $('.prev-start').val('');
          $('.prev-end').val('');
          return false;
        }
        else if (!prevSub && nextSub) {
          $('#subtitles h3').text(editSub.value);
          $('.sub-edit').val(editSub.value);
          $('.edit-start').val(editSub.start);
          $('.edit-end').val(editSub.start + editSub.dur);
          $('.sub-next').val(nextSub.value);
          $('.next-start').val(nextSub.start);
          $('.next-end').val(nextSub.start + nextSub.dur);
          $('.sub-prev').val('');
          $('.prev-start').val('');
          $('.prev-end').val('');
          return false;
        }
        else {
          $('#subtitles h3').text(editSub.value);
          $('.sub-edit').val(editSub.value);
          $('.edit-start').val(editSub.start);
          $('.edit-end').val(editSub.start + editSub.dur);
          $('.sub-next').val('');
          $('.next-start').val('');
          $('.next-end').val('');
          $('.sub-prev').val(prevSub.value);
          $('.prev-start').val(prevSub.start);
          $('.prev-end').val(prevSub.start + prevSub.dur);
          return false;
        }
      }
    }
  }
}

function deleteCaption() {
  videoData.captions.splice(currentSubIndex, 1);
  $.ajax({
    url: '/video/' + videoID,
    type: 'POST',
    data: JSON.stringify(videoData),
    contentType: 'application/json; charset=utf-8',
    dataType: 'json'
  });
  subtitles = videoData.captions;
  $('#subtitles h3').text('');
  $('.sub-edit').val('');
  $('.edit-start').val('');
  $('.edit-end').val('');
  rewindVideo();
  player.playVideo();
}

function addCaption() {
  if (player.getPlayerState() === 1) {
    pauseVideo();
  }
  if (currentSubIndex) {
    startCaption =
    {
      'start': player.getCurrentTime(),
      'dur': 2.0,
      'value': 'Add caption text and change beginning and ending times',
      'extra_data': []
    };
    console.log(typeof currentSubIndex);
    videoData.captions.splice(parseInt(currentSubIndex) + 1, 0, startCaption);
    currentSubIndex = parseInt(currentSubIndex) + 1;
    subtitles = videoData.captions;
    editSub = subtitles[currentSubIndex];
    prevSub = subtitles[parseInt(currentSubIndex)-1];
    nextSub = subtitles[parseInt(currentSubIndex)+1];
    $('#subtitles h3').text(editSub.value);
    $('.sub-edit').val(editSub.value);
    $('.edit-start').val(editSub.start);
    $('.edit-end').val(editSub.start + editSub.dur);
    $('.sub-next').val(nextSub.value);
    $('.next-start').val(nextSub.start);
    $('.next-end').val(nextSub.start + nextSub.dur);
    $('.sub-prev').val(prevSub.value);
    $('.prev-start').val(prevSub.start);
    $('.prev-end').val(prevSub.start + prevSub.dur);
  }
  else {
    currentSubIndex = videoData.captions.length >= 1 ? videoData.captions[videoData.captions.length] : 0;
    startCaption =
    {
      'start': player.getCurrentTime(),
      'dur': 2.0,
      'value': 'Add caption text and change beginning and ending times',
      'extra_data': []
    };
    videoData.captions.push(startCaption);
    subtitles = videoData.captions;
    console.log(subtitles);
    editSub = subtitles[currentSubIndex];
    console.log(editSub);
    console.log(editSub.value)
    $('#subtitles h3').text(editSub.value);
    $('.sub-edit').val(editSub.value);
    $('.edit-start').val(editSub.start);
    $('.edit-end').val(editSub.start + editSub.dur);
  }
}

function saveCaption() {
  console.log(currentSubIndex);
  // if (videoData.captions < 1) {
  //   videoData.transcript = $('.transcription-box').val();
  //   console.log(videoData.transcript);
  // }
  // else {
  videoData.captions[currentSubIndex].value = $('.sub-edit').val();
  videoData.captions[currentSubIndex].start = parseFloat($('.edit-start').val());
  videoData.captions[currentSubIndex].dur = parseFloat($('.edit-end').val()) - parseFloat($('.edit-start').val());
  if (currentSubIndex > 0) {
    videoData.captions[parseInt(currentSubIndex)-1].start = parseFloat($('.prev-start').val());
    videoData.captions[parseInt(currentSubIndex)-1].dur = parseFloat($('.prev-end').val()) - parseFloat($('.prev-start').val());
  }
  if (currentSubIndex < videoData.captions.length-1) {
    videoData.captions[parseInt(currentSubIndex)+1].start = parseFloat($('.next-start').val());
    videoData.captions[parseInt(currentSubIndex)+1].dur = parseFloat($('.next-end').val()) - parseFloat($('.next-start').val());
  }
  subtitles = videoData.captions;
  // }

  $.ajax({
    url: '/video/' + videoID,
    type: 'POST',
    data: JSON.stringify(videoData),
    contentType: 'application/json; charset=utf-8',
    dataType: 'json'
  });
  // if (videoData.captions > 0) {
  rewindVideo();
  player.playVideo();
  // }
}

$(document).ready(function() {

  $('#the-button').click(function() {
    urlValue = $('#link-value').val();
    tag = document.createElement('script');
    firstScriptTag = document.getElementsByTagName('script')[0];

    if (urlValue.length > 11) {
      videoID = urlValue.match(re)[1].trim();
    }
    else {
      videoID = urlValue.trim();
    }

    tag.src = "https://www.youtube.com/iframe_api";
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  });

  $(window).scroll(
    {
        previousTop: 0
    },
    function () {
    var currentTop = $(window).scrollTop();
    if (currentTop < this.previousTop) {
        $(".navbar-fixed-top").fadeIn("slow");
    } else {
        $(".navbar-fixed-top").fadeOut("slow");
    }
    this.previousTop = currentTop;
  });

  $( "#transcript-upload").change(function() {
    console.log("photo file has been chosen")
  });

});

//Test Videos
//https://www.youtube.com/watch?v=MftOONlDQac
//https://www.youtube.com/watch?v=fPloDzu_wcI
//https://www.youtube.com/watch?v=poL7l-Uk3I8
//https://www.youtube.com/watch?v=hjfogiltO80<commit_msg>Remove console log<commit_after>var currentRate,
    currentSubIndex,
    editSub,
    firstScriptTag,
    nextSub,
    player,
    prevSub,
    rateIndex,
    rates,
    re = /=(.+)/,
    startCaption,
    sub,
    subtitleChangeInterval,
    subtitles,
    tag,
    timeEnd,
    timeStart,
    urlValue,
    videoData,
    videoDuration,
    videoID = '';

function onYouTubeIframeAPIReady() {
  player = new YT.Player('player', {
    height: '340',
    width: '560',
    videoId: videoID,
    playerVars: {
      'cc_load_policy': 1,
      'controls': 0
    },
    events: {
      'onReady': onPlayerReady,
    }
  });
}

function onPlayerReady(event) {
  rates = player.getAvailablePlaybackRates();
  currentRate = player.getPlaybackRate();
  rateIndex = rates.indexOf(currentRate);
  subtitleChangeInterval = setInterval(subtitleRefresh, 100);
  console.log(player.getDuration());
  $.getJSON('/video/youtube' + videoID, function(data) {
    videoData = data;
    subtitles = videoData.captions;
    $('.search-bar').hide();
    $('.main-button').hide();
    $('.shortcuts').fadeIn();
    $('.video-main').show();
    $('#player').show();
    $('#current-player-time').show();
    $('#overlay').show();
    $('#subtitles').show();
    // if (subtitles.length > 0) {
    $('.sub-prev').show();
    $('.sub-edit').show();
    $('.sub-next').show();
    $('.prev-head').show();
    $('.edit-head').show();
    $('.next-head').show();
    event.target.playVideo();
    // }
    // else {
    //   $('.transcription-area').show();
    //   $('.transcription-box').val(videoData.transcript);
    //   event.target.playVideo();
    // }
  });

  $('.sub-edit').focus(function() {
    player.pauseVideo();
  });
}

function pauseVideo() {
  if (player.getPlayerState() === 1) {
    player.pauseVideo();
  }
  else {
    player.playVideo();
  }
}

function slowdownVideo() {
  if (rateIndex > 0) {
    player.setPlaybackRate(rates[rateIndex-1]);
    rateIndex -= 1;
  }
}

function speedupVideo() {
  if (rateIndex < rates.length -1) {
    player.setPlaybackRate(rates[rateIndex+1]);
    rateIndex += 1;
  }
}

function rewindVideo() {
  player.seekTo((player.getCurrentTime()-2), true);
  player.playVideo();
  console.log(player.getCurrentTime());
}

function forwardVideo() {
  player.seekTo((player.getCurrentTime()+2), true);
  player.playVideo();
  console.log(player.getCurrentTime());
}

Mousetrap.bind('ctrl+1', pauseVideo);
Mousetrap.bind('ctrl+4', slowdownVideo);
Mousetrap.bind('ctrl+5', speedupVideo);
Mousetrap.bind('ctrl+2', rewindVideo);
Mousetrap.bind('ctrl+3', forwardVideo);
Mousetrap.bind('ctrl+shift+s', saveCaption);
Mousetrap.bind('ctrl+shift+a', addCaption);
Mousetrap.bind('ctrl+shift+d', deleteCaption);

function subtitleRefresh() {
  console.log(player.getCurrentTime());
  $('#player-time').text(parseFloat(player.getCurrentTime()).toFixed(2));

  if (player.getPlayerState() === 1) {
    if (player.getCurrentTime() > (subtitles[subtitles.length-1].start + subtitles[subtitles.length-1].dur)) {
      $('.sub-edit').val('');
      $('.edit-start').val('');
      $('.edit-end').val('');
      $('.sub-next').val('');
      $('.next-start').val('');
      $('.next-end').val('');
      $('.sub-prev').val(subtitles[subtitles.length-1].value);
      $('.prev-start').val(subtitles[subtitles.length-1].start);
      $('.prev-end').val(subtitles[subtitles.length-1].start + subtitles[subtitles.length-1].dur);
      $('#subtitles h3').text('');
      return false;
    }

    if (player.getCurrentTime() < subtitles[0].start) {
      $('.sub-edit').val('');
      $('.edit-start').val('');
      $('.edit-end').val('');
      $('.sub-next').val(subtitles[0].value);
      $('.next-start').val(subtitles[0].start);
      $('.next-end').val(subtitles[0].start + subtitles[0].dur);
      $('.sub-prev').val('');
      $('.prev-start').val('');
      $('.prev-end').val('');
      return false;
    }
    for (sub in subtitles) {
      timeStart = subtitles[sub].start;
      timeEnd = subtitles[sub].start + subtitles[sub].dur;

      if (player.getCurrentTime() >= timeStart && player.getCurrentTime() <= timeEnd) {
        currentSubIndex = sub;
        editSub = subtitles[sub];
        prevSub = subtitles[parseInt(sub)-1];
        nextSub = subtitles[parseInt(sub)+1];
        console.log(currentSubIndex);
        if (nextSub && prevSub) {
          $('#subtitles h3').text(editSub.value);
          $('.sub-edit').val(editSub.value);
          $('.edit-start').val(editSub.start);
          $('.edit-end').val(editSub.start + editSub.dur);
          $('.sub-next').val(nextSub.value);
          $('.next-start').val(nextSub.start);
          $('.next-end').val(nextSub.start + nextSub.dur);
          $('.sub-prev').val(prevSub.value);
          $('.prev-start').val(prevSub.start);
          $('.prev-end').val(prevSub.start + prevSub.dur);
          return false;
        }
        else if (!prevSub && !nextSub) {
          $('#subtitles h3').text(editSub.value);
          $('.sub-edit').val(editSub.value);
          $('.edit-start').val(editSub.start);
          $('.edit-end').val(editSub.start + editSub.dur);
          $('.sub-next').val('');
          $('.next-start').val('');
          $('.next-end').val('');
          $('.sub-prev').val('');
          $('.prev-start').val('');
          $('.prev-end').val('');
          return false;
        }
        else if (!prevSub && nextSub) {
          $('#subtitles h3').text(editSub.value);
          $('.sub-edit').val(editSub.value);
          $('.edit-start').val(editSub.start);
          $('.edit-end').val(editSub.start + editSub.dur);
          $('.sub-next').val(nextSub.value);
          $('.next-start').val(nextSub.start);
          $('.next-end').val(nextSub.start + nextSub.dur);
          $('.sub-prev').val('');
          $('.prev-start').val('');
          $('.prev-end').val('');
          return false;
        }
        else {
          $('#subtitles h3').text(editSub.value);
          $('.sub-edit').val(editSub.value);
          $('.edit-start').val(editSub.start);
          $('.edit-end').val(editSub.start + editSub.dur);
          $('.sub-next').val('');
          $('.next-start').val('');
          $('.next-end').val('');
          $('.sub-prev').val(prevSub.value);
          $('.prev-start').val(prevSub.start);
          $('.prev-end').val(prevSub.start + prevSub.dur);
          return false;
        }
      }
    }
  }
}

function deleteCaption() {
  videoData.captions.splice(currentSubIndex, 1);
  $.ajax({
    url: '/video/' + videoID,
    type: 'POST',
    data: JSON.stringify(videoData),
    contentType: 'application/json; charset=utf-8',
    dataType: 'json'
  });
  subtitles = videoData.captions;
  $('#subtitles h3').text('');
  $('.sub-edit').val('');
  $('.edit-start').val('');
  $('.edit-end').val('');
  rewindVideo();
  player.playVideo();
}

function addCaption() {
  if (player.getPlayerState() === 1) {
    pauseVideo();
  }
  if (currentSubIndex) {
    startCaption =
    {
      'start': player.getCurrentTime(),
      'dur': 2.0,
      'value': 'Add caption text and change beginning and ending times',
      'extra_data': []
    };
    videoData.captions.splice(parseInt(currentSubIndex) + 1, 0, startCaption);
    currentSubIndex = parseInt(currentSubIndex) + 1;
    subtitles = videoData.captions;
    editSub = subtitles[currentSubIndex];
    prevSub = subtitles[parseInt(currentSubIndex)-1];
    nextSub = subtitles[parseInt(currentSubIndex)+1];
    $('#subtitles h3').text(editSub.value);
    $('.sub-edit').val(editSub.value);
    $('.edit-start').val(editSub.start);
    $('.edit-end').val(editSub.start + editSub.dur);
    $('.sub-next').val(nextSub.value);
    $('.next-start').val(nextSub.start);
    $('.next-end').val(nextSub.start + nextSub.dur);
    $('.sub-prev').val(prevSub.value);
    $('.prev-start').val(prevSub.start);
    $('.prev-end').val(prevSub.start + prevSub.dur);
  }
  else {
    currentSubIndex = videoData.captions.length >= 1 ? videoData.captions[videoData.captions.length] : 0;
    startCaption =
    {
      'start': player.getCurrentTime(),
      'dur': 2.0,
      'value': 'Add caption text and change beginning and ending times',
      'extra_data': []
    };
    videoData.captions.push(startCaption);
    subtitles = videoData.captions;
    console.log(subtitles);
    editSub = subtitles[currentSubIndex];
    console.log(editSub);
    console.log(editSub.value)
    $('#subtitles h3').text(editSub.value);
    $('.sub-edit').val(editSub.value);
    $('.edit-start').val(editSub.start);
    $('.edit-end').val(editSub.start + editSub.dur);
  }
}

function saveCaption() {
  console.log(currentSubIndex);
  // if (videoData.captions < 1) {
  //   videoData.transcript = $('.transcription-box').val();
  //   console.log(videoData.transcript);
  // }
  // else {
  videoData.captions[currentSubIndex].value = $('.sub-edit').val();
  videoData.captions[currentSubIndex].start = parseFloat($('.edit-start').val());
  videoData.captions[currentSubIndex].dur = parseFloat($('.edit-end').val()) - parseFloat($('.edit-start').val());
  if (currentSubIndex > 0) {
    videoData.captions[parseInt(currentSubIndex)-1].start = parseFloat($('.prev-start').val());
    videoData.captions[parseInt(currentSubIndex)-1].dur = parseFloat($('.prev-end').val()) - parseFloat($('.prev-start').val());
  }
  if (currentSubIndex < videoData.captions.length-1) {
    videoData.captions[parseInt(currentSubIndex)+1].start = parseFloat($('.next-start').val());
    videoData.captions[parseInt(currentSubIndex)+1].dur = parseFloat($('.next-end').val()) - parseFloat($('.next-start').val());
  }
  subtitles = videoData.captions;
  // }

  $.ajax({
    url: '/video/' + videoID,
    type: 'POST',
    data: JSON.stringify(videoData),
    contentType: 'application/json; charset=utf-8',
    dataType: 'json'
  });
  // if (videoData.captions > 0) {
  rewindVideo();
  player.playVideo();
  // }
}

$(document).ready(function() {

  $('#the-button').click(function() {
    urlValue = $('#link-value').val();
    tag = document.createElement('script');
    firstScriptTag = document.getElementsByTagName('script')[0];

    if (urlValue.length > 11) {
      videoID = urlValue.match(re)[1].trim();
    }
    else {
      videoID = urlValue.trim();
    }

    tag.src = "https://www.youtube.com/iframe_api";
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  });

  $(window).scroll(
    {
        previousTop: 0
    },
    function () {
    var currentTop = $(window).scrollTop();
    if (currentTop < this.previousTop) {
        $(".navbar-fixed-top").fadeIn("slow");
    } else {
        $(".navbar-fixed-top").fadeOut("slow");
    }
    this.previousTop = currentTop;
  });

  $( "#transcript-upload").change(function() {
    console.log("photo file has been chosen")
  });

});

//Test Videos
//https://www.youtube.com/watch?v=MftOONlDQac
//https://www.youtube.com/watch?v=fPloDzu_wcI
//https://www.youtube.com/watch?v=poL7l-Uk3I8
//https://www.youtube.com/watch?v=hjfogiltO80<|endoftext|>