<commit_before>
var LibratoMetrics = {
  url: 'https://metrics-api.librato.com/v1/metrics',
  graphs: {},      // rickshaw objects
  datum: {},       // metric data
  aliases: {},     // alias strings
  realMetrics: {}, // non-false targets
  // minutes of data in the live feed
  period: (typeof period == 'undefined') ? 20 : period,

  // gather our non-false targets
  gatherRealMetrics: function() {
    for (var metric in this.metrics) {
      if (this.metrics[metric].target === false) {
      } else {
        var name = this.metrics[metric].target + '-' + this.metrics[metric].source
        this.realMetrics[name] = this.metrics[metric];
        this.realMetrics[name]['selector'] = this.metrics[metric].target.replace(/[\.:]/g, '-');
      }
    }
  },

  // build our graph objects
  constructGraphs: function() {
    for (var metric in this.realMetrics) {
      var name = this.realMetrics[metric].target + '-' + this.realMetrics[metric].source
      var alias = this.realMetrics[metric].alias || this.realMetrics[metric].target;
      this.aliases[name] = alias;
      this.datum[name] = [{ x:0, y:0 }];
      this.graphs[name] = new Rickshaw.Graph({
        element: document.querySelector('.graph' + this.realMetrics[metric].selector),
        width: 348,
        height: 100,
        interpolation: 'step-after',
        series: [{
          name: this.aliases[name],
          color: '#afdab1',
          data: this.datum[name]
        }]
      });
      this.graphs[name].render();
    }
  },

  // construct url
  constructUrl: function(metric) {
    var source = this.realMetrics[metric].source;
    var target = this.realMetrics[metric].target;
    var now = new Date();
    var offset = now.getTimezoneOffset();
    now = parseInt((now.getTime() + offset * 60) / 1000);
    var start = now - (this.period * 60);
    var end = now;
    return this.url + '/' + encodeURI(target) + '?source=' + source + '&resolution=1&start_time=' + start + '&end_time=' + end;
  },

  // refresh the graph
  refreshData: function(immediately) {
    for (var metric in this.realMetrics) {
      this.getData(metric, function(metric, values) {
        for (var i = 0; i < values.length; i++) {
          if (typeof values[i] !== "undefined") {
            this.datum[metric][i] = values[i];
          }
        }
        // check our thresholds and update color
        var lastValue = this.datum[metric][this.datum[metric].length - 1].y;
        var warning = this.realMetrics[metric].warning;
        var critical = this.realMetrics[metric].critical;
        if (critical > warning) {
          if (lastValue >= critical) {
            this.graphs[metric].series[0].color = '#d59295';
          } else if (lastValue >= warning) {
            this.graphs[metric].series[0].color = '#f5cb56';
          } else {
            this.graphs[metric].series[0].color = '#afdab1';
          }
        } else {
          if (lastValue <= critical) {
            this.graphs[metric].series[0].color = '#d59295';
          } else if (lastValue <= warning) {
            this.graphs[metric].series[0].color = '#f5cb56';
          } else {
            this.graphs[metric].series[0].color = '#afdab1';
          }
        }
        // we want to render immediately, i.e.
        // as soon as ajax completes
        // used for time period / pause view
        if (immediately) this.updateGraph(metric);
      });
      values = null;
    }

    // we can wait until all data is gathered, i.e.
    // the live refresh should happen synchronously
    if (!immediately) {
      for (var graph in this.graphs) {
        this.updateGraph(graph);
      }
    }
  },

  displayTransform: function(value, period, transform) {
    if (transform !== undefined && transform !== null && transform.length > 0) {
      var p = period, x = value;
      return eval(transform);
    } else {
      return value;
    }
  },

  // retrieve the data from Graphite
  getData: function(metric, callback) {
    $.ajax({
      beforeSend: function(xhr) {
        if (auth.length > 0) {
          var bytes = Crypto.charenc.Binary.stringToBytes(auth);
          var base64 = Crypto.util.bytesToBase64(bytes);
          xhr.setRequestHeader("Authorization", "Basic " + base64);
        }
      },
      dataType: 'json',
      error: function(xhr, textStatus, errorThrown) { console.log(errorThrown); },
      url: this.constructUrl(metric),
      cache: false
    }).done(function(d) {
      LibratoMetrics.done(metric, callback, d);
    });
  },

  done: function(metric, callback, d) {
    var myDatum = [];
    var source = this.realMetrics[metric].source;
    var transform = d.attributes.display_transform;
    var period = d.period;
    if (d.measurements[source] !== undefined && d.measurements[source].length > 0) {
      myDatum[0] = {
        x: d.measurements[source][0].measure_time,
        y: this.displayTransform(d.measurements[source][0].value, this.period, transform) || 0
      };
      for (var j = 1; j < d.measurements[source].length; j++) {
        myDatum[j] = {
          x: d.measurements[source][j].measure_time,
          y: this.displayTransform(d.measurements[source][j].value, this.period, transform) || graphs[metric].lastKnownValue
        };
        if (typeof d.measurements[source][0].value === "number") {
          this.graphs[metric].lastKnownValue = d.measurements[source][0].value;
        }
      }
      callback.call(LibratoMetrics, metric, myDatum);
    }

  },

  // perform the actual graph object and
  // overlay name and number updates
  updateGraph: function(graph) {
    // update our graph
    this.graphs[graph].update();
    if (this.datum[graph][this.datum[graph].length - 1] !== undefined) {
      var lastValue = this.datum[graph][this.datum[graph].length - 1].y;
      var lastValueDisplay = Math.round(lastValue * 100) / 100;
      $('.overlay-name' + this.realMetrics[graph].selector).text(this.aliases[graph]);
      $('.overlay-number' + this.realMetrics[graph].selector).text(lastValueDisplay);
      if (this.realMetrics[graph].unit) {
        $('.overlay-number' + this.realMetrics[graph].selector).append('' + this.realMetrics[graph].unit + '');
      }
    } else {
      $('.overlay-name' + this.realMetrics[graph].selector).text(this.aliases[graph]);
      $('.overlay-number' + this.realMetrics[graph].selector).html('NF');
    }
  },

  // add our containers
  buildContainers: function() {
    var falseTargets = 0;
    for (var metric in this.metrics) {
      if (metrics[metric].target === false) {
        $('#main').append('

');
        falseTargets++;
      } else {
        $('#main').append(
          '
' +
          '

' +
          '

' +
          '
'
        );
      }
    }
  },
  initialize: function() {
    this.metrics = metrics;
    // filter out false targets
    this.gatherRealMetrics();

    // build our div containers
    this.buildContainers();

    // build our graph objects
    this.constructGraphs();
    // initial load screen
    for (var graph in this.graphs) {
      if (this.realMetrics[graph].target === false) {
        //continue;
      } else if (myTheme === "dark") {
        $('.overlay-number' + this.realMetrics[graph].selector).html('');
      } else {
        $('.overlay-number' + this.realMetrics[graph].selector).html('');
      }
    }
  }
}

LibratoMetrics.initialize();

// set our last known value at invocation
Rickshaw.Graph.prototype.lastKnownValue = 0;

// set our theme
var myTheme = (typeof theme == 'undefined') ? 'default' : theme;
if (myTheme === "dark") { enableNightMode(); }

// hide our toolbar if necessary
var toolbar = (typeof toolbar == 'undefined') ? true : toolbar;
if (!toolbar) { $('div#toolbar').css('display', 'none'); }

LibratoMetrics.refreshData("now");

// define our refresh and start interval
function refreshData() {
  LibratoMetrics.refreshData();
}

var refreshInterval = (typeof refresh == 'undefined') ? 20000 : refresh;
var refreshId = setInterval(refreshData, refreshInterval);

// set our "live" interval hint
$('#toolbar ul li.timepanel a.play').text(LibratoMetrics.period + 'min');

// activate night mode
function enableNightMode() {
  $('body').addClass('night');
  $('div#title h1').addClass('night');
  $('div#graph svg').css('opacity', '0.8');
  $('div#overlay-name').addClass('night');
  $('div#overlay-number').addClass('night');
  $('div#toolbar ul li.timepanel').addClass('night');
}

// deactivate night mode
function disableNightMode() {
  $('body').removeClass('night');
  $('div#title h1').removeClass('night');
  $('div#graph svg').css('opacity', '1.0');
  $('div#overlay-name').removeClass('night');
  $('div#overlay-number').removeClass('night');
  $('div#toolbar ul li.timepanel').removeClass('night');
}

// activate night mode by click
$('li.toggle-night a').click(function() {
  if ($('body').hasClass('night')) {
    disableNightMode();
  } else {
    enableNightMode();
  }
});

// toggle number display
$('li.toggle-nonum a').click(function() { $('div#overlay-number').toggleClass('nonum'); });

// time panel, pause live feed and show range
$('#toolbar ul li.timepanel a.range').click(function() {
  period = $(this).attr("title");
  LibratoMetrics.refreshData("now")
  if (! $('#toolbar ul li.timepanel a.play').hasClass('pause')) {
    $('#toolbar ul li.timepanel a.play').addClass('pause');
  }
  $('#toolbar ul li.timepanel a.play').text('paused');
  $(this).parent('li').parent('ul').find('li').removeClass('selected');
  $(this).parent('li').addClass('selected');
  clearInterval(refreshId);
});

// time panel, resume live feed
$('#toolbar ul li.timepanel a.play').click(function() {
  period = 20;
  $(this).parent('li').parent('ul').find('li').removeClass('selected');
  $(this).parent('li').addClass('selected');
  $(this).removeClass('pause');
  $('#toolbar ul li.timepanel a.play').text(period + 'min');
  LibratoMetrics.refreshData("now");
  // explicitly clear the old Interval in case
  // someone "doubles up" on the live play button
  clearInterval(refreshId);
  // remove and recreate the original graphs[]
  // helps clear out any rendering artifacts
  $('#graph svg').remove();
  LibratoMetrics.constructGraphs();
  // reapply our style settings if night mode is active
  if ($('body').hasClass('night')) { enableNightMode(); }
  // restart our refresh interval
  refreshId = setInterval(LibratoMetrics.refreshData, refreshInterval);
});

<commit_msg>Extract Tasseo object.<commit_after>
var Tasseo = {
  realMetrics: {}, // non-false targets
  graphs: {},      // rickshaw objects
  datum: {},       // metric data
  aliases: {},     // alias strings
  // minutes of data in the live feed
  period: (typeof period == 'undefined') ? 20 : period,

  //
  // gather our non-false targets
  gatherRealMetrics: function() {
    for (var metric in this.metrics) {
      if (this.metrics[metric].target === false) {
      } else {
        var name = this.metrics[metric].target + '-' + this.metrics[metric].source
        this.realMetrics[name] = this.metrics[metric];
        this.realMetrics[name]['selector'] = this.metrics[metric].target.replace(/[\.:]/g, '-');
      }
    }
  },
  // perform the actual graph object and
  // overlay name and number updates
  updateGraph: function(graph) {
    // update our graph
    this.graphs[graph].update();
    if (this.datum[graph][this.datum[graph].length - 1] !== undefined) {
      var lastValue = this.datum[graph][this.datum[graph].length - 1].y;
      var lastValueDisplay = Math.round(lastValue * 100) / 100;
      $('.overlay-name' + this.realMetrics[graph].selector).text(this.aliases[graph]);
      $('.overlay-number' + this.realMetrics[graph].selector).text(lastValueDisplay);
      if (this.realMetrics[graph].unit) {
        $('.overlay-number' + this.realMetrics[graph].selector).append('' + this.realMetrics[graph].unit + '');
      }
    } else {
      $('.overlay-name' + this.realMetrics[graph].selector).text(this.aliases[graph]);
      $('.overlay-number' + this.realMetrics[graph].selector).html('NF');
    }
  },

  // add our containers
  buildContainers: function() {
    var falseTargets = 0;
    for (var metric in this.metrics) {
      if (metrics[metric].target === false) {
        $('#main').append('

');
        falseTargets++;
      } else {
        $('#main').append(
          '
' +
          '

' +
          '

' +
          '
'
        );
      }
    }
  },
  // build our graph objects
  constructGraphs: function() {
    for (var metric in this.realMetrics) {
      var name = this.realMetrics[metric].target + '-' + this.realMetrics[metric].source
      var alias = this.realMetrics[metric].alias || this.realMetrics[metric].target;
      this.aliases[name] = alias;
      this.datum[name] = [{ x:0, y:0 }];
      this.graphs[name] = new Rickshaw.Graph({
        element: document.querySelector('.graph' + this.realMetrics[metric].selector),
        width: 348,
        height: 100,
        interpolation: 'step-after',
        series: [{
          name: this.aliases[name],
          color: '#afdab1',
          data: this.datum[name]
        }]
      });
      this.graphs[name].render();
    }
  },
  // refresh the graph
  refreshData: function(immediately) {
    for (var metric in this.realMetrics) {
      this.getData(metric, function(metric, values) {
        for (var i = 0; i < values.length; i++) {
          if (typeof values[i] !== "undefined") {
            this.datum[metric][i] = values[i];
          }
        }
        // check our thresholds and update color
        var lastValue = this.datum[metric][this.datum[metric].length - 1].y;
        var warning = this.realMetrics[metric].warning;
        var critical = this.realMetrics[metric].critical;
        if (critical > warning) {
          if (lastValue >= critical) {
            this.graphs[metric].series[0].color = '#d59295';
          } else if (lastValue >= warning) {
            this.graphs[metric].series[0].color = '#f5cb56';
          } else {
            this.graphs[metric].series[0].color = '#afdab1';
          }
        } else {
          if (lastValue <= critical) {
            this.graphs[metric].series[0].color = '#d59295';
          } else if (lastValue <= warning) {
            this.graphs[metric].series[0].color = '#f5cb56';
          } else {
            this.graphs[metric].series[0].color = '#afdab1';
          }
        }
        // we want to render immediately, i.e.
        // as soon as ajax completes
        // used for time period / pause view
        if (immediately) this.updateGraph(metric);
      });
      values = null;
    }

    // we can wait until all data is gathered, i.e.
    // the live refresh should happen synchronously
    if (!immediately) {
      for (var graph in this.graphs) {
        this.updateGraph(graph);
      }
    }
  },

};

var LibratoMetrics = $.extend({
  url: 'https://metrics-api.librato.com/v1/metrics',
  // construct url
  constructUrl: function(metric) {
    var source = this.realMetrics[metric].source;
    var target = this.realMetrics[metric].target;
    var now = new Date();
    var offset = now.getTimezoneOffset();
    now = parseInt((now.getTime() + offset * 60) / 1000);
    var start = now - (this.period * 60);
    var end = now;
    return this.url + '/' + encodeURI(target) + '?source=' + source + '&resolution=1&start_time=' + start + '&end_time=' + end;
  },

  displayTransform: function(value, period, transform) {
    if (transform !== undefined && transform !== null && transform.length > 0) {
      var p = period, x = value;
      return eval(transform);
    } else {
      return value;
    }
  },

  // retrieve the data from Graphite
  getData: function(metric, callback) {
    $.ajax({
      beforeSend: function(xhr) {
        if (auth.length > 0) {
          var bytes = Crypto.charenc.Binary.stringToBytes(auth);
          var base64 = Crypto.util.bytesToBase64(bytes);
          xhr.setRequestHeader("Authorization", "Basic " + base64);
        }
      },
      dataType: 'json',
      error: function(xhr, textStatus, errorThrown) { console.log(errorThrown); },
      url: this.constructUrl(metric),
      cache: false
    }).done(function(d) {
      LibratoMetrics.done(metric, callback, d);
    });
  },

  done: function(metric, callback, d) {
    var myDatum = [];
    var source = this.realMetrics[metric].source;
    var transform = d.attributes.display_transform;
    var period = d.period;
    if (d.measurements[source] !== undefined && d.measurements[source].length > 0) {
      myDatum[0] = {
        x: d.measurements[source][0].measure_time,
        y: this.displayTransform(d.measurements[source][0].value, this.period, transform) || 0
      };
      for (var j = 1; j < d.measurements[source].length; j++) {
        myDatum[j] = {
          x: d.measurements[source][j].measure_time,
          y: this.displayTransform(d.measurements[source][j].value, this.period, transform) || graphs[metric].lastKnownValue
        };
        if (typeof d.measurements[source][0].value === "number") {
          this.graphs[metric].lastKnownValue = d.measurements[source][0].value;
        }
      }
      callback.call(LibratoMetrics, metric, myDatum);
    }

  },

  initialize: function() {
    this.metrics = metrics;
    // filter out false targets
    this.gatherRealMetrics();

    // build our div containers
    this.buildContainers();

    // build our graph objects
    this.constructGraphs();
    // initial load screen
    for (var graph in this.graphs) {
      if (this.realMetrics[graph].target === false) {
        //continue;
      } else if (myTheme === "dark") {
        $('.overlay-number' + this.realMetrics[graph].selector).html('');
      } else {
        $('.overlay-number' + this.realMetrics[graph].selector).html('');
      }
    }
  }
}, Tasseo);

LibratoMetrics.initialize();

// set our last known value at invocation
Rickshaw.Graph.prototype.lastKnownValue = 0;

// set our theme
var myTheme = (typeof theme == 'undefined') ? 'default' : theme;
if (myTheme === "dark") { enableNightMode(); }

// hide our toolbar if necessary
var toolbar = (typeof toolbar == 'undefined') ? true : toolbar;
if (!toolbar) { $('div#toolbar').css('display', 'none'); }

LibratoMetrics.refreshData("now");

// define our refresh and start interval
function refreshData() {
  LibratoMetrics.refreshData();
}

var refreshInterval = (typeof refresh == 'undefined') ? 20000 : refresh;
var refreshId = setInterval(refreshData, refreshInterval);

// set our "live" interval hint
$('#toolbar ul li.timepanel a.play').text(LibratoMetrics.period + 'min');

// activate night mode
function enableNightMode() {
  $('body').addClass('night');
  $('div#title h1').addClass('night');
  $('div#graph svg').css('opacity', '0.8');
  $('div#overlay-name').addClass('night');
  $('div#overlay-number').addClass('night');
  $('div#toolbar ul li.timepanel').addClass('night');
}

// deactivate night mode
function disableNightMode() {
  $('body').removeClass('night');
  $('div#title h1').removeClass('night');
  $('div#graph svg').css('opacity', '1.0');
  $('div#overlay-name').removeClass('night');
  $('div#overlay-number').removeClass('night');
  $('div#toolbar ul li.timepanel').removeClass('night');
}

// activate night mode by click
$('li.toggle-night a').click(function() {
  if ($('body').hasClass('night')) {
    disableNightMode();
  } else {
    enableNightMode();
  }
});

// toggle number display
$('li.toggle-nonum a').click(function() { $('div#overlay-number').toggleClass('nonum'); });

// time panel, pause live feed and show range
$('#toolbar ul li.timepanel a.range').click(function() {
  period = $(this).attr("title");
  LibratoMetrics.refreshData("now")
  if (! $('#toolbar ul li.timepanel a.play').hasClass('pause')) {
    $('#toolbar ul li.timepanel a.play').addClass('pause');
  }
  $('#toolbar ul li.timepanel a.play').text('paused');
  $(this).parent('li').parent('ul').find('li').removeClass('selected');
  $(this).parent('li').addClass('selected');
  clearInterval(refreshId);
});

// time panel, resume live feed
$('#toolbar ul li.timepanel a.play').click(function() {
  period = 20;
  $(this).parent('li').parent('ul').find('li').removeClass('selected');
  $(this).parent('li').addClass('selected');
  $(this).removeClass('pause');
  $('#toolbar ul li.timepanel a.play').text(period + 'min');
  LibratoMetrics.refreshData("now");
  // explicitly clear the old Interval in case
  // someone "doubles up" on the live play button
  clearInterval(refreshId);
  // remove and recreate the original graphs[]
  // helps clear out any rendering artifacts
  $('#graph svg').remove();
  LibratoMetrics.constructGraphs();
  // reapply our style settings if night mode is active
  if ($('body').hasClass('night')) { enableNightMode(); }
  // restart our refresh interval
  refreshId = setInterval(LibratoMetrics.refreshData, refreshInterval);
});

<|endoftext|>


<commit_before>/*
**Date** 2017-03-22 18:08
**File** jquery.dropdown.js
**Version** v2.1
**Desc** The jquery plugin for dropdown widget.
**License** BSD

#Usage
   $('selector').wfdropdown(Options);

# Options
**item** The jquery selector to find the item. Once the item was clicked, the onclick action will be fired; Default is "a.item";

**onclick** The function to handle the item clicking; Default is jQuery.fn.wfdropdown.onclick;

**value** The jQuery selector to find the input. Default is "input:first";

# Basic Example

      <input type="hidden" name="field-name" value="default-value"/>
      <button type="button" data-toggle="dropdown">Label</button>

Opt1

Opt3

# AJAX Example

      <input type="hidden" name="field-name" value="default-value"/>
      <button type="button" data-toggle="dropdown">Label</button>

   [
      {"id":"05574364-e97d-4b39-87e5-f3c6428a41e0", "name":"Opt1"},
      {"id":"aef1d4ca-5bda-42d1-8b52-64e2575e9d0e", "name":"Opt2"},
      {"id":"30dcac3c-dc5e-4bf5-a1a2-ea5bf3f46e57", "name":"Opt3"},
   ]

   {
      "result": [
         {"id":"05574364-e97d-4b39-87e5-f3c6428a41e0", "name":"Opt1"},
         {"id":"aef1d4ca-5bda-42d1-8b52-64e2575e9d0e", "name":"Opt2"},
         {"id":"30dcac3c-dc5e-4bf5-a1a2-ea5bf3f46e57", "name":"Opt3"},
      ],
   }

*/

;(function($) {
   $.extend($, {wfdropdown:{
      onclick: function( evt ){
         var element=$(this).parents('.wfdropdown:first');
         var value=null;
         if(typeof($(this).attr('val'))=='undefined')
            value=$(this).text();
         else
            value=$(this).attr('val');
         $(element)
            .find('button:first').empty().text($(this).text()).end()
            .find('input:first').val(value).end()
            .trigger('change')
         ;
     },
     success: function( data ){
        var result=('result' in data)?data.result:data;
        var menu=$(this).find('.dropdown-menu');
        $(menu).find('.dropdown-item').remove();
        for(var i=0; i<result.length; i++){
           var entry=result[i];
           var item=$('<'+$(this).attr('wfelement')+'/>')
              .addClass('dropdown-item')
              .appendTo(menu)
              .attr('name', $(entry).attr($(this).attr('wfname')))
              .attr('val', $(entry).attr($(this).attr('wfid')))
           ;
           $.wfdropdown.populate(item);
        }
        if(!$(this).find('input').hasClass('required')){
           var item=$('<'+$(this).attr('wfelement')+'/>')
              .addClass('dropdown-item')
              .prependTo(menu)
              .attr('name', $(this).attr('wfPlsSelect'))
              .attr('val', '')
           ;
           $.wfdropdown.populate(item);
        }
        var selected=$(this).find('input:first').attr('value');
        var label=$(this).find('.dropdown-item[val="'+selected+'"]:first').text();
        $(this).find('button').text(label);
        $(this).trigger('ready');
     },
     populate: function( item ){
        var name=$(item).attr('name');
        var val=$(item).attr('val');
        $(item).empty().append($('').text(name).attr({'href':'#','val':val}).addClass('dropdown-item').click($.wfdropdown.onclick));
     },
   }});

   // jQuery plugin definition
   $.fn.wfdropdown = function(params) {
     // merge default and user parameters
     params = $.extend({'items':'a.dropdown-item','value':'input:first','onclick':jQuery.wfdropdown.onclick,'success':jQuery.wfdropdown.success,'element':'li','name':'name','id':'id','ajax':null}, params);
     if($(this).length<1){
        console.log('No element found for dropdown.');
        return this;
     }

     $(this).addClass('wfdropdown');
     //If ajax
     if(params.ajax!=null){
       params.ajax.success=params.success; //Overwrite the success function
       params.ajax.context=this;
       $(this).attr({'wfelement':params.element, 'wfname':params.name, 'wfid':params.id, 'wfPlsSelect':$(this).text()});
       $.ajax(params.ajax);
       return this;
     }

     $(this).find('.dropdown-item').each(function(){ $.wfdropdown.populate( this ); });
     return this;
   };
})(jQuery);
<commit_msg>[bootstrap4 052a2cb]: Add the event of change event of dropdown<commit_after>/*
**Date** 2017-03-22 18:08
**File** jquery.dropdown.js
**Version** v2.1
**Desc** The jquery plugin for dropdown widget.
**License** BSD

#Usage
   $('selector').wfdropdown(Options);

# Options
**item** The jquery selector to find the item. Once the item was clicked, the onclick action will be fired; Default is "a.item";

**onclick** The function to handle the item clicking; Default is jQuery.fn.wfdropdown.onclick;

**value** The jQuery selector to find the input. Default is "input:first";

# Basic Example

      <input type="hidden" name="field-name" value="default-value"/>
      <button type="button" data-toggle="dropdown">Label</button>

Opt1

Opt3

# AJAX Example

      <input type="hidden" name="field-name" value="default-value"/>
      <button type="button" data-toggle="dropdown">Label</button>

   [
      {"id":"05574364-e97d-4b39-87e5-f3c6428a41e0", "name":"Opt1"},
      {"id":"aef1d4ca-5bda-42d1-8b52-64e2575e9d0e", "name":"Opt2"},
      {"id":"30dcac3c-dc5e-4bf5-a1a2-ea5bf3f46e57", "name":"Opt3"},
   ]

   {
      "result": [
         {"id":"05574364-e97d-4b39-87e5-f3c6428a41e0", "name":"Opt1"},
         {"id":"aef1d4ca-5bda-42d1-8b52-64e2575e9d0e", "name":"Opt2"},
         {"id":"30dcac3c-dc5e-4bf5-a1a2-ea5bf3f46e57", "name":"Opt3"},
      ],
   }

*/

;(function($) {
   $.extend($, {wfdropdown:{
      onclick: function( evt ){
         var element=$(this).parents('.wfdropdown:first');
         var value=null;
         var lastVal=$(element).find('input:first').val();
         if(typeof($(this).attr('val'))=='undefined')
            value=$(this).text();
         else
            value=$(this).attr('val');
         $(element)
            .find('button:first').empty().text($(this).text()).end()
            .find('input:first').val(value).end()
            .trigger('change', {'from': lastVal, 'to':value})
         ;
     },
     success: function( data ){
        var result=('result' in data)?data.result:data;
        var menu=$(this).find('.dropdown-menu');
        $(menu).find('.dropdown-item').remove();
        for(var i=0; i<result.length; i++){
           var entry=result[i];
           var item=$('<'+$(this).attr('wfelement')+'/>')
              .addClass('dropdown-item')
              .appendTo(menu)
              .attr('name', $(entry).attr($(this).attr('wfname')))
              .attr('val', $(entry).attr($(this).attr('wfid')))
           ;
           $.wfdropdown.populate(item);
        }
        if(!$(this).find('input').hasClass('required')){
           var item=$('<'+$(this).attr('wfelement')+'/>')
              .addClass('dropdown-item')
              .prependTo(menu)
              .attr('name', $(this).attr('wfPlsSelect'))
              .attr('val', '')
           ;
           $.wfdropdown.populate(item);
        }
        var selected=$(this).find('input:first').attr('value');
        var label=$(this).find('.dropdown-item[val="'+selected+'"]:first').text();
        $(this).find('button').text(label);
        $(this).trigger('ready');
     },
     populate: function( item ){
        var name=$(item).attr('name');
        var val=$(item).attr('val');
        $(item).empty().append($('').text(name).attr({'href':'#','val':val}).addClass('dropdown-item').click($.wfdropdown.onclick));
     },
   }});

   // jQuery plugin definition
   $.fn.wfdropdown = function(params) {
     // merge default and user parameters
     params = $.extend({'items':'a.dropdown-item','value':'input:first','onclick':jQuery.wfdropdown.onclick,'success':jQuery.wfdropdown.success,'element':'li','name':'name','id':'id','ajax':null}, params);
     if($(this).length<1){
        console.log('No element found for dropdown.');
        return this;
     }

     $(this).addClass('wfdropdown');
     //If ajax
     if(params.ajax!=null){
       params.ajax.success=params.success; //Overwrite the success function
       params.ajax.context=this;
       $(this).attr({'wfelement':params.element, 'wfname':params.name, 'wfid':params.id, 'wfPlsSelect':$(this).text()});
       $.ajax(params.ajax);
       return this;
     }

     $(this).find('.dropdown-item').each(function(){ $.wfdropdown.populate( this ); });
     return this;
   };
})(jQuery);
<|endoftext|>


<commit_before>(function () {

var $specContainer = $('#spec-container');

if (!isMobile) {
    $('.section-tabs a').click(function () {
        var href = $(this).attr('href');
        gotoTab(href);
        return false;
    });

    $specContainer.scrollspy({
            'data-spy': 'scroll',
            'data-target': '.section-tabs',
            'offset': 100
        })
        .on('activate.changehash', function () {
            var target = $('.section-tabs li.active a').attr('href');
            selectTab(target);
        });

    function gotoTab(target) {
        selectTab(target);

        var $elem = $(target);

        $specContainer.animate({
            scrollTop: $specContainer.scrollTop() + $elem.position().top
        }, 300);
    }

    function selectTab(target) {
        var $list = $('.section-tabs li');
        $list.removeClass('active');
        $list.children('[href="'+target+'"]').parent('li').addClass('active');

        if (location.hash != target) {
            if (history.pushState) {
                history.pushState({}, null, target);
            } else {
                location.hash = target;
            }
        }
    }
}

}());
<commit_msg>Fix scrollspy bug occured by layout changes<commit_after>(function () {

var $body = $('body');

if (!isMobile) {
    $('.section-tabs a').click(function () {
        var href = $(this).attr('href');
        gotoTab(href);
        return false;
    });

    $body.scrollspy({
            'data-spy': 'scroll',
            'data-target': '.section-tabs',
            'offset': 100
        })
        .on('activate.changehash', function () {
            var target = $('.section-tabs li.active a').attr('href');
            selectTab(target);
        });

    function gotoTab(target) {
        selectTab(target);

        var $elem = $(target);

        $body.animate({
            scrollTop: $elem.offset().top
        }, 300);
    }

    function selectTab(target) {
        var $list = $('.section-tabs li');
        $list.removeClass('active');
        $list.children('[href="'+target+'"]').parent('li').addClass('active');

        if (location.hash != target) {
            if (history.pushState) {
                history.pushState({}, null, target);
            } else {
                location.hash = target;
            }
        }
    }
}

}());
<|endoftext|>


<commit_before>(function() {

ravadaApp.directive("solShowMachine", swMach)
        .directive("solShowNewmachine", swNewMach)
        .controller("new_machine", newMachineCtrl)
        .controller("machinesPage", machinesPageC)
        .controller("usersPage", usersPageC)
        .controller("messagesPage", messagesPageC)

  function swMach() {
    return {
      restrict: "E",
      templateUrl: '/ng-templates/admin_machine.html',
    };
  };

  function swNewMach() {
      return {
          restrict: "E",
          templateUrl: '/ng-templates/new_machine.html',
      };
  };

  function newMachineCtrl($scope, $http) {

    $http.get('/list_vm_types.json').then(function(response) {
            $scope.backends = response.data;
            $scope.backend = response.data[0];
            $scope.loadTemplates();
    });
      $scope.loadTemplates = function() {
        $http.get('/list_images.json',{
          params: {
            backend: $scope.backend
          }
        }).then(function(response) {
                $scope.images = response.data;
        });
      }
      $http.get('/iso_file.json').then(function(response) {
              $scope.isos = response.data;
      });

      $http.get('/list_lxc_templates.json').then(function(response) {
              $scope.templates_lxc = response.data;
      });
      $scope.iso_download=function(id_iso) {
            $http.get('/iso/download/'+id_iso+'.json').then(function() {
                window.location.href = '/admin/machines';
            });
      };
      $scope.name_duplicated = false;

      $scope.ddsize=20;
      $scope.swapsize={value:1};
      $scope.ramSize=1;
      $scope.seeswap=0;

      $scope.showMinSize = false;
      $scope.min_size = 15;
      $scope.change_iso = function(id) {
          if (id.min_disk_size != null) {
            $scope.min_size = id.min_disk_size;
            $scope.showMinSize = true;
          }
          else {
            $scope.showMinSize = false;
            $scope.min_size = 1;
          }
          if (id.device != null) {
             return id.device;
          }
          else return "<NONE>";
      };

      $scope.validate_new_name = function() {
          $http.get('/machine/exists/'+$scope.name)
                .then(duplicated_callback, unique_callback);
            function duplicated_callback(response) {
                if ( response.data ) {
                    $scope.name_duplicated=true;
                } else {
                    $scope.name_duplicated=false;
                }
            };
            function unique_callback() {
                $scope.name_duplicated=false;
            }
      };

      $scope.type = function(v) {
        return typeof(v);
      }
      $scope.show_swap = function() {
        $scope.seeswap = !($scope.seeswap);
      };

      $http.get('/list_machines.json').then(function(response) {
              $scope.base = response.data;
      });
  };

  function machinesPageC($scope, $http, $interval, request, listMach) {
    $http.get('/pingbackend.json').then(function(response) {
      $scope.pingbe_fail = !response.data;
    });
    $scope.getMachines = function() {
        if( $scope.check_netdata && $scope.check_netdata != "0" ) {
            var url = $scope.check_netdata;
            $scope.check_netdata = 0;
            $http.get(url+"?"+Date()).then(function(response) {
                if (response.status == 200 || response.status == 400 ) {
                    $scope.monitoring=1;
                    $http.get("/session/monitoring/1").then(function(response) {
                        window.location.reload();
                    });
                } else {
                    $scope.monitoring=0;
                    $http.get("/session/monitoring/0");
                }
            }, function(response) {
                $scope.monitoring=0;
                $http.get("/session/monitoring/0");
            });
      }
      if(!$scope.modalOpened){
        if ($scope.list_machines_busy) {
            return ;
        }
        $scope.list_machines_busy = true;
        $http.get("/requests.json").then(function(response) {
          $scope.requests=response.data;
          $scope.download_done=false;
          $scope.download_working =false;
          for (var i = 0; i < $scope.requests.length; i++){
              if ( $scope.requests[i].command == 'download') {
                  if ($scope.requests[i].status == 'done') {
                      $scope.download_done=true;
                  } else {
                      $scope.download_working=true;
                  }
              }
          }
        });
        $http.get("/list_machines.json").then(function(response) {
          $scope.list_machines_busy = false;
          $scope.list_machines = [];
          var mach;
          for (var i=0, iLength = response.data.length; i<iLength; i++){
            mach = response.data[i];
            if (!mach.id_base){
              $scope.list_machines[mach.id] = mach;
              $scope.list_machines[mach.id].childs = [];
            }
          }
          var n_clones = 0;
          for (var i=0, iLength = response.data.length; i<iLength; i++){
            mach = response.data[i];
            if (mach.id_base){
              $scope.list_machines[mach.id_base].childs.push(mach);
              n_clones++;
            }
          }
          for (var i = $scope.list_machines.length-1; i >= 0; i--){
            if (!$scope.list_machines[i]){
              $scope.list_machines.splice(i,1);
            }
          }
          $scope.hide_clones = 0;
          if (n_clones > $scope.n_clones_hide ) {
            $scope.hide_clones = 1;
          }
        }
          ,function (error){;
              $scope.list_machines_busy = false;
          }
        );
      }
    };
    $scope.orderParam = ['name'];
    $scope.orderMachineList = function(type1,type2){
      if ($scope.orderParam[0] === '-'+type1)
        $scope.orderParam = ['none'];
      else if ($scope.orderParam[0] === type1 )
        $scope.orderParam = ['-'+type1,type2];
      else $scope.orderParam = [type1,'-'+type2];
    }
    $scope.hide_clones = true;
    $scope.hideClones = function(){
      $scope.hide_clones = !$scope.hide_clones;
    }
    $scope.action = function(target,action,machineId){
      $http.get('/'+target+'/'+action+'/'+machineId+'.json')
        .then(function() {
            $scope.getMachines();
        });
    };
    $scope.set_autostart= function(machineId, value) {
      $http.get("/machine/autostart/"+machineId+"/"+value);
    };
    $scope.set_public = function(machineId, value) {
      if (value) value=1;
      else value = 0;
      $http.get("/machine/public/"+machineId+"/"+value);
    };

    $scope.can_remove_base = function(machine) {
        return machine.is_base > 0 && machine.has_clones == 0 && machine.is_locked ==0;
    };
    $scope.can_prepare_base = function(machine) {
        return machine.is_base == 0 && machine.is_locked ==0;
    };

    $scope.list_images=function() {
        $http.get('/list_images.json').then(function(response) {
              $scope.images = response.data;
        });
    };
    $scope.open_modal=function(prefix,machine){
      $scope.modalOpened=true;
      $('#'+prefix+machine.id).modal({show:true})
    }
    $scope.cancel_modal=function(){
      $scope.modalOpened=false;
    }
    $scope.refresh_machines=function() {
      $scope.getMachines();
    }

    //On load code
    $scope.modalOpened=false;
    $scope.rename= {new_name: 'new_name'};
    $scope.show_rename = false;
    $scope.new_name_duplicated=false;
    $scope.getMachines();
    $interval($scope.getMachines,3000);
  };

  function usersPageC($scope, $http, $interval, request) {
    $http.get('/pingbackend.json').then(function(response) {
      $scope.pingbe_fail = !response.data;
    });
    $scope.action = function(target,action,machineId){
      $http.get('/'+target+'/'+action+'/'+machineId+'.json');
    };
    //On load code
  };

  function messagesPageC($scope, $http, $interval, request) {
    $http.get('/pingbackend.json').then(function(response) {
      $scope.pingbe_fail = !response.data;
    });
    $scope.getMessages = function() {
      $http.get('/messages.json').then(function(response) {
        $scope.list_message= response.data;
      });
    }
    $scope.updateMessages = function() {
      $http.get('/messages.json').then(function(response) {
        for (var i=0, iLength = response.data.length; i<iLength; i++){
          if (response.data[0].id != $scope.list_message[i].id){
            $scope.list_message.splice(i,0,response.data.shift());
          }
          else{break;}
        }
      });
    }
    $scope.asRead = function(messId){
        var toGet = '/messages/read/'+messId+'.json';
        $http.get(toGet);
    };
    $scope.asUnread = function(messId){
        var toGet = '/messages/unread/'+messId+'.json';
        $http.get(toGet);
    };
    //On load code
    $scope.getMessages();
    $scope.updatePromise = $interval($scope.updateMessages,3000);
  };

}());
<commit_msg>refactor(frontend): enforce hide clones<commit_after>(function() {

ravadaApp.directive("solShowMachine", swMach)
        .directive("solShowNewmachine", swNewMach)
        .controller("new_machine", newMachineCtrl)
        .controller("machinesPage", machinesPageC)
        .controller("usersPage", usersPageC)
        .controller("messagesPage", messagesPageC)

  function swMach() {
    return {
      restrict: "E",
      templateUrl: '/ng-templates/admin_machine.html',
    };
  };

  function swNewMach() {
      return {
          restrict: "E",
          templateUrl: '/ng-templates/new_machine.html',
      };
  };

  function newMachineCtrl($scope, $http) {

    $http.get('/list_vm_types.json').then(function(response) {
            $scope.backends = response.data;
            $scope.backend = response.data[0];
            $scope.loadTemplates();
    });
      $scope.loadTemplates = function() {
        $http.get('/list_images.json',{
          params: {
            backend: $scope.backend
          }
        }).then(function(response) {
                $scope.images = response.data;
        });
      }
      $http.get('/iso_file.json').then(function(response) {
              $scope.isos = response.data;
      });

      $http.get('/list_lxc_templates.json').then(function(response) {
              $scope.templates_lxc = response.data;
      });
      $scope.iso_download=function(id_iso) {
            $http.get('/iso/download/'+id_iso+'.json').then(function() {
                window.location.href = '/admin/machines';
            });
      };
      $scope.name_duplicated = false;

      $scope.ddsize=20;
      $scope.swapsize={value:1};
      $scope.ramSize=1;
      $scope.seeswap=0;

      $scope.showMinSize = false;
      $scope.min_size = 15;
      $scope.change_iso = function(id) {
          if (id.min_disk_size != null) {
            $scope.min_size = id.min_disk_size;
            $scope.showMinSize = true;
          }
          else {
            $scope.showMinSize = false;
            $scope.min_size = 1;
          }
          if (id.device != null) {
             return id.device;
          }
          else return "<NONE>";
      };

      $scope.validate_new_name = function() {
          $http.get('/machine/exists/'+$scope.name)
                .then(duplicated_callback, unique_callback);
            function duplicated_callback(response) {
                if ( response.data ) {
                    $scope.name_duplicated=true;
                } else {
                    $scope.name_duplicated=false;
                }
            };
            function unique_callback() {
                $scope.name_duplicated=false;
            }
      };

      $scope.type = function(v) {
        return typeof(v);
      }
      $scope.show_swap = function() {
        $scope.seeswap = !($scope.seeswap);
      };

      $http.get('/list_machines.json').then(function(response) {
              $scope.base = response.data;
      });
  };

  function machinesPageC($scope, $http, $interval, request, listMach) {
    $http.get('/pingbackend.json').then(function(response) {
      $scope.pingbe_fail = !response.data;
    });
    $scope.getMachines = function() {
        if( $scope.check_netdata && $scope.check_netdata != "0" ) {
            var url = $scope.check_netdata;
            $scope.check_netdata = 0;
            $http.get(url+"?"+Date()).then(function(response) {
                if (response.status == 200 || response.status == 400 ) {
                    $scope.monitoring=1;
                    $http.get("/session/monitoring/1").then(function(response) {
                        window.location.reload();
                    });
                } else {
                    $scope.monitoring=0;
                    $http.get("/session/monitoring/0");
                }
            }, function(response) {
                $scope.monitoring=0;
                $http.get("/session/monitoring/0");
            });
      }
      if(!$scope.modalOpened){
        if ($scope.list_machines_busy) {
            return ;
        }
        $scope.list_machines_busy = true;
        $http.get("/requests.json").then(function(response) {
          $scope.requests=response.data;
          $scope.download_done=false;
          $scope.download_working =false;
          for (var i = 0; i < $scope.requests.length; i++){
              if ( $scope.requests[i].command == 'download') {
                  if ($scope.requests[i].status == 'done') {
                      $scope.download_done=true;
                  } else {
                      $scope.download_working=true;
                  }
              }
          }
        });
        $http.get("/list_machines.json").then(function(response) {
          $scope.list_machines_busy = false;
          $scope.list_machines = [];
          var mach;
          for (var i=0, iLength = response.data.length; i<iLength; i++){
            mach = response.data[i];
            if (!mach.id_base){
              $scope.list_machines[mach.id] = mach;
              $scope.list_machines[mach.id].childs = [];
            }
          }
          $scope.n_clones = 0;
          for (var i=0, iLength = response.data.length; i<iLength; i++){
            mach = response.data[i];
            if (mach.id_base){
              $scope.list_machines[mach.id_base].childs.push(mach);
              $scope.n_clones++;
            }
          }
          for (var i = $scope.list_machines.length-1; i >= 0; i--){
            if (!$scope.list_machines[i]){
              $scope.list_machines.splice(i,1);
            }
          }
          if ($scope.auto_hide_clones) {
            $scope.hide_clones = 0;
            if ($scope.n_clones > $scope.n_clones_hide ) {
                $scope.hide_clones = 1;
            }
          }
        }
          ,function (error){;
              $scope.list_machines_busy = false;
          }
        );
      }
    };
    $scope.orderParam = ['name'];
    $scope.auto_hide_clones = true;
    $scope.orderMachineList = function(type1,type2){
      if ($scope.orderParam[0] === '-'+type1)
        $scope.orderParam = ['none'];
      else if ($scope.orderParam[0] === type1 )
        $scope.orderParam = ['-'+type1,type2];
      else $scope.orderParam = [type1,'-'+type2];
    }
    $scope.hide_clones = true;
    $scope.hideClones = function(){
      $scope.hide_clones = !$scope.hide_clones;
      $scope.auto_hide_clones = false;
    }
    $scope.action = function(target,action,machineId){
      $http.get('/'+target+'/'+action+'/'+machineId+'.json')
        .then(function() {
            $scope.getMachines();
        });
    };
    $scope.set_autostart= function(machineId, value) {
      $http.get("/machine/autostart/"+machineId+"/"+value);
    };
    $scope.set_public = function(machineId, value) {
      if (value) value=1;
      else value = 0;
      $http.get("/machine/public/"+machineId+"/"+value);
    };

    $scope.can_remove_base = function(machine) {
        return machine.is_base > 0 && machine.has_clones == 0 && machine.is_locked ==0;
    };
    $scope.can_prepare_base = function(machine) {
        return machine.is_base == 0 && machine.is_locked ==0;
    };

    $scope.list_images=function() {
        $http.get('/list_images.json').then(function(response) {
              $scope.images = response.data;
        });
    };
    $scope.open_modal=function(prefix,machine){
      $scope.modalOpened=true;
      $('#'+prefix+machine.id).modal({show:true})
    }
    $scope.cancel_modal=function(){
      $scope.modalOpened=false;
    }
    $scope.refresh_machines=function() {
      $scope.getMachines();
    }

    //On load code
    $scope.modalOpened=false;
    $scope.rename= {new_name: 'new_name'};
    $scope.show_rename = false;
    $scope.new_name_duplicated=false;
    $scope.getMachines();
    $interval($scope.getMachines,3000);
  };

  function usersPageC($scope, $http, $interval, request) {
    $http.get('/pingbackend.json').then(function(response) {
      $scope.pingbe_fail = !response.data;
    });
    $scope.action = function(target,action,machineId){
      $http.get('/'+target+'/'+action+'/'+machineId+'.json');
    };
    //On load code
  };

  function messagesPageC($scope, $http, $interval, request) {
    $http.get('/pingbackend.json').then(function(response) {
      $scope.pingbe_fail = !response.data;
    });
    $scope.getMessages = function() {
      $http.get('/messages.json').then(function(response) {
        $scope.list_message= response.data;
      });
    }
    $scope.updateMessages = function() {
      $http.get('/messages.json').then(function(response) {
        for (var i=0, iLength = response.data.length; i<iLength; i++){
          if (response.data[0].id != $scope.list_message[i].id){
            $scope.list_message.splice(i,0,response.data.shift());
          }
          else{break;}
        }
      });
    }
    $scope.asRead = function(messId){
        var toGet = '/messages/read/'+messId+'.json';
        $http.get(toGet);
    };
    $scope.asUnread = function(messId){
        var toGet = '/messages/unread/'+messId+'.json';
        $http.get(toGet);
    };
    //On load code
    $scope.getMessages();
    $scope.updatePromise = $interval($scope.updateMessages,3000);
  };

}());
<|endoftext|>


<commit_before>var search_words = [];
if ((window.location['pathname'] === '/') || ((window.location['pathname'] === '/results') && (window.location['search'] === ''))) {
    $.ajax({url:'/api/result?desc=true'}).done(function(data){
                if (window.matchMedia("(min-width: 768px)").matches) {
                    resultsDesktop(data);
                    if (window.location['pathname'] === '/') {
                        updatePlaceholder("#homesearch");
                    }
                    else {
                        updatePlaceholder("input");
                    }
                }

                else {
                    resultsMobile(data);
                    if (window.location['pathname'] === '/') {
                        updatePlaceholder("#homesearch");
                    }
                    else {
                        updatePlaceholder("input");
                    }

                }
    });

    function resultsDesktop(data) {
        $(".swiper-container").remove();
        var container = $("
");
        container.addClass("container");
        var row = $("
");
        row.addClass("row products");
        container.append(row);
        $(".numbers").append(container);
        var total = 0;
        for (i=0; i<data.length;i++) {
            if (data[i]['info']) {
                var location = "/results?name=" + encodeURIComponent(data[i]['info']['name']) + "&showBig=true&back=" + encodeURIComponent(window.location['pathname']);
                var col = $("
");
                col.addClass("col-xs-12 col-sm-6 col-md-4 col-lg-3 div-product last-product");
                var product = $("
", {"data-location": location });
                product.attr("id", "product-" + i);
                product.addClass("product");
                var brand = $("
");
                brand.addClass("brand");
                var name = $("
");
                name.addClass("name");
                var labels = $("
");
                var oneLabel = false;
                if (data[i]['info']['labelGlutenFree'] === 'yes') {
                    oneLabel = true;
                    var iconGlutenFree = $("");
                    iconGlutenFree.attr("src", "/static/img/green-gluten.svg");
                    labels.text(" Sin gluten");
                    labels.prepend(iconGlutenFree);
                    labels.addClass("gluten-free");
                    col.addClass("gluten-free ");
                    labels.addClass("classification-label");
                }

                if (data[i]['info']['ingredientsWheat'] === 'yes') {
                    oneLabel = true;
                    var iconWheat = $("");
                    iconWheat.attr("src", "/static/img/red-gluten.svg");
                    labels.text(" Trigo o trazas");
                    labels.prepend(iconWheat);
                    labels.addClass("wheat");
                    col.addClass("wheat");
                    labels.addClass("classification-label");
                }

                if (!oneLabel) {
                    labels.html("
");
                }

                product.append(brand);
                product.append(name);
                product.append(labels);

                var divImg = $("
");
                divImg.addClass("img-vertical-centered img-vertical-home-centered");
                var productImg = $("");
                productImg.attr("src", data[i]['info']['productImg']);
                productImg.addClass("img img-home img-responsive");
                divImg.append(productImg);

                name.text(data[i]['info']['name']);
                product.append(divImg);
                product.on('click', function(){
                    window.location.href = $(this).data('location');
                });
                col.append(product);
                if (oneLabel) {
                    total += 1;
                    $(".row.products").append(col);
                    //search_words.push(data[i]['info']['brand']);
                    search_words.push(getWords(data[i]['info']['name']));
                }
                if (total === 4) {
                    break;
                }
            }
        }
    }

    function resultsMobile(data) {
        for(i=0;i<data.length;i++) {
            if (data[i]['info']) {
                var location = "/results?name=" + encodeURIComponent(data[i]['info']['name']) + "&showBig=true&back=" + encodeURIComponent(window.location['pathname']);
                var slide = $("
", {"data-location": location });
                var a = $("");
                var col = $("
");
                col.addClass("div-product last-product");
                var col2 = $("
");
                col2.addClass("col-xs-6 col-sm-6 col-md-4 col-lg-3 div-product");
                var brand = $("
");
                brand.addClass("brand");
                var name = $("
");
                name.addClass("name");
                var labels = $("
");
                var oneLabel = false;
                if (data[i]['info']['labelGlutenFree'] === 'yes') {
                    oneLabel = true;
                    var iconGlutenFree = $("");
                    iconGlutenFree.attr("src", "/static/img/green-gluten.svg");
                    labels.text(" Sin gluten");
                    labels.prepend(iconGlutenFree);
                    labels.addClass("gluten-free");
                    col.addClass("gluten-free ");
                    labels.addClass("classification-label");
                }

                if (data[i]['info']['ingredientsWheat'] === 'yes') {
                    oneLabel = true;
                    var iconWheat = $("");
                    iconWheat.attr("src", "/static/img/red-gluten.svg");
                    labels.text(" Trigo o trazas");
                    labels.prepend(iconWheat);
                    labels.addClass("wheat");
                    col.addClass("wheat");
                    labels.addClass("classification-label");
                }

                if (!oneLabel) {
                    labels.html("
");
                }

                name.text(data[i]['info']['name']);
                if (data[i]['info']['brand']) {
                    brand.text(data[i]['info']['brand']);
                }
                else {
                    brand.html("
");
                }

                col2.append(brand);
                col2.append(name);
                col2.append(labels);

                var productImg = $("");
                productImg.attr("src", data[i]['info']['productImg']);
                productImg.addClass("img");
                col.append(productImg);

                slide.addClass("swiper-slide");
                slide.append(col);
                slide.append(col2);
                slide.attr("id", "product-" + data[i]['id']);
                slide.on('click', function(){
                    window.location.href = $(this).data('location');
                });
                if (oneLabel) {
                    $(".swiper-wrapper").append(slide);
                    //search_words.push(data[i]['info']['brand']);
                    search_words.push(getWords(data[i]['info']['name']));
                }

            }
        }

        // Create slides
        var swiper = new Swiper('.swiper-container', {
            loop: true,
            nextButton: '.swiper-button-next',
            prevButton: '.swiper-button-prev',
        });
    }

    $("#homesearch").keyup(function(event){
            if(event.keyCode == 13){
            var data = $("input").val();
            window.location.href = "/results?name=" + encodeURIComponent(data);
            }
            });

    $("#search").off('click').on('click', function(){
        var data = $("input").val();
        window.location.href = "/results?name=" + encodeURIComponent(data);
    });

    function getWords(str) {
        return str.split(/\s+/).slice(0,5).join(" ");
    }

    function updatePlaceholder(id) {
        var string = search_words[Math.floor(Math.random()*search_words.length)];
        $(id).attr("placeholder", "Busca por ejemplo: " + string);
    }
}

<commit_msg>Animate in front page.<commit_after>var search_words = [];
if ((window.location['pathname'] === '/') || ((window.location['pathname'] === '/results') && (window.location['search'] === ''))) {
    $.ajax({url:'/api/result?desc=true'}).done(function(data){
                if (window.matchMedia("(min-width: 768px)").matches) {
                    resultsDesktop(data);
                    if (window.location['pathname'] === '/') {
                        updatePlaceholder("#homesearch");
                    }
                    else {
                        updatePlaceholder("input");
                    }
                }

                else {
                    resultsMobile(data);
                    if (window.location['pathname'] === '/') {
                        updatePlaceholder("#homesearch");
                    }
                    else {
                        updatePlaceholder("input");
                    }

                }
    });

    function resultsDesktop(data) {
        $(".swiper-container").remove();
        var container = $("
");
        container.addClass("container");
        var row = $("
");
        row.addClass("row products");
        container.append(row);
        $(".numbers").append(container);
        var total = 0;
        for (i=0; i<data.length;i++) {
            if (data[i]['info']) {
                var location = "/results?name=" + encodeURIComponent(data[i]['info']['name']) + "&showBig=true&back=" + encodeURIComponent(window.location['pathname']);
                var col = $("
");
                col.addClass("col-xs-12 col-sm-6 col-md-4 col-lg-3 div-product last-product");
                var product = $("
", {"data-location": location });
                product.attr("id", "product-" + i);
                product.addClass("product");
                var brand = $("
");
                brand.addClass("brand");
                var name = $("
");
                name.addClass("name");
                var labels = $("
");
                var oneLabel = false;
                if (data[i]['info']['labelGlutenFree'] === 'yes') {
                    oneLabel = true;
                    var iconGlutenFree = $("");
                    iconGlutenFree.attr("src", "/static/img/green-gluten.svg");
                    labels.text(" Sin gluten");
                    labels.prepend(iconGlutenFree);
                    labels.addClass("gluten-free");
                    col.addClass("gluten-free ");
                    labels.addClass("classification-label");
                }

                if (data[i]['info']['ingredientsWheat'] === 'yes') {
                    oneLabel = true;
                    var iconWheat = $("");
                    iconWheat.attr("src", "/static/img/red-gluten.svg");
                    labels.text(" Trigo o trazas");
                    labels.prepend(iconWheat);
                    labels.addClass("wheat");
                    col.addClass("wheat");
                    labels.addClass("classification-label");
                }

                if (!oneLabel) {
                    labels.html("
");
                }

                product.append(brand);
                product.append(name);
                product.append(labels);

                var divImg = $("
");
                divImg.addClass("img-vertical-centered img-vertical-home-centered");
                var productImg = $("");
                productImg.attr("src", data[i]['info']['productImg']);
                productImg.addClass("img img-home img-responsive");
                divImg.append(productImg);

                name.text(data[i]['info']['name']);
                product.append(divImg);
                product.on('click', function(){
                    window.location.href = $(this).data('location');
                });
                col.append(product);
                if (oneLabel) {
                    col.addClass("animated fadeIn")
                    total += 1;
                    $(".row.products").append(col);
                    //search_words.push(data[i]['info']['brand']);
                    search_words.push(getWords(data[i]['info']['name']));
                }
                if (total === 4) {
                    break;
                }
            }
        }
    }

    function resultsMobile(data) {
        for(i=0;i<data.length;i++) {
            if (data[i]['info']) {
                var location = "/results?name=" + encodeURIComponent(data[i]['info']['name']) + "&showBig=true&back=" + encodeURIComponent(window.location['pathname']);
                var slide = $("
", {"data-location": location });
                var a = $("");
                var col = $("
");
                col.addClass("div-product last-product");
                var col2 = $("
");
                col2.addClass("col-xs-6 col-sm-6 col-md-4 col-lg-3 div-product");
                var brand = $("
");
                brand.addClass("brand");
                var name = $("
");
                name.addClass("name");
                var labels = $("
");
                var oneLabel = false;
                if (data[i]['info']['labelGlutenFree'] === 'yes') {
                    oneLabel = true;
                    var iconGlutenFree = $("");
                    iconGlutenFree.attr("src", "/static/img/green-gluten.svg");
                    labels.text(" Sin gluten");
                    labels.prepend(iconGlutenFree);
                    labels.addClass("gluten-free");
                    col.addClass("gluten-free ");
                    labels.addClass("classification-label");
                }

                if (data[i]['info']['ingredientsWheat'] === 'yes') {
                    oneLabel = true;
                    var iconWheat = $("");
                    iconWheat.attr("src", "/static/img/red-gluten.svg");
                    labels.text(" Trigo o trazas");
                    labels.prepend(iconWheat);
                    labels.addClass("wheat");
                    col.addClass("wheat");
                    labels.addClass("classification-label");
                }

                if (!oneLabel) {
                    labels.html("
");
                }

                name.text(data[i]['info']['name']);
                if (data[i]['info']['brand']) {
                    brand.text(data[i]['info']['brand']);
                }
                else {
                    brand.html("
");
                }

                col2.append(brand);
                col2.append(name);
                col2.append(labels);

                var productImg = $("");
                productImg.attr("src", data[i]['info']['productImg']);
                productImg.addClass("img");
                col.append(productImg);

                slide.addClass("swiper-slide");
                slide.append(col);
                slide.append(col2);
                slide.attr("id", "product-" + data[i]['id']);
                slide.on('click', function(){
                    window.location.href = $(this).data('location');
                });
                if (oneLabel) {
                    $(".swiper-wrapper").append(slide);
                    //search_words.push(data[i]['info']['brand']);
                    search_words.push(getWords(data[i]['info']['name']));
                }

            }
        }

        // Create slides
        var swiper = new Swiper('.swiper-container', {
            loop: true,
            nextButton: '.swiper-button-next',
            prevButton: '.swiper-button-prev',
        });
    }

    $("#homesearch").keyup(function(event){
            if(event.keyCode == 13){
            var data = $("input").val();
            window.location.href = "/results?name=" + encodeURIComponent(data);
            }
            });

    $("#search").off('click').on('click', function(){
        var data = $("input").val();
        window.location.href = "/results?name=" + encodeURIComponent(data);
    });

    function getWords(str) {
        return str.split(/\s+/).slice(0,5).join(" ");
    }

    function updatePlaceholder(id) {
        var string = search_words[Math.floor(Math.random()*search_words.length)];
        $(id).attr("placeholder", "Busca por ejemplo: " + string);
    }
}

<|endoftext|>


<commit_before>/*wait until document is loaded*/
//TODO need to fix how pdict for pwpolicy is passed/received from server; then check if summarize_policy works

var pwpolicy;

function verboseScore(score) {
    if (score < 0.2) {
        return "very low";
    }
    if (score < 0.4) {
        return "low";
    }
    if (score < 0.6) {
        return "average";
    }
    if (score < 0.8) {
        return "high";
    }
    if (score <= 1) {
        return "very high";
    }
}

function get_factors(policy) {
    var factors = [];

//    {"bdata": 0, "pdata": 0, "plen": 0}
    if (policy['bdata'] && policy['bdata'] != 0) {
        factors.push('biometric');
    }
    if (policy['pdata'] && policy['pdata'] != 0) {
        factors.push('passfaces');
    }
    if (policy['plen'] && policy['plen'] != 0) {
        factors.push('password');
    }

    return factors;
}

function update_password_form(policy) {
    var plen = policy["plen"];
    //console.log("found plen " + plen);
    $("#len" + plen).prop("checked", true);
    $("#len" + plen).change();

    /*preset pswd sets value*/
    $("#sets" + policy["psets"]).prop('checked', true);
    $("#sets" + policy["psets"]).change();

    /*preset pswd dictionary value*/
    $("#dic").prop('checked', policy["pdict"] == 1);
    $("#dic").change();

    $("#hist" + policy["phist"]).prop('checked', true);
    $("#hist" + policy["phist"]).change();

    $("#renew" + policy["prenew"]).prop('checked', true);
    $("#renew" + policy["prenew"]).change();

    /*preset pswd attempts number check (yes/no)*/
    /* 0 - unlimited, 1 - limit of 10 attempts, 2 - limit of 3 attempts */
    $("#attempts" + policy["pattempts"]).prop('checked', true);
    $("#attempts" + policy["pattempts"]).change();

    /*preset pswd recovery option*/
    $("#recovery" + policy["precovery"]).prop('checked', true);
    $("#recovery" + policy["precovery"]).change();
}

function update_biometric_form(policy) {
    $("#biometric").val(policy["bdata"]);
    $("#biometric").change();

}

function update_passfaces_form(policy) {
    $("#passfaces").val(policy["pdata"]);
    $("#passfaces").change();
}

function display_contextualized_policy(contextualized) {
    var factorIdx = {"biometric": 0, "passfaces": 1, "password": 2};

    emp = contextualized['employee'];
    $("#" + emp).prop('checked', true);
    $("#" + emp).change();

    loc = contextualized['location'];
    $("#" + loc).prop('checked', true);
    $("#" + loc).change();

    dev = contextualized['device'];
    $("#" + dev).prop('checked', true);
    $("#" + dev).change();
    // TODO: handle policy for more than one environment (emp, loc, dev)

    factors = get_factors(contextualized);

    $("#aut_num").val(factors.length);
    $("#aut_num").change(); // have to do it manually, previous line doesn't call it

    for (var i = 0; (i < factors.length) && (i < 2); i++) {
        $("#authentication" + (i+1)).val(factorIdx[factors[i]]);
        $("#authentication" + (i+1)).change();

        // dynamically compose name of function and call it
        var fname = "update_" + factors[i] + "_form";  // compose function name
        window[fname](contextualized); // call function fname with parameter contextualized
    }

}

function update_policy(policy) {
    policyUpdate = [];
    statusReady();
    console.log('response from server:');
    console.log(policy);
    $('#pause').click();
    timelineModel.currentDate(new Date(policy['date']));
    window.calendar = policy['calendar'];
    get_score_frame();

    //console.log(policy['policy'][0]['employee'] + " " + policy['policy'][0]['location'] + " " + policy['policy'][0]['device']);
    // TODO: store all policies so that when user changes context (employee, location, device) checkboxes, different policies are visualized
    //display_contextualized_policy(policy['policy'][0]);
}

//3 different authentication mechanisms
$('#aut_num').change(function(){
    $("#authentication1").remove();
    $("#authentication2").remove();
    hide_policies();
    //remove all options
    //    <option value="" disabled selected>number</option>

    var options = ['none set',  // need to do -1 to get the rest of the values
                   'biometric',   //value:0
                   'passfaces/swipe-lock',                  //value:1
                   'passwords'];                            //value:2

    for (var i = 0; i < this.value; i++) {  // use i+1, because indices in form start from 1
        var s = $("<select class=\"target\" id=\"authentication" + (i+1) + "\" name=\"authentication" + (i+1) + "\" />");

        // Was previously for(var val in options)
        // It returned further values beyond the array items.
        // Probably these are the default attributes of a (dynamically created) object
        for(var val = 0; val < options.length; val++) {
            if (val == 0) {
                $("<option value=\"\" disabled selected>" + options[val] + "</option>").appendTo(s);
            } else {
                $("<option />", {value: val - 1, text: options[val]}).appendTo(s);
            }
        }
        s.appendTo("#aut" + (i+1));
        //create second options set
    }

});
$(".aut").change(function(){
    if($('#aut_num').val()==2 && ($('#authentication1').val()==$('#authentication2').val())){ //ensure distinct selected options
        hide_policies();
        toastr['error']('Please, select two distinct options or change the number of mechanisms.');
    }else{
        display_policies();
    }
})

function display_policies(){ //display selected policies only
    hide_policies();

    $('.policy' +$("#authentication1").val()).css("display","block");
    $('.policy' +$("#authentication2").val()).css("display","block");
}
function hide_policies(){ //hide all policies
    $('.policy').each(function(){
        $(this).css("display","none");
    });
}
function clear_policy_summary(){
    $('.policy-summary-field').each(function(){
        $(this).text('');
    });
}

$(function(){
    $('#employee').buttonset();
    $('#location').buttonset();
    $('#device').buttonset();

    $('#plen').buttonset();
    $('#psets').buttonset();
    $('#pdict').buttonset();
    $('#phist').buttonset();
    $('#prenew').buttonset();
    $('#pattempts').buttonset();
    $('#precovery').buttonset();
})

//write policyUpdate array on apply btn press
$("#apply").click(function () {
    if (!policies_array.employee || !policies_array.location || !policies_array.device //if no employee/locn/device
        || $.isEmptyObject(policies_array.employee)
        || $.isEmptyObject(policies_array.location)
        || $.isEmptyObject(policies_array.device)) {
        toastr['error']('Failed to apply policy. You have to check at least one of the employees, locations and devices');
    } else if (!policies_array.policyDelta) {
        toastr['error']('Failed to apply policy. You have not chosen any number of the authentication mechanisms');
    } else {
        policyUpdate = policyUpdate.concat(policies_array);
        //reset policies form
        policies_array = {};
        $("#policy_form")[0].reset();
        $("#authentication1").remove();
        $("#authentication2").remove();
        hide_policies();
        clear_policy_summary();
        console.log(policyUpdate);
        toastr['info']('Policy saved. All the changes will be applied in the end of the term. Once you have finished updating the policies, please press the play button to continue');
    }
});

$('.aut').change(function(){ //if one of the names of mechanism to be used was changed
    if($('.authentication').val()>=1){
            var policy1 = $('.policy' +$("#authentication1").val()).attr('id');
            //$('.policy' +$("#authentication1").val()).find('.target').change();
            summarize_policy(policies_array);
            if($('.authentication').val()==2){
                var policy2 = $('.policy' +$("#authentication2").val()).attr('id'); //if exists
                //$('.policy' +$("#authentication2").val()).find('.target').change();
                summarize_policy(policies_array);
            }
    }

    if(policy1!= 'biometric_policy' && policy2!= 'biometric_policy'){null_unused_policy('biometric');}
    if(policy1!= 'passfaces_policy' && policy2!= 'passfaces_policy'){null_unused_policy('passfaces');}
    if(policy1!= 'password_policy' && policy2!= 'password_policy'){null_unused_policy('pwpolicy');}
    policy1 = '';
    policy2 = '';

});

function null_unused_policy(policy){
     policies_array.policyDelta[policy]={};
     $('#sum-'+policy).text('');
}

//populate policies_array onchange of inputs
$('.target').bind("change", function () {
    var attribute = $(this).parent().attr('id'); //can be empployee/device/location/biometric/passfaces/plen/psets/etc.
    if (attribute == 'employee' || attribute == 'location' || attribute == 'device') {   //write employee/location/device
        if (!policies_array[attribute]) {          //if doesn't exist, initialize array
            policies_array[attribute] = []
        }
        if ($(this).prop('checked')) {
            policies_array[attribute] = policies_array[attribute].concat($(this).val());
        } else {
            //console.log('unchecked');
            var index = policies_array[attribute].indexOf($(this).val());
            policies_array[attribute].splice(index, 1); //remove item from list if a checkbox has been unchecked
            //policies_array[attribute] = [];
        }
    } else if (attribute == 'policy_form') { //if number of used mechanisms is changed
        //console.log($(this).val()+' policies'); //how many policies to be passed
        if (!policies_array.policyDelta) {        //initialize dictionary if doesn't exist
            policies_array.policyDelta = {};
        }
        null_unused_policy('biometric');
        null_unused_policy('passfaces');
        null_unused_policy('pwpolicy');
    } else {                                       //write the policyDelta
        if (!policies_array.policyDelta) {        //initialize dictionary if doesn't exist
            policies_array.policyDelta = {};
        }
        //console.log($('#'+attribute).parent().attr('id'));      //can be biometric_policy or passsfaces_policy or password_policy
        if ($('#' + attribute).parent().attr('id') == 'biometric_policy' || $('#' + attribute).parent().attr('id') == 'passfaces_policy') {
            policies_array.policyDelta[$('#' + attribute).parent().attr('id').replace('_policy', '')] = {};
            policies_array.policyDelta[$('#' + attribute).parent().attr('id').replace('_policy', '')][$('#' + attribute).parent().attr('id').substring(0, 1) + 'data'] = $(this).val();
        } else {
            if (!policies_array.policyDelta.pwpolicy) {
                policies_array.policyDelta.pwpolicy = {};
            }
            if ($(this).prop('checked')) {
                policies_array.policyDelta.pwpolicy[attribute] = $(this).val();
            } else {
                //var index = policies_array.policyDelta.pwpolicy[attribute].indexOf($(this).val());
                policies_array.policyDelta.pwpolicy[attribute] = 0;

            }
            //policies_array.policyDelta.pwpolicy[attribute] = $(this).val();//write pwpolicy
        }
    }
    //console.log(policies_array);
    summarize_policy(policies_array);
});<commit_msg>added comment<commit_after>/*wait until document is loaded*/
//TODO need to fix how pdict for pwpolicy is passed/received from server; then check if summarize_policy works

var pwpolicy;

function verboseScore(score) {
    if (score < 0.2) {
        return "very low";
    }
    if (score < 0.4) {
        return "low";
    }
    if (score < 0.6) {
        return "average";
    }
    if (score < 0.8) {
        return "high";
    }
    if (score <= 1) {
        return "very high";
    }
}

function get_factors(policy) {
    var factors = [];

//    {"bdata": 0, "pdata": 0, "plen": 0}
    if (policy['bdata'] && policy['bdata'] != 0) {
        factors.push('biometric');
    }
    if (policy['pdata'] && policy['pdata'] != 0) {
        factors.push('passfaces');
    }
    if (policy['plen'] && policy['plen'] != 0) {
        factors.push('password');
    }

    return factors;
}

function update_password_form(policy) {
    var plen = policy["plen"];
    //console.log("found plen " + plen);
    $("#len" + plen).prop("checked", true);
    $("#len" + plen).change();

    /*preset pswd sets value*/
    $("#sets" + policy["psets"]).prop('checked', true);
    $("#sets" + policy["psets"]).change();

    /*preset pswd dictionary value*/
    $("#dic").prop('checked', policy["pdict"] == 1);
    $("#dic").change();

    $("#hist" + policy["phist"]).prop('checked', true);
    $("#hist" + policy["phist"]).change();

    $("#renew" + policy["prenew"]).prop('checked', true);
    $("#renew" + policy["prenew"]).change();

    /*preset pswd attempts number check (yes/no)*/
    /* 0 - unlimited, 1 - limit of 10 attempts, 2 - limit of 3 attempts */
    $("#attempts" + policy["pattempts"]).prop('checked', true);
    $("#attempts" + policy["pattempts"]).change();

    /*preset pswd recovery option*/
    $("#recovery" + policy["precovery"]).prop('checked', true);
    $("#recovery" + policy["precovery"]).change();
}

function update_biometric_form(policy) {
    $("#biometric").val(policy["bdata"]);
    $("#biometric").change();

}

function update_passfaces_form(policy) {
    $("#passfaces").val(policy["pdata"]);
    $("#passfaces").change();
}

function display_contextualized_policy(contextualized) {
    var factorIdx = {"biometric": 0, "passfaces": 1, "password": 2};

    emp = contextualized['employee'];
    $("#" + emp).prop('checked', true);
    $("#" + emp).change();

    loc = contextualized['location'];
    $("#" + loc).prop('checked', true);
    $("#" + loc).change();

    dev = contextualized['device'];
    $("#" + dev).prop('checked', true);
    $("#" + dev).change();
    // TODO: handle policy for more than one environment (emp, loc, dev)

    factors = get_factors(contextualized);

    $("#aut_num").val(factors.length);
    $("#aut_num").change(); // have to do it manually, previous line doesn't call it

    for (var i = 0; (i < factors.length) && (i < 2); i++) {
        $("#authentication" + (i+1)).val(factorIdx[factors[i]]);
        $("#authentication" + (i+1)).change();

        // dynamically compose name of function and call it
        var fname = "update_" + factors[i] + "_form";  // compose function name
        window[fname](contextualized); // call function fname with parameter contextualized
    }

}

function update_policy(policy) {
    policyUpdate = [];
    statusReady();
    console.log('response from server:');
    console.log(policy);
    $('#pause').click();
    timelineModel.currentDate(new Date(policy['date']));
    window.calendar = policy['calendar'];
    get_score_frame();

    //console.log(policy['policy'][0]['employee'] + " " + policy['policy'][0]['location'] + " " + policy['policy'][0]['device']);
    // TODO: store all policies so that when user changes context (employee, location, device) checkboxes, different policies are visualized
    //display_contextualized_policy(policy['policy'][0]);
}

//3 different authentication mechanisms
$('#aut_num').change(function(){
    $("#authentication1").remove();
    $("#authentication2").remove();
    hide_policies();
    //remove all options
    //    <option value="" disabled selected>number</option>

    var options = ['none set',  // need to do -1 to get the rest of the values
                   'biometric',   //value:0
                   'passfaces/swipe-lock',                  //value:1
                   'passwords'];                            //value:2

    for (var i = 0; i < this.value; i++) {  // use i+1, because indices in form start from 1
        var s = $("<select class=\"target\" id=\"authentication" + (i+1) + "\" name=\"authentication" + (i+1) + "\" />");

        // Was previously for(var val in options)
        // It returned further values beyond the array items.
        // Probably these are the default attributes of a (dynamically created) object
        for(var val = 0; val < options.length; val++) {
            if (val == 0) {
                $("<option value=\"\" disabled selected>" + options[val] + "</option>").appendTo(s);
            } else {
                $("<option />", {value: val - 1, text: options[val]}).appendTo(s);
            }
        }
        s.appendTo("#aut" + (i+1));
        //create second options set
    }

});
$(".aut").change(function(){
    if($('#aut_num').val()==2 && ($('#authentication1').val()==$('#authentication2').val())){ //ensure distinct selected options
        hide_policies();
        toastr['error']('Please, select two distinct options or change the number of mechanisms.');
    }else{
        display_policies();
    }
})

function display_policies(){ //display selected policies only
    hide_policies();

    $('.policy' +$("#authentication1").val()).css("display","block");
    $('.policy' +$("#authentication2").val()).css("display","block");
}
function hide_policies(){ //hide all policies
    $('.policy').each(function(){
        $(this).css("display","none");
    });
}
function clear_policy_summary(){
    $('.policy-summary-field').each(function(){
        $(this).text('');
    });
}

// used for horizontal buttons styling
$(function(){
    $('#employee').buttonset();
    $('#location').buttonset();
    $('#device').buttonset();

    $('#plen').buttonset();
    $('#psets').buttonset();
    $('#pdict').buttonset();
    $('#phist').buttonset();
    $('#prenew').buttonset();
    $('#pattempts').buttonset();
    $('#precovery').buttonset();
})

//write policyUpdate array on apply btn press
$("#apply").click(function () {
    if (!policies_array.employee || !policies_array.location || !policies_array.device //if no employee/locn/device
        || $.isEmptyObject(policies_array.employee)
        || $.isEmptyObject(policies_array.location)
        || $.isEmptyObject(policies_array.device)) {
        toastr['error']('Failed to apply policy. You have to check at least one of the employees, locations and devices');
    } else if (!policies_array.policyDelta) {
        toastr['error']('Failed to apply policy. You have not chosen any number of the authentication mechanisms');
    } else {
        policyUpdate = policyUpdate.concat(policies_array);
        //reset policies form
        policies_array = {};
        $("#policy_form")[0].reset();
        $("#authentication1").remove();
        $("#authentication2").remove();
        hide_policies();
        clear_policy_summary();
        console.log(policyUpdate);
        toastr['info']('Policy saved. All the changes will be applied in the end of the term. Once you have finished updating the policies, please press the play button to continue');
    }
});

$('.aut').change(function(){ //if one of the names of mechanism to be used was changed
    if($('.authentication').val()>=1){
            var policy1 = $('.policy' +$("#authentication1").val()).attr('id');
            //$('.policy' +$("#authentication1").val()).find('.target').change();
            summarize_policy(policies_array);
            if($('.authentication').val()==2){
                var policy2 = $('.policy' +$("#authentication2").val()).attr('id'); //if exists
                //$('.policy' +$("#authentication2").val()).find('.target').change();
                summarize_policy(policies_array);
            }
    }

    if(policy1!= 'biometric_policy' && policy2!= 'biometric_policy'){null_unused_policy('biometric');}
    if(policy1!= 'passfaces_policy' && policy2!= 'passfaces_policy'){null_unused_policy('passfaces');}
    if(policy1!= 'password_policy' && policy2!= 'password_policy'){null_unused_policy('pwpolicy');}
    policy1 = '';
    policy2 = '';

});

function null_unused_policy(policy){
     policies_array.policyDelta[policy]={};
     $('#sum-'+policy).text('');
}

//populate policies_array onchange of inputs
$('.target').bind("change", function () {
    var attribute = $(this).parent().attr('id'); //can be empployee/device/location/biometric/passfaces/plen/psets/etc.
    if (attribute == 'employee' || attribute == 'location' || attribute == 'device') {   //write employee/location/device
        if (!policies_array[attribute]) {          //if doesn't exist, initialize array
            policies_array[attribute] = []
        }
        if ($(this).prop('checked')) {
            policies_array[attribute] = policies_array[attribute].concat($(this).val());
        } else {
            //console.log('unchecked');
            var index = policies_array[attribute].indexOf($(this).val());
            policies_array[attribute].splice(index, 1); //remove item from list if a checkbox has been unchecked
            //policies_array[attribute] = [];
        }
    } else if (attribute == 'policy_form') { //if number of used mechanisms is changed
        //console.log($(this).val()+' policies'); //how many policies to be passed
        if (!policies_array.policyDelta) {        //initialize dictionary if doesn't exist
            policies_array.policyDelta = {};
        }
        null_unused_policy('biometric');
        null_unused_policy('passfaces');
        null_unused_policy('pwpolicy');
    } else {                                       //write the policyDelta
        if (!policies_array.policyDelta) {        //initialize dictionary if doesn't exist
            policies_array.policyDelta = {};
        }
        //console.log($('#'+attribute).parent().attr('id'));      //can be biometric_policy or passsfaces_policy or password_policy
        if ($('#' + attribute).parent().attr('id') == 'biometric_policy' || $('#' + attribute).parent().attr('id') == 'passfaces_policy') {
            policies_array.policyDelta[$('#' + attribute).parent().attr('id').replace('_policy', '')] = {};
            policies_array.policyDelta[$('#' + attribute).parent().attr('id').replace('_policy', '')][$('#' + attribute).parent().attr('id').substring(0, 1) + 'data'] = $(this).val();
        } else {
            if (!policies_array.policyDelta.pwpolicy) {
                policies_array.policyDelta.pwpolicy = {};
            }
            if ($(this).prop('checked')) {
                policies_array.policyDelta.pwpolicy[attribute] = $(this).val();
            } else {
                //var index = policies_array.policyDelta.pwpolicy[attribute].indexOf($(this).val());
                policies_array.policyDelta.pwpolicy[attribute] = 0;

            }
            //policies_array.policyDelta.pwpolicy[attribute] = $(this).val();//write pwpolicy
        }
    }
    //console.log(policies_array);
    summarize_policy(policies_array);
});<|endoftext|>


<commit_before>window.admin = {};

$(document).ready(function() {
	$("#admin-feedback").on("tabOpened", function() {
		window.api.get("admin/feedback/getList", function(resp) {
			$("#admin-feedback-list").text("");
			for (var feedbackIndex in resp.feedback) {
				var feedbackItem = resp.feedback[feedbackIndex];
				var $feedbackLi = $('

');
					var $feedbackDesc = $('

');
						$feedbackDesc.text(" #" + feedbackItem.feedbackId + " " + feedbackItem.msg);
						var $icon = $('');
							if (feedbackItem.type == "smile") {
								$icon.addClass("fa-smile-o");
							} else if (feedbackItem.type == "frown") {
								$icon.addClass("fa-frown-o");
							} else if (feedbackItem.type == "idea") {
								$icon.addClass("fa-lightbulb-o");
							}
						$feedbackDesc.prepend($icon);
					$feedbackLi.append($feedbackDesc);
					var $feedbackName = $('

');
						$feedbackName.text(feedbackItem.name + " (" + feedbackItem.username + ")");
					$feedbackLi.append($feedbackName);
					var $feedbackDay = $('

');
						$feedbackDay.children("em").text("Sent " + moment(feedbackItem.timestamp).format("MM/DD/YY"));
					$feedbackLi.append($feedbackDay);
					$feedbackLi.attr("data-webpage", feedbackItem.webpage)
					$feedbackLi.click(function() {
						var iframeSrc = "";
						if ($(this).attr("data-webpage")) {
							iframeSrc = "<jqueryIsDumb>" + atob($(this).attr("data-webpage")) + "</jqueryIsDumb>";
							var $iframeSrc = $(iframeSrc);
							$iframeSrc.find("#feedback-modal").remove();
							$iframeSrc.find(".modal-backdrop").remove();
							$iframeSrc.find("link[rel=stylesheet]").each(function() {
								var oldUrl = $(this).attr("href");
								if (oldUrl) {
									if (oldUrl[0] == "/") {
										// it is a relative path
										var newUrl = window.location.protocol + "//" + window.location.host + oldUrl; // make it absolute
										$(this).attr("href", newUrl);
									}
								}
							});
							iframeSrc = $iframeSrc.html().toString();
						} else {
							iframeSrc = "No screenshot data was included with this submission.";
						}
						$("#admin-feedback-modal").find("iframe").attr("src", "data:text/html," + iframeSrc);
						if ($(this).attr("data-webpage")) {

						}
						$("#admin-feedback-modal").modal();
					});
				$("#admin-feedback-list").append($feedbackLi);
			};
		});
	});
	window.api.get('overview/announcements/get/', function(data) {
		var response = data.feedback;
		for(feed in response) {
			var $feedLi = $("

");
				$feedLi.append(response[feed].msg);
				if(!moment(response[feed].time).add(response[feed].days, "days").isAfter(moment())) {
					$feedLi.append(" (expired)");
				}
				$feedLi.attr("data-id", response[feed].announcementId);
				var $copyLi = $feedLi.clone();
					var $days = $('');
						$days.text(" Days: " + response[feed].days);
					$copyLi.append($days)
				$("#adminAnnouncementList").append($copyLi);
				var $removeBtn = $('<button class="btn btn-xs btn-danger">  </button>');
					$removeBtn.click(function() {
						var idThingy = $(this).parent().attr("data-id");
						$(this).parent().addClass("announcementDelete");
						$(this).remove();
						window.api.post('admin/announcements/remove', {id: idThingy}, function(result){});
					});
				$feedLi.append($removeBtn)
			$("#announcement-delete-list").append($feedLi);

		}
		if($("#adminAnnouncementList").children().size() > 1) {
			$("#adminNoAnnouncements").remove()
		}
	});
	$("#announcement-submit").click(function() {
		if($("#announcement-msg").val().length != 0 && $("#announcement-days").val() > 0) {
			var postMe = {};
			postMe.days = $("#announcement-days").val();
			postMe.time = window.utils.formatDate_api(moment().toDate());
			postMe.msg = $("#announcement-msg").val();
			window.api.post('admin/announcements/post/', postMe, function(result){});
		};
		swal("Yay", "Your announcement has been posted", "success");
	});
	$("#announcement-clear").click(function() {
		$("#admin-announcement-modal").modal();
	});
	window.api.get('admin/users/count/', function(result) {
		$("#userNumber").text("There are " + result.number + " users!")
	});
});
<commit_msg>Update admin.js<commit_after>window.admin = {};

$(document).ready(function() {
	$("#admin-feedback").on("tabOpened", function() {
		window.api.get("admin/feedback/getList", function(resp) {
			$("#admin-feedback-list").text("");
			for (var feedbackIndex in resp.feedback) {
				var feedbackItem = resp.feedback[feedbackIndex];
				var $feedbackLi = $('

');
					var $feedbackDesc = $('

');
						$feedbackDesc.text(" #" + feedbackItem.feedbackId + " " + feedbackItem.msg);
						var $icon = $('');
							if (feedbackItem.type == "smile") {
								$icon.addClass("fa-smile-o");
							} else if (feedbackItem.type == "frown") {
								$icon.addClass("fa-frown-o");
							} else if (feedbackItem.type == "idea") {
								$icon.addClass("fa-lightbulb-o");
							}
						$feedbackDesc.prepend($icon);
					$feedbackLi.append($feedbackDesc);
					var $feedbackName = $('

');
						$feedbackName.text(feedbackItem.name + " (" + feedbackItem.username + ")");
					$feedbackLi.append($feedbackName);
					var $feedbackDay = $('

');
						$feedbackDay.children("em").text("Sent " + moment(feedbackItem.timestamp).format("MM/DD/YY"));
					$feedbackLi.append($feedbackDay);
					$feedbackLi.attr("data-webpage", feedbackItem.webpage)
					$feedbackLi.click(function() {
						var iframeSrc = "";
						if ($(this).attr("data-webpage")) {
							iframeSrc = "<jqueryIsDumb>" + atob($(this).attr("data-webpage")) + "</jqueryIsDumb>";
							var $iframeSrc = $(iframeSrc);
							$iframeSrc.find("#feedback-modal").remove();
							$iframeSrc.find(".modal-backdrop").remove();
							$iframeSrc.find("link[rel=stylesheet]").each(function() {
								var oldUrl = $(this).attr("href");
								if (oldUrl) {
									if (oldUrl[0] == "/") {
										// it is a relative path
										var newUrl = window.location.protocol + "//" + window.location.host + oldUrl; // make it absolute
										$(this).attr("href", newUrl);
									}
								}
							});
							iframeSrc = $iframeSrc.html().toString();
						} else {
							iframeSrc = "No screenshot data was included with this submission.";
						}
						$("#admin-feedback-modal").find("iframe").attr("src", "data:text/html," + iframeSrc);
						if ($(this).attr("data-webpage")) {

						}
						$("#admin-feedback-modal").modal();
					});
				$("#admin-feedback-list").append($feedbackLi);
			};
		});
	});
	window.api.get('overview/announcements/get/', function(data) {
		var response = data.feedback;
		for(feed in response) {
			var $feedLi = $("

");
				$feedLi.append(response[feed].msg);
				if(!moment(response[feed].time).add(response[feed].days, "days").isAfter(moment())) {
					$feedLi.append(" (expired)");
				}
				$feedLi.attr("data-id", response[feed].announcementId);
				var $copyLi = $feedLi.clone();
					var $days = $('');
						$days.text(" Days: " + response[feed].days + ", Poster ID:" response[feed].posterId);
					$copyLi.append($days)
				$("#adminAnnouncementList").append($copyLi);
				var $removeBtn = $('<button class="btn btn-xs btn-danger">  </button>');
					$removeBtn.click(function() {
						var idThingy = $(this).parent().attr("data-id");
						$(this).parent().addClass("announcementDelete");
						$(this).remove();
						window.api.post('admin/announcements/remove', {id: idThingy}, function(result){});
					});
				$feedLi.append($removeBtn)
			$("#announcement-delete-list").append($feedLi);

		}
		if($("#adminAnnouncementList").children().size() > 1) {
			$("#adminNoAnnouncements").remove()
		}
	});
	$("#announcement-submit").click(function() {
		if($("#announcement-msg").val().length != 0 && $("#announcement-days").val() > 0) {
			var postMe = {};
			postMe.days = $("#announcement-days").val();
			postMe.time = window.utils.formatDate_api(moment().toDate());
			postMe.msg = $("#announcement-msg").val();
			window.api.post('admin/announcements/post/', postMe, function(result){});
		};
		swal("Yay", "Your announcement has been posted", "success");
	});
	$("#announcement-clear").click(function() {
		$("#admin-announcement-modal").modal();
	});
	window.api.get('admin/users/count/', function(result) {
		$("#userNumber").text("There are " + result.number + " users!")
	});
});
<|endoftext|>