<commit_before>var _ = require('lodash'),
    zombieLogic = require('./zombie')(),
    playerLogic = require('./player')(),
    buildingLogic = require('./building')(),
    weapon = require('./weapon')();

module.exports = function(game) {

  var gameState = {},
      staticObjects,
      player,
      zombies,
      cursors,
      bullets,
      buildings,
      playerCollisionGroup,
      zombiesCollisionGroup,
      staticObjectsCollisionGroup;

  function resetEntity(entity) {
    entity.body.velocity.x = 0;
    entity.body.velocity.y = 0;
  };

  function killZombie(bullet, zombie) {
    bullet.kill();
    zombie.kill();
  }

  gameState.create = function () {
    game.physics.startSystem(Phaser.Physics.P2JS);

    staticObjects = game.add.group();
    buildings = game.add.group();
    zombies = game.add.group();

    playerCollisionGroup = game.physics.p2.createCollisionGroup();
    zombiesCollisionGroup = game.physics.p2.createCollisionGroup();
    staticObjectsCollisionGroup = game.physics.p2.createCollisionGroup();

    //Create an array of coordinates that make a 3000px x 3000 grid
    var placementMatrix = [];
    for (var i = 0; i < 6; i++) {
      for (var j = 0; j < 6; j++) {
        placementMatrix.push([i*500, j*500]);
      };
    };

    //Iterate through array to randomly drop cars or trees
    //Once a placement is determined in a grid box, it is randomly placed
    _.each(placementMatrix, function (coordinates) {
      rand = _.random(0, 100);
      randX = _.random(0, 500);
      randY = _.random(0, 500);
      if (rand < 50) {
        if (rand%2 == 0) {
          var car = staticObjects.create(coordinates[0]-randX, coordinates[1]-randY, 'car');
          game.physics.p2.enable(car);
          car.body.setCollisionGroup(staticObjectsCollisionGroup);
        } else {
          var tree = staticObjects.create(coordinates[0]-randX, coordinates[1]-randY, 'tree');
          game.physics.p2.enable(tree);
          tree.body.setCollisionGroup(staticObjectsCollisionGroup);
        }
      } else if (rand > 90) {
        var building = buildings.create(coordinates[0], coordinates[1], 'building');
        building.hasSpawned = false;
        game.physics.p2.enable(building);
        building.body.setCollisionGroup(staticObjectsCollisionGroup);
      }
    });

    //Create player in center area
    player = game.add.sprite(game.world.centerX, game.world.centerY, 'hero');
    player.pivot.setTo(0,0);

    game.physics.p2.enable(player);
    player.body.collideWorldBounds = true;
    player.body.setCollisionGroup(playerCollisionGroup);

    //Create bullets
    bullets = game.add.group();
    game.physics.enable(bullets, Phaser.Physics.ARCADE);
  };

  gameState.update = function() {
    //  Reset the players velocity (movement)
    resetEntity(player);

    game.camera.follow(player);

    // game.physics.arcade.collide(player, staticObjects);
    // game.physics.arcade.collide(player, zombies);
    // game.physics.arcade.collide(zombies, staticObjects);
    // game.physics.arcade.collide(zombies, zombies);

    game.physics.arcade.overlap(bullets, zombies, killZombie, null, this);

    playerLogic.movePlayer(game, player);
    playerLogic.rotatePlayer(game, player);

    if (game.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR)) {
        weapon.shoot(game, player, bullets);
    }

    _.each(zombies.children, function(zombie){
      zombieLogic.moveZombie(player, zombie);
    });

    _.each(buildings.children, function(building) {
      buildingLogic.spawnZombiesFromBuilding(game, zombies, player, building, zombiesCollisionGroup);
    });
  }

  return gameState;
};<commit_msg>Add mouse click for firing<commit_after>var _ = require('lodash'),
    zombieLogic = require('./zombie')(),
    playerLogic = require('./player')(),
    buildingLogic = require('./building')(),
    weapon = require('./weapon')();

module.exports = function(game) {

  var gameState = {},
      staticObjects,
      player,
      zombies,
      cursors,
      bullets,
      buildings,
      playerCollisionGroup,
      zombiesCollisionGroup,
      staticObjectsCollisionGroup;

  function resetEntity(entity) {
    entity.body.velocity.x = 0;
    entity.body.velocity.y = 0;
  };

  function killZombie(bullet, zombie) {
    bullet.kill();
    zombie.kill();
  }

  gameState.create = function () {
    game.physics.startSystem(Phaser.Physics.P2JS);

    staticObjects = game.add.group();
    buildings = game.add.group();
    zombies = game.add.group();

    playerCollisionGroup = game.physics.p2.createCollisionGroup();
    zombiesCollisionGroup = game.physics.p2.createCollisionGroup();
    staticObjectsCollisionGroup = game.physics.p2.createCollisionGroup();

    //Create an array of coordinates that make a 3000px x 3000 grid
    var placementMatrix = [];
    for (var i = 0; i < 6; i++) {
      for (var j = 0; j < 6; j++) {
        placementMatrix.push([i*500, j*500]);
      };
    };

    //Iterate through array to randomly drop cars or trees
    //Once a placement is determined in a grid box, it is randomly placed
    _.each(placementMatrix, function (coordinates) {
      rand = _.random(0, 100);
      randX = _.random(0, 500);
      randY = _.random(0, 500);
      if (rand < 50) {
        if (rand%2 == 0) {
          var car = staticObjects.create(coordinates[0]-randX, coordinates[1]-randY, 'car');
          game.physics.p2.enable(car);
          car.body.setCollisionGroup(staticObjectsCollisionGroup);
        } else {
          var tree = staticObjects.create(coordinates[0]-randX, coordinates[1]-randY, 'tree');
          game.physics.p2.enable(tree);
          tree.body.setCollisionGroup(staticObjectsCollisionGroup);
        }
      } else if (rand > 90) {
        var building = buildings.create(coordinates[0], coordinates[1], 'building');
        building.hasSpawned = false;
        game.physics.p2.enable(building);
        building.body.setCollisionGroup(staticObjectsCollisionGroup);
      }
    });

    //Create player in center area
    player = game.add.sprite(game.world.centerX, game.world.centerY, 'hero');
    player.pivot.setTo(0,0);

    game.physics.p2.enable(player);
    player.body.collideWorldBounds = true;
    player.body.setCollisionGroup(playerCollisionGroup);

    //Create bullets
    bullets = game.add.group();
    game.physics.enable(bullets, Phaser.Physics.ARCADE);
  };

  gameState.update = function() {
    //  Reset the players velocity (movement)
    resetEntity(player);

    game.camera.follow(player);

    // game.physics.arcade.collide(player, staticObjects);
    // game.physics.arcade.collide(player, zombies);
    // game.physics.arcade.collide(zombies, staticObjects);
    // game.physics.arcade.collide(zombies, zombies);

    game.physics.arcade.overlap(bullets, zombies, killZombie, null, this);

    playerLogic.movePlayer(game, player);
    playerLogic.rotatePlayer(game, player);

    if (game.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR) || game.input.mousePointer.justPressed()) {
        weapon.shoot(game, player, bullets);
    }

    _.each(zombies.children, function(zombie){
      zombieLogic.moveZombie(player, zombie);
    });

    _.each(buildings.children, function(building) {
      buildingLogic.spawnZombiesFromBuilding(game, zombies, player, building, zombiesCollisionGroup);
    });
  }

  return gameState;
};<|endoftext|>


<commit_before>/*

function demoFromHTML() {

     var pdf = new jsPDF('p', 'pt', 'a4', false);

  alert(duration_longue);

          if(duration_longue){

            if(adult){
              alert("adult_long");
              var logo = new Image();
              logo.src = "https://vizkit.github.io/pdf_images/long/Long_adults/long_adults_dataset1_1.PNG";
              pdf.addImage(logo, 'PNG', 2, 2, 590,850);
              pdf.addPage();
            }else{
                 alert("enfant_LONGUE");
              logo.src = "https://vizkit.github.io/pdf_images/long/Long_enfants/long_enfants_dataset1_1.PNG";
              pdf.addImage(logo, 'PNG', 2, 2, 590,850);
              pdf.addPage();
            }

          }else{
            if(enfant){
                 alert("enfant_Court");
                logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset1_1.PNG";
                pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                pdf.addPage();

            }else {
              alert("adult_court");
              logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset1_1.PNG";
              pdf.addImage(logo, 'PNG', 2, 2, 590,850);
              pdf.addPage();

            }

           var uno= 1;
          }

       /*   var paso;
        for (paso = 4; paso < 6; paso++) {
            pdf.addPage();
            var logo = new Image();
            logo.src = paso+".png";
            pdf.addImage(logo, 'PNG', 2, 2, 590,850);
          // Se ejecuta 5 veces, con valores desde paso desde 0 hasta 4.

          };

     pdf.output("dataurlnewwindow");

        }*/

  $(document).ready(function(){
  //on initialise les variables avec les valeurs par défaut

    var duree = "longue";
    var pub = "adu";
    var nbDePersonnes = 16;
    var sce = 1;
    var duration_longue = 1;
    var duration_courte = 0;
    var enfant = 0;
    var adult = 1;
  //on appuie les boutons en conséquence
    $("#dur_lon").addClass("active");
    $("#pub_adu").addClass("active");
    $("#sce_1").addClass("active");
    //$("#car").load('carousel_long.html');

    //On remplit le champ du bouton +/- avec la valeur par défaut
    $("#inputnb").val(nbDePersonnes);

    //var carousel_c = $.get("carousel_court.html");
    //var carousel_l = $.get("carousel_long.html");
  //On change la valeur des variables en fonction des actions utilisateurs
  //Pour la durée :
    $("#dur_cou").click(function(e){
      duree = "courte";
      duration_courte = 1;
      duration_longue = 0;
      $("#dur_lon").removeClass("active");
      $("#dur_cou").addClass("active");
      //var code = load("carousel_court.html");
      //$("#myCarousel").replaceWith("
 This text is strong
  This text is italic
");
      //alert(carousel_c);
      //$("#car").empty();
      $("#car").load('carousel_court.html');
      $("#p1").show();
            alert(duration_longue);
            alert(duration_courte);
      alert("Chargement terminé \n Guide pour atelier court !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();});
    });
    $("#dur_lon").click(function(e){
      duree = "longue";
      duration_longue = 1;
      duration_courte = 0;
      $("#dur_cou").removeClass("active");
      $("#dur_lon").addClass("active");
      //$("#myCarousel").replaceWith(carousel_l);
      //$("#car").empty();
      $("#car").load('carousel_long.html');
      $("#p1").show();
      alert("Chargement terminé \n Guide pour atelier long !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();})
    });
  //Pour le public :
    $("#pub_enf").click(function(e){
      pub = "enf";
      adult = 0;
      enfant = 1;
      $("#pub_adu").removeClass("active");
      $("#pub_enf").addClass("active");
    });
    $("#pub_adu").click(function(e){
      pub = "adu";
      adult = 1;
      enfant = 0;
      $("#pub_enf").removeClass("active");
      $("#pub_adu").addClass("active");
    });
  //Pour le scénario :
    $("#sce_2").click(function(e){
      sce = 2;
      $("#sce_1").removeClass("active");
      $("#sce_2").addClass("active");
    });
    $("#sce_1").click(function(e){
      sce = 1;
      $("#sce_2").removeClass("active");
      $("#sce_1").addClass("active");
    });

    $("#pointLien").click(function(e){
      if(pub == "enf"){
        $("#pointLien").attr('href','graphiques_enfants.html');
      }else{
        $("#pointLien").attr('href','graphiques_adultes.html');
      }
    });

    $("#buttonemail").click(function(e){

     var pdf = new jsPDF('p', 'pt', 'a4', false);

  alert("hoaaaa");
  alert(duration_longue);

          if(duration_longue == "1"){

            if(adult== "1"){
              alert("adult_long");
              var logo = new Image();
              logo.src = "https://vizkit.github.io/pdf_images/long/Long_adults/long_adults_dataset1_1.PNG";
              pdf.addImage(logo, 'PNG', 2, 2, 590,850);
              pdf.addPage();
            }else{
                 alert("enfant_LONGUE");
              logo.src = "https://vizkit.github.io/pdf_images/long/Long_enfants/long_enfants_dataset1_1.PNG";
              pdf.addImage(logo, 'PNG', 2, 2, 590,850);
              pdf.addPage();
            }

          }else{
            if(enfant== "1"){
                 alert("enfant_Court");
                logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset1_1.PNG";
                pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                pdf.addPage();

            }else {
              alert("adult_court");
              logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset1_1.PNG";
              pdf.addImage(logo, 'PNG', 2, 2, 590,850);
              pdf.addPage();

            }

           var uno= 1;
          }

       /*   var paso;
        for (paso = 4; paso < 6; paso++) {
            pdf.addPage();
            var logo = new Image();
            logo.src = paso+".png";
            pdf.addImage(logo, 'PNG', 2, 2, 590,850);
          // Se ejecuta 5 veces, con valores desde paso desde 0 hasta 4.

          };*/

     pdf.output("dataurlnewwindow");

     });

  });

<commit_msg>Update dynamic_carousel.js<commit_after>/*

function demoFromHTML() {

     var pdf = new jsPDF('p', 'pt', 'a4', false);

  alert(duration_longue);

          if(duration_longue){

            if(adult){
              alert("adult_long");
              var logo = new Image();
              logo.src = "https://vizkit.github.io/pdf_images/long/Long_adults/long_adults_dataset1_1.PNG";
              pdf.addImage(logo, 'PNG', 2, 2, 590,850);
              pdf.addPage();
            }else{
                 alert("enfant_LONGUE");
              logo.src = "https://vizkit.github.io/pdf_images/long/Long_enfants/long_enfants_dataset1_1.PNG";
              pdf.addImage(logo, 'PNG', 2, 2, 590,850);
              pdf.addPage();
            }

          }else{
            if(enfant){
                 alert("enfant_Court");
                logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset1_1.PNG";
                pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                pdf.addPage();

            }else {
              alert("adult_court");
              logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset1_1.PNG";
              pdf.addImage(logo, 'PNG', 2, 2, 590,850);
              pdf.addPage();

            }

           var uno= 1;
          }

       /*   var paso;
        for (paso = 4; paso < 6; paso++) {
            pdf.addPage();
            var logo = new Image();
            logo.src = paso+".png";
            pdf.addImage(logo, 'PNG', 2, 2, 590,850);
          // Se ejecuta 5 veces, con valores desde paso desde 0 hasta 4.

          };

     pdf.output("dataurlnewwindow");

        }*/
    var duration_longue = true;
    var duration_courte = false;
    var enfant = false;
    var adult = true;

  $(document).ready(function(){
  //on initialise les variables avec les valeurs par défaut

    var duree = "longue";
    var pub = "adu";
    var nbDePersonnes = 16;
    var sce = 1;

  //on appuie les boutons en conséquence
    $("#dur_lon").addClass("active");
    $("#pub_adu").addClass("active");
    $("#sce_1").addClass("active");
    //$("#car").load('carousel_long.html');

    //On remplit le champ du bouton +/- avec la valeur par défaut
    $("#inputnb").val(nbDePersonnes);

    //var carousel_c = $.get("carousel_court.html");
    //var carousel_l = $.get("carousel_long.html");
  //On change la valeur des variables en fonction des actions utilisateurs
  //Pour la durée :
    $("#dur_cou").click(function(e){
      duree = "courte";
      duration_courte = true;
      duration_longue = false;
      $("#dur_lon").removeClass("active");
      $("#dur_cou").addClass("active");
      //var code = load("carousel_court.html");
      //$("#myCarousel").replaceWith("
 This text is strong
  This text is italic
");
      //alert(carousel_c);
      //$("#car").empty();
      $("#car").load('carousel_court.html');
      $("#p1").show();
            alert(duration_longue);
            alert(duration_courte);
      alert("Chargement terminé \n Guide pour atelier court !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();});
    });
    $("#dur_lon").click(function(e){
      duree = "longue";
      duration_longue = true;
      duration_courte = false;
      $("#dur_cou").removeClass("active");
      $("#dur_lon").addClass("active");
      //$("#myCarousel").replaceWith(carousel_l);
      //$("#car").empty();
      $("#car").load('carousel_long.html');
      $("#p1").show();
      alert("Chargement terminé \n Guide pour atelier long !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();})
    });
  //Pour le public :
    $("#pub_enf").click(function(e){
      pub = "enf";
      adult = false;
      enfant = true;
      $("#pub_adu").removeClass("active");
      $("#pub_enf").addClass("active");
    });
    $("#pub_adu").click(function(e){
      pub = "adu";
      adult = true;
      enfant = false;
      $("#pub_enf").removeClass("active");
      $("#pub_adu").addClass("active");
    });
  //Pour le scénario :
    $("#sce_2").click(function(e){
      sce = 2;
      $("#sce_1").removeClass("active");
      $("#sce_2").addClass("active");
    });
    $("#sce_1").click(function(e){
      sce = 1;
      $("#sce_2").removeClass("active");
      $("#sce_1").addClass("active");
    });

    $("#pointLien").click(function(e){
      if(pub == "enf"){
        $("#pointLien").attr('href','graphiques_enfants.html');
      }else{
        $("#pointLien").attr('href','graphiques_adultes.html');
      }
    });

    $("#buttonemail").click(function(e){

     var pdf = new jsPDF('p', 'pt', 'a4', false);

  alert("hoaaaa");
  alert(duration_longue);

          if(duration_longue){

            if(adult){
              alert("adult_long");
              var logo = new Image();
              logo.src = "https://vizkit.github.io/pdf_images/long/Long_adults/long_adults_dataset1_1.PNG";
              pdf.addImage(logo, 'PNG', 2, 2, 590,850);
              pdf.addPage();
            }else{
                 alert("enfant_LONGUE");
              logo.src = "https://vizkit.github.io/pdf_images/long/Long_enfants/long_enfants_dataset1_1.PNG";
              pdf.addImage(logo, 'PNG', 2, 2, 590,850);
              pdf.addPage();
            }

          }else{
            if(enfant){
                 alert("enfant_Court");
                logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset1_1.PNG";
                pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                pdf.addPage();

            }else {
              alert("adult_court");
              logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset1_1.PNG";
              pdf.addImage(logo, 'PNG', 2, 2, 590,850);
              pdf.addPage();

            }

           var uno= 1;
          }

       /*   var paso;
        for (paso = 4; paso < 6; paso++) {
            pdf.addPage();
            var logo = new Image();
            logo.src = paso+".png";
            pdf.addImage(logo, 'PNG', 2, 2, 590,850);
          // Se ejecuta 5 veces, con valores desde paso desde 0 hasta 4.

          };*/

     pdf.output("dataurlnewwindow");

     });

  });

<|endoftext|>


<commit_before>(function () {
"use strict";

var i, j, pieces = [];

function $(id) {
  return document.getElementById(id);
}

function html(id, text) {
  $(id).innerHTML = text;
}

var dragDrop = {
  initialMouseX: null,
  initialMouseY: null,
  startX: null,
  startY: null,
  draggedObject: null,

  bind: function (element) {
    if (typeof element === "string") {
      element = $(element);
    }
    element.onmousedown = dragDrop.startDragMouse;
  },

  startDragMouse: function (e) {
    dragDrop.startDrag(this);
    dragDrop.initialMouseX = e.clientX;
    dragDrop.initialMouseY = e.clientY;
    document.addEventListener("mousemove", dragDrop.dragMouse, false);
    document.addEventListener("mouseup", dragDrop.releaseElement, false);
    return false;
  },

  startDrag: function (object) {
    if (dragDrop.draggedObjct) {
      dragDrop.releaseElement();
    }
    if (isNaN(parseInt(object.style.left))) {
      object.style.left = "0px";
    }
    if (isNaN(parseInt(object.style.top))) {
      object.style.top = "0px";
    }
    dragDrop.startX = parseInt(object.style.left);
    dragDrop.startY = parseInt(object.style.top);
    dragDrop.draggedObject = object;
  },

  dragMouse: function (e) {
    var dx = e.clientX - dragDrop.initialMouseX;
    var dy = e.clientY - dragDrop.initialMouseY;
    dragDrop.draggedObject.style.left = dragDrop.startX + dx + "px";
    dragDrop.draggedObject.style.top = dragDrop.startY + dy + "px";
    return false;
  },

  releaseElement: function () {
    document.removeEventListener("mousemove", dragDrop.dragMouse, false);
    document.removeEventListener("mouseup", dragDrop.releaseElement, false);
    dragDrop.draggedObject = null;
  }
}

function shuffle(array) {
  var i, j, temp;
  for (i = array.length - 1; i > 0; i -= 1) {
    j = Math.floor(Math.random() * (i + 1));
    temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }
}

for (i = 0; i < 4; i += 1) {
  for (j = 1; j <= 13; j += 1) {
    pieces.push(j);
  }
}
shuffle(pieces);

for (i = 0; i < 8; i += 1) {
  html("piece" + i, pieces[i]);
  dragDrop.bind("piece" + i);
}

}());
<commit_msg>Allows pieces to be dragged and dropped onto the game board.<commit_after>(function () {
"use strict";

var i, j, pieces = [];

function $(id) {
  return document.getElementById(id);
}

function html(id, text) {
  $(id).innerHTML = text;
}

var dragDrop = {
  initialMouseX: null,
  initialMouseY: null,
  startX: null,
  startY: null,
  draggedObject: null,

  bind: function (element) {
    if (typeof element === "string") {
      element = $(element);
    }
    element.onmousedown = dragDrop.startDragMouse;
  },

  startDragMouse: function (e) {
    dragDrop.startDrag(this);
    dragDrop.initialMouseX = e.clientX;
    dragDrop.initialMouseY = e.clientY;
    document.addEventListener("mousemove", dragDrop.dragMouse, false);
    document.addEventListener("mouseup", dragDrop.releaseElement, false);
    return false;
  },

  startDrag: function (object) {
    if (dragDrop.draggedObjct) {
      dragDrop.releaseElement();
    }
    if (isNaN(parseInt(object.style.left))) {
      object.style.left = "0px";
    }
    if (isNaN(parseInt(object.style.top))) {
      object.style.top = "0px";
    }
    dragDrop.startX = parseInt(object.style.left);
    dragDrop.startY = parseInt(object.style.top);
    dragDrop.draggedObject = object;
  },

  dragMouse: function (e) {
    var dx = e.clientX - dragDrop.initialMouseX;
    var dy = e.clientY - dragDrop.initialMouseY;
    dragDrop.draggedObject.style.left = dragDrop.startX + dx + "px";
    dragDrop.draggedObject.style.top = dragDrop.startY + dy + "px";
    return false;
  },

  releaseElement: function (e) {
    var under = null;
    document.removeEventListener("mousemove", dragDrop.dragMouse, false);
    document.removeEventListener("mouseup", dragDrop.releaseElement, false);
    dragDrop.draggedObject.style.display = 'none';
    under = document.elementFromPoint(e.clientX, e.clientY);
    if (under && under.nodeName === 'TD' && under.innerHTML === '') {
      under.innerHTML = dragDrop.draggedObject.innerHTML;
      dragDrop.draggedObject.parentNode.removeChild(dragDrop.draggedObject);
    } else {
      dragDrop.draggedObject.style.display = 'inline-block';
    }
    dragDrop.draggedObject = null;
  }
}

function shuffle(array) {
  var i, j, temp;
  for (i = array.length - 1; i > 0; i -= 1) {
    j = Math.floor(Math.random() * (i + 1));
    temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }
}

for (i = 0; i < 4; i += 1) {
  for (j = 1; j <= 13; j += 1) {
    pieces.push(j);
  }
}
shuffle(pieces);

for (i = 0; i < 8; i += 1) {
  html("piece" + i, pieces[i]);
  dragDrop.bind("piece" + i);
}

}());
<|endoftext|>


<commit_before>// authc.js
//
// Authentication middleware
//
// Copyright 2011-2013, E14N https://e14n.com/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

"use strict";

var databank = require("databank"),
    Step = require("step"),
    _ = require("lodash"),
    bcrypt = require("bcryptjs"),
    fs = require("fs"),
    path = require("path"),
    os = require("os"),
    randomString = require("./randomstring").randomString,
    Activity = require("./model/activity").Activity,
    ActivityObject = require("./model/activityobject").ActivityObject,
    User = require("./model/user").User,
    Client = require("./model/client").Client,
    HTTPError = require("./httperror").HTTPError,
    URLMaker = require("./urlmaker").URLMaker,
    BearerToken = require("./model/bearertoken").BearerToken,
    NoSuchThingError = databank.NoSuchThingError;

// Remove all properties of an object and its properties if the key starts with _

var sanitizedJSON = function(obj) {
    var clean = {};
    _.each(obj, function(value, key) {
        if (!_.has(obj, key)) {
            return;
        } else if (key[0] === "_") {
            return;
        } else if (_.isObject(value)) { // includes arrays!
            clean[key] = sanitizedJSON(value);
        } else if (!_.isFunction(value)) {
            clean[key] = value;
        }
    });
    return clean;
};

var maybeAuth = function(req, res, next) {
    if (!hasOAuth(req)) {
        // No client, no user
        next();
    } else {
        clientAuth(req, res, next);
    }
};

var hasOAuth = function(req) {
    return (req &&
            _.has(req, "headers") &&
            _.has(req.headers, "authorization") &&
            req.headers.authorization.match(/^OAuth/));
};

var hasOAuth2 = function(req) {
    return (req &&
            _.has(req, "headers") &&
            _.has(req.headers, "authorization") &&
            req.headers.authorization.match(/^Bearer/));
};

var userOrClientAuth = function(req, res, next) {
    if (hasToken(req)) {
        userAuth(req, res, next);
    } else {
        clientAuth(req, res, next);
    }
};

var wrapRequest = function(req, path) {
    var areq = _.clone(req);

    if (path[0] !== "/") {
        path = "/" + path;
    }

    areq.originalUrl = path + req.originalUrl;

    return areq;
};

// Accept either 2-legged or 3-legged OAuth

var clientAuth = function(req, res, next) {

    var log = req.log, areq;

    req.client = null;
    res.locals.client = null; // init to null

    log.debug("Checking for 2-legged OAuth credentials");

    // If we're coming in the front door, and we have a path, provide it
    if (req.header("Host").toLowerCase() === URLMaker.makeHost() && URLMaker.path) {
        areq = wrapRequest(req, URLMaker.path);
    } else {
        areq = req;
    }

    areq.authenticate(["client"], function(error, authenticated) {

        var deetz;

        if (error) {
            log.error(error);
            next(error);
            return;
        }

        if (!authenticated) {
            log.debug("Not authenticated");
            return;
        }

        log.debug("Authentication succeeded");

        deetz = areq.getAuthDetails();

        log.debug(deetz);

        if (!deetz || !deetz.user || !deetz.user.id) {
            log.debug("Incorrect auth details.");
            return;
        }

        Step(
            function() {
                req.app.provider.getClient(deetz.user.id, this);
            },
            function(err, client) {
                if (err) throw err;

                req.client = client;
                res.locals.client = sanitizedJSON(req.client);

                if (client.webfinger || client.host) {
                    client.asActivityObject(this);
                } else {
                    this(null, null);
                }
            },
            function(err, principal) {
                if (err) {
                    log.error(err);
                    next(err);
                } else {
                    req.principal = principal;
                    res.locals.principal = sanitizedJSON(principal);
                    next();
                }
            }
        );
    });
};

var hasToken = function(req) {
    return (req &&
            (_(req.headers).has("authorization") && req.headers.authorization.match(/oauth_token/)) ||
            (req.query && req.query.oauth_token) ||
            (req.body && req.headers["content-type"] === "application/x-www-form-urlencoded" && req.body.oauth_token));
};

// Accept only 3-legged OAuth
// XXX: It would be nice to merge these two functions

var userAuth = function(req, res, next) {

    var log = req.log,
        areq;

    req.principal = null;
    res.locals.principal = null; // init to null
    req.principalUser = null;
    res.locals.principalUser = null; // init to null
    req.client = null;
    res.locals.client = null; // init to null

    log.debug("Checking for 3-legged OAuth credentials");

    // If we're coming in the front door, and we have a path, provide it
    if (req.header("Host").toLowerCase() === URLMaker.makeHost() && URLMaker.path) {
        areq = wrapRequest(req, URLMaker.path);
    } else {
        areq = req;
    }

    areq.authenticate(["user"], function(error, authenticated) {

        var deetz;

        if (error) {
            log.error(error);
            next(error);
            return;
        }

        if (!authenticated) {
            log.debug("Authentication failed");
            return;
        }

        log.debug("Authentication succeeded");

        deetz = areq.getAuthDetails();

        log.debug(deetz, "Authentication details");

        if (!deetz || !deetz.user || !deetz.user.user || !deetz.user.client) {
            log.debug("Incorrect auth details.");
            next(new Error("Incorrect auth details"));
            return;
        }

        // If email confirmation is required and not yet done, give an error.

        if (req.app.config.requireEmail && !deetz.user.user.email) {
            next(new HTTPError("Can't use the API until you confirm your email address.", 403));
            return;
        }

        req.principalUser = deetz.user.user;
        res.locals.principalUser = sanitizedJSON(req.principalUser);

        req.principal = req.principalUser.profile;
        res.locals.principal = sanitizedJSON(req.principal);

        req.client = deetz.user.client;
        res.locals.client = sanitizedJSON(req.client);

        log.debug({principalUser: req.principalUser.nickname, principal: req.principal, client: req.client.title},
                 "User authorization complete.");

        next();
    });
};

// Accept only 2-legged OAuth with

var remoteUserAuth = function(req, res, next) {
    clientAuth(req, res, function(err) {
        if (err) {
            next(err);
        } else if (!req.principal) {
            next(new HTTPError("Authentication required", 401));
        } else {
            next();
        }
    });
};

var setPrincipal = function(session, obj, callback) {

    if (!_.isObject(obj)) {
        callback(new Error("Can't set principal to non-object"));
        return;
    }

    session.principal = {
        id: obj.id,
        objectType: obj.objectType
    };

    callback(null);
};

var getPrincipal = function(session, callback) {

    if (!session || !_.has(session, "principal")) {
        callback(null, null);
        return;
    }

    var ref = session.principal;

    Step(
        function() {
            ActivityObject.getObject(ref.objectType, ref.id, this);
        },
        callback
    );
};

var clearPrincipal = function(session, callback) {

    if (!session || !_.has(session, "principal")) {
        callback(null);
        return;
    }

    delete session.principal;

    callback(null);
};

var principal = function(req, res, next) {

    req.log.debug({msg: "Checking for principal", session: req.session});

    Step(
        function() {
            getPrincipal(req.session, this);
        },
        function(err, principal) {
            if (err) throw err;
            if (principal) {
                req.log.debug({msg: "Setting session principal", principal: principal});
                req.principal = principal;
                res.locals.principal = sanitizedJSON(req.principal);
                User.fromPerson(principal.id, this);
            } else {
                req.principal = null;
                req.principalUser = null;
                next();
            }
        },
        function(err, user) {
            if (err) {
                next(err);
            } else {
                // XXX: null on miss
                if (user) {
                    req.log.debug({msg: "Setting session principal user", user: user});
                    req.principalUser = user;
                    // Make the profile a "live" object
                    req.principalUser.profile = req.principal;
                    res.locals.principalUser = sanitizedJSON(req.principalUser);
                }
                next();
            }
        }
    );
};

var principalUserOnly = function(req, res, next) {
    if (!_.has(req, "principalUser") || !req.principalUser) {
        next(new HTTPError("Not logged in.", 401));
    } else {
        next();
    }
};

var remoteWriteOAuth = remoteUserAuth;
var noneWriteOAuth = clientAuth;
var userWriteOAuth = userAuth;

var userReadAuth = function(req, res, next) {
    if (hasOAuth(req)) {
        userAuth(req, res, next);
    } else if (req.session) {
        principal(req, res, function(err) {
            if (err) {
                next(err);
            } else {
                principalUserOnly(req, res, next);
            }
        });
    } else {
        next(new HTTPError("Not logged in.", 401));
    }
};

var anyReadAuth = function(req, res, next) {
    if (hasOAuth2(req)) {
        oauth2(req, res, next);
    } else if (hasOAuth(req)) {
        userOrClientAuth(req, res, next);
    } else if (req.session) {
        principal(req, res, function(err) {
            if (err) {
                next(err);
            } else if (!req.principal) {
                next(new HTTPError("Not logged in.", 401));
            } else {
                next();
            }
        });
    } else {
        next(new HTTPError("Not logged in.", 401));
    }
};

var someReadAuth = function(req, res, next) {
    if (hasOAuth(req)) {
        userAuth(req, res, next);
    } else if (req.session) {
        principal(req, res, function(err) {
            if (err) {
                next(err);
            } else if (!req.principal) {
                next(new HTTPError("Not logged in.", 401));
            } else {
                next();
            }
        });
    } else {
        next(new HTTPError("Not logged in.", 401));
    }
};

var oauth2 = function(req, res, next) {
    if (!req.headers) {
        return next(new HTTPError("No headers on this request", 401));
    }
    if (!req.headers.authorization) {
        return next(new HTTPError("No Authorization: header on this request", 401));
    }
    var authz = req.headers.authorization;
    var match = authz.match(/^Bearer (.*)$/);
    if (!match) {
        return next(new HTTPError("Not using Bearer authorization", 401));
    }
    var token = match[1];

    var bt = null;
    var client = null;
    var user = null;

    Step(
        function() {
            BearerToken.get(token, this);
        },
        function(err, results) {
            if (err) throw err;
            bt = results;
            Client.get(bt.client_id, this);
        },
        function(err, results) {
            if (err) throw err;
            client = results;
            if (bt.nickname) {
                User.get(bt.nickname, this);
            } else if (client.webfinger || client.host) {
                client.asActivityObject(this);
            } else {
                this(null, null);
            }
        },
        function(err, results) {
            if (err) return next(err);

            req.client = client;
            res.locals.client = sanitizedJSON(req.client);

            if (bt.nickname) {
                user = results;
                // User bearer token
                req.principalUser = user;
                res.locals.principalUser = sanitizedJSON(req.principalUser);

                req.principal = req.principalUser.profile;
                res.locals.principal = sanitizedJSON(req.principal);
            } else {
                // Client bearer token
                if (results) {
                    // We were able to create an ActivityObject for the client
                    req.principal = results;
                    res.locals.principal = sanitizedJSON(results);
                }
            }

            next();
        }
    );
};

exports.principal = principal;
exports.setPrincipal = setPrincipal;
exports.getPrincipal = getPrincipal;
exports.clearPrincipal = clearPrincipal;
exports.principalUserOnly = principalUserOnly;

exports.userAuth = userAuth;
exports.clientAuth = clientAuth;
exports.userOrClientAuth = userOrClientAuth;
exports.remoteUserAuth = remoteUserAuth;
exports.maybeAuth = maybeAuth;
exports.hasOAuth = hasOAuth;

exports.remoteWriteOAuth = remoteWriteOAuth;
exports.noneWriteOAuth = noneWriteOAuth;
exports.userWriteOAuth = userWriteOAuth;
exports.userReadAuth = userReadAuth;
exports.anyReadAuth = anyReadAuth;
exports.someReadAuth = someReadAuth;

exports.oauth2 = oauth2;
<commit_msg>userReadAuth() includes OAuth 2.0 auth<commit_after>// authc.js
//
// Authentication middleware
//
// Copyright 2011-2013, E14N https://e14n.com/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

"use strict";

var databank = require("databank"),
    Step = require("step"),
    _ = require("lodash"),
    bcrypt = require("bcryptjs"),
    fs = require("fs"),
    path = require("path"),
    os = require("os"),
    randomString = require("./randomstring").randomString,
    Activity = require("./model/activity").Activity,
    ActivityObject = require("./model/activityobject").ActivityObject,
    User = require("./model/user").User,
    Client = require("./model/client").Client,
    HTTPError = require("./httperror").HTTPError,
    URLMaker = require("./urlmaker").URLMaker,
    BearerToken = require("./model/bearertoken").BearerToken,
    NoSuchThingError = databank.NoSuchThingError;

// Remove all properties of an object and its properties if the key starts with _

var sanitizedJSON = function(obj) {
    var clean = {};
    _.each(obj, function(value, key) {
        if (!_.has(obj, key)) {
            return;
        } else if (key[0] === "_") {
            return;
        } else if (_.isObject(value)) { // includes arrays!
            clean[key] = sanitizedJSON(value);
        } else if (!_.isFunction(value)) {
            clean[key] = value;
        }
    });
    return clean;
};

var maybeAuth = function(req, res, next) {
    if (!hasOAuth(req)) {
        // No client, no user
        next();
    } else {
        clientAuth(req, res, next);
    }
};

var hasOAuth = function(req) {
    return (req &&
            _.has(req, "headers") &&
            _.has(req.headers, "authorization") &&
            req.headers.authorization.match(/^OAuth/));
};

var hasOAuth2 = function(req) {
    return (req &&
            _.has(req, "headers") &&
            _.has(req.headers, "authorization") &&
            req.headers.authorization.match(/^Bearer/));
};

var userOrClientAuth = function(req, res, next) {
    if (hasToken(req)) {
        userAuth(req, res, next);
    } else {
        clientAuth(req, res, next);
    }
};

var wrapRequest = function(req, path) {
    var areq = _.clone(req);

    if (path[0] !== "/") {
        path = "/" + path;
    }

    areq.originalUrl = path + req.originalUrl;

    return areq;
};

// Accept either 2-legged or 3-legged OAuth

var clientAuth = function(req, res, next) {

    var log = req.log, areq;

    req.client = null;
    res.locals.client = null; // init to null

    log.debug("Checking for 2-legged OAuth credentials");

    // If we're coming in the front door, and we have a path, provide it
    if (req.header("Host").toLowerCase() === URLMaker.makeHost() && URLMaker.path) {
        areq = wrapRequest(req, URLMaker.path);
    } else {
        areq = req;
    }

    areq.authenticate(["client"], function(error, authenticated) {

        var deetz;

        if (error) {
            log.error(error);
            next(error);
            return;
        }

        if (!authenticated) {
            log.debug("Not authenticated");
            return;
        }

        log.debug("Authentication succeeded");

        deetz = areq.getAuthDetails();

        log.debug(deetz);

        if (!deetz || !deetz.user || !deetz.user.id) {
            log.debug("Incorrect auth details.");
            return;
        }

        Step(
            function() {
                req.app.provider.getClient(deetz.user.id, this);
            },
            function(err, client) {
                if (err) throw err;

                req.client = client;
                res.locals.client = sanitizedJSON(req.client);

                if (client.webfinger || client.host) {
                    client.asActivityObject(this);
                } else {
                    this(null, null);
                }
            },
            function(err, principal) {
                if (err) {
                    log.error(err);
                    next(err);
                } else {
                    req.principal = principal;
                    res.locals.principal = sanitizedJSON(principal);
                    next();
                }
            }
        );
    });
};

var hasToken = function(req) {
    return (req &&
            (_(req.headers).has("authorization") && req.headers.authorization.match(/oauth_token/)) ||
            (req.query && req.query.oauth_token) ||
            (req.body && req.headers["content-type"] === "application/x-www-form-urlencoded" && req.body.oauth_token));
};

// Accept only 3-legged OAuth
// XXX: It would be nice to merge these two functions

var userAuth = function(req, res, next) {

    var log = req.log,
        areq;

    req.principal = null;
    res.locals.principal = null; // init to null
    req.principalUser = null;
    res.locals.principalUser = null; // init to null
    req.client = null;
    res.locals.client = null; // init to null

    log.debug("Checking for 3-legged OAuth credentials");

    // If we're coming in the front door, and we have a path, provide it
    if (req.header("Host").toLowerCase() === URLMaker.makeHost() && URLMaker.path) {
        areq = wrapRequest(req, URLMaker.path);
    } else {
        areq = req;
    }

    areq.authenticate(["user"], function(error, authenticated) {

        var deetz;

        if (error) {
            log.error(error);
            next(error);
            return;
        }

        if (!authenticated) {
            log.debug("Authentication failed");
            return;
        }

        log.debug("Authentication succeeded");

        deetz = areq.getAuthDetails();

        log.debug(deetz, "Authentication details");

        if (!deetz || !deetz.user || !deetz.user.user || !deetz.user.client) {
            log.debug("Incorrect auth details.");
            next(new Error("Incorrect auth details"));
            return;
        }

        // If email confirmation is required and not yet done, give an error.

        if (req.app.config.requireEmail && !deetz.user.user.email) {
            next(new HTTPError("Can't use the API until you confirm your email address.", 403));
            return;
        }

        req.principalUser = deetz.user.user;
        res.locals.principalUser = sanitizedJSON(req.principalUser);

        req.principal = req.principalUser.profile;
        res.locals.principal = sanitizedJSON(req.principal);

        req.client = deetz.user.client;
        res.locals.client = sanitizedJSON(req.client);

        log.debug({principalUser: req.principalUser.nickname, principal: req.principal, client: req.client.title},
                 "User authorization complete.");

        next();
    });
};

// Accept only 2-legged OAuth with

var remoteUserAuth = function(req, res, next) {
    clientAuth(req, res, function(err) {
        if (err) {
            next(err);
        } else if (!req.principal) {
            next(new HTTPError("Authentication required", 401));
        } else {
            next();
        }
    });
};

var setPrincipal = function(session, obj, callback) {

    if (!_.isObject(obj)) {
        callback(new Error("Can't set principal to non-object"));
        return;
    }

    session.principal = {
        id: obj.id,
        objectType: obj.objectType
    };

    callback(null);
};

var getPrincipal = function(session, callback) {

    if (!session || !_.has(session, "principal")) {
        callback(null, null);
        return;
    }

    var ref = session.principal;

    Step(
        function() {
            ActivityObject.getObject(ref.objectType, ref.id, this);
        },
        callback
    );
};

var clearPrincipal = function(session, callback) {

    if (!session || !_.has(session, "principal")) {
        callback(null);
        return;
    }

    delete session.principal;

    callback(null);
};

var principal = function(req, res, next) {

    req.log.debug({msg: "Checking for principal", session: req.session});

    Step(
        function() {
            getPrincipal(req.session, this);
        },
        function(err, principal) {
            if (err) throw err;
            if (principal) {
                req.log.debug({msg: "Setting session principal", principal: principal});
                req.principal = principal;
                res.locals.principal = sanitizedJSON(req.principal);
                User.fromPerson(principal.id, this);
            } else {
                req.principal = null;
                req.principalUser = null;
                next();
            }
        },
        function(err, user) {
            if (err) {
                next(err);
            } else {
                // XXX: null on miss
                if (user) {
                    req.log.debug({msg: "Setting session principal user", user: user});
                    req.principalUser = user;
                    // Make the profile a "live" object
                    req.principalUser.profile = req.principal;
                    res.locals.principalUser = sanitizedJSON(req.principalUser);
                }
                next();
            }
        }
    );
};

var principalUserOnly = function(req, res, next) {
    if (!_.has(req, "principalUser") || !req.principalUser) {
        next(new HTTPError("Not logged in.", 401));
    } else {
        next();
    }
};

var remoteWriteOAuth = remoteUserAuth;
var noneWriteOAuth = clientAuth;
var userWriteOAuth = userAuth;

var userReadAuth = function(req, res, next) {
    if (hasOAuth2(req)) {
        oauth2(req, res, function(err) {
            if (err) {
                next(err);
            } else {
                principalUserOnly(req, res, next);
            }
        });
    } else if (hasOAuth(req)) {
        userAuth(req, res, next);
    } else if (req.session) {
        principal(req, res, function(err) {
            if (err) {
                next(err);
            } else {
                principalUserOnly(req, res, next);
            }
        });
    } else {
        next(new HTTPError("Not logged in.", 401));
    }
};

var anyReadAuth = function(req, res, next) {
    if (hasOAuth2(req)) {
        oauth2(req, res, next);
    } else if (hasOAuth(req)) {
        userOrClientAuth(req, res, next);
    } else if (req.session) {
        principal(req, res, function(err) {
            if (err) {
                next(err);
            } else if (!req.principal) {
                next(new HTTPError("Not logged in.", 401));
            } else {
                next();
            }
        });
    } else {
        next(new HTTPError("Not logged in.", 401));
    }
};

var someReadAuth = function(req, res, next) {
    if (hasOAuth(req)) {
        userAuth(req, res, next);
    } else if (req.session) {
        principal(req, res, function(err) {
            if (err) {
                next(err);
            } else if (!req.principal) {
                next(new HTTPError("Not logged in.", 401));
            } else {
                next();
            }
        });
    } else {
        next(new HTTPError("Not logged in.", 401));
    }
};

var oauth2 = function(req, res, next) {
    if (!req.headers) {
        return next(new HTTPError("No headers on this request", 401));
    }
    if (!req.headers.authorization) {
        return next(new HTTPError("No Authorization: header on this request", 401));
    }
    var authz = req.headers.authorization;
    var match = authz.match(/^Bearer (.*)$/);
    if (!match) {
        return next(new HTTPError("Not using Bearer authorization", 401));
    }
    var token = match[1];

    var bt = null;
    var client = null;
    var user = null;

    Step(
        function() {
            BearerToken.get(token, this);
        },
        function(err, results) {
            if (err) throw err;
            bt = results;
            Client.get(bt.client_id, this);
        },
        function(err, results) {
            if (err) throw err;
            client = results;
            if (bt.nickname) {
                User.get(bt.nickname, this);
            } else if (client.webfinger || client.host) {
                client.asActivityObject(this);
            } else {
                this(null, null);
            }
        },
        function(err, results) {
            if (err) return next(err);

            req.client = client;
            res.locals.client = sanitizedJSON(req.client);

            if (bt.nickname) {
                // User bearer token
                user = results;
                req.principalUser = user;
                res.locals.principalUser = sanitizedJSON(req.principalUser);

                req.principal = req.principalUser.profile;
                res.locals.principal = sanitizedJSON(req.principal);
            } else {
                // Client bearer token
                if (results) {
                    // We were able to create an ActivityObject for the client
                    req.principal = results;
                    res.locals.principal = sanitizedJSON(results);
                }
            }

            next();
        }
    );
};

exports.principal = principal;
exports.setPrincipal = setPrincipal;
exports.getPrincipal = getPrincipal;
exports.clearPrincipal = clearPrincipal;
exports.principalUserOnly = principalUserOnly;

exports.userAuth = userAuth;
exports.clientAuth = clientAuth;
exports.userOrClientAuth = userOrClientAuth;
exports.remoteUserAuth = remoteUserAuth;
exports.maybeAuth = maybeAuth;
exports.hasOAuth = hasOAuth;

exports.remoteWriteOAuth = remoteWriteOAuth;
exports.noneWriteOAuth = noneWriteOAuth;
exports.userWriteOAuth = userWriteOAuth;
exports.userReadAuth = userReadAuth;
exports.anyReadAuth = anyReadAuth;
exports.someReadAuth = someReadAuth;

exports.oauth2 = oauth2;
<|endoftext|>


<commit_before>/*global require: false, module: false */
'use strict';

var _ = require('underscore');

var jStat = require('jStat').jStat,
	linearAlgebra = require('linear-algebra')(),
	Matrix = linearAlgebra.Matrix;

var reduce = _.reduce,
	map = _.map,
	groupBy = _.groupBy,
	sortBy = _.sortBy,
	last = _.last,
	uniq = _.uniq,
	pluck = _.pluck,
	filter = _.filter;

function pluckTte(x) {
	return pluck(x, 'tte');
}

// kaplan-meier
// See http://en.wikipedia.org/wiki/Kaplan%E2%80%93Meier_estimator
//
// tte  time to exit (event or censor)
// ev   is truthy if there is an event.
function compute(tte, ev) {
	var exits = sortBy(map(tte, function (x, i) { return { tte: x, ev: ev[i] }; }), 'tte'), // sort and collate
		uexits = uniq(pluckTte(exits), true),                    // unique tte
		gexits = groupBy(exits, function (x) { return x.tte; }),  // group by common time of exit
		dini = reduce(uexits, function (a, tte) {                 // compute d_i, n_i for times t_i (including censor times)
			var group = gexits[tte],
			l = last(a) || {n: exits.length, e: 0},
			events = filter(group, function (x) { return x.ev; });

			a.push({
				n: l.n - l.e,     // at risk
				e: group.length,  // number exiting
				d: events.length, // number events (death)
				t: group[0].tte   // time
			});
			return a;
		}, []),

		// s : the survival probability from t=0 to the particular time (i.e. the end of the time interval)
		// rate : the chance of an event happened within the time interval (as in t and the previous t with an event)
		si = reduce(dini, function (a, dn) { // survival at each t_i (including censor times)
			var l = last(a) || { s: 1 };
			if (dn.d) {                      // there were events at this t_i
				a.push({t: dn.t, e: true, s: l.s * (1 - dn.d / dn.n), n: dn.n, d: dn.d, rate: dn.d / dn.n});
			} else {                          // only censors
				a.push({t: dn.t, e: false, s: l.s, n: dn.n, d: dn.d, rate: null});
			}
			return a;
		}, []);

	return si;
}

//log-rank test of the difference between KM plots

// http://www.ncbi.nlm.nih.gov/pmc/articles/PMC3059453/
// a good article to understand KM and comparing KM plots using log-rank test,
// they used the pearson chisquared test to compute test statistics
// sum of (O-E)^2/E

// http://oto.sagepub.com/content/143/3/331.long
// a good article to understand KM and comparing KM plots using log-rank test and hazardous ratio test
// they also used the pearson chisquared test to compute test statistics

// http://www.ncbi.nlm.nih.gov/pmc/articles/PMC403858/
// introduce pearson chi-square to compute logrank statistics, however mentioned there is another way

// http://ssp.unl.edu/Log%20Rank%20Test%20For%20More%20Than%202%20Groups.pdf
// gives basic idea of the "other" way R seems to use the "other" way
// (O-E)^2/V V is variance for two groups and covariance for multiple groups

// https://cran.r-project.org/web/packages/survival/survival.pdf
// R use (O-E)^2/V V is variance for two groups and covariance for multiple groups

//https://github.com/CamDavidsonPilon/lifelines/blob/master/lifelines/statistics.py
//python implementation, identical results to R

// covariance calculation
// https://books.google.com/books?id=nPkjIEVY-CsC&pg=PA451&lpg=PA451&dq=multivariate+hypergeometric+distribution+covariance&source=bl&ots=yoieGfA4bu&sig=dhRcSYKcYiqLXBPZWOaqzciViMs&hl=en&sa=X&ved=0CEQQ6AEwBmoVChMIkqbU09SuyAIVgimICh0J3w1x#v=onepage&q=multivariate%20hypergeometric%20distribution%20covariance&f=false

//https://plot.ly/ipython-notebooks/survival-analysis-r-vs-python/#Using-R
// R online tutorial

// chisquare distribution at
// https://github.com/jstat/jstat/blob/master/src/distribution.js
// testing jStat accuracy: http://www.socscistatistics.com/pvalues/chidistribution.aspx

// p value = 1- jStat.chisquare.cdf(x, dof );  -- x is chisquare statistics, dof is degree of freedom
// for comparing two plots, the dof is n-1 = 1, comparing three plots dof = n-1 = 2

// given a theoretical survival curve (si), and tte + ev ( tte and ev is the data ),
// compute the expected total number of events
// report observed n events, expected n events. pearson's chi-square component (O-E)^2/E

function expectedObservedEventNumber(si, tte, ev) {
	var exits = sortBy(map(tte, (x, i) => ({tte: x, ev: ev[i]})), 'tte'), // sort and collate
		uexits = uniq(pluckTte(exits), true),                    // unique tte
		gexits = groupBy(exits, x => x.tte),  // group by common time of exit
		data = reduce(uexits, function (a, tte) {                 // sorted by time stats from the input data as in tte,ev
			var group = gexits[tte],
			l = last(a) || {n: exits.length, e: 0},
			events = filter(group, x => x.ev);

			a.push({
				n: l.n - l.e,     // at risk
				e: group.length,  // number exiting
				d: events.length, // number events (death)
				t: group[0].tte   // time
			});
			return a;
		}, []),
		expectedNumber,
		observedNumber,
		dataByTimeTable = [];

	si = si.filter(function(item) {  //only keep the curve where there is an event
		if (item.e) {return true; }
		else {return false; }
	});

	expectedNumber = reduce(si, function (memo, item) {
		var pointerInData = _.find(data, function (x) {
			if (x.t === item.t) {
				return true;
			}
			if (x.t > item.t) {
				return true;
			}
			return false;
		});

		if (pointerInData) {
			var expected = pointerInData.n * item.rate;
			dataByTimeTable.push(pointerInData);
			return memo + expected;
		}
		else {
			return memo;
		}

	}, 0);

	observedNumber = filter(ev, x => x).length;

	return {
		expected: expectedNumber,
		observed: observedNumber,
		dataByTimeTable: dataByTimeTable,
		timeNumber: dataByTimeTable.length
	};
}

function logranktest (allGroupsRes, groupedDataTable) {
	var KMStats,
		pValue,
		dof, // degree of freedom
		i, j, //groups
		t, //timeIndex
		OETable = [],
		OMinusEVector = [], OMinusEVectorMinus1,// O-E and O-E drop the last element
		vv = [], vvMinus1, //covariant matrix and covraiance matrix drops the last row and column
		N, //total number of samples
		Ki, Kj, // at risk number from each group
		n; //total observed

	_.each(groupedDataTable, function(group) {
		var r = expectedObservedEventNumber(allGroupsRes, group.tte, group.ev);
		//console.log(group.name, group.tte.length, r.observed, r.expected,

		if (r.expected) {
			OETable.push(r);
			OMinusEVector.push(r.observed - r.expected);
		}
	});

	dof = OETable.length - 1;

	// logrank stats covariance matrix vv
	for (i = 0; i < OETable.length; i++) {
		vv.push([]);
		for (j = 0; j < OETable.length; j++) {
			vv[i].push(0);
		}
	}

	for (i = 0; i < OETable.length; i++) {
		for (j = i; j < OETable.length; j++) {
			for (t = 0; t < allGroupsRes.length; t++) {
				N = allGroupsRes[t].n;
				n = allGroupsRes[t].d;
				if (t < OETable[i].timeNumber && t < OETable[j].timeNumber) {
					Ki = OETable[i].dataByTimeTable[t].n;
					Kj = OETable[j].dataByTimeTable[t].n;
					// https://books.google.com/books?id=nPkjIEVY-CsC&pg=PA451&lpg=PA451&dq=multivariate+hypergeometric+distribution+covariance&source=bl&ots=yoieGfA4bu&sig=dhRcSYKcYiqLXBPZWOaqzciViMs&hl=en&sa=X&ved=0CEQQ6AEwBmoVChMIkqbU09SuyAIVgimICh0J3w1x#v=onepage&q=multivariate%20hypergeometric%20distribution%20covariance&f=false
					// when N==1: only 1 subject, no variance
					if (i !== j && N !== 1){
						vv[i][j] -= n * Ki * Kj * (N - n) / (N * N * (N - 1));
						vv[j][i] = vv[i][j];
					}
					else {//i==j
						if (N !== 1) {
							vv[i][i] += n * Ki * (N - Ki) * (N - n) / (N * N * (N - 1));
						}
					}
				}
			}
		}
	}

	OMinusEVectorMinus1 = OMinusEVector.slice(0, OMinusEVector.length - 1);
	vvMinus1 = vv.slice(0, vv.length - 1);
	for (i = 0; i < vvMinus1.length; i++) {
		vvMinus1[i] = vvMinus1[i].slice(0, vvMinus1[i].length - 1);
	}
	var vvMinus1Copy = vvMinus1.slice(0, vvMinus1.length);
	for(i = 0; i < vvMinus1.length; i++) {
		vvMinus1Copy[i] = vvMinus1[i].slice(0, vvMinus1[i].length);
	}

	if (dof > 0) {
		var m = new Matrix([OMinusEVectorMinus1]),
			mT = new Matrix([OMinusEVectorMinus1]).trans(),
				vvMinus1Inv = new Matrix(jStat.inv(vvMinus1Copy)),
				mfinal = m.dot(vvMinus1Inv).dot(mT);

		KMStats = mfinal.data[0][0];

		pValue = 1 - jStat.chisquare.cdf(KMStats, dof);
	}

	return {
		dof: dof,
		KMStats: KMStats,
		pValue: pValue
	};
}

module.exports = {
	compute: compute,
	expectedObservedEventNumber: expectedObservedEventNumber,
	logranktest: logranktest
};
<commit_msg>Handle p = 1.<commit_after>/*global require: false, module: false */
'use strict';

var _ = require('underscore');

var jStat = require('jStat').jStat,
	linearAlgebra = require('linear-algebra')(),
	Matrix = linearAlgebra.Matrix;

var reduce = _.reduce,
	map = _.map,
	groupBy = _.groupBy,
	sortBy = _.sortBy,
	last = _.last,
	uniq = _.uniq,
	pluck = _.pluck,
	filter = _.filter;

function pluckTte(x) {
	return pluck(x, 'tte');
}

// kaplan-meier
// See http://en.wikipedia.org/wiki/Kaplan%E2%80%93Meier_estimator
//
// tte  time to exit (event or censor)
// ev   is truthy if there is an event.
function compute(tte, ev) {
	var exits = sortBy(map(tte, function (x, i) { return { tte: x, ev: ev[i] }; }), 'tte'), // sort and collate
		uexits = uniq(pluckTte(exits), true),                    // unique tte
		gexits = groupBy(exits, function (x) { return x.tte; }),  // group by common time of exit
		dini = reduce(uexits, function (a, tte) {                 // compute d_i, n_i for times t_i (including censor times)
			var group = gexits[tte],
			l = last(a) || {n: exits.length, e: 0},
			events = filter(group, function (x) { return x.ev; });

			a.push({
				n: l.n - l.e,     // at risk
				e: group.length,  // number exiting
				d: events.length, // number events (death)
				t: group[0].tte   // time
			});
			return a;
		}, []),

		// s : the survival probability from t=0 to the particular time (i.e. the end of the time interval)
		// rate : the chance of an event happened within the time interval (as in t and the previous t with an event)
		si = reduce(dini, function (a, dn) { // survival at each t_i (including censor times)
			var l = last(a) || { s: 1 };
			if (dn.d) {                      // there were events at this t_i
				a.push({t: dn.t, e: true, s: l.s * (1 - dn.d / dn.n), n: dn.n, d: dn.d, rate: dn.d / dn.n});
			} else {                          // only censors
				a.push({t: dn.t, e: false, s: l.s, n: dn.n, d: dn.d, rate: null});
			}
			return a;
		}, []);

	return si;
}

//log-rank test of the difference between KM plots

// http://www.ncbi.nlm.nih.gov/pmc/articles/PMC3059453/
// a good article to understand KM and comparing KM plots using log-rank test,
// they used the pearson chisquared test to compute test statistics
// sum of (O-E)^2/E

// http://oto.sagepub.com/content/143/3/331.long
// a good article to understand KM and comparing KM plots using log-rank test and hazardous ratio test
// they also used the pearson chisquared test to compute test statistics

// http://www.ncbi.nlm.nih.gov/pmc/articles/PMC403858/
// introduce pearson chi-square to compute logrank statistics, however mentioned there is another way

// http://ssp.unl.edu/Log%20Rank%20Test%20For%20More%20Than%202%20Groups.pdf
// gives basic idea of the "other" way R seems to use the "other" way
// (O-E)^2/V V is variance for two groups and covariance for multiple groups

// https://cran.r-project.org/web/packages/survival/survival.pdf
// R use (O-E)^2/V V is variance for two groups and covariance for multiple groups

//https://github.com/CamDavidsonPilon/lifelines/blob/master/lifelines/statistics.py
//python implementation, identical results to R

// covariance calculation
// https://books.google.com/books?id=nPkjIEVY-CsC&pg=PA451&lpg=PA451&dq=multivariate+hypergeometric+distribution+covariance&source=bl&ots=yoieGfA4bu&sig=dhRcSYKcYiqLXBPZWOaqzciViMs&hl=en&sa=X&ved=0CEQQ6AEwBmoVChMIkqbU09SuyAIVgimICh0J3w1x#v=onepage&q=multivariate%20hypergeometric%20distribution%20covariance&f=false

//https://plot.ly/ipython-notebooks/survival-analysis-r-vs-python/#Using-R
// R online tutorial

// chisquare distribution at
// https://github.com/jstat/jstat/blob/master/src/distribution.js
// testing jStat accuracy: http://www.socscistatistics.com/pvalues/chidistribution.aspx

// p value = 1- jStat.chisquare.cdf(x, dof );  -- x is chisquare statistics, dof is degree of freedom
// for comparing two plots, the dof is n-1 = 1, comparing three plots dof = n-1 = 2

// given a theoretical survival curve (si), and tte + ev ( tte and ev is the data ),
// compute the expected total number of events
// report observed n events, expected n events. pearson's chi-square component (O-E)^2/E

function expectedObservedEventNumber(si, tte, ev) {
	var exits = sortBy(map(tte, (x, i) => ({tte: x, ev: ev[i]})), 'tte'), // sort and collate
		uexits = uniq(pluckTte(exits), true),                    // unique tte
		gexits = groupBy(exits, x => x.tte),  // group by common time of exit
		data = reduce(uexits, function (a, tte) {                 // sorted by time stats from the input data as in tte,ev
			var group = gexits[tte],
			l = last(a) || {n: exits.length, e: 0},
			events = filter(group, x => x.ev);

			a.push({
				n: l.n - l.e,     // at risk
				e: group.length,  // number exiting
				d: events.length, // number events (death)
				t: group[0].tte   // time
			});
			return a;
		}, []),
		expectedNumber,
		observedNumber,
		dataByTimeTable = [];

	si = si.filter(function(item) {  //only keep the curve where there is an event
		if (item.e) {return true; }
		else {return false; }
	});

	expectedNumber = reduce(si, function (memo, item) {
		var pointerInData = _.find(data, function (x) {
			if (x.t === item.t) {
				return true;
			}
			if (x.t > item.t) {
				return true;
			}
			return false;
		});

		if (pointerInData) {
			var expected = pointerInData.n * item.rate;
			dataByTimeTable.push(pointerInData);
			return memo + expected;
		}
		else {
			return memo;
		}

	}, 0);

	observedNumber = filter(ev, x => x).length;

	return {
		expected: expectedNumber,
		observed: observedNumber,
		dataByTimeTable: dataByTimeTable,
		timeNumber: dataByTimeTable.length
	};
}

function logranktest (allGroupsRes, groupedDataTable) {
	var KMStats,
		pValue,
		dof, // degree of freedom
		i, j, //groups
		t, //timeIndex
		OETable = [],
		OMinusEVector = [], OMinusEVectorMinus1,// O-E and O-E drop the last element
		vv = [], vvMinus1, //covariant matrix and covraiance matrix drops the last row and column
		N, //total number of samples
		Ki, Kj, // at risk number from each group
		n; //total observed

	_.each(groupedDataTable, function(group) {
		var r = expectedObservedEventNumber(allGroupsRes, group.tte, group.ev);
		//console.log(group.name, group.tte.length, r.observed, r.expected,

		if (r.expected) {
			OETable.push(r);
			OMinusEVector.push(r.observed - r.expected);
		}
	});

	dof = OETable.length - 1;

	// logrank stats covariance matrix vv
	for (i = 0; i < OETable.length; i++) {
		vv.push([]);
		for (j = 0; j < OETable.length; j++) {
			vv[i].push(0);
		}
	}

	for (i = 0; i < OETable.length; i++) {
		for (j = i; j < OETable.length; j++) {
			for (t = 0; t < allGroupsRes.length; t++) {
				N = allGroupsRes[t].n;
				n = allGroupsRes[t].d;
				if (t < OETable[i].timeNumber && t < OETable[j].timeNumber) {
					Ki = OETable[i].dataByTimeTable[t].n;
					Kj = OETable[j].dataByTimeTable[t].n;
					// https://books.google.com/books?id=nPkjIEVY-CsC&pg=PA451&lpg=PA451&dq=multivariate+hypergeometric+distribution+covariance&source=bl&ots=yoieGfA4bu&sig=dhRcSYKcYiqLXBPZWOaqzciViMs&hl=en&sa=X&ved=0CEQQ6AEwBmoVChMIkqbU09SuyAIVgimICh0J3w1x#v=onepage&q=multivariate%20hypergeometric%20distribution%20covariance&f=false
					// when N==1: only 1 subject, no variance
					if (i !== j && N !== 1){
						vv[i][j] -= n * Ki * Kj * (N - n) / (N * N * (N - 1));
						vv[j][i] = vv[i][j];
					}
					else {//i==j
						if (N !== 1) {
							vv[i][i] += n * Ki * (N - Ki) * (N - n) / (N * N * (N - 1));
						}
					}
				}
			}
		}
	}

	OMinusEVectorMinus1 = OMinusEVector.slice(0, OMinusEVector.length - 1);
	vvMinus1 = vv.slice(0, vv.length - 1);
	for (i = 0; i < vvMinus1.length; i++) {
		vvMinus1[i] = vvMinus1[i].slice(0, vvMinus1[i].length - 1);
	}
	var vvMinus1Copy = vvMinus1.slice(0, vvMinus1.length);
	for(i = 0; i < vvMinus1.length; i++) {
		vvMinus1Copy[i] = vvMinus1[i].slice(0, vvMinus1[i].length);
	}

	var chi = 0;
	if (dof > 0) {
		var m = new Matrix([OMinusEVectorMinus1]),
			mT = new Matrix([OMinusEVectorMinus1]).trans(),
				vvMinus1Inv = new Matrix(jStat.inv(vvMinus1Copy)),
				mfinal = m.dot(vvMinus1Inv).dot(mT);

		KMStats = mfinal.data[0][0];

		chi = jStat.chisquare.cdf(KMStats, dof);
	}

	pValue = 1 - chi;
	return {
		dof: dof,
		KMStats: KMStats,
		pValue: pValue
	};
}

module.exports = {
	compute: compute,
	expectedObservedEventNumber: expectedObservedEventNumber,
	logranktest: logranktest
};
<|endoftext|>


<commit_before>$(document).ready(function() {
    //Ramasamy
    if ($('#report-login').find('input[type="text"]').length > 0) {
        $('#report-login').find('input[type="text"]').focus();
    }

    $(".datepicker").datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat: 'yy-mm-dd',
        maxDate: new Date()
    });

    var url = "";
    url = $('#agent-name-autocomplete').attr('url');
    $('#agent-name-autocomplete').autocomplete(url, {
        delay: 10,
        minChars: 1,
        matchSubset: 1,
        matchContains: 1,
        cacheLength: 10,
        autoFill: true,
        selectFirst: true

    });

    var new_url = "";
    new_url = $('#new-agent-name-autocomplete').attr('new_url');
    $('#new-agent-name-autocomplete').autocomplete(new_url, {
        delay: 10,
        minChars: 1,
        matchSubset: 1,
        matchContains: 1,
        cacheLength: 10,
        autoFill: true,
        selectFirst: true

    });

    $('.mailbox').live('click', function() {
        if ($(this).is(':checked')) {
            $('.show-fields').show();
        } else {
            $('.show-fields').hide();
        }
    });

    $('.delete-extension').live('click', function() {
        var delete_id = $(this).attr('deleteid');
        var confirmationvalues = confirm("Are you sure you want to delete this Extension " + delete_id + " ? Click Yes to continue or No to cancel");
        if (confirmationvalues == true) {
            if (delete_id != '') {
                $(this).parents('tr').remove();
                var post_data = {delete_id: delete_id};
                $.ajax({
                    type: 'POST',
                    url: baseUrl + "index.php/pbx_admin/deleteExtension",
                    data: post_data,
                    success: function(data) {
                        console.log(data);
                    }
                });
            }
        }
    });

    //rakesh

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

        if ($('#searchable').val() == "null")
        {
            alert("you must select any queue");
            return false;
        }
        else {
            vall = $('#searchable').val();
            var agent = $('#agentname').val();

            var dataString = 'team=' + vall + '&q=' + agent;
            $.ajax({
                type: "POST",
                url: baseUrl + "index.php/login/queue_login",
                data: dataString,
                success: function(response) {
                    window.location.href = baseUrl + "index.php/login/agentmaincontrol";
                    //alert(response);
                    /*
                     if(($.trim(response) != "success")){
                     //alert("Select any queue");
                     window.location.href = "index(test).php?queue="+vall;
                     }
                     else{
                     window.location.href = "index(test).php?queue="+vall+"&campaign=in";
                     }
                     */
                }

            });
        }
    });

    $('#searchable').multiselect2side({
        search: "Search: "
    });
    $('#first').multiselect2side({
        optGroupSearch: "Group: ",
        search: ""
    });
    $('#second').multiselect2side({
        selectedPosition: 'right',
        moveOptions: false,
        labelsx: '',
        labeldx: '',
        autoSort: true,
        autoSortAvailable: true
    });
    $('#third').multiselect2side({
        selectedPosition: 'left',
        moveOptions: true,
        labelTop: '+ +',
        labelBottom: '- -',
        labelUp: '+',
        labelDown: '-',
        labelsx: '* Selected *',
        labeldx: '* Available *',
        search: "Find: "
    });
    $('#fourth').multiselect2side({maxSelected: 4});

    $('.clickToView2').click(function() {
        $(this).parent().prevAll("select:first").toggle();
        return false;
    });

    $('.clickToView').click(function() {
        elClick = $(this);
        selEl = elClick.prevAll("select:first");
//alert(elClick);
        $.ajax({
            url: 'jmultiselect2side.php',
            data: selEl.serialize() + '&SELECTNAME=' + selEl.attr("name"),
            success: function(data) {
                elClick.next().next().next().html(data);
            }
        });
        return false;
    });

    $('#fourth')
            .multiselect2side('addOption', {name: 'test selected', value: 'test1', selected: true})
            .multiselect2side('addOption', {name: 'test not selected', value: 'test2', selected: false});
    $('#third')
            .multiselect2side('addOption', {name: 'test selected', value: 'test1', selected: true})
            .multiselect2side('addOption', {name: 'test not selected', value: 'test2', selected: false});

    $("#pause").click(function() {
        alert('puase');
        var usr = $('#agent').val();
        var dataString = 'agent=' + usr + '&flag=f3';
        $.ajax({
            type: "POST",
            url: baseUrl + "index.php/login/agentpause",
            data: dataString,
            success: function(response) {
                //$('#pause').style.background='gray';
                $("#pause").css("background-color", "gray");
            }
        });

    });

    $("#unpause").click(function() {
        alert('unpause');
        var usr = $('#agent').val();
        var dataString = 'agent=' + usr + '&flag=f4';
        $.ajax({
            type: "POST",
            url: baseUrl + "index.php/login/agentpause",
            data: dataString,
            success: function(response) {
                $("#pause").css("background-color", "#F15A29");
            }
        });

    });
//call popup div

    //Arulprakash
    $("#followmedst").change(function() {
        var dst = $(this).val();
        //  alert(dst);

        var dataString = 'dst=' + dst;
        $.ajax({
            type: "POST",
            //	 dataType: "html",
            url: baseUrl + "index.php/pbx_admin/depended_value",
            data: dataString,
            success: function(response) {
                alert(response);
                //$('#destination').html(response);
            }
        });
    });

});

//ajax popup div
function openpopup(id) {
    popup1.style.visibility = "visible";
//Calculate Page width and height
    var pageWidth = window.innerWidth;
    var pageHeight = window.innerHeight;
    if (typeof pageWidth != "number") {
        if (document.compatMode == "CSS1Compat") {
            pageWidth = document.documentElement.clientWidth;
            pageHeight = document.documentElement.clientHeight;
        } else {
            pageWidth = document.body.clientWidth;
            pageHeight = document.body.clientHeight;
        }
    }
//Make the background div tag visible...
    var divbg = document.getElementById('bg');
    divbg.style.visibility = "visible";

    var divobj = document.getElementById(id);
    divobj.style.visibility = "visible";
//divobj.style.left="330px !important";
//divobj.style.top="25px !important";
    if (navigator.appName == "Microsoft Internet Explorer")
        computedStyle = divobj.currentStyle;
    else
        computedStyle = document.defaultView.getComputedStyle(divobj, null);
//Get Div width and height from StyleSheet
    var divWidth = computedStyle.width.replace('px', '');
    var divHeight = computedStyle.height.replace('px', '');
    var divLeft = (pageWidth - divWidth) / 2;
    var divTop = (pageHeight - divHeight) / 2;
//Set Left and top coordinates for the div tag
    divobj.style.left = (divLeft + 130) + "px";
    divobj.style.top = (divTop + 20) + "px";
//console.log(divLeft);
//console.log(divTop);
//Put a Close button for closing the popped up Div tag
    if (divobj.innerHTML.indexOf("closepopup('" + id + "')") < 0)
        divobj.innerHTML = "X" + divobj.innerHTML;
    //var t=setTimeout(function(){ popup1.style.visibility = "hidden";
    //bg.style.visibility = "hidden";},7000);
    // setTimeout();
    //iframerefresh();
}
function closepopup(id) {
    var divbg = document.getElementById('bg');
    divbg.style.visibility = "hidden";
    var divobj = document.getElementById(id);
    divobj.style.visibility = "hidden";
}

$(function() {
    cometpopup();
});

function cometpopup() {

    var agentnumber = $('#agent').val();
    $.ajax({
        type: 'Get',
        url: baseUrl + "index.php/login/popup",
        async: true,
        success: function(data) {
            var json = eval('(' + data + ')');
            console.log(json);
            var phon = json.phone;

            console.log(phon);
            if (phon != '')
            {
                var ccc = json.check;

                if (ccc == "done")
                {
                    alert("you hv tht number");
                    $('#popup1').html("user data is there in database");
                    openpopup('popup1');
                    var t = setTimeout(function() {
                        popup1.style.visibility = "hidden";
                        bg.style.visibility = "hidden";
                    }, 7000);

                }
                else
                {
                    alert("no such tht number");
                    $('#popup1').html("No data found");
                    openpopup('popup1');
                    var t = setTimeout(function() {
                        popup1.style.visibility = "hidden";
                        bg.style.visibility = "hidden";
                    }, 7000);

                }

            }
            else
            {

            }
            setTimeout('cometpopup()', 1000000);
        },
        error: function(XMLHttpRequest, textstatus, error) {
            //alert(error);
            $('#send').html('ERROR');
            setTimeout('cometpopup()', 1000);

        }

    });
}

<commit_msg>helper.js<commit_after>$(document).ready(function() {
    //Ramasamy
    if ($('#report-login').find('input[type="text"]').length > 0) {
        $('#report-login').find('input[type="text"]').focus();
    }

    $(".datepicker").datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat: 'yy-mm-dd',
        maxDate: new Date()
    });

    var url = "";
    url = $('#agent-name-autocomplete').attr('url');
    $('#agent-name-autocomplete').autocomplete(url, {
        delay: 10,
        minChars: 1,
        matchSubset: 1,
        matchContains: 1,
        cacheLength: 10,
        autoFill: true,
        selectFirst: true

    });

    var new_url = "";
    new_url = $('#new-agent-name-autocomplete').attr('new_url');
    $('#new-agent-name-autocomplete').autocomplete(new_url, {
        delay: 10,
        minChars: 1,
        matchSubset: 1,
        matchContains: 1,
        cacheLength: 10,
        autoFill: true,
        selectFirst: true

    });

    $('.mailbox').live('click', function() {
        if ($(this).is(':checked')) {
            $('.show-fields').show();
        } else {
            $('.show-fields').hide();
        }
    });

    $('.delete-extension').live('click', function() {
        var delete_id = $(this).attr('deleteid');
        var confirmationvalues = confirm("Are you sure you want to delete this Extension " + delete_id + " ? Click Yes to continue or No to cancel");
        if (confirmationvalues == true) {
            if (delete_id != '') {
                $(this).parents('tr').remove();
                var post_data = {delete_id: delete_id};
                $.ajax({
                    type: 'POST',
                    url: baseUrl + "index.php/pbx_admin/deleteExtension",
                    data: post_data,
                    success: function(data) {
                        console.log(data);
                    }
                });
            }
        }
    });

    //rakesh

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

        if ($('#searchable').val() == "null")
        {
            alert("you must select any queue");
            return false;
        }
        else {
            vall = $('#searchable').val();
            var agent = $('#agentname').val();

            var dataString = 'team=' + vall + '&q=' + agent;
            $.ajax({
                type: "POST",
                url: baseUrl + "index.php/login/queue_login",
                data: dataString,
                success: function(response) {
                    window.location.href = baseUrl + "index.php/login/agentmaincontrol";
                    //alert(response);
                    /*
                     if(($.trim(response) != "success")){
                     //alert("Select any queue");
                     window.location.href = "index(test).php?queue="+vall;
                     }
                     else{
                     window.location.href = "index(test).php?queue="+vall+"&campaign=in";
                     }
                     */
                }

            });
        }
    });

    $('#searchable').multiselect2side({
        search: "Search: "
    });
    $('#first').multiselect2side({
        optGroupSearch: "Group: ",
        search: ""
    });
    $('#second').multiselect2side({
        selectedPosition: 'right',
        moveOptions: false,
        labelsx: '',
        labeldx: '',
        autoSort: true,
        autoSortAvailable: true
    });
    $('#third').multiselect2side({
        selectedPosition: 'left',
        moveOptions: true,
        labelTop: '+ +',
        labelBottom: '- -',
        labelUp: '+',
        labelDown: '-',
        labelsx: '* Selected *',
        labeldx: '* Available *',
        search: "Find: "
    });
    $('#fourth').multiselect2side({maxSelected: 4});

    $('.clickToView2').click(function() {
        $(this).parent().prevAll("select:first").toggle();
        return false;
    });

    $('.clickToView').click(function() {
        elClick = $(this);
        selEl = elClick.prevAll("select:first");
//alert(elClick);
        $.ajax({
            url: 'jmultiselect2side.php',
            data: selEl.serialize() + '&SELECTNAME=' + selEl.attr("name"),
            success: function(data) {
                elClick.next().next().next().html(data);
            }
        });
        return false;
    });

    $('#fourth')
            .multiselect2side('addOption', {name: 'test selected', value: 'test1', selected: true})
            .multiselect2side('addOption', {name: 'test not selected', value: 'test2', selected: false});
    $('#third')
            .multiselect2side('addOption', {name: 'test selected', value: 'test1', selected: true})
            .multiselect2side('addOption', {name: 'test not selected', value: 'test2', selected: false});

    $("#pause").click(function() {
        alert('puase');
        var usr = $('#agent').val();
        var dataString = 'agent=' + usr + '&flag=f3';
        $.ajax({
            type: "POST",
            url: baseUrl + "index.php/login/agentpause",
            data: dataString,
            success: function(response) {
                //$('#pause').style.background='gray';
                $("#pause").css("background-color", "gray");
            }
        });

    });

    $("#unpause").click(function() {
        alert('unpause');
        var usr = $('#agent').val();
        var dataString = 'agent=' + usr + '&flag=f4';
        $.ajax({
            type: "POST",
            url: baseUrl + "index.php/login/agentpause",
            data: dataString,
            success: function(response) {
                $("#pause").css("background-color", "#F15A29");
            }
        });

    });
//call popup div

    //Arulprakash
<<<<<<< Updated upstream
    $("#followmedst").change(function() {
        var dst = $(this).val();
        //  alert(dst);

        var dataString = 'dst=' + dst;
        $.ajax({
            type: "POST",
            //	 dataType: "html",
            url: baseUrl + "index.php/pbx_admin/depended_value",
            data: dataString,
            success: function(response) {
                alert(response);
                //$('#destination').html(response);
=======
        $("#followmedst").change(function () {
	    var dst=$(this).val();

	 var dataString = 'dst='+ dst;
	  $.ajax({
         type: "POST",
	//	 dataType: "html",
		 url: baseUrl+"index.php/pbx_admin/depended_value",
		 data: dataString,
		 success: function(response){
		//	var result = eval('(' + response + ')');
			 alert(response);
			//$('#destination').html(response);
>>>>>>> Stashed changes
            }
        });
    });

});

//ajax popup div
function openpopup(id) {
    popup1.style.visibility = "visible";
//Calculate Page width and height
    var pageWidth = window.innerWidth;
    var pageHeight = window.innerHeight;
    if (typeof pageWidth != "number") {
        if (document.compatMode == "CSS1Compat") {
            pageWidth = document.documentElement.clientWidth;
            pageHeight = document.documentElement.clientHeight;
        } else {
            pageWidth = document.body.clientWidth;
            pageHeight = document.body.clientHeight;
        }
    }
//Make the background div tag visible...
    var divbg = document.getElementById('bg');
    divbg.style.visibility = "visible";

    var divobj = document.getElementById(id);
    divobj.style.visibility = "visible";
//divobj.style.left="330px !important";
//divobj.style.top="25px !important";
    if (navigator.appName == "Microsoft Internet Explorer")
        computedStyle = divobj.currentStyle;
    else
        computedStyle = document.defaultView.getComputedStyle(divobj, null);
//Get Div width and height from StyleSheet
    var divWidth = computedStyle.width.replace('px', '');
    var divHeight = computedStyle.height.replace('px', '');
    var divLeft = (pageWidth - divWidth) / 2;
    var divTop = (pageHeight - divHeight) / 2;
//Set Left and top coordinates for the div tag
    divobj.style.left = (divLeft + 130) + "px";
    divobj.style.top = (divTop + 20) + "px";
//console.log(divLeft);
//console.log(divTop);
//Put a Close button for closing the popped up Div tag
    if (divobj.innerHTML.indexOf("closepopup('" + id + "')") < 0)
        divobj.innerHTML = "X" + divobj.innerHTML;
    //var t=setTimeout(function(){ popup1.style.visibility = "hidden";
    //bg.style.visibility = "hidden";},7000);
    // setTimeout();
    //iframerefresh();
}
function closepopup(id) {
    var divbg = document.getElementById('bg');
    divbg.style.visibility = "hidden";
    var divobj = document.getElementById(id);
    divobj.style.visibility = "hidden";
}

$(function() {
    cometpopup();
});

function cometpopup() {

    var agentnumber = $('#agent').val();
    $.ajax({
        type: 'Get',
        url: baseUrl + "index.php/login/popup",
        async: true,
        success: function(data) {
            var json = eval('(' + data + ')');
            console.log(json);
            var phon = json.phone;

            console.log(phon);
            if (phon != '')
            {
                var ccc = json.check;

                if (ccc == "done")
                {
                    alert("you hv tht number");
                    $('#popup1').html("user data is there in database");
                    openpopup('popup1');
                    var t = setTimeout(function() {
                        popup1.style.visibility = "hidden";
                        bg.style.visibility = "hidden";
                    }, 7000);

                }
                else
                {
                    alert("no such tht number");
                    $('#popup1').html("No data found");
                    openpopup('popup1');
                    var t = setTimeout(function() {
                        popup1.style.visibility = "hidden";
                        bg.style.visibility = "hidden";
                    }, 7000);

                }

            }
            else
            {

            }
            setTimeout('cometpopup()', 1000000);
        },
        error: function(XMLHttpRequest, textstatus, error) {
            //alert(error);
            $('#send').html('ERROR');
            setTimeout('cometpopup()', 1000);

        }

    });
}

<|endoftext|>