<commit_before>//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require local_time
//= require bootstrap-sprockets
//= require_tree .

document.addEventListener("turbolinks:load", function() {
  $('button.archive_selected, button.unarchive_selected').click(function () { toggleArchive(); });
  $('button.mute_selected').click(function () { mute(); });
  $('input.archive, input.unarchive').change(function() {
    var marked = $(".js-table-notifications input:checked");
    if ( marked.length > 0 ) {
      if ($(".js-table-notifications input").length === marked.length){
        $(".js-select_all").prop('checked', true)
      } else {
        $(".js-select_all").prop("indeterminate", true);
      }
      $('button.archive_selected, button.unarchive_selected, button.mute_selected').removeClass('hidden');
    } else {
      $(".js-select_all").prop('checked', false)
      $('button.archive_selected, button.unarchive_selected, button.mute_selected').addClass('hidden');
    }
  });
  $('.toggle-star').click(function() {
    $(this).toggleClass("star-active star-inactive")
    $.get('/notifications/'+$(this).data('id')+'/star')
  });
  $('.sync .octicon').on('click', function() {
    $(this).toggleClass('spinning')
  });
  recoverPreviousCursorPosition()

  $('.js-select_all').change(function() {
    checkAll($(".js-select_all").prop('checked'))
  })
});

document.addEventListener("turbolinks:before-cache", function() {
  $('td.js-current').removeClass("current js-current");
});

// Add shortcut events only once
$(document).ready(enableKeyboardShortcuts);

$(document).on('click', '[data-toggle="offcanvas"]', function () {
  $('.flex-content').toggleClass('active')
});

if(!('ontouchstart' in window))
{
  $(function () {
    $('[data-toggle="tooltip"]').tooltip()
  })
}

function enableKeyboardShortcuts() {
  window.row_index = 1
  window.current_id = undefined

  $(document).keydown(function(e) {
    // disable shortcuts for the seach box
    if (e.target.id !== 'search-box') {
      var shortcutFunction = shortcuts[e.which]
      if (shortcutFunction) { shortcutFunction(e) }
    }
  });
}

var shortcuts = {
  65:  checkSelectAll, // a
  74:  cursorDown,      // j
  75:  cursorUp,        // k
  83:  toggleStar,      // s
  88:  markCurrent,     // x
  89:  toggleArchive,   // y
  77:  mute,            // m
  13:  openCurrentLink, // Enter
  79:  openCurrentLink, // o
  191: openModal,       // ?
  190: sync,            // .
  82:  sync             // r
}

function cursorDown() {
  moveCursor('up')
}

function cursorUp() {
  moveCursor('down')
}

function markCurrent() {
  checkbox = $('td.js-current').parent().find("input[type=checkbox]")
  checkbox.prop('checked', function (i, value) {
    return !value;
  });
  checkbox.change();
}

function checkAll(checked) {
  $(".js-table-notifications input").prop("checked", checked).trigger('change');
}

function checkSelectAll() {
  var allSelected = $(".js-select_all").prop('checked')
  $(".js-select_all").prop('checked', !allSelected).trigger('change')
}

function mute() {
  if ( $(".js-table-notifications tr").length === 0 ) return;
  marked = $(".js-table-notifications input:checked");
  if ( marked.length > 0 ) {
    ids = marked.map(function() { return this.value; }).get();
  } else {
    ids = [ $('td.js-current input').val() ];
  }
  $.post( "/notifications/mute_selected", { 'id[]': ids}).done(function() {
    // calculating new position of the cursor
    current = $('td.js-current').parent();
    while ( $.inArray(current.find('input').val(), ids) > -1 && current.next().length > 0) {
      current = current.next();
    }
    window.current_id = current.find('input').val();
    if ( $.inArray(window.current_id, ids ) > -1 ) {
      window.current_id = $(".js-table-notifications input:not(:checked)").last().val();
    }
    Turbolinks.visit("/"+location.search);
  });
}

function markAsRead(id) {
  $.get( "/notifications/"+id+"/mark_as_read");
  $('#notification-'+id).removeClass('active');
}

function toggleArchive() {
  if ( $(".js-table-notifications tr").length === 0 ) return;

  var cssClass, value;

  if ( $(".archive_toggle").hasClass("archive_selected") ) {
    cssClass = '.archive'
    value = true
  } else {
    cssClass = '.unarchive'
    value = false
  }

  marked = $(".js-table-notifications input:checked");
  if ( marked.length > 0 ) {
    ids = marked.map(function() { return this.value; }).get();
  } else {
    ids = [ $('td.js-current input'+ cssClass).val() ];
  }
  $.post( "/notifications/archive_selected", { 'id[]': ids, 'value': value } ).done(function () {
    // calculating new position of the cursor
    current = $('td.js-current').parent();
    while ( $.inArray(current.find('input').val(), ids) > -1 && current.next().length > 0) {
      current = current.next();
    }
    window.current_id = current.find('input').val();
    if ( $.inArray(window.current_id, ids ) > -1 ) {
      window.current_id = $(".js-table-notifications input:not(:checked)").last().val();
    }
    Turbolinks.visit("/"+location.search);
  });
}

function toggleStar() {
  $('td.js-current').parent().find('.toggle-star').click();
}

function openModal() {
  $("#help-box").modal();
}

function openCurrentLink(e) {
  e.preventDefault(e);
  $('td.js-current').parent().find('.link')[0].click();
}

function sync() {
  $("a.sync").click();
}

function autoSync() {
  marked = $(".js-table-notifications input:checked")
  if ( marked.length === 0 ) {
    sync()
  }
}

function setAutoSyncTimer() {
  refresh_interval = $('.js-table-notifications').data('refresh-interval');
  if (isNaN(refresh_interval)) {
    return;
  }
  if (refresh_interval > 0) {
    setInterval(autoSync, refresh_interval)
  }
}

$(document).ready(setAutoSyncTimer);

function scrollToCursor() {
  var current = $('td.js-current');
  var table_offset = $('.js-table-notifications').position().top;
  var cursor_offset = current.offset().top;
  var cursor_relative_offset = current.position().top;
  var cursor_height = current.height();
  var menu_height = $(".js-octobox-menu").height();
  var scroll_top = $(document).scrollTop();
  var window_height = $(window).height();
  if ( cursor_offset < menu_height + scroll_top ) {
    $("html, body").animate({
      scrollTop: table_offset + cursor_relative_offset - cursor_height
    }, 0);
  }
  if ( cursor_offset > scroll_top + window_height - cursor_height ) {
    $("html, body").animate({
      scrollTop: cursor_offset - window_height + 2*cursor_height
    }, 0);
  }
}

function moveCursor(upOrDown) {
  var current = $('td.js-current');
  var parent = $(current).parent()
  var target = upOrDown === 'up' ? parent.next() : parent.prev()
  if(target.length > 0) {
    $(current).removeClass("current js-current");
    $(target).find('td').first().addClass("current js-current");
    row_index += upOrDown === 'up' ? 1 : -1;
    scrollToCursor();
  }
}

function recoverPreviousCursorPosition() {
  if ( current_id === undefined ) {
    row_index = Math.min(row_index, $(".js-table-notifications tr").length);
    row_index = Math.max(row_index, 1);
  } else {
    row_index = $("input[value=" + current_id + "]").parents('tr').index() + 1;
    current_id = undefined;
  }
  $(".js-table-notifications tbody tr:nth-child(" + row_index + ")").first().find("td").first().addClass("current js-current");
}

function loadTurbolinksArchiveURL(link, route) {
  Turbolinks.visit('/notifications/'+$(link).val()+'/'+route+location.search)
}

// Clicking a row marks it current
$(document).ready(function() {
  $("tr.notification").click(function() {
    $(".current.js-current").removeClass("current js-current");
    $( this ).find("td").first().addClass("current js-current");
  })
});
<commit_msg>Refactor application.js for DRYness and readability<commit_after>//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require local_time
//= require bootstrap-sprockets
//= require_tree .

function getDisplayedRows() {
  return $(".js-table-notifications tr.notification")
}

// gets all marked rows (or unmarked rows if unmarked is true)
function getMarkedRows(unmarked) {
  return unmarked ? getDisplayedRows().has("input:not(:checked)") : getDisplayedRows().has("input:checked")
}

function getIdsFromRows(rows) {
  return $.map(rows, function(row) {return $(row).find("input").val()})
}

// returns true if there are any marked rows (or unmarked rows if unmarked is true)
function hasMarkedRows(unmarked) {
  return getMarkedRows(unmarked).length > 0
}

function getCurrentRow() {
  return getDisplayedRows().has('td.js-current')
}

function getMarkedOrCurrentRows() {
  return hasMarkedRows() ? getMarkedRows() : getCurrentRow()
}

document.addEventListener("turbolinks:load", function() {
  $('button.archive_selected, button.unarchive_selected').click(toggleArchive);
  $('button.mute_selected').click(mute);
  $('input.archive, input.unarchive').change(function() {
    if ( hasMarkedRows() ) {
      var prop = hasMarkedRows(true) ? 'indeterminate' : 'checked';
      $(".js-select_all").prop(prop, true);
      $('button.archive_selected, button.unarchive_selected, button.mute_selected').removeClass('hidden');
    } else {
      $(".js-select_all").prop('checked', false);
      $('button.archive_selected, button.unarchive_selected, button.mute_selected').addClass('hidden');
    }
  });
  $('.toggle-star').click(function() {
    $(this).toggleClass("star-active star-inactive");
    $.get('/notifications/'+$(this).data('id')+'/star')
  });
  $('.sync .octicon').on('click', function() {
    $(this).toggleClass('spinning')
  });
  recoverPreviousCursorPosition();

  $('.js-select_all').change(function() {
    checkAll($(".js-select_all").prop('checked'))
  })
});

document.addEventListener("turbolinks:before-cache", function() {
  $('td.js-current').removeClass("current js-current");
});

// Add shortcut events only once
$(document).ready(enableKeyboardShortcuts);

$(document).on('click', '[data-toggle="offcanvas"]', function () {
  $('.flex-content').toggleClass('active')
});

if(!('ontouchstart' in window))
{
  $(function () {
    $('[data-toggle="tooltip"]').tooltip()
  })
}

function enableKeyboardShortcuts() {
  window.row_index = 1;
  window.current_id = undefined;

  $(document).keydown(function(e) {
    // disable shortcuts for the seach box
    if (e.target.id !== 'search-box') {
      var shortcutFunction = shortcuts[e.which];
      if (shortcutFunction) { shortcutFunction(e) }
    }
  });
}

var shortcuts = {
  65:  checkSelectAll, // a
  74:  cursorDown,      // j
  75:  cursorUp,        // k
  83:  toggleStar,      // s
  88:  markCurrent,     // x
  89:  toggleArchive,   // y
  77:  mute,            // m
  13:  openCurrentLink, // Enter
  79:  openCurrentLink, // o
  191: openModal,       // ?
  190: sync,            // .
  82:  sync             // r
};

function cursorDown() {
  moveCursor('up')
}

function cursorUp() {
  moveCursor('down')
}

function markCurrent() {
  getCurrentRow().find("input[type=checkbox]").click();
}

function checkAll(checked) {
  getDisplayedRows().find('input').prop("checked", checked).trigger('change');
}

function checkSelectAll() {
  $(".js-select_all").click()
}

function mute() {
  if (getDisplayedRows().length === 0) return;
  if ( $(".js-table-notifications tr").length === 0 ) return;
  var ids = getIdsFromRows(getMarkedOrCurrentRows());
  $.post( "/notifications/mute_selected", { 'id[]': ids}).done(resetCursorAfterRowsRemoved(ids));
}

function markAsRead(id) {
  $.get( "/notifications/"+id+"/mark_as_read");
  $('#notification-'+id).removeClass('active');
}

function toggleArchive() {
  if (getDisplayedRows().length === 0) return;

  [cssClass, value] = $(".archive_toggle").hasClass("archive_selected") ?
    ['.archive', true] : ['.unarchive', false];

  var ids = getIdsFromRows(getMarkedOrCurrentRows());

  $.post( "/notifications/archive_selected", { 'id[]': ids, 'value': value } ).done(resetCursorAfterRowsRemoved(ids));
}

function resetCursorAfterRowsRemoved(ids) {
  var current = getCurrentRow();
  while ( $.inArray(getIdsFromRows(current)[0], ids) > -1 && current.next().length > 0) {
    current = current.next();
  }
  window.current_id = getIdsFromRows(current)[0];
  if ( $.inArray(window.current_id, ids ) > -1 ) {
    window.current_id = getIdsFromRows(getMarkedRows(true).last())[0];
  }
  Turbolinks.visit("/"+location.search);
}

function toggleStar() {
  getCurrentRow().find('.toggle-star').click();
}

function openModal() {
  $("#help-box").modal();
}

function openCurrentLink(e) {
  e.preventDefault(e);
  getCurrentRow().find('td.notification-subject .link')[0].click();
}

function sync() {
  $("a.sync").click();
}

function autoSync() {
  hasMarkedRows() || sync()
}

function setAutoSyncTimer() {
  var refresh_interval = $('.js-table-notifications').data('refresh-interval');
  if (isNaN(refresh_interval)) return;
  refresh_interval > 0 && setInterval(autoSync, refresh_interval)
}

$(document).ready(setAutoSyncTimer);

function scrollToCursor() {
  var current = $('td.js-current');
  var table_offset = $('.js-table-notifications').position().top;
  var cursor_offset = current.offset().top;
  var cursor_relative_offset = current.position().top;
  var cursor_height = current.height();
  var menu_height = $(".js-octobox-menu").height();
  var scroll_top = $(document).scrollTop();
  var window_height = $(window).height();
  if ( cursor_offset < menu_height + scroll_top ) {
    $("html, body").animate({
      scrollTop: table_offset + cursor_relative_offset - cursor_height
    }, 0);
  }
  if ( cursor_offset > scroll_top + window_height - cursor_height ) {
    $("html, body").animate({
      scrollTop: cursor_offset - window_height + 2*cursor_height
    }, 0);
  }
}

function setRowCurrent(row, add) {
  var classes = 'current js-current';
  var td = row.find('td.notification-checkbox');
  add ? td.addClass(classes) : td.removeClass(classes)
}

function moveCursor(upOrDown) {
  var oldCurrent = getCurrentRow();
  var target = upOrDown === 'up' ? oldCurrent.next() : oldCurrent.prev();
  if(target.length > 0) {
    setRowCurrent(oldCurrent, false);
    setRowCurrent(target, true);
    scrollToCursor();
  }
}

function recoverPreviousCursorPosition() {
  if ( current_id === undefined ) {
    row_index = Math.min(row_index, $(".js-table-notifications tr").length);
    row_index = Math.max(row_index, 1);
  } else {
    row_index = $('#notification-'+current_id).index() + 1;
    current_id = undefined;
  }
  $(".js-table-notifications tbody tr:nth-child(" + row_index + ")").first().find("td").first().addClass("current js-current");
}

// Clicking a row marks it current
$(document).ready(function() {
  $("tr.notification").click(function() {
    $(".current.js-current").removeClass("current js-current");
    $( this ).find("td").first().addClass("current js-current");
  })
});
<|endoftext|>


<commit_before><commit_msg>[DEMAD] Sin turbolinks<commit_after><|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.

//= require jquery
//= require bootstrap
//= require dataTables/jquery.dataTables
//= require jquery_ujs
//= require jquery.ui.datepicker
//= require jquery.ui.slider
//= require jquery-ui-sliderAccess
//= require jquery-ui-timepicker-addon
//= require jquery-ui-timepicker-addon.min
//= require jquery.validate
//= require jquery.validate.additional-methods
//= require jquery.ui.effect
//= require jquery.ui.selectable
//= require jquery.ui.accordion
//= require turbolinks
//= require_self
//= require_directory .

// Touch this code and die
window.onLoad = function(callback) {
    // binds ready event and turbolink page:load event
    $(document).ready(callback);
    $(document).on('page:load',   callback);
};

onLoad(function() {

    var table =  $('.default_table').dataTable({
        "bPaginate" : false,
        "iCookieDuration": 60,
        "bStateSave": false,
        "bAutoWidth": false,
        "bScrollAutoCss": true,
        "bProcessing": true,
        "bRetrieve": true,
        "bJQueryUI": true,
        "sDom": '<"H"CTrf>t<"F"lip>',
        "sScrollXInner": "110%",
        "fnInitComplete": function() {
            this.css("visibility", "visible");
        },
        "fnPreDrawCallback": $(".autoHide").hide()
    }, $(".defaultTooltip").tooltip({
        'selector': '',
        'placement': 'left',
        'container': 'body'
    }));

    $('table.default_table').each(function(i,table) {
        $('

').append($(table)).insertAfter($('#' + $(table).attr('id') + '_wrapper div').first());
    });

    return table;
});

    function overridePrioritySort(){

      // The following is a custom override of the column sorting so that the tickets will push high, medium, and low to the top of the column
      var priorities = ['high', 'medium', 'low'];
      var index      = 0;
      var ascFlag    = true;
      var descFlag   = true;

      var priorityArray = {};
      priorityArray['High']   =-1;
      priorityArray['Medium'] = 0;
      priorityArray['Low']    = 1;

      function updatePriorityArray(){
        priorityArray['High']   = ((priorityArray['High']   + 2) % 3) - 1;
        priorityArray['Medium'] = ((priorityArray['Medium'] + 2) % 3) - 1;
        priorityArray['Low']    = ((priorityArray['Low']    + 2) % 3) - 1;
      }

      // Both the ascending function and descending function have to be overridden since they are called in alternate.
      jQuery.fn.dataTableExt.oSort['priority-asc'] = function(x,y) {

        if (descFlag) { // This prevents the the priority array from going moving more than once per cycle since this function gets called multiple times during the sort.
          index++;
          index   %= priorities.length;
          ascFlag  = true;
          descFlag = false;
          updatePriorityArray();
        }
        var currentPriority = priorities[index];

        // This strips out the span tags I added to the td. - Rob
        x = $(x).text();
        y = $(y).text();

        if (x == (currentPriority) && y == (currentPriority))
          return 0;
        else if (x == (currentPriority))
          return -1;
        else if (y == (currentPriority))
          return 1;
        else
          return ((priorityArray[x] < priorityArray[y]) ?  1 : ((priorityArray[x] > priorityArray[y]) ? -1: 0 ) );
      };

      // This one too
      jQuery.fn.dataTableExt.oSort['priority-desc'] = function(x,y) {

        if (ascFlag) {
          index++;
          index   %= priorities.length;
          ascFlag  = false;
          descFlag = true;
          updatePriorityArray();
        }
        var currentPriority = priorities[index];

        // This strips out the span tags I added to the td. - Rob
        x = $(x).text();
        y = $(y).text();

        if (x == (currentPriority) && y == (currentPriority))
          return 0;
        else if (x == (currentPriority))
          return -1;
        else if (y == (currentPriority))
          return 1;
        else
          return ((priorityArray[x] < priorityArray[y]) ?  1 : ((priorityArray[x] > priorityArray[y]) ? -1: 0 ) );
      };
    }<commit_msg>changed priority order for better functionality<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.

//= require jquery
//= require bootstrap
//= require dataTables/jquery.dataTables
//= require jquery_ujs
//= require jquery.ui.datepicker
//= require jquery.ui.slider
//= require jquery-ui-sliderAccess
//= require jquery-ui-timepicker-addon
//= require jquery-ui-timepicker-addon.min
//= require jquery.validate
//= require jquery.validate.additional-methods
//= require jquery.ui.effect
//= require jquery.ui.selectable
//= require jquery.ui.accordion
//= require turbolinks
//= require_self
//= require_directory .

// Touch this code and die
window.onLoad = function(callback) {
    // binds ready event and turbolink page:load event
    $(document).ready(callback);
    $(document).on('page:load',   callback);
};

onLoad(function() {

    var table =  $('.default_table').dataTable({
        "bPaginate" : false,
        "iCookieDuration": 60,
        "bStateSave": false,
        "bAutoWidth": false,
        "bScrollAutoCss": true,
        "bProcessing": true,
        "bRetrieve": true,
        "bJQueryUI": true,
        "sDom": '<"H"CTrf>t<"F"lip>',
        "sScrollXInner": "110%",
        "fnInitComplete": function() {
            this.css("visibility", "visible");
        },
        "fnPreDrawCallback": $(".autoHide").hide()
    }, $(".defaultTooltip").tooltip({
        'selector': '',
        'placement': 'left',
        'container': 'body'
    }));

    $('table.default_table').each(function(i,table) {
        $('

').append($(table)).insertAfter($('#' + $(table).attr('id') + '_wrapper div').first());
    });

    return table;
});

    function overridePrioritySort(){

      // The following is a custom override of the column sorting so that the tickets will push high, medium, and low to the top of the column
      var priorities = ['high', 'medium', 'low'];
      var index      = 0;
      var ascFlag    = true;
      var descFlag   = true;

      var priorityArray = {};
      priorityArray['High']   = 0;
      priorityArray['Medium'] =-1;
      priorityArray['Low']    = 1;

      function updatePriorityArray(){
        priorityArray['High']   = ((priorityArray['High']   + 2) % 3) - 1;
        priorityArray['Medium'] = ((priorityArray['Medium'] + 2) % 3) - 1;
        priorityArray['Low']    = ((priorityArray['Low']    + 2) % 3) - 1;
      }

      // Both the ascending function and descending function have to be overridden since they are called in alternate.
      jQuery.fn.dataTableExt.oSort['priority-asc'] = function(x,y) {

        if (descFlag) { // This prevents the the priority array from going moving more than once per cycle since this function gets called multiple times during the sort.
          index++;
          index   %= priorities.length;
          ascFlag  = true;
          descFlag = false;
          updatePriorityArray();
        }
        var currentPriority = priorities[index];

        // This strips out the span tags I added to the td. - Rob
        x = $(x).text();
        y = $(y).text();

        if (x == (currentPriority) && y == (currentPriority))
          return 0;
        else if (x == (currentPriority))
          return -1;
        else if (y == (currentPriority))
          return 1;
        else
          return ((priorityArray[x] < priorityArray[y]) ?  1 : ((priorityArray[x] > priorityArray[y]) ? -1: 0 ) );
      };

      // This one too
      jQuery.fn.dataTableExt.oSort['priority-desc'] = function(x,y) {

        if (ascFlag) {
          index++;
          index   %= priorities.length;
          ascFlag  = false;
          descFlag = true;
          updatePriorityArray();
        }
        var currentPriority = priorities[index];

        // This strips out the span tags I added to the td. - Rob
        x = $(x).text();
        y = $(y).text();

        if (x == (currentPriority) && y == (currentPriority))
          return 0;
        else if (x == (currentPriority))
          return -1;
        else if (y == (currentPriority))
          return 1;
        else
          return ((priorityArray[x] < priorityArray[y]) ?  1 : ((priorityArray[x] > priorityArray[y]) ? -1: 0 ) );
      };
    }<|endoftext|>


<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//= require jquery.js
//# require jquery.min.js
//= require jquery.tipTip.js
//= require humane.js
//= require jquery_ujs.js
//# require jquery-ui.js
//# require prototip.js
//= require domains
//= require domain_templates
//= require users
//= require views
//= require audits
//= require bind
//= require_self

$(document).ready(function() {
    // ----------------- ajax activity indicator -----------------
    $('body').append('
<img src="<%= image_path('loading.gif') %>"/>
');
    // $('body').append('

');

    // setup tooltips where required
    $('.help-icon').each(function(i, icon){
        $(icon).tipTip({
            content: $( "#" + $(icon).data("help") ).text()
        });
    });

    // ----------------- setup tooltips of search boxes -----------------
    $('.search-field').each(function(i, field) {
        $(field).tipTip({
            content: $("#" + $(field).data("help")).text(),
			delay: 2000,
			activation: "click"
        });
    });

	// ----------------- ajax flash messages -----------------
	var flashMessageDelay = {
		error:   5000,
		warning: 5000,
		notice:  2000
	};
	var flashMessageIcon = {
		error:   'warning-sign',
		warning: 'warning-sign',
		notice:  'info-sign'
	};
	$.fn.flashMessage = function(message, messageType, delay) {
		var container = $('.flash-ajax.flash-' + messageType);
		if (container.length == 0) {
			if (console) console.log('creating flash container (type: ' + messageType + ')');
			var container = $('

');
			container.hide();
			$('body').append(container);
		}
		container.find('.message').html(message);
		container.fadeIn().delay(delay || flashMessageDelay[messageType]).fadeOut('slow');
	};

	// ----------------- ajax pagination ---------------
	// will_paginate does not support link attributes yet.
	// See: https://github.com/mislav/will_paginate/pull/100
	$('.pagination a').live('click', function () {
		$.rails.handleRemote($(this));
		return false;
	});
});

// ajax activity indicator bound to ajax start/stop document events
$(document).ajaxStart(function() {
    $('#ajaxBusy').show();
}).ajaxStop(function(){
    $('#ajaxBusy').hide();
});

$(document).ajaxComplete(function(evt, xhr, options) {
	var message     = xhr.getResponseHeader('x-flash');
	var messageType = xhr.getResponseHeader('x-flash-type');

	if (message && messageType)
		$.fn.flashMessage(message, messageType);
});

//* rest of file omitted */
<commit_msg>atualiza a img 'loading.gif' como asset<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//= require jquery.js
//# require jquery.min.js
//= require jquery.tipTip.js
//= require humane.js
//= require jquery_ujs.js
//# require jquery-ui.js
//# require prototip.js
//= require domains
//= require domain_templates
//= require users
//= require views
//= require audits
//= require bind
//= require_self

$(document).ready(function() {
    // ----------------- ajax activity indicator -----------------
    // $('body').append('
<img src="<%= image_path('loading.gif') %>"/>
');
    $('body').append('

');

    // setup tooltips where required
    $('.help-icon').each(function(i, icon){
        $(icon).tipTip({
            content: $( "#" + $(icon).data("help") ).text()
        });
    });

    // ----------------- setup tooltips of search boxes -----------------
    $('.search-field').each(function(i, field) {
        $(field).tipTip({
            content: $("#" + $(field).data("help")).text(),
			delay: 2000,
			activation: "click"
        });
    });

	// ----------------- ajax flash messages -----------------
	var flashMessageDelay = {
		error:   5000,
		warning: 5000,
		notice:  2000
	};
	var flashMessageIcon = {
		error:   'warning-sign',
		warning: 'warning-sign',
		notice:  'info-sign'
	};
	$.fn.flashMessage = function(message, messageType, delay) {
		var container = $('.flash-ajax.flash-' + messageType);
		if (container.length == 0) {
			if (console) console.log('creating flash container (type: ' + messageType + ')');
			var container = $('

');
			container.hide();
			$('body').append(container);
		}
		container.find('.message').html(message);
		container.fadeIn().delay(delay || flashMessageDelay[messageType]).fadeOut('slow');
	};

	// ----------------- ajax pagination ---------------
	// will_paginate does not support link attributes yet.
	// See: https://github.com/mislav/will_paginate/pull/100
	$('.pagination a').live('click', function () {
		$.rails.handleRemote($(this));
		return false;
	});
});

// ajax activity indicator bound to ajax start/stop document events
$(document).ajaxStart(function() {
    $('#ajaxBusy').show();
}).ajaxStop(function(){
    $('#ajaxBusy').hide();
});

$(document).ajaxComplete(function(evt, xhr, options) {
	var message     = xhr.getResponseHeader('x-flash');
	var messageType = xhr.getResponseHeader('x-flash-type');

	if (message && messageType)
		$.fn.flashMessage(message, messageType);
});

//* rest of file omitted */
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require foundation
//= require pickadate/picker
//= require pickadate/picker.date
//= require pickadate/picker.time
//= require_tree .

$(function(){ $(document).foundation(); });

$( document ).ready(function() {
  $('.datepicker').pickadate();
  $('.timepicker').pickatime({
    min: [17,00],
    max: [24,00]
  });
});

<commit_msg>moved timepicker to 8am instead of 6pm<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require foundation
//= require pickadate/picker
//= require pickadate/picker.date
//= require pickadate/picker.time
//= require_tree .

$(function(){ $(document).foundation(); });

$( document ).ready(function() {
  $('.datepicker').pickadate();
  $('.timepicker').pickatime({
    min: [9,00],
    max: [24,00]
  });
});

<|endoftext|>


<commit_before>(function() {

    var formCheckValid = function(el) {
        var inputType = (el.tagName.toLowerCase() == 'textarea') ? 'textarea' : $(el).attr('type');

        switch (inputType) {
            case 'radio':
            case 'checkbox':
                return (el.checked) ? el.name : null;
                break;
            case 'text':
            case 'number':
            case 'textarea':
                var pattern = (pattern = $(el).attr('data-pattern')) ? pattern : $(el).attr('pattern');
                if (pattern != null) {
                    var result = $(el).val().match(new RegExp(pattern,"gi"));
                    return (result!= null && result.length > 0 && result[0] != '') ?el.name : null;
                } else {
                    return ($(el).val() != '') ? el.name : null;
                }
                break;
            default:
                return null;
        }
    };

    $(document).ready(function() {
        $('a.previousPage').each(function() {
            $(this).on('click', function() {
                if (!confirm('Are you sure you want to go back? You may lose form data.\n\nNB: We need to assess the need and functionality of this link')) {
                    return false;
                }
            });

        });

        /* display-none-js is a class that should only work to hide information when javascript is enabled */
        $('.display-none-js').hide();

        /* generic toggle functionality */
        $('.toggle-section').on('click', function() {
            var sections = $(this).parents('.form-group').attr('data-target');
            var sectionOn = $(this).parents('.form-group').attr('data-target') + '__' + $(this).val().toLowerCase();
            $('.' + sections).hide();
            $('.' + sectionOn).show();
        });

        $('form.crm-check').on('submit', function(e) {

            //e.preventDefault();
            var form = $(this),
                validationMessage = '',
                errorMessages = '',
                validationType = '',
                inputFields = ['input[type="text"]', 'input[type="number"]', 'input[type="checkbox"]', 'input[type="radio"]', 'select', 'textarea'],
                fieldsWithValidValue,
                fields;

            form.find('div.validation-message').remove();

            // loop each validation-group
            form.find('.validation-group:visible').each(function() {

                validationType = $(this).attr('data-validation-type');
                validationMessage = $(this).attr('data-validation-message');

                var tmp = ['required--one-or-more', 'required--one', 'required--all']
                if (tmp.indexOf(validationType) != -1) {
                    fieldsWithValidValue = $.unique($(this).removeClass('invalid').find(inputFields.join(',')).map(function () {
                        return formCheckValid(this);
                    }).get());
                }

                switch (validationType) {
                    case 'required--one-or-more':
                    case 'required--one':
                        if (fieldsWithValidValue.length == 0) {
                            $(this).addClass('invalid');
                            errorMessages += '
' + validationMessage + '
';
                        }
                        break;

                    case 'required--all':
                        fields = $.unique($(this).removeClass('invalid').find(inputFields.join(',')).map(function() {
                            return this.name;
                        }).get());

                        if (fields.length > fieldsWithValidValue.length) {
                            $(this).addClass('invalid');
                            errorMessages += '
' + validationMessage + '
';
                        }
                        break;

                    case 'required--set':

                        var fields, setOK,
                            setsOK = false,
                            sets = $(this).removeClass('invalid').attr('data-validation-set').split('|');

                        for (var s = 0, sl = sets.length; s < sl; s ++) {

                            fields = sets[s].split(',');
                            setOK = true;
                            for (var f = 0, fl = fields.length; f < fl; f ++) {
                                if (!formCheckValid($(this).find('input[name="' + fields[f] + '"]').get(0))) {
                                    setOK = false;
                                    break;
                                }
                            }
                            if (setOK) {
                                setsOK = true;
                                break;
                            }
                        }
                        if (!setsOK) {
                            $(this).addClass('invalid');
                            errorMessages += '
' + validationMessage + '
';
                        }
                        break;
                }
            });

            if (errorMessages != '') {
                form.find('input[type="submit"]').before('

' + errorMessages + '

');
                return false;
            }

            /* Not ready yet
            // all the validate-groups have been checked - now check the form
            if (formValidationType = form.attr('data-form-validation-type')) {
                switch (formValidationType) {
                    case 'required--set':
                        var groups, groupOK,
                            setsOK = false,
                            sets = $(form).removeClass('invalid').attr('data-form-validation-set').split('|');

                        console.log(sets);

                        for (var s = 0, sl = sets.length; s < sl; s ++) {

                            groups = sets[s].split(',');
                            groupOK = true;
                            for (var f = 0, fl = groups.length; f < fl; f ++) {
                                if (true ) {
                                    groupOK = false;
                                    break;
                                }
                            }
                            if (groupOK) {
                                setsOK = true;
                                break;
                            }
                        }
                        if (!setsOK) {
                            form.addClass('invalid');
                            errorMessages += '
' + validationMessage + '
';
                        }
                        break;

                    break;
                }
            }
            */

            // MANUAL OVERRIDES HERE
            if (form.attr('id') == 'form__fraud-type') { // redirect to new or old website based on user input
                var redirects = ['disabilityCarers', 'abroad', 'idFraud', 'savingsCapital'];
                var selected = form.find('input[type="checkbox"][name="fraud-type"]:checked').map(function() {
                    return this.value;
                }).get();
                var redirectsSelected = $.grep(selected, function(n) {
                    return ( redirects.indexOf(n) != -1 );
                });
                if (redirectsSelected.length > 0) {
                    e.preventDefault();
                    document.location.href = 'https://secure.dwp.gov.uk/benefitfraud/';
                }
            }

        });

        /* RE 01/04/2015: testing from here onwards. To be deleted */

        $('form.crm-check4').on('submit', function(e) {

            //e.preventDefault();
            var form = $(this),
                validationMessage = '',
                errorMessages = '',
                validationType = '',
                inputFields = ['input[type="text"]', 'input[type="number"]', 'input[type="checkbox"]', 'input[type="radio"]', 'select', 'textarea'],
                fieldsWithValidValue,
                fields;

            form.find('div.validation-message').remove();

            // loop each validation-group
            form.find('.validation-group:visible').each(function() {

                validationType = $(this).attr('data-validation-type');
                validationMessage = $(this).attr('data-validation-message');

                var tmp = ['required--one-or-more', 'required--one', 'required--all']
                if (tmp.indexOf(validationType) != -1) {
                    fieldsWithValidValue = $.unique($(this).removeClass('invalid').find(inputFields.join(',')).map(function () {
                        return formCheckValid(this);
                    }).get());
                }

                switch (validationType) {
                    case 'required--one-or-more':
                    case 'required--one':
                        if (fieldsWithValidValue.length == 0) {
                            $(this).addClass('invalid');
                            errorMessages += '
' + validationMessage + '
';
                        }
                        break;

                    case 'required--all':
                        fields = $.unique($(this).removeClass('invalid').find(inputFields.join(',')).map(function() {
                            return this.name;
                        }).get());

                        if (fields.length > fieldsWithValidValue.length) {
                            $(this).addClass('invalid');
                            errorMessages += '
' + validationMessage + '
';
                        }
                        break;

                }
            });

            if (errorMessages != '') {
                form.find('input[type="submit"]').before('

' + errorMessages + '

');
                return false;
            }

            // MANUAL OVERRIDES HERE

            if (form.attr('id') == 'form__fraud-type') { // redirect to new or old website based on user input
                e.preventDefault();
                var redirects = ['disabilityCarers', 'abroad', 'idFraud', 'savingsCapital'];
                console.log(redirects);
                var selected = form.find('input[type="checkbox"][name="fraud-type"]:checked').map(function() {
                    return this.value;
                }).get();
                console.log(selected);
                var redirectsSelected = $.grep(selected, function(n) {
                    return ( redirects.indexOf(n) != -1 );
                });
                console.log(redirectsSelected);
                console.log(redirectsSelected.length);

                /*if (redirectsSelected.length > 0) {
                    e.preventDefault();
                    document.location.href = 'https://secure.dwp.gov.uk/benefitfraud/';
                }*/
            }

        });

    });

})();

    /*

    $('form.crm-check-form').on('submit', function(e) {

        var form = $(this), errorMessage = '';

        // check (groups of) checkboxes where (at least) one must be checked
        var ids = $.unique(form.find('.fieldset').removeClass('invalid').find('input[type="checkbox"].required--one-or-more').map(function() {
            return this.name;
        }).get());
        if (ids.length > 0) {
            var idsChecked = $.unique(form.find('input[type="checkbox"].required--one-or-more:checked').map(function () {
                return (this.name);
            }).get());

            if (idsChecked.length < ids.length) { // not all groups of checkboxes have at least one checked
                // report the issue. Filter out the checked IDs
                ids = $.grep(ids, function (n) {
                    return ( idsChecked.indexOf(n) == -1 );
                });

                for (var i = 0, il = ids.length; i < il; i++) {
                    form.find('#fieldset--' + ids[i]).each(function () {
                        $(this).addClass('invalid');
                        errorMessage += '
' + $(this).attr('data-error-message') + '
';

                    });
                };
            }
        }

        // check required radio buttons

        var ids = $.unique(form.find('.fieldset').find('input[type="radio"].required').map(function() {
            return this.name.replace('helper--', '');
        }).get());
        if (ids.length > 0) {
            var idsChecked = $.unique(form.find('input[type="radio"].required:checked').map(function () {
                return this.name.replace('helper--', '');
            }).get());

            if (idsChecked.length < ids.length) { // not all required sets of radio buttons have been ticked
                // report the issue. Filter out the checked IDs
                ids = $.grep(ids, function (n) {
                    return (idsChecked.indexOf(n) == -1);
                });

                for (var i = 0, il = ids.length; i < il; i++) {
                    form.find('#fieldset--' + ids[i]).each(function() {
                        // set the invalid class and add functionality to remove it
                        $(this).addClass('invalid').attr('data-error-id', i).find('input[type="radio"]').each(function() {

                            $(this).on('click', function () {
                                var errorID = $(this).parents('.invalid').removeClass('invalid').attr('data-error-id');
                                $('#error__' + errorID).remove();
                                if (form.find('div.validation-message').find('li').length == 0) {
                                    form.find('div.validation-message').remove();
                                }
                            });
                        });
                        errorMessage += '
' + $(this).attr('data-error-message') + '
';
                    });
                };
            }
        }

        // check required text fields
        var parentNames = [];

        var ids = $.unique(form.find('.fieldset').removeClass('invalid').find('input[type="text"].required:visible, input[type="number"].required:visible').map(function() {
            return this.name.replace('helper--', '');
        }).get());
        console.log(ids);
        if (ids.length > 0) {
            var idsValid = $.unique(form.find('input[type="text"].required:visible, input[type="number"].required:visible').map(function () {
                // TODO: add validation based on regexp
                if ($(this).val() == '') {
                    parentNames.push($(this).attr('data-parent-fieldset'));
                    return null
                } else {
                    return this.name.replace('helper--', '');
                }

            }).get());
console.log(idsValid);
            if (idsValid.length < ids.length) { // not all required sets of radio buttons have been ticked
                // report the issue. Filter out the valid IDs
                ids = $.grep(ids, function (n) {
                    return (idsValid.indexOf(n) == -1);
                });

                console.log(ids);

                for (var i = 0, il = ids.length; i < il; i++) {
                    console.log('invalidating #fieldset--' + ids[i]);
                    form.find('#fieldset--' + ids[i]).each(function () {
                        $(this).addClass('invalid');
                        errorMessage += '
' + $(this).attr('data-error-message') + '
';
                    });
                };
                for (var i = 0, il = parentNames.length; i < il; i++) {
                    console.log('invalidating #fieldset--' + parentNames[i]);
                    form.find('#fieldset--' + parentNames[i]).each(function () {
                        $(this).addClass('invalid');
                        errorMessage += '
' + $(this).attr('data-error-message') + '
';
                    });
                };

            }
            console.log('------');
        }

        if (errorMessage != '') {
            form.find('div.validation-message').remove();
            form.find('input[type="submit"]').before('

' + errorMessage + '

');

            return false
        }

return false;

    });
    */
<commit_msg>WiP: Heroku app fail<commit_after>(function() {

    var formCheckValid = function(el) {
        var inputType = (el.tagName.toLowerCase() == 'textarea') ? 'textarea' : $(el).attr('type');

        switch (inputType) {
            case 'radio':
            case 'checkbox':
                return (el.checked) ? el.name : null;
                break;
            case 'text':
            case 'number':
            case 'textarea':
                var pattern = (pattern = $(el).attr('data-pattern')) ? pattern : $(el).attr('pattern');
                if (pattern != null) {
                    var result = $(el).val().match(new RegExp(pattern,"gi"));
                    return (result!= null && result.length > 0 && result[0] != '') ?el.name : null;
                } else {
                    return ($(el).val() != '') ? el.name : null;
                }
                break;
            default:
                return null;
        }
    };

    $(document).ready(function() {
        $('a.previousPage').each(function() {
            $(this).on('click', function() {
                if (!confirm('Are you sure you want to go back? You may lose form data.\n\nNB: We need to assess the need and functionality of this link')) {
                    return false;
                }
            });

        });

        /* display-none-js is a class that should only work to hide information when javascript is enabled */
        $('.display-none-js').hide();

        /* generic toggle functionality */
        $('.toggle-section').on('click', function() {
            var sections = $(this).parents('.form-group').attr('data-target');
            var sectionOn = $(this).parents('.form-group').attr('data-target') + '__' + $(this).val().toLowerCase();
            $('.' + sections).hide();
            $('.' + sectionOn).show();
        });

        $('form.crm-check').on('submit', function(e) {

            //e.preventDefault();
            var form = $(this),
                validationMessage = '',
                errorMessages = '',
                validationType = '',
                inputFields = ['input[type="text"]', 'input[type="number"]', 'input[type="checkbox"]', 'input[type="radio"]', 'select', 'textarea'],
                fieldsWithValidValue,
                fields;

            form.find('div.validation-message').remove();

            // loop each validation-group
            form.find('.validation-group:visible').each(function() {

                validationType = $(this).attr('data-validation-type');
                validationMessage = $(this).attr('data-validation-message');

                var tmp = ['required--one-or-more', 'required--one', 'required--all']
                if (tmp.indexOf(validationType) != -1) {
                    fieldsWithValidValue = $.unique($(this).removeClass('invalid').find(inputFields.join(',')).map(function () {
                        return formCheckValid(this);
                    }).get());
                }

                switch (validationType) {
                    case 'required--one-or-more':
                    case 'required--one':
                        if (fieldsWithValidValue.length == 0) {
                            $(this).addClass('invalid');
                            errorMessages += '
' + validationMessage + '
';
                        }
                        break;

                    case 'required--all':
                        fields = $.unique($(this).removeClass('invalid').find(inputFields.join(',')).map(function() {
                            return this.name;
                        }).get());

                        if (fields.length > fieldsWithValidValue.length) {
                            $(this).addClass('invalid');
                            errorMessages += '
' + validationMessage + '
';
                        }
                        break;

                    case 'required--set':

                        var fields, setOK,
                            setsOK = false,
                            sets = $(this).removeClass('invalid').attr('data-validation-set').split('|');

                        for (var s = 0, sl = sets.length; s < sl; s ++) {

                            fields = sets[s].split(',');
                            setOK = true;
                            for (var f = 0, fl = fields.length; f < fl; f ++) {
                                if (!formCheckValid($(this).find('input[name="' + fields[f] + '"]').get(0))) {
                                    setOK = false;
                                    break;
                                }
                            }
                            if (setOK) {
                                setsOK = true;
                                break;
                            }
                        }
                        if (!setsOK) {
                            $(this).addClass('invalid');
                            errorMessages += '
' + validationMessage + '
';
                        }
                        break;
                }
            });

            if (errorMessages != '') {
                form.find('input[type="submit"]').before('

' + errorMessages + '

');
                return false;
            }

            /* Not ready yet
            // all the validate-groups have been checked - now check the form
            if (formValidationType = form.attr('data-form-validation-type')) {
                switch (formValidationType) {
                    case 'required--set':
                        var groups, groupOK,
                            setsOK = false,
                            sets = $(form).removeClass('invalid').attr('data-form-validation-set').split('|');

                        console.log(sets);

                        for (var s = 0, sl = sets.length; s < sl; s ++) {

                            groups = sets[s].split(',');
                            groupOK = true;
                            for (var f = 0, fl = groups.length; f < fl; f ++) {
                                if (true ) {
                                    groupOK = false;
                                    break;
                                }
                            }
                            if (groupOK) {
                                setsOK = true;
                                break;
                            }
                        }
                        if (!setsOK) {
                            form.addClass('invalid');
                            errorMessages += '
' + validationMessage + '
';
                        }
                        break;

                    break;
                }
            }
            */

            // MANUAL OVERRIDES HERE
            if (form.attr('id') == 'form__fraud-type') { // redirect to new or old website based on user input
                var redirects = ['disabilityCarers', 'abroad', 'idFraud', 'savingsCapital'];
                var selected = form.find('input[type="checkbox"][name="fraud-type"]:checked').map(function() {
                    return this.value;
                }).get();
                var redirectsSelected = $.grep(selected, function(n) {
                    return ( redirects.indexOf(n) != -1 );
                });
                if (redirectsSelected.length > 0) {
                    e.preventDefault();
                    document.location.href = 'https://secure.dwp.gov.uk/benefitfraud/';
                }
            }

        });

        /* RE 01/04/2015: testing from here onwards. To be deleted */

        $('form.crm-check4').on('submit', function(e) {

            //e.preventDefault();
            var form = $(this),
                validationMessage = '',
                errorMessages = '',
                validationType = '',
                inputFields = ['input[type="text"]', 'input[type="number"]', 'input[type="checkbox"]', 'input[type="radio"]', 'select', 'textarea'],
                fieldsWithValidValue,
                fields;

            form.find('div.validation-message').remove();

            // loop each validation-group
            form.find('.validation-group:visible').each(function() {

                validationType = $(this).attr('data-validation-type');
                validationMessage = $(this).attr('data-validation-message');

                var tmp = ['required--one-or-more', 'required--one', 'required--all']
                if (tmp.indexOf(validationType) != -1) {
                    fieldsWithValidValue = $.unique($(this).removeClass('invalid').find(inputFields.join(',')).map(function () {
                        return formCheckValid(this);
                    }).get());
                }

                switch (validationType) {
                    case 'required--one-or-more':
                    case 'required--one':
                        if (fieldsWithValidValue.length == 0) {
                            $(this).addClass('invalid');
                            errorMessages += '
' + validationMessage + '
';
                        }
                        break;

                    case 'required--all':
                        fields = $.unique($(this).removeClass('invalid').find(inputFields.join(',')).map(function() {
                            return this.name;
                        }).get());

                        if (fields.length > fieldsWithValidValue.length) {
                            $(this).addClass('invalid');
                            errorMessages += '
' + validationMessage + '
';
                        }
                        break;

                }
            });

            if (errorMessages != '') {
                form.find('input[type="submit"]').before('

' + errorMessages + '

');
                return false;
            }

            // MANUAL OVERRIDES HERE
            e.preventDefault();
            if (form.attr('id') == 'form__fraud-type4') {

                var redirects = ['disabilityCarers', 'abroad', 'idFraud', 'savingsCapital'];
                console.log(redirects);
                var selected = form.find('input[type="checkbox"][name="fraud-type"]:checked').map(function() {
                    return this.value;
                }).get();
                console.log(selected);
                var redirectsSelected = $.grep(selected, function(n) {
                    return ( redirects.indexOf(n) != -1 );
                });
                console.log(redirectsSelected);
                console.log(redirectsSelected.length);

                /*if (redirectsSelected.length > 0) {
                    e.preventDefault();
                    document.location.href = 'https://secure.dwp.gov.uk/benefitfraud/';
                }*/
            }
            console.log('the end');

        });

    });

})();

    /*

    $('form.crm-check-form').on('submit', function(e) {

        var form = $(this), errorMessage = '';

        // check (groups of) checkboxes where (at least) one must be checked
        var ids = $.unique(form.find('.fieldset').removeClass('invalid').find('input[type="checkbox"].required--one-or-more').map(function() {
            return this.name;
        }).get());
        if (ids.length > 0) {
            var idsChecked = $.unique(form.find('input[type="checkbox"].required--one-or-more:checked').map(function () {
                return (this.name);
            }).get());

            if (idsChecked.length < ids.length) { // not all groups of checkboxes have at least one checked
                // report the issue. Filter out the checked IDs
                ids = $.grep(ids, function (n) {
                    return ( idsChecked.indexOf(n) == -1 );
                });

                for (var i = 0, il = ids.length; i < il; i++) {
                    form.find('#fieldset--' + ids[i]).each(function () {
                        $(this).addClass('invalid');
                        errorMessage += '
' + $(this).attr('data-error-message') + '
';

                    });
                };
            }
        }

        // check required radio buttons

        var ids = $.unique(form.find('.fieldset').find('input[type="radio"].required').map(function() {
            return this.name.replace('helper--', '');
        }).get());
        if (ids.length > 0) {
            var idsChecked = $.unique(form.find('input[type="radio"].required:checked').map(function () {
                return this.name.replace('helper--', '');
            }).get());

            if (idsChecked.length < ids.length) { // not all required sets of radio buttons have been ticked
                // report the issue. Filter out the checked IDs
                ids = $.grep(ids, function (n) {
                    return (idsChecked.indexOf(n) == -1);
                });

                for (var i = 0, il = ids.length; i < il; i++) {
                    form.find('#fieldset--' + ids[i]).each(function() {
                        // set the invalid class and add functionality to remove it
                        $(this).addClass('invalid').attr('data-error-id', i).find('input[type="radio"]').each(function() {

                            $(this).on('click', function () {
                                var errorID = $(this).parents('.invalid').removeClass('invalid').attr('data-error-id');
                                $('#error__' + errorID).remove();
                                if (form.find('div.validation-message').find('li').length == 0) {
                                    form.find('div.validation-message').remove();
                                }
                            });
                        });
                        errorMessage += '
' + $(this).attr('data-error-message') + '
';
                    });
                };
            }
        }

        // check required text fields
        var parentNames = [];

        var ids = $.unique(form.find('.fieldset').removeClass('invalid').find('input[type="text"].required:visible, input[type="number"].required:visible').map(function() {
            return this.name.replace('helper--', '');
        }).get());
        console.log(ids);
        if (ids.length > 0) {
            var idsValid = $.unique(form.find('input[type="text"].required:visible, input[type="number"].required:visible').map(function () {
                // TODO: add validation based on regexp
                if ($(this).val() == '') {
                    parentNames.push($(this).attr('data-parent-fieldset'));
                    return null
                } else {
                    return this.name.replace('helper--', '');
                }

            }).get());
console.log(idsValid);
            if (idsValid.length < ids.length) { // not all required sets of radio buttons have been ticked
                // report the issue. Filter out the valid IDs
                ids = $.grep(ids, function (n) {
                    return (idsValid.indexOf(n) == -1);
                });

                console.log(ids);

                for (var i = 0, il = ids.length; i < il; i++) {
                    console.log('invalidating #fieldset--' + ids[i]);
                    form.find('#fieldset--' + ids[i]).each(function () {
                        $(this).addClass('invalid');
                        errorMessage += '
' + $(this).attr('data-error-message') + '
';
                    });
                };
                for (var i = 0, il = parentNames.length; i < il; i++) {
                    console.log('invalidating #fieldset--' + parentNames[i]);
                    form.find('#fieldset--' + parentNames[i]).each(function () {
                        $(this).addClass('invalid');
                        errorMessage += '
' + $(this).attr('data-error-message') + '
';
                    });
                };

            }
            console.log('------');
        }

        if (errorMessage != '') {
            form.find('div.validation-message').remove();
            form.find('input[type="submit"]').before('

' + errorMessage + '

');

            return false
        }

return false;

    });
    */
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require foundation
//= require turbolinks
//= require_tree .
$(function(){ $(document).foundation(); });
<commit_msg>Remove code from Application.js to remedy errors seen in browser console<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require foundation
//= require turbolinks
//= require_tree .
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require twitter/bootstrap
//= require canvas-snow
//= require_tree .
<commit_msg>Removed canvas snow reference<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require twitter/bootstrap
//= require_tree .
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .
<commit_msg>Add d3<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree
//= require d3
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
//= require jquery
//= require jquery-ui
//= require jquery_ujs
//= require bootstrap.min
//= require jquery.flot.min
//= require jquery.flot.selection.min
//= require_tree .
<commit_msg>requere flot valuelabels<commit_after>// This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
//= require jquery
//= require jquery-ui
//= require jquery_ujs
//= require bootstrap.min
//= require jquery.flot.min
//= require jquery.flot.selection.min
//= require jquery.flot.valuelabels
//= require_tree .
<|endoftext|>


<commit_before>//= require govuk_publishing_components/dependencies

//= require govuk_publishing_components/lib/cookie-functions
//= require govuk_publishing_components/lib/header-navigation

//= require analytics

//= require govuk_publishing_components/components/cookie-banner
//= require govuk_publishing_components/components/layout-header
//= require govuk_publishing_components/components/layout-super-navigation-header
//= require govuk_publishing_components/components/feedback

//= require modules/global-bar
//= require modules/cross-domain-tracking

//= require global-bar-init
//= require surveys
<commit_msg>Remove redundant header-navigation import<commit_after>//= require govuk_publishing_components/dependencies

//= require govuk_publishing_components/lib/cookie-functions

//= require analytics

//= require govuk_publishing_components/components/cookie-banner
//= require govuk_publishing_components/components/layout-header
//= require govuk_publishing_components/components/layout-super-navigation-header
//= require govuk_publishing_components/components/feedback

//= require modules/global-bar
//= require modules/cross-domain-tracking

//= require global-bar-init
//= require surveys
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//
// Loads all Bootstrap javascripts
//= require bootstrap
//
// Just the core of AngularJS
//= require angular
//
//= require_tree .<commit_msg>Add angular-route<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//
// Loads all Bootstrap javascripts
//= require bootstrap
//
// Just the core of AngularJS
//= require angular
//= require angular-route
//
//= require_tree .<|endoftext|>


<commit_before>import React, { Component } from 'react';
import AboutPage from '../components/AboutPage';
import { connect } from 'react-redux';
import { nextPost } from '../actions';

// Smart component
class AboutPageContainer extends Component {
    constructor(props) {
        super(props);

        this.handleNextPost = this.handleNextPost.bind(this);
    }

    componentWillMount() {
        const { dispatch } = this.props;
        dispatch(nextPost());
    }

    handleNextPost() {
        console.log('handleNextPost props: ', this.props);
        const { dispatch } = this.props;
        dispatch(nextPost());
    }

    render() {
        console.log('AboutPageContainer props: ', this.props);
        const { post } = this.props;

        return (<AboutPage post={post} onNextPost={this.handleNextPost} />);
    }
}

// We need to connect it to Redux store
export default connect(
    (state) => {
        return {
            post: state.dummyReducer
        }
    }
)(AboutPageContainer);

<commit_msg>Bind dispatch to action creators to AboutPageContainer<commit_after>import React, { Component } from 'react';
import AboutPage from '../components/AboutPage';
import { connect } from 'react-redux';
import * as postActions from '../actions';
import { bindActionCreators } from 'redux';

// Smart component
class AboutPageContainer extends Component {
    constructor(props) {
        super(props);
    }

    componentWillMount() {
        this.props.nextPost();
    }

    render() {
        console.log('AboutPageContainer props: ', this.props);
        const { post, nextPost } = this.props;

        return (<AboutPage post={post} onNextPost={nextPost} />);
    }
}

// We need to connect it to Redux store
export default connect(
    (state) => {
        return {
            post: state.dummyReducer
        }
    },
    postActions
)(AboutPageContainer);

<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require algolia/algoliasearch.min
//= require_tree .

(function($) {
  window.HNSearch = function(applicationID, apiKey, indexName) {
    this.init(applicationID, apiKey, indexName);
  }

  HNSearch.prototype = {
    init: function(applicationID, apiKey, indexName) {
      var self = this;

      this.idx = new AlgoliaSearch(applicationID, apiKey, null, true, [applicationID + '-2.algolia.io', applicationID + '-3.algolia.io']).initIndex(indexName);
      this.$hits = $('#hits');
      this.page = 0;
      this.currentHit = null;

      $(window).scroll(function () {
        if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
          self.search(self.page + 1);
        }
      });

      $('#inputfield input').keyup(function(e) {
        switch (e.keyCode) {
          case 13: return self.goCurrent();
          case 27: $('#inputfield input').val(''); break;
          case 37: return self.goLeft();
          case 38: return self.goUp();
          case 39: return self.goRight();
          case 40: return self.goDown();
          default: break;
        }
        self.page = 0;
        self.currentHit = null;
        self.search(0);
      });

      // backward compatibility
      if (window.location.hash) {
        // #request/all&q=foobar
        var hash = window.location.hash.substring(1);
        if (hash.indexOf('q=') > -1) {
          $('#inputfield input').val(hash.substring(hash.indexOf('q=') + 2));
        }
      }

      if ($('#inputfield input').val() !== '') {
        this.search(0);
      } else {
        $('#inputfield input').focus();

        // resolve DNS
        this.idx.search('', function(success, content) { });
      }
    },

    search: function(p) {
      if ((this.page > 0 && p <= this.page) || this.page > 50) {
        // hard limit
        return;
      }

      var query = $('#inputfield input').val().trim();
      if (query.length == 0) {
        this.$hits.empty();
        return;
      }

      var self = this;
      this.idx.search(query, function(success, content) { self.searchCallback(success, content); }, { hitsPerPage: 25, page: p, getRankingInfo: 1 });
    },

    goLeft: function() {
    },

    goRight: function() {
    },

    goDown: function() {
      if (!this.go('next')) {
        this.search(this.page + 1);
      }
    },

    goUp: function() {
      if (!this.go('prev')) {
        this.currentHit.removeClass('active');
        this.currentHit = null;
      }
    },

    goCurrent: function() {
      if (!this.currentHit) {
        window.location.href = '/?q=' + encodeURI($('#inputfield input').val());
        return;
      }
      window.location.href = 'http://news.ycombinator.com/item?id=' + this.currentHit.data('id');
    },

    go: function(selectFunction) {
      if (!this.currentHit) {
        this.currentHit = $(this.$hits.children('.hit:first-child')[0]);
      } else {
        var next = this.currentHit[selectFunction]();
        if (next.length == 0) {
          return false;
        }
        this.currentHit.removeClass('active');
        this.currentHit = next;
      }
      this.currentHit.addClass('active');
      var target = this.currentHit.offset().top - this.$hits.offset().top;
      $('html, body').scrollTop(target);
      return true;
    },

    searchCallback: function(success, content) {
      if (!success) {
        console.log(content);
        return;
      }

      if (content.query.trim() != $('#inputfield input').val().trim()) {
        return;
      }
      if (this.page != 0 && this.page >= content.page) {
        return;
      }
      this.page = content.page;
      var res = '';
      for (var i = 0; i < content.hits.length; ++i) {
        var hit = content.hits[i];
        var type = hit._tags[0]; // first tag stores the item type
        var item_url = 'https://news.ycombinator.com/item?id=' + (hit.story_id ? hit.story_id : hit.objectID);

        // look & feel
        var classes = ['hit'];
        /// cosmetics
        if ((i % 2) == 1) {
          classes.push('odd');
        }
        /// type
        classes.push(type);
        /// relevancy
        var nbWords = content.query.split(/[\s\.,-\/#!$%\^&\*;:{}=\-_`~()]+/g).length;
        if (hit._rankingInfo.nbTypos === 0 && (nbWords === 1 || hit._rankingInfo.nbExactWords >= nbWords)) {
          classes.push('notypo');
        }
        if (hit.points > 1000) {
          classes.push('p1000');
        } else if (hit.points > 500) {
          classes.push('p500');
        } else if (hit.points > 250) {
          classes.push('p250');
        } else if (hit.points > 100) {
          classes.push('p100');
        }

        // content
        res +=  '
' +
          '
' + hit._highlightResult.author.value + '
';
        if (type === 'story' || type === 'poll') {
          res += '

' +
            '
' +
            '
' + hit._highlightResult.title.value + '
';
          if (hit.url) {
            res += '
' + hit._highlightResult.url.value + '
';
          } else {
            res += '
' + item_url + '
';
          }
          if (hit.story_text) {
            res += '
' + hit._highlightResult.story_text.value.replace(/(\\r)?\\n/g, '
') + '
';
          }
          res += '
' +
            '

';
          var a = $('', { href: (hit.url || item_url) } )[0];
          res += '
' + a.hostname + '
';
        } else if (type === 'comment') {
          if (hit.story_id) {
            res += '

';
            res += '
';
          }
          if (hit.story_title) {
            res += '
' + hit.story_title + '
';
          }
          res += '
';
          res += '    ' + item_url + '';
          if (hit.story_url) {
            res += ' (' + hit.story_url + ')';
          }
          res += '
';
          res += '
' + hit._highlightResult.comment_text.value.replace(/(\\r)?\\n/g, '
') + '
';
          if (hit.story_id) {
            res += '
';
          }
          res += '

';
        }
        res += '

' +
          '
' + hit.points + ' point' + (hit.points > 1 ? 's' : '') + '
';
        if (type === 'story') {
          res += '
' + hit.num_comments + ' comment' + (hit.num_comments > 1 ? 's' : '') + '
';
        }
        res += '

' +
          '
';
      }
      if (content.page === 0) {
        this.$hits.html(res);
      } else {
        this.$hits.append(res);
      }
      $('#hits .timeago').timeago();
    }

  }
})(jQuery);

<commit_msg>Do not try to load the next page so often<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require algolia/algoliasearch.min
//= require_tree .

(function($) {
  window.HNSearch = function(applicationID, apiKey, indexName) {
    this.init(applicationID, apiKey, indexName);
  }

  HNSearch.prototype = {
    init: function(applicationID, apiKey, indexName) {
      var self = this;

      this.idx = new AlgoliaSearch(applicationID, apiKey, null, true, [applicationID + '-2.algolia.io', applicationID + '-3.algolia.io']).initIndex(indexName);
      this.$hits = $('#hits');
      this.page = 0;
      this.currentHit = null;
      this.lastPageAt = new Date().getTime();

      $(window).scroll(function () {
        if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
          if (new Date().getTime() - self.lastPageAt > 1000) {
            self.search(self.page + 1);
            self.lastPageAt = new Date().getTime();
          }
        }
      });

      $('#inputfield input').keyup(function(e) {
        switch (e.keyCode) {
          case 13: return self.goCurrent();
          case 27: $('#inputfield input').val(''); break;
          case 37: return self.goLeft();
          case 38: return self.goUp();
          case 39: return self.goRight();
          case 40: return self.goDown();
          default: break;
        }
        self.page = 0;
        self.currentHit = null;
        self.search(0);
      });

      // backward compatibility
      if (window.location.hash) {
        // #request/all&q=foobar
        var hash = window.location.hash.substring(1);
        if (hash.indexOf('q=') > -1) {
          $('#inputfield input').val(hash.substring(hash.indexOf('q=') + 2));
        }
      }

      if ($('#inputfield input').val() !== '') {
        this.search(0);
      } else {
        $('#inputfield input').focus();

        // resolve DNS
        this.idx.search('', function(success, content) { });
      }
    },

    search: function(p) {
      if ((this.page > 0 && p <= this.page) || this.page > 50) {
        // hard limit
        return;
      }

      var query = $('#inputfield input').val().trim();
      if (query.length == 0) {
        this.$hits.empty();
        return;
      }

      var self = this;
      this.idx.search(query, function(success, content) { self.searchCallback(success, content); }, { hitsPerPage: 25, page: p, getRankingInfo: 1 });
    },

    goLeft: function() {
    },

    goRight: function() {
    },

    goDown: function() {
      if (!this.go('next')) {
        this.search(this.page + 1);
      }
    },

    goUp: function() {
      if (!this.go('prev')) {
        this.currentHit.removeClass('active');
        this.currentHit = null;
      }
    },

    goCurrent: function() {
      if (!this.currentHit) {
        window.location.href = '/?q=' + encodeURI($('#inputfield input').val());
        return;
      }
      window.location.href = 'http://news.ycombinator.com/item?id=' + this.currentHit.data('id');
    },

    go: function(selectFunction) {
      if (!this.currentHit) {
        this.currentHit = $(this.$hits.children('.hit:first-child')[0]);
      } else {
        var next = this.currentHit[selectFunction]();
        if (next.length == 0) {
          return false;
        }
        this.currentHit.removeClass('active');
        this.currentHit = next;
      }
      this.currentHit.addClass('active');
      var target = this.currentHit.offset().top - this.$hits.offset().top;
      $('html, body').scrollTop(target);
      return true;
    },

    searchCallback: function(success, content) {
      if (!success) {
        console.log(content);
        return;
      }

      if (content.query.trim() != $('#inputfield input').val().trim()) {
        return;
      }
      if (this.page != 0 && this.page >= content.page) {
        return;
      }
      this.page = content.page;
      var res = '';
      for (var i = 0; i < content.hits.length; ++i) {
        var hit = content.hits[i];
        var type = hit._tags[0]; // first tag stores the item type
        var item_url = 'https://news.ycombinator.com/item?id=' + (hit.story_id ? hit.story_id : hit.objectID);

        // look & feel
        var classes = ['hit'];
        /// cosmetics
        if ((i % 2) == 1) {
          classes.push('odd');
        }
        /// type
        classes.push(type);
        /// relevancy
        var nbWords = content.query.split(/[\s\.,-\/#!$%\^&\*;:{}=\-_`~()]+/g).length;
        if (hit._rankingInfo.nbTypos === 0 && (nbWords === 1 || hit._rankingInfo.nbExactWords >= nbWords)) {
          classes.push('notypo');
        }
        if (hit.points > 1000) {
          classes.push('p1000');
        } else if (hit.points > 500) {
          classes.push('p500');
        } else if (hit.points > 250) {
          classes.push('p250');
        } else if (hit.points > 100) {
          classes.push('p100');
        }

        // content
        res +=  '
' +
          '
' + hit._highlightResult.author.value + '
';
        if (type === 'story' || type === 'poll') {
          res += '

' +
            '
' +
            '
' + hit._highlightResult.title.value + '
';
          if (hit.url) {
            res += '
' + hit._highlightResult.url.value + '
';
          } else {
            res += '
' + item_url + '
';
          }
          if (hit.story_text) {
            res += '
' + hit._highlightResult.story_text.value.replace(/(\\r)?\\n/g, '
') + '
';
          }
          res += '
' +
            '

';
          var a = $('', { href: (hit.url || item_url) } )[0];
          res += '
' + a.hostname + '
';
        } else if (type === 'comment') {
          if (hit.story_id) {
            res += '

';
            res += '
';
          }
          if (hit.story_title) {
            res += '
' + hit.story_title + '
';
          }
          res += '
';
          res += '    ' + item_url + '';
          if (hit.story_url) {
            res += ' (' + hit.story_url + ')';
          }
          res += '
';
          res += '
' + hit._highlightResult.comment_text.value.replace(/(\\r)?\\n/g, '
') + '
';
          if (hit.story_id) {
            res += '
';
          }
          res += '

';
        }
        res += '

' +
          '
' + hit.points + ' point' + (hit.points > 1 ? 's' : '') + '
';
        if (type === 'story') {
          res += '
' + hit.num_comments + ' comment' + (hit.num_comments > 1 ? 's' : '') + '
';
        }
        res += '

' +
          '
';
      }
      if (content.page === 0) {
        this.$hits.html(res);
      } else {
        this.$hits.append(res);
      }
      $('#hits .timeago').timeago();
    }

  }
})(jQuery);

<|endoftext|>


<commit_before>import React, {Component} from "react";
import { connect } from "react-redux";
import {get, findIndex, each} from "lodash";

import Spinner from "react-spinner";

import {
  loadMoments,
  loadTranscripts,
  loadAudio
} from "../../actions";

import {
  MomentPlayer,
  Timeline,
  MomentNote
} from "../../components";

class MomentViewer extends Component {
  componentWillMount() {
    this.props.loadMoments({
      momentId: this.props.currentMomentId
    });
    this.props.loadTranscripts({
      momentId: this.props.currentMomentId
    });
  }

  render() {
    const {
      currentMoment,
      currentMission,
      loading,
      currentTranscripts,
      loadAudio
    } = this.props;
    if (loading) {
      return

Loading moment...

        <Spinner />

;
    }

    if (!currentMoment) {
      return

        Error fetching moment.

;
    }

    const {time, playing, audio} = this.props.currentAudio;
    const currentMissionTime = this.props.currentMoment.metStart + (time * 1000);
    let activeIndex = findIndex(currentTranscripts.transcripts, function(i) {
      return i.startTime > currentMissionTime;
    });

    //this is bad, but necessary until I can think of a clever solution
    each(currentTranscripts.transcripts, function(i) {
      i.active = false;
    });

    activeIndex -= 1;
    if(activeIndex >= 0) {
      currentTranscripts.transcripts[activeIndex].active = true;
    }
    const timelineClickEvent = function(startTime) {
      if(metStart) {
        loadAudio({
          time: (startTime - metStart) / 1000
        });
      }
    };

    const {
      title,
      audioUrl,
      metStart,
      metEnd
    } = currentMoment;
    const missionLength = currentMission.length;
    return (

        <MomentPlayer
          title={title}
          url={audioUrl}
          start={metStart}
          end={metEnd}
          audio={audio}
          time={time}
          playing={playing}
          loadAudio={loadAudio}
          missionLength={missionLength} />

          <Timeline timeline={currentTranscripts.transcripts} clickEvent={timelineClickEvent}/>
          <MomentNote note={[]} />

    );
  }
}

function mapStateToProps(state) {
  const {audio} = state;
  const { id } = state.router.params;
  const { loading, entities } = state.moments;
  if (loading) {
    return {
      currentMomentId: id,
      loading
    };
  }
  const transcripts = state.transcripts;
  const { moments, missions } = entities;
  const moment = get(moments, id);
  const mission = get(missions, moment.mission);
  return {
    currentMomentId: id,
    loading,
    currentMission: mission,
    currentMoment: moment,
    currentTranscripts: transcripts,
    currentAudio: audio
  };
}

export default connect(mapStateToProps, {
  loadMoments,
  loadTranscripts,
  loadAudio
})(MomentViewer);
<commit_msg>Seek audio from transcript click.<commit_after>import React, {Component} from "react";
import { connect } from "react-redux";
import {get, findIndex, each} from "lodash";

import Spinner from "react-spinner";

import {
  loadMoments,
  loadTranscripts,
  loadAudio
} from "../../actions";

import {
  MomentPlayer,
  Timeline,
  MomentNote
} from "../../components";

class MomentViewer extends Component {
  componentWillMount() {
    this.props.loadMoments({
      momentId: this.props.currentMomentId
    });
    this.props.loadTranscripts({
      momentId: this.props.currentMomentId
    });
  }

  render() {
    const {
      currentMoment,
      currentMission,
      loading,
      currentTranscripts,
      loadAudio
    } = this.props;
    if (loading) {
      return

Loading moment...

        <Spinner />

;
    }

    if (!currentMoment) {
      return

        Error fetching moment.

;
    }

    const {time, playing, audio} = this.props.currentAudio;
    const currentMissionTime = this.props.currentMoment.metStart + (time * 1000);
    let activeIndex = findIndex(currentTranscripts.transcripts, function(i) {
      return i.startTime > currentMissionTime;
    });

    //this is bad, but necessary until I can think of a clever solution
    each(currentTranscripts.transcripts, function(i) {
      i.active = false;
    });

    activeIndex -= 1;
    if(activeIndex >= 0) {
      currentTranscripts.transcripts[activeIndex].active = true;
    }
    const timelineClickEvent = function(startTime) {
      let seekTime = (startTime - metStart) / 1000
      audio.currentTime = seekTime
      if(metStart) {
        loadAudio({
          time: seekTime
        });
      }
    };

    const {
      title,
      audioUrl,
      metStart,
      metEnd
    } = currentMoment;
    const missionLength = currentMission.length;
    return (

        <MomentPlayer
          title={title}
          url={audioUrl}
          start={metStart}
          end={metEnd}
          audio={audio}
          time={time}
          playing={playing}
          loadAudio={loadAudio}
          missionLength={missionLength} />

          <Timeline timeline={currentTranscripts.transcripts} clickEvent={timelineClickEvent}/>
          <MomentNote note={[]} />

    );
  }
}

function mapStateToProps(state) {
  const {audio} = state;
  const { id } = state.router.params;
  const { loading, entities } = state.moments;
  if (loading) {
    return {
      currentMomentId: id,
      loading
    };
  }
  const transcripts = state.transcripts;
  const { moments, missions } = entities;
  const moment = get(moments, id);
  const mission = get(missions, moment.mission);
  return {
    currentMomentId: id,
    loading,
    currentMission: mission,
    currentMoment: moment,
    currentTranscripts: transcripts,
    currentAudio: audio
  };
}

export default connect(mapStateToProps, {
  loadMoments,
  loadTranscripts,
  loadAudio
})(MomentViewer);
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
//= require jquery
//= require jquery_ujs
//= require_tree .

// Application specific behaviour
function addAlternateTableBehaviour() {
  $("table.list tr:odd").addClass("odd");
}

// Dirty Form
function addDirtyForm() {
  $(".form-view form").dirty_form()
    .dirty(function(event, data){
      var buttons = $(this).find("fieldset.buttons");
      buttons.fadeIn();
    })
}

// Initialize behaviours
function initializeBehaviours() {
  // from cyt.js
  addComboboxBehaviour();
  addAutofocusBehaviour();
  addDatePickerBehaviour();
  addSortableBehaviour();
  addLinkifyContainersBehaviour();
  addOverviewTooltipBehaviour();
  addIconTooltipBehaviour();
  addTimeCheckBehaviour();

  // application
  addAlternateTableBehaviour();
  addDirtyForm();
}

// Loads functions after DOM is ready
$(document).ready(initializeBehaviours);
<commit_msg>Show view-form in edit mode on input field focus.<commit_after>// This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
//= require jquery
//= require jquery_ujs
//= require_tree .

// Application specific behaviour
function addAlternateTableBehaviour() {
  $("table.list tr:odd").addClass("odd");
}

// Dirty Form
function makeEditForm(form) {
  var buttons = form.find("fieldset.buttons");
  buttons.fadeIn('slow');
}

function addDirtyForm() {
  $(".form-view form").dirty_form()
    .dirty(function(event, data){
      makeEditForm($(this));
    })

  $(".form-view").focusin(function() {makeEditForm($(this))});
}

// Initialize behaviours
function initializeBehaviours() {
  // from cyt.js
  addComboboxBehaviour();
  addAutofocusBehaviour();
  addDatePickerBehaviour();
  addSortableBehaviour();
  addLinkifyContainersBehaviour();
  addOverviewTooltipBehaviour();
  addIconTooltipBehaviour();
  addTimeCheckBehaviour();

  // application
  addAlternateTableBehaviour();
  addDirtyForm();
}

// Loads functions after DOM is ready
$(document).ready(initializeBehaviours);
<|endoftext|>