<commit_before>(function($, data, lineMath){

  'use strict';

  $.fn.findAword = function(options){

    var
      fAw = this,
      $this = $(this),
      settings, gamedata, wordfinder;

    /**
     * SETTINGS
     */
    settings = $.extend({
        buttons: true,
        results: true
    }, options);

    gamedata = data[settings.game];

    var wordfinder = {

      state: 'ready', // ready, resigned, completed

      init: function(){
        console.log('init');
        wordfinder.layout.create();
        wordfinder.controls.create();
        wordfinder.resultsboard.create();
        wordfinder.wordlist.create();
        wordfinder.gameboard.create();
        wordfinder.canvas.create();
      },

      /**
       * page layout
       */
      layout:{
        create: function(){

          $this.css('margin', '20px');

          var html = [];
          html.push('

');
          html.push('
');
          html.push('

');
          html.push('

');
          html.push('
');
          html.push('
');
          html.push('
');
          html.push('
');
          html.push('
');
          html.push('
');
          html.push('
');
          html.push('    RESET');
          html.push('    RESIGN');
          html.push('
');
          html.push('
');
          $this.append($(html.join("\n")));
        }
      },

      /**
       * basic page controls
       */
      controls:{

        create: function(){
          this.enableResign();
          $('#reset').off().on('click', wordfinder.controls.reset);
          $('#resign').off().on('click', wordfinder.controls.resign);

          if(!settings.buttons)
            $("#controls-container").hide();

        },

        reset: function(){
          console.log('reset');

          function reset(){
            wordfinder.state = 'ready';
            wordfinder.wordlist.reset();
            $("#wordlist-subcontainer").empty();
            $("#gameboard-subcontainer").empty();
            $("#results-container").empty();
            wordfinder.init();
          }

          if(wordfinder.state == 'resigned' ||
             wordfinder.state == 'completed'){
            reset();
            return;
          }

          var r = confirm("You want to reset the game? All found words will be erased.");
          if (r === true) {
            reset();
          }
        },

        resign: function(){
          console.log('resign');
          var r = confirm("You want to resign the game?");
          if (r === true) {
            wordfinder.state = 'resigned';
            wordfinder.resultsboard.indicateResigned();
            wordfinder.gameboard.lock();
          }
        },

        gameCompleted: function(){
          console.log('game-completed');
        },

        enableResign: function(){
          $('#resign').css('visibility','visible');
        },

        disableResign: function(){
          $('#resign').css('visibility','hidden');
        }

      },

      /**
       * Results, problems indication board
       */
      resultsboard: {

         create: function(){
          console.log('create results board');

          var display = $('

')
                          .attr('id', 'results');
          $('#results-container')
            .append(display);

          this.clear();

          if(!settings.results)
            $("#results-container").hide();

        },

        update: function(update){
          $("#results").html(update);
        },

        indicateComplete: function(){
          wordfinder.gameboard.lock();
          this.update('You found all the words on this puzzle.');
          wordfinder.state = 'completed';
          wordfinder.controls.disableResign();
          $("#results").addClass('completed');
        },

        indicateResigned: function(){
          var words = wordfinder.wordlist.words.length;
          var found = wordfinder.wordlist.found.length;
          var results = found+' of '+words;
          this.update('You resigned. You found '+results+' words.');
          $("#results").addClass('resigned');
        },

        clear: function(){
          $('#results').removeClass();
          this.update('Ready to Play!');
        }

      },

      /**
       * list of words to find
       * checks game completion
       */
      wordlist:{

        words: gamedata.wordlist,

        found: [],

        create: function(){

          var display = $('

')
                          .attr('id', 'wordlist');
          $('#wordlist-subcontainer')
            .append(display);

          for(var i in gamedata.wordlist){
            var word = $('
'+gamedata.wordlist[i]+'
')
                          .addClass('word');
            display.append(word);
          }
        },

        isInList: function(word){
          var index = this.words.indexOf(word);
          if(index != -1){
            this.found.push(word);
            return true;
          }else return false;
        },

        crossOffList: function(word){
          $('li.word').each(function(i, el){
            if($(el).text() == word){
              $(el).html(''+word+'');
            }
          })
        },

        isGameCompleted: function(){
          return this.words.length == this.found.length;
        },

        reset: function(){
          this.found = [];
        }

      },

      /**
       * Gameboard w/ lettered tiles
       */
      gameboard: {

        state: 'startup', // startup, waiting, selectA, selectB

        board: null,

        selected_a: [],

        selected_b: [],

        create: function(){

          this.state = 'waiting'

          var board = $('

')
                        .attr('id','gameboard');
          $('#gameboard-subcontainer').append(board);

          function makeGamesquare(x,y,letter){
            return $(''+letter+'	')
                    .data('x',x)
                    .data('y',y)
                    .on('mousedown',  wordfinder.gameboard.selectA)
                    .on('mouseup',    wordfinder.gameboard.selectB)
                    .on('mouseenter', wordfinder.gameboard.isInLine)
                    .on('mouseleave', wordfinder.gameboard.clearInLine);
          }

          for(var i in gamedata.gameboard){
            board.append('

');

            for(var j in gamedata.gameboard[i]){
              var letter     = gamedata.gameboard[i][j];
              var gamesquare = makeGamesquare(j,i,letter);
              board
                .find('tr:eq('+i+')')
                .append(gamesquare);
            }

          }

          // reset board if mouse leaves gameboard
          $("#gameboard")
            .on('mouseleave', wordfinder.gameboard.resetBoard);

          // once created, we have to give this element width and height for
          // proper page layout
          $('#gameboard-subcontainer')
            .css('height', $("#gameboard").height()+"px")
            .css('width', $("#gameboard").width()+"px");
        },

        selectA: function(){
            var el = $(this);
            el.addClass('selectA');
            wordfinder.gameboard.state = 'selectA';
            wordfinder.gameboard.selected_a = [el.data('x'), el.data('y')]
        },

        selectB: function(){
            var el = $(this);
            if(el.hasClass('outofline') ||
               el.hasClass('selectA')){
              wordfinder.gameboard.resetBoard();
              return;
            }
            wordfinder.gameboard.state = 'selectB';
            wordfinder.gameboard.selected_b = [el.data('x'), el.data('y')]
            var is_word = wordfinder.gameboard.checkWord();
            if(is_word){
              wordfinder.gameboard.state = 'waiting';
              if(wordfinder.wordlist.isGameCompleted()){
                wordfinder.resultsboard.indicateComplete();
              }
              wordfinder.gameboard.resetBoard();
            }else{
              wordfinder.gameboard.state = 'waiting';
            }
        },

        isInLine: function(){

          var state = wordfinder.gameboard.state;
          if(state == 'waiting') return;

          var selected_a = wordfinder.gameboard.selected_a;
          var thissquare = [$(this).data('x'), $(this).data('y')];

          if(selected_a[0] == thissquare[0] ||
             selected_a[1] == thissquare[1] ||
             Math.abs(selected_a[0] - thissquare[0]) == Math.abs(selected_a[1] - thissquare[1])){
            wordfinder.gameboard.highlightDraggedSelection(selected_a,thissquare);
          }else{
            $(this).addClass('outofline');
          }

        },

        clearInLine: function(){
          wordfinder.gameboard.clearDraggedSelection();
          $(this).removeClass('outofline');
        },

        checkWord: function(){

          var selected_a    = wordfinder.gameboard.selected_a;
          var selected_b    = wordfinder.gameboard.selected_b;
          var selected_word = this.getWord(selected_a, selected_b);

          wordfinder.gameboard.clearDraggedSelection();

          if(wordfinder.wordlist.isInList(selected_word)){ // if found
            console.log('found a word')
            wordfinder.canvas.circleWord(selected_a, selected_b);
            wordfinder.wordlist.crossOffList(selected_word);
            return true;
          }else{ // if not found
            console.log(selected_word+' is not a word on the list.')
            wordfinder.gameboard.resetBoard();
            return false;
          }
        },

        /**
         * determines word within the two selected points
         */
        getWord: function(selected_a, selected_b){

          var wordarr     = [];
          var coordinates = lineMath(selected_a, selected_b);

          for(var i in coordinates){
            var c = coordinates[i];
            var letter = $('tr:eq('+c[1]+') td:eq('+c[0]+')').text();
            wordarr.push(letter);
          }
          var word = wordarr.join('');

          return word;
        },

        /**
         * highlight all squares between coordinates. should only be triggered
         * after confirmation that line is straight (in this case)
         */
        highlightDraggedSelection(A,B){
          var coordinates = lineMath(A,B);
            for(var i in coordinates){
              var c = coordinates[i];
              $('tr:eq('+c[1]+') td:eq('+c[0]+')').addClass('dragged-selection');
          }
        },

        clearDraggedSelection(){
          $('td').removeClass('dragged-selection');
        },

        resetBoard: function(){
          console.log('resetBoard')
          $('td').removeClass();
          wordfinder.gameboard.clearDraggedSelection();
          wordfinder.gameboard.state = 'waiting';
        },

        lock: function(){
          this.resetBoard();
          $('td').off();
        }

      },

      /**
       * found word highlight
       */
      canvas:{

        create: function(){

          var canvas = $('<canvas></canvas>')
                          .attr('id','gamecanvas');
          $('#gameboard-subcontainer').append(canvas);

          var top    = $("#gameboard").position().top;
          var left   = $("#gameboard").css('margin', '0 auto');
          var height = $("#gameboard").height() - 2;
          var width  = $("#gameboard").width() - 2;
          $("#gamecanvas")
            .css('top', top+'px')
            .css('left', left+'px')
            .css('width', width+'px')
            .css('height', height+'px')
            .attr('width', width)
            .attr('height', height);
        },

        circleWord: function(A,B){
          console.log('circleword');
          console.log(A,B)

          function f(n){
            return (n*26)+13;
          }
          A = [f(A[0]), f(A[1])];
          B = [f(B[0]), f(B[1])];

          var c   = document.getElementById("gamecanvas");
          var ctx = c.getContext("2d");
          ctx.beginPath();
          ctx.lineCap = "round";
          ctx.lineWidth = 20;
          ctx.strokeStyle = this.rainbow(20,Math.floor(Math.random() * 20) + 1  );
          ctx.moveTo(A[0],A[1]);
          ctx.lineTo(B[0],B[1]);
          ctx.stroke();
        },

        rainbow: function(numOfSteps, step) {
          // This function generates vibrant, "evenly spaced" colours (i.e. no clustering).
          // Adam Cole, 2011-Sept-14
          // HSV to RBG adapted from: http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
          var r, g, b;
          var h = step / numOfSteps;
          var i = ~~(h * 6);
          var f = h * 6 - i;
          var q = 1 - f;
          switch(i % 6){
            case 0: r = 1; g = f; b = 0; break;
            case 1: r = q; g = 1; b = 0; break;
            case 2: r = 0; g = 1; b = f; break;
            case 3: r = 0; g = q; b = 1; break;
            case 4: r = f; g = 0; b = 1; break;
            case 5: r = 1; g = 0; b = q; break;
          }
          var c = "#" + ("00" + (~ ~(r * 255)).toString(16)).slice(-2) + ("00" + (~ ~(g * 255)).toString(16)).slice(-2) + ("00" + (~ ~(b * 255)).toString(16)).slice(-2);
          return (c);
        },

        clear: function(){
          $("#gamecanvas").remove();
          this.create();
        }
      }
    }

    wordfinder.init();

  }

}(jQuery, data, lineMath));
<commit_msg>game changes mostly make sure reset doesn't bleed outside of gameboard<commit_after>(function($, data, lineMath){

  'use strict';

  $.fn.findAword = function(options){

    var
      fAw = this,
      $this = $(this),
      settings, gamedata, wordfinder;

    /**
     * SETTINGS
     */
    settings = $.extend({
        buttons: true,
        results: true,
        instructions: 'Highlight (click-and-drag) as many as you can. Words can be forward, backward, or diagonal'
    }, options);

    gamedata = data[settings.game];

    var wordfinder = {

      state: 'ready', // ready, resigned, completed

      init: function(){
        console.log('init');
        wordfinder.layout.create();
        wordfinder.controls.create();
        wordfinder.resultsboard.create();
        wordfinder.wordlist.create();
        wordfinder.gameboard.create();
        wordfinder.canvas.create();
      },

      /**
       * page layout
       */
      layout:{
        create: function(){

          $this.css('margin', '20px');

          var html = [];
          html.push('

');
          html.push('

');
          html.push('
');
          html.push('

');
          html.push('

');
          html.push('
');
          html.push('
');
          html.push('
');
          html.push('
');
          html.push('
');
          html.push('
');
          html.push('
');
          html.push('    RESET');
          html.push('    RESIGN');
          html.push('
');
          html.push('
');
          $this.append($(html.join("\n")));
          $("#instructions-container").html(settings.instructions);
        }
      },

      /**
       * basic page controls
       */
      controls:{

        create: function(){
          this.enableResign();
          $('#reset').off().on('click', wordfinder.controls.reset);
          $('#resign').off().on('click', wordfinder.controls.resign);

          if(!settings.buttons)
            $("#controls-container").hide();

        },

        reset: function(){
          console.log('reset');

          function reset(){
            wordfinder.state = 'ready';
            wordfinder.wordlist.reset();
            $("#wordlist-subcontainer").empty();
            $("#gameboard-subcontainer").empty();
            $("#results-container").empty();
            wordfinder.init();
          }

          if(wordfinder.state == 'resigned' ||
             wordfinder.state == 'completed'){
            reset();
            return;
          }

          var r = confirm("You want to reset the game? All found words will be erased.");
          if (r === true) {
            reset();
          }
        },

        resign: function(){
          console.log('resign');
          var r = confirm("You want to resign the game?");
          if (r === true) {
            wordfinder.state = 'resigned';
            wordfinder.resultsboard.indicateResigned();
            wordfinder.gameboard.lock();
          }
        },

        gameCompleted: function(){
          console.log('game-completed');
        },

        enableResign: function(){
          $('#resign').css('visibility','visible');
        },

        disableResign: function(){
          $('#resign').css('visibility','hidden');
        }

      },

      /**
       * Results, problems indication board
       */
      resultsboard: {

         create: function(){
          console.log('create results board');

          var display = $('

')
                          .attr('id', 'results');
          $('#results-container')
            .append(display);

          this.clear();

          if(!settings.results)
            $("#results-container").hide();

        },

        update: function(update){
          $("#results").html(update);
        },

        indicateComplete: function(){
          wordfinder.gameboard.lock();
          this.update('You found all the words on this puzzle.');
          wordfinder.state = 'completed';
          wordfinder.controls.disableResign();
          $("#results").addClass('completed');
        },

        indicateResigned: function(){
          var words = wordfinder.wordlist.words.length;
          var found = wordfinder.wordlist.found.length;
          var results = found+' of '+words;
          this.update('You resigned. You found '+results+' words.');
          $("#results").addClass('resigned');
        },

        clear: function(){
          $('#results').removeClass();
          this.update('Ready to Play!');
        }

      },

      /**
       * list of words to find
       * checks game completion
       */
      wordlist:{

        words: gamedata.wordlist,

        found: [],

        create: function(){

          var display = $('

')
                          .attr('id', 'wordlist');
          $('#wordlist-subcontainer')
            .append(display);

          for(var i in gamedata.wordlist){
            var word = $('
'+gamedata.wordlist[i]+'
')
                          .addClass('word');
            display.append(word);
          }
        },

        isInList: function(word){
          var index = this.words.indexOf(word);
          if(index != -1){
            this.found.push(word);
            return true;
          }else return false;
        },

        crossOffList: function(word){
          $('li.word').each(function(i, el){
            if($(el).text() == word){
              $(el).html(''+word+'');
            }
          })
        },

        isGameCompleted: function(){
          return this.words.length == this.found.length;
        },

        reset: function(){
          this.found = [];
        }

      },

      /**
       * Gameboard w/ lettered tiles
       */
      gameboard: {

        state: 'startup', // startup, waiting, selectA, selectB

        board: null,

        selected_a: [],

        selected_b: [],

        create: function(){

          this.state = 'waiting'

          var board = $('

')
                        .attr('id','gameboard');
          $('#gameboard-subcontainer').append(board);

          function makeGamesquare(x,y,letter){
            return $(''+letter+'	')
                    .css({backgroundColor: 'transparent' })
                    .data('x',x)
                    .data('y',y)
                    .on('mousedown',  wordfinder.gameboard.selectA)
                    .on('mouseup',    wordfinder.gameboard.selectB)
                    .on('mouseenter', wordfinder.gameboard.isInLine)
                    .on('mouseleave', wordfinder.gameboard.clearInLine);
          }

          for(var i in gamedata.gameboard){
            board.append('

');

            for(var j in gamedata.gameboard[i]){
              var letter     = gamedata.gameboard[i][j];
              var gamesquare = makeGamesquare(j,i,letter);
              board
                .find('tr:eq('+i+')')
                .append(gamesquare);
            }

          }

          // reset board if mouse leaves gameboard
          $("#gameboard")
            .on('mouseleave', wordfinder.gameboard.resetBoard);

          // once created, we have to give this element width and height for
          // proper page layout
          $('#gameboard-subcontainer')
            .css('height', $("#gameboard").height()+"px")
            .css('width', $("#gameboard").width()+"px");
        },

        selectA: function(){
            var el = $(this);
            el.addClass('selectA');
            wordfinder.gameboard.state = 'selectA';
            wordfinder.gameboard.selected_a = [el.data('x'), el.data('y')]
        },

        selectB: function(){
            var el = $(this);
            if(el.hasClass('outofline') ||
               el.hasClass('selectA')){
              wordfinder.gameboard.resetBoard();
              return;
            }
            wordfinder.gameboard.state = 'selectB';
            wordfinder.gameboard.selected_b = [el.data('x'), el.data('y')]
            var is_word = wordfinder.gameboard.checkWord();
            if(is_word){
              wordfinder.gameboard.state = 'waiting';
              if(wordfinder.wordlist.isGameCompleted()){
                wordfinder.resultsboard.indicateComplete();
              }
              wordfinder.gameboard.resetBoard();
            }else{
              wordfinder.gameboard.state = 'waiting';
            }
        },

        isInLine: function(){

          var state = wordfinder.gameboard.state;
          if(state == 'waiting') return;

          var selected_a = wordfinder.gameboard.selected_a;
          var thissquare = [$(this).data('x'), $(this).data('y')];

          if(selected_a[0] == thissquare[0] ||
             selected_a[1] == thissquare[1] ||
             Math.abs(selected_a[0] - thissquare[0]) == Math.abs(selected_a[1] - thissquare[1])){
            wordfinder.gameboard.highlightDraggedSelection(selected_a,thissquare);
          }else{
            $(this).addClass('outofline');
          }

        },

        clearInLine: function(){
          wordfinder.gameboard.clearDraggedSelection();
          $(this).removeClass('outofline');
        },

        checkWord: function(){

          var selected_a    = wordfinder.gameboard.selected_a;
          var selected_b    = wordfinder.gameboard.selected_b;
          var selected_word = this.getWord(selected_a, selected_b);

          wordfinder.gameboard.clearDraggedSelection();

          if(wordfinder.wordlist.isInList(selected_word)){ // if found
            console.log('found a word')
            wordfinder.canvas.circleWord(selected_a, selected_b);
            wordfinder.wordlist.crossOffList(selected_word);
            return true;
          }else{ // if not found
            console.log(selected_word+' is not a word on the list.')
            wordfinder.gameboard.resetBoard();
            return false;
          }
        },

        /**
         * determines word within the two selected points
         */
        getWord: function(selected_a, selected_b){

          var wordarr     = [];
          var coordinates = lineMath(selected_a, selected_b);

          for(var i in coordinates){
            var c = coordinates[i];
            var letter = $('#gameboard tr:eq('+c[1]+') td:eq('+c[0]+')').text();
            wordarr.push(letter);
          }
          var word = wordarr.join('');

          return word;
        },

        /**
         * highlight all squares between coordinates. should only be triggered
         * after confirmation that line is straight (in this case)
         */
        highlightDraggedSelection(A,B){
          var coordinates = lineMath(A,B);
            for(var i in coordinates){
              var c = coordinates[i];
              $('#gameboard tr:eq('+c[1]+') td:eq('+c[0]+')').addClass('dragged-selection');
          }
        },

        clearDraggedSelection(){
          $('#gameboard td').removeClass('dragged-selection');
        },

        resetBoard: function(){
          console.log('resetBoard')
          $('#gameboard td').removeClass();
          wordfinder.gameboard.clearDraggedSelection();
          wordfinder.gameboard.state = 'waiting';
        },

        lock: function(){
          this.resetBoard();
          $('#gameboard td').off();
        }

      },

      /**
       * found word highlight
       */
      canvas:{

        create: function(){

          var canvas = $('<canvas></canvas>')
                          .attr('id','gamecanvas');
          $('#gameboard-subcontainer').prepend(canvas);

          var top    = $("#gameboard").position().top;
          var left   = $("#gameboard").css('margin', '0 auto');
          var height = $("#gameboard").height() - 2;
          var width  = $("#gameboard").width() - 2;
          $("#gamecanvas")
            .css('top', top+'px')
            .css('left', left+'px')
            .css('width', width+'px')
            .css('height', height+'px')
            .attr('width', width)
            .attr('height', height);
        },

        circleWord: function(A,B){
          console.log('circleword');
          console.log(A,B)

          function f(n){
            return (n*26)+13;
          }
          A = [f(A[0]), f(A[1])];
          B = [f(B[0]), f(B[1])];

          var c   = document.getElementById("gamecanvas");
          var ctx = c.getContext("2d");
          ctx.beginPath();
          ctx.lineCap = "round";
          ctx.lineWidth = 20;
          ctx.strokeStyle = this.rainbow(20,Math.floor(Math.random() * 20) + 1  );
          ctx.moveTo(A[0],A[1]);
          ctx.lineTo(B[0],B[1]);
          ctx.stroke();
        },

        rainbow: function(numOfSteps, step) {
          // This function generates vibrant, "evenly spaced" colours (i.e. no clustering).
          // Adam Cole, 2011-Sept-14
          // HSV to RBG adapted from: http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
          var r, g, b;
          var h = step / numOfSteps;
          var i = ~~(h * 6);
          var f = h * 6 - i;
          var q = 1 - f;
          switch(i % 6){
            case 0: r = 1; g = f; b = 0; break;
            case 1: r = q; g = 1; b = 0; break;
            case 2: r = 0; g = 1; b = f; break;
            case 3: r = 0; g = q; b = 1; break;
            case 4: r = f; g = 0; b = 1; break;
            case 5: r = 1; g = 0; b = q; break;
          }
          var c = "#" + ("00" + (~ ~(r * 255)).toString(16)).slice(-2) + ("00" + (~ ~(g * 255)).toString(16)).slice(-2) + ("00" + (~ ~(b * 255)).toString(16)).slice(-2);
          return (c);
        },

        clear: function(){
          $("#gamecanvas").remove();
          this.create();
        }
      }
    }

    wordfinder.init();

  }

}(jQuery, data, lineMath));
<|endoftext|>


<commit_before>$(document).foundation();

$(document).ready(function () {
  // Datatable Initialize.
  $('#example-datatable').DataTable({
    columnDefs: [ {
        targets: [ 0 ],
        orderData: [ 0, 1 ]
    }, {
        targets: [ 1 ],
        orderData: [ 1, 0 ]
    }, {
        targets: [ 4 ],
        orderData: [ 4, 0 ]
    } ]
  });

  $("[data-responsive-toggle]").click(function () {
    var targetMenuClass =  $(this).attr("data-responsive-toggle");

    // Add class "open" to the target menu.
    $("[class*='" + targetMenuClass + "']").toggleClass("open");
  });

  if($("select#varient").length > 0) {
    // Ajax Request for Varient Choices Select
    var varientRequest = function (callback) {
      fetch('https://gist.githubusercontent.com/meladawy/ebc4afc00f6c583437ff4cdee381f0d1/raw/45f9df2d298e0af19899884d5a00d16d126741e6/gistfile1.json')
        .then(function (response) {
          response.json().then(function (data) {
            callback(data.suggestions, 'value', 'label');
          });
        })
        .catch(function (error) {
          console.log(error);
        });
    };

    var selectVarientChoices = new Choices('select#varient', {
      removeItemButton: true,
      delimiter: ',',
    });

    selectVarientChoices.ajax(varientRequest);
  }

  // Initialize Choices.
  if($(".choices").length > 0) {
    var multiSelectChoices = new Choices('.choices[multiple]', {
      delimiter: ',',
      editItems: true,
      maxItemCount: 5,
      removeItemButton: true,
    });

    var singleSelectChoices = new Choices('.choices:not([multiple])', {
      removeItemButton: false,
    });
  }

  // When Click on View All Cancer Types
  $("a.view-all-cancer-types").click(function(ev) {
    $("#cancer-types").attr("style", "height:350px; overflow:auto;");
    $(this).hide();
  });

});<commit_msg>Comment out example functions<commit_after>$(document).foundation();

$(document).ready(function () {

  /*
  // Datatable Initialize.
  $('#example-datatable').DataTable({
    columnDefs: [ {
        targets: [ 0 ],
        orderData: [ 0, 1 ]
    }, {
        targets: [ 1 ],
        orderData: [ 1, 0 ]
    }, {
        targets: [ 4 ],
        orderData: [ 4, 0 ]
    } ]
  });
*/
  $("[data-responsive-toggle]").click(function () {
    var targetMenuClass =  $(this).attr("data-responsive-toggle");

    // Add class "open" to the target menu.
    $("[class*='" + targetMenuClass + "']").toggleClass("open");
  });

/*
  if($("select#varient").length > 0) {
    // Ajax Request for Varient Choices Select
    var varientRequest = function (callback) {
      fetch('https://gist.githubusercontent.com/meladawy/ebc4afc00f6c583437ff4cdee381f0d1/raw/45f9df2d298e0af19899884d5a00d16d126741e6/gistfile1.json')
        .then(function (response) {
          response.json().then(function (data) {
            callback(data.suggestions, 'value', 'label');
          });
        })
        .catch(function (error) {
          console.log(error);
        });
    };

    var selectVarientChoices = new Choices('select#varient', {
      removeItemButton: true,
      delimiter: ',',
    });

    selectVarientChoices.ajax(varientRequest);
  }

  // Initialize Choices.
  if($(".choices").length > 0) {
    var multiSelectChoices = new Choices('.choices[multiple]', {
      delimiter: ',',
      editItems: true,
      maxItemCount: 5,
      removeItemButton: true,
    });

    var singleSelectChoices = new Choices('.choices:not([multiple])', {
      removeItemButton: false,
    });
  }

  // When Click on View All Cancer Types
  $("a.view-all-cancer-types").click(function(ev) {
    $("#cancer-types").attr("style", "height:350px; overflow:auto;");
    $(this).hide();
  });

*/
});<|endoftext|>


<commit_before>var Widgets = {
	connections : [
		{
			id : 1,
			dir1 : "is my classmate",
			dir2 : "is my classmate"
		},
		{
			id: 2,
			dir1 : "is my supervisor",
			dir2 : "is being supervised by me"
		},
		{
			id: 3,
			dir1 : "is being supervised by me",
			dir2 : "is my supervisor"
		},
		{
			id: 4,
			dir1 : "is my lecturer",
			dir2 : "is my student"
		},
		{
			id: 5,
			dir1 : "is my student",
			dir2 : "is my lecturer"
		},
		{
			id: 6,
			dir1 : "is my colleague",
			dir2 : "is my colleague"
		},
		{
			id: 7,
			dir1 : "is my college mate",
			dir2 : "is my college mate"
		},
		{
			id: 8,
			dir1 : "shares an interest with me",
			dir2 : "shares an interest with me"
		},
		{
			id: 9,
			dir1 : "is something else",
			dir2 : "is something else"
		}
	],
	groups:[
		"Administrators",
		"Lecturers & Supervisors",
		"Researchers",
		"Students"],
	layouts : {
		onecolumn :
		{
			name:"One column",
			widths:[100]
		},
		dev :
		{
			name:"Dev Layout",
			widths:[50,50]
		},
		threecolumn :
		{
			name:"Three equal columns",
			widths:[33,33,33]
		},
		fourcolumn :
		{
			name:"Four equal columns",
			widths:[25,25,25,25]
		},
		fivecolumn :
		{
			name:"Five equal columns",
			widths:[20,20,20,20,20]
		}
	},
	widgets: {
		changepic :
		{
			description:"",
			iframe:0,
			url:"/devwidgets/changepic/changepic.html",
			name:"changepic",
			id:"changepic",
			personalportal:0,
			siteportal:0,
			img:"/dev/img/sites.png"
		},
		sites :
		{
			description:"Listing of the sites I'm a member of\r\n",
			iframe:0,
			url:"/devwidgets/sites/sites.html",
			name:"My Courses & Sites",
			id:"sites",
			personalportal:1,
			siteportal:0,
			img:"/dev/img/sites.png"
		},
		myprofile :
		{
			description:"My Personal Profile\r\n",
			iframe:0,
			url:"/devwidgets/myprofile/myprofile.html",
			name:"My Profile",
			id:"myprofile",
			personalportal:1,
			siteportal:0,
			img:"/dev/img/myprofile.png"
		},
		discussion :
		{
			description:"Discussion widget\r\n",
			iframe:0,
			url:"/devwidgets/discussion/discussion.html",
			name:"Discussion",
			id:"discussion",
			personalportal:0,
			siteportal:0,
			ca:1,
			showinmedia:0,
			showinsakaigoodies:1,
			img:"/dev/img/myprofile.png"
		},
		poll :
		{
			description:"Poll widget\r\n",
			iframe:0,
			url:"/devwidgets/poll/poll.html",
			name:"Poll",
			id:"poll",
			personalportal:0,
			siteportal:0,
			ca:1,
			showinmedia:0,
			showinsakaigoodies:1,
			img:"/dev/img/myprofile.png"
		},
		wookiechat :
		{
			description:"wookiechat\r\n",
			iframe:0,
			url:"/devwidgets/wookiechat/wookiechat.html",
			name:"Chat",
			id:"wookiechat",
			personalportal:0,
			siteportal:0,
			ca:1,
			showinmedia:0,
			showinsakaigoodies:1,
			img:"/dev/img/myprofile.png"
		},
		wookieforum :
		{
			description:"wookieforum\r\n",
			iframe:0,
			url:"/devwidgets/wookieforum/wookieforum.html",
			name:"Wookie Forum",
			id:"wookieforum",
			personalportal:0,
			siteportal:0,
			ca:1,
			showinmedia:0,
			showinsakaigoodies:0,
			img:"/dev/img/myprofile.png"
		},
		helloworld :
		{
			description:"Sakai Hackathon Example\r\n",
			iframe:0,
			url:"/devwidgets/helloworld/helloworld.html",
			name:"Hello World",
			id:"helloworld",
			personalportal:1,
			siteportal:0,
			hasSettings: 1,
			img:"/dev/img/myprofile.png"
		},
		sparkline :
		{
			description:"Sparkline\r\n",
			iframe:0,
			url:"/devwidgets/sparkline/sparkline.html",
			name:"Sparkline",
			id:"sparkline",
			personalportal:0,
			siteportal:1,
			img:"/dev/img/sparkline.png"
		},
		createsite :
		{
			description:"Create site\r\n",
			iframe:0,
			url:"/devwidgets/createsite/createsite.html",
			name:"Create Site",
			id:"createsite",
			personalportal:0,
			siteportal:0,
			img:"/dev/img/sites.png"
		},
		sendmessage :
		{
			description:"Send a message\r\n",
			iframe:0,
			url:"/devwidgets/sendmessage/sendmessage.html",
			name:"Send a message",
			id:"sendmessage",
			personalportal:0,
			siteportal:0,
			img:"/dev/img/sites.png"
		},
		myfriends :
		{
			description:"A list of my connections\r\n",
			iframe:0,
			url:"/devwidgets/myfriends/myfriends.html",
			name:"My Contacts",
			id:"myfriends",
			personalportal:1,
			siteportal:0,
			img:"/dev/img/myprofile.png",
			multipleinstance: false
		},
		announcementupdates :
		{
			description:"A list of Announcements & Updates\r\n",
			iframe:0,
			url:"/devwidgets/announcementupdates/announcementupdates.html",
			name:"Announcements & Updates",
			id:"announcementupdates",
			personalportal:0,
			siteportal:1,
			img:"/dev/img/myprofile.png",
			multipleinstance: false
		},
		pagemanagement :
		{
			description:"pagemanagement",
			iframe:0,
			url:"/devwidgets/pagemanagement/pagemanagement.html",
			name:"pagemanagement",
			id:"pagemanagement",
			personalportal:0,
			siteportal:0
		},
		mypreferences :
		{
			description:"mypreferences",
			iframe:0,
			url:"/devwidgets/mypreferences/mypreferences.html",
			name:"mypreferences",
			id:"mypreferences",
			personalportal:0,
			siteportal:0
		},
		myinbox :
		{
			description:"myinbox",
			iframe:0,
			url:"/devwidgets/myinbox/myinbox.html",
			name:"myinbox",
			id:"myinbox",
			personalportal:0,
			siteportal:0
		},
		sitemembers :
		{
			description:"Shows a list of all of the members of this site",
			iframe:0,
			url:"/devwidgets/sitemembers/sitemembers.html",
			name:"Site Members",
			id:"sitemembers",
			personalportal:0,
			siteportal:1,
			img:"/devwidgets/sitemembers/images/icon.png"
		},
		chat :
		{
			description:"chat",
			iframe:0,
			url:"/devwidgets/chat/chat.html",
			name:"chat",
			id:"chat",
			personalportal:0,
			siteportal:0
		},
		siterecentactivity :
		{
			description:"Site Recent Activity",
			iframe:0,
			url:"/devwidgets/siterecentactivity/siterecentactivity.html",
			name:"Recent Activity",
			id:"siterecentactivity",
			personalportal:0,
			siteportal:0,
			ca:1,
			img:"/devwidgets/siterecentactivity/images/icon.png"
		},
		navigation :
		{
			description:"Navigation Widgets",
			iframe:0,
			url:"/devwidgets/navigation/navigation.html",
			name:"Navigation",
			id:"navigation",
			personalportal:0,
			siteportal:0,
			ca:1,
			img:"/devwidgets/navigation/images/icon.png"
		},
		youtubevideo :
		{
			description:"YouTube Video",
			iframe:0,
			url:"/devwidgets/youtubevideo/youtubevideo.html",
			name:"YouTube Video",
			id:"youtubevideo",
			personalportal:0,
			siteportal:0,
			ca:1,
			showinmedia:0,
			showinsakaigoodies:0,
			img:"/devwidgets/youtubevideo/images/icon.png"
		},
		rss :
		{
			description:"RSS Feed",
			iframe:0,
			url:"/devwidgets/rss/rss.html",
			name:"RSS Feed",
			id:"rss",
			personalportal:0,
			siteportal:0,
			ca:1,
			showinmedia:0,
			showinsakaigoodies:1,
			img:"/devwidgets/youtubevideo/images/icon.png"
		},
		video :
		{
			description:"Video",
			iframe:0,
			url:"/devwidgets/video/video.html",
			name:"Video",
			id:"video",
			personalportal:0,
			siteportal:0,
			ca:1,
			showinmedia:1,
			showinsakaigoodies:0,
			img:"/devwidgets/youtubevideo/images/icon.png"
		},
		comments :
		{
			description:"Comments",
			iframe:0,
			url:"/devwidgets/comments/commentswow.html",
			name:"Comments",
			id:"comments",
			personalportal:0,
			siteportal:0,
			ca:1,
			showinmedia:0,
			showinsakaigoodies:1,
			img:"/devwidgets/youtubevideo/images/icon.png"
		},
		remotecontent :
		{
			description:"Remote Content",
			iframe:0,
			url:"/devwidgets/remotecontent/remotecontent.html",
			name:"Remote Content",
			id:"remotecontent",
			personalportal:0,
			siteportal:0,
			ca:1,
			showinmedia:0,
			showinsakaigoodies:1,
			img:"/devwidgets/youtubevideo/images/icon.png"
		},
		linktool :
		{
			description:"Link Tool",
			iframe:0,
			url:"/devwidgets/linktool/linktool.html",
			name:"Link Tool",
			id:"linktool",
			personalportal:0,
			siteportal:0,
			ca:1,
			showinmedia:0,
			showinsakaigoodies:1,
			img:"/devwidgets/youtubevideo/images/icon.png"
		},
		tangler :
		{
			description:"Tangler Forum",
			iframe:0,
			url:"/devwidgets/tangler/tangler.html",
			name:"Tangler Forum",
			id:"tangler",
			personalportal:0,
			siteportal:0,
			ca:1,
			showinmedia:0,
			showinsakaigoodies:1,
			img:"/devwidgets/tangler/images/tangler.png"
		},
		singlefile :
		{
			description:"Single File Reference",
			iframe:0,
			url:"/devwidgets/singlefile/singlefile.html",
			name:"Single File Reference",
			id:"singlefile",
			personalportal:0,
			siteportal:0,
			ca:0,
			img:"/devwidgets/singlefile/images/singlefile.png"
		},
		Resources :
		{
			description:"Resources tool",
			iframe:"0",
			url:"/devwidgets/Resources/Resources.html",
			name:"Resources",
			id:"resources",
			personalportal:0,
			siteportal:0,
			history : {"init":"Resources.initHistory","nav":"Resources.browser.printResources",tag:"Resources.tagging.showTagViewReal"}
		},
		polltracker :
		{
			description:"Track the results of all of the polls on the sites you are a member of",
			iframe:0,
			url:"/devwidgets/polltracker/polltracker.html",
			name:"Poll Tracker",
			id:"polltracker",
			personalportal:1,
			siteportal:0,
			multipleinstance: true,
			img:"/devwidgets/polltracker/images/poll_icon.gif"
		}
	},
	orders:[
		{
			grouptype:"General",
			widgets: ["mycoursesandprojects","messageoftheday","recentactivity"],
			id:1,
			layout: "twocolumnspecial"
		},
		{
			grouptype:"Administrators",
			widgets: ["mycoursesandprojects","messageoftheday","quickannouncement"],
			id:1,
			layout: "twocolumn"
		},
		{
			grouptype:"Lecturers & Supervisors",
			widgets:["mycoursesandprojects","recentactivity"],
			id:2,
			layout: "twocolumnspecial"
		},
		{
			grouptype:"Researchers",
			widgets:["recentactivity","mycoursesandprojects","messageoftheday"],
			id:3,
			layout: "threecolumn"
		},
		{
			grouptype:"Students",
			widgets:["recentactivity","mycoursesandprojects","quickannouncement","messageoftheday","myrssfeed"],
			id:4,
			layout: "fourcolumn"
		}
	]
};<commit_msg>NOJIRA Adding in an entry for the Quiz widget<commit_after>var Widgets = {
	connections : [
		{
			id : 1,
			dir1 : "is my classmate",
			dir2 : "is my classmate"
		},
		{
			id: 2,
			dir1 : "is my supervisor",
			dir2 : "is being supervised by me"
		},
		{
			id: 3,
			dir1 : "is being supervised by me",
			dir2 : "is my supervisor"
		},
		{
			id: 4,
			dir1 : "is my lecturer",
			dir2 : "is my student"
		},
		{
			id: 5,
			dir1 : "is my student",
			dir2 : "is my lecturer"
		},
		{
			id: 6,
			dir1 : "is my colleague",
			dir2 : "is my colleague"
		},
		{
			id: 7,
			dir1 : "is my college mate",
			dir2 : "is my college mate"
		},
		{
			id: 8,
			dir1 : "shares an interest with me",
			dir2 : "shares an interest with me"
		},
		{
			id: 9,
			dir1 : "is something else",
			dir2 : "is something else"
		}
	],
	groups:[
		"Administrators",
		"Lecturers & Supervisors",
		"Researchers",
		"Students"],
	layouts : {
		onecolumn :
		{
			name:"One column",
			widths:[100]
		},
		dev :
		{
			name:"Dev Layout",
			widths:[50,50]
		},
		threecolumn :
		{
			name:"Three equal columns",
			widths:[33,33,33]
		},
		fourcolumn :
		{
			name:"Four equal columns",
			widths:[25,25,25,25]
		},
		fivecolumn :
		{
			name:"Five equal columns",
			widths:[20,20,20,20,20]
		}
	},
	widgets: {
		changepic :
		{
			description:"",
			iframe:0,
			url:"/devwidgets/changepic/changepic.html",
			name:"changepic",
			id:"changepic",
			personalportal:0,
			siteportal:0,
			img:"/dev/img/sites.png"
		},
		sites :
		{
			description:"Listing of the sites I'm a member of\r\n",
			iframe:0,
			url:"/devwidgets/sites/sites.html",
			name:"My Courses & Sites",
			id:"sites",
			personalportal:1,
			siteportal:0,
			img:"/dev/img/sites.png"
		},
		myprofile :
		{
			description:"My Personal Profile\r\n",
			iframe:0,
			url:"/devwidgets/myprofile/myprofile.html",
			name:"My Profile",
			id:"myprofile",
			personalportal:1,
			siteportal:0,
			img:"/dev/img/myprofile.png"
		},
		discussion :
		{
			description:"Discussion widget\r\n",
			iframe:0,
			url:"/devwidgets/discussion/discussion.html",
			name:"Discussion",
			id:"discussion",
			personalportal:0,
			siteportal:0,
			ca:1,
			showinmedia:0,
			showinsakaigoodies:1,
			img:"/dev/img/myprofile.png"
		},
		poll :
		{
			description:"Poll widget\r\n",
			iframe:0,
			url:"/devwidgets/poll/poll.html",
			name:"Poll",
			id:"poll",
			personalportal:0,
			siteportal:0,
			ca:1,
			showinmedia:0,
			showinsakaigoodies:1,
			img:"/dev/img/myprofile.png"
		},
		quiz :
		{
			description:"Quiz widget\r\n",
			iframe:0,
			url:"/devwidgets/quiz/quiz.html",
			name:"Quiz",
			id:"quiz",
			personalportal:0,
			siteportal:0,
			ca:1,
			showinmedia:0,
			showinsakaigoodies:1,
			img:"/dev/img/myprofile.png"
		},
		wookiechat :
		{
			description:"wookiechat\r\n",
			iframe:0,
			url:"/devwidgets/wookiechat/wookiechat.html",
			name:"Chat",
			id:"wookiechat",
			personalportal:0,
			siteportal:0,
			ca:1,
			showinmedia:0,
			showinsakaigoodies:1,
			img:"/dev/img/myprofile.png"
		},
		wookieforum :
		{
			description:"wookieforum\r\n",
			iframe:0,
			url:"/devwidgets/wookieforum/wookieforum.html",
			name:"Wookie Forum",
			id:"wookieforum",
			personalportal:0,
			siteportal:0,
			ca:1,
			showinmedia:0,
			showinsakaigoodies:0,
			img:"/dev/img/myprofile.png"
		},
		helloworld :
		{
			description:"Sakai Hackathon Example\r\n",
			iframe:0,
			url:"/devwidgets/helloworld/helloworld.html",
			name:"Hello World",
			id:"helloworld",
			personalportal:1,
			siteportal:0,
			hasSettings: 1,
			img:"/dev/img/myprofile.png"
		},
		sparkline :
		{
			description:"Sparkline\r\n",
			iframe:0,
			url:"/devwidgets/sparkline/sparkline.html",
			name:"Sparkline",
			id:"sparkline",
			personalportal:0,
			siteportal:1,
			img:"/dev/img/sparkline.png"
		},
		createsite :
		{
			description:"Create site\r\n",
			iframe:0,
			url:"/devwidgets/createsite/createsite.html",
			name:"Create Site",
			id:"createsite",
			personalportal:0,
			siteportal:0,
			img:"/dev/img/sites.png"
		},
		sendmessage :
		{
			description:"Send a message\r\n",
			iframe:0,
			url:"/devwidgets/sendmessage/sendmessage.html",
			name:"Send a message",
			id:"sendmessage",
			personalportal:0,
			siteportal:0,
			img:"/dev/img/sites.png"
		},
		myfriends :
		{
			description:"A list of my connections\r\n",
			iframe:0,
			url:"/devwidgets/myfriends/myfriends.html",
			name:"My Contacts",
			id:"myfriends",
			personalportal:1,
			siteportal:0,
			img:"/dev/img/myprofile.png",
			multipleinstance: false
		},
		announcementupdates :
		{
			description:"A list of Announcements & Updates\r\n",
			iframe:0,
			url:"/devwidgets/announcementupdates/announcementupdates.html",
			name:"Announcements & Updates",
			id:"announcementupdates",
			personalportal:0,
			siteportal:1,
			img:"/dev/img/myprofile.png",
			multipleinstance: false
		},
		pagemanagement :
		{
			description:"pagemanagement",
			iframe:0,
			url:"/devwidgets/pagemanagement/pagemanagement.html",
			name:"pagemanagement",
			id:"pagemanagement",
			personalportal:0,
			siteportal:0
		},
		mypreferences :
		{
			description:"mypreferences",
			iframe:0,
			url:"/devwidgets/mypreferences/mypreferences.html",
			name:"mypreferences",
			id:"mypreferences",
			personalportal:0,
			siteportal:0
		},
		myinbox :
		{
			description:"myinbox",
			iframe:0,
			url:"/devwidgets/myinbox/myinbox.html",
			name:"myinbox",
			id:"myinbox",
			personalportal:0,
			siteportal:0
		},
		sitemembers :
		{
			description:"Shows a list of all of the members of this site",
			iframe:0,
			url:"/devwidgets/sitemembers/sitemembers.html",
			name:"Site Members",
			id:"sitemembers",
			personalportal:0,
			siteportal:1,
			img:"/devwidgets/sitemembers/images/icon.png"
		},
		chat :
		{
			description:"chat",
			iframe:0,
			url:"/devwidgets/chat/chat.html",
			name:"chat",
			id:"chat",
			personalportal:0,
			siteportal:0
		},
		siterecentactivity :
		{
			description:"Site Recent Activity",
			iframe:0,
			url:"/devwidgets/siterecentactivity/siterecentactivity.html",
			name:"Recent Activity",
			id:"siterecentactivity",
			personalportal:0,
			siteportal:0,
			ca:1,
			img:"/devwidgets/siterecentactivity/images/icon.png"
		},
		navigation :
		{
			description:"Navigation Widgets",
			iframe:0,
			url:"/devwidgets/navigation/navigation.html",
			name:"Navigation",
			id:"navigation",
			personalportal:0,
			siteportal:0,
			ca:1,
			img:"/devwidgets/navigation/images/icon.png"
		},
		youtubevideo :
		{
			description:"YouTube Video",
			iframe:0,
			url:"/devwidgets/youtubevideo/youtubevideo.html",
			name:"YouTube Video",
			id:"youtubevideo",
			personalportal:0,
			siteportal:0,
			ca:1,
			showinmedia:0,
			showinsakaigoodies:0,
			img:"/devwidgets/youtubevideo/images/icon.png"
		},
		rss :
		{
			description:"RSS Feed",
			iframe:0,
			url:"/devwidgets/rss/rss.html",
			name:"RSS Feed",
			id:"rss",
			personalportal:0,
			siteportal:0,
			ca:1,
			showinmedia:0,
			showinsakaigoodies:1,
			img:"/devwidgets/youtubevideo/images/icon.png"
		},
		video :
		{
			description:"Video",
			iframe:0,
			url:"/devwidgets/video/video.html",
			name:"Video",
			id:"video",
			personalportal:0,
			siteportal:0,
			ca:1,
			showinmedia:1,
			showinsakaigoodies:0,
			img:"/devwidgets/youtubevideo/images/icon.png"
		},
		comments :
		{
			description:"Comments",
			iframe:0,
			url:"/devwidgets/comments/commentswow.html",
			name:"Comments",
			id:"comments",
			personalportal:0,
			siteportal:0,
			ca:1,
			showinmedia:0,
			showinsakaigoodies:1,
			img:"/devwidgets/youtubevideo/images/icon.png"
		},
		remotecontent :
		{
			description:"Remote Content",
			iframe:0,
			url:"/devwidgets/remotecontent/remotecontent.html",
			name:"Remote Content",
			id:"remotecontent",
			personalportal:0,
			siteportal:0,
			ca:1,
			showinmedia:0,
			showinsakaigoodies:1,
			img:"/devwidgets/youtubevideo/images/icon.png"
		},
		linktool :
		{
			description:"Link Tool",
			iframe:0,
			url:"/devwidgets/linktool/linktool.html",
			name:"Link Tool",
			id:"linktool",
			personalportal:0,
			siteportal:0,
			ca:1,
			showinmedia:0,
			showinsakaigoodies:1,
			img:"/devwidgets/youtubevideo/images/icon.png"
		},
		tangler :
		{
			description:"Tangler Forum",
			iframe:0,
			url:"/devwidgets/tangler/tangler.html",
			name:"Tangler Forum",
			id:"tangler",
			personalportal:0,
			siteportal:0,
			ca:1,
			showinmedia:0,
			showinsakaigoodies:1,
			img:"/devwidgets/tangler/images/tangler.png"
		},
		singlefile :
		{
			description:"Single File Reference",
			iframe:0,
			url:"/devwidgets/singlefile/singlefile.html",
			name:"Single File Reference",
			id:"singlefile",
			personalportal:0,
			siteportal:0,
			ca:0,
			img:"/devwidgets/singlefile/images/singlefile.png"
		},
		Resources :
		{
			description:"Resources tool",
			iframe:"0",
			url:"/devwidgets/Resources/Resources.html",
			name:"Resources",
			id:"resources",
			personalportal:0,
			siteportal:0,
			history : {"init":"Resources.initHistory","nav":"Resources.browser.printResources",tag:"Resources.tagging.showTagViewReal"}
		},
		polltracker :
		{
			description:"Track the results of all of the polls on the sites you are a member of",
			iframe:0,
			url:"/devwidgets/polltracker/polltracker.html",
			name:"Poll Tracker",
			id:"polltracker",
			personalportal:1,
			siteportal:0,
			multipleinstance: true,
			img:"/devwidgets/polltracker/images/poll_icon.gif"
		}
	},
	orders:[
		{
			grouptype:"General",
			widgets: ["mycoursesandprojects","messageoftheday","recentactivity"],
			id:1,
			layout: "twocolumnspecial"
		},
		{
			grouptype:"Administrators",
			widgets: ["mycoursesandprojects","messageoftheday","quickannouncement"],
			id:1,
			layout: "twocolumn"
		},
		{
			grouptype:"Lecturers & Supervisors",
			widgets:["mycoursesandprojects","recentactivity"],
			id:2,
			layout: "twocolumnspecial"
		},
		{
			grouptype:"Researchers",
			widgets:["recentactivity","mycoursesandprojects","messageoftheday"],
			id:3,
			layout: "threecolumn"
		},
		{
			grouptype:"Students",
			widgets:["recentactivity","mycoursesandprojects","quickannouncement","messageoftheday","myrssfeed"],
			id:4,
			layout: "fourcolumn"
		}
	]
};<|endoftext|>


<commit_before>import Validation from 'ember-stickler/validation';

export default Validation.create({
  validate(value, errors) {
    if (!value || !value.length) {
      const message = this.getWithDefault('requiredMessage', 'This field is required');

      errors.push(message);
    }

    return errors;
  }
});
<commit_msg>fix(required): the required test now accepts 0 '0' false and 'false' as 'present ' values<commit_after>import Validation from 'ember-stickler/validation';

export default Validation.create({
  validate(value, errors) {
    if (value === '' || value === null || value === undefined || !value.length) {
      const message = this.getWithDefault('requiredMessage', 'This field is required');

      errors.push(message);
    }

    return errors;
  }
});
<|endoftext|>


<commit_before>(function(module) {
    'use strict';

    // TODO: refactor, document and add tests!!
    module.controller('MapCtrl', ['$scope', '$location', 'playerService', 'Location', 'locationService', 'backendService',
        function($scope, $location, playerService, Location, locationService, backendService) {
            var player;

            /**
             * Whether the user is currently adding a new location
             * @type {boolean}
             */
            $scope.isAddingLocation = false;

            // Expose the location service
            $scope.location = locationService;

            // Expose the map settings
            $scope.mapSettings = locationService.mapSettings;

            /**
             * All Locations shown on the map
             * @type {Location[]}
             */
            $scope.locations = [];

            /**
             * Whether the locations have already been loaded
             * @type {boolean}
             */
            $scope.locationsLoaded = false;

            /**
             * Expose the location types
             * @type {{}}
             */
            $scope.locationTypes = Location.TYPES;

            /**
             * Empty events object (needed to get the leaflet map to broadcast events)
             * @type {{}}
             */
            $scope.events = {};

            /**
             * Starts adding a new location
             */
            $scope.startAddNewLocation = function() {
                $scope.isAddingLocation = true;
                $scope.newLocation = new Location(undefined, player.team);
                locationService.activate($scope.newLocation);
            };

            /**
             * Aborts adding a new location
             */
            $scope.resetAddNewLocation = function() {
                locationService.activate();
                if ($scope.newLocation.isAddedToMap === true) {
                    // Remove from map if it was added
                    $scope.locations = $scope.locations.slice(0, $scope.locations.length - 1);
                }
                $scope.isAddingLocation = false;
                $scope.newLocation = undefined;
            };

            /**
             * Finalises adding a new location
             */
            $scope.addNewLocation = function() {
                locationService.submitLocation($scope.newLocation);
                $scope.isAddingLocation = false;
                $scope.newLocation = undefined;
            };

            /**
             * Goes to the location view
             * @param location
             */
            $scope.visitLocation = function(location) {
                $location.path('location/' + location.id);
            };

            /**
             * Handler for clicks on the map
             * @param event
             * @param args
             */
            var mapClickHandler = function(event, args) {
                if ($scope.isAddingLocation) {
                    $scope.newLocation.lat = args.leafletEvent.latlng.lat;
                    $scope.newLocation.lng = args.leafletEvent.latlng.lng;

                    // Push to map if not already there
                    if ($scope.newLocation.isAddedToMap !== true) {
                        $scope.locations.push($scope.newLocation);
                        $scope.newLocation.isAddedToMap = true;
                    }
                }
            };

            /**
             * Handler for clicks on map markers (Locations)
             * @param event
             * @param args
             */
            var locationClickHandler = function(event, args) {
                locationService.activate($scope.locations[args.markerName]);
            };

            // Register event handlers
            $scope.$on('leafletDirectiveMap.click', mapClickHandler);
            $scope.$on('leafletDirectiveMarker.click', locationClickHandler);

            // Check if we are logged in
            if (backendService.isLoggedIn()) {
                // Get the locations
                locationService.getLocations().then(function(locations) {
                    $scope.locations = locations;
                    $scope.locationsLoaded = true;
                });

                // Get the player
                playerService.getMe().then(function(me) {
                    player = me;
                });
            }
            else {
                $scope.locationsLoaded = true;
            }
        }
    ]);
})(window.veganaut.mapModule);
<commit_msg>Deselecting active location on map click. Refs #49<commit_after>(function(module) {
    'use strict';

    // TODO: refactor, document and add tests!!
    module.controller('MapCtrl', ['$scope', '$location', 'playerService', 'Location', 'locationService', 'backendService',
        function($scope, $location, playerService, Location, locationService, backendService) {
            var player;

            /**
             * Whether the user is currently adding a new location
             * @type {boolean}
             */
            $scope.isAddingLocation = false;

            // Expose the location service
            $scope.location = locationService;

            // Expose the map settings
            $scope.mapSettings = locationService.mapSettings;

            /**
             * All Locations shown on the map
             * @type {Location[]}
             */
            $scope.locations = [];

            /**
             * Whether the locations have already been loaded
             * @type {boolean}
             */
            $scope.locationsLoaded = false;

            /**
             * Expose the location types
             * @type {{}}
             */
            $scope.locationTypes = Location.TYPES;

            /**
             * Empty events object (needed to get the leaflet map to broadcast events)
             * @type {{}}
             */
            $scope.events = {};

            /**
             * Starts adding a new location
             */
            $scope.startAddNewLocation = function() {
                $scope.isAddingLocation = true;
                $scope.newLocation = new Location(undefined, player.team);
                locationService.activate($scope.newLocation);
            };

            /**
             * Aborts adding a new location
             */
            $scope.resetAddNewLocation = function() {
                locationService.activate();
                if ($scope.newLocation.isAddedToMap === true) {
                    // Remove from map if it was added
                    $scope.locations = $scope.locations.slice(0, $scope.locations.length - 1);
                }
                $scope.isAddingLocation = false;
                $scope.newLocation = undefined;
            };

            /**
             * Finalises adding a new location
             */
            $scope.addNewLocation = function() {
                locationService.submitLocation($scope.newLocation);
                $scope.isAddingLocation = false;
                $scope.newLocation = undefined;
            };

            /**
             * Goes to the location view
             * @param location
             */
            $scope.visitLocation = function(location) {
                $location.path('location/' + location.id);
            };

            /**
             * Handler for clicks on the map
             * @param event
             * @param args
             */
            var mapClickHandler = function(event, args) {
                if ($scope.isAddingLocation) {
                    // When adding a new location, take the click
                    // as the coordinates of this new location
                    $scope.newLocation.lat = args.leafletEvent.latlng.lat;
                    $scope.newLocation.lng = args.leafletEvent.latlng.lng;

                    // Push to map if not already there
                    if ($scope.newLocation.isAddedToMap !== true) {
                        $scope.locations.push($scope.newLocation);
                        $scope.newLocation.isAddedToMap = true;
                    }
                }
                else {
                    // When not adding a location, deselect currently active location
                    locationService.activate();
                }
            };

            /**
             * Handler for clicks on map markers (Locations)
             * @param event
             * @param args
             */
            var locationClickHandler = function(event, args) {
                locationService.activate($scope.locations[args.markerName]);
            };

            // Register event handlers
            $scope.$on('leafletDirectiveMap.click', mapClickHandler);
            $scope.$on('leafletDirectiveMarker.click', locationClickHandler);

            // Check if we are logged in
            if (backendService.isLoggedIn()) {
                // Get the locations
                locationService.getLocations().then(function(locations) {
                    $scope.locations = locations;
                    $scope.locationsLoaded = true;
                });

                // Get the player
                playerService.getMe().then(function(me) {
                    player = me;
                });
            }
            else {
                $scope.locationsLoaded = true;
            }
        }
    ]);
})(window.veganaut.mapModule);
<|endoftext|>


<commit_before>'use strict'

const deflate = require('zlib').deflate
const dgram = require('dgram')
const EventEmitter = require('events')
const os = require('os')
const async = require('async')

const defaults = {
  graylogPort: 12201,
  graylogHostname: '127.0.0.1',
  connection: 'wan',
  maxChunkSizeWan: 1420,
  maxChunkSizeLan: 8154
}

const GELF_MAGIC_NO = [ 0x1e, 0x0f ]

class Gelf extends EventEmitter {
  constructor (options) {
    super(options)

    this.config = options = Object.assign({}, defaults, options)
    this.client = this.openSocket()

    this.on('gelf.log', (json = {}, cb = () => {}) => {
      const msg = this.sanitizeMsg(json)
      setImmediate(() => {
        this.sendMessage(msg, cb)
      })
    })

    this.on('gelf.message', (msg, cb = () => {}) => {
      this.sendMessage(msg, cb)
    })
  }

  openSocket () {
    const client = dgram.createSocket('udp4')
    return client
  }

  closeSocket () {
    this.client.close()
  }

  sendMessage (msg, cb) {
    this.compress(msg, (_, buf) => {
      const m = this.maybeChunkMessage(buf)
      this.send(m, cb)
    })
  }

  maybeChunkMessage (buf) {
    const {
      connection,
      maxChunkSizeWan,
      maxChunkSizeLan
    } = this.config

    const bufSize = buf.length

    if (connection === 'wan' && bufSize > maxChunkSizeWan) {
      const chunks = this.getChunks(buf, maxChunkSizeWan)
      return this.createPackets(chunks)
    }

    if (connection === 'lan' && bufSize > maxChunkSizeLan) {
      const chunks = this.getChunks(buf, maxChunkSizeLan)
      return this.createPackets(chunks)
    }

    return buf
  }

  send (msg, cb = () => {}) {
    const { graylogPort, graylogHostname } = this.config
    const client = this.client

    if (!Array.isArray(msg)) {
      msg = [ msg ]
    }

    const tasks = msg.map((m) => {
      const self = this
      return function task (cb) {
        client.send(m, 0, m.length, graylogPort, graylogHostname, (err) => {
          if (err) {
            return cb(err) && self.emitError(err)
          }

          return cb(null)
        })
      }
    })

    async.series(tasks, (err) => {
      if (err) return cb(err) && this.emitError(err)
      cb(null)
    })
  }

  compress (msg, cb = () => {}) {
    deflate(msg, (err, buf) => {
      if (err) {
        cb(err)
        return this.emitError(err)
      }

      cb(null, buf)
    })
  }

  getChunks (buf, chunkSize) {
    const res = []

    for (let index = 0; index < buf.length; index += chunkSize) {
      res.push(
        Array.prototype.slice.call(buf, index, index + chunkSize)
      )
    }

    return res
  }

  createPackets (chunks) {
    const res = []
    const count = chunks.length

    const msgId = Math.floor(
      Math.random() * (99999999 - 10000000)
    ) + 10000000

    chunks.forEach((chunk, index) => {
      res[index] = Buffer.from(
        GELF_MAGIC_NO.concat(msgId, index, count, chunk)
      )
    })

    return res
  }

  emitError (err) {
    this.emit('error', err)
  }

  sanitizeMsg (msg) {
    let json = {}

    json.short_message = msg.short_message

    if (typeof msg === 'string') {
      json.short_message = msg
    } else {
      json = Object.assign({}, json, msg)
    }

    if (msg._id) {
      return this.emitError(new Error('_id is not allowed'))
    }

    if (!msg.version) {
      json.version = '1.0'
    }

    if (!msg.host) {
      json.host = os.hostname()
    }

    if (!msg.timestamp) {
      json.timestamp = new Date().getTime() / 1000
    }

    if (!msg.facility) {
      json.facility = 'node.js'
    }

    if (!json.short_message) {
      json.short_message = 'Gelf Shortmessage'
    }

    return JSON.stringify(json)
  }
}

module.exports = Gelf
<commit_msg>unref the socket (#10)<commit_after>'use strict'

const deflate = require('zlib').deflate
const dgram = require('dgram')
const EventEmitter = require('events')
const os = require('os')
const async = require('async')

const defaults = {
  graylogPort: 12201,
  graylogHostname: '127.0.0.1',
  connection: 'wan',
  maxChunkSizeWan: 1420,
  maxChunkSizeLan: 8154
}

const GELF_MAGIC_NO = [ 0x1e, 0x0f ]

class Gelf extends EventEmitter {
  constructor (options) {
    super(options)

    this.config = options = Object.assign({}, defaults, options)
    this.client = this.openSocket()

    this.on('gelf.log', (json = {}, cb = () => {}) => {
      const msg = this.sanitizeMsg(json)
      setImmediate(() => {
        this.sendMessage(msg, cb)
      })
    })

    this.on('gelf.message', (msg, cb = () => {}) => {
      this.sendMessage(msg, cb)
    })
  }

  openSocket () {
    const client = dgram.createSocket('udp4')
    client.unref()
    return client
  }

  closeSocket () {
    this.client.close()
  }

  sendMessage (msg, cb) {
    this.compress(msg, (_, buf) => {
      const m = this.maybeChunkMessage(buf)
      this.send(m, cb)
    })
  }

  maybeChunkMessage (buf) {
    const {
      connection,
      maxChunkSizeWan,
      maxChunkSizeLan
    } = this.config

    const bufSize = buf.length

    if (connection === 'wan' && bufSize > maxChunkSizeWan) {
      const chunks = this.getChunks(buf, maxChunkSizeWan)
      return this.createPackets(chunks)
    }

    if (connection === 'lan' && bufSize > maxChunkSizeLan) {
      const chunks = this.getChunks(buf, maxChunkSizeLan)
      return this.createPackets(chunks)
    }

    return buf
  }

  send (msg, cb = () => {}) {
    const { graylogPort, graylogHostname } = this.config
    const client = this.client

    if (!Array.isArray(msg)) {
      msg = [ msg ]
    }

    const tasks = msg.map((m) => {
      const self = this
      return function task (cb) {
        client.send(m, 0, m.length, graylogPort, graylogHostname, (err) => {
          if (err) {
            return cb(err) && self.emitError(err)
          }

          return cb(null)
        })
      }
    })

    async.series(tasks, (err) => {
      if (err) return cb(err) && this.emitError(err)
      cb(null)
    })
  }

  compress (msg, cb = () => {}) {
    deflate(msg, (err, buf) => {
      if (err) {
        cb(err)
        return this.emitError(err)
      }

      cb(null, buf)
    })
  }

  getChunks (buf, chunkSize) {
    const res = []

    for (let index = 0; index < buf.length; index += chunkSize) {
      res.push(
        Array.prototype.slice.call(buf, index, index + chunkSize)
      )
    }

    return res
  }

  createPackets (chunks) {
    const res = []
    const count = chunks.length

    const msgId = Math.floor(
      Math.random() * (99999999 - 10000000)
    ) + 10000000

    chunks.forEach((chunk, index) => {
      res[index] = Buffer.from(
        GELF_MAGIC_NO.concat(msgId, index, count, chunk)
      )
    })

    return res
  }

  emitError (err) {
    this.emit('error', err)
  }

  sanitizeMsg (msg) {
    let json = {}

    json.short_message = msg.short_message

    if (typeof msg === 'string') {
      json.short_message = msg
    } else {
      json = Object.assign({}, json, msg)
    }

    if (msg._id) {
      return this.emitError(new Error('_id is not allowed'))
    }

    if (!msg.version) {
      json.version = '1.0'
    }

    if (!msg.host) {
      json.host = os.hostname()
    }

    if (!msg.timestamp) {
      json.timestamp = new Date().getTime() / 1000
    }

    if (!msg.facility) {
      json.facility = 'node.js'
    }

    if (!json.short_message) {
      json.short_message = 'Gelf Shortmessage'
    }

    return JSON.stringify(json)
  }
}

module.exports = Gelf
<|endoftext|>


<commit_before>/** @jsx React.DOM */

define(
  [
    'react',
    'backbone'
  ],
  function (React, Backbone) {

    return React.createClass({

      propTypes: {
        instance: React.PropTypes.instanceOf(Backbone.Model).isRequired
      },

      render: function () {
        var status = this.props.instance.get('status');
        var statusLight;

        if(status === "active"){
          statusLight = ;
        }else if(status === "suspended"){
          statusLight = ;
        }else if(status === "shutoff"){
          statusLight = ;
        }

        return (
          statusLight
        );
      }

    });

  });
<commit_msg>return empty span component to fix bug<commit_after>/** @jsx React.DOM */

define(
  [
    'react',
    'backbone'
  ],
  function (React, Backbone) {

    return React.createClass({

      propTypes: {
        instance: React.PropTypes.instanceOf(Backbone.Model).isRequired
      },

      render: function () {
        var status = this.props.instance.get('status');
        var statusLight;

        if(status === "active"){
          statusLight = ;
        }else if(status === "suspended"){
          statusLight = ;
        }else if(status === "shutoff"){
          statusLight = ;
        }else{
          statusLight = ;
        }

        return (
          statusLight
        );
      }

    });

  });
<|endoftext|>


<commit_before>/*!
 * Module dependencies.
 */

var docpad = require('docpad'),
    docpadInstanceConfig = {},
    docpadGenerateConfig = {};

/*
 * Generate the documentation and capture any errors.
 *
 * We must use this instead of `docpad generate` in order to capture errors.
 * Unfortunately, the docpad binary does not output to stderr and exits with
 * a status code of 0 even when an error exists. This is the only method
 * available to capture an error.
 */

docpad.createInstance(docpadInstanceConfig, function(e, docpadInstance) {
    if (e) throw new Error('failed');

    console.log('docpadGenerateConfig ', docpadGenerateConfig);
    console.log('docpadInstanceConfig ', docpadInstanceConfig);

    docpadInstance.action('generate', docpadGenerateConfig, function(e, result) {
        if (e) {
            console.error(e);
            process.exit(1);
        }
    });
});
<commit_msg>current docpad api is create, not createInstance<commit_after>/*!
 * Module dependencies.
 */

var docpad = require('docpad'),
    docpadInstanceConfig = {},
    docpadGenerateConfig = {};

/*
 * Generate the documentation and capture any errors.
 *
 * We must use this instead of `docpad generate` in order to capture errors.
 * Unfortunately, the docpad binary does not output to stderr and exits with
 * a status code of 0 even when an error exists. This is the only method
 * available to capture an error.
 */

docpad.create(docpadInstanceConfig, function(e, docpadInstance) {
    if (e) throw new Error('failed');

    docpadInstance.action('generate', docpadGenerateConfig, function(e, result) {
        if (e) {
            console.error(e);
            process.exit(1);
        }
    });
});
<|endoftext|>


<commit_before>(function (angular) {
    'use strict';
    var archivoPerfilControllerApp = angular.module('archivoPerfil', ['ngAnimate', 'ngSanitize', 'ui.bootstrap', 'ui.grid', 'ngTouch', 'ui.grid.edit', 'ui.grid.autoResize', 'ui.grid.selection', 'ui.grid.cellNav', 'xeditable'])
    .controller('archivoPerfilController', ['$scope', '$http', '$window', '$location', '$filter', 'uiGridConstants', 'i18nService', '$scope', function ($scope, $http, $window, $location, $filter, i18nService, uiGridConstants) {
        var init = function () {
            $scope.archivoID = $window.localStorage.getItem("archivoID");
            // DATOS PRINCIPALES
            $scope.cargarDatosPrincipales();
            // ANOTACIONES
            $scope.cargarNotas();
        };

        //Datos principales
        $scope.archivoDatos = {};
        $scope.datosPrincipales = {};
        $scope.datosPrincipales.archivoTitulo = "";
        $scope.datosPrincipales.archivoNombre = "";
        $scope.datosPrincipales.institucionFondo = "";
        $scope.datosPrincipales.seccion = "";
        $scope.datosPrincipales.numRefDentroFondo = "";
        $scope.datosPrincipales.archivoFecha = "";
        $scope.datosPrincipales.folioInicial = "";
        $scope.datosPrincipales.folioFinal = "";
        $scope.datosPrincipales.legajo = "";
        $scope.datosPrincipales.numOrden = "";
        $scope.datosPrincipales.numPaginas = "";
        $scope.datosPrincipales.palabrasClaves = {};
        $scope.datosPrincipales.disponibilidad = "";

        //Bandera para saber cuando guardar o no
        $scope.datosPrincipales.editado = false;

        $scope.cargarDatosPrincipales = function () {
            $http.get('http://monsalvediaz.com:5000/PIMC0.1/ConsultaArchivo?archivoID=' + $scope.archivoID).then(function (data) {
                //Obtener los datos JSON
                $scope.archivoDatos = data.data[0];
                //Log
                console.log($scope.archivoDatos);

                //Llenamos los datos del archivo
                $scope.datosPrincipales.archivoTitulo = $scope.archivoDatos.titulo;
                $scope.datosPrincipales.archivoNombre = $scope.archivoDatos.fondo;
                $scope.datosPrincipales.institucionFondo = $scope.archivoDatos.institucionFondo;
                $scope.datosPrincipales.seccion = $scope.archivoDatos.seccion;
                $scope.datosPrincipales.numRefDentroFondo = $scope.archivoDatos.numRefDentroFondo;
                $scope.datosPrincipales.archivoFecha = $filter('date')(new Date($scope.archivoDatos.fechaInicial), String($scope.archivoDatos.fechaInicialFormato).toLowerCase()) + " - " + $filter('date')(new Date($scope.archivoDatos.fechaFinal), String($scope.archivoDatos.fechaFinalFormato).toLowerCase());
                $scope.datosPrincipales.folioInicial = $scope.archivoDatos.folioInicial;
                $scope.datosPrincipales.folioFinal = $scope.archivoDatos.folioFinal;
                $scope.datosPrincipales.legajo = $scope.archivoDatos.legajo;
                $scope.datosPrincipales.numOrden = $scope.archivoDatos.numOrden;
                $scope.datosPrincipales.numPaginas = $scope.archivoDatos.numPaginas;
                $scope.datosPrincipales.palabrasClaves = $scope.archivoDatos.palabrasClaves.split(",");
                $scope.datosPrincipales.palabrasClaves = $scope.datosPrincipales.palabrasClaves.map(function (e) { return e.trim(); });

                $scope.datosPrincipales.disponibilidad = $scope.archivoDatos.disponibilidad;
                //Limpiamos la bandera de editado
                $scope.datosPrincipales.editado = false;

                //Para palabras claves
                $scope.palabraNueva = {mensaje:"+Agregar"};

            });
        };

        // Anotaciones
        $scope.notas = "";
        $scope.notasAEliminar = [];
        $scope.notasCambio = false;
        $scope.cargarNotas = function () {
            $http.get('http://monsalvediaz.com:5000/PIMC0.1/Consulta/ArchivosNotas?archivoID=' + $scope.archivoID).then(function (data) {
                if (!String(data.data).startsWith("[WARNING]")) {
                    $scope.notas = data.data;
                    $scope.notas.forEach( function (nota) {
                        nota.modificada = false;
                    });
                    // LOG
                    console.log($scope.notas);
                }
            });

        };
        $scope.agregarNotaVacia = function () {
            // Una nota que no tiene fecha de creacion es una nota que no existe en la base de datos aun
            if ($scope.notas === "") {
                $scope.notas = [{
                    nota:"",
                    referencia:"",
                    fechaCreacion:"",
                    fechaHistorica:"",
                    fechaHistFormato:"",
                    modificada: false
                }];
            } else {
                $scope.notas.push({
                    nota:"",
                    referencia:"",
                    fechaCreacion:"",
                    fechaHistorica:"",
                    fechaHistFormato:"",
                    modificada: false
                });
            }
            $scope.notasCambios = true;
        }
        $scope.eliminarNota = function(indexNota) {
            if ($scope.notas[indexNota].fechaCreacion != "") {
                $scope.notasAEliminar.push($scope.notas[indexNota]);
            }
            $scope.notas.splice(indexNota,1);
            $scope.notasCambios = true;
        };
        $scope.modificarNota = function(indexNota,nuevaNota) {
            $scope.notas[indexNota].nota = nuevaNota;
            if ($scope.notas[indexNota].fechaCreacion != "") {
                $scope.notas[indexNota].modificada = true;
            };
            $scope.notasCambios = true;
        };
        $scope.modificarReferencia = function(indexNota,nuevaReferencia) {
            $scope.notas[indexNota].referencia = nuevaReferencia;
            if ($scope.notas[indexNota].fechaCreacion != "") {
                $scope.notas[indexNota].modificada = true;
            }
            $scope.notasCambios = true;

        };

        // Para borrar palabras claves
        $scope.borrarSiVacio = function (indexEditada, palabra) {
            if (palabra == "") {
                $scope.datosPrincipales.palabrasClaves.splice(indexEditada,1);
            }
        }
        //Para agregar palabras claves
        $scope.palabraNueva = {mensaje: '+Agregar'};

        $scope.borrarCampo = function () {
            $scope.palabraNueva.mensaje = "";
        }
        $scope.mostrarCampo = function () {
            $scope.palabraNueva.mensaje = "+Agregar";
        }
        $scope.agregarPalabraNueva = function (palabra) {
            if (!$scope.datosPrincipales.palabrasClaves.includes(palabra) && palabra.length != 0) {
                $scope.datosPrincipales.palabrasClaves.push(palabra);
            }
            $scope.palabraNueva.mensaje = "+Agregar";
        }

        //Para guardar borrar y barra
        $scope.ultimaAccion = "";
        // Button functions
        $scope.borrarCambios = function () {
            if (window.confirm("Esta Seguro que quiere borrar los cambios?") === true) {
                init();
            }
        };
        $scope.guardarCambios = function () {
            if($scope.notasCambios) {
                $scope.notasCambios = false;
                $scope.notas.forEach(function (nota) {
                    // Insertamos notas nuevas
                    if (nota.fechaCreacion.length == 0 && nota.nota.length != 0)
                        $http.get('http://monsalvediaz.com:5000/PIMC0.1/Insertar/ArchivosNotas?ArchivoID='+ $scope.archivoID +'&nota="' + nota.nota + '"&referencia="'  + nota.referencia + '"').then(function (data) {
                            console.log(data);
                        });
                    // Modificamos notas viejas
                    if (nota.modificada == true) {
                        $http.get('http://monsalvediaz.com:5000/PIMC0.1/Modificar/ArchivosNotas?idUnico=archivoId&idUnico=notaID&notaID='+ nota.notaID +' &archivoID=' + $scope.archivoID +'&nota="' + nota.nota + '"&referencia="'  + nota.referencia + '"').then(function (data) {
                            console.log(data);
                        });
                    }
                });
                // Eliminamos notas eliminadas
                $scope.notasAEliminar.forEach(function (nota) {
                    $http.get('http://monsalvediaz.com:5000/PIMC0.1/Eliminar/ArchivosNotas?idUnico=archivoId&idUnico=notaID&notaID='+ nota.notaID +'&archivoID=' + $scope.archivoID).then(function (data) {
                            console.log(data);
                        });
                });

            }
            //Revisamos datos principales editados
            if ($scope.datosPrincipales.editado) {

            }
            init();
        };

        // Initialization fucntion
        init();

    }]);
    archivoPerfilControllerApp.run(function (editableOptions,editableThemes) {
        editableThemes.bs3.inputClass = 'input-sm';
        editableThemes.bs3.buttonsClass = 'btn-sm';
        editableOptions.theme = 'bs3';
        editableOptions.buttons = 'no';
    });
})(window.angular);

<commit_msg>Agregar Notas<commit_after>(function (angular) {
    'use strict';
    var archivoPerfilControllerApp = angular.module('archivoPerfil', ['ngAnimate', 'ngSanitize', 'ui.bootstrap', 'ui.grid', 'ngTouch', 'ui.grid.edit', 'ui.grid.autoResize', 'ui.grid.selection', 'ui.grid.cellNav', 'xeditable'])
    .controller('archivoPerfilController', ['$scope', '$http', '$window', '$location', '$filter', 'uiGridConstants', 'i18nService', '$scope', function ($scope, $http, $window, $location, $filter, i18nService, uiGridConstants) {
        var init = function () {
            $scope.archivoID = $window.localStorage.getItem("archivoID");
            // DATOS PRINCIPALES
            $scope.cargarDatosPrincipales();
            // ANOTACIONES
            $scope.cargarNotas();
        };

        //Datos principales
        $scope.archivoDatos = {};
        $scope.datosPrincipales = {};
        $scope.datosPrincipales.archivoTitulo = "";
        $scope.datosPrincipales.archivoNombre = "";
        $scope.datosPrincipales.institucionFondo = "";
        $scope.datosPrincipales.seccion = "";
        $scope.datosPrincipales.numRefDentroFondo = "";
        $scope.datosPrincipales.archivoFecha = "";
        $scope.datosPrincipales.folioInicial = "";
        $scope.datosPrincipales.folioFinal = "";
        $scope.datosPrincipales.legajo = "";
        $scope.datosPrincipales.numOrden = "";
        $scope.datosPrincipales.numPaginas = "";
        $scope.datosPrincipales.palabrasClaves = {};
        $scope.datosPrincipales.disponibilidad = "";

        //Bandera para saber cuando guardar o no
        $scope.datosPrincipales.editado = false;

        $scope.cargarDatosPrincipales = function () {
            $http.get('http://monsalvediaz.com:5000/PIMC0.1/ConsultaArchivo?archivoID=' + $scope.archivoID).then(function (data) {
                //Obtener los datos JSON
                $scope.archivoDatos = data.data[0];
                //Log
                console.log($scope.archivoDatos);

                //Llenamos los datos del archivo
                $scope.datosPrincipales.archivoTitulo = $scope.archivoDatos.titulo;
                $scope.datosPrincipales.archivoNombre = $scope.archivoDatos.fondo;
                $scope.datosPrincipales.institucionFondo = $scope.archivoDatos.institucionFondo;
                $scope.datosPrincipales.seccion = $scope.archivoDatos.seccion;
                $scope.datosPrincipales.numRefDentroFondo = $scope.archivoDatos.numRefDentroFondo;
                $scope.datosPrincipales.archivoFecha = $filter('date')(new Date($scope.archivoDatos.fechaInicial), String($scope.archivoDatos.fechaInicialFormato).toLowerCase()) + " - " + $filter('date')(new Date($scope.archivoDatos.fechaFinal), String($scope.archivoDatos.fechaFinalFormato).toLowerCase());
                $scope.datosPrincipales.folioInicial = $scope.archivoDatos.folioInicial;
                $scope.datosPrincipales.folioFinal = $scope.archivoDatos.folioFinal;
                $scope.datosPrincipales.legajo = $scope.archivoDatos.legajo;
                $scope.datosPrincipales.numOrden = $scope.archivoDatos.numOrden;
                $scope.datosPrincipales.numPaginas = $scope.archivoDatos.numPaginas;
                $scope.datosPrincipales.palabrasClaves = $scope.archivoDatos.palabrasClaves.split(",");
                $scope.datosPrincipales.palabrasClaves = $scope.datosPrincipales.palabrasClaves.map(function (e) { return e.trim(); });

                $scope.datosPrincipales.disponibilidad = $scope.archivoDatos.disponibilidad;
                //Limpiamos la bandera de editado
                $scope.datosPrincipales.editado = false;

                //Para palabras claves
                $scope.palabraNueva = {mensaje:"+Agregar"};

            });
        };

        // Anotaciones
        $scope.notas = "";
        $scope.notasAEliminar = [];
        $scope.notasCambio = false;
        $scope.cargarNotas = function () {
            $http.get('http://monsalvediaz.com:5000/PIMC0.1/Consulta/ArchivosNotas?archivoID=' + $scope.archivoID).then(function (data) {
                if (!String(data.data).startsWith("[WARNING]")) {
                    $scope.notas = data.data;
                    $scope.notas.forEach( function (nota) {
                        nota.modificada = false;
                    });
                    // LOG
                    console.log($scope.notas);
                }
            });

        };
        $scope.agregarNotaVacia = function () {
            // Una nota que no tiene fecha de creacion es una nota que no existe en la base de datos aun
            if ($scope.notas === "") {
                $scope.notas = [{
                    nota:"",
                    referencia:"",
                    fechaCreacion:"",
                    fechaHistorica:"",
                    fechaHistFormato:"",
                    modificada: false
                }];
            } else {
                $scope.notas.push({
                    nota:"",
                    referencia:"",
                    fechaCreacion:"",
                    fechaHistorica:"",
                    fechaHistFormato:"",
                    modificada: false
                });
            }
            $scope.notasCambios = true;
        }
        $scope.eliminarNota = function(indexNota) {
            if ($scope.notas[indexNota].fechaCreacion != "") {
                $scope.notasAEliminar.push($scope.notas[indexNota]);
            }
            $scope.notas.splice(indexNota,1);
            $scope.notasCambios = true;
        };
        $scope.modificarNota = function(indexNota,nuevaNota) {
            $scope.notas[indexNota].nota = nuevaNota;
            if ($scope.notas[indexNota].fechaCreacion != "") {
                $scope.notas[indexNota].modificada = true;
            };
            $scope.notasCambios = true;
        };
        $scope.modificarReferencia = function(indexNota,nuevaReferencia) {
            $scope.notas[indexNota].referencia = nuevaReferencia;
            if ($scope.notas[indexNota].fechaCreacion != "") {
                $scope.notas[indexNota].modificada = true;
            }
            $scope.notasCambios = true;

        };

        // Para borrar palabras claves
        $scope.borrarSiVacio = function (indexEditada, palabra) {
            if (palabra == "") {
                $scope.datosPrincipales.palabrasClaves.splice(indexEditada,1);
            }
        }
        //Para agregar palabras claves
        $scope.palabraNueva = {mensaje: '+Agregar'};

        $scope.borrarCampo = function () {
            $scope.palabraNueva.mensaje = "";
        }
        $scope.mostrarCampo = function () {
            $scope.palabraNueva.mensaje = "+Agregar";
        }
        $scope.agregarPalabraNueva = function (palabra) {
            if (!$scope.datosPrincipales.palabrasClaves.includes(palabra) && palabra.length != 0) {
                $scope.datosPrincipales.palabrasClaves.push(palabra);
            }
            $scope.palabraNueva.mensaje = "+Agregar";
        }

        //Para guardar borrar y barra
        $scope.ultimaAccion = "";
        // Button functions
        $scope.borrarCambios = function () {
            if (window.confirm("Esta Seguro que quiere borrar los cambios?") === true) {
                init();
            }
        };
        $scope.guardarCambios = function () {
            if($scope.notasCambios) {
                $scope.notasCambios = false;
                $scope.notas.forEach(function (nota) {
                    // Insertamos notas nuevas
                    if (nota.fechaCreacion.length == 0 && nota.nota.length != 0)
                        $http.get('http://monsalvediaz.com:5000/PIMC0.1/Insertar/ArchivosNotas?ArchivoID='+ $scope.archivoID +'&nota="' + nota.nota + '"&referencia="'  + nota.referencia + '"').then(function (data) {
                            console.log(data);
                        });
                    // Modificamos notas viejas
                    if (nota.modificada == true) {
                        $http.get('http://monsalvediaz.com:5000/PIMC0.1/Modificar/ArchivosNotas?idUnico=archivoID&idUnico=notaID&notaID='+ nota.notaID +' &archivoID=' + $scope.archivoID +'&nota="' + nota.nota + '"&referencia="'  + nota.referencia + '"').then(function (data) {
                            console.log(data);
                        });
                    }
                });
                // Eliminamos notas eliminadas
                $scope.notasAEliminar.forEach(function (nota) {
                    $http.get('http://monsalvediaz.com:5000/PIMC0.1/Eliminar/ArchivosNotas?idUnico=archivoID&idUnico=notaID&notaID='+ nota.notaID +'&archivoID=' + $scope.archivoID).then(function (data) {
                            console.log(data);
                        });
                });

            }
            //Revisamos datos principales editados
            if ($scope.datosPrincipales.editado) {

            }
            init();
        };

        // Initialization fucntion
        init();

    }]);
    archivoPerfilControllerApp.run(function (editableOptions,editableThemes) {
        editableThemes.bs3.inputClass = 'input-sm';
        editableThemes.bs3.buttonsClass = 'btn-sm';
        editableOptions.theme = 'bs3';
        editableOptions.buttons = 'no';
    });
})(window.angular);

<|endoftext|>


<commit_before>import React, { PropTypes } from 'react'

const pathIsActive = (to, location, activeOnlyWhenExact) => {
  const { pathname } = location
  return activeOnlyWhenExact ?
    pathname === to : pathname.startsWith(to)
}

// needs accessibility stuff from React Router Link
class Link extends React.Component {
  static propTypes = {
    to: PropTypes.oneOfType([ PropTypes.string, PropTypes.object ]),
    style: PropTypes.object,
    activeStyle: PropTypes.object,
    location: PropTypes.object,
    activeOnlyWhenExact: PropTypes.bool
  }

  static defaultProps = {
    activeOnlyWhenExact: false,
    style: {},
    activeStyle: {}
  }

  static contextTypes = {
    history: PropTypes.object,
    location: PropTypes.object
  }

  handleClick = (event) => {
    event.preventDefault()

    const { history } = this.context
    const { to } = this.props

    history.push(to)
  }

  render() {
    const {
      to,
      style,
      activeStyle,
      location,
      activeOnlyWhenExact,
      ...rest
    } = this.props

    const loc = location || this.context.location
    const isActive = pathIsActive(to, loc, activeOnlyWhenExact)
    return (
      <a
        {...rest}
        href={typeof to === 'object' ? to.pathname : to}
        style={isActive ? { ...style, ...activeStyle } : style}
        onClick={this.handleClick}
      />
    )
  }
}

export default Link
<commit_msg>Added in everything we already knew about Link<commit_after>import React, { PropTypes } from 'react'

const { oneOfType, string, object, bool, func } = PropTypes

const pathIsActive = (to, pathname, activeOnlyWhenExact) =>
  activeOnlyWhenExact ? pathname === to : pathname.startsWith(to)

const isLeftClickEvent = (event) =>
  event.button === 0

const isModifiedEvent = (event) =>
  !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey)

class Link extends React.Component {

  static propTypes = {
    to: oneOfType([ string, object ]).isRequired,
    style: object,
    activeStyle: object,
    className: string,
    activeClassName: string,
    location: object,
    activeOnlyWhenExact: bool,
    target: string,
    onClick: func
  }

  static defaultProps = {
    activeOnlyWhenExact: false,
    className: '',
    activeClassName: '',
    style: {},
    activeStyle: {}
  }

  static contextTypes = {
    history: PropTypes.object,
    location: PropTypes.object
  }

  handleClick = (event) => {
    const { history } = this.context
    const { to, onClick, target } = this.props

    if (onClick)
      onClick(event)

    if (
      !event.defaultPrevented && // onClick prevented default
      !target && // let browser handle "target=_blank" etc.
      !isModifiedEvent(event) &&
      isLeftClickEvent(event)
    ) {
      event.preventDefault()
      history.push(to)
    }
  }

  render() {
    const {
      to,
      style,
      activeStyle,
      className,
      activeClassName,
      location,
      activeOnlyWhenExact,
      ...rest
    } = this.props

    const loc = location || this.context.location
    const isActive = pathIsActive(to, loc.pathname, activeOnlyWhenExact)

    return (
      <a
        {...rest}
        href={typeof to === 'object' ? to.pathname : to}
        onClick={this.handleClick}
        style={isActive ? { ...style, ...activeStyle } : style }
        className={isActive ?
          [ activeClassName, className ].join(' ').trim() : className
        }
      />
    )
  }
}

export default Link
<|endoftext|>