<commit_before>function getUrl(){
  var currentUrl = window.location.href;
  var locationToCut = currentUrl.indexOf("?");
  currentUrl = currentUrl.substring(locationToCut+1);
  return currentUrl;

}

function routTo(currentUrl, back){

  // debugger;
  if (back == undefined){back = false}

  var slashPostion = currentUrl.indexOf("/");

  var currentType = currentUrl.slice(0,slashPostion);
  var currentEntity = currentUrl.slice(slashPostion+1);

  showEntities(currentType, currentEntity);

}

function setUrl(type, uid){
  //get domain
  var currentUrl = window.location.href;
  var locationToCut = currentUrl.indexOf("?");
  var domainUrl = currentUrl.slice(0,locationToCut);

  if(type == undefined || uid == undefined){
    history.pushState({}, uid, domainUrl );
  } else{

    var typeEntity = {type: type, entity: uid};

    var url = domainUrl+"?"+type+"/"+uid;
    if(locationToCut >=0 && url!=currentUrl) {
      history.pushState(typeEntity, uid, url );
    } else {
      history.replaceState(typeEntity, uid, url );
    }
  }
};

function setActiveEntity (newEntity, newUid, newEventType, newCallback, turnOff) {

  // debugger;
  var previuosEntityType = activeEntity.entityType;
  var previuosUid = activeEntity.uid;
  var previuosEventType = activeEntity.eventType;
  var previuosCallback = activeEntity.callback;
  var previuosTurnOff = activeEntity.turnOff;

  activeEntity.previuosEntity = previuosEntityType;
  activeEntity.previuosUid = previuosUid;

  checkChatsUpdates(newEntity, newUid);

     if (previuosEntityType != "main") {
        if (previuosEventType != undefined){
           if (previuosUid != undefined){
              previuosTurnOff();
           } else {
              console.log("Error: no previuos entity to close off previous callback");
           }
        } else if( previuosEntityType == "feed") {
           feedManager.queue = "popAll";
           feedManager.inbox = 0;
        }
     } else {
        switch (previuosUid) {
           case "member":
           case "owned":
              DB.child("users/"+userUuid+"/role").off(previuosEventType, previuosCallback);
              break;
           case "public":
              DB.child("groups").off(previuosEventType, previuosCallback);
              break;
           default:
              console.log("Error: no such groups cluster in main ("+previuosUid+")");
        }
     }

   activeEntity.entityType = newEntity;
   activeEntity.uid = newUid;
   activeEntity.eventType = newEventType;
   activeEntity.callback = newCallback;
   activeEntity.turnOff = turnOff;
   //activeEntity.previuosEntityType = previuosEntityType;

  setUrl(newEntity, newUid);

  if (newEntity == "chats")
    DB.child(previuosEntityType+"/"+newUid).once("value", function (dataSnapshot){

      document.title = "דליב: " + entityTypeToHebrew(newEntity) + " - " +dataSnapshot.val().title;
    });

  if (newEntity == "groups" || newEntity == "topics" || newEntity == "questions"){
    DB.child(newEntity+"/"+newUid).once("value", function (dataSnapshot){

      document.title = "דליב: " + entityTypeToHebrew(newEntity) + " - " +dataSnapshot.val().title;
    })
  } else {
    document.title = "דליב (ראשי) : מחליטים ביחד";
  }

  $("#entitiesPanel").slideUp(400);

  var currentEntity = activeEntity.uid;

  showNumberOfFeeds();
}

function showEntities(entity, uid){

  $("wrapper").css("overflow","auto");
  switch (entity){
    case "groups":
      DB.child("groups/"+uid).once("value", function (group){
        if(group.exists()){
          showGroup(uid);
        } else {
          console.log("group "+uid+" do not exist");
          showMain("public");
        }
      })
      break;
    case "topics":
      DB.child("topics/"+uid).once("value", function (topic){
        if (topic.exists()){
          showTopic(uid);
        } else {
          console.log("topic "+uid+" do not exist");
          showMain("public");
        }
      })
      break;
    case "questions":
      DB.child("questions/"+uid).once("value", function (question){
        if (question.exists()){
          showQuestion(uid);
        } else {
          console.log("question "+uid+" do not exist");
          showMain("public");
        }
      })
      break;
    case "chats":
      DB.child("chats/"+uid).once("value", function (question){
        if (question.exists()){
          var entityType = question.val().entity.typeInDB;
          showChat(entityType, uid);
        } else {
          console.log("question "+uid+" do not exist");
          showMain("public");
        }
      })
      break;
    case "liveTalks":
      DB.child("liveTalks/"+uid).once("value", function (question){
        if (question.exists()){
          showLiveTalk(uid);
        } else {
          console.log("question "+uid+" do not exist");
          showMain("public");
        }
      })
      break;
    case "main":
      showMain(uid);
      break;
    case "options":
      DB.child("options/"+uid).once("value", function(dataSnapshot){
        if (question.exists()){
          var questionUid = dataSnapshot.val().questionUid;
          var optionUid = dataSnapshot.val().optionUid;

          showOption(questionUid,optionUid);
        } else {
          console.log("option "+uid+" do not exist");
          showMain("public");
        }
      })
      break;
    default:
      showMain("public");
  }

};

function showBreadCrumb(entityType, uid, title){
  //get all parents of an entity (by settin it's type and uid)

  //child

  var currentChild = {entityType: entityType, uid: uid, title:title, symbol: symbols[entityType]};

  //get parent 1
  DB.child(entityType+"/"+uid).once("value", function(dataP1){

    if (dataP1.val().parentEntityUid != null && dataP1.val().parentEntityUid !=""){
      console.log("has a parent1");

      var parent1Type = dataP1.val().parentEntityType;
      var parent1Uid = dataP1.val().parentEntityUid;
      var parent1Symbol = symbols[parent1Type];

      var parent1 = {entityType: parent1Type, uid: parent1Uid, symbol: parent1Symbol};

      DB.child(parent1Type+"/"+parent1Uid).once("value", function(dataP2){

        //get parent1 title
        parent1.title = dataP2.val().title;

        if (dataP2.val() != null && dataP2.val().parentEntityType != ""){
          //check if the parent1 have parent2

          //get parent2 uid and type
          var parent2Type = dataP2.val().parentEntityType;
          var parent2Uid = dataP2.val().parentEntityUid;
          var parent2Symbol = symbols[parent2Type];

          var parent2 = {entityType: parent2Type, uid: parent2Uid, symbol: parent2Symbol};

          //get parent 2 title
          DB.child(parent2Type+"/"+parent2Uid).once("value", function(dataP3){

            parent2.title = dataP3.val().title;
            var context = {path: [parent2, parent1, currentChild]}
            renderTemplate("#headerBreadCrumbs-tmpl",context,"#headerBreadCrumbs");

          })
        } else {

          var context = {path: [parent1, currentChild]}
          renderTemplate("#headerBreadCrumbs-tmpl",context,"#headerBreadCrumbs");
        }

      })
    } else {

      var context = {path: [currentChild]};
      renderTemplate("#headerBreadCrumbs-tmpl",context,"#headerBreadCrumbs");
    }
  })

}
<commit_msg>temp<commit_after>function getUrl(){
  var currentUrl = window.location.href;
  var locationToCut = currentUrl.indexOf("?");
  currentUrl = currentUrl.substring(locationToCut+1);
  return currentUrl;

}

function routTo(currentUrl, back){

  // debugger;
  if (back == undefined){back = false}

  var slashPostion = currentUrl.indexOf("/");

  var currentType = currentUrl.slice(0,slashPostion);
  var currentEntity = currentUrl.slice(slashPostion+1);

  showEntities(currentType, currentEntity);

}

function setUrl(type, uid){
  //get domain
  var currentUrl = window.location.href;
  var locationToCut = currentUrl.indexOf("?");
  var domainUrl = currentUrl.slice(0,locationToCut);

  if(type == undefined || uid == undefined){
    history.pushState({}, uid, domainUrl );
  } else{

    var typeEntity = {type: type, entity: uid};

    var url = domainUrl+"?"+type+"/"+uid;
    if(locationToCut >=0 && url!=currentUrl) {
      history.pushState(typeEntity, uid, url );
    } else {
      history.replaceState(typeEntity, uid, url );
    }
  }
};

function setActiveEntity (newEntity, newUid, newEventType, newCallback, turnOff) {

  // debugger;
  var previuosEntityType = activeEntity.entityType;
  var previuosUid = activeEntity.uid;
  var previuosEventType = activeEntity.eventType;
  var previuosCallback = activeEntity.callback;
  var previuosTurnOff = activeEntity.turnOff;

  activeEntity.previuosEntity = previuosEntityType;
  activeEntity.previuosUid = previuosUid;

  checkChatsUpdates(newEntity, newUid);

     if (previuosEntityType != "main") {
        if (previuosEventType != undefined){
           if (previuosUid != undefined){
              previuosTurnOff();
           } else {
              console.log("Error: no previuos entity to close off previous callback");
           }
        } else if( previuosEntityType == "feed") {
           feedManager.queue = "popAll";
           feedManager.inbox = 0;
        }
     } else {
        switch (previuosUid) {
           case "member":
           case "owned":
              DB.child("users/"+userUuid+"/role").off(previuosEventType, previuosCallback);
              break;
           case "public":
              DB.child("groups").off(previuosEventType, previuosCallback);
              break;
           default:
              console.log("Error: no such groups cluster in main ("+previuosUid+")");
        }
     }

   console.log("bksbvfsbfbf");
   activeEntity.entityType = newEntity;
   activeEntity.uid = newUid;
   activeEntity.eventType = newEventType;
   activeEntity.callback = newCallback;
   activeEntity.turnOff = turnOff;
   //activeEntity.previuosEntityType = previuosEntityType;

  setUrl(newEntity, newUid);

  if (newEntity == "chats")
    DB.child(previuosEntityType+"/"+newUid).once("value", function (dataSnapshot){

      document.title = "דליב: " + entityTypeToHebrew(newEntity) + " - " +dataSnapshot.val().title;
    });

  if (newEntity == "groups" || newEntity == "topics" || newEntity == "questions"){
    DB.child(newEntity+"/"+newUid).once("value", function (dataSnapshot){

      document.title = "דליב: " + entityTypeToHebrew(newEntity) + " - " +dataSnapshot.val().title;
    })
  } else {
    document.title = "דליב (ראשי) : מחליטים ביחד";
  }

  $("#entitiesPanel").slideUp(400);

  var currentEntity = activeEntity.uid;

  showNumberOfFeeds();
}

function showEntities(entity, uid){

  $("wrapper").css("overflow","auto");
  switch (entity){
    case "groups":
      DB.child("groups/"+uid).once("value", function (group){
        if(group.exists()){
          showGroup(uid);
        } else {
          console.log("group "+uid+" do not exist");
          showMain("public");
        }
      })
      break;
    case "topics":
      DB.child("topics/"+uid).once("value", function (topic){
        if (topic.exists()){
          showTopic(uid);
        } else {
          console.log("topic "+uid+" do not exist");
          showMain("public");
        }
      })
      break;
    case "questions":
      DB.child("questions/"+uid).once("value", function (question){
        if (question.exists()){
          showQuestion(uid);
        } else {
          console.log("question "+uid+" do not exist");
          showMain("public");
        }
      })
      break;
    case "chats":
      DB.child("chats/"+uid).once("value", function (question){
        if (question.exists()){
          var entityType = question.val().entity.typeInDB;
          showChat(entityType, uid);
        } else {
          console.log("question "+uid+" do not exist");
          showMain("public");
        }
      })
      break;
    case "liveTalks":
      DB.child("liveTalks/"+uid).once("value", function (question){
        if (question.exists()){
          showLiveTalk(uid);
        } else {
          console.log("question "+uid+" do not exist");
          showMain("public");
        }
      })
      break;
    case "main":
      showMain(uid);
      break;
    case "options":
      DB.child("options/"+uid).once("value", function(dataSnapshot){
        if (question.exists()){
          var questionUid = dataSnapshot.val().questionUid;
          var optionUid = dataSnapshot.val().optionUid;

          showOption(questionUid,optionUid);
        } else {
          console.log("option "+uid+" do not exist");
          showMain("public");
        }
      })
      break;
    default:
      showMain("public");
  }

};

function showBreadCrumb(entityType, uid, title){
  //get all parents of an entity (by settin it's type and uid)

  //child

  var currentChild = {entityType: entityType, uid: uid, title:title, symbol: symbols[entityType]};

  //get parent 1
  DB.child(entityType+"/"+uid).once("value", function(dataP1){

    if (dataP1.val().parentEntityUid != null && dataP1.val().parentEntityUid !=""){
      console.log("has a parent1");

      var parent1Type = dataP1.val().parentEntityType;
      var parent1Uid = dataP1.val().parentEntityUid;
      var parent1Symbol = symbols[parent1Type];

      var parent1 = {entityType: parent1Type, uid: parent1Uid, symbol: parent1Symbol};

      DB.child(parent1Type+"/"+parent1Uid).once("value", function(dataP2){

        //get parent1 title
        parent1.title = dataP2.val().title;

        if (dataP2.val() != null && dataP2.val().parentEntityType != ""){
          //check if the parent1 have parent2

          //get parent2 uid and type
          var parent2Type = dataP2.val().parentEntityType;
          var parent2Uid = dataP2.val().parentEntityUid;
          var parent2Symbol = symbols[parent2Type];

          var parent2 = {entityType: parent2Type, uid: parent2Uid, symbol: parent2Symbol};

          //get parent 2 title
          DB.child(parent2Type+"/"+parent2Uid).once("value", function(dataP3){

            parent2.title = dataP3.val().title;
            var context = {path: [parent2, parent1, currentChild]}
            renderTemplate("#headerBreadCrumbs-tmpl",context,"#headerBreadCrumbs");

          })
        } else {

          var context = {path: [parent1, currentChild]}
          renderTemplate("#headerBreadCrumbs-tmpl",context,"#headerBreadCrumbs");
        }

      })
    } else {

      var context = {path: [currentChild]};
      renderTemplate("#headerBreadCrumbs-tmpl",context,"#headerBreadCrumbs");
    }
  })

}
<|endoftext|>


<commit_before>$(document).ready(function() {
  app.hookupMap();
  app.hookupSteps();
});

var app = app || {};
app.state = {
  channel: 'sms',
  geom: undefined,
  publisher_id: undefined,
};

app.eventMarkers = new L.FeatureGroup();

app.hookupMap = function() {
  var options = {
    zoom: 13,
    center: [47.604432, -122.336014],
    tileLayer: { detectRetina: true },
    scrollWheelZoom: false,
  };
  var mapId = $('meta[name=mapId]').attr('content');
  var map = app.map = L.mapbox.map('map', mapId, options);
};

app.hookupSteps = function() {
  $('.startButton').on('click', function() {
    app.scrollToElement($('#step1'));
  });

  $('.publisher:not(.soon)').on('click', function(event) {
    $('.publisher').removeClass('selected');

    var $publisher = $(event.currentTarget);
    app.state.publisher_id = $publisher.data('publisher-id');
    $publisher.addClass('selected');

    // Update the confirmation section with the name
    $('.confirmationType').html($publisher.data('publisher-title'));

    app.scrollToElement($('#step2'));

    // update events for the new publisher
    app.updateEvents(app.map.getBounds());
  });

  $('.mapButton').on('click', function() {
    app.scrollToElement($('#step3'));
  });

  $('.smsButton').on('click', function(event) {
    $(event.target).addClass('selected');
    $('.extraInfo').slideDown();
  });

  var finishSubscribe = function(e) {
    // TODO: animate the done checkmark at the same time
    e.preventDefault();

    // TODO: handle email and webhooks also
    app.state.phone_number = $('.phoneNumber').val();

    app.submitSubscription(function() {
      $('#confirmation').slideDown();
      app.scrollToElement($('#confirmation'));
    });
  };
  $('.subscribeButton').on('click', finishSubscribe);
  $('#subscribeForm').on('submit', finishSubscribe);

  $('.resetButton').on('click', function(event) {
    app.resetState();
    app.scrollToElement($('#step1'));

    // Hide after we've scrolled up.
    setTimeout(function() {
      $('#confirmation').hide();
    }, 800);
  });

  var prevMarker, prevCircle;
  var geolocate = function(e) {
    e.preventDefault();
    var city = $('.publisher.selected').data('publisher-city');
    var address = $('#geolocate').val();
    var radius = $('#user-selected-radius').val();
    var radiusMeters = parseFloat(radius) * 1609.344;
    var oneWeekAgo = new Date();
    oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);

    app.geocode(address+' '+city, function(latlng) {
      // Set the new app state
      var center = new LatLon(latlng[0], latlng[1]);
      var bboxWidth = parseFloat($('#user-selected-radius').val())
      var bbox = center.boundingBox(bboxWidth);
      app.state.geom = JSON.stringify({
        type: 'Polygon',
        coordinates: [bbox],
      });

      // Remove old layers
      if (prevMarker) app.map.removeLayer(prevMarker);
      if (prevCircle) app.map.removeLayer(prevCircle);

      // Preserve references to new layers
      prevMarker = L.marker(latlng).addTo(app.map);
      prevCircle = L.circle(latlng, radiusMeters).addTo(app.map);

      // fit bounds
      app.map.fitBounds(prevCircle.getBounds());

      // Frequency estimate
      app.getEventsCount(app.state.publisher_id, app.state.geom, oneWeekAgo, function(response) {
        $('#freqRadius').html(radius + ' mi');
        $('#freqAddress').html(address);
        $('#freqNum').html(response.events_count + ' citygrams');
      });

    });
  };

  app.map.on('zoomend', function() {
    app.updateEvents(app.map.getBounds());
  });
  $('#user-selected-radius').on('change', geolocate);
  $('#geolocateForm').on('submit', geolocate);
  $('.geolocateButton').on('click', geolocate);
  $('#geolocate').on('change', geolocate);
};

// Populate events
app.updateEvents = function(bounds) {
  var mapGeometry = {
    type: 'Polygon',
    coordinates: [[
      [bounds._southWest.lng, bounds._northEast.lat],
      [bounds._northEast.lng, bounds._northEast.lat],
      [bounds._northEast.lng, bounds._southWest.lat],
      [bounds._southWest.lng, bounds._southWest.lat],
      [bounds._southWest.lng, bounds._northEast.lat]
    ]]
  }

  app.getEventsForGeometry(JSON.stringify(mapGeometry), function(events) {
    app.eventMarkers.eachLayer(function(layer) {
      app.map.removeLayer(layer);
    });
    events.forEach(app.displayEventMarker);
  });
};

app.displayEventMarker = function(event) {
  var geometry = JSON.parse(event.geom);
  var html = "
"+event.title+"
"
  var marker = L.circleMarker([geometry.coordinates[1], geometry.coordinates[0]], { radius: 6 })
                 .addTo(app.map)
                 .bindPopup(html);

  app.eventMarkers.addLayer(marker);
  return marker;
}

app.getEventsForGeometry = function(geometry, callback){
  if (!app.state.publisher_id) return;
  $.getJSON('/publishers/'+app.state.publisher_id+'/events', { geometry: geometry }, callback);
};

app.getEventsCount = function(publisherId, geometry, since, callback){
  if (!publisherId) return;
  $.getJSON('/publishers/'+publisherId+'/events_count', { geometry: geometry, since: since }, callback);
};

app.scrollToElement = function(el) {
  $('html,body').animate({
    scrollTop: el.offset().top
  }, 800);
};

app.geocode = function(city, callback, context) {
  var url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + encodeURIComponent(city);

  $.getJSON(url, function(response) {
    if (response.error || response.results.length === 0) {
      console.log('Unable to geocode city. Womp Womp.', response.error);
    }

    // Get the coordinates for the center of the city
    var location = response.results[0].geometry.location;
    var latlng = [location.lat, location.lng];
    callback.call(context || this, latlng);
  });
};

app.resetState = function() {
  app.state.publisher_id = undefined;
  $('.publisher').removeClass('selected');

  // Let's leave the location and phone number in place, for easy re-subscribe
};

app.submitSubscription = function(callback) {
  $.post('/subscriptions', { subscription: app.state }, callback);
};
<commit_msg>Double radius for bounding box width<commit_after>$(document).ready(function() {
  app.hookupMap();
  app.hookupSteps();
});

var app = app || {};
app.state = {
  channel: 'sms',
  geom: undefined,
  publisher_id: undefined,
};

app.eventMarkers = new L.FeatureGroup();

app.hookupMap = function() {
  var options = {
    zoom: 13,
    center: [47.604432, -122.336014],
    tileLayer: { detectRetina: true },
    scrollWheelZoom: false,
  };
  var mapId = $('meta[name=mapId]').attr('content');
  var map = app.map = L.mapbox.map('map', mapId, options);
};

app.hookupSteps = function() {
  $('.startButton').on('click', function() {
    app.scrollToElement($('#step1'));
  });

  $('.publisher:not(.soon)').on('click', function(event) {
    $('.publisher').removeClass('selected');

    var $publisher = $(event.currentTarget);
    app.state.publisher_id = $publisher.data('publisher-id');
    $publisher.addClass('selected');

    // Update the confirmation section with the name
    $('.confirmationType').html($publisher.data('publisher-title'));

    app.scrollToElement($('#step2'));

    // update events for the new publisher
    app.updateEvents(app.map.getBounds());
  });

  $('.mapButton').on('click', function() {
    app.scrollToElement($('#step3'));
  });

  $('.smsButton').on('click', function(event) {
    $(event.target).addClass('selected');
    $('.extraInfo').slideDown();
  });

  var finishSubscribe = function(e) {
    // TODO: animate the done checkmark at the same time
    e.preventDefault();

    // TODO: handle email and webhooks also
    app.state.phone_number = $('.phoneNumber').val();

    app.submitSubscription(function() {
      $('#confirmation').slideDown();
      app.scrollToElement($('#confirmation'));
    });
  };
  $('.subscribeButton').on('click', finishSubscribe);
  $('#subscribeForm').on('submit', finishSubscribe);

  $('.resetButton').on('click', function(event) {
    app.resetState();
    app.scrollToElement($('#step1'));

    // Hide after we've scrolled up.
    setTimeout(function() {
      $('#confirmation').hide();
    }, 800);
  });

  var prevMarker, prevCircle;
  var geolocate = function(e) {
    e.preventDefault();
    var city = $('.publisher.selected').data('publisher-city');
    var address = $('#geolocate').val();
    var radius = $('#user-selected-radius').val();
    var radiusMeters = parseFloat(radius) * 1609.344;
    var oneWeekAgo = new Date();
    oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);

    app.geocode(address+' '+city, function(latlng) {
      // Set the new app state
      var center = new LatLon(latlng[0], latlng[1]);
      var bboxWidth = 2 * parseFloat($('#user-selected-radius').val())
      var bbox = center.boundingBox(bboxWidth);
      app.state.geom = JSON.stringify({
        type: 'Polygon',
        coordinates: [bbox],
      });

      // Remove old layers
      if (prevMarker) app.map.removeLayer(prevMarker);
      if (prevCircle) app.map.removeLayer(prevCircle);

      // Preserve references to new layers
      prevMarker = L.marker(latlng).addTo(app.map);
      prevCircle = L.circle(latlng, radiusMeters).addTo(app.map);

      // fit bounds
      app.map.fitBounds(prevCircle.getBounds());

      // Frequency estimate
      app.getEventsCount(app.state.publisher_id, app.state.geom, oneWeekAgo, function(response) {
        $('#freqRadius').html(radius + ' mi');
        $('#freqAddress').html(address);
        $('#freqNum').html(response.events_count + ' citygrams');
      });

    });
  };

  app.map.on('zoomend', function() {
    app.updateEvents(app.map.getBounds());
  });
  $('#user-selected-radius').on('change', geolocate);
  $('#geolocateForm').on('submit', geolocate);
  $('.geolocateButton').on('click', geolocate);
  $('#geolocate').on('change', geolocate);
};

// Populate events
app.updateEvents = function(bounds) {
  var mapGeometry = {
    type: 'Polygon',
    coordinates: [[
      [bounds._southWest.lng, bounds._northEast.lat],
      [bounds._northEast.lng, bounds._northEast.lat],
      [bounds._northEast.lng, bounds._southWest.lat],
      [bounds._southWest.lng, bounds._southWest.lat],
      [bounds._southWest.lng, bounds._northEast.lat]
    ]]
  }

  app.getEventsForGeometry(JSON.stringify(mapGeometry), function(events) {
    app.eventMarkers.eachLayer(function(layer) {
      app.map.removeLayer(layer);
    });
    events.forEach(app.displayEventMarker);
  });
};

app.displayEventMarker = function(event) {
  var geometry = JSON.parse(event.geom);
  var html = "
"+event.title+"
"
  var marker = L.circleMarker([geometry.coordinates[1], geometry.coordinates[0]], { radius: 6 })
                 .addTo(app.map)
                 .bindPopup(html);

  app.eventMarkers.addLayer(marker);
  return marker;
}

app.getEventsForGeometry = function(geometry, callback){
  if (!app.state.publisher_id) return;
  $.getJSON('/publishers/'+app.state.publisher_id+'/events', { geometry: geometry }, callback);
};

app.getEventsCount = function(publisherId, geometry, since, callback){
  if (!publisherId) return;
  $.getJSON('/publishers/'+publisherId+'/events_count', { geometry: geometry, since: since }, callback);
};

app.scrollToElement = function(el) {
  $('html,body').animate({
    scrollTop: el.offset().top
  }, 800);
};

app.geocode = function(city, callback, context) {
  var url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + encodeURIComponent(city);

  $.getJSON(url, function(response) {
    if (response.error || response.results.length === 0) {
      console.log('Unable to geocode city. Womp Womp.', response.error);
    }

    // Get the coordinates for the center of the city
    var location = response.results[0].geometry.location;
    var latlng = [location.lat, location.lng];
    callback.call(context || this, latlng);
  });
};

app.resetState = function() {
  app.state.publisher_id = undefined;
  $('.publisher').removeClass('selected');

  // Let's leave the location and phone number in place, for easy re-subscribe
};

app.submitSubscription = function(callback) {
  $.post('/subscriptions', { subscription: app.state }, callback);
};
<|endoftext|>


<commit_before>/* ShowOff JS Logic */

var ShowOff = {};

var preso_started = false
var slidenum = 0
var slideTotal = 0
var slides
var currentSlide
var totalslides = 0
var slidesLoaded = false
var incrSteps = 0
var incrElem
var incrCurr = 0
var incrCode = false
var debugMode = false
var gotoSlidenum = 0
var shiftKeyActive = false

var loadSlidesBool
var loadSlidesPrefix

function setupPreso(load_slides, prefix) {
  if (preso_started)
  {
     alert("already started")
     return
  }
  preso_started = true

  loadSlidesBool = load_slides
  loadSlidesPrefix = prefix
  loadSlides(loadSlidesBool, loadSlidesPrefix)

  doDebugStuff()

  // bind event handlers
  document.onkeydown = keyDown
  document.onkeyup = keyUp
  /* window.onresize  = resized; */
  /* window.onscroll = scrolled; */
  /* window.onunload = unloaded; */
}

function loadSlides(load_slides, prefix) {
  //load slides offscreen, wait for images and then initialize
  if (load_slides) {
  	$("#slides").load("/slides", false, function(){
    	$("#slides img").batchImageLoad({
			loadingCompleteCallback: initializePresentation(prefix)
		})
  	})
  } else {
	$("#slides img").batchImageLoad({
		loadingCompleteCallback: initializePresentation(prefix)
	})
  }
}

function initializePresentation(prefix) {
  //center slides offscreen
  centerSlides($('#slides > .slide'))

  //copy into presentation area
  $("#preso").empty()
  $('#slides > .slide').appendTo($("#preso"))

  //populate vars
  slides = $('#preso > .slide')
  slideTotal = slides.size()

  //setup manual jquery cycle
  $('#preso').cycle({
    timeout: 0
  })

  setupMenu()
  if (slidesLoaded) {
    showSlide()
  } else {
    showFirstSlide();
    slidesLoaded = true
  }
  setupSlideParamsCheck();
  sh_highlightDocument(prefix+'/js/sh_lang/', '.min.js')
}

function centerSlides(slides) {
  slides.each(function(s, slide) {
    centerSlide(slide)
  })
}

function centerSlide(slide) {
  var slide_content = $(slide).children(".content").first()
  var height = slide_content.height()
  var mar_top = (0.5 * parseFloat($(slide).height())) - (0.5 * parseFloat(height))
  if (mar_top < 0) {
    mar_top = 0
  }
  slide_content.css('margin-top', mar_top)
}

function setupMenu() {
  $('#navmenu').hide();

  var currSlide = 0
  var menu = new ListMenu()

  slides.each(function(s, elem) {
    content = $(elem).children(".content")
    shortTxt = $(content).text().substr(0, 20)
    path = $(content).attr('ref').split('/')
    currSlide += 1
    menu.addItem(path, shortTxt, currSlide)
  })

  $('#navigation').html(menu.getList())
  $('#navmenu').menu({
    content: $('#navigation').html(),
    flyOut: true
  });
}

function checkSlideParameter() {
  if (slideParam = currentSlideFromParams()) {
    slidenum = slideParam;
  }
}

function currentSlideFromParams() {
  var result;
  if (result = window.location.hash.match(/#([0-9]+)/)) {
    return result[result.length - 1] - 1;
  }
}

function setupSlideParamsCheck() {
  var check = function() {
    var currentSlide = currentSlideFromParams();
    if (slidenum != currentSlide) {
      slidenum = currentSlide;
      showSlide();
    }
    setTimeout(check, 100);
  }
  setTimeout(check, 100);
}

function gotoSlide(slideNum) {
  slidenum = parseInt(slideNum)
  if (!isNaN(slidenum)) {
    showSlide()
  }
}

function showFirstSlide() {
  slidenum = 0
  checkSlideParameter();
  showSlide()
}

function showSlide(back_step) {

  if(slidenum < 0) {
    slidenum = 0
    return
  }

  if(slidenum > (slideTotal - 1)) {
    slidenum = slideTotal - 1
    return
  }

  currentSlide = slides.eq(slidenum)

  var transition = currentSlide.attr('data-transition')
  var fullPage = currentSlide.find(".content").is('.full-page');

  if (back_step || fullPage) {
    transition = 'none'
  }

  $('#preso').cycle(slidenum, transition)

  if (fullPage) {
    $('#preso').css({'width' : '100%', 'overflow' : 'visible'});
    currentSlide.css({'width' : '100%', 'text-align' : 'center', 'overflow' : 'visible'});
  } else {
    $('#preso').css({'width' : '1020px', 'overflow' : 'hidden'});
  }

  percent = getSlidePercent()
  $("#slideInfo").text((slidenum + 1) + '/' + slideTotal + '  - ' + percent + '%')

  if(!back_step) {
    // determine if there are incremental bullets to show
    // unless we are moving backward
    determineIncremental()
  } else {
    incrCurr = 0
    incrSteps = 0
  }
  location.hash = slidenum + 1;
  $('body').addSwipeEvents().
    bind('swipeleft',  swipeLeft).
    bind('swiperight', swipeRight)
  removeResults()

  $(currentSlide).find(".content").trigger("showoff:show");

  return getCurrentNotes()
}

function getSlideProgress()
{
  return (slidenum + 1) + '/' + slideTotal
}

function getCurrentNotes()
{
  return currentSlide.find("p.notes").text()
}

function getSlidePercent()
{
  return Math.ceil(((slidenum + 1) / slideTotal) * 100)
}

function determineIncremental()
{
  incrCurr = 0
  incrCode = false
  incrElem = currentSlide.find(".incremental > ul > li")
  incrSteps = incrElem.size()
  if(incrSteps == 0) {
    // also look for commandline
    incrElem = currentSlide.find(".incremental > pre > code > code")
    incrSteps = incrElem.size()
    incrCode = true
  }
  incrElem.each(function(s, elem) {
    $(elem).hide()
  })
}

function prevStep()
{

  var event = jQuery.Event("showoff:prev");
  $(currentSlide).find(".content").trigger(event);
  if (event.isDefaultPrevented()) {
      return;
  }

  slidenum--
  return showSlide(true) // We show the slide fully loaded
}

function nextStep()
{
  var event = jQuery.Event("showoff:next");
  $(currentSlide).find(".content").trigger(event);
  if (event.isDefaultPrevented()) {
      return;
  }

  if (incrCurr >= incrSteps) {
    slidenum++
    return showSlide()
  } else {
    elem = incrElem.eq(incrCurr)
    if (incrCode && elem.hasClass('command')) {
      incrElem.eq(incrCurr).show().jTypeWriter({duration:1.0})
    } else {
      incrElem.eq(incrCurr).show()
    }
    incrCurr++
  }
}

function doDebugStuff()
{
  if (debugMode) {
    $('#debugInfo').show()
    debug('debug mode on')
  } else {
    $('#debugInfo').hide()
  }
}

function debug(data)
{
  $('#debugInfo').text(data)
}

//  See e.g. http://www.quirksmode.org/js/keys.html for keycodes
function keyDown(event)
{
    var key = event.keyCode;

    if (event.ctrlKey || event.altKey || event.metaKey)
       return true;

    debug('keyDown: ' + key)

    if (key >= 48 && key <= 57) // 0 - 9
    {
      gotoSlidenum = gotoSlidenum * 10 + (key - 48);
      return true;
    }

    if (key == 13){
        if (gotoSlidenum > 0) {
            debug('go to ' + gotoSlidenum);
            slidenum = gotoSlidenum - 1;
            showSlide(true);
            gotoSlidenum = 0;
        } else {
            debug('executeCode');
            executeCode.call($('.sh_javaScript code:visible'));
        }

    }

    if (key == 16) // shift key
    {
      shiftKeyActive = true;
    }
    if (key == 32) // space bar
    {
      if (shiftKeyActive) { prevStep() }
      else                { nextStep() }
    }
    else if (key == 68) // 'd' for debug
    {
      debugMode = !debugMode
      doDebugStuff()
    }
    else if (key == 37 || key == 33 || key == 38) // Left arrow, page up, or up arrow
    {
      prevStep()
    }
    else if (key == 39 || key == 34 || key == 40) // Right arrow, page down, or down arrow
    {
      nextStep()
    }
    else if (key == 82) // R for reload
    {
      if (confirm('really reload slides?')) {
        loadSlides(loadSlidesBool, loadSlidesPrefix)
        showSlide()
      }
    }
    else if (key == 84 || key == 67)  // T or C for table of contents
    {
      $('#navmenu').toggle().trigger('click')
    }
    else if (key == 90) // z for help
    {
      $('#help').toggle()
    }
    else if (key == 66 || key == 70) // f for footer (also "b" which is what kensington remote "stop" button sends
    {
      toggleFooter()
    }
	else if (key == 27) // esc
	{
		removeResults();
	}
	else if (key == 80) // 'p' for preshow
	{
		runPreShow();
	}
    return true
}

function toggleFooter()
{
  $('#footer').toggle()
}

function keyUp(event) {
  var key = event.keyCode;
  debug('keyUp: ' + key);
  if (key == 16) // shift key
  {
    shiftKeyActive = false;
  }
}

function swipeLeft() {
  nextStep()
}

function swipeRight() {
  prevStep()
}

function ListMenu(s)
{
  this.slide = s
  this.typeName = 'ListMenu'
  this.itemLength = 0;
  this.items = new Array();
  this.addItem = function (key, text, slide) {
    if (key.length > 1) {
      thisKey = key.shift()
      if (!this.items[thisKey]) {
        this.items[thisKey] = new ListMenu(slide)
      }
      this.items[thisKey].addItem(key, text, slide)
    } else {
      thisKey = key.shift()
      this.items[thisKey] = new ListMenuItem(text, slide)
    }
  }
  this.getList = function() {
    var newMenu = $("
")
    for(var i in this.items) {
      var item = this.items[i]
      var domItem = $("
")
      if (item.typeName == 'ListMenu') {
        choice = $("" + i + "")
        domItem.append(choice)
        domItem.append(item.getList())
      }
      if (item.typeName == 'ListMenuItem') {
        choice = $("" + item.slide + '. ' + item.textName + "")
        domItem.append(choice)
      }
      newMenu.append(domItem)
    }
    return newMenu
  }
}

function ListMenuItem(t, s)
{
  this.typeName = "ListMenuItem"
  this.slide = s
  this.textName = t
}

var removeResults = function() {
  $('.results').remove();
};

var print = function(text) {
  removeResults();
  var _results = $('
').addClass('results').html($.print(text, {max_string:500}));
  $('body').append(_results);
  _results.click(removeResults);
};

function executeCode () {
    result = null;
    var codeDiv = $(this);
    codeDiv.addClass("executing");
    eval(codeDiv.text());
    setTimeout(function() { codeDiv.removeClass("executing");}, 250 );
    if (result != null) print(result);
}
$('.sh_javaScript code').live("click", executeCode);

/********************
 PreShow Code
 ********************/

var preshow_seconds = 0;
var preshow_secondsLeft = 0;
var preshow_secondsPer = 8;
var preshow_running = false;
var preshow_timerRunning = false;
var preshow_current = 0;
var preshow_images;
var preshow_imagesTotal = 0;
var preshow_des;

function runPreShow() {
	if(preshow_running) {
		stopPreShow()
	} else {
		var minutes = prompt("Minutes from now to start")
		preshow_secondsLeft = parseFloat(minutes) * 60
		toggleFooter()
		$.getJSON("preshow_files", false, function(data) {
			$('#preso').after("

")
			$.each(data, function(i, n) {
				if(n == "preshow.json") {
					// has a descriptions file
					$.getJSON("/file/_preshow/preshow.json", false, function(data) {
						preshow_des = data
					})
				} else {
					$('#preshow').append('')
				}
			})
			startPreShow()
		})
	}
}

function startPreShow() {
  if (!preshow_running) {
    preshow_running = true
    preshow_seconds = 0
    preshow_images = $('#preshow > img')
    preshow_imagesTotal = preshow_images.size()
    nextPreShowImage()

    if(!preshow_timerRunning) {
      setInterval(function() {
        preshow_timerRunning = true
        if (!preshow_running) { return }
        preshow_seconds++
        preshow_secondsLeft--
		if (preshow_secondsLeft < 0) {
			stopPreShow()
		}
        if (preshow_seconds == preshow_secondsPer) {
          preshow_seconds = 0
          nextPreShowImage()
        }
		addPreShowTips()
      }, 1000)
    }
  }
}

function addPreShowTips() {
	time = secondsToTime(preshow_secondsLeft)
	$('#preshow_timer').text(time + ' to go-time')
	var des = preshow_des[tmpImg.attr("ref")]
	if(des) {
		$('#tips').show()
		$('#tips').text(des)
	} else {
		$('#tips').hide()
	}
}

function secondsToTime(sec) {
	min = Math.floor(sec / 60)
	sec = sec - (min * 60)
	if(sec < 10) {
		sec = "0" + sec
	}
	return min + ":" + sec
}

function stopPreShow() {
	preshow_running = false

	$('#preshow').remove()
	$('#tips').remove()
	$('#preshow_timer').remove()

	toggleFooter()
	loadSlides(loadSlidesBool, loadSlidesPrefix);
}

function nextPreShowImage() {
	preshow_current += 1
	if((preshow_current + 1) > preshow_imagesTotal) {
		preshow_current = 0
	}

	$("#preso").empty()
	tmpImg = preshow_images.eq(preshow_current).clone()
	$(tmpImg).attr('width', '1020')
	$("#preso").html(tmpImg)
}

/********************
 End PreShow Code
 ********************/
<commit_msg>Fixes vertical centering.<commit_after>/* ShowOff JS Logic */

var ShowOff = {};

var preso_started = false
var slidenum = 0
var slideTotal = 0
var slides
var currentSlide
var totalslides = 0
var slidesLoaded = false
var incrSteps = 0
var incrElem
var incrCurr = 0
var incrCode = false
var debugMode = false
var gotoSlidenum = 0
var shiftKeyActive = false

var loadSlidesBool
var loadSlidesPrefix

function setupPreso(load_slides, prefix) {
  if (preso_started)
  {
     alert("already started")
     return
  }
  preso_started = true

  loadSlidesBool = load_slides
  loadSlidesPrefix = prefix
  loadSlides(loadSlidesBool, loadSlidesPrefix)

  doDebugStuff()

  // bind event handlers
  document.onkeydown = keyDown
  document.onkeyup = keyUp
  /* window.onresize  = resized; */
  /* window.onscroll = scrolled; */
  /* window.onunload = unloaded; */
}

function loadSlides(load_slides, prefix) {
  //load slides offscreen, wait for images and then initialize
  if (load_slides) {
  	$("#slides").load("/slides", false, function(){
    	$("#slides img").batchImageLoad({
			loadingCompleteCallback: initializePresentation(prefix)
		})
  	})
  } else {
	$("#slides img").batchImageLoad({
		loadingCompleteCallback: initializePresentation(prefix)
	})
  }
}

function initializePresentation(prefix) {
  $("#slides").show();

  //center slides offscreen
  centerSlides($('#slides > .slide'))

  //copy into presentation area
  $("#preso").empty()
  $('#slides > .slide').appendTo($("#preso"))

  //populate vars
  slides = $('#preso > .slide')
  slideTotal = slides.size()

  //setup manual jquery cycle
  $('#preso').cycle({
    timeout: 0
  })

  setupMenu()
  if (slidesLoaded) {
    showSlide()
  } else {
    showFirstSlide();
    slidesLoaded = true
  }
  setupSlideParamsCheck();
  sh_highlightDocument(prefix+'/js/sh_lang/', '.min.js')
}

function centerSlides(slides) {
  slides.each(function(s, slide) {
    centerSlide(slide)
  })
}

function centerSlide(slide) {
  var slide_content = $(slide).children(".content").first()
  var height = slide_content.height()
  var mar_top = (0.5 * parseFloat($(slide).height())) - (0.5 * parseFloat(height))
  if (mar_top < 0) {
    mar_top = 0
  }
  slide_content.css('margin-top', mar_top)
}

function setupMenu() {
  $('#navmenu').hide();

  var currSlide = 0
  var menu = new ListMenu()

  slides.each(function(s, elem) {
    content = $(elem).children(".content")
    shortTxt = $(content).text().substr(0, 20)
    path = $(content).attr('ref').split('/')
    currSlide += 1
    menu.addItem(path, shortTxt, currSlide)
  })

  $('#navigation').html(menu.getList())
  $('#navmenu').menu({
    content: $('#navigation').html(),
    flyOut: true
  });
}

function checkSlideParameter() {
  if (slideParam = currentSlideFromParams()) {
    slidenum = slideParam;
  }
}

function currentSlideFromParams() {
  var result;
  if (result = window.location.hash.match(/#([0-9]+)/)) {
    return result[result.length - 1] - 1;
  }
}

function setupSlideParamsCheck() {
  var check = function() {
    var currentSlide = currentSlideFromParams();
    if (slidenum != currentSlide) {
      slidenum = currentSlide;
      showSlide();
    }
    setTimeout(check, 100);
  }
  setTimeout(check, 100);
}

function gotoSlide(slideNum) {
  slidenum = parseInt(slideNum)
  if (!isNaN(slidenum)) {
    showSlide()
  }
}

function showFirstSlide() {
  slidenum = 0
  checkSlideParameter();
  showSlide()
}

function showSlide(back_step) {

  if(slidenum < 0) {
    slidenum = 0
    return
  }

  if(slidenum > (slideTotal - 1)) {
    slidenum = slideTotal - 1
    return
  }

  currentSlide = slides.eq(slidenum)

  var transition = currentSlide.attr('data-transition')
  var fullPage = currentSlide.find(".content").is('.full-page');

  if (back_step || fullPage) {
    transition = 'none'
  }

  $('#preso').cycle(slidenum, transition)

  if (fullPage) {
    $('#preso').css({'width' : '100%', 'overflow' : 'visible'});
    currentSlide.css({'width' : '100%', 'text-align' : 'center', 'overflow' : 'visible'});
  } else {
    $('#preso').css({'width' : '1020px', 'overflow' : 'hidden'});
  }

  percent = getSlidePercent()
  $("#slideInfo").text((slidenum + 1) + '/' + slideTotal + '  - ' + percent + '%')

  if(!back_step) {
    // determine if there are incremental bullets to show
    // unless we are moving backward
    determineIncremental()
  } else {
    incrCurr = 0
    incrSteps = 0
  }
  location.hash = slidenum + 1;
  $('body').addSwipeEvents().
    bind('swipeleft',  swipeLeft).
    bind('swiperight', swipeRight)
  removeResults()

  $(currentSlide).find(".content").trigger("showoff:show");

  return getCurrentNotes()
}

function getSlideProgress()
{
  return (slidenum + 1) + '/' + slideTotal
}

function getCurrentNotes()
{
  return currentSlide.find("p.notes").text()
}

function getSlidePercent()
{
  return Math.ceil(((slidenum + 1) / slideTotal) * 100)
}

function determineIncremental()
{
  incrCurr = 0
  incrCode = false
  incrElem = currentSlide.find(".incremental > ul > li")
  incrSteps = incrElem.size()
  if(incrSteps == 0) {
    // also look for commandline
    incrElem = currentSlide.find(".incremental > pre > code > code")
    incrSteps = incrElem.size()
    incrCode = true
  }
  incrElem.each(function(s, elem) {
    $(elem).hide()
  })
}

function prevStep()
{

  var event = jQuery.Event("showoff:prev");
  $(currentSlide).find(".content").trigger(event);
  if (event.isDefaultPrevented()) {
      return;
  }

  slidenum--
  return showSlide(true) // We show the slide fully loaded
}

function nextStep()
{
  var event = jQuery.Event("showoff:next");
  $(currentSlide).find(".content").trigger(event);
  if (event.isDefaultPrevented()) {
      return;
  }

  if (incrCurr >= incrSteps) {
    slidenum++
    return showSlide()
  } else {
    elem = incrElem.eq(incrCurr)
    if (incrCode && elem.hasClass('command')) {
      incrElem.eq(incrCurr).show().jTypeWriter({duration:1.0})
    } else {
      incrElem.eq(incrCurr).show()
    }
    incrCurr++
  }
}

function doDebugStuff()
{
  if (debugMode) {
    $('#debugInfo').show()
    debug('debug mode on')
  } else {
    $('#debugInfo').hide()
  }
}

function debug(data)
{
  $('#debugInfo').text(data)
}

//  See e.g. http://www.quirksmode.org/js/keys.html for keycodes
function keyDown(event)
{
    var key = event.keyCode;

    if (event.ctrlKey || event.altKey || event.metaKey)
       return true;

    debug('keyDown: ' + key)

    if (key >= 48 && key <= 57) // 0 - 9
    {
      gotoSlidenum = gotoSlidenum * 10 + (key - 48);
      return true;
    }

    if (key == 13){
        if (gotoSlidenum > 0) {
            debug('go to ' + gotoSlidenum);
            slidenum = gotoSlidenum - 1;
            showSlide(true);
            gotoSlidenum = 0;
        } else {
            debug('executeCode');
            executeCode.call($('.sh_javaScript code:visible'));
        }

    }

    if (key == 16) // shift key
    {
      shiftKeyActive = true;
    }
    if (key == 32) // space bar
    {
      if (shiftKeyActive) { prevStep() }
      else                { nextStep() }
    }
    else if (key == 68) // 'd' for debug
    {
      debugMode = !debugMode
      doDebugStuff()
    }
    else if (key == 37 || key == 33 || key == 38) // Left arrow, page up, or up arrow
    {
      prevStep()
    }
    else if (key == 39 || key == 34 || key == 40) // Right arrow, page down, or down arrow
    {
      nextStep()
    }
    else if (key == 82) // R for reload
    {
      if (confirm('really reload slides?')) {
        loadSlides(loadSlidesBool, loadSlidesPrefix)
        showSlide()
      }
    }
    else if (key == 84 || key == 67)  // T or C for table of contents
    {
      $('#navmenu').toggle().trigger('click')
    }
    else if (key == 90) // z for help
    {
      $('#help').toggle()
    }
    else if (key == 66 || key == 70) // f for footer (also "b" which is what kensington remote "stop" button sends
    {
      toggleFooter()
    }
	else if (key == 27) // esc
	{
		removeResults();
	}
	else if (key == 80) // 'p' for preshow
	{
		runPreShow();
	}
    return true
}

function toggleFooter()
{
  $('#footer').toggle()
}

function keyUp(event) {
  var key = event.keyCode;
  debug('keyUp: ' + key);
  if (key == 16) // shift key
  {
    shiftKeyActive = false;
  }
}

function swipeLeft() {
  nextStep()
}

function swipeRight() {
  prevStep()
}

function ListMenu(s)
{
  this.slide = s
  this.typeName = 'ListMenu'
  this.itemLength = 0;
  this.items = new Array();
  this.addItem = function (key, text, slide) {
    if (key.length > 1) {
      thisKey = key.shift()
      if (!this.items[thisKey]) {
        this.items[thisKey] = new ListMenu(slide)
      }
      this.items[thisKey].addItem(key, text, slide)
    } else {
      thisKey = key.shift()
      this.items[thisKey] = new ListMenuItem(text, slide)
    }
  }
  this.getList = function() {
    var newMenu = $("
")
    for(var i in this.items) {
      var item = this.items[i]
      var domItem = $("
")
      if (item.typeName == 'ListMenu') {
        choice = $("" + i + "")
        domItem.append(choice)
        domItem.append(item.getList())
      }
      if (item.typeName == 'ListMenuItem') {
        choice = $("" + item.slide + '. ' + item.textName + "")
        domItem.append(choice)
      }
      newMenu.append(domItem)
    }
    return newMenu
  }
}

function ListMenuItem(t, s)
{
  this.typeName = "ListMenuItem"
  this.slide = s
  this.textName = t
}

var removeResults = function() {
  $('.results').remove();
};

var print = function(text) {
  removeResults();
  var _results = $('
').addClass('results').html($.print(text, {max_string:500}));
  $('body').append(_results);
  _results.click(removeResults);
};

function executeCode () {
    result = null;
    var codeDiv = $(this);
    codeDiv.addClass("executing");
    eval(codeDiv.text());
    setTimeout(function() { codeDiv.removeClass("executing");}, 250 );
    if (result != null) print(result);
}
$('.sh_javaScript code').live("click", executeCode);

/********************
 PreShow Code
 ********************/

var preshow_seconds = 0;
var preshow_secondsLeft = 0;
var preshow_secondsPer = 8;
var preshow_running = false;
var preshow_timerRunning = false;
var preshow_current = 0;
var preshow_images;
var preshow_imagesTotal = 0;
var preshow_des;

function runPreShow() {
	if(preshow_running) {
		stopPreShow()
	} else {
		var minutes = prompt("Minutes from now to start")
		preshow_secondsLeft = parseFloat(minutes) * 60
		toggleFooter()
		$.getJSON("preshow_files", false, function(data) {
			$('#preso').after("

")
			$.each(data, function(i, n) {
				if(n == "preshow.json") {
					// has a descriptions file
					$.getJSON("/file/_preshow/preshow.json", false, function(data) {
						preshow_des = data
					})
				} else {
					$('#preshow').append('')
				}
			})
			startPreShow()
		})
	}
}

function startPreShow() {
  if (!preshow_running) {
    preshow_running = true
    preshow_seconds = 0
    preshow_images = $('#preshow > img')
    preshow_imagesTotal = preshow_images.size()
    nextPreShowImage()

    if(!preshow_timerRunning) {
      setInterval(function() {
        preshow_timerRunning = true
        if (!preshow_running) { return }
        preshow_seconds++
        preshow_secondsLeft--
		if (preshow_secondsLeft < 0) {
			stopPreShow()
		}
        if (preshow_seconds == preshow_secondsPer) {
          preshow_seconds = 0
          nextPreShowImage()
        }
		addPreShowTips()
      }, 1000)
    }
  }
}

function addPreShowTips() {
	time = secondsToTime(preshow_secondsLeft)
	$('#preshow_timer').text(time + ' to go-time')
	var des = preshow_des[tmpImg.attr("ref")]
	if(des) {
		$('#tips').show()
		$('#tips').text(des)
	} else {
		$('#tips').hide()
	}
}

function secondsToTime(sec) {
	min = Math.floor(sec / 60)
	sec = sec - (min * 60)
	if(sec < 10) {
		sec = "0" + sec
	}
	return min + ":" + sec
}

function stopPreShow() {
	preshow_running = false

	$('#preshow').remove()
	$('#tips').remove()
	$('#preshow_timer').remove()

	toggleFooter()
	loadSlides(loadSlidesBool, loadSlidesPrefix);
}

function nextPreShowImage() {
	preshow_current += 1
	if((preshow_current + 1) > preshow_imagesTotal) {
		preshow_current = 0
	}

	$("#preso").empty()
	tmpImg = preshow_images.eq(preshow_current).clone()
	$(tmpImg).attr('width', '1020')
	$("#preso").html(tmpImg)
}

/********************
 End PreShow Code
 ********************/
<|endoftext|>


<commit_before>// requires canvassify, mathtex

$(function(){
  $('#spinner').show();

  // Canvas
  var c = $.canvassify('#tafel');

  var symbols;
  var filter = '';
  var latex_classifier = new Detexify({ baseuri: '/' });

  var localesort = function(a,b){ return (''+a).localeCompare(''+b); }
  var alphasort = function(a,b){ return localesort(a.command, b.command); }
  var packagesort = function(a,b) {
    if (a.package === b.package) {
      return alphasort(a, b);
    } else {
      return localesort(a.package, b.package);
    }
  }
  var samplesort = function(a,b){ return (a.samples - b.samples); }

  function colorcode(num) {
    var n = parseInt($(num).text());
    if (n < 26) {
      $(num).css('color','rgb('+(255-n*10)+','+(n*10)+',0)');
    } else {
      $(num).css('color','green');
    }
  }

  var filtered = function(symbols) {
    // only show dem with package or command matching filter
    if (filter === '') return symbols;
    return $.grep(symbols, function(symbol, index){
      return (symbol.package && symbol.package.match(filter)) || symbol.command.match(filter);
    });
  }

  var populateSymbolListWrapper = function(symbols) {
    // secure the trainingarea
    $('#trainingarea').appendTo($('#safespot'));
    populateSymbolList(filtered(symbols));
    // color code training numbers
    // var num = $('#symbols li .info .samples .number').each(function(){
    //   colorcode(this);
    // });
    // setup training
    $('#symbols li')
    //$('#symbols li .symbol img')
    //.wrap('')
    .css('cursor', 'pointer')
    .tooltip({ tip: '#traintip' })
    .click(function(){
      $(this).tooltip(0).hide();
      if ($('#trainingli').is(":hidden")) {
        c.clear();
        $("#drawhere").show();
        $('#trainingli').prev().removeClass('active');
        $('#trainingli').insertAfter($(this).closest("li")).slideDown('slow');
        $('#trainingli').prev().addClass('active');
      } else {
        var that = this;
        $('#trainingli').prev().removeClass('active');
        $('#trainingli').slideUp('slow', function(){
          c.clear();
          $("#drawhere").show();
          $(this).insertAfter($(that).closest("li")).slideDown('slow');
          $('#trainingli').prev().addClass('active');
        });
      }
      return false;
    });

    // push the canvas inside the symbol list
    $('#trainingarea').appendTo('#symbols').wrap('

').show();
  }

  function positionUpLink() {
    $('#up').css({
      'position': 'fixed',
      'top'     : $(window).height()-$('#up').outerHeight()-10,
      'left'    : $('#everything').offset().left+560
    });
  }

  $(window).resize(positionUpLink);

  $('#sort').change(function(){
    switch ($(this).val()) {
      case 'alpha':
      symbols.sort(alphasort);
      break;
      case 'samples':
      symbols.sort(samplesort);
      break;
      case 'package':
      symbols.sort(packagesort);
      break;
    }
    populateSymbolListWrapper(symbols);
  });

  $.getJSON("/symbols", function(json) {
    symbols = json;
    symbols.sort(alphasort);
    populateSymbolListWrapper(symbols);
    $('#spinner').hide();
    positionUpLink();
  });

  jQuery.fn.handleKeyboardChange = function(nDelay)
  {
    // Utility function to test if a keyboard event should be ignored
    function shouldIgnore(event)
    {
      var mapIgnoredKeys = {
        9:true, // Tab
        16:true, 17:true, 18:true, // Shift, Alt, Ctrl
        37:true, 38:true, 39:true, 40:true, // Arrows
        91:true, 92:true, 93:true // Windows keys
      };
      return mapIgnoredKeys[event.which];
    }

    // Utility function to fire OUR change event if the value was actually changed
    function fireChange($element)
    {
      if( $element.val() != jQuery.data($element[0], "valueLast") )
      {
        jQuery.data($element[0], "valueLast", $element.val())
        $element.trigger("change");
      }
    }

    // The currently running timeout,
    // will be accessed with closures
    var timeout = 0;

    // Utility function to cancel a previously set timeout
    function clearPreviousTimeout()
    {
      if( timeout )
      {
        clearTimeout(timeout);
      }
    }

    return this
    .keydown(function(event)
    {
      if( shouldIgnore(event) ) return;
      // User pressed a key, stop the timeout for now
      clearPreviousTimeout();
      return null;
    })
    .keyup(function(event)
    {
      if( shouldIgnore(event) ) return;
      // Start a timeout to fire our event after some time of inactivity
      // Eventually cancel a previously running timeout
      clearPreviousTimeout();
      var $self = $(this);
      timeout = setTimeout(function(){ fireChange($self) }, nDelay);
    })
    .change(function()
    {
      // Fire a change
      // Use our function instead of just firing the event
      // Because we want to check if value really changed since
      // our previous event.
      // This is for when the browser fires the change event
      // though we already fired the event because of the timeout
      fireChange($(this));
    })
    ;
  }

  $('#filter').handleKeyboardChange(300).change(function(){
    filter = $(this).val();
    populateSymbolListWrapper(symbols);
  });

  // Train if train button pressed
  var trainClicked = function() {
    $.gritter.add({title:'Thanks!', text:'Thank you for training!', time: 1000})
    // get the previous li's
    id = $(this).closest("li").prev().attr('id');
    num = $(this).closest("li").prev().find('.info .samples .number');
    $('#canvasspinner').show('scale');
    latex_classifier.train(id, c.strokes, function(json){
      num.text(parseInt(num.text())+1);
      colorcode(num);
      $('#canvasspinner').hide('scale');
      // TODO DRY
      if (json.message) {
        $.gritter.add({title:'Success!', text: json.message, time: 1000});
      } else {
        $.gritter.add({title:'Error!', text: json.error, time: 1000});
      }
    });
    // TODO Buttons ausgrauen solange Request $('...').ubind('click', fn);
    c.clear();
    // c.block();
    return false;
  }
  $('#train').click(trainClicked);
  $('#clear').click(function(){
    c.clear();
    return false;
  });
  $('#trainingarea').mouseenter(function(){$("#drawhere").fadeOut("slow");});

  $("#canvaserror").hide();

});<commit_msg>work around not sorting ;|<commit_after>// requires canvassify, mathtex

$(function(){
  $('#spinner').show();

  // Canvas
  var c = $.canvassify('#tafel');

  var symbols = [];
  var filter = "";
  var latex_classifier = new Detexify({ baseuri: '/' });

  var localesort = function(a,b){ return (''+a).localeCompare(''+b); }
  var alphasort = function(a,b){ return localesort(a.command, b.command); }
  var packagesort = function(a,b) {
    if (a.package === b.package) {
      return alphasort(a, b);
    } else {
      return localesort(a.package, b.package);
    }
  }
  var samplesort = function(a,b){ return (a.samples - b.samples); }

  function colorcode(num) {
    var n = parseInt($(num).text());
    if (n < 26) {
      $(num).css('color','rgb('+(255-n*10)+','+(n*10)+',0)');
    } else {
      $(num).css('color','green');
    }
  }

  var filtered = function(symbols) {
    // only show dem with package or command matching filter
    if (filter === '') return symbols;
    return $.grep(symbols, function(symbol, index){
      return (symbol.package && symbol.package.match(filter)) || symbol.command.match(filter);
    });
  }

  var populateSymbolListWrapper = function(symbols) {
    // secure the trainingarea
    $('#trainingarea').appendTo($('#safespot'));
    populateSymbolList(filtered(symbols));
    // color code training numbers
    // var num = $('#symbols li .info .samples .number').each(function(){
    //   colorcode(this);
    // });
    // setup training
    $('#symbols li')
    //$('#symbols li .symbol img')
    //.wrap('')
    .css('cursor', 'pointer')
    .tooltip({ tip: '#traintip' })
    .click(function(){
      $(this).tooltip(0).hide();
      if ($('#trainingli').is(":hidden")) {
        c.clear();
        $("#drawhere").show();
        $('#trainingli').prev().removeClass('active');
        $('#trainingli').insertAfter($(this).closest("li")).slideDown('slow');
        $('#trainingli').prev().addClass('active');
      } else {
        var that = this;
        $('#trainingli').prev().removeClass('active');
        $('#trainingli').slideUp('slow', function(){
          c.clear();
          $("#drawhere").show();
          $(this).insertAfter($(that).closest("li")).slideDown('slow');
          $('#trainingli').prev().addClass('active');
        });
      }
      return false;
    });

    // push the canvas inside the symbol list
    $('#trainingarea').appendTo('#symbols').wrap('

').show();
  }

  function positionUpLink() {
    $('#up').css({
      'position': 'fixed',
      'top'     : $(window).height()-$('#up').outerHeight()-10,
      'left'    : $('#everything').offset().left+560
    });
  }

  $(window).resize(positionUpLink);

  $('#sort').change(function(){
    switch ($(this).val()) {
      case 'alpha':
      symbols.sort(alphasort);
      break;
      case 'samples':
      symbols.sort(samplesort);
      break;
      case 'package':
      symbols.sort(packagesort);
      break;
    }
    populateSymbolListWrapper(symbols);
  });

  jQuery.fn.handleKeyboardChange = function(nDelay)
  {
    // Utility function to test if a keyboard event should be ignored
    function shouldIgnore(event)
    {
      var mapIgnoredKeys = {
        9:true, // Tab
        16:true, 17:true, 18:true, // Shift, Alt, Ctrl
        37:true, 38:true, 39:true, 40:true, // Arrows
        91:true, 92:true, 93:true // Windows keys
      };
      return mapIgnoredKeys[event.which];
    }

    // Utility function to fire OUR change event if the value was actually changed
    function fireChange($element)
    {
      if( $element.val() != jQuery.data($element[0], "valueLast") )
      {
        jQuery.data($element[0], "valueLast", $element.val())
        $element.trigger("change");
      }
    }

    // The currently running timeout,
    // will be accessed with closures
    var timeout = 0;

    // Utility function to cancel a previously set timeout
    function clearPreviousTimeout()
    {
      if( timeout )
      {
        clearTimeout(timeout);
      }
    }

    return this
    .keydown(function(event)
    {
      if( shouldIgnore(event) ) return;
      // User pressed a key, stop the timeout for now
      clearPreviousTimeout();
      return null;
    })
    .keyup(function(event)
    {
      if( shouldIgnore(event) ) return;
      // Start a timeout to fire our event after some time of inactivity
      // Eventually cancel a previously running timeout
      clearPreviousTimeout();
      var $self = $(this);
      timeout = setTimeout(function(){ fireChange($self) }, nDelay);
    })
    .change(function()
    {
      // Fire a change
      // Use our function instead of just firing the event
      // Because we want to check if value really changed since
      // our previous event.
      // This is for when the browser fires the change event
      // though we already fired the event because of the timeout
      fireChange($(this));
    })
    ;
  }

  $('#filter').handleKeyboardChange(300).change(function(){
    filter = $(this).val();
    populateSymbolListWrapper(symbols);
  });

  // Train if train button pressed
  var trainClicked = function() {
    $.gritter.add({title:'Thanks!', text:'Thank you for training!', time: 1000})
    // get the previous li's
    id = $(this).closest("li").prev().attr('id');
    num = $(this).closest("li").prev().find('.info .samples .number');
    $('#canvasspinner').show('scale');
    latex_classifier.train(id, c.strokes, function(json){
      num.text(parseInt(num.text())+1);
      colorcode(num);
      $('#canvasspinner').hide('scale');
      // TODO DRY
      if (json.message) {
        $.gritter.add({title:'Success!', text: json.message, time: 1000});
      } else {
        $.gritter.add({title:'Error!', text: json.error, time: 1000});
      }
    });
    // TODO Buttons ausgrauen solange Request $('...').ubind('click', fn);
    c.clear();
    // c.block();
    return false;
  }
  $('#train').click(trainClicked);
  $('#clear').click(function(){
    c.clear();
    return false;
  });
  $('#trainingarea').mouseenter(function(){$("#drawhere").fadeOut("slow");});

  $("#canvaserror").hide();

  $.getJSON("/symbols", function(json) {
    symbols = json;
    symbols.sort(alphasort);
    populateSymbolListWrapper(symbols);
    //second time to make it work. This is an ugly workaround
    symbols.sort(alphasort);
    populateSymbolListWrapper(symbols);
    $('#spinner').hide();
    positionUpLink();
  });

});<|endoftext|>


<commit_before>var id;
var array;
var game;
var newTables;
var push = true;
var timeLock = false;
var lockTimer;
var lock = false;
var lockEnd = false;

function sync_sv() {
    socket.emit("get seated players");
    socket.on("chrono", function(i, str) {
        $("#chrono").html(str + '
' + i + ' sec remaining
to add more players');
        var chrono = setInterval(function() {
            i--;
            $("#sec").html(i);
            if (i == 0) {
                clearInterval(chrono);
            }
        }, 1000);
    });
    socket.on("chrono off", function() {
        $("#chrono").empty();
    });
    socket.on("action is true", function() {
        console.log('timeLock est true');
        timeLock = true;
    });
    socket.on("timer action", function(table) {
        var sec = 0;

		clearInterval(lockTimer);
    	lockTimer = setInterval(function() {
            sec++;
			console.log('secondes '+sec);
            if (timeLock && sec != 30) {
				sec = 0
                clearInterval(lockTimer);
                timeLock = false;
            } else if (sec == 30) {
                sec = 0;
                timeLock = false;
                socket.emit("stop timer action", table);
				clearInterval(lockTimer);
            }
        }, 1000);
    });
    socket.on("seated players info", function(seat, seat_idx) {
        $("#qr" + seat_idx).css("visibility", "hidden");
        $("#qr_spot" + seat_idx).css("visibility", "hidden");
        $("#scan_msg" + seat_idx).css("visibility", "hidden");
        $("#player_name" + seat_idx).css("visibility", "visible");
        $("#player_name" + seat_idx).text(seat.player.nickname);
        $("#player_bankroll" + seat_idx).css("visibility", "visible");
        $("#player_bankroll" + seat_idx).text((Math.floor(+seat.player.bankroll * 100)) / 100 + "$");
        $("#player_cards" + seat_idx).css("visibility", "visible");
    });
    socket.on("new player", function(player) {
        $("#qr" + player.seat_nb).css("visibility", "hidden");
        $("#qr_spot" + player.seat_nb).css("visibility", "hidden");
        $("#scan_msg" + player.seat_nb).css("visibility", "hidden");
        $("#player_name" + player.seat_nb).css("visibility", "visible");
        $("#player_name" + player.seat_nb).text(player.nickname);
        $("#player_bankroll" + player.seat_nb).css("visibility", "visible");
        $("#player_bankroll" + player.seat_nb).text((Math.floor(+player.bankroll * 100)) / 100 + "$");
        $("#player_cards" + player.seat_nb).css("visibility", "visible");
    });
    socket.on("kick player", function(seat_nb) {
        $("#qr" + seat_nb).css("visibility", "visible");
        $("#qr_spot" + seat_nb).css("visibility", "visible");
        $("#scan_msg" + seat_nb).css("visibility", "visible");
        $("#player_name" + seat_nb).css("visibility", "hidden");
        $("#player_name" + seat_nb).text("");
        $("#player_bankroll" + seat_nb).css("visibility", "hidden");
        $("#player_bankroll" + seat_nb).text("");
        $("#player_cards" + seat_nb).css("visibility", "hidden");
        $("#btn" + seat_nb).attr("src", "");
        $("#btn" + seat_nb).css("visibility", "hidden");
        $("#card1_" + seat_nb).css("visibility", "hidden");
        $("#card2_" + seat_nb).css("visibility", "hidden");
        $("#last_action" + seat_nb).css("visibility", "hidden");
    });
    socket.emit("ask buttons");
    socket.on("place button", function(type, seat_nb) {
        if (seat_nb <= 0 || seat_nb >= 7)
            return;
        if (type == "dealer") {
            $("#btn" + seat_nb).attr("src", "../img/Dealer.png")
            $("#btn" + seat_nb).css("visibility", "visible");
        } else if (type == "sb") {
            $("#btn" + seat_nb).attr("src", "../img/sb.png")
            $("#btn" + seat_nb).css("visibility", "visible");
        } else if (type == "bb") {
            $("#btn" + seat_nb).attr("src", "../img/bb.png")
            $("#btn" + seat_nb).css("visibility", "visible");
        }
        $("#player_cards" + seat_nb).attr("src", "../img/hidden_cards.png");
    });
    socket.on("give cards", function(seat_nb) {
        $("#player_cards" + seat_nb).attr("src", "../img/hidden_cards.png");
    });
    socket.on("highlights", function(seat_idx, new_state) {
        var pos = $("#hSeat" + seat_idx);
        var idx;
        var pos_idx;

        if (new_state == "off") {
            for (idx = 1; idx <= 6; idx++) {
                pos_idx = $("#hSeat" + idx);
                pos_idx.hide();
                pos_idx.stop();
                pos_idx.css("width", "100%");
            }
        } else if (new_state == "on") {
            pos.show();
            pos.css("background-color", "#FE554C");
            pos.animate({
                "width": "0%"
            }, 31000);
        }
    });
    socket.on("i fold", function(decision, private_ids, zero) {
        socket.emit("player decision", decision, private_ids, zero);
    })
    socket.on("bankroll modification", function(seat_idx, player) {
        if (player.bankroll == "ALL IN")
            $("#player_bankroll" + seat_idx).text("ALL IN");
        else
            $("#player_bankroll" + seat_idx).text((Math.floor(player.bankroll * 100)) / 100 + "$");
    });
    socket.on("pot modification", function(pot_amount) {
        $("#pot").text(Math.floor(+pot_amount * 100) / 100 + "$");
    });
    socket.on("bet", function(seat_idx, amount) {
        if (!amount)
            $("#last_action" + seat_idx).text('');
        else {
            $("#last_action" + seat_idx).text((Math.floor(amount * 100)) / 100 + "$");
        }
    });

    socket.on("last action", function(decision, seat_nb, amount) {
        amount == 0 ? amount = "" : amount = " " + amount + "$";
        var nick = $("#player_name" + seat_nb).text();
        var str = decision.split(" ");
        var text = "
" + nick + " " + str[0] + amount + "
";

        $("#last_action").text(nick + " " + str[0] + amount);
        $("#histoContent").empty();
        $("#histoContent").append(text);
    });
    socket.on("fold", function(seat_nb) {
        $("#seat" + seat_nb).css('opacity', '0.3');
        $("#btn" + seat_nb).css("visibility", "hidden");
        $("#bet_val" + seat_nb).text('');
        $("#player_cards" + seat_nb).attr("src", "../img/avatar.png");
        $("#last_action" + seat_nb).text('FOLD');
    });
    socket.on("fold off", function() {
        var id;

        for (id = 1; id <= 6; id++) {
            $("#seat" + id).css('opacity', '1');
            $("#hSeat" + id).hide();
        }
    });
    socket.emit("get board");
    socket.on("send flop", function(card1, card2, card3) {
        $("#b1").attr("src", "img/cards/" + card1 + ".png");
        $("#b2").attr("src", "img/cards/" + card2 + ".png");
        $("#b3").attr("src", "img/cards/" + card3 + ".png");
        $("#b1, #b2, #b3").css("visibility", "visible");
    });
    socket.on("send turn", function(card4) {
        $("#b4").attr("src", "img/cards/" + card4 + ".png");
        $("#b4").css("visibility", "visible");
    });
    socket.on("send river", function(card5) {
        $("#b5").attr("src", "img/cards/" + card5 + ".png");
        $("#b5").css("visibility", "visible");
    });
    socket.on("remove last actions", function() {
        for (var idx = 1; idx <= 6; ++idx)
            $("#last_action" + idx).remove();
    });
    socket.on("remove board", function() {
        $("#b1, #b2, #b3, #b4, #b5").css("visibility", "hidden");
        for (var idx = 1; idx <= 6; ++idx)
            $("#player_cards" + idx).attr("src", "../img/avatar.png");
        $("#last_action").text('');
    });
    socket.on("remove emplacements", function() {
        for (var idx = 1; idx <= 6; ++idx)
            $("#btn" + idx).css("visibility", "hidden");
    });
    socket.on("show down", function(card1, card2, seat_nb) {
        if ($('#qr_spot' + seat_nb).css('visibility') == 'hidden') {
            if (card1 != -1 && card2 != -1) {
                $("#card1_" + seat_nb).attr("src", "../img/cards/" + card1 + ".png");
                $("#card2_" + seat_nb).attr("src", "../img/cards/" + card2 + ".png");
                $("#card1_" + seat_nb).css("visibility", "visible");
                $("#card2_" + seat_nb).css("visibility", "visible");
            } else {
                $("#card1_" + seat_nb).css("visibility", "hidden");
                $("#card2_" + seat_nb).css("visibility", "hidden");
            }
        }
    });
    socket.on("show down off", function(seat_nb) {
        $("#card1_" + seat_nb).css("visibility", "hidden");
        $("#card2_" + seat_nb).css("visibility", "hidden");
    });
    socket.on("winner", function(seat_nb, rank_name) {
        var disconnect = '
' + $("#player_name" + seat_nb).text() + ' won because player ' + rank_name + ' or folded
';
        var won = '
' + $("#player_name" + seat_nb).text() + ' won with ' + rank_name + '
';

        if (rank_name == "null")
            return;
        if (rank_name == 'disconnected') {
            $('#histoContent').empty();
            $('#histoContent').append(disconnect);
        } else if (seat_nb == 42 && rank_name == 'null') {
            $('#histoContent').empty();
            $('#histoContent').append('
Split !
');
        } else {
            $('#histoContent').empty();
            $('#histoContent').append(won);
        }
    });
    socket.on("win off", function() {
        $("#winner, #card1_1, #card2_1, #card1_2, #card2_2, #card1_3, #card2_3, #card1_4, #card2_4, #card1_5, #card2_5, #card1_6, #card2_6").css("visibility", "hidden");
    });
    socket.on("what is lock", function() {
        socket.emit("lock is true or false", lock);
    });
    socket.on("lock is true", function(vrai) {
        lock = vrai;
    })
    socket.on("lock is false", function(faux) {
        lock = faux;
    })
    socket.on("what is lock end", function(table, game) {
        socket.emit("lock is true or false end", lockEnd, table, game);
    });
    socket.on("lock is true end", function(vrai) {
        lockEnd = vrai;
    })
    socket.on("lock is false end", function(faux) {
        lockEnd = faux;
    })
}

function check_timeLock(action) {
    timeLock = action;
}
<commit_msg>test<commit_after>var id;
var array;
var game;
var newTables;
var push = true;
var timeLock = false;
var lockTimer;
var lock = false;
var lockEnd = false;

function sync_sv() {
    socket.emit("get seated players");
    socket.on("chrono", function(i, str) {
        $("#chrono").html(str + '
' + i + ' sec remaining
to add more players');
        var chrono = setInterval(function() {
            i--;
            $("#sec").html(i);
            if (i == 0) {
                clearInterval(chrono);
            }
        }, 1000);
    });
    socket.on("chrono off", function() {
        $("#chrono").empty();
    });
    socket.on("action is true", function() {
        console.log('timeLock est true');
        timeLock = true;
    });
    socket.on("timer action", function(table) {
        var sec = 0;

    	lockTimer = setInterval(function() {
            sec++;
			console.log('secondes '+sec);
            if (timeLock && sec != 30) {
				sec = 0
                clearInterval(lockTimer);
                timeLock = false;
            } else if (sec == 30) {
                sec = 0;
                timeLock = false;
                socket.emit("stop timer action", table);
				clearInterval(lockTimer);
				clearInterval(lockTimer);
            }
        }, 1000);
    });
    socket.on("seated players info", function(seat, seat_idx) {
        $("#qr" + seat_idx).css("visibility", "hidden");
        $("#qr_spot" + seat_idx).css("visibility", "hidden");
        $("#scan_msg" + seat_idx).css("visibility", "hidden");
        $("#player_name" + seat_idx).css("visibility", "visible");
        $("#player_name" + seat_idx).text(seat.player.nickname);
        $("#player_bankroll" + seat_idx).css("visibility", "visible");
        $("#player_bankroll" + seat_idx).text((Math.floor(+seat.player.bankroll * 100)) / 100 + "$");
        $("#player_cards" + seat_idx).css("visibility", "visible");
    });
    socket.on("new player", function(player) {
        $("#qr" + player.seat_nb).css("visibility", "hidden");
        $("#qr_spot" + player.seat_nb).css("visibility", "hidden");
        $("#scan_msg" + player.seat_nb).css("visibility", "hidden");
        $("#player_name" + player.seat_nb).css("visibility", "visible");
        $("#player_name" + player.seat_nb).text(player.nickname);
        $("#player_bankroll" + player.seat_nb).css("visibility", "visible");
        $("#player_bankroll" + player.seat_nb).text((Math.floor(+player.bankroll * 100)) / 100 + "$");
        $("#player_cards" + player.seat_nb).css("visibility", "visible");
    });
    socket.on("kick player", function(seat_nb) {
        $("#qr" + seat_nb).css("visibility", "visible");
        $("#qr_spot" + seat_nb).css("visibility", "visible");
        $("#scan_msg" + seat_nb).css("visibility", "visible");
        $("#player_name" + seat_nb).css("visibility", "hidden");
        $("#player_name" + seat_nb).text("");
        $("#player_bankroll" + seat_nb).css("visibility", "hidden");
        $("#player_bankroll" + seat_nb).text("");
        $("#player_cards" + seat_nb).css("visibility", "hidden");
        $("#btn" + seat_nb).attr("src", "");
        $("#btn" + seat_nb).css("visibility", "hidden");
        $("#card1_" + seat_nb).css("visibility", "hidden");
        $("#card2_" + seat_nb).css("visibility", "hidden");
        $("#last_action" + seat_nb).css("visibility", "hidden");
    });
    socket.emit("ask buttons");
    socket.on("place button", function(type, seat_nb) {
        if (seat_nb <= 0 || seat_nb >= 7)
            return;
        if (type == "dealer") {
            $("#btn" + seat_nb).attr("src", "../img/Dealer.png")
            $("#btn" + seat_nb).css("visibility", "visible");
        } else if (type == "sb") {
            $("#btn" + seat_nb).attr("src", "../img/sb.png")
            $("#btn" + seat_nb).css("visibility", "visible");
        } else if (type == "bb") {
            $("#btn" + seat_nb).attr("src", "../img/bb.png")
            $("#btn" + seat_nb).css("visibility", "visible");
        }
        $("#player_cards" + seat_nb).attr("src", "../img/hidden_cards.png");
    });
    socket.on("give cards", function(seat_nb) {
        $("#player_cards" + seat_nb).attr("src", "../img/hidden_cards.png");
    });
    socket.on("highlights", function(seat_idx, new_state) {
        var pos = $("#hSeat" + seat_idx);
        var idx;
        var pos_idx;

        if (new_state == "off") {
            for (idx = 1; idx <= 6; idx++) {
                pos_idx = $("#hSeat" + idx);
                pos_idx.hide();
                pos_idx.stop();
                pos_idx.css("width", "100%");
            }
        } else if (new_state == "on") {
            pos.show();
            pos.css("background-color", "#FE554C");
            pos.animate({
                "width": "0%"
            }, 31000);
        }
    });
    socket.on("i fold", function(decision, private_ids, zero) {
        socket.emit("player decision", decision, private_ids, zero);
    })
    socket.on("bankroll modification", function(seat_idx, player) {
        if (player.bankroll == "ALL IN")
            $("#player_bankroll" + seat_idx).text("ALL IN");
        else
            $("#player_bankroll" + seat_idx).text((Math.floor(player.bankroll * 100)) / 100 + "$");
    });
    socket.on("pot modification", function(pot_amount) {
        $("#pot").text(Math.floor(+pot_amount * 100) / 100 + "$");
    });
    socket.on("bet", function(seat_idx, amount) {
        if (!amount)
            $("#last_action" + seat_idx).text('');
        else {
            $("#last_action" + seat_idx).text((Math.floor(amount * 100)) / 100 + "$");
        }
    });

    socket.on("last action", function(decision, seat_nb, amount) {
        amount == 0 ? amount = "" : amount = " " + amount + "$";
        var nick = $("#player_name" + seat_nb).text();
        var str = decision.split(" ");
        var text = "
" + nick + " " + str[0] + amount + "
";

        $("#last_action").text(nick + " " + str[0] + amount);
        $("#histoContent").empty();
        $("#histoContent").append(text);
    });
    socket.on("fold", function(seat_nb) {
        $("#seat" + seat_nb).css('opacity', '0.3');
        $("#btn" + seat_nb).css("visibility", "hidden");
        $("#bet_val" + seat_nb).text('');
        $("#player_cards" + seat_nb).attr("src", "../img/avatar.png");
        $("#last_action" + seat_nb).text('FOLD');
    });
    socket.on("fold off", function() {
        var id;

        for (id = 1; id <= 6; id++) {
            $("#seat" + id).css('opacity', '1');
            $("#hSeat" + id).hide();
        }
    });
    socket.emit("get board");
    socket.on("send flop", function(card1, card2, card3) {
        $("#b1").attr("src", "img/cards/" + card1 + ".png");
        $("#b2").attr("src", "img/cards/" + card2 + ".png");
        $("#b3").attr("src", "img/cards/" + card3 + ".png");
        $("#b1, #b2, #b3").css("visibility", "visible");
    });
    socket.on("send turn", function(card4) {
        $("#b4").attr("src", "img/cards/" + card4 + ".png");
        $("#b4").css("visibility", "visible");
    });
    socket.on("send river", function(card5) {
        $("#b5").attr("src", "img/cards/" + card5 + ".png");
        $("#b5").css("visibility", "visible");
    });
    socket.on("remove last actions", function() {
        for (var idx = 1; idx <= 6; ++idx)
            $("#last_action" + idx).remove();
    });
    socket.on("remove board", function() {
        $("#b1, #b2, #b3, #b4, #b5").css("visibility", "hidden");
        for (var idx = 1; idx <= 6; ++idx)
            $("#player_cards" + idx).attr("src", "../img/avatar.png");
        $("#last_action").text('');
    });
    socket.on("remove emplacements", function() {
        for (var idx = 1; idx <= 6; ++idx)
            $("#btn" + idx).css("visibility", "hidden");
    });
    socket.on("show down", function(card1, card2, seat_nb) {
        if ($('#qr_spot' + seat_nb).css('visibility') == 'hidden') {
            if (card1 != -1 && card2 != -1) {
                $("#card1_" + seat_nb).attr("src", "../img/cards/" + card1 + ".png");
                $("#card2_" + seat_nb).attr("src", "../img/cards/" + card2 + ".png");
                $("#card1_" + seat_nb).css("visibility", "visible");
                $("#card2_" + seat_nb).css("visibility", "visible");
            } else {
                $("#card1_" + seat_nb).css("visibility", "hidden");
                $("#card2_" + seat_nb).css("visibility", "hidden");
            }
        }
    });
    socket.on("show down off", function(seat_nb) {
        $("#card1_" + seat_nb).css("visibility", "hidden");
        $("#card2_" + seat_nb).css("visibility", "hidden");
    });
    socket.on("winner", function(seat_nb, rank_name) {
        var disconnect = '
' + $("#player_name" + seat_nb).text() + ' won because player ' + rank_name + ' or folded
';
        var won = '
' + $("#player_name" + seat_nb).text() + ' won with ' + rank_name + '
';

        if (rank_name == "null")
            return;
        if (rank_name == 'disconnected') {
            $('#histoContent').empty();
            $('#histoContent').append(disconnect);
        } else if (seat_nb == 42 && rank_name == 'null') {
            $('#histoContent').empty();
            $('#histoContent').append('
Split !
');
        } else {
            $('#histoContent').empty();
            $('#histoContent').append(won);
        }
    });
    socket.on("win off", function() {
        $("#winner, #card1_1, #card2_1, #card1_2, #card2_2, #card1_3, #card2_3, #card1_4, #card2_4, #card1_5, #card2_5, #card1_6, #card2_6").css("visibility", "hidden");
    });
    socket.on("what is lock", function() {
        socket.emit("lock is true or false", lock);
    });
    socket.on("lock is true", function(vrai) {
        lock = vrai;
    })
    socket.on("lock is false", function(faux) {
        lock = faux;
    })
    socket.on("what is lock end", function(table, game) {
        socket.emit("lock is true or false end", lockEnd, table, game);
    });
    socket.on("lock is true end", function(vrai) {
        lockEnd = vrai;
    })
    socket.on("lock is false end", function(faux) {
        lockEnd = faux;
    })
}

function check_timeLock(action) {
    timeLock = action;
}
<|endoftext|>


<commit_before>/**
 * @URL https://github.com/csetea/magpieJS
 * @license MIT
 */
define([ 'magpie/log!magpie/html5/widget/select/m-option'  ], //
function(log) {

	var forEach = Array.prototype.forEach;

	function findParent(el, tagName){
		if (el.parentNode.localName == tagName){
			return el.parentNode;
		} else if (el.parentNode == document.body){
			return null;
		}
		return findParent(el.parentNode, tagName);
	}

	return {
		tag : 'm-option',

		select: function(mSelectEl, mOptionEl, event){
			if (mOptionEl.hasAttribute('disabled')){
				mSelectEl.blur();
			} else if (mOptionEl.hasAttribute('prevent')){
				// ...
			}else{
				var selected =  !mOptionEl.hasAttribute('selected');
				var multiple = mSelectEl.hasAttribute('multiple');
				var oldSelection = mSelectEl.selection();
				if (!multiple){
					forEach.call(mSelectEl.querySelectorAll('m-option'), function( optionEl ){
						optionEl.removeAttribute('selected');
					});
				}
				if (selected){
					mOptionEl.setAttribute('selected','true');
				}else{
					mOptionEl.removeAttribute('selected');
				}
				mSelectEl.fire('selectionChanged', {
					oldSelection: oldSelection,
					newSelection: mSelectEl.selection(),
					source: mOptionEl,
					selected: selected
				});
			}
		},

		createdCallback : function() {

		},

		attachedCallback: function(){
			if (!this._m_select){
				this._m_select = findParent(this, 'm-select');

				var _this=this;
				this._EventListener=function(event){
					if (this.parentNode !==null && this.parentNode.hasAttribute('result') ){
						// do nothing,
						// this is a copy from original m-option element in result holder
					}else{
						_this.select(_this._m_select, _this ,event);
					}
				};

				this.addEventListener( 'click',this._EventListener);
			}
		}

	};

});
<commit_msg>!fix findParent()<commit_after>/**
 * @URL https://github.com/csetea/magpieJS
 * @license MIT
 */
define([ 'magpie/log!magpie/html5/widget/select/m-option'  ], //
function(log) {

	var forEach = Array.prototype.forEach;

	function findParent(el, tagName){
		if (!el.parentNode || el.parentNode == document.body){
			return null;
		} else  if (el.parentNode.localName == tagName){
			return el.parentNode;
		}
		return findParent(el.parentNode, tagName);
	}

	return {
		tag : 'm-option',

		select: function(mSelectEl, mOptionEl, event){
			if (mOptionEl.hasAttribute('disabled')){
				mSelectEl.blur();
			} else if (mOptionEl.hasAttribute('prevent')){
				// ...
			}else{
				var selected =  !mOptionEl.hasAttribute('selected');
				var multiple = mSelectEl.hasAttribute('multiple');
				var oldSelection = mSelectEl.selection();
				if (!multiple){
					forEach.call(mSelectEl.querySelectorAll('m-option'), function( optionEl ){
						optionEl.removeAttribute('selected');
					});
				}
				if (selected){
					mOptionEl.setAttribute('selected','true');
				}else{
					mOptionEl.removeAttribute('selected');
				}
				mSelectEl.fire('selectionChanged', {
					oldSelection: oldSelection,
					newSelection: mSelectEl.selection(),
					source: mOptionEl,
					selected: selected
				});
			}
		},

		createdCallback : function() {

		},

		attachedCallback: function(){
			if (!this._m_select){
				this._m_select = findParent(this, 'm-select');

				var _this=this;
				this._EventListener=function(event){
					if (this.parentNode !==null && this.parentNode.hasAttribute('result') ){
						// do nothing,
						// this is a copy from original m-option element in result holder
					}else{
						_this.select(_this._m_select, _this ,event);
					}
				};

				this.addEventListener( 'click',this._EventListener);
			}
		}

	};

});
<|endoftext|>


<commit_before>#!/usr/bin/env node
/*
 * The "shebang" above is required for npm to correctly and install package the
 * package bin shortcut on windows
 * see: https://github.com/ForbesLindesay/cmd-shim/blob/f59af911f1373239a7537072641d55ff882c3701/index.js#L22
 */

const binge = require('../lib/index').default
const chalk = require('chalk')
const meow = require('meow')
const packageJson = require('../package.json')
const ensureRuntime = require('../lib/util/ensureRuntime').default

process.on('exit', () => {
    console.log('---------- -----------------')
    console.log('Binge (Eating Local Modules)')
    console.log(`version:   ${packageJson.version}`)
    console.timeEnd('execution')
    console.log('---------- -----------------')
})

ensureRuntime()

var cli = meow([
    'Usage',
    '  $ binge [command]',
    'Commands:',
    '  bootstrap  Recursively [Install,Bridge,Build] the local package tree',
    '             --install-concurrency {NUMBER} -> to limit the number of installs spawned in parallel',
    '  check      Recursively checks the local-package tree for lockfile sync',
    '  copy       Copies a file recursively into each of the local-packages',
    '             --dest-name {NAME} -> to use a different destination name',
    '             --skip-root -> to skip root local-packages',
    '  ls         Prints the local package tree. Prints the hoisting algorithm output',
    '  nuke       Recursively removes modules (rm -rf node_modules) from the local-package tree',
    '  watch      Build and watch the local-package tree',
])

var commandName = cli.input[0]
var command = binge[commandName]

console.time('execution')

if (!command) {
    if (commandName) {
        console.log(chalk.red('Invalid binge command: ' + commandName))
    }

    cli.showHelp()
} else {
    command(cli.flags, cli.input)
}
<commit_msg>Moving execution time log to mm:ss<commit_after>#!/usr/bin/env node
/*
 * The "shebang" above is required for npm to correctly and install package the
 * package bin shortcut on windows
 * see: https://github.com/ForbesLindesay/cmd-shim/blob/f59af911f1373239a7537072641d55ff882c3701/index.js#L22
 */
const packageJson = require('../package.json')

const pad = require('pad')
const chalk = require('chalk')
const meow = require('meow')

const ensureRuntime = require('../lib/util/ensureRuntime').default
const binge = require('../lib/index').default

const start = Date.now()
process.on('exit', () => {
    console.log('---------- -----------------')
    console.log('Binge (Eating Local Modules)')
    console.log(`version:   ${packageJson.version}`)
    console.log(`execution: ${mmss(Date.now() - start)}`)
    console.log('---------- -----------------')
})

ensureRuntime()

var cli = meow([
    'Usage',
    '  $ binge [command]',
    'Commands:',
    '  bootstrap  Recursively [Install,Bridge,Build] the local package tree',
    '             --install-concurrency {NUMBER} -> to limit the number of installs spawned in parallel',
    '  check      Recursively checks the local-package tree for lockfile sync',
    '  copy       Copies a file recursively into each of the local-packages',
    '             --dest-name {NAME} -> to use a different destination name',
    '             --skip-root -> to skip root local-packages',
    '  ls         Prints the local package tree. Prints the hoisting algorithm output',
    '  nuke       Recursively removes modules (rm -rf node_modules) from the local-package tree',
    '  watch      Build and watch the local-package tree',
])

const [commandName] = cli.input
const command = binge[commandName]

if (!command) {
    if (commandName) {
        console.log(chalk.red('Invalid binge command: ' + commandName))
    }

    cli.showHelp()
} else {
    command(cli.flags, cli.input)
}

function mmss(milliseconds) {
    const seconds = Math.floor((milliseconds / 1000) % 60)
    const minutes = Math.floor((milliseconds / (1000 * 60)) % 60)

    return `${pad(2, String(minutes), '0')}m${pad(2, seconds, '0')}s`
}
<|endoftext|>