<commit_before>const expect = require('chai').expect;
const validationHelper = require('../../src/helpers/validation.helper');

describe.only('ValidationHelper', () => {

  it('throw error on undefined properties', () => {
    expect(function () {
      validationHelper.validateHasProperties({a: 'a', b: 'b', c: 'c'},
        ['b', 'd', 'e'])
    }).to.throw(/Validated object doesn\'t have properties: d,e/);
  });

  it('do not throw error on defined properties', () => {
    validationHelper.validateHasProperties({a: 'a', b: 'b', c: 'c'},
      ['a', 'b', 'c']);

    validationHelper.validateHasProperties({a: 'a', b: 'b', c: 'c'},
      ['b']);

    validationHelper.validateHasProperties({a: 'a', b: 'b', c: 'c'},
      []);

    validationHelper.validateHasProperties({a: 'a', b: 'b', c: 'c'},
      null);
  });

  it('throw error on not truthy values', () => {
    expect(function () {
      validationHelper.validateIsTruthy(false)
    }).to.throw(/Validated object is not truthy/);

    expect(function () {
      validationHelper.validateIsTruthy(undefined)
    }).to.throw(/Validated object is not truthy/);

    expect(function () {
      validationHelper.validateIsTruthy(NaN)
    }).to.throw(/Validated object is not truthy/);

    expect(function () {
      validationHelper.validateIsTruthy(0)
    }).to.throw(/Validated object is not truthy/);

    expect(function () {
      validationHelper.validateIsTruthy('')
    }).to.throw(/Validated object is not truthy/);
  });

  it('do not throw error on truthy values', () => {
    validationHelper.validateIsTruthy(true);
    validationHelper.validateIsTruthy({});
    validationHelper.validateIsTruthy(1);
    validationHelper.validateIsTruthy(-1);
    validationHelper.validateIsTruthy(' ');
    validationHelper.validateIsTruthy('a');
  });

  it('throw error on not falsy values', () => {
    expect(function () {
      validationHelper.validateIsFalsy(true)
    }).to.throw(/Validated object is not falsy/);

    expect(function () {
      validationHelper.validateIsFalsy({})
    }).to.throw(/Validated object is not falsy/);

    expect(function () {
      validationHelper.validateIsFalsy(1)
    }).to.throw(/Validated object is not falsy/);

    expect(function () {
      validationHelper.validateIsFalsy(-1)
    }).to.throw(/Validated object is not falsy/);

    expect(function () {
      validationHelper.validateIsFalsy(' ')
    }).to.throw(/Validated object is not falsy/);

    expect(function () {
      validationHelper.validateIsFalsy('a')
    }).to.throw(/Validated object is not falsy/);
  });

  it('do not throw error on falsy values', () => {
    validationHelper.validateIsFalsy(false);
    validationHelper.validateIsFalsy(undefined);
    validationHelper.validateIsFalsy(NaN);
    validationHelper.validateIsFalsy(0);
    validationHelper.validateIsFalsy('');
  });

  it('throw error on not True values', () => {
    expect(function () {
      validationHelper.validateIsTrue(false)
    }).to.throw(/Validated object is not True/);

    expect(function () {
      validationHelper.validateIsTrue({})
    }).to.throw(/Validated object is not True/);

    expect(function () {
      validationHelper.validateIsTrue(1)
    }).to.throw(/Validated object is not True/);
  });

  it('do not throw error on True values', () => {
    validationHelper.validateIsTrue(true);
  });

  it('throw error on not False values', () => {
    expect(function () {
      validationHelper.validateIsFalse(true)
    }).to.throw(/Validated object is not False/);

    expect(function () {
      validationHelper.validateIsFalse(undefined)
    }).to.throw(/Validated object is not False/);

    expect(function () {
      validationHelper.validateIsFalse(null)
    }).to.throw(/Validated object is not False/);

    expect(function () {
      validationHelper.validateIsFalse(NaN)
    }).to.throw(/Validated object is not False/);

    expect(function () {
      validationHelper.validateIsFalse(0)
    }).to.throw(/Validated object is not False/);

    expect(function () {
      validationHelper.validateIsFalse(1)
    }).to.throw(/Validated object is not False/);
  });

  it('do not throw error on False values', () => {
    validationHelper.validateIsFalse(false);
  });

  it('throw error on not a Number value', () => {
    expect(function () {
      validationHelper.validateIsNumber({})
    }).to.throw(/Validated object is not a number/);

    expect(function () {
      validationHelper.validateIsNumber(undefined)
    }).to.throw(/Validated object is not a number/);

    expect(function () {
      validationHelper.validateIsNumber(NaN)
    }).to.throw(/Validated object is not a number/);

    expect(function () {
      validationHelper.validateIsNumber(null)
    }).to.throw(/Validated object is not a number/);

    expect(function () {
      validationHelper.validateIsNumber('1')
    }).to.throw(/Validated object is not a number/);
  });

  it('do not throw error on Number value', () => {
    validationHelper.validateIsNumber(-1);
    validationHelper.validateIsNumber(0);
    validationHelper.validateIsNumber(1);
    validationHelper.validateIsNumber(1.5);
  });

  it('throw error on not a positive number value', () => {
    expect(function () {
      validationHelper.validateIsPositiveNumber(0)
    }).to.throw(/Validated number is not positive/);

    expect(function () {
      validationHelper.validateIsPositiveNumber(-1)
    }).to.throw(/Validated number is not positive/);

    expect(function () {
      validationHelper.validateIsPositiveNumber(NaN)
    }).to.throw(/Validated object is not a number/);
  });

  it('do not throw error on a positive number value', () => {
    validationHelper.validateIsPositiveNumber(0.1);
    validationHelper.validateIsPositiveNumber(1);
    validationHelper.validateIsPositiveNumber(1.5);
  });

  it('throw error on null or undefined', () => {
    expect(function () {
      validationHelper.validateIsNotNil(null);
    }).to.throw(/Validated object is null or undefined/);

    expect(function () {
      validationHelper.validateIsNotNil(undefined);
    }).to.throw(/Validated object is null or undefined/);
  });

  it('do not throw error on not a null or undefined', () => {
    validationHelper.validateIsNotNil(1);
    validationHelper.validateIsNotNil(0);
    validationHelper.validateIsNotNil(-1);
    validationHelper.validateIsNotNil({});
    validationHelper.validateIsNotNil('');
    validationHelper.validateIsNotNil('a');
    validationHelper.validateIsNotNil(true);
    validationHelper.validateIsNotNil(false);
  });

  it('throw error on empty object', () => {
    expect(function () {
      validationHelper.validateIsNotEmpty([])
    }).to.throw(/Validated object is empty/);

    expect(function () {
      validationHelper.validateIsNotEmpty('')
    }).to.throw(/Validated object is empty/);

    expect(function () {
      validationHelper.validateIsNotEmpty(new Set())
    }).to.throw(/Validated object is empty/);

    expect(function () {
      validationHelper.validateIsNotEmpty(null)
    }).to.throw(/Validated object is empty/);

    expect(function () {
      validationHelper.validateIsNotEmpty(undefined)
    }).to.throw(/Validated object is empty/);

    expect(function () {
      validationHelper.validateIsNotEmpty(1)
    }).to.throw(/Validated object is empty/);

    expect(function () {
      validationHelper.validateIsNotEmpty({})
    }).to.throw(/Validated object is empty/);
  });

  it('do not throw error on a not empty object', () => {
    validationHelper.validateIsNotEmpty({a: ''});
    validationHelper.validateIsNotEmpty(' ');
    validationHelper.validateIsNotEmpty('a');
    validationHelper.validateIsNotEmpty([{}]);
  });

});
<commit_msg>Remove "only".<commit_after>const expect = require('chai').expect;
const validationHelper = require('../../src/helpers/validation.helper');

describe('ValidationHelper', () => {

  it('throw error on undefined properties', () => {
    expect(function () {
      validationHelper.validateHasProperties({a: 'a', b: 'b', c: 'c'},
        ['b', 'd', 'e'])
    }).to.throw(/Validated object doesn\'t have properties: d,e/);
  });

  it('do not throw error on defined properties', () => {
    validationHelper.validateHasProperties({a: 'a', b: 'b', c: 'c'},
      ['a', 'b', 'c']);

    validationHelper.validateHasProperties({a: 'a', b: 'b', c: 'c'},
      ['b']);

    validationHelper.validateHasProperties({a: 'a', b: 'b', c: 'c'},
      []);

    validationHelper.validateHasProperties({a: 'a', b: 'b', c: 'c'},
      null);
  });

  it('throw error on not truthy values', () => {
    expect(function () {
      validationHelper.validateIsTruthy(false)
    }).to.throw(/Validated object is not truthy/);

    expect(function () {
      validationHelper.validateIsTruthy(undefined)
    }).to.throw(/Validated object is not truthy/);

    expect(function () {
      validationHelper.validateIsTruthy(NaN)
    }).to.throw(/Validated object is not truthy/);

    expect(function () {
      validationHelper.validateIsTruthy(0)
    }).to.throw(/Validated object is not truthy/);

    expect(function () {
      validationHelper.validateIsTruthy('')
    }).to.throw(/Validated object is not truthy/);
  });

  it('do not throw error on truthy values', () => {
    validationHelper.validateIsTruthy(true);
    validationHelper.validateIsTruthy({});
    validationHelper.validateIsTruthy(1);
    validationHelper.validateIsTruthy(-1);
    validationHelper.validateIsTruthy(' ');
    validationHelper.validateIsTruthy('a');
  });

  it('throw error on not falsy values', () => {
    expect(function () {
      validationHelper.validateIsFalsy(true)
    }).to.throw(/Validated object is not falsy/);

    expect(function () {
      validationHelper.validateIsFalsy({})
    }).to.throw(/Validated object is not falsy/);

    expect(function () {
      validationHelper.validateIsFalsy(1)
    }).to.throw(/Validated object is not falsy/);

    expect(function () {
      validationHelper.validateIsFalsy(-1)
    }).to.throw(/Validated object is not falsy/);

    expect(function () {
      validationHelper.validateIsFalsy(' ')
    }).to.throw(/Validated object is not falsy/);

    expect(function () {
      validationHelper.validateIsFalsy('a')
    }).to.throw(/Validated object is not falsy/);
  });

  it('do not throw error on falsy values', () => {
    validationHelper.validateIsFalsy(false);
    validationHelper.validateIsFalsy(undefined);
    validationHelper.validateIsFalsy(NaN);
    validationHelper.validateIsFalsy(0);
    validationHelper.validateIsFalsy('');
  });

  it('throw error on not True values', () => {
    expect(function () {
      validationHelper.validateIsTrue(false)
    }).to.throw(/Validated object is not True/);

    expect(function () {
      validationHelper.validateIsTrue({})
    }).to.throw(/Validated object is not True/);

    expect(function () {
      validationHelper.validateIsTrue(1)
    }).to.throw(/Validated object is not True/);
  });

  it('do not throw error on True values', () => {
    validationHelper.validateIsTrue(true);
  });

  it('throw error on not False values', () => {
    expect(function () {
      validationHelper.validateIsFalse(true)
    }).to.throw(/Validated object is not False/);

    expect(function () {
      validationHelper.validateIsFalse(undefined)
    }).to.throw(/Validated object is not False/);

    expect(function () {
      validationHelper.validateIsFalse(null)
    }).to.throw(/Validated object is not False/);

    expect(function () {
      validationHelper.validateIsFalse(NaN)
    }).to.throw(/Validated object is not False/);

    expect(function () {
      validationHelper.validateIsFalse(0)
    }).to.throw(/Validated object is not False/);

    expect(function () {
      validationHelper.validateIsFalse(1)
    }).to.throw(/Validated object is not False/);
  });

  it('do not throw error on False values', () => {
    validationHelper.validateIsFalse(false);
  });

  it('throw error on not a Number value', () => {
    expect(function () {
      validationHelper.validateIsNumber({})
    }).to.throw(/Validated object is not a number/);

    expect(function () {
      validationHelper.validateIsNumber(undefined)
    }).to.throw(/Validated object is not a number/);

    expect(function () {
      validationHelper.validateIsNumber(NaN)
    }).to.throw(/Validated object is not a number/);

    expect(function () {
      validationHelper.validateIsNumber(null)
    }).to.throw(/Validated object is not a number/);

    expect(function () {
      validationHelper.validateIsNumber('1')
    }).to.throw(/Validated object is not a number/);
  });

  it('do not throw error on Number value', () => {
    validationHelper.validateIsNumber(-1);
    validationHelper.validateIsNumber(0);
    validationHelper.validateIsNumber(1);
    validationHelper.validateIsNumber(1.5);
  });

  it('throw error on not a positive number value', () => {
    expect(function () {
      validationHelper.validateIsPositiveNumber(0)
    }).to.throw(/Validated number is not positive/);

    expect(function () {
      validationHelper.validateIsPositiveNumber(-1)
    }).to.throw(/Validated number is not positive/);

    expect(function () {
      validationHelper.validateIsPositiveNumber(NaN)
    }).to.throw(/Validated object is not a number/);
  });

  it('do not throw error on a positive number value', () => {
    validationHelper.validateIsPositiveNumber(0.1);
    validationHelper.validateIsPositiveNumber(1);
    validationHelper.validateIsPositiveNumber(1.5);
  });

  it('throw error on null or undefined', () => {
    expect(function () {
      validationHelper.validateIsNotNil(null);
    }).to.throw(/Validated object is null or undefined/);

    expect(function () {
      validationHelper.validateIsNotNil(undefined);
    }).to.throw(/Validated object is null or undefined/);
  });

  it('do not throw error on not a null or undefined', () => {
    validationHelper.validateIsNotNil(1);
    validationHelper.validateIsNotNil(0);
    validationHelper.validateIsNotNil(-1);
    validationHelper.validateIsNotNil({});
    validationHelper.validateIsNotNil('');
    validationHelper.validateIsNotNil('a');
    validationHelper.validateIsNotNil(true);
    validationHelper.validateIsNotNil(false);
  });

  it('throw error on empty object', () => {
    expect(function () {
      validationHelper.validateIsNotEmpty([])
    }).to.throw(/Validated object is empty/);

    expect(function () {
      validationHelper.validateIsNotEmpty('')
    }).to.throw(/Validated object is empty/);

    expect(function () {
      validationHelper.validateIsNotEmpty(new Set())
    }).to.throw(/Validated object is empty/);

    expect(function () {
      validationHelper.validateIsNotEmpty(null)
    }).to.throw(/Validated object is empty/);

    expect(function () {
      validationHelper.validateIsNotEmpty(undefined)
    }).to.throw(/Validated object is empty/);

    expect(function () {
      validationHelper.validateIsNotEmpty(1)
    }).to.throw(/Validated object is empty/);

    expect(function () {
      validationHelper.validateIsNotEmpty({})
    }).to.throw(/Validated object is empty/);
  });

  it('do not throw error on a not empty object', () => {
    validationHelper.validateIsNotEmpty({a: ''});
    validationHelper.validateIsNotEmpty(' ');
    validationHelper.validateIsNotEmpty('a');
    validationHelper.validateIsNotEmpty([{}]);
  });

});
<|endoftext|>


<commit_before>/*jshint multistr: true */

var Helpy = Helpy || {};

Helpy.ready = function(){

  $(".best_in_place").best_in_place();

  $('.profile').initial();

  $('.attachinary-input').attachinary();

  $('.uploader').fileupload({
    dataType: 'script',
    singleFileUploads: false
  });

  $('.submit-loader').off('submit', Helpy.loader).on('submit', Helpy.loader);
  $('.click-loader').off('click').on('click', Helpy.loader);
  $('ul.pagination li a').off('click').on('click', Helpy.loader);

  $('.screenshot-link').magnificPopup({type:'image', gallery:{enabled:true}});

  // make sure dropdowns close after click of link
  $(".dropdown-menu a").click(function() {
    $(this).closest(".dropdown-menu").prev().dropdown("toggle");
  });

  $('.navbar-form, #search-form').off().on('submit', function(){
    $('.navbar-collapse.in').collapse('hide');
  });

  $('.thumbnail, .stats').off();

  // jquery hhoks for the home page
  $('.topic-box').click(function(){
    document.location.href = $(this).data("link");
  });

  $('.thumbnail, .stats').on('mouseover',function(){
    $(this).css('cursor','pointer');
    $(this).css('border','1px solid #666');
    $(this).css('box-shadow', '0px 0px 10px #eee');
    $(this).closest('.has-arrow').addClass('over');
  });

  $.ui.autocomplete.prototype._renderItem = function( ul, item) {
    return $( "

" )
        .data( "item.autocomplete", item.name )
        .append( "
" + item.name + "
" )
        .append( "
" + item.content + "
" )
        .appendTo( ul );
  };

  $(".autosearch").keyup(function () {
      var that = $(this);
      value = $(this).val();
      $(this).autocomplete({
        source: function (request, response) {
          jQuery.get("/"+location.href.split("/")[3]+"/search.json", {
              query: value
          }, function (data) {
            response(data);
          });
        },
        minLength: 3,
        appendTo: that.next(),
        focus: function( event, ui ) {
          $(".autosearch").val(ui.item.name);
        },
        select: function( event, ui ) {
          window.location.href = ui.item.link;
        },
        messages: {
          noResults: '',
          results: function() {}
        }

      });

  });

  $("#topic_name").blur(function () {
      var that = $(this);
      var $results = $('.suggestion-results');
      var $container = $('.suggestion-results-container');
      $query = $(this).val();

      if ($query.length >= 3) {
        $.getJSON( "/"+location.href.split("/")[3]+"/search.json?depth=5&query=" + $query, function( data ) {
          var items = [];
          $.each( data, function( key, val ) {
            items.push( "
" + val.name + "
" );
          });

          var $html = $( "
", {
          "class": "suggested-results list-unstyled",
          html: items.join( "" )}
          );

          if (items.length > 0) {
            $results.html($html);
            $container.removeClass("hidden");
            $container.fadeIn();
          }
        });
      }
  });

  $('.stats').on('click', function(){

    $('.stats').css('border','1px solid #ddd');
    $('.stats').css('box-shadow', '');
    $('.has-arrow').removeClass("over");
    $('.stats').removeClass("selected");

    $(this).addClass('selected');
    $(this).css('border','1px solid #666');
    $(this).css('box-shadow', '0px 0px 10px #eee');
    $(this).closest('.has-arrow').addClass('over');

    var form = $("<form></form>");
    var url = $(this).find('a').attr('href');
    form.attr(
    {
        id     : "formform",
        // The location given in the link itself
        action : $(this).find('a').attr('href'),
        method : "GET",
        "data-remote" : "true"
    });

    $("body").append(form);
    $("#formform").submit();
    $("#formform").remove();

    // Show loader
    Helpy.loader();

    // Ensure history is captured in the browser
    history.pushState(null, '', url);
    $(window).off().on("popstate", function(){
      console.log("Popstate fired: " + location.href);
      $.getScript(location.href);
    });

    // Prevent the link from opening normally
    return false;
  });

  $('.thumbnail, .stats').on('mouseout',function(){
    if ($(this).hasClass('selected') !== true) {
      $(this).css('cursor','auto');
      $(this).css('border','1px solid #ddd');
      $(this).css('box-shadow', '');
      $(this).closest('.has-arrow').removeClass('over');
    }
  });

  // Sets up autoscroll for any link with class autoscroll
  // requires data-target param containing class or ID of target
  $(".autoscroll").each(function(){
      $(this).click(function(){
        var scrollTarget=$(this).data("target");
        $('html,body').animate({
          scrollTop: $(scrollTarget).offset().top},'slow');
        });
  });

  // used by create topic form
  $('#topic_private_true').click(function(){
    $("#topic_forum_id").parent().hide();
    $('#new_topic').append("<input type='hidden' id='new_topic_forum_id' name='topic[forum_id]' value='1'/>");
    Helpy.showGroup();
  });
  $('#topic_private_false').click(function(){
    $("#topic_forum_id").parent().show();
    $("#new_topic_forum_id").remove();
    Helpy.showGroup();
  });

  // Hide/replace last child of breadcrumbs since I don't have time to hack gem right now
  $("ul.breadcrumb li:last-child").html("");

  // compress thread if there are more than 4 messages
  var $thread = $('.post-container.kind-reply.disallow-post-voting, .post-container.kind-note.disallow-post-voting');
  if ($thread.size() >= 2) {

    // insert expand thread message
//    var $hider = "
" + ($thread.size()-1) + " collapsed messages
";
    var $hider = "
" + Helpy.messages + "
";

    // check to see if we are already collapsed
    if ($(".collapsed-posts").size() === 0) {
      $(".kind-first").append($hider);
    }

    // add listener to expand messages
    $('.collapsed-posts').on('click', function(){
      $thread.show();
      $('.collapsed-posts').hide();
    });

    // hide thread, except for most recent message
    $thread.hide().last().show();
  }

  // Use or append common reply
  $('#post_reply_id').on('change', function(){
    var post_body = $('#post_body');
    var common_reply = $('#post_reply_id option:selected');

    // append new line if some text already exists
    if( post_body.val() && common_reply.val() ) {
      post_body.val(post_body.val() + "\n\n");
    }

    // add content of selected reply
    post_body.val( post_body.val() + common_reply.val() );
    $('.disableable').attr('disabled', false);
  });

  $('.post-menu span').off().on('click', function(){
    $(this).closest('.post-container').css('z-index','99999');
  });

  function updateMessage(){
    var output;
    var messages = $('.topic-checkbox:checked').size();

    switch(messages) {
      case 1:
        output = Helpy.selected[1];
        break;
      case 2:
        output = Helpy.selected[2];
        break;
      default:
        output = Helpy.selected[3].replace("9", messages);
        break;
    }
    $('.selected-message').text(output);
  }

  $('#check-all').off().on('change', function(){
    if (this.checked) {
      $('.topic-checkbox').prop('checked', true);
      $('#multiple-edit').fadeIn();
      updateMessage();

    } else {
      $('.topic-checkbox').prop('checked', false);
      $('#multiple-edit').fadeOut();
    }
  });

  $('.topic-checkbox').off().on('change', function(){

    if (this.checked) {
      $('#multiple-edit').fadeIn();
      updateMessage();

    } else {
      if ($('.topic-checkbox:checked').size() === 0) {
        $('#multiple-edit').fadeOut();
      } else {
        updateMessage();
      }
    }
  });

  $('.multiple-update').off().on('click', function(){
    // collect array of all checked boxes
    var topic_ids = {};
    var str = $(this).attr('href');
    $('.topic-checkbox:checked').each(function(i){
      topic_ids[i] = $(this).val();
    });
    // modify link to include array
    $.each(topic_ids, function(i){
      str = str + "&topic_ids[]=" + topic_ids[i];
    });
    $(this).attr('href', str);
    // return true to follow the link
    return true;
  });

  // Topic voting widget animation
  $('.topic-points').hover(function(){
    $(this).addClass('animated pulse');
    $(this).prev().addClass('animated bounce');
  }, function(){
    $(this).removeClass('animated pulse');
    $(this).prev().removeClass('animated bounce');
  });

  // Locale Picker
  $('#lang').off().on('change', function() {
    var url = $("#lang").val();
    if(url !=="")
     {
     $("#locale-change").submit();
     }
  });

  // Login/Forgot Switcher

  $('.login-link').off().on('click', function() {
    $('.login-form').show();
    $('.forgot-form').hide();
    $('.modal-title').text($('.login-form').data("title"));
    $('.modal-links').show();
  });

  $('.forgot-link').off().on('click', function() {
    $('.login-form').hide();
    $('.forgot-form').show();
    $(ClientSideValidations.selectors.forms).validate();
    $('.modal-title').text($('.forgot-form').data("title"));
    $('.modal-links').hide();
  });

  // Disable submit button if post not provided
  $('.disable-empty').keyup(function(){
    $('.disable-empty').each(function(){
      if ($(this).val() === '') {
        $('.disableable').attr('disabled', 'disabled');
      } else {
        $('.disableable').removeAttr('disabled');
      }
    });
  });

  // Autolink messages
  $('.post-body').each(function(){
    var that = $(this);
    var text = that.html();

    that.html(text.autoLink({ target: "_blank" }));
  });

  // Post CC and BCC
  $('.cc-bcc-toggle').off().on('click', function() {
    $fieldContainer = $('.cc-bcc');

    if ($fieldContainer.hasClass('hidden')){
      $fieldContainer.removeClass('hidden');
      var previousCC = $('.post-cc').last().text().split(": ")[1];
      var previousBCC = $('.post-bcc').last().text().split(": ")[1];
      $('#post_cc').val(previousCC);
      $('#post_bcc').val(previousBCC);
      $('.cc-bcc-toggle').addClass('fa-angle-up').removeClass('fa-angle-down');
    } else {
      $fieldContainer.addClass('hidden');
      $('#post_cc').val("");
      $('#post_bcc').val("");
      $('.cc-bcc-toggle').removeClass('fa-angle-up').addClass('fa-angle-down');
    }
  });

  // Hide required field indicator generated by simple_form, as we already
  // Add this in css.  There is probably a better way to do this?
  $("abbr[title='required']").hide();

};

$.attachinary.config.template = '\

\
    <% for(var i=0; i<files.length; i++){ %>\

\
        <% if(files[i].resource_type == "raw") { %>\

\
        <% } else { %>\
          <img\
            src="<%= $.cloudinary.url(files[i].public_id, { "version": files[i].version, "format": "jpg", "crop": "fill", "width": 250, "height": 250 }) %>"\
            alt="" width="75" height="75" />\
        <% } %>\

\
        <a href="#" data-remove="<%= files[i].public_id %>">Remove\

\
    <% } %>\

\
';

// This is included here because you would expect to find it here.  The function is actually called
// from event-tracking.js where we have to unbind and rebind the event to support turbolinks
Helpy.didthisHelp = function(yesno){
  var message;
  var contactus;
  if (yesno === "no") {
    message = "
" + Helpy.noHelped + "
";
    contactus = "

" + Helpy.contactUs + "

";
  } else {
    message = "
" + Helpy.yesHelped + "
";
    contactus = '';
  }

  message = "
" + message + "
" + contactus;

  $('#did-this-help').html(message);
  return true;
};

Helpy.showGroup = function() {
  if ($('#topic_private_true').is(':checked')) {
    $('#topic_team_list').parent().removeClass('hidden');
  } else if ($('#topic_private_false').is(':checked')) {
    $('#topic_team_list').parent().addClass('hidden');
  } else {
    $('#topic_team_list').parent().removeClass('hidden');
  }
};

Helpy.loader = function(){
  $('#tickets').html("

");
}

$(document).ready(Helpy.ready);
$(document).on('page:load', Helpy.ready);

$(document).on('page:change', function () {

  //Truncate Q&A responses
  $('.shorten').jTruncate({
    length: 200,
    minTrail: 0,
    moreText: " (more)",
    lessText: " (less)",
    ellipsisText: " ...",
    moreAni: "",
    lessAni: ""
  });

  // Allows image insertion into quill editor
  $('.doc-form-files .cloudinary-fileupload').bind('cloudinarydone', function(e, data) {
    var element = document.querySelector("trix-editor");
    var thisImage = "";
    element.editor.insertHTML(thisImage);

    $('.image_public_id').val(data.result.public_id);
    return true;
  });

});
<commit_msg>Add missing semicolon<commit_after>/*jshint multistr: true */

var Helpy = Helpy || {};

Helpy.ready = function(){

  $(".best_in_place").best_in_place();

  $('.profile').initial();

  $('.attachinary-input').attachinary();

  $('.uploader').fileupload({
    dataType: 'script',
    singleFileUploads: false
  });

  $('.submit-loader').off('submit', Helpy.loader).on('submit', Helpy.loader);
  $('.click-loader').off('click').on('click', Helpy.loader);
  $('ul.pagination li a').off('click').on('click', Helpy.loader);

  $('.screenshot-link').magnificPopup({type:'image', gallery:{enabled:true}});

  // make sure dropdowns close after click of link
  $(".dropdown-menu a").click(function() {
    $(this).closest(".dropdown-menu").prev().dropdown("toggle");
  });

  $('.navbar-form, #search-form').off().on('submit', function(){
    $('.navbar-collapse.in').collapse('hide');
  });

  $('.thumbnail, .stats').off();

  // jquery hhoks for the home page
  $('.topic-box').click(function(){
    document.location.href = $(this).data("link");
  });

  $('.thumbnail, .stats').on('mouseover',function(){
    $(this).css('cursor','pointer');
    $(this).css('border','1px solid #666');
    $(this).css('box-shadow', '0px 0px 10px #eee');
    $(this).closest('.has-arrow').addClass('over');
  });

  $.ui.autocomplete.prototype._renderItem = function( ul, item) {
    return $( "

" )
        .data( "item.autocomplete", item.name )
        .append( "
" + item.name + "
" )
        .append( "
" + item.content + "
" )
        .appendTo( ul );
  };

  $(".autosearch").keyup(function () {
      var that = $(this);
      value = $(this).val();
      $(this).autocomplete({
        source: function (request, response) {
          jQuery.get("/"+location.href.split("/")[3]+"/search.json", {
              query: value
          }, function (data) {
            response(data);
          });
        },
        minLength: 3,
        appendTo: that.next(),
        focus: function( event, ui ) {
          $(".autosearch").val(ui.item.name);
        },
        select: function( event, ui ) {
          window.location.href = ui.item.link;
        },
        messages: {
          noResults: '',
          results: function() {}
        }

      });

  });

  $("#topic_name").blur(function () {
      var that = $(this);
      var $results = $('.suggestion-results');
      var $container = $('.suggestion-results-container');
      $query = $(this).val();

      if ($query.length >= 3) {
        $.getJSON( "/"+location.href.split("/")[3]+"/search.json?depth=5&query=" + $query, function( data ) {
          var items = [];
          $.each( data, function( key, val ) {
            items.push( "
" + val.name + "
" );
          });

          var $html = $( "
", {
          "class": "suggested-results list-unstyled",
          html: items.join( "" )}
          );

          if (items.length > 0) {
            $results.html($html);
            $container.removeClass("hidden");
            $container.fadeIn();
          }
        });
      }
  });

  $('.stats').on('click', function(){

    $('.stats').css('border','1px solid #ddd');
    $('.stats').css('box-shadow', '');
    $('.has-arrow').removeClass("over");
    $('.stats').removeClass("selected");

    $(this).addClass('selected');
    $(this).css('border','1px solid #666');
    $(this).css('box-shadow', '0px 0px 10px #eee');
    $(this).closest('.has-arrow').addClass('over');

    var form = $("<form></form>");
    var url = $(this).find('a').attr('href');
    form.attr(
    {
        id     : "formform",
        // The location given in the link itself
        action : $(this).find('a').attr('href'),
        method : "GET",
        "data-remote" : "true"
    });

    $("body").append(form);
    $("#formform").submit();
    $("#formform").remove();

    // Show loader
    Helpy.loader();

    // Ensure history is captured in the browser
    history.pushState(null, '', url);
    $(window).off().on("popstate", function(){
      console.log("Popstate fired: " + location.href);
      $.getScript(location.href);
    });

    // Prevent the link from opening normally
    return false;
  });

  $('.thumbnail, .stats').on('mouseout',function(){
    if ($(this).hasClass('selected') !== true) {
      $(this).css('cursor','auto');
      $(this).css('border','1px solid #ddd');
      $(this).css('box-shadow', '');
      $(this).closest('.has-arrow').removeClass('over');
    }
  });

  // Sets up autoscroll for any link with class autoscroll
  // requires data-target param containing class or ID of target
  $(".autoscroll").each(function(){
      $(this).click(function(){
        var scrollTarget=$(this).data("target");
        $('html,body').animate({
          scrollTop: $(scrollTarget).offset().top},'slow');
        });
  });

  // used by create topic form
  $('#topic_private_true').click(function(){
    $("#topic_forum_id").parent().hide();
    $('#new_topic').append("<input type='hidden' id='new_topic_forum_id' name='topic[forum_id]' value='1'/>");
    Helpy.showGroup();
  });
  $('#topic_private_false').click(function(){
    $("#topic_forum_id").parent().show();
    $("#new_topic_forum_id").remove();
    Helpy.showGroup();
  });

  // Hide/replace last child of breadcrumbs since I don't have time to hack gem right now
  $("ul.breadcrumb li:last-child").html("");

  // compress thread if there are more than 4 messages
  var $thread = $('.post-container.kind-reply.disallow-post-voting, .post-container.kind-note.disallow-post-voting');
  if ($thread.size() >= 2) {

    // insert expand thread message
//    var $hider = "
" + ($thread.size()-1) + " collapsed messages
";
    var $hider = "
" + Helpy.messages + "
";

    // check to see if we are already collapsed
    if ($(".collapsed-posts").size() === 0) {
      $(".kind-first").append($hider);
    }

    // add listener to expand messages
    $('.collapsed-posts').on('click', function(){
      $thread.show();
      $('.collapsed-posts').hide();
    });

    // hide thread, except for most recent message
    $thread.hide().last().show();
  }

  // Use or append common reply
  $('#post_reply_id').on('change', function(){
    var post_body = $('#post_body');
    var common_reply = $('#post_reply_id option:selected');

    // append new line if some text already exists
    if( post_body.val() && common_reply.val() ) {
      post_body.val(post_body.val() + "\n\n");
    }

    // add content of selected reply
    post_body.val( post_body.val() + common_reply.val() );
    $('.disableable').attr('disabled', false);
  });

  $('.post-menu span').off().on('click', function(){
    $(this).closest('.post-container').css('z-index','99999');
  });

  function updateMessage(){
    var output;
    var messages = $('.topic-checkbox:checked').size();

    switch(messages) {
      case 1:
        output = Helpy.selected[1];
        break;
      case 2:
        output = Helpy.selected[2];
        break;
      default:
        output = Helpy.selected[3].replace("9", messages);
        break;
    }
    $('.selected-message').text(output);
  }

  $('#check-all').off().on('change', function(){
    if (this.checked) {
      $('.topic-checkbox').prop('checked', true);
      $('#multiple-edit').fadeIn();
      updateMessage();

    } else {
      $('.topic-checkbox').prop('checked', false);
      $('#multiple-edit').fadeOut();
    }
  });

  $('.topic-checkbox').off().on('change', function(){

    if (this.checked) {
      $('#multiple-edit').fadeIn();
      updateMessage();

    } else {
      if ($('.topic-checkbox:checked').size() === 0) {
        $('#multiple-edit').fadeOut();
      } else {
        updateMessage();
      }
    }
  });

  $('.multiple-update').off().on('click', function(){
    // collect array of all checked boxes
    var topic_ids = {};
    var str = $(this).attr('href');
    $('.topic-checkbox:checked').each(function(i){
      topic_ids[i] = $(this).val();
    });
    // modify link to include array
    $.each(topic_ids, function(i){
      str = str + "&topic_ids[]=" + topic_ids[i];
    });
    $(this).attr('href', str);
    // return true to follow the link
    return true;
  });

  // Topic voting widget animation
  $('.topic-points').hover(function(){
    $(this).addClass('animated pulse');
    $(this).prev().addClass('animated bounce');
  }, function(){
    $(this).removeClass('animated pulse');
    $(this).prev().removeClass('animated bounce');
  });

  // Locale Picker
  $('#lang').off().on('change', function() {
    var url = $("#lang").val();
    if(url !=="")
     {
     $("#locale-change").submit();
     }
  });

  // Login/Forgot Switcher

  $('.login-link').off().on('click', function() {
    $('.login-form').show();
    $('.forgot-form').hide();
    $('.modal-title').text($('.login-form').data("title"));
    $('.modal-links').show();
  });

  $('.forgot-link').off().on('click', function() {
    $('.login-form').hide();
    $('.forgot-form').show();
    $(ClientSideValidations.selectors.forms).validate();
    $('.modal-title').text($('.forgot-form').data("title"));
    $('.modal-links').hide();
  });

  // Disable submit button if post not provided
  $('.disable-empty').keyup(function(){
    $('.disable-empty').each(function(){
      if ($(this).val() === '') {
        $('.disableable').attr('disabled', 'disabled');
      } else {
        $('.disableable').removeAttr('disabled');
      }
    });
  });

  // Autolink messages
  $('.post-body').each(function(){
    var that = $(this);
    var text = that.html();

    that.html(text.autoLink({ target: "_blank" }));
  });

  // Post CC and BCC
  $('.cc-bcc-toggle').off().on('click', function() {
    $fieldContainer = $('.cc-bcc');

    if ($fieldContainer.hasClass('hidden')){
      $fieldContainer.removeClass('hidden');
      var previousCC = $('.post-cc').last().text().split(": ")[1];
      var previousBCC = $('.post-bcc').last().text().split(": ")[1];
      $('#post_cc').val(previousCC);
      $('#post_bcc').val(previousBCC);
      $('.cc-bcc-toggle').addClass('fa-angle-up').removeClass('fa-angle-down');
    } else {
      $fieldContainer.addClass('hidden');
      $('#post_cc').val("");
      $('#post_bcc').val("");
      $('.cc-bcc-toggle').removeClass('fa-angle-up').addClass('fa-angle-down');
    }
  });

  // Hide required field indicator generated by simple_form, as we already
  // Add this in css.  There is probably a better way to do this?
  $("abbr[title='required']").hide();

};

$.attachinary.config.template = '\

\
    <% for(var i=0; i<files.length; i++){ %>\

\
        <% if(files[i].resource_type == "raw") { %>\

\
        <% } else { %>\
          <img\
            src="<%= $.cloudinary.url(files[i].public_id, { "version": files[i].version, "format": "jpg", "crop": "fill", "width": 250, "height": 250 }) %>"\
            alt="" width="75" height="75" />\
        <% } %>\

\
        <a href="#" data-remove="<%= files[i].public_id %>">Remove\

\
    <% } %>\

\
';

// This is included here because you would expect to find it here.  The function is actually called
// from event-tracking.js where we have to unbind and rebind the event to support turbolinks
Helpy.didthisHelp = function(yesno){
  var message;
  var contactus;
  if (yesno === "no") {
    message = "
" + Helpy.noHelped + "
";
    contactus = "

" + Helpy.contactUs + "

";
  } else {
    message = "
" + Helpy.yesHelped + "
";
    contactus = '';
  }

  message = "
" + message + "
" + contactus;

  $('#did-this-help').html(message);
  return true;
};

Helpy.showGroup = function() {
  if ($('#topic_private_true').is(':checked')) {
    $('#topic_team_list').parent().removeClass('hidden');
  } else if ($('#topic_private_false').is(':checked')) {
    $('#topic_team_list').parent().addClass('hidden');
  } else {
    $('#topic_team_list').parent().removeClass('hidden');
  }
};

Helpy.loader = function(){
  $('#tickets').html("

");
};

$(document).ready(Helpy.ready);
$(document).on('page:load', Helpy.ready);

$(document).on('page:change', function () {

  //Truncate Q&A responses
  $('.shorten').jTruncate({
    length: 200,
    minTrail: 0,
    moreText: " (more)",
    lessText: " (less)",
    ellipsisText: " ...",
    moreAni: "",
    lessAni: ""
  });

  // Allows image insertion into quill editor
  $('.doc-form-files .cloudinary-fileupload').bind('cloudinarydone', function(e, data) {
    var element = document.querySelector("trix-editor");
    var thisImage = "";
    element.editor.insertHTML(thisImage);

    $('.image_public_id').val(data.result.public_id);
    return true;
  });

});
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2016 Language Technology Group and Interactive Graphics Systems Group, Technische Universität Darmstadt, Germany
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

define([
    'angular',
    'angularMoment',
    './factory/network/ToolFactory',
    './factory/metadata/MetaFactory',
    './factory/source/SourceFactory',
    './factory/source/HighlightFactory',
    './components/sources/SourceController',
    './components/network/NetworkController',
    './components/network/ToolController',
    './components/network/TextModalController',
    './components/network/MergeModalController',
    './components/network/EditModalController',
    './components/network/ConfirmModalController',
    './components/metadata/MetadataController',
    './components/sources/SearchController',
    './components/history/HistoryController',
    './components/histogram/HistogramController',
    './services/playRoutes',
    './services/ObserverService',
    './factory/appData',
    './factory/util',
    './services/underscore-module',
    'ui-layout',
    'ui-router',
    'ui-bootstrap',
    'angularResizable',
    'ngMaterial'
], function (angular) {
    'use strict';

    var app = angular.module('myApp',
        [
            'ui.layout', 'ui.router', 'ui.bootstrap', 'play.routing','angularResizable','ngMaterial',
            'angularMoment', 'underscore', 'myApp.data', 'myApp.observer', 'myApp.util', 'myApp.history',
            'myApp.tools',
            'myApp.textmodal', 'myApp.mergemodal', 'myApp.editmodal', 'myApp.confirmmodal',
            'myApp.network', 'myApp.metadata', 'myApp.source', 'myApp.sourcefactory', 'myApp.highlightfactory',
            'myApp.metafactory', 'myApp.toolfactory',
            'myApp.histogram', 'myApp.search'
        ]
    );

    app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
        $stateProvider
        .state('layout', {
            views: {
                'header': {
                    templateUrl: 'assets/partials/header.html',
                    controller: 'AppController'
                },
                'documentlist': {
                    templateUrl: 'assets/partials/document_list.html',
                    controller: 'SourceController'
                },
                'network': {
                    templateUrl: 'assets/partials/network.html',
                    controller: 'NetworkController'
                },
                'tools': {
                    templateUrl: 'assets/partials/tools.html',
                    controller: 'ToolController'
                },
                'source': {
                    templateUrl: 'assets/partials/source.html',
                    controller: 'SourceController'
                },
                'histogram': {
                    templateUrl: 'assets/partials/histogram.html',
                    controller: 'HistogramController'
                },
                'metadata': {
                    templateUrl: 'assets/partials/metadata.html',
                    controller: 'MetadataController'
                },
                'history': {
                    templateUrl: 'assets/partials/history.html',
                    controller: 'HistoryController'
                },
                'search' : {
                    templateUrl: 'assets/partials/search.html',
                    controller: 'SearchController'
                }
            }
        });
        $urlRouterProvider.otherwise('/');

    }]);

    app.factory('uiShareService', function() {
        var uiProperties = {
            mainContainerHeight: -1,
            mainContainerWidth: -1,
            footerHeight: -1
        };
        return uiProperties;
    });

    app.controller('AppController', ['$scope', '$state', '$timeout', '$window', 'moment', 'appData', 'uiShareService', 'ObserverService', 'playRoutes',
        function ($scope, $state, $timeout, $window, moment, appData, uiShareService, ObserverService, playRoutes) {
            $scope.selectedDataset = '';
            $scope.datasets = ['cable', 'enron'];

            init();

            function init() {
                $state.go('layout');
                // $timeout in order to have the right values right from the beginning on
                $timeout(function() {
                    setUILayoutProperties(parseInt($('#network-maps-container').css('width')), parseInt($('#network-maps-container').css('height'))-96);
                }, 100);
            };

            //TODO: WHEN USING THIS FOR WATCH NO DEEP COPY IS NEEDED!!!!
            $scope.$watch(function () {
                return appData.getDate();
            }, function (newVal, oldVal) {
                if (!angular.equals(newVal, oldVal)) {
                    $scope.date = newVal;
                }
            });

            $scope.$on("angular-resizable.resizeEnd", function (event, args) {
                if(args.id == 'center-box') setUILayoutProperties(args.width, false);
                if(args.id == 'footer') setUILayoutProperties(false, parseInt($('#network-maps-container').css('height'))-96);
                $("#histogram").highcharts().reflow();
                $("#metadata-view .active .active .meta-chart").highcharts().reflow();
            });

            angular.element($window).bind('resize', function () {
                setUILayoutProperties(parseInt($('#network-maps-container').css('width')), parseInt($('#network-maps-container').css('height'))-96);
            });

            /**
             * This function sets properties that describe the dimensions of the UI layout.
             */
            function setUILayoutProperties(mainWidth, mainHeight) {
                if(mainHeight != false) uiShareService.mainContainerHeight = mainHeight;
                if(mainWidth != false) uiShareService.mainContainerWidth = mainWidth;
                // NaN check is necessary because when loading the page the bar chart isn't rendered yet
                uiShareService.footerHeight = parseInt($('#chartBarchart').css('height'));
            }

            // On change event of the UI layout
            $scope.$on('ui.layout.resize', function (e, beforeContainer, afterContainer) {
                //setUILayoutProperties();
            });

            $scope.changeDataset = function() {
                console.log('Changed ' + $scope.selectedDataset);
                playRoutes.controllers.Application.changeDataset($scope.selectedDataset).get().then(function(response) {
                    // Update views with new data from the changed data collection
                    if(response.data.oldDataset != response.data.newDataset) {
                        ObserverService.reset();
                    }
                });
            };

        }]);

    return app;
});
<commit_msg>added theme provider<commit_after>/*
 * Copyright (C) 2016 Language Technology Group and Interactive Graphics Systems Group, Technische Universität Darmstadt, Germany
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

define([
    'angular',
    'angularMoment',
    './factory/network/ToolFactory',
    './factory/metadata/MetaFactory',
    './factory/source/SourceFactory',
    './factory/source/HighlightFactory',
    './components/sources/SourceController',
    './components/network/NetworkController',
    './components/network/ToolController',
    './components/network/TextModalController',
    './components/network/MergeModalController',
    './components/network/EditModalController',
    './components/network/ConfirmModalController',
    './components/metadata/MetadataController',
    './components/sources/SearchController',
    './components/history/HistoryController',
    './components/histogram/HistogramController',
    './services/playRoutes',
    './services/ObserverService',
    './factory/appData',
    './factory/util',
    './services/underscore-module',
    'ui-layout',
    'ui-router',
    'ui-bootstrap',
    'angularResizable',
    'ngMaterial'
], function (angular) {
    'use strict';

    var app = angular.module('myApp',
        [
            'ui.layout', 'ui.router', 'ui.bootstrap', 'play.routing','angularResizable','ngMaterial',
            'angularMoment', 'underscore', 'myApp.data', 'myApp.observer', 'myApp.util', 'myApp.history',
            'myApp.tools',
            'myApp.textmodal', 'myApp.mergemodal', 'myApp.editmodal', 'myApp.confirmmodal',
            'myApp.network', 'myApp.metadata', 'myApp.source', 'myApp.sourcefactory', 'myApp.highlightfactory',
            'myApp.metafactory', 'myApp.toolfactory',
            'myApp.histogram', 'myApp.search'
        ]
    );

    app.config(['$stateProvider', '$urlRouterProvider', '$mdThemingProvider', function($stateProvider, $urlRouterProvider, $mdThemingProvider) {

        //$mdThemingProvider.theme('control-theme')
            //.primaryPalette('light-blue')
            //.backgroundPalette('blue', {
             //   'default': '200'
           // });

        $stateProvider
        .state('layout', {
            views: {
                'header': {
                    templateUrl: 'assets/partials/header.html',
                    controller: 'AppController'
                },
                'documentlist': {
                    templateUrl: 'assets/partials/document_list.html',
                    controller: 'SourceController'
                },
                'network': {
                    templateUrl: 'assets/partials/network.html',
                    controller: 'NetworkController'
                },
                'tools': {
                    templateUrl: 'assets/partials/tools.html',
                    controller: 'ToolController'
                },
                'source': {
                    templateUrl: 'assets/partials/source.html',
                    controller: 'SourceController'
                },
                'histogram': {
                    templateUrl: 'assets/partials/histogram.html',
                    controller: 'HistogramController'
                },
                'metadata': {
                    templateUrl: 'assets/partials/metadata.html',
                    controller: 'MetadataController'
                },
                'history': {
                    templateUrl: 'assets/partials/history.html',
                    controller: 'HistoryController'
                },
                'search' : {
                    templateUrl: 'assets/partials/search.html',
                    controller: 'SearchController'
                }
            }
        });
        $urlRouterProvider.otherwise('/');

    }]);

    app.factory('uiShareService', function() {
        var uiProperties = {
            mainContainerHeight: -1,
            mainContainerWidth: -1,
            footerHeight: -1
        };
        return uiProperties;
    });

    app.controller('AppController', ['$scope', '$state', '$timeout', '$window', 'moment', 'appData', 'uiShareService', 'ObserverService', 'playRoutes',
        function ($scope, $state, $timeout, $window, moment, appData, uiShareService, ObserverService, playRoutes) {
            $scope.selectedDataset = '';
            $scope.datasets = ['cable', 'enron'];

            init();

            function init() {
                $state.go('layout');
                // $timeout in order to have the right values right from the beginning on
                $timeout(function() {
                    setUILayoutProperties(parseInt($('#network-maps-container').css('width')), parseInt($('#network-maps-container').css('height'))-96);
                }, 100);
            };

            //TODO: WHEN USING THIS FOR WATCH NO DEEP COPY IS NEEDED!!!!
            $scope.$watch(function () {
                return appData.getDate();
            }, function (newVal, oldVal) {
                if (!angular.equals(newVal, oldVal)) {
                    $scope.date = newVal;
                }
            });

            $scope.$on("angular-resizable.resizeEnd", function (event, args) {
                if(args.id == 'center-box') setUILayoutProperties(args.width, false);
                if(args.id == 'footer') setUILayoutProperties(false, parseInt($('#network-maps-container').css('height'))-96);
                $("#histogram").highcharts().reflow();
                $("#metadata-view .active .active .meta-chart").highcharts().reflow();
            });

            angular.element($window).bind('resize', function () {
                setUILayoutProperties(parseInt($('#network-maps-container').css('width')), parseInt($('#network-maps-container').css('height'))-96);
            });

            /**
             * This function sets properties that describe the dimensions of the UI layout.
             */
            function setUILayoutProperties(mainWidth, mainHeight) {
                if(mainHeight != false) uiShareService.mainContainerHeight = mainHeight;
                if(mainWidth != false) uiShareService.mainContainerWidth = mainWidth;
                // NaN check is necessary because when loading the page the bar chart isn't rendered yet
                uiShareService.footerHeight = parseInt($('#chartBarchart').css('height'));
            }

            // On change event of the UI layout
            $scope.$on('ui.layout.resize', function (e, beforeContainer, afterContainer) {
                //setUILayoutProperties();
            });

            $scope.changeDataset = function() {
                console.log('Changed ' + $scope.selectedDataset);
                playRoutes.controllers.Application.changeDataset($scope.selectedDataset).get().then(function(response) {
                    // Update views with new data from the changed data collection
                    if(response.data.oldDataset != response.data.newDataset) {
                        ObserverService.reset();
                    }
                });
            };

        }]);

    return app;
});
<|endoftext|>


<commit_before>'use strict';

describe('SimpleVirtualDOMElement', () => {

    it('should exist', () => {
        expect(JSWorks.Internal.SimpleVirtualDOMElement).to.be.ok;
    });

    it('should set attribute', () => {
        const holder = getTestServiceHolder('SimpleVirtualDOM');
        const virtualDOM = holder.getServiceByName('SimpleVirtualDOM');

        const element = virtualDOM.createElement('div');
        expect(element.tagName).to.equal('DIV');

        element.setAttribute('id', 'id1');
        expect(element.getAttribute('id')).to.equal('id1');
    });

    it('should append child', () => {
        const holder = getTestServiceHolder('SimpleVirtualDOM');
        const virtualDOM = holder.getServiceByName('SimpleVirtualDOM');

        const element = virtualDOM.createElement('div');

        for (let i = 0; i < 5; i++) {
            const child = virtualDOM.createElement('div');
            element.appendChild(child);
        }
        expect(element.children.length).to.equal(5);
    });

    it('should remove child', () => {
        const holder = getTestServiceHolder('SimpleVirtualDOM');
        const virtualDOM = holder.getServiceByName('SimpleVirtualDOM');

        const element = virtualDOM.createElement('div');
        for (let i = 0; i < 5; i++) {
            const child = virtualDOM.createElement('div');
            child.setAttribute('id', '' + i);
            element.appendChild(child);
        }

        [0,2,4].forEach(id => {
            element.removeChild(element.children[id]);
        });

        expect(element.children.length).to.equal(2);

        Array.from(element.children).forEach(child => {
            expect([0, 2, 4].includes(child.getAttribute('id'))).to.equal(false);
        });

        Array.from(element.children).forEach(child => {
            expect([1, 3].includes(child.getAttribute('id')));
        })
    });

    it('should render dom element', done => {
        const holder = getTestServiceHolder('SimpleVirtualDOM');
        const virtualDOM = holder.getServiceByName('SimpleVirtualDOM');

        const element = virtualDOM.createElement('div');
        element.setAttribute('id', '1');

        element.render();
        expect(element.rendered.getAttribute('id')).to.equal('1');
        done();
    });

    it('should render dom element after adding children',() => {
        const holder = getTestServiceHolder('SimpleVirtualDOM');
        const virtualDOM = holder.getServiceByName('SimpleVirtualDOM');

        const element = virtualDOM.createElement('div');
        for (let i = 0; i < 5; i++) {
            const child = virtualDOM.createElement('div');
            element.appendChild(child);
        }
        element.render();

        expect(element.rendered.childNodes.length).to.equal(5);
    });

    it('should render DOM element after deleting children', () => {
        const holder = getTestServiceHolder('SimpleVirtualDOM');
        const virtualDOM = holder.getServiceByName('SimpleVirtualDOM');

        const element = virtualDOM.createElement('div');
        for (let i = 0; i < 5; i++) {
            const child = virtualDOM.createElement('div');
            element.appendChild(child);
        }
        element.render();
        expect(element.rendered.childNodes.length).to.equal(5);
        expect(element.children.length).to.equal(5);

        [0, 2, 4].forEach(index => {
            element.removeChild(element.children[index]);
        });

        element.render();
        expect(element.rendered.childNodes.length).to.equal(2);
    });

});
<commit_msg>Added test for deleting<commit_after>'use strict';

describe('SimpleVirtualDOMElement', () => {

    it('should exist', () => {
        expect(JSWorks.Internal.SimpleVirtualDOMElement).to.be.ok;
    });

    it('should set attribute', () => {
        const holder = getTestServiceHolder('SimpleVirtualDOM');
        const virtualDOM = holder.getServiceByName('SimpleVirtualDOM');

        const element = virtualDOM.createElement('div');
        expect(element.tagName).to.equal('DIV');

        element.setAttribute('id', 'id1');
        expect(element.getAttribute('id')).to.equal('id1');
    });

    it('should append child', () => {
        const holder = getTestServiceHolder('SimpleVirtualDOM');
        const virtualDOM = holder.getServiceByName('SimpleVirtualDOM');

        const element = virtualDOM.createElement('div');

        for (let i = 0; i < 5; i++) {
            const child = virtualDOM.createElement('div');
            element.appendChild(child);
        }
        expect(element.children.length).to.equal(5);
    });

    it('should remove child', () => {
        const holder = getTestServiceHolder('SimpleVirtualDOM');
        const virtualDOM = holder.getServiceByName('SimpleVirtualDOM');

        const element = virtualDOM.createElement('div');
        for (let i = 0; i < 5; i++) {
            const child = virtualDOM.createElement('div');
            child.setAttribute('id', '' + i);
            element.appendChild(child);
        }

        [0,2,4].forEach(id => {
            element.removeChild(element.children[id]);
        });

        expect(element.children.length).to.equal(2);

        Array.from(element.children).forEach(child => {
            expect([0, 2, 4].includes(child.getAttribute('id'))).to.equal(false);
        });

        Array.from(element.children).forEach(child => {
            expect([1, 3].includes(child.getAttribute('id')));
        })
    });

    it('should render dom element', done => {
        const holder = getTestServiceHolder('SimpleVirtualDOM');
        const virtualDOM = holder.getServiceByName('SimpleVirtualDOM');

        const element = virtualDOM.createElement('div');
        element.setAttribute('id', '1');

        element.render();
        expect(element.rendered.getAttribute('id')).to.equal('1');
        done();
    });

    it('should render dom element after adding children',() => {
        const holder = getTestServiceHolder('SimpleVirtualDOM');
        const virtualDOM = holder.getServiceByName('SimpleVirtualDOM');

        const element = virtualDOM.createElement('div');
        for (let i = 0; i < 5; i++) {
            const child = virtualDOM.createElement('div');
            element.appendChild(child);
        }
        element.render();

        expect(element.rendered.childNodes.length).to.equal(5);
    });

    it('should render DOM element after deleting children', () => {
        const holder = getTestServiceHolder('SimpleVirtualDOM');
        const virtualDOM = holder.getServiceByName('SimpleVirtualDOM');

        const element = virtualDOM.createElement('div');
        for (let i = 0; i < 5; i++) {
            const child = virtualDOM.createElement('div');
            child.setAttribute('id', 'id' + i);
            element.appendChild(child);
        }
        element.render();
        expect(element.rendered.childNodes.length).to.equal(5);
        expect(element.children.length).to.equal(5);
        console.log(element);
        [0, 2, 4].forEach(index => {
            element.removeChild(element.children[index]);
        });

        element.render();
        expect(element.rendered.childNodes.length).to.equal(2);

        Array.from(element.children).forEach(child => {
            expect(['id1', 'id3'].includes(child.getAttribute('id'))).to.equal(true);
        });
    });

});
<|endoftext|>


<commit_before>"use strict";

var fs = require("fs");
var fse = require("fs-extra");
var path = require("path");

var chai = require("chai");
var expect = chai.expect;

var MiddlewareJs = require("../lib/middleware");

// describing the logger variable instantiated above.
describe("Middleware.js Loader with Names", function() {

  beforeEach(function(done) {
    // create the middleware directory for the configuration
    var configMiddlewareDir = path.resolve(MiddlewareJs.APP_DIR, "middleware");
    fse.mkdirsSync(configMiddlewareDir);

    // copy the fixture config
    var fromFile = path.resolve("./test/fixture/middleware-conf.js");
    var toFile = path.resolve(configMiddlewareDir, "config.js");
    fs.writeFileSync(toFile, fs.readFileSync(fromFile), "utf8");

    done();
  });

  afterEach(function(done) {
    // undo the config
    fse.removeSync(path.resolve(MiddlewareJs.APP_DIR, "middleware"));

    done();
  });

  it("should load middleware using dot notation and index file APP/middleware/config.js", function(done) {
    var conf = MiddlewareJs.instance().load("middleware.config");
    expect(conf).to.be.an("object");
    expect(conf.isp.logging.console.level).to.equal("debug");
    expect(conf.isp.monitoring.type).to.equal("newrelic");
    expect(conf.superApp.server.secure).to.be.true;

    done();
  });
});
<commit_msg>Issue #1: Removing duplicate test, as it can be moved to loadSettingsFromMiddleware<commit_after><|endoftext|>


<commit_before>var models = [];

$.getJSON( "models.json", function( data ) {
    models = data;
});

function getCriteria () {
    var selected = [];
    $('input:checked').each(function() {
        selected.push($(this).attr('name'));
    });
    return selected;
}

function updateScores () {
    var criteria = getCriteria();

    $.each(models, function(){
        this.score = calculateScore(criteria, this.properties);
        cell = $("#" + this.key + " > .score");
        cell.html(toPercentageString(this.score));
        cell.css({"background-size": toPercentageString(this.score) + " 100%"});
    });
}

// Calculated score by comparing list of user 'wished' properties
// with the properties defined by the model.
function calculateScore(userProperties, modelProperties) {
    if (userProperties.length == 0) {
        return 0;
    }
    var matches = 0;
    for (var i = 0; i < userProperties.length; i++) {
        if ($.inArray(userProperties[i], modelProperties) > -1) {
            matches++;
        }
    }
    return matches / userProperties.length;
};

function toPercentageString(number) {
    return (number*100).toFixed(2) + "%";
}

// From http://stackoverflow.com/a/7558600
function sortTable(){
    var tbl = document.getElementById("output_table").tBodies[0];
    var store = [];
    for(var i=0, len=tbl.rows.length; i<len; i++){
        var row = tbl.rows[i];
        var sortnr = parseFloat(row.cells[1].textContent || row.cells[1].innerText);
        var name = row.cells[0].textContent;
        if(!isNaN(sortnr)) store.push([sortnr, name, row]);
    }
    store.sort(function(x,y){
        if (y[0] > x[0]) return 1;
        if (y[0] < x[0]) return -1;

        if (y[1] > x[1]) return -1;
        if (y[1] < x[1]) return 1;
        return 0;
    });
    for(var i=0, len=store.length; i<len; i++){
        tbl.appendChild(store[i][2]);
    }
    store = null;
}

function hideDeselectAll(){
    $('#wis').hide();
}

function showDeslectAll(){
    $('#wis').show();
}

function updateAll(){
    updateScores();
    sortTable();
    if($('input:checkbox:checked').length > 0) {
        showDeslectAll();
    }
    else {
        hideDeselectAll();
    }
}

$(document).ready(function(){
    $('input:checkbox').change(function() {
        updateAll();
    });

    $(document).ready(function(){
        $("#output table").sticky({topSpacing:20});
    });

    $('#wis').hide().click(function(){
        $('input:checkbox').removeAttr('checked');
        updateAll();
    });
});
<commit_msg>reorganize functions a bit<commit_after>var models = [];

$.getJSON( "models.json", function( data ) {
    models = data;
});

function getCriteria () {
    var selected = [];
    $('input:checked').each(function() {
        selected.push($(this).attr('name'));
    });
    return selected;
}

function updateScores () {
    var criteria = getCriteria();

    $.each(models, function(){
        this.score = calculateScore(criteria, this.properties);
        cell = $("#" + this.key + " > .score");
        cell.html(toPercentageString(this.score));
        cell.css({"background-size": toPercentageString(this.score) + " 100%"});
    });
}

// Calculated score by comparing list of user 'wished' properties
// with the properties defined by the model.
function calculateScore(userProperties, modelProperties) {
    if (userProperties.length == 0) {
        return 0;
    }
    var matches = 0;
    for (var i = 0; i < userProperties.length; i++) {
        if ($.inArray(userProperties[i], modelProperties) > -1) {
            matches++;
        }
    }
    return matches / userProperties.length;
};

function toPercentageString(number) {
    return (number*100).toFixed(2) + "%";
}

// From http://stackoverflow.com/a/7558600
function sortTable(){
    var tbl = document.getElementById("output_table").tBodies[0];
    var store = [];
    for(var i=0, len=tbl.rows.length; i<len; i++){
        var row = tbl.rows[i];
        var sortnr = parseFloat(row.cells[1].textContent || row.cells[1].innerText);
        var name = row.cells[0].textContent;
        if(!isNaN(sortnr)) store.push([sortnr, name, row]);
    }
    store.sort(function(x,y){
        if (y[0] > x[0]) return 1;
        if (y[0] < x[0]) return -1;

        if (y[1] > x[1]) return -1;
        if (y[1] < x[1]) return 1;
        return 0;
    });
    for(var i=0, len=store.length; i<len; i++){
        tbl.appendChild(store[i][2]);
    }
    store = null;
}

function hideDeselectAll(){
    $('#wis').hide();
}

function showDeslectAll(){
    $('#wis').show();
}

function renderDeselectAll(){
    if($('input:checkbox:checked').length > 0) {
        showDeslectAll();
    }
    else {
        hideDeselectAll();
    }
}

function updateAll(){
    updateScores();
    sortTable();
    renderDeselectAll();
}

$(document).ready(function(){
    $('input:checkbox').change(function() {
        updateAll();
    });

    $(document).ready(function(){
        $("#output table").sticky({topSpacing:20});
    });

    $('#wis').hide().click(function(){
        $('input:checkbox').removeAttr('checked');
        updateAll();
    });
});
<|endoftext|>


<commit_before>var TRACKING_TESTING_ON = true;
var TRACKING_TESTING_LAT = 40.704887199999995, TRACKING_TESTING_LON = -74.0123736;
moveMe = function (i) {
  console.log("moving you");
  var self = SoapStone.app.mapView;
  TRACKING_TESTING_LAT += i/10000
  TRACKING_TESTING_LON += i/10000
  self.trackingLocation =  new google.maps.LatLng(TRACKING_TESTING_LAT, TRACKING_TESTING_LON);
  self.setCirclePosition(self.circle, {coords: {latitude: TRACKING_TESTING_LAT, longitude: TRACKING_TESTING_LON}});
  self.controller.map.refreshDrops();
};

SoapStone.Map = function () {
  this.allDrops = [];
 //  this.outsideDrops = [];
	// this.clickableDrops = [];
  $('#set-center').on('click',function(e){
    SoapStone.app.mapView.centerMap();
  });
};

SoapStone.Map.prototype.addClickableDrop = function (dropData) {
  var drop = new SoapStone.Drop(dropData);
  if (drop.lat && drop.lon) {
    drop.marker = new google.maps.Marker({
      position: new google.maps.LatLng(drop.lat, drop.lon),
      cursor: 'crosshair',
      icon: {
        path: 'M -2,0 0,-2 2,0 0,2 z',//google.maps.SymbolPath.BACKWARD_CLOSED_ARROW,
        scale: 1,//4,
        strokeColor: "hsla("+drop.user.hue+",100%,50%,0.9)",
        strokeWeight: 5//3
      }
    });
    drop.marker.setMap(SoapStone.app.mapView.map);
    SoapStone.app.map.clickableDrops.unshift(drop);//bad???? why was 'this' the window and not a map?
  }
};

SoapStone.Map.prototype.addOutsideDrop = function (dropData) {
  var drop = new SoapStone.Drop(dropData);
  if (drop.lat && drop.lon) {
  drop.marker = new google.maps.Marker({
    position: new google.maps.LatLng(drop.lat, drop.lon),
    clickable: false,
    icon: {
      path: 'M -2,0 0,-2 2,0 0,2 z',//google.maps.SymbolPath.BACKWARD_OPEN_ARROW,
      scale: 4,
      strokeColor: "hsl("+drop.user.hue+",30%,50%)",
      strokeWeight: 3,
    }
  });
  drop.marker.setMap(SoapStone.app.mapView.map);
  SoapStone.app.map.outsideDrops.unshift(drop);
  }
};

SoapStone.Map.prototype.clearMarkers = function(){
  this.allDrops.forEach(function(drop){
    drop.marker.setMap(null);
  });
  this.allDrops = [];
};

SoapStone.Map.prototype.hitTheDataBaseForDrops = function (filter) {
  var self = this;
  var myUrl = '/drops';
  var myPosition = SoapStone.app.mapView.trackingLocation;
  var myData = { lat: myPosition.lat(), lon: myPosition.lng() }
  if (filter){
    if (typeof filter !== "number"){
      myUrl+=filter;
    }else{
      myData.user_id = filter;
    }
  }
  return $.ajax({
    url: myUrl,
    method : "get",
    data: myData,
    dataType: 'json'
  })
  .then(function(response) {
    self.addSurroundingDrops(response);//takes all the data within a mileish and turns them into drops and puts them on an array at self.allDrops
    // var clickableArray = response[0];
    // var outsideArray = response[1];
    // clickableArray.updateDropsArray(self.addClickableDrop, self.clickableDrops, self.outsideDrops, 50)
    // outsideArray.updateDropsArray(self.addOutsideDrop, self.outsideDrops, self.clickableDrops, 100)
  });
};

SoapStone.Map.prototype.loadDrops = function (filter) {
  this.clearMarkers();

	var self = this;
  var myPosition = self.controller.mapView.trackingLocation;
  var myData = { lat: myPosition.lat(), lon: myPosition.lng() }
  var myUrl = '/drops';//drops/filter
  if (filter){
    if (typeof filter !== "number"){
      myUrl+=filter;// '/followees'
    }else{
      myData.user_id = filter;
    }
  }
	return $.ajax({
    url: myUrl,
    method : "get",
    data: myData,
    dataType: 'json'
  })
	.then(function(response) {//response should be ONE array of all drops within a mileish

    self.addSurroundingDrops(response);
	});
};

// SoapStone.MapView.prototype.getLocation = function() {
//     return new Promise(function(resolve, reject) {
//       if ("geolocation" in navigator) {
//         navigator.geolocation.getCurrentPosition(function(position) {
//           var coords = {};
//           coords.latitude = position.coords.latitude;
//           coords.longitude = position.coords.longitude;
//           resolve(coords);
//         });
//       } else {
//           reject(); //Geolocation not available
//       }
//   });
// };

SoapStone.MapView = function () {
  this.filter = null;
};

SoapStone.MapView.prototype.init = function () {
  var self = this;
  var mapStyles = [{featureType: "all",
      elementType: "labels.icon",
      stylers: [
        { visibility: "off" }
      ]
    },
    {
    "featureType": "landscape",
    "stylers": [
      {
        "hue": "#FF0300"
      },
      {
        "saturation": -100
      },
      {
        "lightness": 156
      },
      {
        "gamma": 1
      }
    ]
  },
  {
    "featureType": "road.highway",
    "stylers": [
      {
        "hue": "#FF2500"
      },
      {
        "saturation": -100
      },
      {
        "lightness": 138.60000000000002
      },
      {
        "gamma": 1
      }
    ]
  },
  {
    "featureType": "road.arterial",
    "stylers": [
      {
        "hue": "#7F00FF"
      },
      {
        "saturation": -71.42857142857149
      },
      {
        "lightness": 45.709803921568636
      },
      {
        "gamma": 1
      }
    ]
  },
  {
    "featureType": "road.local",
    "stylers": [
      {
        "hue": "#7F00FF"
      },
      {
        "saturation": -71.42857142857149
      },
      {
        "lightness": 46.50980392156862
      },
      {
        "gamma": 1
      }
    ]
  },
  {
    "featureType": "water",
    "stylers": [
      {
        "hue": "#0078FF"
      },
      {
        "saturation": 0
      },
      {
        "lightness": 47
      },
      {
        "gamma": 1
      }
    ]
  },
  {
    "featureType": "poi",
    "stylers": [
      {
        "hue": "#FF1B00"
      },
      {
        "saturation": -95.8
      },
      {
        "lightness": 143.8
      },
      {
        "gamma": 1
      }
    ]}];//folded text for the style press command option ']' to unfold or '[' to refold
  return new Promise(function (resolve, reject) {
      if ("geolocation" in navigator) {
        navigator.geolocation.getCurrentPosition(function(position) {
          if (TRACKING_TESTING_ON) {
            self.trackingLocation = new google.maps.LatLng(TRACKING_TESTING_LAT, TRACKING_TESTING_LON);
          } else {
            self.trackingLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
          }
          self.mapProp = {
            center: self.trackingLocation, //find center of collection
            zoom:17,
            zoomControlOptions: {
              position: google.maps.ControlPosition.TOP_RIGHT
            },
            streetViewControl: false,
            styles: mapStyles,
            mapTypeId:google.maps.MapTypeId.ROADMAP
          };
          self.map = new google.maps.Map(document.getElementById("googleMap"),self.mapProp);
          self.circle = new google.maps.Circle({
            strokeColor: '#0000FF',
            strokeOpacity: 0.25,
            strokeWeight: 2,
            fillColor: '#00FFFF',
            fillOpacity: 0.25,
            map: self.map,
            center: self.trackingLocation,//new google.maps.LatLng(TRACKING_TESTING_LAT, TRACKING_TESTING_LON),//self.trackingLocation,
            radius: 330 * 0.3048 //feet to meters
          });
          resolve(self);
        });
      } else {
        reject(); //Geolocation not available
      }
  });
};

SoapStone.MapView.prototype.showDrops = function (allDrops) {
	var self = this;
  allDrops.forEach(function(drop){
    if(drop.withinRange){
      if (drop.hasEventListener == null){
        google.maps.event.addListener(drop.marker, 'click', function () {
            SoapStone.app.showDrop(drop.id);
        });
      }
      drop.hasEventListener = true;
    }else{
      if (drop.hasEventListener){
        google.maps.event.clearListeners(drop.marker, 'click');
      }
      drop.hasEventListener = null;
    }
  });
};

SoapStone.MapView.prototype.centerMap = function(){
  var self = this;
  self.map.panTo(self.trackingLocation);
};

SoapStone.MapView.prototype.watchCurrentPosition = function() {
  var self = this;
  navigator.geolocation.watchPosition(function (position) {
    if (TRACKING_TESTING_ON) {
      self.trackingLocation = new google.maps.LatLng(TRACKING_TESTING_LAT, TRACKING_TESTING_LON);
    } else {
      self.trackingLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
    }
    self.setCirclePosition(self.circle, position);

    self.controller.map.refreshDrops();
  });
};

SoapStone.MapView.prototype.setCirclePosition = function (circle, position) {
  circle.setCenter( new google.maps.LatLng(
    position.coords.latitude,
    position.coords.longitude)
  );
};

<commit_msg>testing with filtering :)<commit_after>var TRACKING_TESTING_ON = true;
var TRACKING_TESTING_LAT = 40.704887199999995, TRACKING_TESTING_LON = -74.0123736;
moveMe = function (i,j) {
  console.log("moving you");
  var self = SoapStone.app.mapView;
  TRACKING_TESTING_LAT += i/10000
  TRACKING_TESTING_LON += j/10000
  self.trackingLocation =  new google.maps.LatLng(TRACKING_TESTING_LAT, TRACKING_TESTING_LON);
  self.setCirclePosition(self.circle, {coords: {latitude: TRACKING_TESTING_LAT, longitude: TRACKING_TESTING_LON}});
  self.controller.map.refreshDrops();
};

SoapStone.Map = function () {
  this.allDrops = [];
 //  this.outsideDrops = [];
	// this.clickableDrops = [];
  $('#set-center').on('click',function(e){
    SoapStone.app.mapView.centerMap();
  });
};

SoapStone.Map.prototype.addClickableDrop = function (dropData) {
  var drop = new SoapStone.Drop(dropData);
  if (drop.lat && drop.lon) {
    drop.marker = new google.maps.Marker({
      position: new google.maps.LatLng(drop.lat, drop.lon),
      cursor: 'crosshair',
      icon: {
        path: 'M -2,0 0,-2 2,0 0,2 z',//google.maps.SymbolPath.BACKWARD_CLOSED_ARROW,
        scale: 1,//4,
        strokeColor: "hsla("+drop.user.hue+",100%,50%,0.9)",
        strokeWeight: 5//3
      }
    });
    drop.marker.setMap(SoapStone.app.mapView.map);
    SoapStone.app.map.clickableDrops.unshift(drop);//bad???? why was 'this' the window and not a map?
  }
};

SoapStone.Map.prototype.addOutsideDrop = function (dropData) {
  var drop = new SoapStone.Drop(dropData);
  if (drop.lat && drop.lon) {
  drop.marker = new google.maps.Marker({
    position: new google.maps.LatLng(drop.lat, drop.lon),
    clickable: false,
    icon: {
      path: 'M -2,0 0,-2 2,0 0,2 z',//google.maps.SymbolPath.BACKWARD_OPEN_ARROW,
      scale: 4,
      strokeColor: "hsl("+drop.user.hue+",30%,50%)",
      strokeWeight: 3,
    }
  });
  drop.marker.setMap(SoapStone.app.mapView.map);
  SoapStone.app.map.outsideDrops.unshift(drop);
  }
};

SoapStone.Map.prototype.clearMarkers = function(){
  this.allDrops.forEach(function(drop){
    drop.marker.setMap(null);
  });
  this.allDrops = [];
};

SoapStone.Map.prototype.hitTheDataBaseForDrops = function (filter) {
  var self = this;
  var myUrl = '/drops';
  var myPosition = SoapStone.app.mapView.trackingLocation;
  var myData = { lat: myPosition.lat(), lon: myPosition.lng() }
  if (filter){
    if (typeof filter !== "number"){
      myUrl+=filter;
    }else{
      myData.user_id = filter;
    }
  }
  return $.ajax({
    url: myUrl,
    method : "get",
    data: myData,
    dataType: 'json'
  })
  .then(function(response) {
    self.addSurroundingDrops(response);//takes all the data within a mileish and turns them into drops and puts them on an array at self.allDrops
    // var clickableArray = response[0];
    // var outsideArray = response[1];
    // clickableArray.updateDropsArray(self.addClickableDrop, self.clickableDrops, self.outsideDrops, 50)
    // outsideArray.updateDropsArray(self.addOutsideDrop, self.outsideDrops, self.clickableDrops, 100)
  });
};

SoapStone.Map.prototype.loadDrops = function (filter) {
  this.clearMarkers();

	var self = this;
  var myPosition = self.controller.mapView.trackingLocation;
  var myData = { lat: myPosition.lat(), lon: myPosition.lng() }
  var myUrl = '/drops';//drops/filter
  if (filter){
    if (typeof filter !== "number"){
      myUrl+=filter;// '/followees'
    }else{
      myData.user_id = filter;
    }
  }
	return $.ajax({
    url: myUrl,
    method : "get",
    data: myData,
    dataType: 'json'
  })
	.then(function(response) {//response should be ONE array of all drops within a mileish

    self.addSurroundingDrops(response);
	});
};

// SoapStone.MapView.prototype.getLocation = function() {
//     return new Promise(function(resolve, reject) {
//       if ("geolocation" in navigator) {
//         navigator.geolocation.getCurrentPosition(function(position) {
//           var coords = {};
//           coords.latitude = position.coords.latitude;
//           coords.longitude = position.coords.longitude;
//           resolve(coords);
//         });
//       } else {
//           reject(); //Geolocation not available
//       }
//   });
// };

SoapStone.MapView = function () {
  this.filter = null;
};

SoapStone.MapView.prototype.init = function () {
  var self = this;
  var mapStyles = [{featureType: "all",
      elementType: "labels.icon",
      stylers: [
        { visibility: "off" }
      ]
    },
    {
    "featureType": "landscape",
    "stylers": [
      {
        "hue": "#FF0300"
      },
      {
        "saturation": -100
      },
      {
        "lightness": 156
      },
      {
        "gamma": 1
      }
    ]
  },
  {
    "featureType": "road.highway",
    "stylers": [
      {
        "hue": "#FF2500"
      },
      {
        "saturation": -100
      },
      {
        "lightness": 138.60000000000002
      },
      {
        "gamma": 1
      }
    ]
  },
  {
    "featureType": "road.arterial",
    "stylers": [
      {
        "hue": "#7F00FF"
      },
      {
        "saturation": -71.42857142857149
      },
      {
        "lightness": 45.709803921568636
      },
      {
        "gamma": 1
      }
    ]
  },
  {
    "featureType": "road.local",
    "stylers": [
      {
        "hue": "#7F00FF"
      },
      {
        "saturation": -71.42857142857149
      },
      {
        "lightness": 46.50980392156862
      },
      {
        "gamma": 1
      }
    ]
  },
  {
    "featureType": "water",
    "stylers": [
      {
        "hue": "#0078FF"
      },
      {
        "saturation": 0
      },
      {
        "lightness": 47
      },
      {
        "gamma": 1
      }
    ]
  },
  {
    "featureType": "poi",
    "stylers": [
      {
        "hue": "#FF1B00"
      },
      {
        "saturation": -95.8
      },
      {
        "lightness": 143.8
      },
      {
        "gamma": 1
      }
    ]}];//folded text for the style press command option ']' to unfold or '[' to refold
  return new Promise(function (resolve, reject) {
      if ("geolocation" in navigator) {
        navigator.geolocation.getCurrentPosition(function(position) {
          if (TRACKING_TESTING_ON) {
            self.trackingLocation = new google.maps.LatLng(TRACKING_TESTING_LAT, TRACKING_TESTING_LON);
          } else {
            self.trackingLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
          }
          self.mapProp = {
            center: self.trackingLocation, //find center of collection
            zoom:17,
            zoomControlOptions: {
              position: google.maps.ControlPosition.TOP_RIGHT
            },
            streetViewControl: false,
            styles: mapStyles,
            mapTypeId:google.maps.MapTypeId.ROADMAP
          };
          self.map = new google.maps.Map(document.getElementById("googleMap"),self.mapProp);
          self.circle = new google.maps.Circle({
            strokeColor: '#0000FF',
            strokeOpacity: 0.25,
            strokeWeight: 2,
            fillColor: '#00FFFF',
            fillOpacity: 0.25,
            map: self.map,
            center: self.trackingLocation,//new google.maps.LatLng(TRACKING_TESTING_LAT, TRACKING_TESTING_LON),//self.trackingLocation,
            radius: 330 * 0.3048 //feet to meters
          });
          resolve(self);
        });
      } else {
        reject(); //Geolocation not available
      }
  });
};

SoapStone.MapView.prototype.showDrops = function (allDrops) {
	var self = this;
  allDrops.forEach(function(drop){
    if(drop.withinRange){
      if (drop.hasEventListener == null){
        google.maps.event.addListener(drop.marker, 'click', function () {
            SoapStone.app.showDrop(drop.id);
        });
      }
      drop.hasEventListener = true;
    }else{
      if (drop.hasEventListener){
        google.maps.event.clearListeners(drop.marker, 'click');
      }
      drop.hasEventListener = null;
    }
  });
};

SoapStone.MapView.prototype.centerMap = function(){
  var self = this;
  self.map.panTo(self.trackingLocation);
};

SoapStone.MapView.prototype.watchCurrentPosition = function() {
  var self = this;
  navigator.geolocation.watchPosition(function (position) {
    if (TRACKING_TESTING_ON) {
      self.trackingLocation = new google.maps.LatLng(TRACKING_TESTING_LAT, TRACKING_TESTING_LON);
    } else {
      self.trackingLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
    }
    self.setCirclePosition(self.circle, position);

    self.controller.map.refreshDrops();
  });
};

SoapStone.MapView.prototype.setCirclePosition = function (circle, position) {
  circle.setCenter( new google.maps.LatLng(
    position.coords.latitude,
    position.coords.longitude)
  );
};

<|endoftext|>


<commit_before>import Map from '../../../../src/ol/Map.js';
import View from '../../../../src/ol/View.js';
import VectorRenderTile from '../../../../src/ol/VectorRenderTile.js';
import VectorTile from '../../../../src/ol/VectorTile.js';
import GeoJSON from '../../../../src/ol/format/GeoJSON.js';
import MVT from '../../../../src/ol/format/MVT.js';
import VectorTileLayer from '../../../../src/ol/layer/VectorTile.js';
import {get as getProjection} from '../../../../src/ol/proj.js';
import VectorTileSource from '../../../../src/ol/source/VectorTile.js';
import {createXYZ} from '../../../../src/ol/tilegrid.js';
import TileGrid from '../../../../src/ol/tilegrid/TileGrid.js';
import {listen, unlistenByKey} from '../../../../src/ol/events.js';
import TileState from '../../../../src/ol/TileState.js';

describe('ol.source.VectorTile', function() {

  const format = new MVT();
  const source = new VectorTileSource({
    format: format,
    tilePixelRatio: 8,
    url: 'spec/ol/data/{z}-{x}-{y}.vector.pbf'
  });
  let tile;

  describe('constructor', function() {
    it('sets the format on the instance', function() {
      expect(source.format_).to.equal(format);
    });

    it('uses ol.VectorTile as default tileClass', function() {
      expect(source.tileClass).to.equal(VectorTile);
    });

    it('creates a 512 XYZ tilegrid by default', function() {
      const tileGrid = createXYZ({tileSize: 512});
      expect(source.tileGrid.tileSize_).to.equal(tileGrid.tileSize_);
      expect(source.tileGrid.extent_).to.equal(tileGrid.extent_);
    });
  });

  describe('#getTile()', function() {
    it('creates a tile with the correct tile class', function() {
      tile = source.getTile(0, 0, 0, 1, getProjection('EPSG:3857'));
      expect(tile).to.be.a(VectorRenderTile);
    });
    it('sets the correct tileCoord on the created tile', function() {
      expect(tile.getTileCoord()).to.eql([0, 0, 0]);
    });
    it('fetches tile from cache when requested again', function() {
      expect(source.getTile(0, 0, 0, 1, getProjection('EPSG:3857')))
        .to.equal(tile);
    });
    it('loads source tiles', function(done) {
      const source = new VectorTileSource({
        format: new GeoJSON(),
        url: 'spec/ol/data/point.json'
      });
      const tile = source.getTile(0, 0, 0, 1, source.getProjection());

      tile.load();
      const key = listen(tile, 'change', function(e) {
        if (tile.getState() === TileState.LOADED) {
          const sourceTile = tile.load()[0];
          expect(sourceTile.getFeatures().length).to.be.greaterThan(0);
          unlistenByKey(key);
          done();
        }
      });
    });

  });

  describe('#getTileGridForProjection', function() {
    it('creates a tile grid with the source tile grid\'s tile size', function() {
      const tileGrid = source.getTileGridForProjection(getProjection('EPSG:3857'));
      expect(tileGrid.getTileSize(0)).to.be(512);
    });
  });

  describe('Tile load events', function() {
    it('triggers tileloadstart and tileloadend with ol.VectorTile', function(done) {
      tile = source.getTile(14, 8938, 5680, 1, getProjection('EPSG:3857'));
      let started = false;
      source.on('tileloadstart', function() {
        started = true;
      });
      source.on('tileloadend', function(e) {
        expect(started).to.be(true);
        expect(e.tile).to.be.a(VectorTile);
        expect(e.tile.getFeatures().length).to.be(1327);
        done();
      });
      tile.load();
    });
  });

  describe('different source and render tile grids', function() {

    let source, map, loaded, requested, target;

    beforeEach(function() {

      loaded = [];
      requested = 0;

      function tileUrlFunction(tileCoord) {
        ++requested;
        if (tileCoord.toString() == '5,13,-29') {
          return tileCoord.join('/');
        }
      }

      function tileLoadFunction(tile, src) {
        tile.setLoader(function() {});
        loaded.push(src);
      }

      const extent = [665584.2026596286, 7033250.839875697, 667162.0221431496, 7035280.378636755];

      source = new VectorTileSource({
        tileGrid: new TileGrid({
          origin: [218128, 6126002],
          resolutions: [4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1, 0.5]
        }),
        tileUrlFunction: tileUrlFunction,
        tileLoadFunction: tileLoadFunction
      });

      target = document.createElement('div');
      target.style.width = target.style.height = '100px';
      document.body.appendChild(target);

      map = new Map({
        layers: [
          new VectorTileLayer({
            extent: extent,
            source: source
          })
        ],
        target: target,
        view: new View({
          zoom: 11,
          center: [666373.1624999996, 7034265.3572]
        })
      });

    });

    afterEach(function() {
      document.body.removeChild(target);
    });

    it('loads available tiles', function(done) {
      map.renderSync();
      setTimeout(function() {
        expect(requested).to.be.greaterThan(1);
        expect(loaded).to.eql(['5/13/-29']);
        done();
      }, 0);
    });

  });

});
<commit_msg>Remove tilePixelRatio options from ol.source.VectorTile<commit_after>import Map from '../../../../src/ol/Map.js';
import View from '../../../../src/ol/View.js';
import VectorRenderTile from '../../../../src/ol/VectorRenderTile.js';
import VectorTile from '../../../../src/ol/VectorTile.js';
import GeoJSON from '../../../../src/ol/format/GeoJSON.js';
import MVT from '../../../../src/ol/format/MVT.js';
import VectorTileLayer from '../../../../src/ol/layer/VectorTile.js';
import {get as getProjection} from '../../../../src/ol/proj.js';
import VectorTileSource from '../../../../src/ol/source/VectorTile.js';
import {createXYZ} from '../../../../src/ol/tilegrid.js';
import TileGrid from '../../../../src/ol/tilegrid/TileGrid.js';
import {listen, unlistenByKey} from '../../../../src/ol/events.js';
import TileState from '../../../../src/ol/TileState.js';

describe('ol.source.VectorTile', function() {

  const format = new MVT();
  const source = new VectorTileSource({
    format: format,
    url: 'spec/ol/data/{z}-{x}-{y}.vector.pbf'
  });
  let tile;

  describe('constructor', function() {
    it('sets the format on the instance', function() {
      expect(source.format_).to.equal(format);
    });

    it('uses ol.VectorTile as default tileClass', function() {
      expect(source.tileClass).to.equal(VectorTile);
    });

    it('creates a 512 XYZ tilegrid by default', function() {
      const tileGrid = createXYZ({tileSize: 512});
      expect(source.tileGrid.tileSize_).to.equal(tileGrid.tileSize_);
      expect(source.tileGrid.extent_).to.equal(tileGrid.extent_);
    });
  });

  describe('#getTile()', function() {
    it('creates a tile with the correct tile class', function() {
      tile = source.getTile(0, 0, 0, 1, getProjection('EPSG:3857'));
      expect(tile).to.be.a(VectorRenderTile);
    });
    it('sets the correct tileCoord on the created tile', function() {
      expect(tile.getTileCoord()).to.eql([0, 0, 0]);
    });
    it('fetches tile from cache when requested again', function() {
      expect(source.getTile(0, 0, 0, 1, getProjection('EPSG:3857')))
        .to.equal(tile);
    });
    it('loads source tiles', function(done) {
      const source = new VectorTileSource({
        format: new GeoJSON(),
        url: 'spec/ol/data/point.json'
      });
      const tile = source.getTile(0, 0, 0, 1, source.getProjection());

      tile.load();
      const key = listen(tile, 'change', function(e) {
        if (tile.getState() === TileState.LOADED) {
          const sourceTile = tile.load()[0];
          expect(sourceTile.getFeatures().length).to.be.greaterThan(0);
          unlistenByKey(key);
          done();
        }
      });
    });

  });

  describe('#getTileGridForProjection', function() {
    it('creates a tile grid with the source tile grid\'s tile size', function() {
      const tileGrid = source.getTileGridForProjection(getProjection('EPSG:3857'));
      expect(tileGrid.getTileSize(0)).to.be(512);
    });
  });

  describe('Tile load events', function() {
    it('triggers tileloadstart and tileloadend with ol.VectorTile', function(done) {
      tile = source.getTile(14, 8938, 5680, 1, getProjection('EPSG:3857'));
      let started = false;
      source.on('tileloadstart', function() {
        started = true;
      });
      source.on('tileloadend', function(e) {
        expect(started).to.be(true);
        expect(e.tile).to.be.a(VectorTile);
        expect(e.tile.getFeatures().length).to.be(1327);
        done();
      });
      tile.load();
    });
  });

  describe('different source and render tile grids', function() {

    let source, map, loaded, requested, target;

    beforeEach(function() {

      loaded = [];
      requested = 0;

      function tileUrlFunction(tileCoord) {
        ++requested;
        if (tileCoord.toString() == '5,13,-29') {
          return tileCoord.join('/');
        }
      }

      function tileLoadFunction(tile, src) {
        tile.setLoader(function() {});
        loaded.push(src);
      }

      const extent = [665584.2026596286, 7033250.839875697, 667162.0221431496, 7035280.378636755];

      source = new VectorTileSource({
        tileGrid: new TileGrid({
          origin: [218128, 6126002],
          resolutions: [4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1, 0.5]
        }),
        tileUrlFunction: tileUrlFunction,
        tileLoadFunction: tileLoadFunction
      });

      target = document.createElement('div');
      target.style.width = target.style.height = '100px';
      document.body.appendChild(target);

      map = new Map({
        layers: [
          new VectorTileLayer({
            extent: extent,
            source: source
          })
        ],
        target: target,
        view: new View({
          zoom: 11,
          center: [666373.1624999996, 7034265.3572]
        })
      });

    });

    afterEach(function() {
      document.body.removeChild(target);
    });

    it('loads available tiles', function(done) {
      map.renderSync();
      setTimeout(function() {
        expect(requested).to.be.greaterThan(1);
        expect(loaded).to.eql(['5/13/-29']);
        done();
      }, 0);
    });

  });

});
<|endoftext|>