<commit_before>
var recents = { };
var current_document;
var current_section;

var KEY_LEFT = 37;
var KEY_UP = 38;
var KEY_RIGHT = 39;
var KEY_DOWN = 40;
var KEY_RETURN = 13;

(function(){
  var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;

  // The base Class implementation (does nothing)
  this.Class = function(){};

  // Create a new Class that inherits from this class
  Class.extend = function(prop) {
    var _super = this.prototype;

    // Instantiate a base class (but only create the instance,
    // don't run the init constructor)
    initializing = true;
    var prototype = new this();
    initializing = false;

    // Copy the properties over onto the new prototype
    for (var name in prop) {
      // Check if we're overwriting an existing function
      prototype[name] = typeof prop[name] == "function" &&
        typeof _super[name] == "function" && fnTest.test(prop[name]) ?
        (function(name, fn){
          return function() {
            var tmp = this._super;

            // Add a new ._super() method that is the same method
            // but on the super-class
            this._super = _super[name];

            // The method only need to be bound temporarily, so we
            // remove it when we're done executing
            var ret = fn.apply(this, arguments);
            this._super = tmp;

            return ret;
          };
        })(name, prop[name]) :
        prop[name];
    }

    // The dummy class constructor
    function Class() {
      // All construction is actually done in the init method
      if ( !initializing && this.init )
        this.init.apply(this, arguments);
    }

    // Populate our constructed prototype object
    Class.prototype = prototype;

    // Enforce the constructor to be what we expect
    Class.prototype.constructor = Class;

    // And make this class extendable
    Class.extend = arguments.callee;

    return Class;
  };
})();

(function($){
    $.getQuery = function( query ) {
        query = query.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
        var expr = "[\\?&]"+query+"=([^&#]*)";
        var regex = new RegExp( expr );
        var results = regex.exec( window.location.href );
        if( results !== null ) {
            return decodeURIComponent(results[1].replace(/\+/g, " "));
        } else {
            return false;
        }
    };
})(jQuery);

function setActiveStyleSheet(title) {
   var i, a, main;
   for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
     if(a.getAttribute("rel").indexOf("style") != -1
        && a.getAttribute("title")) {
       a.disabled = true;
       if(a.getAttribute("title") == title) a.disabled = false;
     }
   }
   createCookie("style",title,365)
}

function getActiveStyleSheet() {
 var i, a;
 for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
  if(a.getAttribute("rel").indexOf("style") != -1
  && a.getAttribute("title")
  && !a.disabled) return a.getAttribute("title");
  }
  return null;
}

function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

function getPreferredStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1
       && a.getAttribute("rel").indexOf("alt") == -1
       && a.getAttribute("title")
       ) return a.getAttribute("title");
  }
  return null;
}

function refresh_document() {
    display_document(current_document);
}

function display_document(name,section) {
    var f_overlay = $('#overlay:checked').val();
    var f_view = $('#view').val();
    var f_sort = $('#sort:checked').val();
    section = section || '';

    new $.ajax({
        url: '/_load',
        type: "get",
        dataType: "json",
        data: { paws_key: name, section: section, overlay: f_overlay, sort: f_sort, view: f_view },
        success: function(response){
            $('#pod_content').html(response.content);
            $('#menu').html(response.menu);
            $('#doc_links').html(response.links);
            $('#inbound_links').html(response.inbound_links);
            recents[name] = 1;
            current_document = name;
            current_section = '';
            var el = update_recents(name);
            el.addClass('uk-active');
            el.hide().fadeIn(500);

            /* Trigger highlight.js */
            $("pre code").each(function() {
                hljs.highlightBlock(this);
            });
            attach_listeners();
        }
    });
}

function paws_go(section_name, section_id) {
    current_section = section_name;
    UIkit.Utils.scrollToElement(UIkit.$('#sa_' + section_id));
    set_url_state();
    return false;
}

function attach_listeners() {
    $('button.annotate_button').each(function(elt) {
        $(this).on("click",edit_annotation);
    });
}

function overlay_on() {
    var overlay = $('#edit_overlay');
    overlay.addClass('on');
    $(overlay).on("click",overlay_off);
}

function overlay_off(ev) {
    if(ev) ev.stopPropagation();
    $('.popover').removeClass('on');

    return false;
}

function edit_annotation(event) {
    event.stopPropagation();
    var elt = this;
    var form = $(elt).parent("form");
    var params = form.serialize();

    overlay_on();
    var ed = $('#annotate_edit');
    ed.innerHTML = '
'
    ed.addClass("on");

    new $.ajax({
        url: "/_edit_annotation",
        type: "post",
        dataType: "html",
        data: params,
        success: function(response) {
            $(ed).html(response);
            $('#edit-save').on("click",save_annotation);
        }
    });

    return false;
}

function save_annotation(ev) {
    var elt = this;
    ev.stopPropagation();
    var form = $(elt).parent("form");
    var params = form.serialize();
    var module_name = form.children('[name="module"]').val()

    overlay_on();
    var ed = $('annotate_edit');
    ed.innerHTML = '
'

    new $.ajax({
        url: "/_save_annotation",
        type: "post",
        dataType: "json",
        data: params,
        success: function(response) {
            if(response.saved == 'yes') {
                overlay_off();
                var f = function() { display_document(module_name) };
                _.delay(f,1000);
            }
        }
    });

    return false;
}

function load_recents() {
    var d = $.getQuery('d');

    if(!d)
        return;
    var all = d.split(",");
    _.each(all,function(x) { recents[x] = 1; });
//    display_document(c);
}

function set_url_state() {
    var count_recents = _.keys(recents).length;
    var slug = "/" + current_document;
    var f_view = $('#view').val();

    if(f_view != 'normal') {
        slug += '/' + f_view;
    }

    if(current_section) {
        slug += "/@" + current_section;
    }

    if(count_recents > 1) {
        slug += "?d=" + _.without(_.keys(recents), current_document).sort().join(",");
    }

    history.pushState( {
      old_text: "PAWS",
      new_text: "PAWS",
      slug: slug
    }, null, slug);
}

function update_recents(name) { // returns the element created for "name" if possible
    var out = null;
    $('#recent_searches').children().each(function() { this.remove() });

    _.each(_.keys(recents).sort(), function(k) {
        var label = k;

        var li = $("

");
        var a = $(""+label+""); a.attr("onClick","display_document('"+k+"')" );
        var x = $(""); x.attr( 'onClick', "kill_recent('"+k+"')");

        li.append(x);
        li.append(a);

        $('#recent_searches').append(li);
        if(name == k) {
            out = li;
        }
    });

    set_url_state();

    return out;
}

function kill_recent(k) {
    var el = update_recents(k);
    el.fadeOut(500,function() {
        delete recents[k];
        update_recents();
    });
}

var PAWS_FastSearch = Class.extend({
      init: function(field,request_path) {
          var obj = this;
          obj.s_field = field;
          obj.s_path = request_path;
          obj.keynav = false;
          obj.initializeElements();
      },
      px: function() {
          var obj = this;
          this.fs_load_praps();
          setTimeout(function() { obj.px() }, 500 )
      },
      initializeElements: function() {
          var fs_field = $('#'+this.s_field);
          var div_name = "paws_fsearch";
          var obj = this;

          this.prev_value = this.terms();
          this.has_results = false;
          this.px(); // Start periodic execute on this.px every half second
          this.ajax_active = false;
          this.key_select = false;

          var div = $(div_name);
          if (div) {
              $(fs_field).on("focus", function(event) { obj.fs_focus() } );
              $(fs_field).on("blur", function(event) { obj.fs_blur() } );
              $(fs_field).keydown( function(event) { obj.fs_keynav(event) } );
          }
    },
    fs_div: function() {
        var div_name = "paws_fsearch";
        return $('#'+div_name);
    },
    fs_load_praps: function() {
        if(this.prev_value != this.terms()) {
            if(!this.ajax_active) {
                this.fs_load();
            }
        }
    },
    fs_focus: function() {
        if( this.has_results ) {
            this.fs_show()
        }
    },
    fs_blur: function() {
        this.fs_hide();
    },
    fs_hide: function() {
        var obj = this;
        setTimeout( function() {
            obj.fs_div().css('display','none');
        },200 );
    },
    fs_show: function() {
        this.fs_div().show();
    },
    fs_mousefollow: function(lines) {
        var obj = this;
        lines.each( function() {
            $(this).on('mouseover',function(event) {
                obj.fs_result_over(event, this);
            });
            $(this).on('click',function(event) {
                obj.fs_result_click(event, this);
            });
        });
    },
    fs_result_over: function(ev,elt) {
        if(this.selected_elt != null) {
            $(this.selected_elt).removeClass("hilight");
        }
        this.selected_elt = elt;
        this.keynav = false;
        $(elt).addClass("hilight");
    },
    fs_keynav: function(ev) {
        if(ev.which == KEY_UP || ev.which == KEY_DOWN) {
            var next_el = this.fs_div().find(".result_line").first();
            if(this.selected_elt != null) {
                switch (ev.which) {
                case KEY_UP:
                    next_el = $(this.selected_elt).prev(".result_line");
                    break;
                case KEY_DOWN:
                    next_el = $(this.selected_elt).next(".result_line");
                    break;
                }
            }
            if(next_el.length > 0) {
                if(this.selected_elt)
                    $(this.selected_elt).removeClass("hilight");
                this.selected_elt = next_el;
                $(this.selected_elt).addClass("hilight");
                this.keynav = true;
            }
            ev.stopPropagation();
        } else if(this.keynav &&
                  this.selected_elt &&
                  (ev.which == KEY_LEFT || ev.which == KEY_RIGHT)) {
            var sibs = $(this.selected_elt).prevAll();
            var position = sibs.length - 1; /* one for heading */
            var column = $(this.selected_elt).parent(".fs_section");
            var next_el = null;
            switch (ev.which) {
                case KEY_LEFT:
                  next_col = $(column).prev(".fs_section");
                  break;
                case KEY_RIGHT:
                  next_col = $(column).next(".fs_section");
                  break;
            }
            if(next_col.length > 0) {
                var col_results = next_col.children(".result_line");
                if(col_results.length <= position) {
                    next_el = col_results.last();
                } else {
                    next_el = col_results[position];
                }
                if(next_el) {
                    if(this.selected_elt)
                        $(this.selected_elt).removeClass("hilight");
                    this.selected_elt = next_el;
                    $(this.selected_elt).addClass("hilight");
                }
            }
            ev.stopPropagation()
        } else if(ev.which != KEY_RETURN) {
            this.keynav = false;
        }

        if(ev.which == KEY_RETURN) {
            if(this.keynav && this.selected_elt) {
                var paws_link = $(this.selected_elt).attr('paws_link')
                display_document(paws_link);
                ev.stopPropagation();
            }
        }

    },
    fs_result_click: function(ev,elt) {
        var paws_link = $(elt).attr('paws_link')
        display_document(paws_link);
    },
    fs_load: function() {
        var div = this.fs_div();
        var path = this.s_path;
        var obj = this;
        var tval = this.terms();
        this.ajax_active = true;
        $.ajax({
            url: path, type: "get", dataType: "html",
            data: { terms: tval },
            success: function(response){
                var response_divs = $(div).html(response).find(".fs_section");

                var section_count = response_divs.length;
                div.attr("class","uk-grid uk-grid-small");
                div.addClass("uk-width-medium-"+section_count+"-4");
                div.addClass("uk-width-small-1-1");
                div.css('position', 'absolute')
                obj.ajax_active = false;
                obj.selected_elt = null;

                var total_lines = div.find(".result_line");
                if(total_lines.length == 0) {
                    obj.fs_hide();
                    return true;
                } else {
                    obj.has_results = true;
                    obj.fs_div().css('display','block');
                    obj.fs_mousefollow(total_lines);
                    obj.prev_value = tval;
                }
            }
        });
    },
    terms: function() {
        return $('#'+this.s_field).val();
    }
});<commit_msg>Load recents will no longer ajax-load a document. These documents will be preloaded from the original URL.<commit_after>
var recents = { };
var current_document;
var current_section;

var KEY_LEFT = 37;
var KEY_UP = 38;
var KEY_RIGHT = 39;
var KEY_DOWN = 40;
var KEY_RETURN = 13;

(function(){
  var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;

  // The base Class implementation (does nothing)
  this.Class = function(){};

  // Create a new Class that inherits from this class
  Class.extend = function(prop) {
    var _super = this.prototype;

    // Instantiate a base class (but only create the instance,
    // don't run the init constructor)
    initializing = true;
    var prototype = new this();
    initializing = false;

    // Copy the properties over onto the new prototype
    for (var name in prop) {
      // Check if we're overwriting an existing function
      prototype[name] = typeof prop[name] == "function" &&
        typeof _super[name] == "function" && fnTest.test(prop[name]) ?
        (function(name, fn){
          return function() {
            var tmp = this._super;

            // Add a new ._super() method that is the same method
            // but on the super-class
            this._super = _super[name];

            // The method only need to be bound temporarily, so we
            // remove it when we're done executing
            var ret = fn.apply(this, arguments);
            this._super = tmp;

            return ret;
          };
        })(name, prop[name]) :
        prop[name];
    }

    // The dummy class constructor
    function Class() {
      // All construction is actually done in the init method
      if ( !initializing && this.init )
        this.init.apply(this, arguments);
    }

    // Populate our constructed prototype object
    Class.prototype = prototype;

    // Enforce the constructor to be what we expect
    Class.prototype.constructor = Class;

    // And make this class extendable
    Class.extend = arguments.callee;

    return Class;
  };
})();

(function($){
    $.getQuery = function( query ) {
        query = query.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
        var expr = "[\\?&]"+query+"=([^&#]*)";
        var regex = new RegExp( expr );
        var results = regex.exec( window.location.href );
        if( results !== null ) {
            return decodeURIComponent(results[1].replace(/\+/g, " "));
        } else {
            return false;
        }
    };
})(jQuery);

function setActiveStyleSheet(title) {
   var i, a, main;
   for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
     if(a.getAttribute("rel").indexOf("style") != -1
        && a.getAttribute("title")) {
       a.disabled = true;
       if(a.getAttribute("title") == title) a.disabled = false;
     }
   }
   createCookie("style",title,365)
}

function getActiveStyleSheet() {
 var i, a;
 for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
  if(a.getAttribute("rel").indexOf("style") != -1
  && a.getAttribute("title")
  && !a.disabled) return a.getAttribute("title");
  }
  return null;
}

function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

function getPreferredStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1
       && a.getAttribute("rel").indexOf("alt") == -1
       && a.getAttribute("title")
       ) return a.getAttribute("title");
  }
  return null;
}

function refresh_document() {
    display_document(current_document);
}

function display_document(name,section) {
    var f_overlay = $('#overlay:checked').val();
    var f_view = $('#view').val();
    var f_sort = $('#sort:checked').val();
    section = section || '';

    new $.ajax({
        url: '/_load',
        type: "get",
        dataType: "json",
        data: { paws_key: name, section: section, overlay: f_overlay, sort: f_sort, view: f_view },
        success: function(response){
            $('#pod_content').html(response.content);
            $('#menu').html(response.menu);
            $('#doc_links').html(response.links);
            $('#inbound_links').html(response.inbound_links);
            recents[name] = 1;
            current_document = name;
            current_section = '';
            var el = update_recents(name);
            el.addClass('uk-active');
            el.hide().fadeIn(500);

            /* Trigger highlight.js */
            $("pre code").each(function() {
                hljs.highlightBlock(this);
            });
            attach_listeners();
        }
    });
}

function paws_go(section_name, section_id) {
    current_section = section_name;
    UIkit.Utils.scrollToElement(UIkit.$('#sa_' + section_id));
    set_url_state();
    return false;
}

function attach_listeners() {
    $('button.annotate_button').each(function(elt) {
        $(this).on("click",edit_annotation);
    });
}

function overlay_on() {
    var overlay = $('#edit_overlay');
    overlay.addClass('on');
    $(overlay).on("click",overlay_off);
}

function overlay_off(ev) {
    if(ev) ev.stopPropagation();
    $('.popover').removeClass('on');

    return false;
}

function edit_annotation(event) {
    event.stopPropagation();
    var elt = this;
    var form = $(elt).parent("form");
    var params = form.serialize();

    overlay_on();
    var ed = $('#annotate_edit');
    ed.innerHTML = '
'
    ed.addClass("on");

    new $.ajax({
        url: "/_edit_annotation",
        type: "post",
        dataType: "html",
        data: params,
        success: function(response) {
            $(ed).html(response);
            $('#edit-save').on("click",save_annotation);
        }
    });

    return false;
}

function save_annotation(ev) {
    var elt = this;
    ev.stopPropagation();
    var form = $(elt).parent("form");
    var params = form.serialize();
    var module_name = form.children('[name="module"]').val()

    overlay_on();
    var ed = $('annotate_edit');
    ed.innerHTML = '
'

    new $.ajax({
        url: "/_save_annotation",
        type: "post",
        dataType: "json",
        data: params,
        success: function(response) {
            if(response.saved == 'yes') {
                overlay_off();
                var f = function() { display_document(module_name) };
                _.delay(f,1000);
            }
        }
    });

    return false;
}

function load_recents() {
    var d = $.getQuery('d');

    if(!d)
        return;
    var all = d.split(",");
    _.each(all,function(x) { recents[x] = 1; });
}

function set_url_state() {
    var count_recents = _.keys(recents).length;
    var slug = "/" + current_document;
    var f_view = $('#view').val();

    if(f_view != 'normal') {
        slug += '/' + f_view;
    }

    if(current_section) {
        slug += "/@" + current_section;
    }

    if(count_recents > 1) {
        slug += "?d=" + _.without(_.keys(recents), current_document).sort().join(",");
    }

    history.pushState( {
      old_text: "PAWS",
      new_text: "PAWS",
      slug: slug
    }, null, slug);
}

function update_recents(name) { // returns the element created for "name" if possible
    var out = null;
    $('#recent_searches').children().each(function() { this.remove() });

    _.each(_.keys(recents).sort(), function(k) {
        var label = k;

        var li = $("

");
        var a = $(""+label+""); a.attr("onClick","display_document('"+k+"')" );
        var x = $(""); x.attr( 'onClick', "kill_recent('"+k+"')");

        li.append(x);
        li.append(a);

        $('#recent_searches').append(li);
        if(name == k) {
            out = li;
        }
    });

    set_url_state();

    return out;
}

function kill_recent(k) {
    var el = update_recents(k);
    el.fadeOut(500,function() {
        delete recents[k];
        update_recents();
    });
}

var PAWS_FastSearch = Class.extend({
      init: function(field,request_path) {
          var obj = this;
          obj.s_field = field;
          obj.s_path = request_path;
          obj.keynav = false;
          obj.initializeElements();
      },
      px: function() {
          var obj = this;
          this.fs_load_praps();
          setTimeout(function() { obj.px() }, 500 )
      },
      initializeElements: function() {
          var fs_field = $('#'+this.s_field);
          var div_name = "paws_fsearch";
          var obj = this;

          this.prev_value = this.terms();
          this.has_results = false;
          this.px(); // Start periodic execute on this.px every half second
          this.ajax_active = false;
          this.key_select = false;

          var div = $(div_name);
          if (div) {
              $(fs_field).on("focus", function(event) { obj.fs_focus() } );
              $(fs_field).on("blur", function(event) { obj.fs_blur() } );
              $(fs_field).keydown( function(event) { obj.fs_keynav(event) } );
          }
    },
    fs_div: function() {
        var div_name = "paws_fsearch";
        return $('#'+div_name);
    },
    fs_load_praps: function() {
        if(this.prev_value != this.terms()) {
            if(!this.ajax_active) {
                this.fs_load();
            }
        }
    },
    fs_focus: function() {
        if( this.has_results ) {
            this.fs_show()
        }
    },
    fs_blur: function() {
        this.fs_hide();
    },
    fs_hide: function() {
        var obj = this;
        setTimeout( function() {
            obj.fs_div().css('display','none');
        },200 );
    },
    fs_show: function() {
        this.fs_div().show();
    },
    fs_mousefollow: function(lines) {
        var obj = this;
        lines.each( function() {
            $(this).on('mouseover',function(event) {
                obj.fs_result_over(event, this);
            });
            $(this).on('click',function(event) {
                obj.fs_result_click(event, this);
            });
        });
    },
    fs_result_over: function(ev,elt) {
        if(this.selected_elt != null) {
            $(this.selected_elt).removeClass("hilight");
        }
        this.selected_elt = elt;
        this.keynav = false;
        $(elt).addClass("hilight");
    },
    fs_keynav: function(ev) {
        if(ev.which == KEY_UP || ev.which == KEY_DOWN) {
            var next_el = this.fs_div().find(".result_line").first();
            if(this.selected_elt != null) {
                switch (ev.which) {
                case KEY_UP:
                    next_el = $(this.selected_elt).prev(".result_line");
                    break;
                case KEY_DOWN:
                    next_el = $(this.selected_elt).next(".result_line");
                    break;
                }
            }
            if(next_el.length > 0) {
                if(this.selected_elt)
                    $(this.selected_elt).removeClass("hilight");
                this.selected_elt = next_el;
                $(this.selected_elt).addClass("hilight");
                this.keynav = true;
            }
            ev.stopPropagation();
        } else if(this.keynav &&
                  this.selected_elt &&
                  (ev.which == KEY_LEFT || ev.which == KEY_RIGHT)) {
            var sibs = $(this.selected_elt).prevAll();
            var position = sibs.length - 1; /* one for heading */
            var column = $(this.selected_elt).parent(".fs_section");
            var next_el = null;
            switch (ev.which) {
                case KEY_LEFT:
                  next_col = $(column).prev(".fs_section");
                  break;
                case KEY_RIGHT:
                  next_col = $(column).next(".fs_section");
                  break;
            }
            if(next_col.length > 0) {
                var col_results = next_col.children(".result_line");
                if(col_results.length <= position) {
                    next_el = col_results.last();
                } else {
                    next_el = col_results[position];
                }
                if(next_el) {
                    if(this.selected_elt)
                        $(this.selected_elt).removeClass("hilight");
                    this.selected_elt = next_el;
                    $(this.selected_elt).addClass("hilight");
                }
            }
            ev.stopPropagation()
        } else if(ev.which != KEY_RETURN) {
            this.keynav = false;
        }

        if(ev.which == KEY_RETURN) {
            if(this.keynav && this.selected_elt) {
                var paws_link = $(this.selected_elt).attr('paws_link')
                display_document(paws_link);
                ev.stopPropagation();
            }
        }

    },
    fs_result_click: function(ev,elt) {
        var paws_link = $(elt).attr('paws_link')
        display_document(paws_link);
    },
    fs_load: function() {
        var div = this.fs_div();
        var path = this.s_path;
        var obj = this;
        var tval = this.terms();
        this.ajax_active = true;
        $.ajax({
            url: path, type: "get", dataType: "html",
            data: { terms: tval },
            success: function(response){
                var response_divs = $(div).html(response).find(".fs_section");

                var section_count = response_divs.length;
                div.attr("class","uk-grid uk-grid-small");
                div.addClass("uk-width-medium-"+section_count+"-4");
                div.addClass("uk-width-small-1-1");
                div.css('position', 'absolute')
                obj.ajax_active = false;
                obj.selected_elt = null;

                var total_lines = div.find(".result_line");
                if(total_lines.length == 0) {
                    obj.fs_hide();
                    return true;
                } else {
                    obj.has_results = true;
                    obj.fs_div().css('display','block');
                    obj.fs_mousefollow(total_lines);
                    obj.prev_value = tval;
                }
            }
        });
    },
    terms: function() {
        return $('#'+this.s_field).val();
    }
});<|endoftext|>


<commit_before>$(document).ready(function() {
	// Javascript code for comments (from Facebook SDK)
	(function(d, s, id) {
		var js, fjs = d.getElementsByTagName(s)[0];
		if (d.getElementById(id)) return;
		js = d.createElement(s); js.id = id;
		js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=621121534641370";
		fjs.parentNode.insertBefore(js, fjs);
	}
	(document, 'script', 'facebook-jssdk'));

	// // Javascript code for the share button (from Facebook SDK)
	// (function(d, s, id) {
	//   var js, fjs = d.getElementsByTagName(s)[0];
	//   if (d.getElementById(id)) return;
	//   js = d.createElement(s); js.id = id;
	//   js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=621121534641370";
	//   fjs.parentNode.insertBefore(js, fjs);
	// }(document, 'script', 'facebook-jssdk'));

	// // Javascript code for tweet button to work
	// !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="https://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");

	// // Javascript code for the Google+ share button to work
	// (function() {
	//   var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
	//   po.src = 'https://apis.google.com/js/platform.js';
	//   var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
	// })();

	new Share('.socialbuttons', {
		ui: {
			button_background: 'rgb(68,97,159)',
			button_color: 'rgb(255,255,255)'
		},
		networks: {
			facebook: {
				app_id: 'abc123'
			}
		}
	});
});
<commit_msg>Removed junk js code<commit_after>$(document).ready(function() {
	// Javascript code for comments (from Facebook SDK)
	(function(d, s, id) {
		var js, fjs = d.getElementsByTagName(s)[0];
		if (d.getElementById(id)) return;
		js = d.createElement(s); js.id = id;
		js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=621121534641370";
		fjs.parentNode.insertBefore(js, fjs);
	}
	(document, 'script', 'facebook-jssdk'));

	new Share('.socialbuttons', {
		ui: {
			button_background: 'rgb(68,97,159)',
			button_color: 'rgb(255,255,255)'
		},
		networks: {
			facebook: {
				app_id: 'abc123'
			}
		}
	});
});
<|endoftext|>


<commit_before>'use strict';

function initTeam(){
    const teamId = urlGetParam('id');
    console.log("/team - Initializing");
    $("#createTeamMemberBtn").on("click", function(){
        createNewTeamMember(teamId);
    });

    $("#saveBillingDetails").on("click", function(){
        saveAddressDetails('billing',teamId);
    });

    $("#saveShippingDetails").on("click", function(){
        saveAddressDetails('shipping',teamId);
    });

    $("#btnRegister").on("click", function(){
        registerForEvent(teamId);
    });

    loadTeamCoaches(teamId);
    loadTeamMembers(teamId);
    loadAddressDetails(teamId);
    loadAvailableEvents(teamId);

    console.log("/team - Initializing completed");
}

function loadTeamCoaches(teamId){
    const site = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '');
    console.log("Loading team coaches");
    const t = $("#coachList");
    t.empty();
    $.get( "/team?id="+teamId+"&cmd=getTeamCoaches", function(res) {
        console.log("Server returned coaches",res);
        if (res.result === 'ok'){
            console.log("List of",res.list.length,"records");
            t.empty();
            if (res.list.length > 0) {
                console.log("Found ",res.list.length,"records");
                res.list.forEach(function(item) {
                    var c = $('')
                        .append(item.fullName);

                    t.append(c);

                });
            } else {
                t.text('Žiadni tréneri');
            }
        } else {
            console.log("Server returned ERROR");
        }

    });

}

function loadTeamMembers(teamId){
    const site = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '');
    console.log("Loading team members");
    const t = $("#memberList");
    t.empty();
    $.get( "/team?id="+teamId+"&cmd=getTeamMembers", function(res) {
        console.log("Server returned members",res);
        if (res.result === 'ok'){
            console.log("List of",res.list.length,"records");
            t.empty();
            if (res.list.length > 0) {
                res.list.forEach(function(item) {

                    let btnRemove = $('<button type="button" class="btn btn-link btn-xs">');
                    btnRemove.memberId = item.id;
                    btnRemove.on("click",function(){removeMember(item.id, teamId);});
                    btnRemove.append($(''));

                    let btnEdit = $('<button type="button" class="btn btn-link btn-xs">');
                    btnEdit.memberId = item.id;
                    btnEdit.on("click",function(){editMember(item.id);});
                    btnEdit.append($(''));

                    let c = $('
')
                            .append($('
')
                                .append(btnRemove)
                                .append(item.fullName)
                                //.append(btnEdit)
                            )
                            .append($('
')
                                .append($('<input class="form-control" type="date" readonly value="'+(item.dateOfBirth?item.dateOfBirth.substr(0,10):null)+'">'))
                                .append($('<input class="form-control" type="string" readonly value="'+(item.email?item.email:'')+'">'))
                            );

                    t.append(c);

                });
            } else {
                t.text('Žiadni členovia tímu');
            }
        } else {
            console.log("Server returned ERROR");
        }

    })
        .fail(function(err){
            console.log("getTeamMembers FAILED",err);
            t.text('Chyba pri komunikácii so serverom');
        });

}

function createNewTeamMember(teamId){

    const selDialog = $("#newMemberModal");
    const selNameGrp = $("#newMemberName");
    const selName = $("#newMemberName > input:first");

    const selEmailGrp = $("#newMemberEmail");
    const selEmail = $("#newMemberEmail > input:first");

    const selDOBGrp = $("#newMemberDOB");
    const selDOB = $("#newMemberDOB > input:first");

    var selStatus = $("#createStatus");

    if (selName.val().trim() != '') {
        console.log("Posting request to create new member");
        $.post("/team",
            {
                cmd: 'createTeamMember',
                name: selName.val(),
                email: selEmail.val(),
                dob: selDOB.val(),
                teamId: teamId
            },
            function (res) {
                console.log("createTeamMember: Server returned",res);
                if (res.result == "ok") {
                    console.log("Member created");
                    selStatus.text('Člen tímu vytvorený.');
                    selStatus.css("display", "inline").fadeOut(2000);
                    selName.val('');
                    selEmail.val('');
                    selDOB.val('');
                    selDialog.modal("hide");
                    loadTeamMembers(teamId);
                } else {
                    console.log("Error while creating team-member");
                    selStatus.text('Nepodarilo sa vytvoriť člena tímu.');
                    selStatus.css("display", "inline").fadeOut(5000);
                }
            }
        )
        .fail(function (err) {
            selStatus.text('Nepodarilo sa vytvoriť nového člena.');
            console.log("Creation failed",err);
        });
    } else {
        selStatus.text('Člen tímu musí mať meno.');
        selStatus.css("display", "inline").fadeOut(5000);
    }
}

function removeMember(id, teamId){
    console.log("Removing member",id);
    $.post("/team",
        {
            cmd: 'removeTeamMember',
            memberId: id,
            teamId: teamId
        },
        function (res) {
            console.log("removeTeamMember: Server returned",res);
            if (res.result == "ok") {
                console.log("Member removed");
                loadTeamMembers(teamId);
            } else {
                console.log("Error while creating team");
            }
        }
    )
    .fail(function (err) {
        console.log("Member removal failed",err);
    });
}

function editMember(id){
    console.log("Editing ",id);
}

function saveAddressDetails(detType, teamId){
    var succ = false;
    var selStatus;
    var selDialog;
    console.log("Saving address details", detType);

    const details = {};

    if (detType === 'billing'){
        selStatus = $("#saveBillingStatus");
        selDialog = $("#billingAddress");

        details.orgName = $("#billOrg").val();
        details.addr1 = $("#billAdr1").val();
        details.addr2 = $("#billAdr2").val();
        details.city = $("#billCity").val();
        details.postCode = $("#billPostCode").val();
        details.compNo = $("#billCompNo").val();
        details.taxNo = $("#billTaxNo").val();
        details.conName = $("#billContactName").val();
        details.conPhone = $("#billContactPhone").val();
        details.conEmail = $("#billContactEmail").val();
    } else {
        selStatus = $("#saveShippingStatus");
        selDialog = $("#shippingAddress");

        details.orgName = $("#shipOrg").val();
        details.addr1 = $("#shipAdr1").val();
        details.addr2 = $("#shipAdr2").val();
        details.city = $("#shipCity").val();
        details.postCode = $("#shipPostCode").val();
        details.conName = $("#shipContactName").val();
        details.conPhone = $("#shipContactPhone").val();
        details.conEmail = $("#shipContactEmail").val();
    }

    console.log("Posting request to save address details");

    $.ajax({
            type:"POST",
            url:"/team",
            dataType: "json",
            data: {
                cmd: 'saveAdrDetails',
                teamId: teamId,
                type: detType,
                data: JSON.stringify(details)
            }

        })
        .done( function (res) {
            console.log("saveAdrDetails: Server returned",res);
            if (res.result == "ok") {
                console.log("Details saved");
                selStatus.text('Uložené');
                selStatus.css("display", "inline").fadeOut(2000);
                loadAddressDetails(teamId);
                selDialog.modal("hide");
            } else {
                console.log("Error while saving details");
                selStatus.text('Nepodarilo sa uložiť.');
                selStatus.css("display", "inline").fadeOut(5000);
            }
        })
        .fail(function (err) {
            selStatus.text('Nepodarilo sa uložiť detaily.');
            selStatus.css("display", "inline").fadeOut(5000);
            console.log("Save failed",err);
        });

    return succ;
}

function loadAddressDetails(teamId){
    console.log("Loading team address details");
    $.get("/team?id="+teamId+"&cmd=getAdrDetails")
        .done(function (res) {
            console.log("loadAdrDetails: Server returned",res);
            if (res.result == "ok") {
                formatAddressDetails(res.details);
            } else {
                console.log("Error while loading details");
            }
        })
        .fail(function (err) {
            console.log("Load failed",err);
        });
}

function formatAddressDetails(data) {

    if (!data.billingOrg) data.billingOrg = {};
    $("#billOrg").val(data.billingOrg.name || '');
    $("#billCompNo").val(data.billingOrg.companyNo || '');
    $("#billTaxNo").val(data.billingOrg.taxNo || '');

    if (!data.billingAdr) data.billingAdr = {};
    $("#billAdr1").val(data.billingAdr.addrLine1 || '');
    $("#billAdr2").val(data.billingAdr.addrLine2 || '');
    $("#billCity").val(data.billingAdr.city || '');
    $("#billPostCode").val(data.billingAdr.postCode || '');

    if (!data.billingContact) data.billingContact = {};
    $("#billContactName").val(data.billingContact.name || '');
    $("#billContactPhone").val(data.billingContact.phone || '');
    $("#billContactEmail").val(data.billingContact.email || '');

    if (!data.shippingOrg) data.shippingOrg = {};
    $("#shipOrg").val(data.shippingOrg.name || '');

    if (!data.shippingAdr) data.shippingAdr = {};
    $("#shipAdr1").val(data.shippingAdr.addrLine1 || '');
    $("#shipAdr2").val(data.shippingAdr.addrLine2 || '');
    $("#shipCity").val(data.shippingAdr.city || '');
    $("#shipPostCode").val(data.shippingAdr.postCode || '');

    if (!data.shippingContact) data.shippingContact = {};
    $("#shipContactName").val(data.shippingContact.name || '');
    $("#shipContactPhone").val(data.shippingContact.phone || '');
    $("#shipContactEmail").val(data.shippingContact.email || '');

}

function loadAvailableEvents(teamId){
    const sel = $('#availEvents');
    console.log('Loading events');
    $.get( "/event?cmd=getAvailTeamEvents&teamId="+teamId, function(res) {
        console.log("Server returned events",res);
        console.log("List of",res.list.length,"records");
        if (res.result === 'ok'){
            sel.empty();
            if (res.list.length > 0) {
                console.log("Found ",res.list.length,"records");
                res.list.forEach(function(item) {
                    var c = $('<option value="'+item.id+'"">').append(item.name);
                    sel.append(c);
                });
            } else {
                sel.text('Žiadne');
            }
        } else {
            console.log("Server returned ERROR");
        }

    });

}

function loadTeamData(teamId){
    $.get( "/team?cmd=getData&teamId="+teamId, function(res) {
        console.log('Server returned team data',res);
        if (res.result === 'ok'){

        } else {
            console.log('Server returned error');
        }
    });
}

function registerForEvent(teamId){
    console.log('Registering for event');
    const eventId = $('#availEvents').val();
    $.post("/event",
        {
            cmd: 'registerTeam',
            eventId: eventId,
            teamId: teamId
        },
        function (res) {
            console.log("registerTeam for event: Server returned",res);
            if (res.result == "ok") {
                console.log("team registered");
                location.reload(true);
            } else {
                console.log("Error while creating team");
            }
        }
    )
        .fail(function (err) {
            console.log("Member removal failed",err);
        });

}<commit_msg>fixe member remove icon issue #7<commit_after>'use strict';

function initTeam(){
    const teamId = urlGetParam('id');
    console.log("/team - Initializing");
    $("#createTeamMemberBtn").on("click", function(){
        createNewTeamMember(teamId);
    });

    $("#saveBillingDetails").on("click", function(){
        saveAddressDetails('billing',teamId);
    });

    $("#saveShippingDetails").on("click", function(){
        saveAddressDetails('shipping',teamId);
    });

    $("#btnRegister").on("click", function(){
        registerForEvent(teamId);
    });

    loadTeamCoaches(teamId);
    loadTeamMembers(teamId);
    loadAddressDetails(teamId);
    loadAvailableEvents(teamId);

    console.log("/team - Initializing completed");
}

function loadTeamCoaches(teamId){
    const site = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '');
    console.log("Loading team coaches");
    const t = $("#coachList");
    t.empty();
    $.get( "/team?id="+teamId+"&cmd=getTeamCoaches", function(res) {
        console.log("Server returned coaches",res);
        if (res.result === 'ok'){
            console.log("List of",res.list.length,"records");
            t.empty();
            if (res.list.length > 0) {
                console.log("Found ",res.list.length,"records");
                res.list.forEach(function(item) {
                    var c = $('')
                        .append(item.fullName);

                    t.append(c);

                });
            } else {
                t.text('Žiadni tréneri');
            }
        } else {
            console.log("Server returned ERROR");
        }

    });

}

function loadTeamMembers(teamId){
    const site = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '');
    console.log("Loading team members");
    const t = $("#memberList");
    t.empty();
    $.get( "/team?id="+teamId+"&cmd=getTeamMembers", function(res) {
        console.log("Server returned members",res);
        if (res.result === 'ok'){
            console.log("List of",res.list.length,"records");
            t.empty();
            if (res.list.length > 0) {
                res.list.forEach(function(item) {

                    let btnRemove = $('<button type="button" class="btn btn-link btn-xs">');
                    btnRemove.memberId = item.id;
                    btnRemove.on("click",function(){removeMember(item.id, teamId);});
                    btnRemove.append($(''));

                    let btnEdit = $('<button type="button" class="btn btn-link btn-xs">');
                    btnEdit.memberId = item.id;
                    btnEdit.on("click",function(){editMember(item.id);});
                    btnEdit.append($(''));

                    let c = $('
')
                            .append($('
')
                                .append(btnRemove)
                                .append(item.fullName)
                                //.append(btnEdit)
                            )
                            .append($('
')
                                .append($('<input class="form-control" type="date" readonly value="'+(item.dateOfBirth?item.dateOfBirth.substr(0,10):null)+'">'))
                                .append($('<input class="form-control" type="string" readonly value="'+(item.email?item.email:'')+'">'))
                            );

                    t.append(c);

                });
            } else {
                t.text('Žiadni členovia tímu');
            }
        } else {
            console.log("Server returned ERROR");
        }

    })
        .fail(function(err){
            console.log("getTeamMembers FAILED",err);
            t.text('Chyba pri komunikácii so serverom');
        });

}

function createNewTeamMember(teamId){

    const selDialog = $("#newMemberModal");
    const selNameGrp = $("#newMemberName");
    const selName = $("#newMemberName > input:first");

    const selEmailGrp = $("#newMemberEmail");
    const selEmail = $("#newMemberEmail > input:first");

    const selDOBGrp = $("#newMemberDOB");
    const selDOB = $("#newMemberDOB > input:first");

    var selStatus = $("#createStatus");

    if (selName.val().trim() != '') {
        console.log("Posting request to create new member");
        $.post("/team",
            {
                cmd: 'createTeamMember',
                name: selName.val(),
                email: selEmail.val(),
                dob: selDOB.val(),
                teamId: teamId
            },
            function (res) {
                console.log("createTeamMember: Server returned",res);
                if (res.result == "ok") {
                    console.log("Member created");
                    selStatus.text('Člen tímu vytvorený.');
                    selStatus.css("display", "inline").fadeOut(2000);
                    selName.val('');
                    selEmail.val('');
                    selDOB.val('');
                    selDialog.modal("hide");
                    loadTeamMembers(teamId);
                } else {
                    console.log("Error while creating team-member");
                    selStatus.text('Nepodarilo sa vytvoriť člena tímu.');
                    selStatus.css("display", "inline").fadeOut(5000);
                }
            }
        )
        .fail(function (err) {
            selStatus.text('Nepodarilo sa vytvoriť nového člena.');
            console.log("Creation failed",err);
        });
    } else {
        selStatus.text('Člen tímu musí mať meno.');
        selStatus.css("display", "inline").fadeOut(5000);
    }
}

function removeMember(id, teamId){
    console.log("Removing member",id);
    $.post("/team",
        {
            cmd: 'removeTeamMember',
            memberId: id,
            teamId: teamId
        },
        function (res) {
            console.log("removeTeamMember: Server returned",res);
            if (res.result == "ok") {
                console.log("Member removed");
                loadTeamMembers(teamId);
            } else {
                console.log("Error while creating team");
            }
        }
    )
    .fail(function (err) {
        console.log("Member removal failed",err);
    });
}

function editMember(id){
    console.log("Editing ",id);
}

function saveAddressDetails(detType, teamId){
    var succ = false;
    var selStatus;
    var selDialog;
    console.log("Saving address details", detType);

    const details = {};

    if (detType === 'billing'){
        selStatus = $("#saveBillingStatus");
        selDialog = $("#billingAddress");

        details.orgName = $("#billOrg").val();
        details.addr1 = $("#billAdr1").val();
        details.addr2 = $("#billAdr2").val();
        details.city = $("#billCity").val();
        details.postCode = $("#billPostCode").val();
        details.compNo = $("#billCompNo").val();
        details.taxNo = $("#billTaxNo").val();
        details.conName = $("#billContactName").val();
        details.conPhone = $("#billContactPhone").val();
        details.conEmail = $("#billContactEmail").val();
    } else {
        selStatus = $("#saveShippingStatus");
        selDialog = $("#shippingAddress");

        details.orgName = $("#shipOrg").val();
        details.addr1 = $("#shipAdr1").val();
        details.addr2 = $("#shipAdr2").val();
        details.city = $("#shipCity").val();
        details.postCode = $("#shipPostCode").val();
        details.conName = $("#shipContactName").val();
        details.conPhone = $("#shipContactPhone").val();
        details.conEmail = $("#shipContactEmail").val();
    }

    console.log("Posting request to save address details");

    $.ajax({
            type:"POST",
            url:"/team",
            dataType: "json",
            data: {
                cmd: 'saveAdrDetails',
                teamId: teamId,
                type: detType,
                data: JSON.stringify(details)
            }

        })
        .done( function (res) {
            console.log("saveAdrDetails: Server returned",res);
            if (res.result == "ok") {
                console.log("Details saved");
                selStatus.text('Uložené');
                selStatus.css("display", "inline").fadeOut(2000);
                loadAddressDetails(teamId);
                selDialog.modal("hide");
            } else {
                console.log("Error while saving details");
                selStatus.text('Nepodarilo sa uložiť.');
                selStatus.css("display", "inline").fadeOut(5000);
            }
        })
        .fail(function (err) {
            selStatus.text('Nepodarilo sa uložiť detaily.');
            selStatus.css("display", "inline").fadeOut(5000);
            console.log("Save failed",err);
        });

    return succ;
}

function loadAddressDetails(teamId){
    console.log("Loading team address details");
    $.get("/team?id="+teamId+"&cmd=getAdrDetails")
        .done(function (res) {
            console.log("loadAdrDetails: Server returned",res);
            if (res.result == "ok") {
                formatAddressDetails(res.details);
            } else {
                console.log("Error while loading details");
            }
        })
        .fail(function (err) {
            console.log("Load failed",err);
        });
}

function formatAddressDetails(data) {

    if (!data.billingOrg) data.billingOrg = {};
    $("#billOrg").val(data.billingOrg.name || '');
    $("#billCompNo").val(data.billingOrg.companyNo || '');
    $("#billTaxNo").val(data.billingOrg.taxNo || '');

    if (!data.billingAdr) data.billingAdr = {};
    $("#billAdr1").val(data.billingAdr.addrLine1 || '');
    $("#billAdr2").val(data.billingAdr.addrLine2 || '');
    $("#billCity").val(data.billingAdr.city || '');
    $("#billPostCode").val(data.billingAdr.postCode || '');

    if (!data.billingContact) data.billingContact = {};
    $("#billContactName").val(data.billingContact.name || '');
    $("#billContactPhone").val(data.billingContact.phone || '');
    $("#billContactEmail").val(data.billingContact.email || '');

    if (!data.shippingOrg) data.shippingOrg = {};
    $("#shipOrg").val(data.shippingOrg.name || '');

    if (!data.shippingAdr) data.shippingAdr = {};
    $("#shipAdr1").val(data.shippingAdr.addrLine1 || '');
    $("#shipAdr2").val(data.shippingAdr.addrLine2 || '');
    $("#shipCity").val(data.shippingAdr.city || '');
    $("#shipPostCode").val(data.shippingAdr.postCode || '');

    if (!data.shippingContact) data.shippingContact = {};
    $("#shipContactName").val(data.shippingContact.name || '');
    $("#shipContactPhone").val(data.shippingContact.phone || '');
    $("#shipContactEmail").val(data.shippingContact.email || '');

}

function loadAvailableEvents(teamId){
    const sel = $('#availEvents');
    console.log('Loading events');
    $.get( "/event?cmd=getAvailTeamEvents&teamId="+teamId, function(res) {
        console.log("Server returned events",res);
        console.log("List of",res.list.length,"records");
        if (res.result === 'ok'){
            sel.empty();
            if (res.list.length > 0) {
                console.log("Found ",res.list.length,"records");
                res.list.forEach(function(item) {
                    var c = $('<option value="'+item.id+'"">').append(item.name);
                    sel.append(c);
                });
            } else {
                sel.text('Žiadne');
            }
        } else {
            console.log("Server returned ERROR");
        }

    });

}

function loadTeamData(teamId){
    $.get( "/team?cmd=getData&teamId="+teamId, function(res) {
        console.log('Server returned team data',res);
        if (res.result === 'ok'){

        } else {
            console.log('Server returned error');
        }
    });
}

function registerForEvent(teamId){
    console.log('Registering for event');
    const eventId = $('#availEvents').val();
    $.post("/event",
        {
            cmd: 'registerTeam',
            eventId: eventId,
            teamId: teamId
        },
        function (res) {
            console.log("registerTeam for event: Server returned",res);
            if (res.result == "ok") {
                console.log("team registered");
                location.reload(true);
            } else {
                console.log("Error while creating team");
            }
        }
    )
        .fail(function (err) {
            console.log("Member removal failed",err);
        });

}<|endoftext|>


<commit_before>/////////////////////////////////////////////////////////////
//
// Author Scott Herbert (www.scott-herbert.com)
//		  Dimitri Kourkoulis (http://dimitros.net/en/home)
//
// Version History
// 1 (10-Feb-2013) Inital release on to GitHub.
//
// 2 (12-Mar-2013) Small modification by Dimitri Kourkoulis.
//    This version of the script, keeps visitors on the web site
//    if they decline the use of cookies. However, in that event,
//    the cookie stored in their browser is named 'jsNoCookieCheck'
//    instead of 'jsCookieCheck'. This can be used by the software
//    and/or CMS of the web site to disable cookie producing content.
//    An example of how this has been used in one case on the Umbraco
//    CMS can be found here:
//    http://dimitros.net/en/blog/complyingwiththecookielaw
//
// 3 (03-April-2013) SAH - Added a variable that allows the developer to
//	  select if the script redirects (as it originally did) or carry?s
//    on (as per Dimitri?s great addition).
//
// Download from http://adf.ly/IvElY

function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
}

function displayNotification(c_action) {

    // this sets the page background to semi-transparent black should work with all browsers
    var message = "
";

    // center vert
    message = message + "
";

    // this is the message displayed to the user.
    message = message + "This site uses heavy sarcasm, imaginary friends and things that never happened or even might be physically possible.
If you are too much of a sissy to handle that, I prefer would prefer if you just go somewhere else
and click the \"I don't agree\" button.
 Oh, this site also uses some Cloudflare and Github cookies...so here is that standard disclaimer stuff:
In order for this site to work correctly, and for us to improve the site we need to store a small file (called a cookie) on your computer.
 Most every site in the world does this, however it seems that now, by law, we have to get your permission first.
 If you click agree below we will store all needed cookies and you'll notice no difference, if you click on I don't agree we will send you on your merry way..far, far, VERY away from here.
";

    // Displays the I agree/disagree buttons.
    // Feel free to change the address of the I disagree redirection to either a non-cookie site or a Google or the ICO web site
    message = message + "
<INPUT TYPE='button' VALUE='I Agree' onClick='JavaScript:doAccept();' /> <INPUT TYPE='button' VALUE=\"I don't agree\" onClick='JavaScript:doNotAccept("
	message = message + c_action;
	message = message + ");' />";

    // and this closes everything off.
    message = message + "

";

    document.writeln(message);
}

function doAccept() {
    setCookie("ILoveAr0xA", null, 365);
    location.reload(true);
}

function doNotAccept(c_action) {

	if (c_action == 1) {
		setCookie("ImSuperLame", null, 365);
		location.reload(true);
		window.location.replace("http://www.quickmeme.com/img/0a/0a6263074c7ce94f09dae0aa3721d1726564ae899a2b97994ccefcbf78161076.jpg");
	} else {
		window.location.replace("http://www.quickmeme.com/img/0a/0a6263074c7ce94f09dae0aa3721d1726564ae899a2b97994ccefcbf78161076.jpg");
	}
}

function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString() + "; path=/");
    document.cookie = c_name + "=" + c_value;
}

function checkCookie(c_action) {

    var cookieName = "ILoveAr0xA";
    var cookieNameNo = "ImSuperLame";
    var cookieChk = getCookie(cookieName);
    var cookieChkNo = getCookie(cookieNameNo);
    if (cookieChk != null && cookieChk != "") {
        // the jsCookieCheck cookie exists so we can assume the person has read the notification
        // within the last year and has accepted the use of cookies

        setCookie(cookieName, cookieChk, 365); // set the cookie to expire in a year.
    }
    else if (cookieChkNo != null && cookieChkNo != "") {
        // the ImSuperLame cookie exists so we can assume the person has read the notification
        // within the last year and has declined the use of cookies

        setCookie(cookieNameNo, cookieChkNo, 365); // set the cookie to expire in a year.
    }
    else {
        // No cookie exists, so display the lightbox effect notification.
        displayNotification(c_action);
    }
}

// blockOrCarryOn - 1 = Carry on, store a do not store cookies cookie and carry on
//					0 = Block, redirect the user to a different website (google for example)
var blockOrCarryOn = 1;
checkCookie(blockOrCarryOn);
<commit_msg>shorter<commit_after>/////////////////////////////////////////////////////////////
//
// Author Scott Herbert (www.scott-herbert.com)
//		  Dimitri Kourkoulis (http://dimitros.net/en/home)
//
// Version History
// 1 (10-Feb-2013) Inital release on to GitHub.
//
// 2 (12-Mar-2013) Small modification by Dimitri Kourkoulis.
//    This version of the script, keeps visitors on the web site
//    if they decline the use of cookies. However, in that event,
//    the cookie stored in their browser is named 'jsNoCookieCheck'
//    instead of 'jsCookieCheck'. This can be used by the software
//    and/or CMS of the web site to disable cookie producing content.
//    An example of how this has been used in one case on the Umbraco
//    CMS can be found here:
//    http://dimitros.net/en/blog/complyingwiththecookielaw
//
// 3 (03-April-2013) SAH - Added a variable that allows the developer to
//	  select if the script redirects (as it originally did) or carry?s
//    on (as per Dimitri?s great addition).
//
// Download from http://adf.ly/IvElY

function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
}

function displayNotification(c_action) {

    // this sets the page background to semi-transparent black should work with all browsers
    var message = "
";

    // center vert
    message = message + "
";

    // this is the message displayed to the user.
    message = message + "This site uses heavy sarcasm, imaginary friends and things that never happened or even might be physically possible.
If you are too much of a sissy to handle that, I prefer would prefer if you just go somewhere else
and click the \"I don't agree\" button.
 Oh, this site also uses some Cloudflare and Github cookies...so here is that standard disclaimer stuff:
In order for this site to work correctly, and for us to improve the site we need to store a small file (called a cookie) on your computer.
 Most every site in the world does this, however it seems that now, by law, we have to get your permission first.
 If you click agree below we will store all needed cookies and you'll notice no difference, if you click on I don't agree we will send you on your merry way..far, far, VERY away from here.
";

    // Displays the I agree/disagree buttons.
    // Feel free to change the address of the I disagree redirection to either a non-cookie site or a Google or the ICO web site
    message = message + "
<INPUT TYPE='button' VALUE='I Agree' onClick='JavaScript:doAccept();' /> <INPUT TYPE='button' VALUE=\"I don't agree\" onClick='JavaScript:doNotAccept("
	message = message + c_action;
	message = message + ");' />";

    // and this closes everything off.
    message = message + "

";

    document.writeln(message);
}

function doAccept() {
    setCookie("ILoveAr0xA", null, 365);
    location.reload(true);
}

function doNotAccept(c_action) {

	if (c_action == 1) {
		setCookie("ImSuperLame", null, 365);
		//location.reload(true);
		window.location.replace("http://www.quickmeme.com/img/0a/0a6263074c7ce94f09dae0aa3721d1726564ae899a2b97994ccefcbf78161076.jpg");
	} else {
		window.location.replace("http://www.quickmeme.com/img/0a/0a6263074c7ce94f09dae0aa3721d1726564ae899a2b97994ccefcbf78161076.jpg");
	}
}

function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString() + "; path=/");
    document.cookie = c_name + "=" + c_value;
}

function checkCookie(c_action) {

    var cookieName = "ILoveAr0xA";
    var cookieNameNo = "ImSuperLame";
    var cookieChk = getCookie(cookieName);
    var cookieChkNo = getCookie(cookieNameNo);
    if (cookieChk != null && cookieChk != "") {
        // the jsCookieCheck cookie exists so we can assume the person has read the notification
        // within the last year and has accepted the use of cookies

        setCookie(cookieName, cookieChk, 365); // set the cookie to expire in a year.
    }
    else if (cookieChkNo != null && cookieChkNo != "") {
        // the ImSuperLame cookie exists so we can assume the person has read the notification
        // within the last year and has declined the use of cookies

        setCookie(cookieNameNo, cookieChkNo, 365); // set the cookie to expire in a year.
    }
    else {
        // No cookie exists, so display the lightbox effect notification.
        displayNotification(c_action);
    }
}

// blockOrCarryOn - 1 = Carry on, store a do not store cookies cookie and carry on
//					0 = Block, redirect the user to a different website (google for example)
var blockOrCarryOn = 1;
checkCookie(blockOrCarryOn);
<|endoftext|>


<commit_before>var results  = {};
var promises = [];
$(document).ready(function() {
  // la magia aquí

  $.whenall = function(arr) {
    return $.when.apply($, arr).pipe(function() {
      return Array.prototype.slice.call(arguments);
    });
  };

  var
    vids = [
    'ozj2-bnTL3s',
    'EAZ4Tlt8MQ4',
    'Xn9o7cxqVoA','xxx','xxx','xxx','xxx','xxx'
  ],
  url = 'http://gdata.youtube.com/feeds/api/videos/{{vid}}?v=2&alt=json',
  promise = null;

  $.each(vids, function(idx, vid){
    var u = url.replace('{{vid}}', vids[idx]);
    $.ajaxSetup({cache: false});
    $.getJSON( u ).done(function(data) {
      promises.push(this);
      results[vid] = data.entry;
    }).fail(function(){
      //
    });
  });

  $.when.apply($, promises).then(function(){
    console.log('éxito');
    console.log(results);
  });

});
<commit_msg>simple promises<commit_after>var
  results  = {},
  promises = [];

$(document).ready(function() {
  // la magia aquí

  var
    vids = [
    'ozj2-bnTL3s',
    'EAZ4Tlt8MQ4',
    'Xn9o7cxqVoA',
    'xxx',
    'xxx',
    'xxx',
    'xxx'
  ],
  url = 'http://gdata.youtube.com/feeds/api/videos/{{vid}}?v=2&alt=json';

  $.each(vids, function(idx, vid){
    var u = url.replace('{{vid}}', vids[idx]);
    promises.push($.getJSON( u ).done(function(data) {
      results[vid] = data.entry;
    }));
  });

  $.when.apply($, promises).done(function(){
    console.log(promises);
  });

});
<|endoftext|>


<commit_before>// load the things we need
var mongoose = require('mongoose');

// define the schema for our position model
var telemetrySchema = mongoose.Schema({

    timestamp : {
    	notes: String,
        category: String,
        name: String,
        alarm_low: Date,
        warn_low: Date,
        value: Date,
        warn_high: Date,
        alarm_high: Date,
        units: String
    },
    vehicleId : {
    	notes: String,
        category: String,
        name: String,
        alarm_low: String,
        warn_low: String,
        value: String,
        warn_high: String,
        alarm_high: String,
        units: String
    },
    vx : {
    	notes: String,
        category: String,
        name: String,
        alarm_low: Number,
        warn_low: Number,
        value: Number,
        warn_high: Number,
        alarm_high: Number,
        units: String
    },
    vy : {
    	notes: String,
        category: String,
        name: String,
        alarm_low: Number,
        warn_low: Number,
        value: Number,
        warn_high: Number,
        alarm_high: Number,
        units: String
    },
    vz : {
    	notes: String,
        category: String,
        name: String,
        alarm_low: Number,
        warn_low: Number,
        value: Number,
        warn_high: Number,
        alarm_high: Number,
        units: String
    },
    x : {
    	notes: String,
        category: String,
        name: String,
        alarm_low: Number,
        warn_low: Number,
        value: Number,
        warn_high: Number,
        alarm_high: Number,
        units: String
    },
    y : {
    	notes: String,
        category: String,
        name: String,
        alarm_low: Number,
        warn_low: Number,
        value: Number,
        warn_high: Number,
        alarm_high: Number,
        units: String
    },
    z : {
    	notes: String,
        category: String,
        name: String,
        alarm_low: Number,
        warn_low: Number,
        value: Number,
        warn_high: Number,
        alarm_high: Number,
        units: String
    },
    r : {
    	notes: String,
        category: String,
        name: String,
        alarm_low: Number,
        warn_low: Number,
        value: Number,
        warn_high: Number,
        alarm_high: Number,
        units: String
    },
    v : {
    	notes: String,
        category: String,
        name: String,
        alarm_low: Number,
        warn_low: Number,
        value: Number,
        warn_high: Number,
        alarm_high: Number,
        units: String
    },
    longitude : {
        notes: String,
        category: String,
        name: String,
        alarm_low: Number,
        warn_low: Number,
        value: Number,
        warn_high: Number,
        alarm_high: Number,
        units: String
    },
    latitude : {
        notes: String,
        category: String,
        name: String,
        alarm_low: Number,
        warn_low: Number,
        value: Number,
        warn_high: Number,
        alarm_high: Number,
        units: String
    },
    stationId : {
        notes: String,
        category: String,
        name: String,
        alarm_low: String,
        warn_low: String,
        value: String,
        warn_high: String,
        alarm_high: String,
        units: String
    }

}, { collection: 'telemetry' });

// create the model for users and expose it to our app
module.exports = mongoose.model('Telemetry', telemetrySchema);<commit_msg>modified model for quaternion data<commit_after>// load the things we need
var mongoose = require('mongoose');

// define the schema for our position model
var telemetrySchema = mongoose.Schema({

    timestamp : {
    	notes: String,
        category: String,
        name: String,
        alarm_low: Date,
        warn_low: Date,
        value: Date,
        warn_high: Date,
        alarm_high: Date,
        units: String
    },
    vehicleId : {
    	notes: String,
        category: String,
        name: String,
        alarm_low: String,
        warn_low: String,
        value: String,
        warn_high: String,
        alarm_high: String,
        units: String
    },
    vx : {
    	notes: String,
        category: String,
        name: String,
        alarm_low: Number,
        warn_low: Number,
        value: Number,
        warn_high: Number,
        alarm_high: Number,
        units: String
    },
    vy : {
    	notes: String,
        category: String,
        name: String,
        alarm_low: Number,
        warn_low: Number,
        value: Number,
        warn_high: Number,
        alarm_high: Number,
        units: String
    },
    vz : {
    	notes: String,
        category: String,
        name: String,
        alarm_low: Number,
        warn_low: Number,
        value: Number,
        warn_high: Number,
        alarm_high: Number,
        units: String
    },
    x : {
    	notes: String,
        category: String,
        name: String,
        alarm_low: Number,
        warn_low: Number,
        value: Number,
        warn_high: Number,
        alarm_high: Number,
        units: String
    },
    y : {
    	notes: String,
        category: String,
        name: String,
        alarm_low: Number,
        warn_low: Number,
        value: Number,
        warn_high: Number,
        alarm_high: Number,
        units: String
    },
    z : {
    	notes: String,
        category: String,
        name: String,
        alarm_low: Number,
        warn_low: Number,
        value: Number,
        warn_high: Number,
        alarm_high: Number,
        units: String
    },
    r : {
    	notes: String,
        category: String,
        name: String,
        alarm_low: Number,
        warn_low: Number,
        value: Number,
        warn_high: Number,
        alarm_high: Number,
        units: String
    },
    v : {
    	notes: String,
        category: String,
        name: String,
        alarm_low: Number,
        warn_low: Number,
        value: Number,
        warn_high: Number,
        alarm_high: Number,
        units: String
    },
    longitude : {
        notes: String,
        category: String,
        name: String,
        alarm_low: Number,
        warn_low: Number,
        value: Number,
        warn_high: Number,
        alarm_high: Number,
        units: String
    },
    latitude : {
        notes: String,
        category: String,
        name: String,
        alarm_low: Number,
        warn_low: Number,
        value: Number,
        warn_high: Number,
        alarm_high: Number,
        units: String
    },
    stationId : {
        notes: String,
        category: String,
        name: String,
        alarm_low: String,
        warn_low: String,
        value: String,
        warn_high: String,
        alarm_high: String,
        units: String
    },
    q1 : {
        notes: String,
        category: String,
        name: String,
        alarm_low: Number,
        warn_low: Number,
        value: Number,
        warn_high: Number,
        alarm_high: Number,
        units: String
    },
    q2 : {
        notes: String,
        category: String,
        name: String,
        alarm_low: Number,
        warn_low: Number,
        value: Number,
        warn_high: Number,
        alarm_high: Number,
        units: String
    },
    q3 : {
        notes: String,
        category: String,
        name: String,
        alarm_low: Number,
        warn_low: Number,
        value: Number,
        warn_high: Number,
        alarm_high: Number,
        units: String
    },
    qc : {
        notes: String,
        category: String,
        name: String,
        alarm_low: Number,
        warn_low: Number,
        value: Number,
        warn_high: Number,
        alarm_high: Number,
        units: String
    }

}, { collection: 'telemetry' });

// create the model for users and expose it to our app
module.exports = mongoose.model('Telemetry', telemetrySchema);<|endoftext|>


<commit_before>import React, {Component, PropTypes} from 'react'
import {Link} from 'react-router'

import Student from '../models/student'
import studentActions from '../flux/student-actions'
import studentStore from '../flux/student-store'

import Button from '../components/button'
import CourseSearcher from './course-searcher'
import GraduationStatus from './graduation-status'
import Icon from '../components/icon'
import Toolbar from '../components/toolbar'

export default class Sidebar extends Component {
	static propTypes = {
		student: PropTypes.instanceOf(Student).isRequired,
	}

	constructor() {
		super()
		this.state = {
			isSearching: false,
		}
	}

	toggleSearch = () => {
		this.setState({isSearching: !this.state.isSearching})
	}

	render() {
		return (
			<aside className='sidebar'>
				<Toolbar className='student-buttons'>
					<Button className='sidebar-btn'>
						<Link to='/' >
							<Icon name='ionicon-ios-list-outline' type='block' />
							Students
						</Link>
					</Button>
					<Button className='sidebar-btn'
						onClick={this.toggleSearch}>
						<Icon name='ionicon-ios-search' type='block' />
						Search
					</Button>
					<Button className='sidebar-btn'>
						<Link to='download' params={{id: this.props.student.id}}>
							<Icon name='ionicon-ios-download-outline' type='block' />
							Download
						</Link>
					</Button>
					<Button className='sidebar-btn'
						onClick={() => studentActions.resetStudentToDemo(this.props.student.id)}>
						<Icon name='ionicon-ios-rose' type='block' />
						Demo
					</Button>
					<Button className='sidebar-btn'
						onClick={studentActions.undo}
						disabled={studentStore.history.size === 0}>
						<Icon name='ionicon-ios-undo' type='block' />
						Undo
					</Button>
					<Button className='sidebar-btn'
						onClick={studentActions.redo}
						disabled={studentStore.future.size === 0}>
						<Icon name='ionicon-ios-redo' type='block' />
						Redo
					</Button>
				</Toolbar>

				<GraduationStatus
					isHidden={this.state.isSearching}
					student={this.props.student} />

				<CourseSearcher
					isHidden={!this.state.isSearching}
					toggle={this.toggleSearch} />
			</aside>
		)
	}
}
<commit_msg>make the undo/redo icons outlines when disabled<commit_after>import React, {Component, PropTypes} from 'react'
import {Link} from 'react-router'

import Student from '../models/student'
import studentActions from '../flux/student-actions'
import studentStore from '../flux/student-store'

import Button from '../components/button'
import CourseSearcher from './course-searcher'
import GraduationStatus from './graduation-status'
import Icon from '../components/icon'
import Toolbar from '../components/toolbar'

export default class Sidebar extends Component {
	static propTypes = {
		student: PropTypes.instanceOf(Student).isRequired,
	}

	constructor() {
		super()
		this.state = {
			isSearching: false,
		}
	}

	toggleSearch = () => {
		this.setState({isSearching: !this.state.isSearching})
	}

	render() {
		return (
			<aside className='sidebar'>
				<Toolbar className='student-buttons'>
					<Button className='sidebar-btn'>
						<Link to='/' >
							<Icon name='ionicon-ios-list-outline' type='block' />
							Students
						</Link>
					</Button>
					<Button className='sidebar-btn'
						onClick={this.toggleSearch}>
						<Icon name='ionicon-ios-search' type='block' />
						Search
					</Button>
					<Button className='sidebar-btn'>
						<Link to='download' params={{id: this.props.student.id}}>
							<Icon name='ionicon-ios-download-outline' type='block' />
							Download
						</Link>
					</Button>
					<Button className='sidebar-btn'
						onClick={() => studentActions.resetStudentToDemo(this.props.student.id)}>
						<Icon name='ionicon-ios-rose' type='block' />
						Demo
					</Button>
					<Button className='sidebar-btn'
						onClick={studentActions.undo}
						disabled={studentStore.history.size === 0}>
						<Icon name={`ionicon-ios-undo${studentStore.history.size === 0 ? '-outline' : ''}`} type='block' />
						Undo
					</Button>
					<Button className='sidebar-btn'
						onClick={studentActions.redo}
						disabled={studentStore.future.size === 0}>
						<Icon name={`ionicon-ios-redo${studentStore.future.size === 0 ? '-outline' : ''}`} type='block' />
						Redo
					</Button>
				</Toolbar>

				<GraduationStatus
					isHidden={this.state.isSearching}
					student={this.props.student} />

				<CourseSearcher
					isHidden={!this.state.isSearching}
					toggle={this.toggleSearch} />
			</aside>
		)
	}
}
<|endoftext|>


<commit_before>/* global Backbone, Raphael */
var GameObject = Backbone.RaphaelView.extend({
    // object methods
}, {
    startX        : 0,
    startY        : 100,
    squareWidth   : 50,
    squareHeight  : 30,
    squareDistance: 10,
    borderDepth   : 20,
    getPaper      : function () {
        return GameObject.paper || (GameObject.paper = new Raphael('holder', 800, 540));
    }
});<commit_msg>change board size<commit_after>/* global Backbone, Raphael */
var GameObject = Backbone.RaphaelView.extend({
    // object methods
}, {
    startX        : 0,
    startY        : 100,
    squareWidth   : 50,
    squareHeight  : 30,
    squareDistance: 10,
    borderDepth   : 20,
    getPaper      : function () {
        return GameObject.paper || (GameObject.paper = new Raphael('holder', 580, 540));
    }
});<|endoftext|>


<commit_before>import { createSelector } from 'reselect/src/index.js'
import { collator } from '../utils/index.js'

/*
 * Selectors help you to retrieve data from the state so you don't have to write the
 * same code to access the state over and over again. It also helps to have a central position
 * on how to access the state
 *
 * We also make use of reselect which makes it possible to use a selector as a statePath inside any component
 * -> https://github.com/reactjs/reselect
 * -> https://redux.js.org/docs/recipes/ComputingDerivedData.html
 */
export const getBpm = state => state.bpm
export const getDrawerOpened = state => state.app.drawerOpened
export const getLive = state => state.live
export const getConnections = state => state.connectionManager
export const getUniverses = state => state.universeManager
export const getScenes = state => state.sceneManager
export const getAnimations = state => state.animationManager
export const getFixtures = state => state.fixtureManager
export const getTimeline = state => state.timelineManager
export const getTimelineSceneIds = state => state.timelineManager.scenes
export const getModv = state => state.modvManager
export const getModvUrl = state => state.modvManager.url
export const getModvReconnect = state => state.modvManager.reconnect
export const getModvConnected = state => state.modvManager.connected
export const getMidi = state => state.midiManager
export const getMidiEnabled = state => state.midiManager.enabled
export const getMidiControllers = state => state.midiManager.controllers
export const getMidiLearning = state => state.midiManager.learning
export const getDekk = state => state.dekkManager
export const getDekkConnected = state => state.dekkManager.connected
export const getDekkData = state => state.dekkManager.data
export const getFivetwelveConnected = state => state.fivetwelveManager.connected
export const getUsbDmxControllerConnected = state => state.connectionManager.usb.connected
export const getVenues = state => state.venueManager

export const getAnimation = (state, properties) => {
  return getAnimations(state)
    .filter(animation => animation.id === properties.animationId)[0]
}

/*
 * Sort animations by animation.name
 */
export const getAnimationsSorted = createSelector(
  getAnimations,
  animations => animations.sort((a, b) => collator.compare(a.name, b.name))
)

export const getScene = (state, properties) => {
  return getScenes(state)
    .filter(scene => scene.id === properties.sceneId)[0]
}

// @TODO: This will be a problem because name is not unique
export const getSceneByName = (state, properties) => {
  return getScenes(state)
    .filter(scene => scene.name === properties.name)[0]
}

/*
 * Sort scenes by scene.name
 */
export const getScenesSorted = createSelector(
  getScenes,
  scenes => scenes.sort((a, b) => collator.compare(a.name, b.name))
)

/*
 * Get scenes that are part of the timeline
 */
 export const getTimelineScenes = createSelector(
   getScenes,
   getTimelineSceneIds,
   (scenes, timelineSceneIds) => {
     return scenes.filter(scene => {
       return timelineSceneIds.includes(scene.id)
     })
   }
 )

/*
 * Get a specific fixture by using the fixtureId
 */
export const getFixture = (state, properties) => {
  return getFixtures(state)
    .filter(fixture => fixture.id === properties.fixtureId)[0]
}

/*
 * Get a specific fixture by using the fixtureId
 */
export const getVenue = (state, properties) => {
  return getVenues(state)
    .filter(venue => venue.id === properties.venueId)[0]
}

/*
 * Sort venues by venue.name
 */
export const getVenuesSorted = createSelector(
  getVenues,
  venues => venues.sort((a, b) => collator.compare(a.name, b.name))
)

/*
 * Sort fixtures by fixture.name
 */
export const getFixturesSorted = createSelector(
  getFixtures,
  fixtures => fixtures.sort((a, b) => collator.compare(a.name, b.name))
)
<commit_msg>feat(selector): Is timeline playing?<commit_after>import { createSelector } from 'reselect/src/index.js'
import { collator } from '../utils/index.js'

/*
 * Selectors help you to retrieve data from the state so you don't have to write the
 * same code to access the state over and over again. It also helps to have a central position
 * on how to access the state
 *
 * We also make use of reselect which makes it possible to use a selector as a statePath inside any component
 * -> https://github.com/reactjs/reselect
 * -> https://redux.js.org/docs/recipes/ComputingDerivedData.html
 */
export const getBpm = state => state.bpm
export const getDrawerOpened = state => state.app.drawerOpened
export const getLive = state => state.live
export const getConnections = state => state.connectionManager
export const getUniverses = state => state.universeManager
export const getScenes = state => state.sceneManager
export const getAnimations = state => state.animationManager
export const getFixtures = state => state.fixtureManager
export const getTimeline = state => state.timelineManager
export const getTimelinePlaying = state => state.timelineManager.playing
export const getTimelineSceneIds = state => state.timelineManager.scenes
export const getModv = state => state.modvManager
export const getModvUrl = state => state.modvManager.url
export const getModvReconnect = state => state.modvManager.reconnect
export const getModvConnected = state => state.modvManager.connected
export const getMidi = state => state.midiManager
export const getMidiEnabled = state => state.midiManager.enabled
export const getMidiControllers = state => state.midiManager.controllers
export const getMidiLearning = state => state.midiManager.learning
export const getDekk = state => state.dekkManager
export const getDekkConnected = state => state.dekkManager.connected
export const getDekkData = state => state.dekkManager.data
export const getFivetwelveConnected = state => state.fivetwelveManager.connected
export const getUsbDmxControllerConnected = state => state.connectionManager.usb.connected
export const getVenues = state => state.venueManager

export const getAnimation = (state, properties) => {
  return getAnimations(state)
    .filter(animation => animation.id === properties.animationId)[0]
}

/*
 * Sort animations by animation.name
 */
export const getAnimationsSorted = createSelector(
  getAnimations,
  animations => animations.sort((a, b) => collator.compare(a.name, b.name))
)

export const getScene = (state, properties) => {
  return getScenes(state)
    .filter(scene => scene.id === properties.sceneId)[0]
}

// @TODO: This will be a problem because name is not unique
export const getSceneByName = (state, properties) => {
  return getScenes(state)
    .filter(scene => scene.name === properties.name)[0]
}

/*
 * Sort scenes by scene.name
 */
export const getScenesSorted = createSelector(
  getScenes,
  scenes => scenes.sort((a, b) => collator.compare(a.name, b.name))
)

/*
 * Get scenes that are part of the timeline
 */
 export const getTimelineScenes = createSelector(
   getScenes,
   getTimelineSceneIds,
   (scenes, timelineSceneIds) => {
     return scenes.filter(scene => {
       return timelineSceneIds.includes(scene.id)
     })
   }
 )

/*
 * Get a specific fixture by using the fixtureId
 */
export const getFixture = (state, properties) => {
  return getFixtures(state)
    .filter(fixture => fixture.id === properties.fixtureId)[0]
}

/*
 * Get a specific fixture by using the fixtureId
 */
export const getVenue = (state, properties) => {
  return getVenues(state)
    .filter(venue => venue.id === properties.venueId)[0]
}

/*
 * Sort venues by venue.name
 */
export const getVenuesSorted = createSelector(
  getVenues,
  venues => venues.sort((a, b) => collator.compare(a.name, b.name))
)

/*
 * Sort fixtures by fixture.name
 */
export const getFixturesSorted = createSelector(
  getFixtures,
  fixtures => fixtures.sort((a, b) => collator.compare(a.name, b.name))
)
<|endoftext|>