<commit_before>$(document).ready(function() {
// static stuff
var ref = new Firebase("***firebase-url***");
var socket = io();
var canPost = true;
var authData;
var lastUser;
var unreadMessages =  false;
var soundEnabledText = "Sound enabled";
var soundDisabledText = "Mentions Only";
var lostConnection = false;
var ServerUser = {name: "Server", tags: "Server", image: "", colour: "inherit"};

var msgbox = $("#message");

$('.helpButton').click(function() {
  $('.about-box').fadeIn(function() {
    $('.close-button').click(function() {
      $('.about-box').fadeOut()
    });
  })
});

function updateSoundPrefButton(){
  // Check localstorage
  if (localStorage.getItem("soundPref") === null){
    localStorage.setItem("soundPref", 1)
  }else if (localStorage.getItem("soundPref") == 1){
    document.getElementById("soundPref").innerHTML = soundEnabledText;
  }else{
    document.getElementById("soundPref").innerHTML = soundDisabledText;
  }
}
updateSoundPrefButton();

$("#soundPref").click(toggleSoundPref);

function toggleSoundPref(){
  if (localStorage.getItem("soundPref") == "1"){
    localStorage.setItem("soundPref", 0);
  } else {
    localStorage.setItem("soundPref", 1);
  }

  updateSoundPrefButton()
}

function updateTitle() {
  var title= $(document).find("title");
  if (unreadMessages){
    if (title.text().charAt(0) != "*" ){
      title.text("* " + title.text())
    }
  }else{
    if (title.text().charAt(0) == "*"){
      title.text(title.text().substring(2));
    }
  }
}

window.onfocus = function() {
  unreadMessages = false;
  updateTitle();
};

function formatTimestamp(timestamp) {
  var date = new Date(timestamp);
  var hours = date.getHours().toString();
  var minutes = date.getMinutes().toString();
  if (hours.length == 1){
    hours = "0" + hours
  }
  if (minutes.length == 1){
    minutes = "0" + minutes
  }
  return hours + ":" + minutes
}

function SayAsServer(message){
  showMessage({text: message, timestamp: Date.now()}, ServerUser)
}

function getUsers(socket){
  socket.emit("get users", authData.token, function(users){
    $('#userlist').empty();
    users.data.forEach(function(user){
      $('#userlist').append("
@"+user.name+"
");
    });
  });
}

function showMessage(message, user){
  message.text = emojione.toImage(message.text);

  var msgClass = "msg";
  var hasImage = Boolean(user.image);
  var wasLastUser = lastUser == user.name;
  var canTweet = true;

  var twitterUser = user.name;
  var href = "https://twitter.com/"+ user.image + "/";
  var html = "
";

  if (user.name == "Server"){
    msgClass = "server-msg";
    hasImage = false;
    wasLastUser = false;
    canTweet = false;
    href = "http://yrs.io";
  } else if (user.name == "RubyBot") {
    msgClass = "bot-msg";
    canTweet = false;
    href = "http://twitter.com/YRSChat"
  }

  if (!wasLastUser) {
    if (hasImage) {
      html += '';
    }

    html += '
' +
      '' + '@' + user.name + '' +
      '' + user.tags + '' + formatTimestamp(message.timestamp) + '' +
      '
' + message.text + '
';

    if(canTweet){
      html += '' +
        'Tweet' + '
';
    } else {
      html += '
';
    }

  } else {
    messageElement = $('#messages li').last();
    messageElement.find(".message").append("
" + message.text + "
");

    if (canTweet){
      messageElement.find(".message").append(
        '' +
        'Tweet'
      );
    }
  }

  html += "
";
  var messageElement = $(html);

  messageElement.linkify({
    target: "_blank"
  });

  if (!wasLastUser){
    $('#messages').append(messageElement).animate({scrollTop: 1000000}, "slow");
  }

  lastUser = user.name;

  if(canTweet){
    twttr.widgets.load()
  }

  if (!document.hasFocus()){
    unreadMessages = true;
    updateTitle();
    var nameFormatted = authData.twitter.username;
    if (message.text.toLowerCase().indexOf(nameFormatted.toLowerCase()) !== -1){
        var audio = new Audio('/assets/sound/Ding.mp3');
        audio.play();
    }else{
      if (localStorage.getItem("soundPref") == "1"){
        var audio = new Audio('/assets/sound/pop.ogg');
        audio.play();
      }
    }
  }
}

// firebase stuff
ref.onAuth(function(data) {
  authData = data;
  if (!data){
    $('.twitter').css("display", "block")
  } else {
    socket.emit("user join", data.token, data.twitter.username, data.twitter.profileImageURL);
  }
});

$('#twitter-button').click(function() {
  ref.authWithOAuthPopup("twitter", function(error, data) {
    if (error) {
      console.log("Login Failed!", error);
    } else {
      $('.twitter').fadeOut()
    }
  });
  return false;
});

ref.getAuth();

$('form').submit(function(){
  if(canPost == false){
    showMessage('Please do not spam!', 'Server', '');
  } else {
    socket.emit('chat message',
      msgbox.val(),
      authData.token,
      function(response) {
        if (response.status == "failed"){
          showMessage(response.message, ServerUser);
        }
      }
    );
    canPost=false;
    setTimeout(function(){canPost=true},500);
  }
  msgbox.val('');
  return false;
});

socket.on("connect", function(){
  if (!authData) return;
  if (!lostConnection) return;
  SayAsServer("You have reconnected to the server.");
  socket.emit("user join", authData.token, authData.twitter.username, authData.twitter.profileImageURL);
  lostConnection = false;
});

socket.on("disconnect", function(){
  SayAsServer("You have been temporarlly disconnected from the server.");
  lostConnection = true;
});

socket.on('chat message', function(message, user) {
  showMessage(message, user);
});

socket.on("user join", function(user) {
  SayAsServer(user.name + " has joined!")
  getUsers(socket);
});

socket.on("user leave", function(user) {
  SayAsServer(user.name + " has left.")
  getUsers(socket);
});

getUsers(socket);

window.setInterval(function() {
  socket.emit("user ping", authData.token)
  getUsers(socket);
}, 5000);

$(window).unload(function() {
  socket.emit("user leave", authData.token);
})
});

window.onbeforeunload = function(){
    return "Closing the window will disconnect your from YRS Chat";
};
<commit_msg>Added #FOC2015 to tweets<commit_after>$(document).ready(function() {
// static stuff
var ref = new Firebase("***firebase-url***");
var socket = io();
var canPost = true;
var authData;
var lastUser;
var unreadMessages =  false;
var soundEnabledText = "Sound enabled";
var soundDisabledText = "Mentions Only";
var lostConnection = false;
var ServerUser = {name: "Server", tags: "Server", image: "", colour: "inherit"};

var msgbox = $("#message");

$('.helpButton').click(function() {
  $('.about-box').fadeIn(function() {
    $('.close-button').click(function() {
      $('.about-box').fadeOut()
    });
  })
});

function updateSoundPrefButton(){
  // Check localstorage
  if (localStorage.getItem("soundPref") === null){
    localStorage.setItem("soundPref", 1)
  }else if (localStorage.getItem("soundPref") == 1){
    document.getElementById("soundPref").innerHTML = soundEnabledText;
  }else{
    document.getElementById("soundPref").innerHTML = soundDisabledText;
  }
}
updateSoundPrefButton();

$("#soundPref").click(toggleSoundPref);

function toggleSoundPref(){
  if (localStorage.getItem("soundPref") == "1"){
    localStorage.setItem("soundPref", 0);
  } else {
    localStorage.setItem("soundPref", 1);
  }

  updateSoundPrefButton()
}

function updateTitle() {
  var title= $(document).find("title");
  if (unreadMessages){
    if (title.text().charAt(0) != "*" ){
      title.text("* " + title.text())
    }
  }else{
    if (title.text().charAt(0) == "*"){
      title.text(title.text().substring(2));
    }
  }
}

window.onfocus = function() {
  unreadMessages = false;
  updateTitle();
};

function formatTimestamp(timestamp) {
  var date = new Date(timestamp);
  var hours = date.getHours().toString();
  var minutes = date.getMinutes().toString();
  if (hours.length == 1){
    hours = "0" + hours
  }
  if (minutes.length == 1){
    minutes = "0" + minutes
  }
  return hours + ":" + minutes
}

function SayAsServer(message){
  showMessage({text: message, timestamp: Date.now()}, ServerUser)
}

function getUsers(socket){
  socket.emit("get users", authData.token, function(users){
    $('#userlist').empty();
    users.data.forEach(function(user){
      $('#userlist').append("
@"+user.name+"
");
    });
  });
}

function showMessage(message, user){
  message.text = emojione.toImage(message.text);

  var msgClass = "msg";
  var hasImage = Boolean(user.image);
  var wasLastUser = lastUser == user.name;
  var canTweet = true;

  var twitterUser = user.name;
  var href = "https://twitter.com/"+ user.image + "/";
  var html = "
";

  if (user.name == "Server"){
    msgClass = "server-msg";
    hasImage = false;
    wasLastUser = false;
    canTweet = false;
    href = "http://yrs.io";
  } else if (user.name == "RubyBot") {
    msgClass = "bot-msg";
    canTweet = false;
    href = "http://twitter.com/YRSChat"
  }

  if (!wasLastUser) {
    if (hasImage) {
      html += '';
    }

    html += '
' +
      '' + '@' + user.name + '' +
      '' + user.tags + '' + formatTimestamp(message.timestamp) + '' +
      '
' + message.text + '
';

    if(canTweet){
      html += '' +
        'Tweet' + '
';
    } else {
      html += '
';
    }

  } else {
    messageElement = $('#messages li').last();
    messageElement.find(".message").append("
" + message.text + "
");

    if (canTweet){
      messageElement.find(".message").append(
        '' +
        'Tweet'
      );
    }
  }

  html += "
";
  var messageElement = $(html);

  messageElement.linkify({
    target: "_blank"
  });

  if (!wasLastUser){
    $('#messages').append(messageElement).animate({scrollTop: 1000000}, "slow");
  }

  lastUser = user.name;

  if(canTweet){
    twttr.widgets.load()
  }

  if (!document.hasFocus()){
    unreadMessages = true;
    updateTitle();
    var nameFormatted = authData.twitter.username;
    if (message.text.toLowerCase().indexOf(nameFormatted.toLowerCase()) !== -1){
        var audio = new Audio('/assets/sound/Ding.mp3');
        audio.play();
    }else{
      if (localStorage.getItem("soundPref") == "1"){
        var audio = new Audio('/assets/sound/pop.ogg');
        audio.play();
      }
    }
  }
}

// firebase stuff
ref.onAuth(function(data) {
  authData = data;
  if (!data){
    $('.twitter').css("display", "block")
  } else {
    socket.emit("user join", data.token, data.twitter.username, data.twitter.profileImageURL);
  }
});

$('#twitter-button').click(function() {
  ref.authWithOAuthPopup("twitter", function(error, data) {
    if (error) {
      console.log("Login Failed!", error);
    } else {
      $('.twitter').fadeOut()
    }
  });
  return false;
});

ref.getAuth();

$('form').submit(function(){
  if(canPost == false){
    showMessage('Please do not spam!', 'Server', '');
  } else {
    socket.emit('chat message',
      msgbox.val(),
      authData.token,
      function(response) {
        if (response.status == "failed"){
          showMessage(response.message, ServerUser);
        }
      }
    );
    canPost=false;
    setTimeout(function(){canPost=true},500);
  }
  msgbox.val('');
  return false;
});

socket.on("connect", function(){
  if (!authData) return;
  if (!lostConnection) return;
  SayAsServer("You have reconnected to the server.");
  socket.emit("user join", authData.token, authData.twitter.username, authData.twitter.profileImageURL);
  lostConnection = false;
});

socket.on("disconnect", function(){
  SayAsServer("You have been temporarlly disconnected from the server.");
  lostConnection = true;
});

socket.on('chat message', function(message, user) {
  showMessage(message, user);
});

socket.on("user join", function(user) {
  SayAsServer(user.name + " has joined!")
  getUsers(socket);
});

socket.on("user leave", function(user) {
  SayAsServer(user.name + " has left.")
  getUsers(socket);
});

getUsers(socket);

window.setInterval(function() {
  socket.emit("user ping", authData.token)
  getUsers(socket);
}, 5000);

$(window).unload(function() {
  socket.emit("user leave", authData.token);
})
});

window.onbeforeunload = function(){
    return "Closing the window will disconnect your from YRS Chat";
};
<|endoftext|>


<commit_before>const Discord = require('discord.js');
module.exports = member => {
const modlog = member.guild.channels.find('name', 'pie-log');
const muteRole = ("376052336117940235").roles.find("name","SendMessage")
  //${member.user.username}
  const embed = new Discord.RichEmbed()
  .setTimestamp()
  .setColor(0xffff00)
  .setTitle("User Joined")
  .setThumbnail(`${member.user.avatarURL}`)
  .setDescription(`\n`)
  .addField("Username:",`${member.user.username} (${member.user})`,true)
  .addField("Role Added:",`SendMessage`,false)
.setFooter(`User: ${member.user.username}`,`${member.user.avatarURL}`);
member.guild.member(member.user).addRole(muteRole)
member.guild.channels.get(modlog.id).send({embed}).catch(console.error);
}
<commit_msg>Update guildMemberAdd.js<commit_after>const Discord = require('discord.js');
module.exports = member => {
const modlog = member.guild.channels.find('name', 'pie-log');
const muteRole = member.guild.roles.find("name","SendMessage")
  //${member.user.username}
  const embed = new Discord.RichEmbed()
  .setTimestamp()
  .setColor(0xffff00)
  .setTitle("User Joined")
  .setThumbnail(`${member.user.avatarURL}`)
  .setDescription(`\n`)
  .addField("Username:",`${member.user.username} (${member.user})`,true)
  .addField("Role Added:",`SendMessage`,false)
.setFooter(`User: ${member.user.username}`,`${member.user.avatarURL}`);
member.guild.member(member.user).addRole(muteRole)
member.guild.channels.get(modlog.id).send({embed}).catch(console.error);
}
<|endoftext|>


<commit_before>// *************************************************************************
// Copyright (c) 2014-2017, SUSE LLC
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of SUSE LLC nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
// *************************************************************************
//
// lib.js
//
"use strict";

define ([
    'jquery',
    'cf',
    'current-user',
    'prototypes'
], function (
    $,
    cf,
    currentUser,
    prototypes
) {

    var heldObject = null,
        dbrowserStateOverride = false,
        dbrowserState = {
            "obj": null,  // the dbrowser object itself
            "set": null,  // the dataset (array) we are browsing
            "pos": null   // the current position within that array
        },
        drowselectState = {
            "obj": null,  // the drowselect object itself
            "set": null,  // the dataset (array) we are selecting from
            "pos": null   // the current position within that array
        };

    return {

        // special entries
        dividerEntry: {
            name: 'divider',
            aclProfileRead: 'passerby',
            aclProfileWrite: null,
            text: '-',
            prop: null,
            maxlen: 20
        },

        emptyLineEntry: {
            name: 'emptyLine',
            aclProfileRead: 'passerby',
            aclProfileWrite: null,
            text: "&nbsp",
            prop: null,
            maxlen: 20
        },

        clearResult: function () {
            $('#result').css('text-align', 'left');
            $('#result').html(' ');
        },

        // dbrowser states
        // FIXME: move this into stack.js
        dbrowserState: dbrowserState,

        // display error message
        displayError: function (buf, id) {
            console.log("ERROR: " + buf);
            $('#result').css('text-align', 'center');
            $("#result").html(buf);
            $('input[name="sel"]').val('');
            if (id) {
                $('input[name="' + id + '"]').focus();
            } else {
                $('input[name="entry0"]').focus();
            }
        },

        displayResult: function (buf) {
            console.log("RESULT: " + buf);
            $('#result').css('text-align', 'center');
            $('#result').html(buf);
        },

        // drowselect state
        // FIXME: move this into stack.js
        drowselectState: drowselectState,

        focusedItem: function () {
            return {
                "id": $(document.activeElement).attr('id'),
                "name": $(document.activeElement).attr('name'),
            };
        },

        // convert null to empty array
        forceArray: function (arr) {
            return (arr === null) ? [] : arr;
        },

        // generate string "n objects" based on array length
        genObjStr: function (len) {
            return (len === 1) ?
                '1 object' :
                len + " objects";
        },

        // give object a "haircut" by throwing out all properties
        // that do not appear in proplist
        hairCut: function (obj, proplist) {
            for (var prop in obj) {
                if (obj.hasOwnProperty(prop)) {
                    if (proplist.indexOf(prop) !== -1) {
                        continue;
                    }
                    delete obj[prop];
                }
            }
            return obj;
        },

        // Crockford, Douglas; "JavaScript: The Good Parts"; page 61
        isArray: function (value) {
            return value &&
                typeof value === 'object' &&
                typeof value.length === 'number' &&
                typeof value.splice === 'function' &&
                !(value.propertyIsEnumerable('length'));
        },

        isInteger: function (value) {
            var pival = parseInt(value, 10),
                cond1 = pival == value,
                cond2 = typeof pival === 'number',
                cond3 = isFinite(pival),
                res = cond1 && cond2 && cond3;
            //console.log("isInteger() called with", value);
            //console.log("parseInt says", pival);
            //console.log("typeof says", typeof pival === 'number');
            //console.log("isFinite says", isFinite(pival));
            //console.log("isInteger says", res);
            return res;
        },

        isObjEmpty: function (obj) {
            if (Object.getOwnPropertyNames(obj).length > 0) return false;
            return true;
        },

        // boolean function for existing, non-empty string, from
        // https://www.safaribooksonline.com/library/view/javascript-cookbook/9781449390211/ch01s07.html
        // true if variable exists, is a string, and has a length greater than zero
        isStringNotEmpty: function (unknownVariable) {
            if (((typeof unknownVariable !== "undefined") &&
                 (typeof unknownVariable.valueOf() === "string")) &&
                 (unknownVariable.length > 0)) {
                return true;
            }
            return false;
        },

        // log events to browser JavaScript console
        logKeyDown: function (evt) {
            console.log("WHICH: " + evt.which + ", KEYCODE: " + evt.keyCode);
        },

        objectify: function (st) {
            // if st ("something") is not a traditional object
            // like { "foo": "bar" }, turn it into {}
            if (st === undefined || st === null || typeof st !== 'object') {
                return {};
            }
            return st;
        },

        // check current employee's privilege against a given ACL profile
        privCheck: function (p) {

            var cep = currentUser('priv'),
                r,
                yesno;

            if ( cf('testing') && ! cep ) {
                cep = 'passerby';
            }
            if ( ! cep ) {
                console.log("Cannot determine priv level of current user! Falling back to sane value \"passerby\"");
                currentUser('priv', 'passerby');
                cep = currentUser('priv');
            }

            if (p === 'passerby' && cep) {
                r = true;
                yesno = "Yes.";
            } else if (p === 'inactive' && (cep === 'inactive' || cep === 'active' || cep === 'admin')) {
                r = true;
                yesno = "Yes.";
            } else if (p === 'active' && (cep === 'active' || cep === 'admin')) {
                r = true;
                yesno = "Yes.";
            } else if (p === 'admin' && cep === 'admin') {
                r = true;
                yesno = "Yes.";
            } else {
                r = false;
                yesno = "No.";
            }

            console.log("Does " + cep + " user satisfy ACL " + p + "? " + yesno);
            return r;
        }, // privCheck

        // reverse-video a row (on/off)
        reverseVideo: function (row, onoff) {
            if (onoff === true) {
                $('#row' + row).css('background-color','#000000');
                $('#row' + row).css('color','#ffffff');
            }
            if (onoff === false) {
                $('#row' + row).css('background-color','#d0e4fe');
                $('#row' + row).css('color','#000000');
            }
        },

        // right pad a string with spaces
        rightPadSpaces: function (toPad, padto) {
            var strToPad = ((toPad === null) ? '' : toPad).toString();
            // console.log("Padding " + strToPad + " to " + padto + " spaces.");
            var sp = ' ',
                padSpaces = sp.repeat(padto - String(strToPad).length);
            return strToPad.concat(padSpaces);
        },

        // shallow object copy, from
        // http://blog.soulserv.net/understanding-object-cloning-in-javascript-part-i/
        shallowCopy: function (original) {
            // First create an empty object with
            // same prototype of our original source
            var clone = Object.create(Object.getPrototypeOf(original)),
                i, keys = Object.getOwnPropertyNames(original);
            for (i = 0; i < keys.length; i++) {
                // copy each property into the clone
                Object.defineProperty(clone, keys[i],
                    Object.getOwnPropertyDescriptor(original, keys[i])
                );
            }
            return clone;
        },

        // pause main thread for n milliseconds
        //wait: function (ms) {
        //    var start = new Date().getTime();
        //    var end = start;
        //    while(end < start + ms) {
        //        end = new Date().getTime();
        //    }
        //},

    };

});

<commit_msg>js: core: lib: stop logging every keydown<commit_after>// *************************************************************************
// Copyright (c) 2014-2017, SUSE LLC
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of SUSE LLC nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
// *************************************************************************
//
// lib.js
//
"use strict";

define ([
    'jquery',
    'cf',
    'current-user',
    'prototypes'
], function (
    $,
    cf,
    currentUser,
    prototypes
) {

    var heldObject = null,
        dbrowserStateOverride = false,
        dbrowserState = {
            "obj": null,  // the dbrowser object itself
            "set": null,  // the dataset (array) we are browsing
            "pos": null   // the current position within that array
        },
        drowselectState = {
            "obj": null,  // the drowselect object itself
            "set": null,  // the dataset (array) we are selecting from
            "pos": null   // the current position within that array
        };

    return {

        // special entries
        dividerEntry: {
            name: 'divider',
            aclProfileRead: 'passerby',
            aclProfileWrite: null,
            text: '-',
            prop: null,
            maxlen: 20
        },

        emptyLineEntry: {
            name: 'emptyLine',
            aclProfileRead: 'passerby',
            aclProfileWrite: null,
            text: "&nbsp",
            prop: null,
            maxlen: 20
        },

        clearResult: function () {
            $('#result').css('text-align', 'left');
            $('#result').html(' ');
        },

        // dbrowser states
        // FIXME: move this into stack.js
        dbrowserState: dbrowserState,

        // display error message
        displayError: function (buf, id) {
            console.log("ERROR: " + buf);
            $('#result').css('text-align', 'center');
            $("#result").html(buf);
            $('input[name="sel"]').val('');
            if (id) {
                $('input[name="' + id + '"]').focus();
            } else {
                $('input[name="entry0"]').focus();
            }
        },

        displayResult: function (buf) {
            console.log("RESULT: " + buf);
            $('#result').css('text-align', 'center');
            $('#result').html(buf);
        },

        // drowselect state
        // FIXME: move this into stack.js
        drowselectState: drowselectState,

        focusedItem: function () {
            return {
                "id": $(document.activeElement).attr('id'),
                "name": $(document.activeElement).attr('name'),
            };
        },

        // convert null to empty array
        forceArray: function (arr) {
            return (arr === null) ? [] : arr;
        },

        // generate string "n objects" based on array length
        genObjStr: function (len) {
            return (len === 1) ?
                '1 object' :
                len + " objects";
        },

        // give object a "haircut" by throwing out all properties
        // that do not appear in proplist
        hairCut: function (obj, proplist) {
            for (var prop in obj) {
                if (obj.hasOwnProperty(prop)) {
                    if (proplist.indexOf(prop) !== -1) {
                        continue;
                    }
                    delete obj[prop];
                }
            }
            return obj;
        },

        // Crockford, Douglas; "JavaScript: The Good Parts"; page 61
        isArray: function (value) {
            return value &&
                typeof value === 'object' &&
                typeof value.length === 'number' &&
                typeof value.splice === 'function' &&
                !(value.propertyIsEnumerable('length'));
        },

        isInteger: function (value) {
            var pival = parseInt(value, 10),
                cond1 = pival == value,
                cond2 = typeof pival === 'number',
                cond3 = isFinite(pival),
                res = cond1 && cond2 && cond3;
            //console.log("isInteger() called with", value);
            //console.log("parseInt says", pival);
            //console.log("typeof says", typeof pival === 'number');
            //console.log("isFinite says", isFinite(pival));
            //console.log("isInteger says", res);
            return res;
        },

        isObjEmpty: function (obj) {
            if (Object.getOwnPropertyNames(obj).length > 0) return false;
            return true;
        },

        // boolean function for existing, non-empty string, from
        // https://www.safaribooksonline.com/library/view/javascript-cookbook/9781449390211/ch01s07.html
        // true if variable exists, is a string, and has a length greater than zero
        isStringNotEmpty: function (unknownVariable) {
            if (((typeof unknownVariable !== "undefined") &&
                 (typeof unknownVariable.valueOf() === "string")) &&
                 (unknownVariable.length > 0)) {
                return true;
            }
            return false;
        },

        // log events to browser JavaScript console
        logKeyDown: function (evt) {
            // console.log("WHICH: " + evt.which + ", KEYCODE: " + evt.keyCode);
        },

        objectify: function (st) {
            // if st ("something") is not a traditional object
            // like { "foo": "bar" }, turn it into {}
            if (st === undefined || st === null || typeof st !== 'object') {
                return {};
            }
            return st;
        },

        // check current employee's privilege against a given ACL profile
        privCheck: function (p) {

            var cep = currentUser('priv'),
                r,
                yesno;

            if ( cf('testing') && ! cep ) {
                cep = 'passerby';
            }
            if ( ! cep ) {
                console.log("Cannot determine priv level of current user! Falling back to sane value \"passerby\"");
                currentUser('priv', 'passerby');
                cep = currentUser('priv');
            }

            if (p === 'passerby' && cep) {
                r = true;
                yesno = "Yes.";
            } else if (p === 'inactive' && (cep === 'inactive' || cep === 'active' || cep === 'admin')) {
                r = true;
                yesno = "Yes.";
            } else if (p === 'active' && (cep === 'active' || cep === 'admin')) {
                r = true;
                yesno = "Yes.";
            } else if (p === 'admin' && cep === 'admin') {
                r = true;
                yesno = "Yes.";
            } else {
                r = false;
                yesno = "No.";
            }

            console.log("Does " + cep + " user satisfy ACL " + p + "? " + yesno);
            return r;
        }, // privCheck

        // reverse-video a row (on/off)
        reverseVideo: function (row, onoff) {
            if (onoff === true) {
                $('#row' + row).css('background-color','#000000');
                $('#row' + row).css('color','#ffffff');
            }
            if (onoff === false) {
                $('#row' + row).css('background-color','#d0e4fe');
                $('#row' + row).css('color','#000000');
            }
        },

        // right pad a string with spaces
        rightPadSpaces: function (toPad, padto) {
            var strToPad = ((toPad === null) ? '' : toPad).toString();
            // console.log("Padding " + strToPad + " to " + padto + " spaces.");
            var sp = ' ',
                padSpaces = sp.repeat(padto - String(strToPad).length);
            return strToPad.concat(padSpaces);
        },

        // shallow object copy, from
        // http://blog.soulserv.net/understanding-object-cloning-in-javascript-part-i/
        shallowCopy: function (original) {
            // First create an empty object with
            // same prototype of our original source
            var clone = Object.create(Object.getPrototypeOf(original)),
                i, keys = Object.getOwnPropertyNames(original);
            for (i = 0; i < keys.length; i++) {
                // copy each property into the clone
                Object.defineProperty(clone, keys[i],
                    Object.getOwnPropertyDescriptor(original, keys[i])
                );
            }
            return clone;
        },

        // pause main thread for n milliseconds
        //wait: function (ms) {
        //    var start = new Date().getTime();
        //    var end = start;
        //    while(end < start + ms) {
        //        end = new Date().getTime();
        //    }
        //},

    };

});

<|endoftext|>


<commit_before>require("../custom-methods")

var powers = [];

for (var a = 2; a <= 100; a++) {
  for (var b = 2; b <= 100; b++) {
    var powerFactors = [];
    for (var counter = 1; counter <= b; counter++) {
      powerFactors.push(a.primeFactors())
    }
    powers.push(powerFactors.join(',').split(',').sort());
  }
}

var distinctPowers = [];
var usedPowers = {};

powers.forEach(function(power) {
  if (!usedPowers[power]) {
    distinctPowers.push(power);
  }
  usedPowers[power] = true;
})

console.log(distinctPowers.length);
<commit_msg>Add a semicolon :)<commit_after>require("../custom-methods")

var powers = [];

for (var a = 2; a <= 100; a++) {
  for (var b = 2; b <= 100; b++) {
    var powerFactors = [];
    for (var counter = 1; counter <= b; counter++) {
      powerFactors.push(a.primeFactors());
    }
    powers.push(powerFactors.join(',').split(',').sort());
  }
}

var distinctPowers = [];
var usedPowers = {};

powers.forEach(function(power) {
  if (!usedPowers[power]) {
    distinctPowers.push(power);
  }
  usedPowers[power] = true;
})

console.log(distinctPowers.length);
<|endoftext|>


<commit_before>'use strict'

var http = require('http'),
    fileSystem = require('fs'),
    path = require('path');
var hummus=require('hummus');
var fillForm = require('./pdf-form-fill').fillForm;
function generatePDF(req, res){
  var outputName = new Date().getTime();
  var filePath = path.join(__dirname, '../output/cultos_'+outputName+'.pdf');
  console.log('filePath: '+filePath);
  var writer = hummus.createWriterToModify('./public/pdf_templates/cultos.pdf', {
  			modifiedFilePath: filePath
  });

  var params = req.body;

  var data = params;
  console.log(data);

  fillForm(writer,data);
  writer.end();

  var stat = fileSystem.statSync(filePath);
  res.writeHead(200, {'Content-Type': 'application/pdf',
                      'Content-Length': stat.size});

  var readStream = fileSystem.createReadStream(filePath);
  // We replaced all the event handlers with a simple call to readStream.pipe()
  readStream.pipe(res);
  readStream.on('close', function(){
    fs.unlink(filePath);
  });
  res.end();
}

module.exports = {
  generatePDF
};
<commit_msg>Escribir fichero en /tmp<commit_after>'use strict'

var http = require('http'),
    fileSystem = require('fs'),
    path = require('path');
var hummus=require('hummus');
var fillForm = require('./pdf-form-fill').fillForm;
function generatePDF(req, res){
  var outputName = new Date().getTime();
  var filePath = path.join(__dirname, '/tmp/cultos_'+outputName+'.pdf');
  console.log('filePath: '+filePath);
  var writer = hummus.createWriterToModify('./public/pdf_templates/cultos.pdf', {
  			modifiedFilePath: filePath
  });

  var params = req.body;

  var data = params;
  console.log(data);

  fillForm(writer,data);
  writer.end();

  var stat = fileSystem.statSync(filePath);
  res.writeHead(200, {'Content-Type': 'application/pdf',
                      'Content-Length': stat.size});

  var readStream = fileSystem.createReadStream(filePath);
  // We replaced all the event handlers with a simple call to readStream.pipe()
  readStream.pipe(res);
  readStream.on('close', function(){
    fs.unlink(filePath);
  });
  res.end();
}

module.exports = {
  generatePDF
};
<|endoftext|>


<commit_before>function SwatImagePreviewDisplay(id, preview_src, preview_width, preview_height)
{
	this.id = id;

	var image_link = document.getElementById(id + '_link');

	this.overlay = document.createElement('div');
	this.overlay.className = 'swat-image-preview-overlay';
	this.overlay.style.display = 'none';

	this.preview_image = document.createElement('img');
	this.preview_image.src = preview_src;
	this.preview_image.width = preview_width;
	this.preview_image.height = preview_height;

	this.preview_link = document.createElement('a');
	this.preview_link.href = '#';
	this.preview_link.appendChild(this.preview_image);

	this.preview_container = document.createElement('div');
	this.preview_container.className = 'swat-image-preview-container';
	this.preview_container.style.display = 'none';
	this.preview_container.appendChild(this.preview_link);

	this.opened = false;

	// add overlay and preview image to document
	var body = document.getElementsByTagName('body')[0];
	body.appendChild(this.overlay);
	body.appendChild(this.preview_container);

	// setup event handlers
	YAHOO.util.Event.addListener(image_link, 'click',
		this.handleClick, this, true);

	YAHOO.util.Event.addListener(this.preview_container, 'click',
		this.handleClick, this, true);

	YAHOO.util.Event.addListener(this.overlay, 'click',
		this.handleClick, this, true);

	YAHOO.util.Event.addListener(this.preview_link, 'keypress',
		this.handleKeyPress, this, true);
}

/**
 * Padding of preview image
 *
 * @var Number
 */
SwatImagePreviewDisplay.padding = 20;

SwatImagePreviewDisplay.prototype.open = function()
{
	var padding = SwatImagePreviewDisplay.padding;
	var max_width = YAHOO.util.Dom.getViewportWidth() - (padding * 2);
	var max_height = YAHOO.util.Dom.getViewportHeight() - (padding * 2);

	this.overlay.style.width = YAHOO.util.Dom.getDocumentWidth() + 'px';
	this.overlay.style.height = YAHOO.util.Dom.getDocumentHeight() + 'px';

	// if preview image is larger than viewport width, scale down
	if (this.preview_image.width > max_width) {
		this.preview_image.width = max_width;
		this.preview_image.height = (this.preview_image.height *
			(max_width / this.preview_image.width));
	}

	// if preview image is larger than viewport height, scale down
	if (this.preview_image.height > max_height) {
		this.preview_image.width = (this.preview_image.width *
			(max_height / this.preview_image.height));

		this.preview_image.height = max_height;
	}

	this.overlay.style.display = 'block';
	this.preview_container.style.display = 'block';

	var x = (max_width - this.preview_image.width  + padding) / 2;
	var y = (max_height - this.preview_image.height + padding) / 2;

	YAHOO.util.Dom.setXY(this.preview_image, [x, y]);

	// focus link to capture keyboard events
	this.preview_link.focus();

	this.opened = true;
}

SwatImagePreviewDisplay.prototype.close = function()
{
	this.overlay.style.display = 'none';
	this.preview_container.style.display = 'none';

	this.opened = false;
}

SwatImagePreviewDisplay.prototype.handleClick = function(e)
{
	YAHOO.util.Event.preventDefault(e);

	if (this.opened)
		this.close();
	else
		this.open();
}

SwatImagePreviewDisplay.prototype.handleKeyPress = function(e)
{
	YAHOO.util.Event.preventDefault(e);

	// close preview on backspace or escape
	if (e.keyCode == 8 || e.keyCode == 27)
		this.close();
}
<commit_msg>Append elements to link parent instead of body to fix IE crasher bug. Ticket #1249.<commit_after>function SwatImagePreviewDisplay(id, preview_src, preview_width, preview_height)
{
	this.id = id;

	var image_link = document.getElementById(id + '_link');

	this.overlay = document.createElement('div');
	this.overlay.className = 'swat-image-preview-overlay';
	this.overlay.style.display = 'none';

	this.preview_image = document.createElement('img');
	this.preview_image.src = preview_src;
	this.preview_image.width = preview_width;
	this.preview_image.height = preview_height;

	this.preview_link = document.createElement('a');
	this.preview_link.href = '#';
	this.preview_link.appendChild(this.preview_image);

	this.preview_container = document.createElement('div');
	this.preview_container.className = 'swat-image-preview-container';
	this.preview_container.style.display = 'none';
	this.preview_container.appendChild(this.preview_link);

	this.opened = false;

	// add overlay and preview image to document
	image_link.parentNode.appendChild(this.overlay);
	image_link.parentNode.appendChild(this.preview_container);

	// setup event handlers
	YAHOO.util.Event.addListener(image_link, 'click',
		this.handleClick, this, true);

	YAHOO.util.Event.addListener(this.preview_container, 'click',
		this.handleClick, this, true);

	YAHOO.util.Event.addListener(this.overlay, 'click',
		this.handleClick, this, true);

	YAHOO.util.Event.addListener(this.preview_link, 'keypress',
		this.handleKeyPress, this, true);
}

/**
 * Padding of preview image
 *
 * @var Number
 */
SwatImagePreviewDisplay.padding = 20;

SwatImagePreviewDisplay.prototype.open = function()
{
	var padding = SwatImagePreviewDisplay.padding;
	var max_width = YAHOO.util.Dom.getViewportWidth() - (padding * 2);
	var max_height = YAHOO.util.Dom.getViewportHeight() - (padding * 2);

	this.overlay.style.display = 'block';
	YAHOO.util.Dom.setXY(this.overlay, [0, 0]);
	this.overlay.style.width = YAHOO.util.Dom.getDocumentWidth() + 'px';
	this.overlay.style.height = YAHOO.util.Dom.getDocumentHeight() + 'px';

	// if preview image is larger than viewport width, scale down
	if (this.preview_image.width > max_width) {
		this.preview_image.width = max_width;
		this.preview_image.height = (this.preview_image.height *
			(max_width / this.preview_image.width));
	}

	// if preview image is larger than viewport height, scale down
	if (this.preview_image.height > max_height) {
		this.preview_image.width = (this.preview_image.width *
			(max_height / this.preview_image.height));

		this.preview_image.height = max_height;
	}

	this.overlay.style.display = 'block';
	this.preview_container.style.display = 'block';

	var x = (max_width - this.preview_image.width  + padding) / 2;
	var y = (max_height - this.preview_image.height + padding) / 2;

	YAHOO.util.Dom.setXY(this.preview_image, [x, y]);

	// focus link to capture keyboard events
	this.preview_link.focus();

	this.opened = true;
}

SwatImagePreviewDisplay.prototype.close = function()
{
	this.overlay.style.display = 'none';
	this.preview_container.style.display = 'none';

	this.opened = false;
}

SwatImagePreviewDisplay.prototype.handleClick = function(e)
{
	YAHOO.util.Event.preventDefault(e);

	if (this.opened)
		this.close();
	else
		this.open();
}

SwatImagePreviewDisplay.prototype.handleKeyPress = function(e)
{
	YAHOO.util.Event.preventDefault(e);

	// close preview on backspace or escape
	if (e.keyCode == 8 || e.keyCode == 27)
		this.close();
}
<|endoftext|>


<commit_before>/*global angular, d3, _*/
'use strict';

angular.module('mean.system')
.controller('BattleController', ['$scope', 'Global', 'socket', function ($scope, Global, socket) {
    $scope.global = Global;
    console.log( 'Battle started' );
    console.log( window.user.battleCreatures );

    // Game state is contiained in this structure, which is synchronized between devices
    var gameState,
        fire,
        updateArena;
    // Create SVG to hold game arena
    var width = 800;
    var height = 600;
    var creatureSize = 50; // How big creatures should be
    var shotSize = 10; // How big shots should be
    var arena = d3.select('#arena').append('svg')
      .attr('width', width)
      .attr('height', height)
      .style('fill', '#000000')
      .append('g');

    var init = function() {
      // TODO do not hardcode
      //if ( !shift ) {
        //arena.attr( 'transform', 'translate(0, ' + height / 2 + ')' );
      //}
    };

    // Helper functions and behaviours for creatures
    var positionCreature = function( creature ) {
      creature
        .attr( 'xlink:href', function(d) {
          var uniqueName = d.player + d.id;
          // TODO Massive security hole!!!!!
          return 'http://robohash.org/' + uniqueName;
        } )
        .attr('x', function(d) { return d.position.x - 64; })
        .attr('y', function(d) { return d.position.y - 64; })
        .attr('width', 128)
        .attr('height', 128);
    };

    // Add behaviour for dragging, to shoot
    var drag = d3.behavior.drag()
      .origin(function(d) { return d.position; })
      .on('dragstart', function( d ) {
        // Stash away drag points
        d._dragPoints = [];
      })
      .on('drag', function( d ) {
        // Stash
        var point = {
          x: d3.event.x,
          y: d3.event.y
        };
        d._dragPoints.push( point );
      })
      .on('dragend', function( d ) {
        var start = d._dragPoints[0];
        var end = d._dragPoints[d._dragPoints.length - 1];
        console.log( d._dragPoints );
        console.log( start );
        console.log( end );
        var dragDirection = {
          x: end.x - start.x,
          y: end.y - start.y
        };
        console.log( 'Dragged in direction:' );
        console.log( dragDirection );
        var shot = {
          position: start,
          direction: dragDirection,
          creature: d
        };

        fire( shot );
      });

    fire = function( shot ) {
      // Normalize direction
      var factor = shot.direction.y > 0 ? ( height - shot.position.y - 50 ) / shot.direction.y : ( 50 - shot.position.y ) / shot.direction.y;
      shot.direction.x *= factor;
      shot.direction.y *= factor;
      gameState.shots.push( shot );
      updateArena();
      $scope.sendData(gameState);
    };

    // Rendering, binds actions to SVG elements using d3
    updateArena = function() {
      // Add creatures for player one (assuming it's `me`)
      var creatures = arena.selectAll( 'image.creature' )
        .data( gameState.creatures ); // Bind creatures data set to selection

      // Create new creatures
      creatures.enter().append( 'image' )
          .classed('creature', true)
          .call( drag );

      // Update creatures
      creatures
          .call( positionCreature );

      // Add health labels
      var health = arena.selectAll( 'text.health' )
        .data( gameState.creatures );

      health
        .enter().append( 'text' )
          .classed('health', true)
          .style('fill', '#ff4100')
          .attr('x', function(d) { return d.position.x + 30; })
          .attr('y', function(d) { return d.position.y - 20; });

      health
        .text( function( d ) { return d.health; } );

      // Bind drag behaviour to creatures

      // Add shots
      arena.selectAll( 'circle.shot' )
        .data( gameState.shots )
        .enter().append( 'circle' )
          .classed('shot', true)
          .attr('r', shotSize)
          .attr('cx', function(d) { return d.position.x; })
          .attr('cy', function(d) { return d.position.y; })
        .transition()
          .ease( 'linear' )
          .attr('cx', function(d) { return d.position.x + d.direction.x; })
          .attr('cy', function(d) { return d.position.y + d.direction.y; })
          .each( 'end', function( d, i ) {
            // Remove shot at end of animation
            gameState.shots.splice( i, 1 );

            // Check if we hit something (pretty terrible hit-testing, should use line/circle intersection)
            for ( var c in gameState.creatures ) {
              if( gameState.creatures.hasOwnProperty( c ) ) {
                var creature = gameState.creatures[c];
                if ( Math.abs( d.position.x + d.direction.x - creature.position.x ) < 1.1 * creatureSize &&
                     Math.abs( d.position.y + d.direction.y - creature.position.y ) < 2.0 * creatureSize) {
                  creature.health -= 10;
                  updateArena();
                  break;
                }
              }
            }
          })
          .remove();
    };

    //d3.json('system/data.json', function(error, json) {
    //  if (error) {
    //    return console.warn(error);
    //  }
    //  gameState = json;
    //  init();
    //  updateArena();
    //});

  // Receive/send data
	$scope.sendData = function (data) {
		var dataReady = {room: window.gameConnection.room};
    dataReady.data = data;
    socket.emit('gameConnection', dataReady);
	};

  socket.on('gameConnection', function (data) {
    mergeState( data );
    console.log( gameState );
    updateArena();
  });

  // Generate game data (mock out data for now)
  gameState = {
    'creatures': [],
    'shots': []
  };
  for( var a = 0; a < 3; a++ ) {
    var creature = {
      'id': 'creature_' + a,
      'player': window.user.username,
      'health': 100,
      'attack': 7,
      'defense': 4,
      'type': 'fire',
      'position': {
        'x': 50 + 350 * a,
        'y': 50
      }
    };
    gameState.creatures.push( creature );
  }
  console.log( gameState );
  $scope.sendData( gameState );
  init();

  var mergeState = function( data ) {
    console.log( 'Merging state' );
    if ( data.data ) {
      // Combine all creatures
      gameState.creatures = gameState.creatures.concat( data.data.creatures );
      gameState.creatures = _.uniq( gameState.creatures, false, function( d ) { return d.player + d.id; } );

      // Combine all shots
      gameState.shots = gameState.shots.concat( data.data.shots );
      gameState.shots = _.uniq( gameState.shots, false, function( d ) { return d.creature.player + d.creature.id; } );

      // Get players to figure out who to put at bottom
      var players = _.uniq( _.pluck( gameState.creatures, 'player' ) );
      players.sort();

      // Shift bottom player's creatures to bottom of screen
      var bottomPlayer = players[0];
      console.log( 'players ' + players);
      console.log( 'Bottom ' + bottomPlayer);
      _.each( gameState.creatures, function( creature ) {
        if ( creature.player === bottomPlayer ) {
          creature.position.y = 550;
        }
      } );
      //if ( bottomPlayer === me ) {
      //  // Do something...
      //}
    }
  };
}]);
<commit_msg>Load in creatures passed in<commit_after>/*global angular, d3, _*/
'use strict';

angular.module('mean.system')
.controller('BattleController', ['$scope', 'Global', 'socket', function ($scope, Global, socket) {
    $scope.global = Global;
    console.log( 'Battle started' );
    console.log( window.user.battleCreatures );

    // Game state is contiained in this structure, which is synchronized between devices
    var gameState,
        fire,
        updateArena;
    // Create SVG to hold game arena
    var width = 800;
    var height = 600;
    var creatureSize = 50; // How big creatures should be
    var shotSize = 10; // How big shots should be
    var arena = d3.select('#arena').append('svg')
      .attr('width', width)
      .attr('height', height)
      .style('fill', '#000000')
      .append('g');

    var init = function() {
      // TODO do not hardcode
      //if ( !shift ) {
        //arena.attr( 'transform', 'translate(0, ' + height / 2 + ')' );
      //}
    };

    // Helper functions and behaviours for creatures
    var positionCreature = function( creature ) {
      creature
        .attr( 'xlink:href', function(d) {
          var uniqueName = d.player + d.id;
          // TODO Massive security hole!!!!!
          return 'http://robohash.org/' + uniqueName;
        } )
        .attr('x', function(d) { return d.position.x - 64; })
        .attr('y', function(d) { return d.position.y - 64; })
        .attr('width', 128)
        .attr('height', 128);
    };

    // Add behaviour for dragging, to shoot
    var drag = d3.behavior.drag()
      .origin(function(d) { return d.position; })
      .on('dragstart', function( d ) {
        // Stash away drag points
        d._dragPoints = [];
      })
      .on('drag', function( d ) {
        // Stash
        var point = {
          x: d3.event.x,
          y: d3.event.y
        };
        d._dragPoints.push( point );
      })
      .on('dragend', function( d ) {
        var start = d._dragPoints[0];
        var end = d._dragPoints[d._dragPoints.length - 1];
        console.log( d._dragPoints );
        console.log( start );
        console.log( end );
        var dragDirection = {
          x: end.x - start.x,
          y: end.y - start.y
        };
        console.log( 'Dragged in direction:' );
        console.log( dragDirection );
        var shot = {
          position: start,
          direction: dragDirection,
          creature: d
        };

        fire( shot );
      });

    fire = function( shot ) {
      // Normalize direction
      var factor = shot.direction.y > 0 ? ( height - shot.position.y - 50 ) / shot.direction.y : ( 50 - shot.position.y ) / shot.direction.y;
      shot.direction.x *= factor;
      shot.direction.y *= factor;
      gameState.shots.push( shot );
      updateArena();
      $scope.sendData(gameState);
    };

    // Rendering, binds actions to SVG elements using d3
    updateArena = function() {
      // Add creatures for player one (assuming it's `me`)
      var creatures = arena.selectAll( 'image.creature' )
        .data( gameState.creatures ); // Bind creatures data set to selection

      // Create new creatures
      creatures.enter().append( 'image' )
          .classed('creature', true)
          .call( drag );

      // Update creatures
      creatures
          .call( positionCreature );

      // Add health labels
      var health = arena.selectAll( 'text.health' )
        .data( gameState.creatures );

      health
        .enter().append( 'text' )
          .classed('health', true)
          .style('fill', '#ff4100')
          .attr('x', function(d) { return d.position.x + 30; })
          .attr('y', function(d) { return d.position.y - 20; });

      health
        .text( function( d ) { return d.health; } );

      // Bind drag behaviour to creatures

      // Add shots
      arena.selectAll( 'circle.shot' )
        .data( gameState.shots )
        .enter().append( 'circle' )
          .classed('shot', true)
          .attr('r', shotSize)
          .attr('cx', function(d) { return d.position.x; })
          .attr('cy', function(d) { return d.position.y; })
        .transition()
          .ease( 'linear' )
          .attr('cx', function(d) { return d.position.x + d.direction.x; })
          .attr('cy', function(d) { return d.position.y + d.direction.y; })
          .each( 'end', function( d, i ) {
            // Remove shot at end of animation
            gameState.shots.splice( i, 1 );

            // Check if we hit something (pretty terrible hit-testing, should use line/circle intersection)
            for ( var c in gameState.creatures ) {
              if( gameState.creatures.hasOwnProperty( c ) ) {
                var creature = gameState.creatures[c];
                if ( Math.abs( d.position.x + d.direction.x - creature.position.x ) < 1.1 * creatureSize &&
                     Math.abs( d.position.y + d.direction.y - creature.position.y ) < 2.0 * creatureSize) {
                  creature.health -= 10;
                  updateArena();
                  break;
                }
              }
            }
          })
          .remove();
    };

    //d3.json('system/data.json', function(error, json) {
    //  if (error) {
    //    return console.warn(error);
    //  }
    //  gameState = json;
    //  init();
    //  updateArena();
    //});

  // Receive/send data
	$scope.sendData = function (data) {
		var dataReady = {room: window.gameConnection.room};
    dataReady.data = data;
    socket.emit('gameConnection', dataReady);
	};

  socket.on('gameConnection', function (data) {
    mergeState( data );
    console.log( gameState );
    updateArena();
  });

  // Generate game data
  gameState = {
    'creatures': [],
    'shots': []
  };
  for( var a = 0; a < window.user.battleCreatures.length; a++ ) {
    var creature = window.user.battleCreatures[a];
    creature.id = creature._id; // TODO refactor to avoid id duplication
    creature.player = window.user.username;
    creature.position = {
      'x': 50 + 350 * a,
      'y': 50
    };
    gameState.creatures.push( creature );
  }
  console.log( gameState );
  $scope.sendData( gameState );
  init();

  var mergeState = function( data ) {
    console.log( 'Merging state' );
    if ( data.data ) {
      // Combine all creatures
      gameState.creatures = gameState.creatures.concat( data.data.creatures );
      gameState.creatures = _.uniq( gameState.creatures, false, function( d ) { return d.player + d.id; } );

      // Combine all shots
      gameState.shots = gameState.shots.concat( data.data.shots );
      gameState.shots = _.uniq( gameState.shots, false, function( d ) { return d.creature.player + d.creature.id; } );

      // Get players to figure out who to put at bottom
      var players = _.uniq( _.pluck( gameState.creatures, 'player' ) );
      players.sort();

      // Shift bottom player's creatures to bottom of screen
      var bottomPlayer = players[0];
      console.log( 'players ' + players);
      console.log( 'Bottom ' + bottomPlayer);
      _.each( gameState.creatures, function( creature ) {
        if ( creature.player === bottomPlayer ) {
          creature.position.y = 550;
        }
      } );
      //if ( bottomPlayer === me ) {
      //  // Do something...
      //}
    }
  };
}]);
<|endoftext|>


<commit_before>import styled, { css } from "styled-components";
import { colors } from "@crave/farmblocks-theme";

const border = `1px solid ${colors.GREY_16}`;

const Table = styled.table`
  border-collapse: collapse;
  border: ${props => !props.borderless && border};
  padding: 8px 16px;

  ${props =>
    props.selectionHeaderVisible &&
    css`
      border-top: none;
    `};
  .cell {
    box-sizing: border-box;
    height: ${props => props.rowHeight};
    border-bottom: ${border};
    padding: 16px 0 16px 16px;

    &:last-child {
      padding-right: 16px;
    }

    &.corner-icon {
      position: relative;
      padding-left: 40px;
    }

    /* corner icon for grouped rows */
    &.corner-icon:before {
      content: "";
      float: left;
      box-sizing: border-box;
      width: 8px;
      height: 8px;
      border-left: 2px solid ${colors.INDIGO_MILK_CAP};
      border-bottom: 2px solid ${colors.INDIGO_MILK_CAP};
      position: absolute;
      top: calc(50% - 3px);
      left: 16px;
    }

    /* @HACK checkbox component already have a left padding,
     so we use negative margin to keep only the table padding */
    & .checkbox {
      height: 16px;
      margin-left: -8px;
    }
  }

  tbody.collapsed tr.grouped {
    display: none;
  }

  tbody tr:hover {
    & .cell {
      background: ${colors.DEMERARA_SUGAR};
    }
  }

  tbody tr.clickable {
    cursor: pointer;
  }
`;

export default Table;
<commit_msg>feat(Table): increase row selection checkbox hit area<commit_after>import styled, { css } from "styled-components";
import { colors } from "@crave/farmblocks-theme";

const border = `1px solid ${colors.GREY_16}`;

const Table = styled.table`
  border-collapse: collapse;
  border: ${props => !props.borderless && border};
  padding: 8px 16px;

  ${props =>
    props.selectionHeaderVisible &&
    css`
      border-top: none;
    `};
  .cell {
    box-sizing: border-box;
    height: ${props => props.rowHeight};
    border-bottom: ${border};
    padding: 16px 0 16px 16px;

    &:last-child {
      padding-right: 16px;
    }

    &.corner-icon {
      position: relative;
      padding-left: 40px;
    }

    /* corner icon for grouped rows */
    &.corner-icon:before {
      content: "";
      float: left;
      box-sizing: border-box;
      width: 8px;
      height: 8px;
      border-left: 2px solid ${colors.INDIGO_MILK_CAP};
      border-bottom: 2px solid ${colors.INDIGO_MILK_CAP};
      position: absolute;
      top: calc(50% - 3px);
      left: 16px;
    }

    & .checkbox {
      height: 16px;

      label {
        /*  Increase the hit area of the checkbox
            This is important for tables with onRowClick */
        padding: 8px;
        margin: -8px;
      }
    }
  }

  tbody.collapsed tr.grouped {
    display: none;
  }

  tbody tr:hover {
    & .cell {
      background: ${colors.DEMERARA_SUGAR};
    }
  }

  tbody tr.clickable {
    cursor: pointer;
  }
`;

export default Table;
<|endoftext|>


<commit_before>/**
 * Alphagov Locator jQuery plugin
 * @name locator-0.4.js
 * @author Matt Patterson
 * @version 0.4
 * @date April 29, 2011
 * @category jQuery plugin
 */
(function($) {
  /**
   * $ is an alias to jQuery object
   */
  $.fn.locator = function(settings) {
    var locator_form = this.closest('form'),
        locator_box = this,
        settings = settings || {},
        ignore_location_known_on_page_load = settings.ignore_location_known_on_page_load || false,
        error_area_selector = settings.error_area_selector || '#global-app-error',
        submit_form_without_ajax = settings.submit_form_without_ajax || false,
        ask_ui = locator_box.find('.ask_location'),
        locating_ui = locator_box.find('.finding_location'),
        found_ui = locator_box.find('.found_location'),
        all_ui = ask_ui.add(locating_ui).add(found_ui),
        geolocate_ui;

    /* Helper functions */
    var setup_geolocation_api_ui = function() {
      var geolocation_ui_node = ask_ui.find('.locate-me');
      if (geolocation_ui_node.length > 0) return geolocation_ui_node;
      return $('
or locate me automatically
').appendTo(ask_ui);
    };
    var show_ui = function(ui_to_show) {
      all_ui.addClass('hidden');
      ui_to_show.removeClass('hidden');
    };
    var update_geo_labels = function(geo_data) {
      display_name = Alphagov.get_display_place_name(geo_data.locality, geo_data.councils[geo_data.councils.length - 1].name);
      found_ui.find('h3').text(display_name);
      found_ui.find('a').text('Not in ' + geo_data.locality + '?');
    };
    var update_geo_fields = function(geo_data) {
      locator_box.find('input[name=lat]').val(geo_data.lat);
      locator_box.find('input[name=lon]').val(geo_data.lon);
    };
    var clear_geo_fields = function() {
      locator_box.find('input[name=lat]').val('');
      locator_box.find('input[name=lon]').val('');
    };
    var dispatch_location = function(response_data) {
      if (response_data.current_location === undefined) {
        $(error_area_selector).empty().append("
Please enter a valid UK postcode.
").removeClass('hidden');
        show_ui(ask_ui);
      } else if (! response_data.current_location.locality) {
        $(error_area_selector).empty().append("
Sorry, that postcode was not recognised.
").removeClass('hidden');
        show_ui(ask_ui);
      } else {
        $(error_area_selector).empty().addClass("hidden");
        $(document).trigger('location-changed', response_data);
      }
    }
    var changed_location = function(data) {
      if (data.current_location != undefined) {
        update_geo_labels(data.current_location);
        update_geo_fields(data.current_location);
        show_ui(found_ui);
        locator_box.data('located', true);
      }
      else {
        show_ui(ask_ui);
        locator_box.data('located', false);
      }
    }
    var reset_location = function() {
      clear_geo_fields();
      found_ui.find('h3').text('');
      show_ui(ask_ui);
      locator_box.data('located', false);
    }

    // Check to see if we're starting located
    locator_box.data('located', !found_ui.hasClass('hidden'))
    // Locator setup
    found_ui.find('a').click(function (e) {
      $(document).trigger('location-removed');
      e.preventDefault();
    });
    if (navigator.geolocation) {
      var geolocate_ui = setup_geolocation_api_ui();
      geolocate_ui.bind('location-started', function () {
        show_ui(locating_ui);
      });
      geolocate_ui.bind('location-failed', function () {
        $(this).text('We were not able to locate you.');
        show_ui(ask_ui);
      });
      geolocate_ui.bind('location-completed', function (event, details) {
        update_geo_fields(details);
        if (settings.submit_form_without_ajax) {
          locator_form.submit();
        }
        else {
          $.post(locator_form[0].action, locator_form.serialize(), dispatch_location, 'json');
        }
      });
      geolocate_ui.find('a').click(function (e) {
        var parent_element = $(this).closest('.locate-me');

        geolocate_ui.trigger('location-started');
        browserSupportFlag = true;
        navigator.geolocation.getCurrentPosition(
          function(position) {
            var new_location = {lat: position.coords.latitude, lon: position.coords.longitude};
            geolocate_ui.trigger('location-completed', new_location);
          },
          function() {
            geolocate_ui.trigger('location-failed');
          }
        );

        e.preventDefault();
        // return false;
      });
    }
    if (!ignore_location_known_on_page_load) {
      $(document).bind('location-known', function(e, data) {
        changed_location(data);
      });
    }
    $(document).bind('location-changed', function(e, data) {
      changed_location(data);
    });
    $(document).bind('location-removed', function() {
      reset_location();
    });
    locator_box.bind('reset-locator-form', function() {
      reset_location();
    });
    locator_box.bind('check-locator-form-state', function() {
      show_ui(locator_box.data('located') ? found_ui : ask_ui);
    });
    locator_form.submit(function(e) {
      clear_geo_fields();
      if (!settings.submit_form_without_ajax) {
        e.preventDefault();
        $.post(locator_form[0].action, locator_form.serialize(), dispatch_location, 'json');
      }
      show_ui(locating_ui);
    });
  }
})(jQuery);

var no_location_change_animation;
var AlphaGeo = {
  readAndParseJSONCookie: function(name) {
    var cookie = Alphagov.read_cookie(name);
    if (cookie) {
      var json_cookie = $.base64Decode(cookie);
      var geo_json = jQuery.parseJSON(json_cookie);
      return geo_json;
    }
    return false;
  },

  locationName: function() {
    var geo_json = AlphaGeo.readAndParseJSONCookie('geo');
    if (geo_json && geo_json["friendly_name"]) {
      return geo_json["friendly_name"];
    } else {
      return null;
    }
  },

  councils: function() {
    var geo_json = AlphaGeo.readAndParseJSONCookie('geo');
    var councils = [];
    if (geo_json && geo_json["ward"]) {
      councils = councils.concat(geo_json["ward"]);
    }
    if (geo_json && geo_json["council"]) {
      councils = councils.concat(geo_json["council"]);
    }
    return councils;
  },

  locationCoords: function() {
    var geo_json = AlphaGeo.readAndParseJSONCookie('geo');
    if (geo_json && geo_json["fuzzy_point"]) {
      return {lat: geo_json.fuzzy_point.lat, lon: geo_json.fuzzy_point.lon};
    } else {
      return {lat: null, lon: null};
    }
  },

  locator_object: function() {
    return {
      locality: AlphaGeo.locationName(),
      lat: AlphaGeo.locationCoords().lat,
      lon: AlphaGeo.locationCoords().lon,
      councils: AlphaGeo.councils()
    }
  },

  deleteGeoCookie: function() {
    Alphagov.delete_cookie('geo');
  }
};

$(document).ready(function() {
  $('#large-locator-form').locator();
  $('#global-locator-form').locator({
    ignore_location_known_on_page_load: true,
    error_area_selector: '#global-locator-error'
  });
  var set_location_known = function(current_location, highlight_func) {
    highlight_func();

    //show correct message
    $('#location-set-message').show();
    $('#location-unset-message').hide();

    //set the name of the place
    display_name = Alphagov.get_display_place_name(current_location.locality, AlphaGeo.councils()[AlphaGeo.councils().length - 1].name);
    $("#location-name").html(display_name);

    //set local info
    $('#location-notifications').click(
      function(){
        $('#local-info').show();
        $('#local-info-box .close').click(
          function(){
            $('#local-info').hide();
          }
        );
        return false;
      }
    );
  };
  var setup_location_change_highlight = function() {
    if ($("#global-user-location span.text-highlight").length == 0) {
      $('').prependTo("#global-user-location p").hide();
    }
  }
  var flash_location_change_state = function() {
    if (!no_location_change_animation && no_location_change_animation != true) {
      var pins = $("#global-user-location");
      var scale_back = function() { pins.removeClass('changing'); }
      var scale_up = function() { pins.addClass('changing'); }
      window.setTimeout(scale_up, 200);
      window.setTimeout(scale_back, 850);
      $('#global-user-location p span.text-highlight').fadeIn(750).fadeOut(750);
    }
  }
  var set_location_unknown = function(highlight_func) {
    if (highlight_func != undefined) {
      highlight_func();
    }
    //set class on the geo elements
    $("#global-user-location").addClass('removing');
    setup_location_change_highlight();
    $("#global-user-location").removeClass('set');
    flash_location_change_state();

    //show correct message
    $('#location-set-message').hide();
    $('#location-unset-message').show();

    //delete cookie
    AlphaGeo.deleteGeoCookie();
  }
  $(document).bind('location-known', function(e, data) {
    set_location_known(data.current_location, function() {
      $("#global-user-location").addClass('set');
    })
  });
  $(document).bind('location-changed', function(e, data) {
    set_location_known(data.current_location, function() {
      $("#global-user-location").addClass('setting');
      setup_location_change_highlight();
      $("#global-user-location").addClass('set');
      flash_location_change_state();
    });
  });
  $(document).bind('location-removed', function(e, message) {
    set_location_unknown();
  });
  // setup extra HTML
  var located = AlphaGeo.locationName();
  if (located) $(document).trigger('location-known', {current_location: AlphaGeo.locator_object()});
  $('#global-locator .close').click(function() {
    $('#global-locator').hide();
    return false;
  });

  var open_location_dialog = function() {
    $('#global-locator').show();
    $('#global-locator-form').trigger('reset-locator-form');
  };
  // Event handlers
  $(document).bind('request-location', open_location_dialog);
  $('#global-user-location .change-location').click(function() {
    $(document).trigger('request-location');
    return false;
  });
  $('#global-user-location .explain-location').click(function() {
    $(document).trigger('request-location');
    return false;
  });
  $('#forget-location').click(function() {
    $(document).trigger('location-removed');
    $('#global-locator').hide();
    return false;
  });
  $(document).bind('location-changed', function() {
    $('#global-locator').hide();
  });
});
<commit_msg>Use null ward to detect unrecognised postcodes<commit_after>/**
 * Alphagov Locator jQuery plugin
 * @name locator-0.4.js
 * @author Matt Patterson
 * @version 0.4
 * @date April 29, 2011
 * @category jQuery plugin
 */
(function($) {
  /**
   * $ is an alias to jQuery object
   */
  $.fn.locator = function(settings) {
    var locator_form = this.closest('form'),
        locator_box = this,
        settings = settings || {},
        ignore_location_known_on_page_load = settings.ignore_location_known_on_page_load || false,
        error_area_selector = settings.error_area_selector || '#global-app-error',
        submit_form_without_ajax = settings.submit_form_without_ajax || false,
        ask_ui = locator_box.find('.ask_location'),
        locating_ui = locator_box.find('.finding_location'),
        found_ui = locator_box.find('.found_location'),
        all_ui = ask_ui.add(locating_ui).add(found_ui),
        geolocate_ui;

    /* Helper functions */
    var setup_geolocation_api_ui = function() {
      var geolocation_ui_node = ask_ui.find('.locate-me');
      if (geolocation_ui_node.length > 0) return geolocation_ui_node;
      return $('
or locate me automatically
').appendTo(ask_ui);
    };
    var show_ui = function(ui_to_show) {
      all_ui.addClass('hidden');
      ui_to_show.removeClass('hidden');
    };
    var update_geo_labels = function(geo_data) {
      display_name = Alphagov.get_display_place_name(geo_data.locality, geo_data.councils[geo_data.councils.length - 1].name);
      found_ui.find('h3').text(display_name);
      found_ui.find('a').text('Not in ' + geo_data.locality + '?');
    };
    var update_geo_fields = function(geo_data) {
      locator_box.find('input[name=lat]').val(geo_data.lat);
      locator_box.find('input[name=lon]').val(geo_data.lon);
    };
    var clear_geo_fields = function() {
      locator_box.find('input[name=lat]').val('');
      locator_box.find('input[name=lon]').val('');
    };
    var dispatch_location = function(response_data) {
      if (response_data.current_location === undefined) {
        $(error_area_selector).empty().append("
Please enter a valid UK postcode.
").removeClass('hidden');
        show_ui(ask_ui);
      } else if (! response_data.current_location.ward) {
        $(error_area_selector).empty().append("
Sorry, that postcode was not recognised.
").removeClass('hidden');
        show_ui(ask_ui);
      } else {
        $(error_area_selector).empty().addClass("hidden");
        $(document).trigger('location-changed', response_data);
      }
    }
    var changed_location = function(data) {
      if (data.current_location != undefined) {
        update_geo_labels(data.current_location);
        update_geo_fields(data.current_location);
        show_ui(found_ui);
        locator_box.data('located', true);
      }
      else {
        show_ui(ask_ui);
        locator_box.data('located', false);
      }
    }
    var reset_location = function() {
      clear_geo_fields();
      found_ui.find('h3').text('');
      show_ui(ask_ui);
      locator_box.data('located', false);
    }

    // Check to see if we're starting located
    locator_box.data('located', !found_ui.hasClass('hidden'))
    // Locator setup
    found_ui.find('a').click(function (e) {
      $(document).trigger('location-removed');
      e.preventDefault();
    });
    if (navigator.geolocation) {
      var geolocate_ui = setup_geolocation_api_ui();
      geolocate_ui.bind('location-started', function () {
        show_ui(locating_ui);
      });
      geolocate_ui.bind('location-failed', function () {
        $(this).text('We were not able to locate you.');
        show_ui(ask_ui);
      });
      geolocate_ui.bind('location-completed', function (event, details) {
        update_geo_fields(details);
        if (settings.submit_form_without_ajax) {
          locator_form.submit();
        }
        else {
          $.post(locator_form[0].action, locator_form.serialize(), dispatch_location, 'json');
        }
      });
      geolocate_ui.find('a').click(function (e) {
        var parent_element = $(this).closest('.locate-me');

        geolocate_ui.trigger('location-started');
        browserSupportFlag = true;
        navigator.geolocation.getCurrentPosition(
          function(position) {
            var new_location = {lat: position.coords.latitude, lon: position.coords.longitude};
            geolocate_ui.trigger('location-completed', new_location);
          },
          function() {
            geolocate_ui.trigger('location-failed');
          }
        );

        e.preventDefault();
        // return false;
      });
    }
    if (!ignore_location_known_on_page_load) {
      $(document).bind('location-known', function(e, data) {
        changed_location(data);
      });
    }
    $(document).bind('location-changed', function(e, data) {
      changed_location(data);
    });
    $(document).bind('location-removed', function() {
      reset_location();
    });
    locator_box.bind('reset-locator-form', function() {
      reset_location();
    });
    locator_box.bind('check-locator-form-state', function() {
      show_ui(locator_box.data('located') ? found_ui : ask_ui);
    });
    locator_form.submit(function(e) {
      clear_geo_fields();
      if (!settings.submit_form_without_ajax) {
        e.preventDefault();
        $.post(locator_form[0].action, locator_form.serialize(), dispatch_location, 'json');
      }
      show_ui(locating_ui);
    });
  }
})(jQuery);

var no_location_change_animation;
var AlphaGeo = {
  readAndParseJSONCookie: function(name) {
    var cookie = Alphagov.read_cookie(name);
    if (cookie) {
      var json_cookie = $.base64Decode(cookie);
      var geo_json = jQuery.parseJSON(json_cookie);
      return geo_json;
    }
    return false;
  },

  locationName: function() {
    var geo_json = AlphaGeo.readAndParseJSONCookie('geo');
    if (geo_json && geo_json["friendly_name"]) {
      return geo_json["friendly_name"];
    } else {
      return null;
    }
  },

  councils: function() {
    var geo_json = AlphaGeo.readAndParseJSONCookie('geo');
    var councils = [];
    if (geo_json && geo_json["ward"]) {
      councils = councils.concat(geo_json["ward"]);
    }
    if (geo_json && geo_json["council"]) {
      councils = councils.concat(geo_json["council"]);
    }
    return councils;
  },

  locationCoords: function() {
    var geo_json = AlphaGeo.readAndParseJSONCookie('geo');
    if (geo_json && geo_json["fuzzy_point"]) {
      return {lat: geo_json.fuzzy_point.lat, lon: geo_json.fuzzy_point.lon};
    } else {
      return {lat: null, lon: null};
    }
  },

  locator_object: function() {
    return {
      locality: AlphaGeo.locationName(),
      lat: AlphaGeo.locationCoords().lat,
      lon: AlphaGeo.locationCoords().lon,
      councils: AlphaGeo.councils()
    }
  },

  deleteGeoCookie: function() {
    Alphagov.delete_cookie('geo');
  }
};

$(document).ready(function() {
  $('#large-locator-form').locator();
  $('#global-locator-form').locator({
    ignore_location_known_on_page_load: true,
    error_area_selector: '#global-locator-error'
  });
  var set_location_known = function(current_location, highlight_func) {
    highlight_func();

    //show correct message
    $('#location-set-message').show();
    $('#location-unset-message').hide();

    //set the name of the place
    display_name = Alphagov.get_display_place_name(current_location.locality, AlphaGeo.councils()[AlphaGeo.councils().length - 1].name);
    $("#location-name").html(display_name);

    //set local info
    $('#location-notifications').click(
      function(){
        $('#local-info').show();
        $('#local-info-box .close').click(
          function(){
            $('#local-info').hide();
          }
        );
        return false;
      }
    );
  };
  var setup_location_change_highlight = function() {
    if ($("#global-user-location span.text-highlight").length == 0) {
      $('').prependTo("#global-user-location p").hide();
    }
  }
  var flash_location_change_state = function() {
    if (!no_location_change_animation && no_location_change_animation != true) {
      var pins = $("#global-user-location");
      var scale_back = function() { pins.removeClass('changing'); }
      var scale_up = function() { pins.addClass('changing'); }
      window.setTimeout(scale_up, 200);
      window.setTimeout(scale_back, 850);
      $('#global-user-location p span.text-highlight').fadeIn(750).fadeOut(750);
    }
  }
  var set_location_unknown = function(highlight_func) {
    if (highlight_func != undefined) {
      highlight_func();
    }
    //set class on the geo elements
    $("#global-user-location").addClass('removing');
    setup_location_change_highlight();
    $("#global-user-location").removeClass('set');
    flash_location_change_state();

    //show correct message
    $('#location-set-message').hide();
    $('#location-unset-message').show();

    //delete cookie
    AlphaGeo.deleteGeoCookie();
  }
  $(document).bind('location-known', function(e, data) {
    set_location_known(data.current_location, function() {
      $("#global-user-location").addClass('set');
    })
  });
  $(document).bind('location-changed', function(e, data) {
    set_location_known(data.current_location, function() {
      $("#global-user-location").addClass('setting');
      setup_location_change_highlight();
      $("#global-user-location").addClass('set');
      flash_location_change_state();
    });
  });
  $(document).bind('location-removed', function(e, message) {
    set_location_unknown();
  });
  // setup extra HTML
  var located = AlphaGeo.locationName();
  if (located) $(document).trigger('location-known', {current_location: AlphaGeo.locator_object()});
  $('#global-locator .close').click(function() {
    $('#global-locator').hide();
    return false;
  });

  var open_location_dialog = function() {
    $('#global-locator').show();
    $('#global-locator-form').trigger('reset-locator-form');
  };
  // Event handlers
  $(document).bind('request-location', open_location_dialog);
  $('#global-user-location .change-location').click(function() {
    $(document).trigger('request-location');
    return false;
  });
  $('#global-user-location .explain-location').click(function() {
    $(document).trigger('request-location');
    return false;
  });
  $('#forget-location').click(function() {
    $(document).trigger('location-removed');
    $('#global-locator').hide();
    return false;
  });
  $(document).bind('location-changed', function() {
    $('#global-locator').hide();
  });
});
<|endoftext|>


<commit_before>import 'babel-polyfill'; // fixme

// new VeritoneApp([...widgets])
import React from 'react';
import ReactDOM from 'react-dom';
// import { Sagas } from 'react-redux-saga'; // fixme -- need to fork this and make compatible with react16
import { Provider } from 'react-redux';

import configureStore from './redux/configureStore';

export default class VeritoneApp {
  constructor(...widgets) {
    this._widgets = widgets;
    this._store = configureStore();

    const existingApp = document.getElementById('veritone-react-app');
    if (existingApp) {
      // todo: should this be an error?
      console.warn(
        'The DOM element from a VeritoneApp instance already exists on this page. Deleting it.'
      );

      document.removeChild(existingApp);
    }
  }

  _renderReactApp() {
    ReactDOM.render(
      <VeritoneRootComponent store={this._store} widgets={this._widgets} />,
      this._containerEl
    );
  }

  mount() {
    this._containerEl = document.createElement('div');
    this._containerEl.setAttribute('id', 'veritone-react-app');
    document.body.appendChild(this._containerEl);

    this._widgets.forEach(w => w.init());
    this._renderReactApp();
  }
}

class VeritoneRootComponent extends React.Component {
  render() {
    const components = this.props.widgets.map(w => w.getComponent());

    return (
      <Provider store={this.props.store}>

          This is the veritone app
          {this.props.widgets.map(w =>
            w.el && ReactDOM.createPortal(React.createElement(w.getComponent()), w.el)
          )}

      </Provider>
    );
  }
}
<commit_msg>cleanup<commit_after>import 'babel-polyfill'; // fixme

// new VeritoneApp([...widgets])
import React from 'react';
import ReactDOM from 'react-dom';
// import { Sagas } from 'react-redux-saga'; // fixme -- need to fork this and make compatible with react16
import { Provider } from 'react-redux';

import configureStore from './redux/configureStore';

export default class VeritoneApp {
  constructor(...widgets) {
    this._widgets = widgets;
    this._store = configureStore();
    this._containerEl = null;

    const existingApp = document.getElementById('veritone-react-app');
    if (existingApp) {
      // todo: should this be an error?
      console.warn(
        'The DOM element from a VeritoneApp instance already exists on this page. Deleting it.'
      );

      document.removeChild(existingApp);
    }
  }

  mount() {
    this._containerEl = document.createElement('div', { id: 'veritone-react-app'});
    document.body.appendChild(this._containerEl);

    this._widgets.forEach(w => w.init());
    this._renderReactApp();
  }

  _renderReactApp() {
    ReactDOM.render(
      <VeritoneRootComponent store={this._store} widgets={this._widgets} />,
      this._containerEl
    );
  }
}

class VeritoneRootComponent extends React.Component {
  render() {
    const components = this.props.widgets.map(w => w.getComponent());

    return (
      <Provider store={this.props.store}>

          This is the veritone app
          {this.props.widgets.map(
            w =>
              w.el &&
              ReactDOM.createPortal(React.createElement(w.getComponent()), w.el)
          )}

      </Provider>
    );
  }
}
<|endoftext|>