<commit_before>var cy = cytoscape();

// {name : position} dict
var prebuilt_model = 'McCormick';
var preset_pos = {};
var preset_pos_static = {}

// {id : position} dict
var id_pos = {};

var scapes = {};

var indra_server_addr = "http://0.0.0.0:8080"

var ctxt = {}
grabJSON('static/models/' + prebuilt_model + '/model_context.json').then(
  function(ajax_response){
    console.log('done')
    ctxt =  ajax_response
  })

var korkut = {}
grabJSON('static/models/' + 'Korkut' + '/korkut.json').then(
  function(ajax_response){
    console.log('done')
    korkut =  ajax_response
  })
var condition = 'AK|10'

var domain = [2.7, 3.7, 4.7, 5.7, 6.7, 7.7, 8.7, 9.7, 10.7]
var exp_colorscale = d3.scaleThreshold()
    .domain(domain)
    .range(['#f7fcf5','#e5f5e0','#c7e9c0','#a1d99b','#74c476','#41ab5d','#238b45','#006d2c','#00441b']);
var mut_colorscale =  d3.scaleThreshold()
    .domain(domain)
    .range(['#fff5eb','#fee6ce','#fdd0a2','#fdae6b','#fd8d3c','#f16913','#d94801','#a63603','#7f2704']);

var parser = 'trips';

$(function(){

  var win = $(window);

  // build the dropdown pickers
  grabJSON('static/cell_dict.json').then(
    function(ajax_response){
      var prebuilt_models = {"McCormick":"McCormick", "Korkut":"Korkut", "Korkut2":"Korkut2"};
      dropdownFromJSON('#model_picker', prebuilt_models)
      }
  )

  // build the dropdown pickers
  grabJSON('static/cell_dict.json').then(
    function(ajax_response){

      var interesting_lines = {"A101D_SKIN":"model_A101D_SKIN.json", "LOXIMVI_SKIN":"model_LOXIMVI_SKIN.json"};
      for (var d of ['#cellSelectStatic', '#cellSelectDynamic']) {
          dropdownFromJSON(d, interesting_lines)
          $(d).append($('<option data-divider="true"/>'))
        }

      for (var d of ['#cellSelectStatic', '#cellSelectDynamic']) {
          dropdownFromJSON(d, ajax_response)
        }

      }
  )

  // set the preset_pos
  setPresetPos()

  $("#loadButtonDynamic").click(function(){
    var txt = $('#textArea')[0].value

    txtProcess(txt, parser).then(groundingMapper).then(assembleCyJS).then(function (model_response) {
      drawCytoscape('cy_1', model_response)
      qtipNodes(scapes['cy_1'])
    });
    // txtProcess(txt, parser).then(assembleCyJS).then(function (model_response) {
    //   drawCytoscape ('cy_1', model_response)
    // });
    $('.cyjs2loopy').prop('disabled', false);
    console.log($('#cellSelectDynamic').val().substring(6));
  });

  $("#loadContextButton").click(function(){
    var cell_line = $('#cellSelectDynamic').val().slice(6,-5)
    contextualizeNodesCCLE(cy, cell_line)
    console.log($('#cellSelectDynamic').val().substring(6));
  });

  $("#downloadPySB").click(function(){
    var txt = $('#textArea')[0].value

    txtProcess(txt, parser).then(groundingMapper).then(assemblePySB).then(function (res) {
      download($('#cellSelectDynamic').val().slice(6,-5)+'.py', res['model'])
    });
    // txtProcess(txt, parser).then(assembleCyJS).then(function (model_response) {
    //   drawCytoscape ('cy_1', model_response)
    // });

    console.log($('#cellSelectDynamic').val().substring(6));
  });

  $("#downloadINDRA").click(function(){
    var txt = $('#textArea')[0].value

    txtProcess(txt, parser).then(groundingMapper).then(function (res) {
      download($('#cellSelectDynamic').val()+'_INDRA_stmts.json', JSON.stringify(res['statements'], null, 2))
    });
    // txtProcess(txt, parser).then(assembleCyJS).then(function (model_response) {
    //   drawCytoscape ('cy_1', model_response)
    // });

    console.log($('#cellSelectDynamic').val().substring(6));
  });

  $("#loopy").click(function(){
    var txt = $('#textArea')[0].value

    txtProcess(txt, parser).then(groundingMapper).then(assembleLoopy).then(function (res) {

        window.open(
          res['loopy_url'].toString(),
          "_blank"
        );

    });

    console.log($('#cellSelectDynamic').val().substring(6));
  });

$("#loadButtonStatic").click(function(){

  setPresetPos()

  grabJSON('static/models/' + prebuilt_model + '/model.json').then(function (model_response) {
    drawCytoscape ('cy_1', model_response)
    qtipNodes(scapes['cy_1'])
  });

  $('.cyjs2loopy').prop('disabled', false);
});

$(".cyjs2loopy").click(function(){

  var model = loopyFromCyJS("cy_1");
  console.log(model)
  window.open(
    'http://ncase.me/loopy/v1/?data=' + model,
    "_blank"
  );

});

$(".presetLayout").click(function(){
  // console.log(this)
  if (this.classList.contains("active")){
    $(".presetLayout").removeClass("active")
    preset_pos = {}
  }
  else {
    $(".presetLayout").addClass("active")
    preset_pos = preset_pos_static
  }

})

$('a[href="#byom"]').click(function(){
  if (this.classList.contains("active") === false){
    preset_pos = {}
  }
  console.log(preset_pos)
})

$("#parseReach").click(function(){
  // console.log(this)
  if (this.classList.contains("active")){
    $("#parseReach").removeClass("active")
    $("#parseTrips").addClass("active")
    parser='trips'
  }
  else {
    $("#parseReach").addClass("active")
    $("#parseTrips").removeClass("active")
    parser='reach'
  }

})

$("#parseTrips").click(function(){
  // console.log(this)
  if (this.classList.contains("active")){
    $("#parseTrips").removeClass("active")
    $("#parseReach").addClass("active")
    parser='reach'
  }
  else {
    $("#parseTrips").addClass("active")
    $("#parseReach").removeClass("active")
    parser='trips'
  }

})

$('a[href="#ras227"]').click(function(){
  preset_pos = preset_pos_static
  console.log(preset_pos)
})

// change prebuilt_model name every time the user changes dropdown
$('#model_picker').on('changed.bs.select', function(){
  prebuilt_model = $('#model_picker').selectpicker('val')
})

// destroy cy on tab change
// don't really want this
// $('a[data-toggle=tab]').click(function(){
//     cy.destroy();
//     console.log(this.href);
// });

// get all divs of class cy
// get their data-url location
// draw them!
$('.cy').each(function(){
    var div_id = $(this).attr('id')
    console.log(div_id)
    var data_model = $(this).attr('data-url')
    console.log(data_model)
    setPresetPos()

    grabJSON('static/models/' + prebuilt_model + '/model.json').then(function (model_response) {
      drawCytoscape ('cy_1', model_response)
      qtipNodes(scapes['cy_1'])
    });

    console.log($(this).attr('data-url'))
})

  function resize() {
    //console.log(win.height(), win.innerHeight());
    $(".cy-container").height(win.innerHeight() - 250);
    $(".cy").height(win.innerHeight() - 250);
    //scapes.cy_1.fit(padding=30)
    scapes['cy_1'].center()
  }

  setTimeout(resize, 0);

  var resizeTimer;

  $(window).on('resize', function(e) {

    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(function() {

      resize();

    }, 250);

  });

          $('#menu').on('show.bs.modal', function (e) {
              console.log('show')
              $(".cy-panzoom").css({"display": "none"})
          })
          $('#menu').on('hidden.bs.modal', function (e) {
              console.log('hidden')
              $(".cy-panzoom").css({"display": "unset"})
          })

// cy.edges().forEach(function(e){
//   var g = e.data('weight');
//   e.qtip({
//     content: [
//       {
//         name: g,
//         url:  g
//       }
//     ].map(function( link ){
//       return '' + link.name + '';
//     }).join('
\n'),
//     position: {
//       my: 'top center',
//       at: 'top center'
//     },
//     style: {
//       classes: 'qtip-blue',
//       tip: {
//         width: 16,
//         height: 8
//       }
//     }
//   });
// });

});// dom ready
<commit_msg>Expose only McCormick model for now, change AWS address<commit_after>var cy = cytoscape();

// {name : position} dict
var prebuilt_model = 'McCormick';
var preset_pos = {};
var preset_pos_static = {}

// {id : position} dict
var id_pos = {};

var scapes = {};

var indra_server_addr = "http://ec2-34-226-201-156.compute-1.amazonaws.com:8080"

var ctxt = {}
grabJSON('static/models/' + prebuilt_model + '/model_context.json').then(
  function(ajax_response){
    console.log('done')
    ctxt =  ajax_response
  })

var korkut = {}
grabJSON('static/models/' + 'Korkut' + '/korkut.json').then(
  function(ajax_response){
    console.log('done')
    korkut =  ajax_response
  })
var condition = 'AK|10'

var domain = [2.7, 3.7, 4.7, 5.7, 6.7, 7.7, 8.7, 9.7, 10.7]
var exp_colorscale = d3.scaleThreshold()
    .domain(domain)
    .range(['#f7fcf5','#e5f5e0','#c7e9c0','#a1d99b','#74c476','#41ab5d','#238b45','#006d2c','#00441b']);
var mut_colorscale =  d3.scaleThreshold()
    .domain(domain)
    .range(['#fff5eb','#fee6ce','#fdd0a2','#fdae6b','#fd8d3c','#f16913','#d94801','#a63603','#7f2704']);

var parser = 'trips';

$(function(){

  var win = $(window);

  // build the dropdown pickers
  grabJSON('static/cell_dict.json').then(
    function(ajax_response){
      var prebuilt_models = {"McCormick":"McCormick"};
      // var prebuilt_models = {"McCormick":"McCormick", "Korkut":"Korkut", "Korkut2":"Korkut2"};
      dropdownFromJSON('#model_picker', prebuilt_models)
      }
  )

  // build the dropdown pickers
  grabJSON('static/cell_dict.json').then(
    function(ajax_response){

      var interesting_lines = {"A101D_SKIN":"model_A101D_SKIN.json", "LOXIMVI_SKIN":"model_LOXIMVI_SKIN.json"};
      for (var d of ['#cellSelectStatic', '#cellSelectDynamic']) {
          dropdownFromJSON(d, interesting_lines)
          $(d).append($('<option data-divider="true"/>'))
        }

      for (var d of ['#cellSelectStatic', '#cellSelectDynamic']) {
          dropdownFromJSON(d, ajax_response)
        }

      }
  )

  // set the preset_pos
  setPresetPos()

  $("#loadButtonDynamic").click(function(){
    var txt = $('#textArea')[0].value

    txtProcess(txt, parser).then(groundingMapper).then(assembleCyJS).then(function (model_response) {
      drawCytoscape('cy_1', model_response)
      qtipNodes(scapes['cy_1'])
    });
    // txtProcess(txt, parser).then(assembleCyJS).then(function (model_response) {
    //   drawCytoscape ('cy_1', model_response)
    // });
    $('.cyjs2loopy').prop('disabled', false);
    console.log($('#cellSelectDynamic').val().substring(6));
  });

  $("#loadContextButton").click(function(){
    var cell_line = $('#cellSelectDynamic').val().slice(6,-5)
    contextualizeNodesCCLE(cy, cell_line)
    console.log($('#cellSelectDynamic').val().substring(6));
  });

  $("#downloadPySB").click(function(){
    var txt = $('#textArea')[0].value

    txtProcess(txt, parser).then(groundingMapper).then(assemblePySB).then(function (res) {
      download($('#cellSelectDynamic').val().slice(6,-5)+'.py', res['model'])
    });
    // txtProcess(txt, parser).then(assembleCyJS).then(function (model_response) {
    //   drawCytoscape ('cy_1', model_response)
    // });

    console.log($('#cellSelectDynamic').val().substring(6));
  });

  $("#downloadINDRA").click(function(){
    var txt = $('#textArea')[0].value

    txtProcess(txt, parser).then(groundingMapper).then(function (res) {
      download($('#cellSelectDynamic').val()+'_INDRA_stmts.json', JSON.stringify(res['statements'], null, 2))
    });
    // txtProcess(txt, parser).then(assembleCyJS).then(function (model_response) {
    //   drawCytoscape ('cy_1', model_response)
    // });

    console.log($('#cellSelectDynamic').val().substring(6));
  });

  $("#loopy").click(function(){
    var txt = $('#textArea')[0].value

    txtProcess(txt, parser).then(groundingMapper).then(assembleLoopy).then(function (res) {

        window.open(
          res['loopy_url'].toString(),
          "_blank"
        );

    });

    console.log($('#cellSelectDynamic').val().substring(6));
  });

$("#loadButtonStatic").click(function(){

  setPresetPos()

  grabJSON('static/models/' + prebuilt_model + '/model.json').then(function (model_response) {
    drawCytoscape ('cy_1', model_response)
    qtipNodes(scapes['cy_1'])
  });

  $('.cyjs2loopy').prop('disabled', false);
});

$(".cyjs2loopy").click(function(){

  var model = loopyFromCyJS("cy_1");
  console.log(model)
  window.open(
    'http://ncase.me/loopy/v1/?data=' + model,
    "_blank"
  );

});

$(".presetLayout").click(function(){
  // console.log(this)
  if (this.classList.contains("active")){
    $(".presetLayout").removeClass("active")
    preset_pos = {}
  }
  else {
    $(".presetLayout").addClass("active")
    preset_pos = preset_pos_static
  }

})

$('a[href="#byom"]').click(function(){
  if (this.classList.contains("active") === false){
    preset_pos = {}
  }
  console.log(preset_pos)
})

$("#parseReach").click(function(){
  // console.log(this)
  if (this.classList.contains("active")){
    $("#parseReach").removeClass("active")
    $("#parseTrips").addClass("active")
    parser='trips'
  }
  else {
    $("#parseReach").addClass("active")
    $("#parseTrips").removeClass("active")
    parser='reach'
  }

})

$("#parseTrips").click(function(){
  // console.log(this)
  if (this.classList.contains("active")){
    $("#parseTrips").removeClass("active")
    $("#parseReach").addClass("active")
    parser='reach'
  }
  else {
    $("#parseTrips").addClass("active")
    $("#parseReach").removeClass("active")
    parser='trips'
  }

})

$('a[href="#ras227"]').click(function(){
  preset_pos = preset_pos_static
  console.log(preset_pos)
})

// change prebuilt_model name every time the user changes dropdown
$('#model_picker').on('changed.bs.select', function(){
  prebuilt_model = $('#model_picker').selectpicker('val')
})

// destroy cy on tab change
// don't really want this
// $('a[data-toggle=tab]').click(function(){
//     cy.destroy();
//     console.log(this.href);
// });

// get all divs of class cy
// get their data-url location
// draw them!
$('.cy').each(function(){
    var div_id = $(this).attr('id')
    console.log(div_id)
    var data_model = $(this).attr('data-url')
    console.log(data_model)
    setPresetPos()

    grabJSON('static/models/' + prebuilt_model + '/model.json').then(function (model_response) {
      drawCytoscape ('cy_1', model_response)
      qtipNodes(scapes['cy_1'])
    });

    console.log($(this).attr('data-url'))
})

  function resize() {
    //console.log(win.height(), win.innerHeight());
    $(".cy-container").height(win.innerHeight() - 250);
    $(".cy").height(win.innerHeight() - 250);
    //scapes.cy_1.fit(padding=30)
    scapes['cy_1'].center()
  }

  setTimeout(resize, 0);

  var resizeTimer;

  $(window).on('resize', function(e) {

    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(function() {

      resize();

    }, 250);

  });

          $('#menu').on('show.bs.modal', function (e) {
              console.log('show')
              $(".cy-panzoom").css({"display": "none"})
          })
          $('#menu').on('hidden.bs.modal', function (e) {
              console.log('hidden')
              $(".cy-panzoom").css({"display": "unset"})
          })

// cy.edges().forEach(function(e){
//   var g = e.data('weight');
//   e.qtip({
//     content: [
//       {
//         name: g,
//         url:  g
//       }
//     ].map(function( link ){
//       return '' + link.name + '';
//     }).join('
\n'),
//     position: {
//       my: 'top center',
//       at: 'top center'
//     },
//     style: {
//       classes: 'qtip-blue',
//       tip: {
//         width: 16,
//         height: 8
//       }
//     }
//   });
// });

});// dom ready
<|endoftext|>


<commit_before>function centerWindow() {
    "use strict";
    var centeredWidth = $('.centered').width() / 2,
        centeredHeight = $('.centered').height() / 2;
    $('.centered').css({ 'margin-left' : -centeredWidth , 'margin-top' : -centeredHeight });
}

function requestData() {
    "use strict";
    var req = new XMLHttpRequest();
    req.open("GET", "/games", true);
    req.setRequestHeader("accept", "application/json");

    req.onload = function() {
        if (req.status >= 200 && req.status < 400){
            var gamesjson = req.responseText;
            var gamesData = JSON.parse(gamesjson);
            var gamesToHtml = "";
            var key, x = 0;

            for (key in gamesData.games) {
                gamesToHtml += "
";
                var gameurl = "/#" + gamesData.games[x].id;
                var threadurl = gamesData.games[x].url;
                gamesToHtml +=  '' + gamesData.games[x].name + "	";
                gamesToHtml += '' + threadurl + "	";
                gamesToHtml += "" + '<button type="button" onclick="deleteGame(\'' + gamesData.games[x].id + '\');return false;" class="pure-button">Delete</button>' + "	";
                gamesToHtml += "
";
                x++;
            }

            document.getElementById("games").innerHTML = gamesToHtml;
        } else {
            console.log("Error. Status code " + req.status);
        }
    };

    req.send(null);
    locationHashChanged();
}

function locationHashChanged() {
    "use strict";
    if (window.location.hash != "") {
        var id = "" + window.location.hash;
        id = id.slice(1, id.length);
        showGame(id);
    }
}

function showCreateGame() {
    "use strict";
    var createGame = document.getElementById("creategame");
    document.getElementById("index").className += ' hidden';
    createGame.className = createGame.className.replace( /(?:^|\s)hidden(?!\S)/g , '' );

    centerWindow();
}

function hideCreateGame() {
    "use strict";
    document.getElementById("creategame").className += ' hidden';
    document.getElementById("index").className =
    document.getElementById("index").className.replace
      ( /(?:^|\s)hidden(?!\S)/g , '' );
    window.location.hash = "";
}

function showGame(id) {
    "use strict";
    var req = new XMLHttpRequest();
    var url = "/game/" + id;
    req.open("GET", url, true);
    req.setRequestHeader("accept", "application/json");

    req.onload = function() {
        if (req.status >= 200 && req.status < 400){
            var gamejson = req.responseText;
            var gameData = JSON.parse(gamejson);
            var gameToHtml = "";

            document.getElementById("gameheader").innerHTML = gameData.game.name;

            gameToHtml += '' + gameData.game.url + "

";

            var hosts = [];

            for (var i = 0; i < gameData.hosts.length; i++) {
                hosts.push(gameData.hosts[i]);
            }

            gameToHtml += "Hosts
" + hosts.join(', ');

            var players = [];

            for (var i = 0; i < gameData.players.length; i++) {
                players.push(gameData.players[i].name);
            }

            var playerLinks = [];

            for (var i = 0; i < gameData.players.length; i++) {
                playerLinks.push('' + gameData.players[i].name + '');
            }

            gameToHtml += "

Players
" + playerLinks.join(', ');

            gameToHtml += "
Click on a player to permanently remove him from the game! (reload the page to see the result)
";

            var nicknames = {
                "27ninjabunnies": ["27nb", "nb", "ninja", "bunnies", "ninjabunnies"],
                "Alakaslam": ["slam"],
                "Artanis[Xp]": ["art", "artanis"],
                "batsnacks": ["bat", "bats"],
                "Bill Murray": ["bm", "bill", "murray"],
                "Blazinghand": ["bh", "blazing"],
                "boxerfred": ["bf", "boxer"],
                "Chezinu": ["che", "chez"],
                "Clarity_nl": ["clarity"],
                "Damdred": ["damd", "damdy"],
                "EdgarAllanPoE": ["edgar", "allan", "poe", "edgarallenpoe"],
                "Fecalfeast": ["ff", "fecal"],
                "Fidei86": ["fidei"],
                "FirmTofu": ["ft", "firm", "tofu"],
                "GlowingBear": ["gb", "glowing", "bear"],
                "Half the Sky": ["hts", "sky"],
                "Hapahauli": ["hapa"],
                "Holyflare": ["hf"],
                "IAmRobik": ["robik"],
                "JudgeJudy": ["jj", "judge", "judy"],
                "justanothertownie": ["jat"],
                "Keirathi": ["kei", "keir"],
                "LightningStrike": ["ls", "lightning"],
                "marvellosity": ["marv", "marvy", "marvel", "marvelocity", "marshmallow"],
                "Oatsmaster": ["oat", "oats"],
                "ObiWanShinobi": ["ows", "obi", "obiwan", "shinobi"],
                "Onegu": ["o", "oneg"],
                "raynpelikoneet": ["ray", "rayn", "raypelikoneet"],
                "rsoultin": ["rs", "rsou", "rsoul"],
                "sandroba": ["sand", "roba"],
                "[UoN]Sentinel": ["sent", "sentinel"],
                "scott31337": ["scott"],
                "Stutters695": ["stutters"],
                "The Shining": ["shining"],
                "Tubesock": ["ts", "tube"],
                "VayneAuthority": ["va", "vayne"],
                "VisceraEyes": ["ve", "viscera"],
                "WaveofShadow": ["wos", "wave"],
                "Xatalos": ["xat", "xata"],
                "yamato77": ["yam", "yama", "yamato"]
            };

            var currentDay = 0;

            if (gameData.votes.length > 0) {
                currentDay = gameData.votes[gameData.votes.length - 1].day;

                var targets = [];

                for (var i = 0; i < gameData.votes.length; i++) {
                    if (currentDay == gameData.votes[i].day) {
                        for (var key in nicknames) {
                            if (!nicknames.hasOwnProperty(key)) {
                                continue;
                            }
                            var nicknameslist = nicknames[key];
                            for (var j = 0; j < nicknameslist.length; j++) {
                                if (nicknameslist[j].toLowerCase() == gameData.votes[i].target.toLowerCase()) {
                                    // if a vote target equals one of the nicknames, then change the vote to target the "real" name
                                    gameData.votes[i].target = key;
                                }
                            }
                        }
                        for (var j = 0; j < players.length; j++) {
                            if (players[j].toLowerCase() == gameData.votes[i].target.toLowerCase()) {
                                // if a vote target equals a name with the wrong capitalization, then change the vote to target the "real" name
                                gameData.votes[i].target = players[j];
                            }
                        }
                        if (targets.indexOf(gameData.votes[i].target.toLowerCase()) == -1) {
                            // push every new unique vote target to the targets array
                            targets.push(gameData.votes[i].target);
                        }
                      }
                }

                for (var i = 0; i < targets.length; i++) {
                    if (targets[i] == "") {
                        // remove the null (unvote) target from the list of vote targets
                        targets.splice(i, 1);
                        break;
                    }
                }

                var voters = {}; // "voters" is a JavaScript object with targets as keys and their voters as values
                var activeVoters = {}; // "activeVoters" is a JavaScript object with targets as keys and ACTIVE (not unvoted) voters as values
                var nonvoters = players; // players who aren't voting for anyone at the current time

                for (var i = 0; i < targets.length; i++) {
                    for (var j = 0; j < gameData.votes.length; j++) {
                        if (currentDay == gameData.votes[j].day && gameData.votes[j].target.toLowerCase() == targets[i].toLowerCase()) {
                            // add a new key (property) to the object for every vote target during the current day
                            voters[targets[i]] = [];
                            activeVoters[targets[i]] = [];
                        }
                    }
                }

                for (var i = 0; i < gameData.votes.length; i++) {
                    if (currentDay == gameData.votes[i].day) {
                        for (var j = 0; j < targets.length; j++) {
                            var remainingVoters = activeVoters[targets[j]];
                            for (var z = 0; z < remainingVoters.length; z++) {
                                if (remainingVoters[z] == gameData.votes[i].voter) {
                                    // every time a new vote is given, remove every previous ACTIVE vote from the voter
                                    remainingVoters.splice(z, 1);
                                }
                            }
                            activeVoters[targets[j]] = remainingVoters;
                            if (gameData.votes[i].target.toLowerCase() == targets[j].toLowerCase() && gameData.votes[j].target != "") {
                                // push every voter of the current day to the objects as a value of their vote target
                                voters[targets[j]].push(gameData.votes[i].voter);
                                activeVoters[targets[j]].push(gameData.votes[i].voter);
                            }
                        }
                    }
                }

                for (var i = 0; i < targets.length; i++) {
                    var votersList = activeVoters[targets[i]];
                    for (var j = 0; j < votersList.length; j++) {
                        for (var z = 0; z < nonvoters; z++) {
                            if (votersList[j] == nonvoters[z]) {
                                // remove every currently active voter from the "Not Voting" list
                                nonvoters.splice(z, 1);
                            }
                        }
                    }
                }

                gameToHtml += "

Day " + currentDay + " Votecount
";

                for (var i = 0; i < targets.length; i++) {
                    var votersList = voters[targets[i]];
                    for (var j = 0; j < votersList.length; j++) {
                            if (activeVoters[targets[i]].indexOf(votersList[j]) == -1 && votersList[j].indexOf("<s>") == -1) {
                                votersList[j] = "<s>" + votersList[j] + "</s>";
                            }
                    }

                    gameToHtml += "
" + targets[i] + " (" + activeVoters[targets[i]].length + "): " + votersList.join(', ');
            }

                gameToHtml += '

Not Voting (' + nonvoters.length + '): ' + nonvoters.join(', ');
        }

            var firstNewDayVote = false;
            currentDay = 0;

            for (var i = 0; i < gameData.votes.length; i++) {
                var post = gameData.votes[i].index;
                var page = Math.floor(post/20) + 1;
                var address = gameData.game.url + "?page=" + page + "#" + post;

                if (currentDay != gameData.votes[i].day) {
                    firstNewDayVote = true;
                    currentDay = gameData.votes[i].day;
                }
                if (firstNewDayVote === true) {
                    gameToHtml += "

Day " + gameData.votes[i].day + "
";
                    firstNewDayVote = false;
                }
                if (gameData.votes[i].target == "") {
                    gameToHtml += '
' + gameData.votes[i].voter + " unvoted";
                } else if (gameData.votes[i].target == null) {
                    gameToHtml += '
' + gameData.votes[i].voter + " gave an invalid vote!";
                } else {
                    gameToHtml += '
' + gameData.votes[i].voter +
                        " voted for " + gameData.votes[i].target + "";
                }
            }

            if (gameData.votes.length > 0) {
                gameToHtml += '

<textarea id="reply_area" cols=80 rows=25 name="bericht" style="font:10pt Arial; margin-bottom: 4px; width:732px">';
                currentDay = gameData.votes[gameData.votes.length - 1].day;

                gameToHtml += "[blue][b][u][big]Day " + currentDay + " Votecount[/big][/u][/b][/blue]\r\n\r\n";

                for (var i = 0; i < targets.length; i++) {
                    var votersList = voters[targets[i]];
                    for (var j = 0; j < votersList.length; j++) {
                            if (activeVoters[targets[i]].indexOf(votersList[j]) == -1 && votersList[j].indexOf("[s]") == -1) {
                                votersList[j] = "[s]" + votersList[j] + "[/s]";
                            }
                    }

                    gameToHtml += "[b]" + targets[i] + " (" + activeVoters[targets[i]].length + "):[/b] " + votersList.join(', ') + "\r\n";
            }

                gameToHtml += '\r\n' + '[b]Not Voting (' + nonvoters.length + '):[/b] ' + nonvoters.join(', ');
                gameToHtml += '</textarea>';
        }

            if (gameData.votes.length === 0) {
                gameToHtml += "
No votes have been extracted from the given thread yet (this may take more time or there may have been an error while reading the thread)
";
            }

            console.log(voters[targets[0]]);
            console.log(activeVoters[targets[0]]);

            document.getElementById("gamedata").innerHTML = gameToHtml;
        } else {
            console.log("Error. Status code " + req.status);
        }
    };

    req.send(null);
    document.getElementById("index").className += ' hidden';
    document.getElementById("gameview").className =
    document.getElementById("gameview").className.replace
      ( /(?:^|\s)hidden(?!\S)/g , '' );
}

function deletePlayer(id) {
    "use strict";
    $.post("/delete-player", {id: id});
}

function deleteGame(id) {
    "use strict";
    $.post("/delete-game", {id: id});
}

function hideGame() {
    "use strict";
    document.getElementById("gameview").className += ' hidden';
    document.getElementById("index").className =
    document.getElementById("index").className.replace
      ( /(?:^|\s)hidden(?!\S)/g , '' );
    window.location.hash = "";
}

requestData();
<commit_msg>more fixes<commit_after>function centerWindow() {
    "use strict";
    var centeredWidth = $('.centered').width() / 2,
        centeredHeight = $('.centered').height() / 2;
    $('.centered').css({ 'margin-left' : -centeredWidth , 'margin-top' : -centeredHeight });
}

function requestData() {
    "use strict";
    var req = new XMLHttpRequest();
    req.open("GET", "/games", true);
    req.setRequestHeader("accept", "application/json");

    req.onload = function() {
        if (req.status >= 200 && req.status < 400){
            var gamesjson = req.responseText;
            var gamesData = JSON.parse(gamesjson);
            var gamesToHtml = "";
            var key, x = 0;

            for (key in gamesData.games) {
                gamesToHtml += "
";
                var gameurl = "/#" + gamesData.games[x].id;
                var threadurl = gamesData.games[x].url;
                gamesToHtml +=  '' + gamesData.games[x].name + "	";
                gamesToHtml += '' + threadurl + "	";
                gamesToHtml += "" + '<button type="button" onclick="deleteGame(\'' + gamesData.games[x].id + '\');return false;" class="pure-button">Delete</button>' + "	";
                gamesToHtml += "
";
                x++;
            }

            document.getElementById("games").innerHTML = gamesToHtml;
        } else {
            console.log("Error. Status code " + req.status);
        }
    };

    req.send(null);
    locationHashChanged();
}

function locationHashChanged() {
    "use strict";
    if (window.location.hash != "") {
        var id = "" + window.location.hash;
        id = id.slice(1, id.length);
        showGame(id);
    }
}

function showCreateGame() {
    "use strict";
    var createGame = document.getElementById("creategame");
    document.getElementById("index").className += ' hidden';
    createGame.className = createGame.className.replace( /(?:^|\s)hidden(?!\S)/g , '' );

    centerWindow();
}

function hideCreateGame() {
    "use strict";
    document.getElementById("creategame").className += ' hidden';
    document.getElementById("index").className =
    document.getElementById("index").className.replace
      ( /(?:^|\s)hidden(?!\S)/g , '' );
    window.location.hash = "";
}

function showGame(id) {
    "use strict";
    var req = new XMLHttpRequest();
    var url = "/game/" + id;
    req.open("GET", url, true);
    req.setRequestHeader("accept", "application/json");

    req.onload = function() {
        if (req.status >= 200 && req.status < 400){
            var gamejson = req.responseText;
            var gameData = JSON.parse(gamejson);
            var gameToHtml = "";

            document.getElementById("gameheader").innerHTML = gameData.game.name;

            gameToHtml += '' + gameData.game.url + "

";

            var hosts = [];

            for (var i = 0; i < gameData.hosts.length; i++) {
                hosts.push(gameData.hosts[i]);
            }

            gameToHtml += "Hosts
" + hosts.join(', ');

            var players = [];

            for (var i = 0; i < gameData.players.length; i++) {
                players.push(gameData.players[i].name);
            }

            var playerLinks = [];

            for (var i = 0; i < gameData.players.length; i++) {
                playerLinks.push('' + gameData.players[i].name + '');
            }

            gameToHtml += "

Players
" + playerLinks.join(', ');

            gameToHtml += "
Click on a player to permanently remove him from the game! (reload the page to see the result)
";

            var nicknames = {
                "27ninjabunnies": ["27nb", "nb", "ninja", "bunnies", "ninjabunnies"],
                "Alakaslam": ["slam"],
                "Artanis[Xp]": ["art", "artanis"],
                "batsnacks": ["bat", "bats"],
                "Bill Murray": ["bm", "bill", "murray"],
                "Blazinghand": ["bh", "blazing"],
                "boxerfred": ["bf", "boxer"],
                "Chezinu": ["che", "chez"],
                "Clarity_nl": ["clarity"],
                "Damdred": ["damd", "damdy"],
                "EdgarAllanPoE": ["edgar", "allan", "poe", "edgarallenpoe"],
                "Fecalfeast": ["ff", "fecal"],
                "Fidei86": ["fidei"],
                "FirmTofu": ["ft", "firm", "tofu"],
                "GlowingBear": ["gb", "glowing", "bear"],
                "Half the Sky": ["hts", "sky"],
                "Hapahauli": ["hapa"],
                "Holyflare": ["hf"],
                "IAmRobik": ["robik"],
                "JudgeJudy": ["jj", "judge", "judy"],
                "justanothertownie": ["jat"],
                "Keirathi": ["kei", "keir"],
                "LightningStrike": ["ls", "lightning"],
                "marvellosity": ["marv", "marvy", "marvel", "marvelocity", "marshmallow"],
                "Oatsmaster": ["oat", "oats"],
                "ObiWanShinobi": ["ows", "obi", "obiwan", "shinobi"],
                "Onegu": ["o", "oneg"],
                "raynpelikoneet": ["ray", "rayn", "raypelikoneet"],
                "rsoultin": ["rs", "rsou", "rsoul"],
                "sandroba": ["sand", "roba"],
                "[UoN]Sentinel": ["sent", "sentinel"],
                "scott31337": ["scott"],
                "Stutters695": ["stutters"],
                "The Shining": ["shining"],
                "Tubesock": ["ts", "tube"],
                "VayneAuthority": ["va", "vayne"],
                "VisceraEyes": ["ve", "viscera"],
                "WaveofShadow": ["wos", "wave"],
                "Xatalos": ["xat", "xata"],
                "yamato77": ["yam", "yama", "yamato"]
            };

            var currentDay = 0;

            if (gameData.votes.length > 0) {
                currentDay = gameData.votes[gameData.votes.length - 1].day;

                var targets = [];

                for (var i = 0; i < gameData.votes.length; i++) {
                    if (currentDay == gameData.votes[i].day) {
                        for (var key in nicknames) {
                            if (!nicknames.hasOwnProperty(key)) {
                                continue;
                            }
                            var nicknameslist = nicknames[key];
                            for (var j = 0; j < nicknameslist.length; j++) {
                                if (nicknameslist[j].toLowerCase() == gameData.votes[i].target.toLowerCase()) {
                                    // if a vote target equals one of the nicknames, then change the vote to target the "real" name
                                    gameData.votes[i].target = key;
                                }
                            }
                        }
                        for (var j = 0; j < players.length; j++) {
                            if (players[j].toLowerCase() == gameData.votes[i].target.toLowerCase()) {
                                // if a vote target equals a name with the wrong capitalization, then change the vote to target the "real" name
                                gameData.votes[i].target = players[j];
                            }
                        }
                        if (targets.indexOf(gameData.votes[i].target.toLowerCase()) == -1) {
                            // push every new unique vote target to the targets array
                            targets.push(gameData.votes[i].target);
                        }
                      }
                }

                for (var i = 0; i < targets.length; i++) {
                    if (targets[i] == "") {
                        // remove the null (unvote) target from the list of vote targets
                        targets.splice(i, 1);
                        break;
                    }
                }

                var voters = {}; // "voters" is a JavaScript object with targets as keys and their voters as values
                var activeVoters = {}; // "activeVoters" is a JavaScript object with targets as keys and ACTIVE (not unvoted) voters as values
                var nonvoters = players; // players who aren't voting for anyone at the current time

                for (var i = 0; i < targets.length; i++) {
                    for (var j = 0; j < gameData.votes.length; j++) {
                        if (currentDay == gameData.votes[j].day && gameData.votes[j].target.toLowerCase() == targets[i].toLowerCase()) {
                            // add a new key (property) to the object for every vote target during the current day
                            voters[targets[i]] = [];
                            activeVoters[targets[i]] = [];
                        }
                    }
                }

                for (var i = 0; i < gameData.votes.length; i++) {
                    if (currentDay == gameData.votes[i].day) {
                        for (var j = 0; j < targets.length; j++) {
                            var remainingVoters = activeVoters[targets[j]];
                            for (var z = 0; z < remainingVoters.length; z++) {
                                if (remainingVoters[z] == gameData.votes[i].voter) {
                                    // every time a new vote is given, remove every previous ACTIVE vote from the voter
                                    remainingVoters.splice(z, 1);
                                }
                            }
                            activeVoters[targets[j]] = remainingVoters;
                            if (gameData.votes[i].target.toLowerCase() == targets[j].toLowerCase() && gameData.votes[j].target != "") {
                                // push every voter of the current day to the objects as a value of their vote target
                                voters[targets[j]].push(gameData.votes[i].voter);
                                activeVoters[targets[j]].push(gameData.votes[i].voter);
                            }
                        }
                    }
                }

                for (var i = 0; i < targets.length; i++) {
                    var activesList = activeVoters[targets[i]];
                    for (var j = 0; j < activesList.length; j++) {
                        for (var z = 0; z < nonvoters; z++) {
                            if (activesList[j] == nonvoters[z]) {
                                // remove every currently active voter from the "Not Voting" list
                                nonvoters.splice(z, 1);
                            }
                        }
                    }
                }

                gameToHtml += "

Day " + currentDay + " Votecount
";

                for (var i = 0; i < targets.length; i++) {
                    var mainVotersList = voters[targets[i]];
                    for (var j = 0; j < mainVotersList.length; j++) {
                            if (activeVoters[targets[i]].indexOf(mainVotersList[j]) == -1 && mainVotersList[j].indexOf("<s>") == -1) {
                                mainVotersList[j] = "<s>" + mainVotersList[j] + "</s>";
                            }
                    }

                    gameToHtml += "
" + targets[i] + " (" + activeVoters[targets[i]].length + "): " + votersList.join(', ');
            }

                gameToHtml += '

Not Voting (' + nonvoters.length + '): ' + nonvoters.join(', ');
        }

            var firstNewDayVote = false;
            currentDay = 0;

            for (var i = 0; i < gameData.votes.length; i++) {
                var post = gameData.votes[i].index;
                var page = Math.floor(post/20) + 1;
                var address = gameData.game.url + "?page=" + page + "#" + post;

                if (currentDay != gameData.votes[i].day) {
                    firstNewDayVote = true;
                    currentDay = gameData.votes[i].day;
                }
                if (firstNewDayVote === true) {
                    gameToHtml += "

Day " + gameData.votes[i].day + "
";
                    firstNewDayVote = false;
                }
                if (gameData.votes[i].target == "") {
                    gameToHtml += '
' + gameData.votes[i].voter + " unvoted";
                } else if (gameData.votes[i].target == null) {
                    gameToHtml += '
' + gameData.votes[i].voter + " gave an invalid vote!";
                } else {
                    gameToHtml += '
' + gameData.votes[i].voter +
                        " voted for " + gameData.votes[i].target + "";
                }
            }

            if (gameData.votes.length > 0) {
                gameToHtml += '

<textarea id="reply_area" cols=80 rows=25 name="bericht" style="font:10pt Arial; margin-bottom: 4px; width:732px">';
                currentDay = gameData.votes[gameData.votes.length - 1].day;

                gameToHtml += "[blue][b][u][big]Day " + currentDay + " Votecount[/big][/u][/b][/blue]\r\n\r\n";

                for (var i = 0; i < targets.length; i++) {
                    var votersList = voters[targets[i]];
                    for (var j = 0; j < votersList.length; j++) {
                            if (activeVoters[targets[i]].indexOf(votersList[j]) == -1 && votersList[j].indexOf("[s]") == -1) {
                                votersList[j] = "[s]" + votersList[j] + "[/s]";
                            }
                    }

                    gameToHtml += "[b]" + targets[i] + " (" + activeVoters[targets[i]].length + "):[/b] " + votersList.join(', ') + "\r\n";
            }

                gameToHtml += '\r\n' + '[b]Not Voting (' + nonvoters.length + '):[/b] ' + nonvoters.join(', ');
                gameToHtml += '</textarea>';
        }

            if (gameData.votes.length === 0) {
                gameToHtml += "
No votes have been extracted from the given thread yet (this may take more time or there may have been an error while reading the thread)
";
            }

            console.log(voters[targets[0]]);
            console.log(activeVoters[targets[0]]);

            document.getElementById("gamedata").innerHTML = gameToHtml;
        } else {
            console.log("Error. Status code " + req.status);
        }
    };

    req.send(null);
    document.getElementById("index").className += ' hidden';
    document.getElementById("gameview").className =
    document.getElementById("gameview").className.replace
      ( /(?:^|\s)hidden(?!\S)/g , '' );
}

function deletePlayer(id) {
    "use strict";
    $.post("/delete-player", {id: id});
}

function deleteGame(id) {
    "use strict";
    $.post("/delete-game", {id: id});
}

function hideGame() {
    "use strict";
    document.getElementById("gameview").className += ' hidden';
    document.getElementById("index").className =
    document.getElementById("index").className.replace
      ( /(?:^|\s)hidden(?!\S)/g , '' );
    window.location.hash = "";
}

requestData();
<|endoftext|>


<commit_before>$.getJSON('/bookdb/db.json', function(data) {
	var reading = "
"
	for (var i in data.books) {
		if (data.books[i].amReading == "true" || data.books[i].amReading == true) {

			reading += "

"

			reading += "

I am on page " + Math.floor(data.books[i].numPages *(data.progress.read / 100)) + " of " + data.books[i].title + " by "  + data.books[i].author + "

" + data.progress.read + "%

\"" + data.books[i].abstract + "\"
"
			}
	document.getElementById("current").innerHTML=reading;
	}
});
<commit_msg>https issues, again<commit_after>$.getJSON('/bookdb/db.json', function(data) {
	var reading = "
"
	for (var i in data.books) {
		if (data.books[i].amReading == "true" || data.books[i].amReading == true) {

			reading += "

"

			reading += "

I am on page " + Math.floor(data.books[i].numPages *(data.progress.read / 100)) + " of " + data.books[i].title + " by "  + data.books[i].author + "

" + data.progress.read + "%

\"" + data.books[i].abstract + "\"
"
			}
	document.getElementById("current").innerHTML=reading;
	}
});
<|endoftext|>


<commit_before>var map;
var page;
$(function () {

    // Set up map widget
    options = {
        map_id: "map",
        zoom: 12
    }
    map = new LeafletPolylineWidget(options);

    if(call_status == "Pending") {
        addMarkerCall(map, call_location_y, call_location_x);
    } else if(call_status == "Started") {

        ambulances.forEach(id => {
            retrieveAmbulances(id);
        });
        addMarkerCall(map, call_location_y, call_location_x);

    } else if(call_status == "Ended") {

    } else {
        console.error("Call status " + call_status + " not handled");
    }
    console.log(ambulances);
});

function retrieveAmbulances(ambulance_id) {

    // Build url
    var url = APIBaseUrl + 'ambulance/' + ambulance_id + '/updates';
    // if (page != null) {
    //     url += "?page=" + page;
    //     if (page_size != null)
    //         url += "&page_size=" + page_size;
    // } else if (page_size != null)
    //     url += "?page_size=" + page_size;

    $.ajax({
        type: 'GET',
        datatype: "json",
        url: url,

        fail: function (msg) {

            alert('Could not retrieve data from API:' + msg)

        },

        success: function (data) {

            console.log('Got data from API')

            addAmbulanceRoute(data)

        }

    })
        .done(function (data) {
            if (console && console.log) {
                console.log("Done retrieving ambulance data from API");
            }
        });

}

//icon: ambulance_icons[ambulance.status],

function addMarkerCall(map, x, y) {
    // add marker
    map.addPoint(x, y, call_id, null)
        .bindPopup('hi
@')
        .on('mouseover',
            function (e) {
                // open popup bubble
                this.openPopup().on('mouseout',
                    function (e) {
                        this.closePopup();
                    });
            });

}

function addMarker(map, update) {
    // add marker
    var myIcon = L.icon({
        iconUrl: '/static/icons/cars/ambulance_blue.svg',
        iconSize: [15, 30],
    });
    L.marker([update.location.latitude, update.location.longitude], {icon: myIcon}).addTo(map);

    // map.addPoint(update.location.latitude, update.location.longitude, update.id, null)
    //     .bindPopup('hi
@'
    //         + (new Date(Date.parse(update.timestamp))).toLocaleString())
    //     .on('mouseover',
    //         function (e) {
    //             // open popup bubble
    //             this.openPopup().on('mouseout',
    //                 function (e) {
    //                     this.closePopup();
    //                 });
    //         });

}

function calculateDistanceHaversine(location1, location2, radius) {

    radius = radius || 6371e3;

    // convert latitude and longitude to radians first
    var lat1 = Math.PI * location1.latitude / 180;
    var lat2 = Math.PI * location2.latitude / 180;
    var d_phi = lat2 - lat1;
    var d_lambda = Math.PI * (location2.longitude - location1.longitude) / 180;

    var a = Math.sin(d_phi / 2) * Math.sin(d_phi / 2) + Math.cos(lat1) * Math.cos(lat2) * Math.sin(d_lambda / 2) * Math.sin(d_lambda / 2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

    // console.log('|| {} - {} ||= {}'.format(location2, location1, earth_radius * c))

    return radius * c;
}

function breakSegments(data, separationRadius, timeInterval) {

    separationRadius = separationRadius || [100, 10000]; // 10m, 10km
    timeInterval = timeInterval || [2 * 60 * 1000, 60 * 60 * 1000]; // 2 minutes, 1 hour

    var segments = [];

    var currentSegment = [];
    var lastPosition = null;
    var n = data.length;
    for (var i = 0; i < n; i++) {

        // current position
        var currentPosition = data[i];

        // distance?
        if (lastPosition != null) {
            var distance = calculateDistanceHaversine(lastPosition.location, currentPosition.location);
            var interval = Math.abs(Date.parse(lastPosition.timestamp) - Date.parse(currentPosition.timestamp));
            if (distance > separationRadius[1] || interval > timeInterval[1] ||
                (interval > timeInterval[0] && distance > separationRadius[0])) {
                // terminate current segment
                segments.push(currentSegment);
                currentSegment = [];
            }
        }

        // add position to segment
        currentSegment.push(currentPosition);

        // update lastPosition
        lastPosition = currentPosition;
    }

    // anything left?
    if (currentSegment.length > 0) {
        // terminate last segment
        segments.push(currentSegment);
    }

    return segments;

}

function addSegment(updates, layer) {

    // Add status markers
    // TODO: color depending on status

    // Create layer
    map.createLayer(layer);

    // First entry
    var lastStatus;
    if (updates.length >= 2) {

        // Retrieve last entry (first position)
        entry = updates[updates.length - 1];

        // add marker
        addMarker(map, entry, layer);

        // entry status
        lastStatus = entry.status;

    }

    // Mid updates
    for (var i = updates.length - 2; i > 0; i--) {

        // Retrieve next entry
        entry = updates[i];

        if (entry.status != lastStatus) {

            // add marker
            addMarker(map, entry, layer);

        }

        // entry status
        lastStatus = entry.status;

    }

    // Last entry
    if (updates.length > 0) {

        // Retrieve last entry (first position)
        entry = updates[0];

        // add marker
        addMarker(map, entry, layer);

    }

    // Store data in an array
    var latlngs = [];
    updates.forEach(function (update) {

        // push location
        var loc = update.location;
        latlngs.push([loc.latitude, loc.longitude]);

    });

    // Add line to map
    console.log('Adding segment');
    map.addLine(latlngs, 1, "red", null, layer);

}

// Interact with widget to add an ambulance route
function addAmbulanceRoute(data) {

    // short return
    if (data.results.length == 0)
        return;

    // break segments
    var segments = breakSegments(data.results);

    // loop on segments
    segments.forEach(function (segment, index) {

        // add segment to map
        addSegment(segment, 'layer_' + index);

    });

    // create route filter
    createRouteFilter(segments);

    console.log('Centering map');
    map.center(data.results[0].location);

}

function createRouteFilter(segments) {

    // Add the checkbox on the top right corner for filtering.
    var container = L.DomUtil.create('div', 'filter-options bg-light');

    //Generate HTML code for checkboxes for each of the statuses.
    var filterHtml = "";

    filterHtml += '
';
    segments.forEach(function (segment, index) {

        var date = new Date(Date.parse(segment[0].timestamp));
        filterHtml += '
'
            + '<input class="chk" data-status="layer_' + index + '" type="checkbox" value="" checked >'
            + date.toLocaleString()
            + ''
            + '
';

    });
    filterHtml += "
";

    // Append html code to container
    container.innerHTML = filterHtml;

    // Add the checkboxes.
    var customControl = L.Control.extend({

        options: {
            position: 'topright'
        },

        onAdd: function (map) {
            return container;
        }

    });
    map.map.addControl(new customControl());

    // Add listener to remove status layer when filter checkbox is clicked
    $('.chk').change(function () {

        // Which layer?
        var layer = map.getLayerPane(this.getAttribute('data-status'));

        if (this.checked) {
            layer.style.display = 'block';
        } else {
            layer.style.display = 'none';
        }

    });

};
<commit_msg>Testing<commit_after>var map;
var page;
$(function () {

    // Set up map widget
    options = {
        map_id: "map",
        zoom: 12
    }
    map = new LeafletPolylineWidget(options);

    if(call_status == "Pending") {
        addMarkerCall(map, call_location_y, call_location_x);
    } else if(call_status == "Started") {

        ambulances.forEach(id => {
            retrieveAmbulances(id);
        });
        addMarkerCall(map, call_location_y, call_location_x);

    } else if(call_status == "Ended") {

    } else {
        console.error("Call status " + call_status + " not handled");
    }
    console.log(ambulances);
});

function retrieveAmbulances(ambulance_id) {

    // Build url
    var url = APIBaseUrl + 'ambulance/' + ambulance_id + '/updates';
    // if (page != null) {
    //     url += "?page=" + page;
    //     if (page_size != null)
    //         url += "&page_size=" + page_size;
    // } else if (page_size != null)
    //     url += "?page_size=" + page_size;

    $.ajax({
        type: 'GET',
        datatype: "json",
        url: url,

        fail: function (msg) {

            alert('Could not retrieve data from API:' + msg)

        },

        success: function (data) {

            console.log('Got data from API')

            addAmbulanceRoute(data)

        }

    })
        .done(function (data) {
            if (console && console.log) {
                console.log("Done retrieving ambulance data from API");
            }
        });

}

//icon: ambulance_icons[ambulance.status],

function addMarkerCall(map, x, y) {
    // add marker
    map.addPoint(x, y, call_id, null)
        .bindPopup('hi
@')
        .on('mouseover',
            function (e) {
                // open popup bubble
                this.openPopup().on('mouseout',
                    function (e) {
                        this.closePopup();
                    });
            });

}

function addMarker(map, update) {
    // add marker
    var myIcon = L.icon({
        iconUrl: '/static/icons/cars/ambulance_blue.svg',
        iconSize: [15, 30],
    });
    // L.marker([update.location.latitude, update.location.longitude], {icon: myIcon}).addTo(map);

    // map.addPoint(update.location.latitude, update.location.longitude, update.id, null)
    //     .bindPopup('hi
@'
    //         + (new Date(Date.parse(update.timestamp))).toLocaleString())
    //     .on('mouseover',
    //         function (e) {
    //             // open popup bubble
    //             this.openPopup().on('mouseout',
    //                 function (e) {
    //                     this.closePopup();
    //                 });
    //         });

}

function calculateDistanceHaversine(location1, location2, radius) {

    radius = radius || 6371e3;

    // convert latitude and longitude to radians first
    var lat1 = Math.PI * location1.latitude / 180;
    var lat2 = Math.PI * location2.latitude / 180;
    var d_phi = lat2 - lat1;
    var d_lambda = Math.PI * (location2.longitude - location1.longitude) / 180;

    var a = Math.sin(d_phi / 2) * Math.sin(d_phi / 2) + Math.cos(lat1) * Math.cos(lat2) * Math.sin(d_lambda / 2) * Math.sin(d_lambda / 2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

    // console.log('|| {} - {} ||= {}'.format(location2, location1, earth_radius * c))

    return radius * c;
}

function breakSegments(data, separationRadius, timeInterval) {

    separationRadius = separationRadius || [100, 10000]; // 10m, 10km
    timeInterval = timeInterval || [2 * 60 * 1000, 60 * 60 * 1000]; // 2 minutes, 1 hour

    var segments = [];

    var currentSegment = [];
    var lastPosition = null;
    var n = data.length;
    for (var i = 0; i < n; i++) {

        // current position
        var currentPosition = data[i];

        // distance?
        if (lastPosition != null) {
            var distance = calculateDistanceHaversine(lastPosition.location, currentPosition.location);
            var interval = Math.abs(Date.parse(lastPosition.timestamp) - Date.parse(currentPosition.timestamp));
            if (distance > separationRadius[1] || interval > timeInterval[1] ||
                (interval > timeInterval[0] && distance > separationRadius[0])) {
                // terminate current segment
                segments.push(currentSegment);
                currentSegment = [];
            }
        }

        // add position to segment
        currentSegment.push(currentPosition);

        // update lastPosition
        lastPosition = currentPosition;
    }

    // anything left?
    if (currentSegment.length > 0) {
        // terminate last segment
        segments.push(currentSegment);
    }

    return segments;

}

function addSegment(updates, layer) {

    // Add status markers
    // TODO: color depending on status

    // Create layer
    map.createLayer(layer);

    // First entry
    var lastStatus;
    if (updates.length >= 2) {

        // Retrieve last entry (first position)
        entry = updates[updates.length - 1];

        // add marker
        addMarker(map, entry, layer);

        // entry status
        lastStatus = entry.status;

    }

    // Mid updates
    for (var i = updates.length - 2; i > 0; i--) {

        // Retrieve next entry
        entry = updates[i];

        if (entry.status != lastStatus) {

            // add marker
            addMarker(map, entry, layer);

        }

        // entry status
        lastStatus = entry.status;

    }

    // Last entry
    if (updates.length > 0) {

        // Retrieve last entry (first position)
        entry = updates[0];

        // add marker
        addMarker(map, entry, layer);

    }

    // Store data in an array
    var latlngs = [];
    updates.forEach(function (update) {

        // push location
        var loc = update.location;
        latlngs.push([loc.latitude, loc.longitude]);

    });

    // Add line to map
    console.log('Adding segment');
    map.addLine(latlngs, 1, "red", null, layer);

}

// Interact with widget to add an ambulance route
function addAmbulanceRoute(data) {

    // short return
    if (data.results.length == 0)
        return;

    // break segments
    var segments = breakSegments(data.results);

    // loop on segments
    segments.forEach(function (segment, index) {

        // add segment to map
        addSegment(segment, 'layer_' + index);

    });

    // create route filter
    createRouteFilter(segments);

    console.log('Centering map');
    map.center(data.results[0].location);

}

function createRouteFilter(segments) {

    // Add the checkbox on the top right corner for filtering.
    var container = L.DomUtil.create('div', 'filter-options bg-light');

    //Generate HTML code for checkboxes for each of the statuses.
    var filterHtml = "";

    filterHtml += '
';
    segments.forEach(function (segment, index) {

        var date = new Date(Date.parse(segment[0].timestamp));
        filterHtml += '
'
            + '<input class="chk" data-status="layer_' + index + '" type="checkbox" value="" checked >'
            + date.toLocaleString()
            + ''
            + '
';

    });
    filterHtml += "
";

    // Append html code to container
    container.innerHTML = filterHtml;

    // Add the checkboxes.
    var customControl = L.Control.extend({

        options: {
            position: 'topright'
        },

        onAdd: function (map) {
            return container;
        }

    });
    map.map.addControl(new customControl());

    // Add listener to remove status layer when filter checkbox is clicked
    $('.chk').change(function () {

        // Which layer?
        var layer = map.getLayerPane(this.getAttribute('data-status'));

        if (this.checked) {
            layer.style.display = 'block';
        } else {
            layer.style.display = 'none';
        }

    });

};
<|endoftext|>


<commit_before>'use strict';

/* Use JQuery.gritter to popup success message */
function alert_success(message) {
    $.gritter.add({
        title: 'Success!',
        text: message,
        image: 'static/img/pirate-logo.png',
        time: 3000
    });
}

/* Use JQuery.gritter to popup error message */
function alert_error(message) {
    $.gritter.add({
        title: 'Error!',
        text: message,
        image: 'static/img/pirate-logo.png',
        time: 3000
    });
}

/* All angular application controllers */
var seagullControllers = angular.module('seagullControllers', []);

/* This controller to get comment from beego api */
seagullControllers.controller('HomeController', ['$scope', '$routeParams', 'dockerService',
    function ($scope, $routeParams, dockerService) {

        /* Get the version object */
        dockerService.getVersion().then(function (version) {
            $scope.version = version;
            $scope.Os = version.Os;
            $scope.KernelVersion = version.KernelVersion;
            $scope.GoVersion = version.GoVersion;
            $scope.Version = version.Version;
        });

        /* Get the info object */
        dockerService.getInfo().then(function (info) {
            $scope.info = info;
            $scope.Containers = info.Containers;
            $scope.Images = info.Images;
        });
    }]);

/* Images controller requests beego API server to get/delete images */
seagullControllers.controller('ImagesController', ['$scope', '$routeParams', '$http', 'dockerService', '$modal',
    function ($scope, $routeParams, $http, dockerService, $modal) {

        dockerService.getVersion().then(function (version) {
            $scope.version = version;
            dockerService.getImages().then(function (images) {
                $scope.images = images;
            });
        });

        $scope.pullImage = function (image) {
            if ($scope.version) {
                $scope.pullUrl = $scope.version.PirateUrlAlias + "/" + image.Name + "/" + image.Tag;
                var modalInstance = $modal.open({
                    templateUrl: '/static/html/modal.html',
                    controller: 'ModalController',
                    resolve: {
                        pullUrl: function () {
                            return $scope.pullUrl;
                        }
                    }
                });

                modalInstance.result.then(function () {
                }, function () {
                });
            }
        };

        $scope.deleteImage = function (image) {
            var id = image.Id.substring(0, 12);
            dockerService.deleteImage(image).then(function (data) {
                alert_success("Delete image " + id);
                dockerService.getImages().then(function (images) {
                    $scope.images = images;
                });
            }, function (reason) {
                alert_error("Delete image " + id);
            });
        };

        $scope.isReadonly = function () {
            if ($scope.version && $scope.version.PirateMode !== 'readonly') {
                return false;
            }
            return true;
        }
    }]);

/*
 * Modal controller
 */
seagullControllers.controller('ModalController', [
    '$scope',
    '$modalInstance',
    'pullUrl',
    function ($scope, $modalInstance, pullUrl) {
        $scope.pullCmd = "docker pull " + pullUrl;
        $scope.close = function () {
            $modalInstance.close();
        }
    }]);

/*
 * Image controller requests beego API server to get image
 */
seagullControllers.controller('ImageController', ['$scope', '$routeParams', 'dockerService',
    function ($scope, $routeParams, dockerService) {

        function getImageInfo(image) {
            dockerService.getImageInfo(image.id).then(function (info) {
                $scope.mdInfo = info.Comment;
            });
        }

        if (typeof $routeParams.id === 'undefined' || $routeParams.id == null) {
            dockerService.getImageByUserAndRepo($routeParams.user, $routeParams.repo).then(function (image) {
                $scope.image = image;
                getImageInfo(image);
            });
        } else {
            dockerService.getImageById($routeParams.id).then(function (image) {
                $scope.image = image;
                getImageInfo(image);
            });
        }

    }]);

/* Contaienrs controller requests beego API server to get configuration */
seagullControllers.controller('ConfigurationController', ['$scope', '$routeParams', 'dockerService',
    function ($scope, $routeParams, dockerService) {

        dockerService.getVersion().then(function (version) {
            $scope.version = version;
        });

        dockerService.getInfo().then(function (info) {
            $scope.info = info;
        });

    }]);

/* Dockerhub controller requests beego API server to get search images */
seagullControllers.controller('DockerhubController', ['$scope', '$routeParams', 'dockerService',
    function ($scope, $routeParams, dockerService) {

        /* Display the loading icon before get search images */
        $scope.isSearching = true;

        /* Request beego API server to get search images, default is seagull */
        dockerService.searchImages('seagull').then(function (images) {
            $scope.isSearching = false;
            $scope.images = images;
        });

        /* Request beego API server to get search images */
        $scope.getSearchImages = function (term) {
            $scope.isSearching = true;

            dockerService.searchImages(term).then(function (images) {
                $scope.isSearching = false;
                $scope.images = images;
                alert_success("Search images of " + term);
            }, function (reason) {
                $scope.isSearching = false;
                alert_error("Search images of " + term);
            });
        };

        /* Generate the image link by judging it's official images or not */
        $scope.getImageLink = function (name) {
            var address;

            if (name.indexOf('/') === -1) {
                // Example: https://registry.hub.docker.com/_/golang
                address = "https://registry.hub.docker.com/_/" + name;
            } else {
                // Example: https://registry.hub.docker.com/u/tobegit3hub/seagull
                address = "https://registry.hub.docker.com/u/" + name;
            }

            return address;
        };

    }]);
<commit_msg>Fix #23 pull message is not correct for tag<commit_after>'use strict';

/* Use JQuery.gritter to popup success message */
function alert_success(message) {
    $.gritter.add({
        title: 'Success!',
        text: message,
        image: 'static/img/pirate-logo.png',
        time: 3000
    });
}

/* Use JQuery.gritter to popup error message */
function alert_error(message) {
    $.gritter.add({
        title: 'Error!',
        text: message,
        image: 'static/img/pirate-logo.png',
        time: 3000
    });
}

/* All angular application controllers */
var seagullControllers = angular.module('seagullControllers', []);

/* This controller to get comment from beego api */
seagullControllers.controller('HomeController', ['$scope', '$routeParams', 'dockerService',
    function ($scope, $routeParams, dockerService) {

        /* Get the version object */
        dockerService.getVersion().then(function (version) {
            $scope.version = version;
            $scope.Os = version.Os;
            $scope.KernelVersion = version.KernelVersion;
            $scope.GoVersion = version.GoVersion;
            $scope.Version = version.Version;
        });

        /* Get the info object */
        dockerService.getInfo().then(function (info) {
            $scope.info = info;
            $scope.Containers = info.Containers;
            $scope.Images = info.Images;
        });
    }]);

/* Images controller requests beego API server to get/delete images */
seagullControllers.controller('ImagesController', ['$scope', '$routeParams', '$http', 'dockerService', '$modal',
    function ($scope, $routeParams, $http, dockerService, $modal) {

        dockerService.getVersion().then(function (version) {
            $scope.version = version;
            dockerService.getImages().then(function (images) {
                $scope.images = images;
            });
        });

        $scope.pullImage = function (image) {
            if ($scope.version) {
                $scope.pullUrl = $scope.version.PirateUrlAlias + "/" + image.Name + ":" + image.Tag;
                var modalInstance = $modal.open({
                    templateUrl: '/static/html/modal.html',
                    controller: 'ModalController',
                    resolve: {
                        pullUrl: function () {
                            return $scope.pullUrl;
                        }
                    }
                });

                modalInstance.result.then(function () {
                }, function () {
                });
            }
        };

        $scope.deleteImage = function (image) {
            var id = image.Id.substring(0, 12);
            dockerService.deleteImage(image).then(function (data) {
                alert_success("Delete image " + id);
                dockerService.getImages().then(function (images) {
                    $scope.images = images;
                });
            }, function (reason) {
                alert_error("Delete image " + id);
            });
        };

        $scope.isReadonly = function () {
            if ($scope.version && $scope.version.PirateMode !== 'readonly') {
                return false;
            }
            return true;
        }
    }]);

/*
 * Modal controller
 */
seagullControllers.controller('ModalController', [
    '$scope',
    '$modalInstance',
    'pullUrl',
    function ($scope, $modalInstance, pullUrl) {
        $scope.pullCmd = "docker pull " + pullUrl;
        $scope.close = function () {
            $modalInstance.close();
        }
    }]);

/*
 * Image controller requests beego API server to get image
 */
seagullControllers.controller('ImageController', ['$scope', '$routeParams', 'dockerService',
    function ($scope, $routeParams, dockerService) {

        function getImageInfo(image) {
            dockerService.getImageInfo(image.id).then(function (info) {
                $scope.mdInfo = info.Comment;
            });
        }

        if (typeof $routeParams.id === 'undefined' || $routeParams.id == null) {
            dockerService.getImageByUserAndRepo($routeParams.user, $routeParams.repo).then(function (image) {
                $scope.image = image;
                getImageInfo(image);
            });
        } else {
            dockerService.getImageById($routeParams.id).then(function (image) {
                $scope.image = image;
                getImageInfo(image);
            });
        }

    }]);

/* Contaienrs controller requests beego API server to get configuration */
seagullControllers.controller('ConfigurationController', ['$scope', '$routeParams', 'dockerService',
    function ($scope, $routeParams, dockerService) {

        dockerService.getVersion().then(function (version) {
            $scope.version = version;
        });

        dockerService.getInfo().then(function (info) {
            $scope.info = info;
        });

    }]);

/* Dockerhub controller requests beego API server to get search images */
seagullControllers.controller('DockerhubController', ['$scope', '$routeParams', 'dockerService',
    function ($scope, $routeParams, dockerService) {

        /* Display the loading icon before get search images */
        $scope.isSearching = true;

        /* Request beego API server to get search images, default is seagull */
        dockerService.searchImages('seagull').then(function (images) {
            $scope.isSearching = false;
            $scope.images = images;
        });

        /* Request beego API server to get search images */
        $scope.getSearchImages = function (term) {
            $scope.isSearching = true;

            dockerService.searchImages(term).then(function (images) {
                $scope.isSearching = false;
                $scope.images = images;
                alert_success("Search images of " + term);
            }, function (reason) {
                $scope.isSearching = false;
                alert_error("Search images of " + term);
            });
        };

        /* Generate the image link by judging it's official images or not */
        $scope.getImageLink = function (name) {
            var address;

            if (name.indexOf('/') === -1) {
                // Example: https://registry.hub.docker.com/_/golang
                address = "https://registry.hub.docker.com/_/" + name;
            } else {
                // Example: https://registry.hub.docker.com/u/tobegit3hub/seagull
                address = "https://registry.hub.docker.com/u/" + name;
            }

            return address;
        };

    }]);
<|endoftext|>


<commit_before>///Variables from html-record.jade
////links - links array
////geoExtent - the geographic extent for ths record
////collIds - collection ids array for this record
var service_types = {
		"OGC:WMS": "WMS Capabilities",
		"OGC:WFS": "WFS Capabilities",
		"OGC_WCS": "WCS Capabilities",
		"ESRI": "ESRI Service Endpoint",
		"OPENDAP": "OPeNDap Service"
};

var resp;

$(document).ready(function(){
	if(links){
		for(var iLink = 0; iLink < links.length; iLink ++){
			addOnlineFile(links[iLink]);
		}
	}

	if(collIds){
		$.post("/collection-names", { ids: collIds }, function(response) {
			resp = response;
			for(iColl = 0; iColl < response.length; iColl ++){
				addCollection(response[iColl]);
			}
		});
	}

	addMap("map", geoExtent);
});

function addCollection(collection){
	var strMenuItem = "
";
	strMenuItem += "";
	strMenuItem += collection.value.title;
	strMenuItem += "";
	strMenuItem += "
";

	$("#collections-menu").append(strMenuItem);

}

function addOnlineFile(link){
	var link_url = objGet(link, "URL", "Nothing");

	var link_type = objGet(link, "Name", "Downloadable Files");
	if(link_type == "Downloadable Files"){
		var service_type = objGet(link, "ServiceType", "").toUpperCase();
		if(service_type){
			if(service_types.hasOwnProperty(service_type)){
				link_type = service_types[service_type];
			}
		}
	}

	var strMenuItem = "
";
	strMenuItem += "";
	strMenuItem += link_type;
	strMenuItem += "";
	strMenuItem += "
";
	$("#file-attachment-menu").append(strMenuItem);
}

///Get property value
function objGet(obj, prop, defVal){
	if(obj.hasOwnProperty(prop)){
		return obj[prop];
	}else{
		return defVal;
	}
}

<commit_msg>Fixed a bug so that records in no collections appear as such in HTML view<commit_after>///Variables from html-record.jade
////links - links array
////geoExtent - the geographic extent for ths record
////collIds - collection ids array for this record
var service_types = {
		"OGC:WMS": "WMS Capabilities",
		"OGC:WFS": "WFS Capabilities",
		"OGC_WCS": "WCS Capabilities",
		"ESRI": "ESRI Service Endpoint",
		"OPENDAP": "OPeNDap Service"
};

var resp;

$(document).ready(function(){
	if(links){
		for(var iLink = 0; iLink < links.length; iLink ++){
			addOnlineFile(links[iLink]);
		}
	}

	if(collIds && collIds.length > 0){
		$.post("/collection-names", { ids: collIds }, function(response) {
			resp = response;
			for(var iColl = 0; iColl < response.length; iColl ++){
				addCollection(response[iColl]);
			}
		});
	} else {
		$("#collections-menu").append("
Not included in any collections
");
	}

	addMap("map", geoExtent);
});

function addCollection(collection){
	var strMenuItem = "
";
	strMenuItem += "";
	strMenuItem += collection.value.title;
	strMenuItem += "";
	strMenuItem += "
";

	$("#collections-menu").append(strMenuItem);

}

function addOnlineFile(link){
	var link_url = objGet(link, "URL", "Nothing");

	var link_type = objGet(link, "Name", "Downloadable Files");
	if(link_type == "Downloadable Files"){
		var service_type = objGet(link, "ServiceType", "").toUpperCase();
		if(service_type){
			if(service_types.hasOwnProperty(service_type)){
				link_type = service_types[service_type];
			}
		}
	}

	var strMenuItem = "
";
	strMenuItem += "";
	strMenuItem += link_type;
	strMenuItem += "";
	strMenuItem += "
";
	$("#file-attachment-menu").append(strMenuItem);
}

///Get property value
function objGet(obj, prop, defVal){
	if(obj.hasOwnProperty(prop)){
		return obj[prop];
	}else{
		return defVal;
	}
}

<|endoftext|>


<commit_before>/**
 * [placeholder.js]
 * Let working "placeholder" in Internet Explorer 9 lte
 *
 * @version 1.1.2
 * @author prevdev@gmail.com
 *
 * source code in https://github.com/Prev/placeholderjs
 * built in 2013.10.16
 *
 * MIT LICENSE
 */

(function(d){var PLACE_HOLDER_COLOR="#aaa";var intervalExcuting=false;var domBodyInnerHTML;function initPlaceholder(){var inputs=d.getElementsByTagName('input');var textareas=d.getElementsByTagName('textarea');var i;for(i=0;i<inputs.length;i++)setPlaceHolder(inputs[i]);for(i=0;i<textareas.length;i++)setPlaceHolder(textareas[i])}function intervalHandler(){if(domBodyInnerHTML!=d.body.innerHTML){initPlaceholder();domBodyInnerHTML=d.body.innerHTML}}function setPlaceHolder(inputText){var placeholder;if((inputText.type!="text"&&inputText.type!="password"&&inputText.nodeName.toLowerCase()!="textarea")||(inputText.placeholder&&!intervalExcuting))return;if(inputText.getAttribute('isPlaceHolderInited'))return;if(inputText.getAttribute('placeholder'))placeholder=inputText.getAttribute('placeholder');else{var matches=inputText.outerHTML.match(/placeholder=("([^"]*)"|[^\s>]*)/);if(matches&&matches[2])placeholder=matches[2];else if(matches&&matches[1])placeholder=matches[1];if(placeholder)inputText.setAttribute('placeholder',placeholder)}inputText.setAttribute('isPlaceHolderInited',true);if(!placeholder)return;inputText.setAttribute('originalColor',inputText.style.color);if(inputText.type=="text"||inputText.nodeName.toLowerCase()=="textarea"){if(!inputText.value){inputText.value=placeholder;inputText.style.color=PLACE_HOLDER_COLOR;inputText.setAttribute('isPlaceholdered',true)}if(inputText.addEventListener){inputText.addEventListener("focus",placeholderFocusHandler);inputText.addEventListener("blur",placeholderBlurHandler)}else if(inputText.attachEvent){inputText.attachEvent("onfocus",placeholderFocusHandler);inputText.attachEvent("onblur",placeholderBlurHandler)}else{inputText.onfocus=placeholderFocusHandler;inputText.onblur=placeholderBlurHandler}}else if(inputText.type=="password"){var randInputId=Math.floor(Math.random()*100000);var fakeInputText=d.createElement("input");fakeInputText.className=inputText.className+" _fake-placeholder-"+randInputId;fakeInputText.type="text";fakeInputText.value=placeholder;for(var i in inputText.style){if(inputText.style[i])fakeInputText.style[i]=inputText.style[i]}fakeInputText.style.color=PLACE_HOLDER_COLOR;inputText.className+=" _placeholder-"+randInputId;inputText.style.display="none";inputText.parentElement.insertBefore(fakeInputText,inputText);if(inputText.className.substr(0,1)==" ")inputText.className=inputText.className.substr(1,inputText.className.length);if(fakeInputText.className.substr(0,1)==" ")fakeInputText.className=fakeInputText.className.substr(1,fakeInputText.className.length);fakeInputText.setAttribute("randInputId",randInputId);inputText.setAttribute("randInputId",randInputId);if(fakeInputText.addEventListener){fakeInputText.addEventListener("focus",passwordPlaceHolderFocusHandler);inputText.addEventListener("blur",passwordPlaceHolderBlurHandler)}else if(fakeInputText.attachEvent){fakeInputText.attachEvent("onfocus",passwordPlaceHolderFocusHandler);inputText.attachEvent("onblur",passwordPlaceHolderBlurHandler)}else{fakeInputText.onfocus=passwordPlaceHolderFocusHandler;inputText.onblur=passwordPlaceHolderBlurHandler}}if(!intervalExcuting){setInterval(intervalHandler,20);intervalExcuting=true}}function placeholderFocusHandler(event){var target=event.srcElement||this;if(target.getAttribute('isPlaceholdered')&&target.getAttribute('isPlaceholdered')!="false"){target.value="";target.style.color=target.getAttribute('originalColor');target.setAttribute('isPlaceholdered',false)}}function placeholderBlurHandler(event){var target=event.srcElement||this;if(target.value==""){target.value=target.getAttribute('placeholder');target.style.color=PLACE_HOLDER_COLOR;target.setAttribute('isPlaceholdered',true)}else target.setAttribute('isPlaceholdered',false)}function passwordPlaceHolderFocusHandler(event){var target=event.srcElement||this;var randInputId=target.getAttribute('randInputId');var realInputText=d.getElementsByClassName("_placeholder-"+randInputId)[0];target.style.display="none";realInputText.style.display="inline";realInputText.focus()}function passwordPlaceHolderBlurHandler(event){var target=event.srcElement||this;if(target.value==""){var randInputId=target.getAttribute('randInputId');var fakeInputText=d.getElementsByClassName("_fake-placeholder-"+randInputId)[0];fakeInputText.style.display="inline";target.style.display="none"}}if(!d.getElementsByClassName){if(d.querySelectorAll){d.getElementsByClassName=function(className){return d.querySelectorAll("."+className)}}else if(d.getElementsByTagName){d.getElementsByClassName=function(className){var t=d.getElementsByTagName("input");var arr=[];for(var i=0;i<t.length;i++){var classLists=t[i].className.split(" ");if(classLists.indexOf(className)!=-1)arr.push(t[i])}return arr}}}function NodeList(length){if(length){for(var i=0;i<length;i++)this[i]=0;this.length=parseInt(length)}else this.length=0}NodeList.prototype={item:function(index){return this[index]},__push:function(node){var __index=this.length;this[__index]=node;this.length++},toString:function(){return"[object NodeList]"}};if(!Array.prototype.indexOf){Array.prototype.indexOf=function(searchElement,fromIndex){if(!fromIndex)fromIndex=0;for(var i=fromIndex;i<this.length;i++){if(this[i]===searchElement)return i}return-1}}if(window.addEventListener)window.addEventListener('load',initPlaceholder);else if(window.attachEvent)window.attachEvent('onload',initPlaceholder)})(document);<commit_msg>v 0.5.4 r4<commit_after>/**
 * [placeholder.js]
 * Let working "placeholder" in Internet Explorer 9 lte
 *
 * @version 1.1.4
 * @author prevdev@gmail.com
 *
 * source code in https://github.com/Prev/placeholderjs
 * built in 2013.11.16
 *
 * MIT LICENSE
 */

(function(d){var g="#aaa";var h;function isPlaceholderSupport(){var a=document.createElement('input');return('placeholder'in a)}function initPlaceholder(){var a=d.getElementsByTagName('input');var b=d.getElementsByTagName('textarea');var i;for(i=0;i<a.length;i++)setPlaceHolder(a[i]);for(i=0;i<b.length;i++)setPlaceHolder(b[i]);if(!isPlaceholderSupport()){setInterval(intervalHandler,20)}}function intervalHandler(){if(h!=d.body.innerHTML){initPlaceholder();h=d.body.innerHTML}}function setPlaceHolder(a){var b;if((a.type!="text"&&a.type!="password"&&a.nodeName.toLowerCase()!="textarea")||(a.placeholder&&isPlaceholderSupport()))return;if(a.getAttribute('isPlaceHolderInited'))return;if(a.getAttribute('placeholder'))b=a.getAttribute('placeholder');else{var c=a.outerHTML.match(/placeholder=("([^"]*)"|[^\s>]*)/);if(c&&c[2])b=c[2];else if(c&&c[1])b=c[1];if(b)a.setAttribute('placeholder',b)}a.setAttribute('isPlaceHolderInited',true);if(!b)return;a.setAttribute('originalColor',a.style.color);if(a.type=="text"||a.nodeName.toLowerCase()=="textarea"){if(!a.value){a.value=b;a.style.color=g;a.setAttribute('isPlaceholdered',true)}if(a.addEventListener){a.addEventListener("focus",placeholderFocusHandler);a.addEventListener("blur",placeholderBlurHandler)}else if(a.attachEvent){a.attachEvent("onfocus",placeholderFocusHandler);a.attachEvent("onblur",placeholderBlurHandler)}else{a.onfocus=placeholderFocusHandler;a.onblur=placeholderBlurHandler}}else if(a.type=="password"){var e=Math.floor(Math.random()*100000);var f=d.createElement("input");f.className=a.className+" _fake-placeholder-"+e;f.type="text";f.value=b;for(var i in a.style){if(a.style[i])f.style[i]=a.style[i]}f.style.color=g;a.className+=" _placeholder-"+e;a.style.display="none";a.parentElement.insertBefore(f,a);if(a.className.substr(0,1)==" ")a.className=a.className.substr(1,a.className.length);if(f.className.substr(0,1)==" ")f.className=f.className.substr(1,f.className.length);f.setAttribute("randInputId",e);a.setAttribute("randInputId",e);if(f.addEventListener){f.addEventListener("focus",passwordPlaceHolderFocusHandler);a.addEventListener("blur",passwordPlaceHolderBlurHandler)}else if(f.attachEvent){f.attachEvent("onfocus",passwordPlaceHolderFocusHandler);a.attachEvent("onblur",passwordPlaceHolderBlurHandler)}else{f.onfocus=passwordPlaceHolderFocusHandler;a.onblur=passwordPlaceHolderBlurHandler}}}function placeholderFocusHandler(a){var b=a.srcElement||this;if(b.getAttribute('isPlaceholdered')&&b.getAttribute('isPlaceholdered')!="false"){b.value="";b.style.color=b.getAttribute('originalColor');b.setAttribute('isPlaceholdered',false)}}function placeholderBlurHandler(a){var b=a.srcElement||this;if(b.value==""){b.value=b.getAttribute('placeholder');b.style.color=g;b.setAttribute('isPlaceholdered',true)}else b.setAttribute('isPlaceholdered',false)}function passwordPlaceHolderFocusHandler(a){var b=a.srcElement||this;var c=b.getAttribute('randInputId');var e=d.getElementsByClassName("_placeholder-"+c)[0];b.style.display="none";e.style.display="inline";e.focus()}function passwordPlaceHolderBlurHandler(a){var b=a.srcElement||this;if(b.value==""){var c=b.getAttribute('randInputId');var e=d.getElementsByClassName("_fake-placeholder-"+c)[0];e.style.display="inline";b.style.display="none"}}if(!d.getElementsByClassName){if(d.querySelectorAll){d.getElementsByClassName=function(a){return d.querySelectorAll("."+a)}}else if(d.getElementsByTagName){d.getElementsByClassName=function(a){var t=d.getElementsByTagName("input");var b=[];for(var i=0;i<t.length;i++){var c=t[i].className.split(" ");if(c.indexOf(a)!=-1)b.push(t[i])}return b}}}function NodeList(a){if(a){for(var i=0;i<a;i++)this[i]=0;this.length=parseInt(a)}else this.length=0}NodeList.prototype={item:function(a){return this[a]},__push:function(a){var b=this.length;this[b]=a;this.length++},toString:function(){return"[object NodeList]"}};if(!Array.prototype.indexOf){Array.prototype.indexOf=function(a,b){if(!b)b=0;for(var i=b;i<this.length;i++){if(this[i]===a)return i}return-1}}if(window.addEventListener)window.addEventListener('load',initPlaceholder);else if(window.attachEvent)window.attachEvent('onload',initPlaceholder)})(document);<|endoftext|>