<commit_before>/* globals jQuery, window, document */

(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS
        module.exports = factory(require('jquery'));
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function($) {

  var methods = {
    options : {
      "optionClass": "",
      "dropdownClass": "",
      "autoinit": false,
      "callback": false,
      "onSelected": false,
      "destroy": function(element) {
        this.destroy(element);
      },
      "dynamicOptLabel": "Add a new option..."
    },
    init: function(options) {

      // Apply user options if user has defined some
      if (options) {
        options = $.extend(methods.options, options);
      } else {
        options = methods.options;
      }

      function initElement($select) {
        // Don't do anything if this is not a select or if this select was already initialized
        if ($select.data("dropdownjs") || !$select.is("select")) {
          return;
        }

        // Is it a multi select?
        var multi = $select.attr("multiple");

        // Does it allow to create new options dynamically?
        var dynamicOptions = $select.attr("data-dynamic-opts"),
            $dynamicInput = $();

        // Create the dropdown wrapper
        var $dropdown = $("

");
        $dropdown.addClass("dropdownjs").addClass(options.dropdownClass);
        $dropdown.data("select", $select);

        // Create the fake input used as "select" element and cache it as $input
        var $input = $("<input type=text readonly class=fakeinput>");
        if ($.material) { $input.data("mdproc", true); }
        // Append it to the dropdown wrapper
        $dropdown.append($input);

        // Create the UL that will be used as dropdown and cache it AS $ul
        var $ul = $("

");
        $ul.data("select", $select);

        // Append it to the dropdown
        $dropdown.append($ul);

        // Transfer the placeholder attribute
        $input.attr("placeholder", $select.attr("placeholder"));

        // Loop trough options and transfer them to the dropdown menu
        $select.find("option").each(function() {
          // Cache $(this)
          var $this = $(this);
          methods._addOption($ul, $this);

        });

        // If this select allows dynamic options add the widget
        if (dynamicOptions) {
          $dynamicInput = $("

");
          $dynamicInput.append("<input>");
          $dynamicInput.find("input").attr("placeholder", options.dynamicOptLabel);
          $ul.append($dynamicInput);
        }

        // Cache the dropdown options
        var selectOptions = $dropdown.find("li");

        // If is a single select, selected the first one or the last with selected attribute
        if (!multi) {
            var $selected;
            if ($select.find(":selected").length) {
                $selected = $select.find(":selected").last();
            }
            else {
                $selected = $select.find("option, li").first();
               // $selected = $select.find("option").first();
            }
            methods._select($dropdown, $selected);
        } else {
            var selectors = [], val = $select.val()
            for (var i in val) {
              selectors.push('li[value=' + val[i] + ']')
            }
            if (selectors.length > 0) {
              var $target = $dropdown.find(selectors.join(','));
              $target.removeClass("selected");
              methods._select($dropdown, $target);
            }
        }

        // Transfer the classes of the select to the input dropdown
        $input.addClass($select[0].className);

        // Hide the old and ugly select
        $select.hide().attr("data-dropdownjs", true);

        // Bring to life our awesome dropdownjs
        $select.after($dropdown);

        // Call the callback
        if (options.callback) {
          options.callback($dropdown);
        }

        //---------------------------------------//
        // DROPDOWN EVENTS                       //
        //---------------------------------------//

        // On click, set the clicked one as selected
        $ul.on("click", "li:not(.dropdownjs-add)", function(e) {
          methods._select($dropdown, $(this));
          // trigger change event, if declared on the original selector
          $select.change();
        });
        $ul.on("keydown", "li:not(.dropdownjs-add)", function(e) {
          if (e.which === 27) {
            $(".dropdownjs > ul > li").attr("tabindex", -1);
            return $input.removeClass("focus").blur();
          }
          if (e.which === 32 && !$(e.target).is("input")) {
            methods._select($dropdown, $(this));
            return false;
          }
        });

        $ul.on("focus", "li:not(.dropdownjs-add)", function() {
          if ($select.is(":disabled")) {
            return;
          }
          $input.addClass("focus");
        });

        // Add new options when the widget is used
        if (dynamicOptions && dynamicOptions.length) {
          $dynamicInput.on("keydown", function(e) {
            if(e.which !== 13) return;
            var $option = $("<option>"),
                val = $dynamicInput.find("input").val();
            $dynamicInput.find("input").val("");

            $option.attr("value", val);
            $option.text(val);
            $select.append($option);

          });
        }

        // Listen for new added options and update dropdown if needed
        $select.on("DOMNodeInserted", function(e) {
          var $this = $(e.target);
          if (!$this.val().length) return;

          methods._addOption($ul, $this);
          $ul.find("li").not(".dropdownjs-add").attr("tabindex", 0);

        });

        $select.on("DOMNodeRemoved", function(e) {
          var deletedValue = e.target.getAttribute('value');
          $ul.find("li[value='"+deletedValue+"']").remove();
          var $selected;

          setTimeout(function () {
            if ($select.find(":selected").length) {
              $selected = $select.find(":selected").last();
            }
            else {
              $selected = $select.find("option, li").first();
            }
            methods._select($dropdown, $selected);
          }, 100);

        });

        // Update dropdown when using val, need to use .val("value").trigger("change");
        $select.on("change", function(e) {
          var $this = $(e.target);

          if (!multi) {
            var $selected;
            if ($select.find(":selected").length) {
              $selected = $select.find(":selected").last();
            }
            else {
              $selected = $select.find("option, li").first();
            }
            methods._select($dropdown, $selected);
          } else {
            var target = $select.find(":selected");
            // Unselect all options
            selectOptions.removeClass("selected");
            // Select options
            target.each(function () {
                var selected = selectOptions.filter("[value=\"" + $(this).attr("value") + "\"]");
                selected.addClass("selected");
            });
          }
        });

        // Used to make the dropdown menu more dropdown-ish
        $input.on("click focus", function(e) {
          e.stopPropagation();
          if ($select.is(":disabled")) {
            return;
          }
          $(".dropdownjs > ul > li").attr("tabindex", -1);
          $(".dropdownjs > input").not($(this)).removeClass("focus").blur();

          $(".dropdownjs > ul > li").not(".dropdownjs-add").attr("tabindex", 0);

          // Set height of the dropdown
          var coords = {
            top: $(this).offset().top - $(document).scrollTop(),
            left: $(this).offset().left - $(document).scrollLeft(),
            bottom: $(window).height() - ($(this).offset().top - $(document).scrollTop()),
            right: $(window).width() - ($(this).offset().left - $(document).scrollLeft())
          };

          var height = coords.bottom;

          // Decide if place the dropdown below or above the input
          if (height < 200 && coords.top > coords.bottom) {
            height = coords.top;
            $ul.attr("placement", "top-left");
          } else {
            $ul.attr("placement", "bottom-left");
          }

          $(this).next("ul").css("max-height", height - 20);
          $(this).addClass("focus");
        });
        // Close every dropdown on click outside
        $(document).on("click", function(e) {

          // Don't close the multi dropdown if user is clicking inside it
          if (multi && $(e.target).parents(".dropdownjs").length) return;

          // Don't close the dropdown if user is clicking inside the dynamic-opts widget
          if ($(e.target).parents(".dropdownjs-add").length || $(e.target).is(".dropdownjs-add")) return;

          // Close opened dropdowns
          $(".dropdownjs > ul > li").attr("tabindex", -1);
            if ($(e.target).hasClass('disabled')) {
              return;
        }
          $input.removeClass("focus");
        });
      }

      if (options.autoinit) {
        $(document).on("DOMNodeInserted", function(e) {
          var $this = $(e.target);
          if (!$this.is("select")) {
            $this = $this.find('select');
          }
            $this.each(function() {
                if ($(this).is(options.autoinit)) {
                    initElement($(this));
                }
            });
        });
      }

      // Loop trough elements
      $(this).each(function() {
        initElement($(this));
      });
    },
    select: function(target) {
      var $target = $(this).find("[value=\"" + target + "\"]");
      methods._select($(this), $target);
    },
    _select: function($dropdown, $target) {

      if ($target.is(".dropdownjs-add")) return;

      // Get dropdown's elements
      var $select = $dropdown.data("select"),
          $input  = $dropdown.find("input.fakeinput");
      // Is it a multi select?
      var multi = $select.attr("multiple");

      // Cache the dropdown options
      var selectOptions = $dropdown.find("li");

      // Behavior for multiple select
      if (multi) {
        // Toggle option state
        $target.toggleClass("selected");
        // Toggle selection of the clicked option in native select
        $target.each(function(){
          var $selected = $select.find("[value=\"" + $(this).attr("value") + "\"]");
          $selected.prop("selected", $(this).hasClass("selected"));
        });
        // Add or remove the value from the input
        var text = [];
        selectOptions.each(function() {
          if ($(this).hasClass("selected")) {
            text.push($(this).text());
          }
        });
        $input.val(text.join(", "));
      }

      // Behavior for single select
      if (!multi) {
        if ($target.hasClass("disabled")) {
          return;
        }
        // Unselect options except the one that will be selected
        if ($target.is("li")) {
            selectOptions.not($target).removeClass("selected");
        }
        // Select the selected option
        $target.addClass("selected");
        // Set the value to the native select
        $select.val($target.attr("value"));
        // Set the value to the input
        $input.val($target.text().trim());
      }

      // This is used only if Material Design for Bootstrap is selected
      if ($.material) {
        if ($input.val().trim()) {
          $select.removeClass("empty");
        } else {
          $select.addClass("empty");
        }
      }

       // Call the callback
        if (this.options.onSelected) {
            this.options.onSelected($target.attr("value"));
        }

    },
    _addOption: function($ul, $this) {
      // Create the option
      var $option = $("

");

      // Style the option
      $option.addClass(this.options.optionClass);

      // If the option has some text then transfer it
      if ($this.text()) {
        $option.text($this.text());
      }
      // Otherwise set the empty label and set it as an empty option
      else {
        $option.html(" ");
      }
      // Set the value of the option
      $option.attr("value", $this.val());

      // Will user be able to remove this option?
      if ($ul.data("select").attr("data-dynamic-opts")) {
        $option.append("");
        $option.find(".close").on("click", function() {
          $option.remove();
          $this.remove();
        });
      }

      // Ss it selected?
      if ($this.prop("selected")) {
        $option.attr("selected", true);
        $option.addClass("selected");
      }

      if ($this.prop("disabled")) {
        $option.addClass("disabled");
      }

      // Append option to our dropdown
      if ($ul.find(".dropdownjs-add").length) {
        $ul.find(".dropdownjs-add").before($option);
      } else {
        $ul.append($option);
      }
    },
    destroy: function($e) {
      $($e).show().removeAttr('data-dropdownjs').next('.dropdownjs').remove();
    }
  };

  $.fn.dropdown = function(params) {
    if( typeof methods[params] == 'function' ) methods[params](this);
    if (methods[params]) {
      return methods[params].apply(this, Array.prototype.slice.call(arguments,1));
    } else if (typeof params === "object" | !params) {
      return methods.init.apply(this, arguments);
    } else {
      $.error("Method " + params + " does not exists on jQuery.dropdown");
    }
  };

}));
<commit_msg>Changed some javascript syntax to jquery<commit_after>/* globals jQuery, window, document */

(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS
        module.exports = factory(require('jquery'));
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function($) {

  var methods = {
    options : {
      "optionClass": "",
      "dropdownClass": "",
      "autoinit": false,
      "callback": false,
      "onSelected": false,
      "destroy": function(element) {
        this.destroy(element);
      },
      "dynamicOptLabel": "Add a new option..."
    },
    init: function(options) {

      // Apply user options if user has defined some
      if (options) {
        options = $.extend(methods.options, options);
      } else {
        options = methods.options;
      }

      function initElement($select) {
        // Don't do anything if this is not a select or if this select was already initialized
        if ($select.data("dropdownjs") || !$select.is("select")) {
          return;
        }

        // Is it a multi select?
        var multi = $select.attr("multiple");

        // Does it allow to create new options dynamically?
        var dynamicOptions = $select.attr("data-dynamic-opts"),
            $dynamicInput = $();

        // Create the dropdown wrapper
        var $dropdown = $("

");
        $dropdown.addClass("dropdownjs").addClass(options.dropdownClass);
        $dropdown.data("select", $select);

        // Create the fake input used as "select" element and cache it as $input
        var $input = $("<input type=text readonly class=fakeinput>");
        if ($.material) { $input.data("mdproc", true); }
        // Append it to the dropdown wrapper
        $dropdown.append($input);

        // Create the UL that will be used as dropdown and cache it AS $ul
        var $ul = $("

");
        $ul.data("select", $select);

        // Append it to the dropdown
        $dropdown.append($ul);

        // Transfer the placeholder attribute
        $input.attr("placeholder", $select.attr("placeholder"));

        // Loop trough options and transfer them to the dropdown menu
        $select.find("option").each(function() {
          // Cache $(this)
          var $this = $(this);
          methods._addOption($ul, $this);

        });

        // If this select allows dynamic options add the widget
        if (dynamicOptions) {
          $dynamicInput = $("

");
          $dynamicInput.append("<input>");
          $dynamicInput.find("input").attr("placeholder", options.dynamicOptLabel);
          $ul.append($dynamicInput);
        }

        // Cache the dropdown options
        var selectOptions = $dropdown.find("li");

        // If is a single select, selected the first one or the last with selected attribute
        if (!multi) {
            var $selected;
            if ($select.find(":selected").length) {
                $selected = $select.find(":selected").last();
            }
            else {
                $selected = $select.find("option, li").first();
               // $selected = $select.find("option").first();
            }
            methods._select($dropdown, $selected);
        } else {
            var selectors = [], val = $select.val()
            for (var i in val) {
              selectors.push('li[value=' + val[i] + ']')
            }
            if (selectors.length > 0) {
              var $target = $dropdown.find(selectors.join(','));
              $target.removeClass("selected");
              methods._select($dropdown, $target);
            }
        }

        // Transfer the classes of the select to the input dropdown
        $input.addClass($select[0].className);

        // Hide the old and ugly select
        $select.hide().attr("data-dropdownjs", true);

        // Bring to life our awesome dropdownjs
        $select.after($dropdown);

        // Call the callback
        if (options.callback) {
          options.callback($dropdown);
        }

        //---------------------------------------//
        // DROPDOWN EVENTS                       //
        //---------------------------------------//

        // On click, set the clicked one as selected
        $ul.on("click", "li:not(.dropdownjs-add)", function(e) {
          methods._select($dropdown, $(this));
          // trigger change event, if declared on the original selector
          $select.change();
        });
        $ul.on("keydown", "li:not(.dropdownjs-add)", function(e) {
          if (e.which === 27) {
            $(".dropdownjs > ul > li").attr("tabindex", -1);
            return $input.removeClass("focus").blur();
          }
          if (e.which === 32 && !$(e.target).is("input")) {
            methods._select($dropdown, $(this));
            return false;
          }
        });

        $ul.on("focus", "li:not(.dropdownjs-add)", function() {
          if ($select.is(":disabled")) {
            return;
          }
          $input.addClass("focus");
        });

        // Add new options when the widget is used
        if (dynamicOptions && dynamicOptions.length) {
          $dynamicInput.on("keydown", function(e) {
            if(e.which !== 13) return;
            var $option = $("<option>"),
                val = $dynamicInput.find("input").val();
            $dynamicInput.find("input").val("");

            $option.attr("value", val);
            $option.text(val);
            $select.append($option);

          });
        }

        // Listen for new added options and update dropdown if needed
        $select.on("DOMNodeInserted", function(e) {
          var $this = $(e.target);
          if (!$this.val().length) return;

          methods._addOption($ul, $this);
          $ul.find("li").not(".dropdownjs-add").attr("tabindex", 0);

        });

        $select.on("DOMNodeRemoved", function(e) {
          var deletedValue = $(e.target).attr('value');
          $ul.find("li[value='"+deletedValue+"']").remove();
          var $selected;

          setTimeout(function () {
            if ($select.find(":selected").length) {
              $selected = $select.find(":selected").last();
            }
            else {
              $selected = $select.find("option, li").first();
            }
            methods._select($dropdown, $selected);
          }, 100);

        });

        // Update dropdown when using val, need to use .val("value").trigger("change");
        $select.on("change", function(e) {
          var $this = $(e.target);

          if (!multi) {
            var $selected;
            if ($select.find(":selected").length) {
              $selected = $select.find(":selected").last();
            }
            else {
              $selected = $select.find("option, li").first();
            }
            methods._select($dropdown, $selected);
          } else {
            var target = $select.find(":selected");
            // Unselect all options
            selectOptions.removeClass("selected");
            // Select options
            target.each(function () {
                var selected = selectOptions.filter("[value=\"" + $(this).attr("value") + "\"]");
                selected.addClass("selected");
            });
          }
        });

        // Used to make the dropdown menu more dropdown-ish
        $input.on("click focus", function(e) {
          e.stopPropagation();
          if ($select.is(":disabled")) {
            return;
          }
          $(".dropdownjs > ul > li").attr("tabindex", -1);
          $(".dropdownjs > input").not($(this)).removeClass("focus").blur();

          $(".dropdownjs > ul > li").not(".dropdownjs-add").attr("tabindex", 0);

          // Set height of the dropdown
          var coords = {
            top: $(this).offset().top - $(document).scrollTop(),
            left: $(this).offset().left - $(document).scrollLeft(),
            bottom: $(window).height() - ($(this).offset().top - $(document).scrollTop()),
            right: $(window).width() - ($(this).offset().left - $(document).scrollLeft())
          };

          var height = coords.bottom;

          // Decide if place the dropdown below or above the input
          if (height < 200 && coords.top > coords.bottom) {
            height = coords.top;
            $ul.attr("placement", "top-left");
          } else {
            $ul.attr("placement", "bottom-left");
          }

          $(this).next("ul").css("max-height", height - 20);
          $(this).addClass("focus");
        });
        // Close every dropdown on click outside
        $(document).on("click", function(e) {

          // Don't close the multi dropdown if user is clicking inside it
          if (multi && $(e.target).parents(".dropdownjs").length) return;

          // Don't close the dropdown if user is clicking inside the dynamic-opts widget
          if ($(e.target).parents(".dropdownjs-add").length || $(e.target).is(".dropdownjs-add")) return;

          // Close opened dropdowns
          $(".dropdownjs > ul > li").attr("tabindex", -1);
            if ($(e.target).hasClass('disabled')) {
              return;
        }
          $input.removeClass("focus");
        });
      }

      if (options.autoinit) {
        $(document).on("DOMNodeInserted", function(e) {
          var $this = $(e.target);
          if (!$this.is("select")) {
            $this = $this.find('select');
          }
            $this.each(function() {
                if ($(this).is(options.autoinit)) {
                    initElement($(this));
                }
            });
        });
      }

      // Loop trough elements
      $(this).each(function() {
        initElement($(this));
      });
    },
    select: function(target) {
      var $target = $(this).find("[value=\"" + target + "\"]");
      methods._select($(this), $target);
    },
    _select: function($dropdown, $target) {

      if ($target.is(".dropdownjs-add")) return;

      // Get dropdown's elements
      var $select = $dropdown.data("select"),
          $input  = $dropdown.find("input.fakeinput");
      // Is it a multi select?
      var multi = $select.attr("multiple");

      // Cache the dropdown options
      var selectOptions = $dropdown.find("li");

      // Behavior for multiple select
      if (multi) {
        // Toggle option state
        $target.toggleClass("selected");
        // Toggle selection of the clicked option in native select
        $target.each(function(){
          var $selected = $select.find("[value=\"" + $(this).attr("value") + "\"]");
          $selected.prop("selected", $(this).hasClass("selected"));
        });
        // Add or remove the value from the input
        var text = [];
        selectOptions.each(function() {
          if ($(this).hasClass("selected")) {
            text.push($(this).text());
          }
        });
        $input.val(text.join(", "));
      }

      // Behavior for single select
      if (!multi) {
        if ($target.hasClass("disabled")) {
          return;
        }
        // Unselect options except the one that will be selected
        if ($target.is("li")) {
            selectOptions.not($target).removeClass("selected");
        }
        // Select the selected option
        $target.addClass("selected");
        // Set the value to the native select
        $select.val($target.attr("value"));
        // Set the value to the input
        $input.val($target.text().trim());
      }

      // This is used only if Material Design for Bootstrap is selected
      if ($.material) {
        if ($input.val().trim()) {
          $select.removeClass("empty");
        } else {
          $select.addClass("empty");
        }
      }

       // Call the callback
        if (this.options.onSelected) {
            this.options.onSelected($target.attr("value"));
        }

    },
    _addOption: function($ul, $this) {
      // Create the option
      var $option = $("

");

      // Style the option
      $option.addClass(this.options.optionClass);

      // If the option has some text then transfer it
      if ($this.text()) {
        $option.text($this.text());
      }
      // Otherwise set the empty label and set it as an empty option
      else {
        $option.html(" ");
      }
      // Set the value of the option
      $option.attr("value", $this.val());

      // Will user be able to remove this option?
      if ($ul.data("select").attr("data-dynamic-opts")) {
        $option.append("");
        $option.find(".close").on("click", function() {
          $option.remove();
          $this.remove();
        });
      }

      // Ss it selected?
      if ($this.prop("selected")) {
        $option.attr("selected", true);
        $option.addClass("selected");
      }

      if ($this.prop("disabled")) {
        $option.addClass("disabled");
      }

      // Append option to our dropdown
      if ($ul.find(".dropdownjs-add").length) {
        $ul.find(".dropdownjs-add").before($option);
      } else {
        $ul.append($option);
      }
    },
    destroy: function($e) {
      $($e).show().removeAttr('data-dropdownjs').next('.dropdownjs').remove();
    }
  };

  $.fn.dropdown = function(params) {
    if( typeof methods[params] == 'function' ) methods[params](this);
    if (methods[params]) {
      return methods[params].apply(this, Array.prototype.slice.call(arguments,1));
    } else if (typeof params === "object" | !params) {
      return methods.init.apply(this, arguments);
    } else {
      $.error("Method " + params + " does not exists on jQuery.dropdown");
    }
  };

}));
<|endoftext|>


<commit_before>// Template.createSampleGroup

Template.createSampleGroup.onCreated(function() {
  let instance = this;

  instance.newSampleGroup = new ReactiveVar();
  instance.error = new ReactiveVar();
});

Template.createSampleGroup.helpers({
  nameAndDescription() {
    return SampleGroups.simpleSchema().pick(["name", "description"]);
  },
  error() { return Template.instance().error },
  newSampleGroup() { return Template.instance().newSampleGroup },
});

Template.createSampleGroup.events({
  "click .create-sample-group"(event, instance) {
    let sampleGroup = instance.newSampleGroup.get();

    Meteor.call("createSampleGroup", sampleGroup, (error, selected) => {
      if (error) {
        if (error.reason === "Match failed") {
          // there might be edge cases here which I haven't found yet so other
          // messages might have to be shown instead
          instance.error.set({ header: "Please correct errors above" });
        } else if (!error.details) {
          console.log("error:", error);
          instance.error.set({
            header: "Internal server error",
            message: error.reason || "Error: " + error.error,
          });
        } else {
          console.log("error:", error);
          instance.error.set({
            header: error.reason,
            message: error.details
          });
        }
      } else {
        FlowRouter.setParams({ selected });
      }
    });
  },
});

// Template.showSampleGroup

Template.showSampleGroup.helpers({
  slugToString: MedBook.utility.slugToString,
  downloadUrl() {
    let userId = Meteor.userId();
    let loginToken = Accounts._storedLoginToken();

    return `/download/${userId}/${loginToken}/data-collection/` +
        `SampleGroups/${this._id}`;
  },
  totalSampleCount() {
    return _.reduce(this.data_sets, (memo, sgDataSet) => {
      return memo + sgDataSet.sample_count;
    }, 0);
  },
});

// Sample Group Expression Level & Variance Filters

// Setup the client-side Blobs2 collection
Blobs2 = new Mongo.Collection('blobs');

// Subscribe to associated jobs & blobs
Template.sampleGroupExprVarFilters.onCreated(function(){
  let instance = this;
  let sampleGroupId = instance.data._id ;
  // use Template.subscriptionsReady to know when these are available
  console.log("setting up..."); // XXX
  instance.subscribe("jobsOfType", "ApplyExprAndVarianceFilters");
  console.log("subscribing with id", sampleGroupId); // XXX
  instance.subscribe("blobsAssociatedWithObject", "SampleGroups", sampleGroupId);
});

Template.sampleGroupExprVarFilters.helpers({

  // if a filter has been applied, the download URL for the
  // filtered data; otherwise, 'false'
  urlForFilteredData(){
    let fileName = "sampleGroup_filteredByExprAndVar.tsv"
    let foundBlob = Blobs2.findOne({
      //associated object is the sample group id
      "associated_object.collection_name":"SampleGroups",
      "associated_object.mongo_id":this._id,
      "file_name": fileName,
    });

    console.log("do w have any RELEVANT blobs", foundBlob); // XXX

    if(!foundBlob){return false;}
    // Construct the URL a la downloadUrl above

    // Use the samplegroup name to make a custom download
    // filename. Url encode it since it will be going into a path
    let sampleGroupName = encodeURI(this.name);
    let visibleFileName = `${sampleGroupName}.genes_filtered.tsv`;
    let userId = Meteor.userId();
    let loginToken = Accounts._storedLoginToken();

    let url = `/download/${userId}/${loginToken}/blob/` +
        `${foundBlob._id}/${visibleFileName}`;

    console.log("made url", url); // XXX
    return url;
  },

  // if there is a job currently processing or waiting, return its status;
  // else return false
  isJobRunning(){
    return getFilterJobStatus(this._id);
  },
  // did the job error out
  didJobFail(){
    return ( getFilterJobStatus(this._id) === "error" );
  }
});
// helper for isJobRunning & didJobFail above
// heavily depends on there only ever being 1 job per sample group
// as it will pick an arbitrary one
function getFilterJobStatus(sampleGroupId){
    console.log("checking for jobs with", sampleGroupId); // XXX
    let currentJob = Jobs.findOne({
      '$and': [
        {name: "ApplyExprAndVarianceFilters"},
        {status: {$in: ["creating", "waiting", "running","error"]}},
        {'args.sample_group_id': sampleGroupId},
      ],
    },);
    console.log("found job", currentJob); // XXX
    if(currentJob){ return currentJob.status; } else { return false; }
}

Template.sampleGroupExprVarFilters.events({
  // initiate the expression & variance filter job
  "click .button.run-job": function(event, instance){
    let sampleGroupId = instance.data._id ;
    console.log("about to run the job for expr var filter", sampleGroupId); // XXX
    // TODO anything else before calling the method?
    Meteor.call("applyExprVarianceFilters", sampleGroupId, (error, result) => {
      if(error){
        // TODO recover? throw?
      } else {
        console.log("called meteor method and got result", result); // XXX
        // TODO handle result
      }
    });
  }
});

// Template.waitAndThenPermissionDenied

Template.waitAndThenPermissionDenied.onCreated(function() {
  let instance = this;

  instance.waitForTheServer = new ReactiveVar(true);

  instance.timeoutHandle = Meteor.setTimeout(() => {
    instance.waitForTheServer.set(false);
  }, 15 * 1000);
});

Template.waitAndThenPermissionDenied.events({
  "click .skip-wait"(event, instance) {
    Meteor.clearTimeout(instance.timeoutHandle);

    instance.waitForTheServer.set(false);
  },
});
<commit_msg>remove debug console.logs<commit_after>// Template.createSampleGroup

Template.createSampleGroup.onCreated(function() {
  let instance = this;

  instance.newSampleGroup = new ReactiveVar();
  instance.error = new ReactiveVar();
});

Template.createSampleGroup.helpers({
  nameAndDescription() {
    return SampleGroups.simpleSchema().pick(["name", "description"]);
  },
  error() { return Template.instance().error },
  newSampleGroup() { return Template.instance().newSampleGroup },
});

Template.createSampleGroup.events({
  "click .create-sample-group"(event, instance) {
    let sampleGroup = instance.newSampleGroup.get();

    Meteor.call("createSampleGroup", sampleGroup, (error, selected) => {
      if (error) {
        if (error.reason === "Match failed") {
          // there might be edge cases here which I haven't found yet so other
          // messages might have to be shown instead
          instance.error.set({ header: "Please correct errors above" });
        } else if (!error.details) {
          console.log("error:", error);
          instance.error.set({
            header: "Internal server error",
            message: error.reason || "Error: " + error.error,
          });
        } else {
          console.log("error:", error);
          instance.error.set({
            header: error.reason,
            message: error.details
          });
        }
      } else {
        FlowRouter.setParams({ selected });
      }
    });
  },
});

// Template.showSampleGroup

Template.showSampleGroup.helpers({
  slugToString: MedBook.utility.slugToString,
  downloadUrl() {
    let userId = Meteor.userId();
    let loginToken = Accounts._storedLoginToken();

    return `/download/${userId}/${loginToken}/data-collection/` +
        `SampleGroups/${this._id}`;
  },
  totalSampleCount() {
    return _.reduce(this.data_sets, (memo, sgDataSet) => {
      return memo + sgDataSet.sample_count;
    }, 0);
  },
});

// Sample Group Expression Level & Variance Filters

// Setup the client-side Blobs2 collection
Blobs2 = new Mongo.Collection('blobs');

// Subscribe to associated jobs & blobs
Template.sampleGroupExprVarFilters.onCreated(function(){
  let instance = this;
  let sampleGroupId = instance.data._id ;
  // use Template.subscriptionsReady to know when these are available
  instance.subscribe("jobsOfType", "ApplyExprAndVarianceFilters");
  instance.subscribe("blobsAssociatedWithObject", "SampleGroups", sampleGroupId);
});

Template.sampleGroupExprVarFilters.helpers({

  // if a filter has been applied, the download URL for the
  // filtered data; otherwise, 'false'
  urlForFilteredData(){
    let fileName = "sampleGroup_filteredByExprAndVar.tsv"
    let foundBlob = Blobs2.findOne({
      //associated object is the sample group id
      "associated_object.collection_name":"SampleGroups",
      "associated_object.mongo_id":this._id,
      "file_name": fileName,
    });

    if(!foundBlob){return false;}
    // Construct the URL a la downloadUrl above

    // Use the samplegroup name to make a custom download
    // filename. Url encode it since it will be going into a path
    let sampleGroupName = encodeURI(this.name);
    let visibleFileName = `${sampleGroupName}.genes_filtered.tsv`;
    let userId = Meteor.userId();
    let loginToken = Accounts._storedLoginToken();

    let url = `/download/${userId}/${loginToken}/blob/` +
        `${foundBlob._id}/${visibleFileName}`;
    return url;
  },

  // if there is a job currently processing or waiting, return its status;
  // else return false
  isJobRunning(){
    return getFilterJobStatus(this._id);
  },
  // did the job error out
  didJobFail(){
    return ( getFilterJobStatus(this._id) === "error" );
  }
});
// helper for isJobRunning & didJobFail above
// heavily depends on there only ever being 1 job per sample group
// as it will pick an arbitrary one
function getFilterJobStatus(sampleGroupId){
    let currentJob = Jobs.findOne({
      '$and': [
        {name: "ApplyExprAndVarianceFilters"},
        {status: {$in: ["creating", "waiting", "running","error"]}},
        {'args.sample_group_id': sampleGroupId},
      ],
    },);
    if(currentJob){ return currentJob.status; } else { return false; }
}

Template.sampleGroupExprVarFilters.events({
  // initiate the expression & variance filter job
  "click .button.run-job": function(event, instance){
    let sampleGroupId = instance.data._id ;
    Meteor.call("applyExprVarianceFilters", sampleGroupId, (error, result) => {
      if(error){
        console.log("error:", error);
        if (!error.details) {
          instance.error.set({
            header: "Internal server error",
            message: error.reason || "Error: " + error.error,
          });
        } else {
          instance.error.set({
            header: error.reason,
            message: error.details
          });
        }
      }
      // No action needed if call succeeds.
    });
  }
});

// Template.waitAndThenPermissionDenied

Template.waitAndThenPermissionDenied.onCreated(function() {
  let instance = this;

  instance.waitForTheServer = new ReactiveVar(true);

  instance.timeoutHandle = Meteor.setTimeout(() => {
    instance.waitForTheServer.set(false);
  }, 15 * 1000);
});

Template.waitAndThenPermissionDenied.events({
  "click .skip-wait"(event, instance) {
    Meteor.clearTimeout(instance.timeoutHandle);

    instance.waitForTheServer.set(false);
  },
});
<|endoftext|>


<commit_before>/*
 *  incdec v 0.1.1 - jQuery plugin
 *  Increase or decrease numeric values
 *  written by Diego Ghersi
 *
 *  Copyright 2013, Diego Ghersi
 *  Built for jQuery library
 *  http://jquery.com
 *
 */

(function($) {
  $.fn.idcrease = function(options) {

    var settings = $.extend( {
      'data_type' : 'none',
      'original_value' : 0,
      'next_value' : 100
    }, options);

    return this.each(function() {

        var element = $(this);

        // convert the value to a numeric value
        settings.original_value = parseFloat(settings.original_value);
        settings.next_value = parseFloat(settings.next_value);

        // if the values are the same skip animation
        if (settings.original_value != settings.next_value)
        {
            $({value: settings.original_value}).animate({value: settings.next_value}, {
                duration: 2000,
                easing: 'swing',
                step: function()
                {
                    if (settings.data_type == 'money') {
                        element.text('$' + Math.ceil(this.value));
                    }
                    else if (settings.data_type == 'percentage') {
                        element.text(Math.ceil(this.value) + '%');
                    }
                    else if (settings.data_type == 'none') {
                        element.text(Math.ceil(this.value));
                    }
                },
                complete: function() {
                    if (settings.data_type == 'money') {
                        element.text('$' + settings.next_value);
                    }
                    else if (settings.data_type == 'percentage') {
                        element.text(settings.next_value + '%');
                    }
                    else if (settings.data_type == 'none') {
                        element.text(settings.next_value);
                    }
                }
            });
        }

    });

  };
})( jQuery );<commit_msg>Change name<commit_after>/*
 *  idcrease v 0.1.1 - jQuery plugin
 *  Increase or decrease numeric values
 *  written by Diego Ghersi
 *
 *  Copyright 2013, Diego Ghersi
 *  Built for jQuery library
 *  http://jquery.com
 *
 */

(function($) {
  $.fn.idcrease = function(options) {

    var settings = $.extend( {
      'data_type' : 'none',
      'original_value' : 0,
      'next_value' : 100
    }, options);

    return this.each(function() {

        var element = $(this);

        // convert the value to a numeric value
        settings.original_value = parseFloat(settings.original_value);
        settings.next_value = parseFloat(settings.next_value);

        // if the values are the same skip animation
        if (settings.original_value != settings.next_value)
        {
            $({value: settings.original_value}).animate({value: settings.next_value}, {
                duration: 2000,
                easing: 'swing',
                step: function()
                {
                    if (settings.data_type == 'money') {
                        element.text('$' + Math.ceil(this.value));
                    }
                    else if (settings.data_type == 'percentage') {
                        element.text(Math.ceil(this.value) + '%');
                    }
                    else if (settings.data_type == 'none') {
                        element.text(Math.ceil(this.value));
                    }
                },
                complete: function() {
                    if (settings.data_type == 'money') {
                        element.text('$' + settings.next_value);
                    }
                    else if (settings.data_type == 'percentage') {
                        element.text(settings.next_value + '%');
                    }
                    else if (settings.data_type == 'none') {
                        element.text(settings.next_value);
                    }
                }
            });
        }

    });

  };
})( jQuery );<|endoftext|>


<commit_before>/**
 * jQuery Lightbox
 * Version 0.5 - 11/29/2007
 * @author Warren Krewenki
 *
 * This package is distributed under the BSD license.
 * For full license information, see LICENSE.TXT
 *
 * Based on Lightbox 2 by Lokesh Dhakar (http://www.huddletogether.com/projects/lightbox2/)
 * Originally written to make use of the Prototype framework, and Script.acalo.us, now altered to use jQuery.
 *
 *
 **/

(function($){
	var opts;

	$.fn.lightbox = function(options){
		// build main options
		opts = $.extend({}, $.fn.lightbox.defaults, options);

		// initalize the lightbox
		$.fn.lightbox.initialize();
		return this.each(function(){
			$(this).click(function(){
				$(this).lightbox.start(this);
				return false;
			});
		});
	};

	/**
	 * initalize()
	 *
	 * @return void
	 * @author Warren Krewenki
	 */
	$.fn.lightbox.initialize = function(){
		$('#overlay').remove();
		$('#lightbox').remove();
		opts.inprogress = false;
		var outerImage = '

';
		var imageData = '

';

		if (opts.displayHelp)
			imageData += '' + opts.strings.help + '';

		imageData += '

';

		var string;

		if (opts.navbarOnTop) {
		  string = '

' + imageData + outerImage + '
';
		  $("body").append(string);
		  $("#imageDataContainer").addClass('ontop');
		} else {
		  string = '

' + outerImage + imageData + '
';
		  $("body").append(string);
		}

		$("#overlay").click(function(){ $.fn.lightbox.end(); }).hide();
		$("#lightbox").click(function(){ $.fn.lightbox.end();}).hide();
		$("#loadingLink").click(function(){ $.fn.lightbox.end(); return false;});
		$("#bottomNavClose").click(function(){ $.fn.lightbox.end(); return false; });
		$('#outerImageContainer').width(opts.widthCurrent).height(opts.heightCurrent);
		$('#imageDataContainer').width(opts.widthCurrent);
	};

	$.fn.lightbox.getPageSize = function(){
		var jqueryPageSize = new Array($(document).width(),$(document).height(), $(window).width(), $(window).height());
		return jqueryPageSize;
	};

	$.fn.lightbox.getPageScroll = function(){
		var xScroll, yScroll;

		if (self.pageYOffset) {
			yScroll = self.pageYOffset;
			xScroll = self.pageXOffset;
		} else if (document.documentElement && document.documentElement.scrollTop){  // Explorer 6 Strict
			yScroll = document.documentElement.scrollTop;
			xScroll = document.documentElement.scrollLeft;
		} else if (document.body) {// all other Explorers
			yScroll = document.body.scrollTop;
			xScroll = document.body.scrollLeft;
		}

		var arrayPageScroll = new Array(xScroll,yScroll);
		return arrayPageScroll;
	};

	$.fn.lightbox.pause = function(ms){
		var date = new Date();
		var curDate = null;
		do{curDate = new Date();}
		while( curDate - date < ms);
	};

	$.fn.lightbox.start = function(imageLink){

		$("select, embed, object").hide();
		var arrayPageSize = $.fn.lightbox.getPageSize();
		$("#overlay").hide().css({width: '100%', height: arrayPageSize[1]+'px', opacity : opts.overlayOpacity}).fadeIn();
		opts.imageArray = [];
		imageNum = 0;

		// if image is NOT part of a set..
		if(!imageLink.rel || (imageLink.rel == '')){
			// add single image to Lightbox.imageArray
			opts.imageArray.push(new Array(imageLink.href, opts.displayTitle ? imageLink.title : ''));
		} else {
		// if image is part of a set..
			$("a").each(function(){
				if(this.href && (this.rel == imageLink.rel)){
					opts.imageArray.push(new Array(this.href, opts.displayTitle ? this.title : ''));
				}
			});

			for(i = 0; i < opts.imageArray.length; i++){
				for(j = opts.imageArray.length-1; j>i; j--){
					if(opts.imageArray[i][0] == opts.imageArray[j][0]){
						opts.imageArray.splice(j,1);
					}
				}
			}
			while(opts.imageArray[imageNum][0] != imageLink.href) { imageNum++;}
		}

		// calculate top and left offset for the lightbox
		var arrayPageScroll = $.fn.lightbox.getPageScroll();
		var lightboxTop = arrayPageScroll[1] + (arrayPageSize[3] / 10);
		var lightboxLeft = arrayPageScroll[0];
		$('#lightbox').css({top: lightboxTop+'px', left: lightboxLeft+'px'}).show();

		if (!opts.slideNavBar)
			$('#imageData').hide();

		$.fn.lightbox.changeImage(imageNum);

	};

	$.fn.lightbox.changeImage = function(imageNum){
		if(opts.inprogress == false){
			opts.inprogress = true;
			opts.activeImage = imageNum;	// update global var

			// hide elements during transition
			$('#loading').show();
			$('#lightboxImage').hide();
			$('#hoverNav').hide();
			$('#prevLink').hide();
			$('#nextLink').hide();

			if (opts.slideNavBar) { // delay preloading image until navbar will slide up
				// $('#imageDataContainer').slideUp(opts.navBarSlideSpeed, $.fn.doChangeImage);
				$('#imageDataContainer').hide();
				$('#imageData').hide();
				$.fn.doChangeImage();
			} else {
			    $.fn.doChangeImage();
			}
		}
	};

	$.fn.doChangeImage = function(){

		imgPreloader = new Image();

		// once image is preloaded, resize image container
		imgPreloader.onload=function(){
		    var newWidth = imgPreloader.width;
		    var newHeight = imgPreloader.height;

			if (opts.fitToScreen) {
		        var arrayPageSize = $.fn.lightbox.getPageSize();
				var ratio;
				var initialPageWidth = arrayPageSize[2] - 2 * opts.borderSize;
				var initialPageHeight = arrayPageSize[3] - 200;

				if (imgPreloader.height > initialPageHeight)
				{
					newWidth = parseInt((initialPageHeight/imgPreloader.height) * imgPreloader.width);
					newHeight = initialPageHeight;
				}
				else if (imgPreloader.width > initialPageWidth)
				{
					newHeight = parseInt((initialPageWidth/imgPreloader.width) * imgPreloader.height);
					newWidth = initialPageWidth;
				}
			}

			$('#lightboxImage').attr('src', opts.imageArray[opts.activeImage][0])
							   .width(newWidth).height(newHeight);
			$.fn.lightbox.resizeImageContainer(newWidth, newHeight);
		};

		imgPreloader.src = opts.imageArray[opts.activeImage][0];
	};

	$.fn.lightbox.end = function(){
		$.fn.lightbox.disableKeyboardNav();
		$('#lightbox').hide();
		$('#overlay').fadeOut();
		$('select, object, embed').show();
	};

	$.fn.lightbox.preloadNeighborImages = function(){
		if((opts.imageArray.length - 1) > opts.activeImage){
			preloadNextImage = new Image();
			preloadNextImage.src = opts.imageArray[opts.activeImage + 1][0];
		}
		if(opts.activeImage > 0){
			preloadPrevImage = new Image();
			preloadPrevImage.src = opts.imageArray[opts.activeImage - 1][0];
		}
	};

	$.fn.lightbox.keyboardAction = function(e){
		if (e == null) { // ie
			var keycode = event.keyCode;
			var escapeKey = 27;
		} else { // mozilla
			var keycode = e.keyCode;
			var escapeKey = e.DOM_VK_ESCAPE;
		}

		var key = String.fromCharCode(keycode).toLowerCase();

		if((key == 'x') || (key == 'o') || (key == 'c') || (keycode == escapeKey)){ // close lightbox
			$.fn.lightbox.end();
		} else if((key == 'p') || (keycode == 37)){ // display previous image
			if(opts.activeImage != 0){
				$.fn.lightbox.disableKeyboardNav();
				$.fn.lightbox.changeImage(opts.activeImage - 1);
			}
		} else if((key == 'n') || (keycode == 39)){ // display next image
			if(opts.activeImage != (opts.imageArray.length - 1)){
				$.fn.lightbox.disableKeyboardNav();
				$.fn.lightbox.changeImage(opts.activeImage + 1);
			}
		}
	};

	$.fn.lightbox.resizeImageContainer = function(imgWidth, imgHeight){
		// get current width and height
		opts.widthCurrent = document.getElementById('outerImageContainer').offsetWidth;
		opts.heightCurrent = document.getElementById('outerImageContainer').offsetHeight;

		// get new width and height
		var widthNew = (imgWidth  + (opts.borderSize * 2));
		var heightNew = (imgHeight  + (opts.borderSize * 2));

		// scalars based on change from old to new
		opts.xScale = ( widthNew / opts.widthCurrent) * 100;
		opts.yScale = ( heightNew / opts.heightCurrent) * 100;

		// calculate size difference between new and old image, and resize if necessary
		wDiff = opts.widthCurrent - widthNew;
		hDiff = opts.heightCurrent - heightNew;

		$('#imageDataContainer').animate({width: widthNew},opts.resizeSpeed,'linear');
		$('#outerImageContainer').animate({width: widthNew},opts.resizeSpeed,'linear',function(){
			$('#outerImageContainer').animate({height: heightNew},opts.resizeSpeed,'linear',function(){
				$.fn.lightbox.showImage();
			});
		});

		// if new and old image are same size and no scaling transition is necessary,
		// do a quick pause to prevent image flicker.
		if((hDiff == 0) && (wDiff == 0)){
			if (jQuery.browser.msie){ $.fn.lightbox.pause(250); } else { $.fn.lightbox.pause(100);}
		}

		$('#prevLink').height(imgHeight);
		$('#nextLink').height(imgHeight);
	};

	$.fn.lightbox.showImage = function(){
		$('#loading').hide();
		$('#lightboxImage').fadeIn("fast");
		$.fn.lightbox.updateDetails();
		$.fn.lightbox.preloadNeighborImages();

		opts.inprogress = false;
	};

	$.fn.lightbox.updateDetails = function(){

		$('#numberDisplay').html('');

		if(opts.imageArray[opts.activeImage][1]){
			$('#caption').html(opts.imageArray[opts.activeImage][1]).show();
		}

		// if image is part of set display 'Image x of x'
		if(opts.imageArray.length > 1){
			var nav_html;

			nav_html = opts.strings.image + (opts.activeImage + 1) + opts.strings.of + opts.imageArray.length;

			if (!opts.disableNavbarLinks) {
        // display previous / next text links
        if ((opts.activeImage) > 0) {
          nav_html = '' + opts.strings.prevLinkText + "" + nav_html;
        }

        if ((opts.activeImage + 1) < opts.imageArray.length) {
          nav_html += '' + opts.strings.nextLinkText + "";
        }
      }

			$('#numberDisplay').html(nav_html).show();
		}

		if (opts.slideNavBar) {
		    $("#imageData").slideDown(opts.navBarSlideSpeed);
		} else {
			$("#imageData").show();
		}

		var arrayPageSize = $.fn.lightbox.getPageSize();
		$('#overlay').height(arrayPageSize[1]);
		$.fn.lightbox.updateNav();
	};

	$.fn.lightbox.updateNav = function(){
		if(opts.imageArray.length > 1){
			$('#hoverNav').show();

			// if not first image in set, display prev image button
			if(opts.activeImage != 0){
				$('#prevLink,#prevLinkText').show().click(function(){
					$.fn.lightbox.changeImage(opts.activeImage - 1); return false;
				});
			}

			// if not last image in set, display next image button
			if(opts.activeImage != (opts.imageArray.length - 1)){
				$('#nextLink,#nextLinkText').show().click(function(){

					$.fn.lightbox.changeImage(opts.activeImage +1); return false;
				});
			}

			$.fn.lightbox.enableKeyboardNav();
		}
	};

	$.fn.lightbox.enableKeyboardNav = function(){
		document.onkeydown = $.fn.lightbox.keyboardAction;
	};

	$.fn.lightbox.disableKeyboardNav = function(){
		document.onkeydown = '';
	};

	$.fn.lightbox.defaults = {
		fileLoadingImage : 'images/loading.gif',
		fileBottomNavCloseImage : 'images/closelabel.gif',
		overlayOpacity : 0.8,
		borderSize : 10,
		imageArray : new Array,
		activeImage : null,
		inprogress : false,
		resizeSpeed : 350,
		widthCurrent: 250,
		heightCurrent: 250,
		xScale : 1,
		yScale : 1,
		displayTitle: true,
		navbarOnTop: false,
		slideNavBar: false, // slide nav bar up/down between image resizing transitions
		navBarSlideSpeed: 350,
		displayHelp: false,
		strings : {
			help: ' \u2190 / P - previous image\u00a0\u00a0\u00a0\u00a0\u2192 / N - next image\u00a0\u00a0\u00a0\u00a0ESC / X - close image gallery',
			prevLinkTitle: 'previous image',
			nextLinkTitle: 'next image',
			prevLinkText:  '« Previous',
			nextLinkText:  'Next »',
			closeTitle: 'close image gallery',
			image: 'Image ',
			of: ' of '
		},
		fitToScreen: false,		// resize images if they are bigger than window
    disableNavbarLinks: false
	};
})(jQuery);
<commit_msg>Added option for continuous looping of images. (loopImages, defaults to false )<commit_after>/**
 * jQuery Lightbox
 * Version 0.5 - 11/29/2007
 * @author Warren Krewenki
 *
 * This package is distributed under the BSD license.
 * For full license information, see LICENSE.TXT
 *
 * Based on Lightbox 2 by Lokesh Dhakar (http://www.huddletogether.com/projects/lightbox2/)
 * Originally written to make use of the Prototype framework, and Script.acalo.us, now altered to use jQuery.
 *
 *
 **/

(function($){
	var opts;

	$.fn.lightbox = function(options){
		// build main options
		opts = $.extend({}, $.fn.lightbox.defaults, options);

		// initalize the lightbox
		$.fn.lightbox.initialize();
		return this.each(function(){
			$(this).click(function(){
				$(this).lightbox.start(this);
				return false;
			});
		});
	};

	/**
	 * initalize()
	 *
	 * @return void
	 * @author Warren Krewenki
	 */
	$.fn.lightbox.initialize = function(){
		$('#overlay').remove();
		$('#lightbox').remove();
		opts.inprogress = false;
		var outerImage = '

';
		var imageData = '

';

		if (opts.displayHelp)
			imageData += '' + opts.strings.help + '';

		imageData += '

';

		var string;

		if (opts.navbarOnTop) {
		  string = '

' + imageData + outerImage + '
';
		  $("body").append(string);
		  $("#imageDataContainer").addClass('ontop');
		} else {
		  string = '

' + outerImage + imageData + '
';
		  $("body").append(string);
		}

		$("#overlay").click(function(){ $.fn.lightbox.end(); }).hide();
		$("#lightbox").click(function(){ $.fn.lightbox.end();}).hide();
		$("#loadingLink").click(function(){ $.fn.lightbox.end(); return false;});
		$("#bottomNavClose").click(function(){ $.fn.lightbox.end(); return false; });
		$('#outerImageContainer').width(opts.widthCurrent).height(opts.heightCurrent);
		$('#imageDataContainer').width(opts.widthCurrent);

		if (!opts.imageClickClose) {
    		$("#hoverNav").click(function(){ return false; });
		}
	};

	$.fn.lightbox.getPageSize = function(){
		var jqueryPageSize = new Array($(document).width(),$(document).height(), $(window).width(), $(window).height());
		return jqueryPageSize;
	};

	$.fn.lightbox.getPageScroll = function(){
		var xScroll, yScroll;

		if (self.pageYOffset) {
			yScroll = self.pageYOffset;
			xScroll = self.pageXOffset;
		} else if (document.documentElement && document.documentElement.scrollTop){  // Explorer 6 Strict
			yScroll = document.documentElement.scrollTop;
			xScroll = document.documentElement.scrollLeft;
		} else if (document.body) {// all other Explorers
			yScroll = document.body.scrollTop;
			xScroll = document.body.scrollLeft;
		}

		var arrayPageScroll = new Array(xScroll,yScroll);
		return arrayPageScroll;
	};

	$.fn.lightbox.pause = function(ms){
		var date = new Date();
		var curDate = null;
		do{curDate = new Date();}
		while( curDate - date < ms);
	};

	$.fn.lightbox.start = function(imageLink){

		$("select, embed, object").hide();
		var arrayPageSize = $.fn.lightbox.getPageSize();
		$("#overlay").hide().css({width: '100%', height: arrayPageSize[1]+'px', opacity : opts.overlayOpacity}).fadeIn();
		opts.imageArray = [];
		imageNum = 0;

		// if image is NOT part of a set..
		if(!imageLink.rel || (imageLink.rel == '')){
			// add single image to Lightbox.imageArray
			opts.imageArray.push(new Array(imageLink.href, opts.displayTitle ? imageLink.title : ''));
		} else {
		// if image is part of a set..
			$("a").each(function(){
				if(this.href && (this.rel == imageLink.rel)){
					opts.imageArray.push(new Array(this.href, opts.displayTitle ? this.title : ''));
				}
			});

			for(i = 0; i < opts.imageArray.length; i++){
				for(j = opts.imageArray.length-1; j>i; j--){
					if(opts.imageArray[i][0] == opts.imageArray[j][0]){
						opts.imageArray.splice(j,1);
					}
				}
			}
			while(opts.imageArray[imageNum][0] != imageLink.href) { imageNum++;}
		}

		// calculate top and left offset for the lightbox
		var arrayPageScroll = $.fn.lightbox.getPageScroll();
		var lightboxTop = arrayPageScroll[1] + (arrayPageSize[3] / 10);
		var lightboxLeft = arrayPageScroll[0];
		$('#lightbox').css({top: lightboxTop+'px', left: lightboxLeft+'px'}).show();

		if (!opts.slideNavBar)
			$('#imageData').hide();

		$.fn.lightbox.changeImage(imageNum);

	};

	$.fn.lightbox.changeImage = function(imageNum){
		if(opts.inprogress == false){
			opts.inprogress = true;
			opts.activeImage = imageNum;	// update global var

			// hide elements during transition
			$('#loading').show();
			$('#lightboxImage').hide();
			$('#hoverNav').hide();
			$('#prevLink').hide();
			$('#nextLink').hide();

			if (opts.slideNavBar) { // delay preloading image until navbar will slide up
				// $('#imageDataContainer').slideUp(opts.navBarSlideSpeed, $.fn.doChangeImage);
				$('#imageDataContainer').hide();
				$('#imageData').hide();
				$.fn.doChangeImage();
			} else {
			    $.fn.doChangeImage();
			}
		}
	};

	$.fn.doChangeImage = function(){

		imgPreloader = new Image();

		// once image is preloaded, resize image container
		imgPreloader.onload=function(){
		    var newWidth = imgPreloader.width;
		    var newHeight = imgPreloader.height;

			if (opts.fitToScreen) {
		        var arrayPageSize = $.fn.lightbox.getPageSize();
				var ratio;
				var initialPageWidth = arrayPageSize[2] - 2 * opts.borderSize;
				var initialPageHeight = arrayPageSize[3] - 200;

				if (imgPreloader.height > initialPageHeight)
				{
					newWidth = parseInt((initialPageHeight/imgPreloader.height) * imgPreloader.width);
					newHeight = initialPageHeight;
				}
				else if (imgPreloader.width > initialPageWidth)
				{
					newHeight = parseInt((initialPageWidth/imgPreloader.width) * imgPreloader.height);
					newWidth = initialPageWidth;
				}
			}

			$('#lightboxImage').attr('src', opts.imageArray[opts.activeImage][0])
							   .width(newWidth).height(newHeight);
			$.fn.lightbox.resizeImageContainer(newWidth, newHeight);
		};

		imgPreloader.src = opts.imageArray[opts.activeImage][0];
	};

	$.fn.lightbox.end = function(){
		$.fn.lightbox.disableKeyboardNav();
		$('#lightbox').hide();
		$('#overlay').fadeOut();
		$('select, object, embed').show();
	};

	$.fn.lightbox.preloadNeighborImages = function(){
		if(opts.loopImages && opts.imageArray.length > 1) {
	        preloadNextImage = new Image();
	        preloadNextImage.src = opts.imageArray[(opts.activeImage == (opts.imageArray.length - 1)) ? 0 : opts.activeImage + 1][0]

	        preloadPrevImage = new Image();
	        preloadPrevImage.src = opts.imageArray[(opts.activeImage == 0) ? (opts.imageArray.length - 1) : opts.activeImage - 1][0]
	    } else {
		    if((opts.imageArray.length - 1) > opts.activeImage){
			    preloadNextImage = new Image();
			    preloadNextImage.src = opts.imageArray[opts.activeImage + 1][0];
		    }
		    if(opts.activeImage > 0){
			    preloadPrevImage = new Image();
			    preloadPrevImage.src = opts.imageArray[opts.activeImage - 1][0];
		    }
	    }
	};

	$.fn.lightbox.keyboardAction = function(e){
		if (e == null) { // ie
			var keycode = event.keyCode;
			var escapeKey = 27;
		} else { // mozilla
			var keycode = e.keyCode;
			var escapeKey = e.DOM_VK_ESCAPE;
		}

		var key = String.fromCharCode(keycode).toLowerCase();

		if((key == 'x') || (key == 'o') || (key == 'c') || (keycode == escapeKey)){ // close lightbox
			$.fn.lightbox.end();
		} else if((key == 'p') || (keycode == 37)){ // display previous image
			if(opts.activeImage != 0){
				$.fn.lightbox.disableKeyboardNav();
				$.fn.lightbox.changeImage(opts.activeImage - 1);
			}
		} else if((key == 'n') || (keycode == 39)){ // display next image
			if(opts.activeImage != (opts.imageArray.length - 1)){
				$.fn.lightbox.disableKeyboardNav();
				$.fn.lightbox.changeImage(opts.activeImage + 1);
			}
		}
	};

	$.fn.lightbox.resizeImageContainer = function(imgWidth, imgHeight){
		// get current width and height
		opts.widthCurrent = document.getElementById('outerImageContainer').offsetWidth;
		opts.heightCurrent = document.getElementById('outerImageContainer').offsetHeight;

		// get new width and height
		var widthNew = (imgWidth  + (opts.borderSize * 2));
		var heightNew = (imgHeight  + (opts.borderSize * 2));

		// scalars based on change from old to new
		opts.xScale = ( widthNew / opts.widthCurrent) * 100;
		opts.yScale = ( heightNew / opts.heightCurrent) * 100;

		// calculate size difference between new and old image, and resize if necessary
		wDiff = opts.widthCurrent - widthNew;
		hDiff = opts.heightCurrent - heightNew;

		$('#imageDataContainer').animate({width: widthNew},opts.resizeSpeed,'linear');
		$('#outerImageContainer').animate({width: widthNew},opts.resizeSpeed,'linear',function(){
			$('#outerImageContainer').animate({height: heightNew},opts.resizeSpeed,'linear',function(){
				$.fn.lightbox.showImage();
			});
		});

		// if new and old image are same size and no scaling transition is necessary,
		// do a quick pause to prevent image flicker.
		if((hDiff == 0) && (wDiff == 0)){
			if (jQuery.browser.msie){ $.fn.lightbox.pause(250); } else { $.fn.lightbox.pause(100);}
		}

		$('#prevLink').height(imgHeight);
		$('#nextLink').height(imgHeight);
	};

	$.fn.lightbox.showImage = function(){
		$('#loading').hide();
		$('#lightboxImage').fadeIn("fast");
		$.fn.lightbox.updateDetails();
		$.fn.lightbox.preloadNeighborImages();

		opts.inprogress = false;
	};

	$.fn.lightbox.updateDetails = function(){

		$('#numberDisplay').html('');

		if(opts.imageArray[opts.activeImage][1]){
			$('#caption').html(opts.imageArray[opts.activeImage][1]).show();
		}

		// if image is part of set display 'Image x of x'
		if(opts.imageArray.length > 1){
			var nav_html;

			nav_html = opts.strings.image + (opts.activeImage + 1) + opts.strings.of + opts.imageArray.length;

			if (!opts.disableNavbarLinks) {
                // display previous / next text links
                if ((opts.activeImage) > 0 || opts.loopImages) {
                  nav_html = '' + opts.strings.prevLinkText + "" + nav_html;
                }

                if (((opts.activeImage + 1) < opts.imageArray.length) || opts.loopImages) {
                  nav_html += '' + opts.strings.nextLinkText + "";
                }
            }

			$('#numberDisplay').html(nav_html).show();
		}

		if (opts.slideNavBar) {
		    $("#imageData").slideDown(opts.navBarSlideSpeed);
		} else {
			$("#imageData").show();
		}

		var arrayPageSize = $.fn.lightbox.getPageSize();
		$('#overlay').height(arrayPageSize[1]);
		$.fn.lightbox.updateNav();
	};

	$.fn.lightbox.updateNav = function(){
		if(opts.imageArray.length > 1){
			$('#hoverNav').show();

            // if loopImages is true, always show next and prev image buttons
            if(opts.loopImages) {
		        $('#prevLink,#prevLinkText').show().click(function(){
			        $.fn.lightbox.changeImage((opts.activeImage == 0) ? (opts.imageArray.length - 1) : opts.activeImage - 1); return false;
		        });

		        $('#nextLink,#nextLinkText').show().click(function(){
			        $.fn.lightbox.changeImage((opts.activeImage == (opts.imageArray.length - 1)) ? 0 : opts.activeImage + 1); return false;
		        });

		    } else {
			    // if not first image in set, display prev image button
			    if(opts.activeImage != 0){
				    $('#prevLink,#prevLinkText').show().click(function(){
					    $.fn.lightbox.changeImage(opts.activeImage - 1); return false;
				    });
			    }

			    // if not last image in set, display next image button
			    if(opts.activeImage != (opts.imageArray.length - 1)){
				    $('#nextLink,#nextLinkText').show().click(function(){

					    $.fn.lightbox.changeImage(opts.activeImage +1); return false;
				    });
			    }
            }

			$.fn.lightbox.enableKeyboardNav();
		}
	};

	$.fn.lightbox.enableKeyboardNav = function(){
		document.onkeydown = $.fn.lightbox.keyboardAction;
	};

	$.fn.lightbox.disableKeyboardNav = function(){
		document.onkeydown = '';
	};

	$.fn.lightbox.defaults = {
		fileLoadingImage : 'images/loading.gif',
		fileBottomNavCloseImage : 'images/closelabel.gif',
		overlayOpacity : 0.8,
		borderSize : 10,
		imageArray : new Array,
		activeImage : null,
		inprogress : false,
		resizeSpeed : 350,
		widthCurrent: 250,
		heightCurrent: 250,
		xScale : 1,
		yScale : 1,
		displayTitle: true,
		navbarOnTop: false,
		slideNavBar: false, // slide nav bar up/down between image resizing transitions
		navBarSlideSpeed: 350,
		displayHelp: false,
		strings : {
			help: ' \u2190 / P - previous image\u00a0\u00a0\u00a0\u00a0\u2192 / N - next image\u00a0\u00a0\u00a0\u00a0ESC / X - close image gallery',
			prevLinkTitle: 'previous image',
			nextLinkTitle: 'next image',
			prevLinkText:  '« Previous',
			nextLinkText:  'Next »',
			closeTitle: 'close image gallery',
			image: 'Image ',
			of: ' of '
		},
		fitToScreen: false,		// resize images if they are bigger than window
        disableNavbarLinks: false,
        loopImages: false,
        imageClickClose: true
	};
})(jQuery);
<|endoftext|>


<commit_before>import React from 'react';
import classnames from 'classnames';

import { KeyCodes } from 'constants/ActorAppConstants';

class Dropdown extends React.Component {
  static propTypes = {
    isShown: React.PropTypes.bool,
    className: React.PropTypes.string,
    children: React.PropTypes.array,
    onSelect: React.PropTypes.func.isRequired
  };

  constructor(props) {
    super(props);

    this.state = {
      isShown: props.isShown,
      selectedIndex: this.getDefaultIndex(props.children)
    };
  }

  componentWillMount() {
    document.addEventListener('keydown', this.onKeyDown, false);
  }

  componentWillUnmount() {
    document.removeEventListener('click', this.closeDropdown);
    document.removeEventListener('keydown', this.onKeyDown, false);
  }

  componentWillReceiveProps(props) {
    this.setState({
      isShown: props.isShown,
      selectedIndex: this.getDefaultIndex(props.children)
    });
  }

  getDefaultIndex = (children) => {
    let index = null;

    if (children && children.length > 0) {
      index = children.length - 1;
    }

    return index;
  };

  getValue = (index) => {
    if (this.props.children.length > 0) {
      return this.props.children[index].props.value;
    } else {
      return null;
    }
  };

  closeDropdown = () => {
    this.setState({isShown: false});
    document.removeEventListener('click', this.closeDropdown, false);
  };

  onSelect = (value) => {
    if (this.props.onSelect) {
      this.props.onSelect(value);
    }
  };

  onKeyDown = (e) => {
    let index = this.state.selectedIndex;

    if (index !== null) {

      switch (e.keyCode) {
        case KeyCodes.ENTER:
          e.stopPropagation();
          e.preventDefault();

          this.onSelect(this.getValue(this.state.selectedIndex));
          break;
        case KeyCodes.ARROW_UP:
          e.stopPropagation();
          e.preventDefault();

          if (index !== 0) {
            index -= 1;
          }

          this.setState({selectedIndex: index});
          break;
        case KeyCodes.ARROW_DOWN:
          e.stopPropagation();
          e.preventDefault();

          if (index !== this.props.children.length) {
            index += 1;
          }

          this.setState({selectedIndex: index});
          break;
        default:
      }
    }
  };

  render() {
    const { className, children } = this.props;

    let dropdownItems = [];

    React.Children.forEach(children, (child, index) => {
      if (child.type.name === 'DropdownItem') {
        let elClassName = 'dropdown__menu__item';

        if (this.state.selectedIndex === index) {
          elClassName += ' dropdown__menu__item--active';
        }

        dropdownItems.push(

            {child.props.children}

        );
      }
    });

    const dropdownClassName = classnames({
      'dropdown': true,
      'dropdown--opened': this.state.isShown
    }, className);

    return (

          {dropdownItems}

    );
  }
}

class DropdownItem extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return this.props.children;
  }
}

export default { Dropdown, DropdownItem };
<commit_msg>fix(web): fixed mentions behavior on arrow down and esc<commit_after>import React from 'react';
import classnames from 'classnames';

import { KeyCodes } from 'constants/ActorAppConstants';

class Dropdown extends React.Component {
  static propTypes = {
    isShown: React.PropTypes.bool,
    className: React.PropTypes.string,
    children: React.PropTypes.array,
    onSelect: React.PropTypes.func.isRequired
  };

  constructor(props) {
    super(props);

    this.state = {
      isShown: props.isShown,
      selectedIndex: this.getDefaultIndex(props.children)
    };
  }

  componentWillMount() {
    document.addEventListener('keydown', this.onKeyDown, false);
  }

  componentWillUnmount() {
    document.removeEventListener('click', this.closeDropdown);
    document.removeEventListener('keydown', this.onKeyDown, false);
  }

  componentWillReceiveProps(props) {
    this.setState({
      isShown: props.isShown,
      selectedIndex: this.getDefaultIndex(props.children)
    });
  }

  getDefaultIndex = (children) => {
    let index = null;

    if (children && children.length > 0) {
      index = children.length - 1;
    }

    return index;
  };

  getValue = (index) => {
    if (this.props.children.length > 0) {
      return this.props.children[index].props.value;
    } else {
      return null;
    }
  };

  closeDropdown = () => {
    this.setState({isShown: false});
    document.removeEventListener('click', this.closeDropdown, false);
  };

  onSelect = (value) => {
    if (this.props.onSelect) {
      this.props.onSelect(value);
    }
  };

  onKeyDown = (e) => {
    let index = this.state.selectedIndex;

    if (index !== null) {
      switch (e.keyCode) {
        case KeyCodes.ENTER:
          e.stopPropagation();
          e.preventDefault();

          this.onSelect(this.getValue(this.state.selectedIndex));
          break;
        case KeyCodes.ARROW_UP:
          e.stopPropagation();
          e.preventDefault();

          if (index !== 0) {
            index -= 1;
          }

          this.setState({selectedIndex: index});
          break;
        case KeyCodes.ARROW_DOWN:
          e.stopPropagation();
          e.preventDefault();

          if (index !== this.props.children.length - 1) {
            index += 1;
          }

          this.setState({selectedIndex: index});
          break;
        default:
      }
    }

    if (e.keyCode === KeyCodes.ESC) {
      this.closeDropdown();
    }
  };

  render() {
    const { className, children } = this.props;

    let dropdownItems = [];

    React.Children.forEach(children, (child, index) => {
      if (child.type.name === 'DropdownItem') {
        let elClassName = 'dropdown__menu__item';

        if (this.state.selectedIndex === index) {
          elClassName += ' dropdown__menu__item--active';
        }

        dropdownItems.push(

            {child.props.children}

        );
      }
    });

    const dropdownClassName = classnames({
      'dropdown': true,
      'dropdown--opened': this.state.isShown
    }, className);

    return (

          {dropdownItems}

    );
  }
}

class DropdownItem extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return this.props.children;
  }
}

export default { Dropdown, DropdownItem };
<|endoftext|>


<commit_before>/*
 * L.TileLayer is used for standard xyz-numbered tile layers.
 */
//(function (ymaps, L) {

L.Yandex = L.Class.extend({
	includes: L.Mixin.Events,

	options: {
		minZoom: 0,
		maxZoom: 18,
		attribution: '',
		opacity: 1,
		traffic: false
	},

	// Possible types: map, satellite, hybrid, publicMap, publicMapHybrid
	initialize: function(type, options) {
		L.Util.setOptions(this, options);

		this._type = "yandex#" + (type || 'map');
	},

	onAdd: function(map, insertAtTheBottom) {
		this._map = map;
		this._insertAtTheBottom = insertAtTheBottom;

		// create a container div for tiles
		this._initContainer();
		this._initMapObject();

		// set up events
		map.on('viewreset', this._resetCallback, this);

		this._limitedUpdate = L.Util.limitExecByInterval(this._update, 150, this);
		map.on('move', this._update, this);

		map._controlCorners['bottomright'].style.marginBottom = "3em";

		this._reset();
		this._update(true);
	},

	onRemove: function(map) {
		this._map._container.removeChild(this._container);

		this._map.off('viewreset', this._resetCallback, this);

		this._map.off('move', this._update, this);

		map._controlCorners['bottomright'].style.marginBottom = "0em";
	},

	getAttribution: function() {
		return this.options.attribution;
	},

	setOpacity: function(opacity) {
		this.options.opacity = opacity;
		if (opacity < 1) {
			L.DomUtil.setOpacity(this._container, opacity);
		}
	},

	setElementSize: function(e, size) {
		e.style.width = size.x + "px";
		e.style.height = size.y + "px";
	},

	_initContainer: function() {
		var tilePane = this._map._container,
			first = tilePane.firstChild;

		if (!this._container) {
			this._container = L.DomUtil.create('div', 'leaflet-yandex-layer leaflet-top leaflet-left');
			this._container.id = "_YMapContainer_" + L.Util.stamp(this);
			this._container.style.zIndex = "auto";
		}

		if (this.options.overlay) {
			first = this._map._container.getElementsByClassName('leaflet-map-pane')[0];
			first = first.nextSibling;
			// XXX: Bug with layer order
			if (L.Browser.opera)
				this._container.className += " leaflet-objects-pane";
		}
		tilePane.insertBefore(this._container, first);

		this.setOpacity(this.options.opacity);
		this.setElementSize(this._container, this._map.getSize());
	},

	_initMapObject: function() {
		if (this._yandex) return;

		// Check that ymaps.Map is ready
		if (ymaps.Map === undefined) {
			if (console) {
				console.debug("L.Yandex: Waiting on ymaps.load('package.map')");
			}
			return ymaps.load(["package.map"], this._initMapObject, this);
		}

		// If traffic layer is requested check if control.TrafficControl is ready
		if (this.options.traffic)
			if (ymaps.control === undefined ||
					ymaps.control.TrafficControl === undefined) {
				if (console) {
					console.debug("L.Yandex: loading traffic and controls");
				}
				return ymaps.load(["package.traffic", "package.controls"],
					this._initMapObject, this);
			}

		var map = new ymaps.Map(this._container, {center: [0,0], zoom: 0, behaviors: []});

		if (this.options.traffic)
			map.controls.add(new ymaps.control.TrafficControl({shown: true}));

		if (this._type == "yandex#null") {
			this._type = new ymaps.MapType("null", []);
			map.container.getElement().style.background = "transparent";
		}
		map.setType(this._type);

		this._yandex = map;
		this._update(true);
	},

	_resetCallback: function(e) {
		this._reset(e.hard);
	},

	_reset: function(clearOldContainer) {
		this._initContainer();
	},

	_update: function(force) {
		if (!this._yandex) return;
		this._resize(force);

		var center = this._map.getCenter();
		var _center = [center.lat, center.lng];
		var zoom = this._map.getZoom();

		if (force || this._yandex.getZoom() != zoom)
			this._yandex.setZoom(zoom);
		this._yandex.panTo(_center, {duration: 0, delay: 0});
	},

	_resize: function(force) {
		var size = this._map.getSize(), style = this._container.style;
		if (style.width == size.x + "px" &&
				style.height == size.y + "px")
			if (force != true) return;
		this.setElementSize(this._container, size);
		var b = this._map.getBounds(), sw = b.getSouthWest(), ne = b.getNorthEast();
		this._yandex.container.fitToViewport();
	}
});
//})(ymaps, L)
<commit_msg>Fix yandex tilelayer<commit_after>/*
	 * L.TileLayer is used for standard xyz-numbered tile layers.
	 */

	/* global ymaps: true */

	L.Yandex = L.Layer.extend({
		includes: L.Mixin.Events,

		options: {
			minZoom: 0,
			maxZoom: 18,
			attribution: '',
			opacity: 1,
			traffic: false
		},

		possibleShortMapTypes: {
			schemaMap: 'map',
			satelliteMap: 'satellite',
			hybridMap: 'hybrid',
			publicMap: 'publicMap',
			publicMapInHybridView: 'publicMapHybrid'
		},

		_getPossibleMapType: function (mapType) {
			var result = 'yandex#map';
			if (typeof mapType !== 'string') {
				return result;
			}
			for (var key in this.possibleShortMapTypes) {
				if (mapType === this.possibleShortMapTypes[key]) {
					result = 'yandex#' + mapType;
					break;
				}
				if (mapType === ('yandex#' + this.possibleShortMapTypes[key])) {
					result = mapType;
				}
			}
			return result;
		},

		// Possible types: yandex#map, yandex#satellite, yandex#hybrid, yandex#publicMap, yandex#publicMapHybrid
		// Or their short names: map, satellite, hybrid, publicMap, publicMapHybrid
		initialize: function (type, options) {
			L.Util.setOptions(this, options);
			//Assigning an initial map type for the Yandex layer
			this._type = this._getPossibleMapType(type);
		},

		onAdd: function (map, insertAtTheBottom) {
			this._map = map;
			this._insertAtTheBottom = insertAtTheBottom;

			// create a container div for tiles
			this._initContainer();
			this._initMapObject();

			// set up events
			map.on('viewreset', this._reset, this);

			this._limitedUpdate = L.Util.throttle(this._update, 150, this);
			map.on('move', this._update, this);

			map._controlCorners.bottomright.style.marginBottom = '3em';

			this._reset();
			this._update(true);
		},

		onRemove: function (map) {
			this._map._container.removeChild(this._container);

			this._map.off('viewreset', this._reset, this);

			this._map.off('move', this._update, this);

			map._controlCorners.bottomright.style.marginBottom = '0em';
		},

		getAttribution: function () {
			return this.options.attribution;
		},

		setOpacity: function (opacity) {
			this.options.opacity = opacity;
			if (opacity < 1) {
				L.DomUtil.setOpacity(this._container, opacity);
			}
		},

		setElementSize: function (e, size) {
			e.style.width = size.x + 'px';
			e.style.height = size.y + 'px';
		},

		_initContainer: function () {
			var tilePane = this._map._container,
				first = tilePane.firstChild;

			if (!this._container) {
				this._container = L.DomUtil.create('div', 'leaflet-yandex-layer');
				this._container.id = '_YMapContainer_' + L.Util.stamp(this);
				this._container.style.zIndex = 'auto';
			}

			if (this.options.overlay) {
				first = this._map._container.getElementsByClassName('leaflet-map-pane')[0];
				first = first.nextSibling;
				// XXX: Bug with layer order
				if (L.Browser.opera)
					this._container.className += ' leaflet-objects-pane';
			}
			tilePane.insertBefore(this._container, first);

			this.setOpacity(this.options.opacity);
			this.setElementSize(this._container, this._map.getSize());
		},

		_initMapObject: function () {
			if (this._yandex) return;

			// Check that ymaps.Map is ready
			if (ymaps.Map === undefined) {
				return ymaps.load(['package.map'], this._initMapObject, this);
			}

			// If traffic layer is requested check if control.TrafficControl is ready
			if (this.options.traffic)
				if (ymaps.control === undefined ||
						ymaps.control.TrafficControl === undefined) {
					return ymaps.load(['package.traffic', 'package.controls'],
						this._initMapObject, this);
				}
			//Creating ymaps map-object without any default controls on it
			var map = new ymaps.Map(this._container, {center: [0, 0], zoom: 0, behaviors: [], controls: []});

			if (this.options.traffic)
				map.controls.add(new ymaps.control.TrafficControl({shown: true}));

			if (this._type === 'yandex#null') {
				this._type = new ymaps.MapType('null', []);
				map.container.getElement().style.background = 'transparent';
			}
			map.setType(this._type);

			this._yandex = map;
			this._update(true);

			//Reporting that map-object was initialized
			this.fire('MapObjectInitialized', {mapObject: map});
		},

		_reset: function () {
			this._initContainer();
		},

		_update: function (force) {
			if (!this._yandex) return;
			this._resize(force);

			var center = this._map.getCenter();
			var _center = [center.lat, center.lng];
			var zoom = this._map.getZoom();

			if (force || this._yandex.getZoom() !== zoom)
				this._yandex.setZoom(zoom);
			this._yandex.panTo(_center, {duration: 0, delay: 0});
		},

		_resize: function (force) {
			var size = this._map.getSize(), style = this._container.style;
			if (style.width === size.x + 'px' && style.height === size.y + 'px')
				if (force !== true) return;
			this.setElementSize(this._container, size);
			this._yandex.container.fitToViewport();
		}
	});<|endoftext|>


<commit_before>module.exports = function(grunt) {
  grunt.initConfig({
    devperf: {
      options: {
        urls: [
          'http://gruntjs.com'
        ],
        resultsFolder: './reports/'
      }
    }
  });

  grunt.loadNpmTasks('grunt-devperf');
  grunt.registerTask('default', ['devperf']);
};<commit_msg>ugh, LINE BREAKS<commit_after>module.exports = function(grunt) {
  grunt.initConfig({
    devperf: {
      options: {
        urls: [
          'http://gruntjs.com'
        ],
        resultsFolder: './reports/'
      }
    }
  });

  grunt.loadNpmTasks('grunt-devperf');
  grunt.registerTask('default', ['devperf']);
};
<|endoftext|>


<commit_before>angular.module('loginModule')
.controller('loginCtrl', function ($scope, $state, $ionicSideMenuDelegate, $ionicSlideBoxDelegate, $timeout, signinFac) {

  $ionicSideMenuDelegate.canDragContent(false);

  $scope.startApp = function() {
    $state.go('home');
  };
  $scope.next = function() {
    $ionicSlideBoxDelegate.next();
  };
  $scope.previous = function() {
    $ionicSlideBoxDelegate.previous();
  };

  // Called each time the slide changes
  $scope.slideChanged = function(index) {
    $scope.slideIndex = index;
  };

  $scope.showIntroduction = false;

  signinFac.checkSignin()
  .then(function (status) {
    console.log(status);
    signinFac.signinModalClose();
    $scope.startApp();
    //    $scope.showIntroduction = true;
  }, function (status) {
    console.log(status);
    signinFac.signinModalOpen();
  });

  $scope.$on('showIntroductionHandle', function (event, show) {
    $scope.showIntroduction = show;
    if (!show) {
      $scope.startApp();
    }
  });

  //  $timeout(function() {
  //  signinFac.checkSignin();
  //  }, 10);

  //  queryAPI.getDayToday()
  //  .then(function(data) {
  //    if (data.status.code === 100) {
  //      queryAPI.cleanDay(data.result)
  //      .then(function (daysObject) {
  //        $scope.days = daysObject;
  //        queryAPI.setDayColors();
  //      });
  //    } else {
  //      console.log(data.status.code);
  //    }
  //  }, function (status) {
  //    console.log(status);
  //  });
});
<commit_msg>disabled back-button after login<commit_after>angular.module('loginModule')
.controller('loginCtrl', function ($scope, $state, $ionicHistory, $ionicSideMenuDelegate, $ionicSlideBoxDelegate, $timeout, signinFac) {

  $ionicSideMenuDelegate.canDragContent(false);

  $scope.startApp = function() {
    $state.go('home');

    $ionicHistory.nextViewOptions({
      disableAnimate: true,
      disableBack: true
    });
  };
  $scope.next = function() {
    $ionicSlideBoxDelegate.next();
  };
  $scope.previous = function() {
    $ionicSlideBoxDelegate.previous();
  };

  // Called each time the slide changes
  $scope.slideChanged = function(index) {
    $scope.slideIndex = index;
  };

  $scope.showIntroduction = false;

  signinFac.checkSignin()
  .then(function (status) {
    console.log(status);
    signinFac.signinModalClose();
    $scope.startApp();
    //    $scope.showIntroduction = true;
  }, function (status) {
    console.log(status);
    signinFac.signinModalOpen();
  });

  $scope.$on('showIntroductionHandle', function (event, show) {
    $scope.showIntroduction = show;
    if (!show) {
      $scope.startApp();
    }
  });

  //  $timeout(function() {
  //  signinFac.checkSignin();
  //  }, 10);

  //  queryAPI.getDayToday()
  //  .then(function(data) {
  //    if (data.status.code === 100) {
  //      queryAPI.cleanDay(data.result)
  //      .then(function (daysObject) {
  //        $scope.days = daysObject;
  //        queryAPI.setDayColors();
  //      });
  //    } else {
  //      console.log(data.status.code);
  //    }
  //  }, function (status) {
  //    console.log(status);
  //  });
});
<|endoftext|>


<commit_before>/*!
 * jQuery Panelize - v0.7b - 2013-10-29
 * Image navigation with image maps
 *
 * (c) 2013 R.E. Warner <rewarner@russellbits.com>
 * MIT Licensed.
 *
 * http://russellbits.github.io/panelize
 * http://github.com/russellbits/panelize

 * TDODs
 * + Work out index bug
 * + Previous button
 * + Create transitions without transit.js dependency
 * + Create alternate area for link w/out pan/zoom
 * + Needs a pre-loading function for large images
*/

jQuery.fn.panelize = function( options ) {

	var defaults = {
		container: this, // this should be used as opposed to explicit jquery references
		fullPageStart: true,
		panelViewerID : '#panelViewer',
		showNextBtnID : '#nextPanelBtn',
		showPrevBtnID : '#prevPanelBtn',
		resetBtnID: '#resetBtn'
	};

	var settings = $.extend( {}, defaults, options );

	var panels = {
		panelIndex: 0,
		panel: [],
		viewerWidth: this.width(),
		viewerHeight: this.height()
	};

	function Panel(x1, y1, x2, y2) {
		this.x1 = x1;
		this.y1 = y1;
		this.x2 = x2;
		this.y2 = y2;
		this.width = this.x2 - this.x1;
		this.height = this.y2 - this.y1;
	}

	console.log('Viewer: '+panels.viewerWidth+', '+panels.viewerHeight);

	// Intialize the panels in the comic
	// Assign area tag coordinates to the panels object
	$(this).find('area').each(function(i) {
		var coords = $(this).attr('coords');
		var coordsStrArray = coords.split(',');
		panels.panel.push(new Panel(
			coordsStrArray[0],
			coordsStrArray[1],
			coordsStrArray[2],
			coordsStrArray[3]
		));
	});

	/**
	* Start with full page option
	* 	The full scaled page will show, unless the user opts not to,
	* 	in which case, the first panel will zoom and show
	**/
	if(settings.fullPageStart) {
		var xOffset = 0;
		var yOffset = 0;
		comic = $(settings.panelViewerID).find('img');
		if(comic.width() > comic.height()) {
			scaleFactor = panels.viewerWidth/comic.width();
			yOffset = Math.floor(((panels.viewerHeight-(comic.height()*scaleFactor))/2));
			console.log('yOffset: '+yOffset);
			console.log('Comic is '+comic.width()+' wide');
		} else {
			scaleFactor = panels.viewerHeight/comic.height();
			xOffset = Math.floor(((panels.viewerWidth-(comic.width()*scaleFactor))/2));
			console.log('xOffset: '+xOffset);
			console.log('Comic is '+comic.height()+'  tall');
		}
		$('#comicOverlay')
			.css({transformOrigin:'0px 0px'})
			.transition({x:xOffset,y:yOffset})
			.transition({scale:scaleFactor});
	} else {
		transformPanel();
	}

	/**
	* MAIN TRANSFORM FUNCTION
	**/
	function transformPanel() {
		// Reset to first panel when index hits maximum
		if(panels.panelIndex == panels.panel.length) {
			panels.panelIndex = 0;
		}
		// Undo full page transform
		if(settings.fullPageStart && panels.panelIndex == 0) {
			console.log('Returning to initial scale and position');
			//$('#comicOverlay').css({transformOrigin:'0px 0px'}).transition({x:0,y:0}).transition({scale:1});
		}
		// Assign local variables
		var panelTop = panels.panel[panels.panelIndex].y1;
		var panelLeft = panels.panel[panels.panelIndex].x1;
		var panelWidth = panels.panel[panels.panelIndex].width;
		var panelHeight = panels.panel[panels.panelIndex].height;
		var panelBottom = panels.panel[panels.panelIndex].y2;
		var panelRight = panels.panel[panels.panelIndex].x2;
		var offsetIsX;
		var yOffset = 0;
		var xOffset = 0;
		var portraitMode = true;

		// Check if we are dealing with a portrait or landscape viewer
		if(panels.viewerWidth > panels.viewerHeight) {
			portraitMode = true;
		} else {
			portraitMode = false;
		}

		if(panelWidth > panelHeight || portraitMode==false) {
			var usingWidthAsMax = true;
			scaleFactor = panels.viewerWidth/panelWidth;
			offsetIsX = true;
		} else {
			var usingWidthAsMax = false;
			scaleFactor = panels.viewerHeight/panelHeight;
			offsetIsX = false;
		}

		var scaledPanelHeight = Math.floor(panelHeight*scaleFactor);
		var scaledPanelWdith = Math.floor(panelWidth*scaleFactor);

		// need to divide the offest by the scalefactor?
		if(offsetIsX) {
			yOffset = Math.floor((panels.viewerHeight-scaledPanelHeight)/2);
		} else {
			xOffset = Math.floor((panels.viewerWidth-scaledPanelWdith)/2);
		}

		console.log("Panel location: top:"+panelTop+
			', left:'+panelLeft+
			', bottom: '+panelBottom+
			', right:'+panelRight+
			', width: '+panelWidth+
			', height: '+panelHeight+
			', scalefactor: '+scaleFactor);
		console.log('Using a width offset of '+xOffset+' given width of '+scaledPanelHeight+'.');
		console.log('Using a height offset of '+yOffset+' given height of '+scaledPanelWdith+'.');
		console.log(panels.panel[panels.panelIndex]);
		console.log(panels.panel.length);

		// Perform the actual transformation
		$(settings.panelViewerID).find('img')
			.css({transformOrigin:'0px 0px'})
			.transition({scale:scaleFactor})
			.transition({x:-panelLeft+xOffset,y:-panelTop+yOffset});

		// Update location in panels object
		panels.panelIndex += 1;
	}

	/**
	* Interactive functions (UI)
	**/
	return this.each(function() {

		/*return $(settings.resetBtnID).click(function() {
			console.log('reset function activated');
			panels.panelIndex = 0;
			$('#comic').transition({x:0,y:0}).transition({scale:1});
		});*/

		return $(settings.showNextBtnID).click(function(event) {
			console.log('Next button activated');
			event.preventDefault();
			transformPanel();
		});

	});

};<commit_msg>Major Changes<commit_after>/*!
 * jQuery Panelize - v0.7b - 2013-10-29
 * Image navigation with image maps
 *
 * (c) 2013 R.E. Warner <rewarner@russellbits.com>
 * MIT Licensed.
 *
 * http://russellbits.github.io/panelize
 * http://github.com/russellbits/panelize

 * TDODs
 * + DONE? Work out index bug
 * + Previous button - any button - current structure returns only next function
 * + DONE! YAY! Create transitions without transit.js dependency
 * + DONE YAY! Create alternate area for link w/out pan/zoom
 * + Needs a pre-loading function for large images
*/

jQuery.fn.panelize = function( options ) {

	var defaults = {
		container: this, // this should be used as opposed to explicit jquery references
		fullPageStart: true,
		panelViewerID : '#panelViewer',
		showNextBtnID : '#nextPanelBtn',
		showPrevBtnID : '#prevPanelBtn',
		resetBtnID: '#resetBtn'
	};

	var settings = $.extend( {}, defaults, options );

	var panels = {
		panelIndex: 0,
		panel: [],
		viewerWidth: this.width(),
		viewerHeight: this.height()
	};

	function Panel(x1, y1, x2, y2) {
		this.x1 = x1;
		this.y1 = y1;
		this.x2 = x2;
		this.y2 = y2;
		this.width = this.x2 - this.x1;
		this.height = this.y2 - this.y1;
	}

	console.log('Viewer: '+panels.viewerWidth+', '+panels.viewerHeight);

	// Intialize the panels in the comic
	// Assign area tag coordinates to the panels object
	$(this).find('area').each(function(i) {
		if($(this).attr("target")!=null||$(this).attr("target")=="") {}
		else {
			console.log($(this).attr("target"));
			var coords = $(this).attr('coords');
			var coordsStrArray = coords.split(',');
			panels.panel.push(new Panel(
				coordsStrArray[0],
				coordsStrArray[1],
				coordsStrArray[2],
				coordsStrArray[3]
			));
		}
	});

	/**
	* Start with full page option
	* 	The full scaled page will show, unless the user opts not to,
	* 	in which case, the first panel will zoom and show
	**/
	if(settings.fullPageStart) {
		var xOffset = 0;
		var yOffset = 0;
		comic = $(settings.panelViewerID).find('img');
		if(comic.width() > comic.height()) {
			scaleFactor = panels.viewerWidth/comic.width();
			yOffset = Math.floor(((panels.viewerHeight-(comic.height()*scaleFactor))/2));
			console.log('yOffset: '+yOffset);
			console.log('Comic is '+comic.width()+' wide');
		} else {
			scaleFactor = panels.viewerHeight/comic.height();
			xOffset = Math.floor(((panels.viewerWidth-(comic.width()*scaleFactor))/2));
			console.log('xOffset: '+xOffset);
			console.log('Comic is '+comic.height()+'  tall');
		}
		$(settings.panelViewerID).find('img')
			.css({transformOrigin:'0px 0px'})
			.transition({x:xOffset,y:yOffset})
			.transition({scale:scaleFactor});
	} else {
		transformPanel();
	}

	/**
	* MAIN TRANSFORM FUNCTION
	**/
	function transformPanel() {
		// Reset to first panel when index hits maximum
		if(panels.panelIndex == panels.panel.length) {
			panels.panelIndex = 0;
		}
		// Undo full page transform
		if(settings.fullPageStart && panels.panelIndex == 0) {
			console.log('Returning to initial scale and position');
			//$('#comicOverlay').css({transformOrigin:'0px 0px'}).transition({x:0,y:0}).transition({scale:1});
		}
		// Assign local variables
		var panelTop = panels.panel[panels.panelIndex].y1;
		var panelLeft = panels.panel[panels.panelIndex].x1;
		var panelWidth = panels.panel[panels.panelIndex].width;
		var panelHeight = panels.panel[panels.panelIndex].height;
		var panelBottom = panels.panel[panels.panelIndex].y2;
		var panelRight = panels.panel[panels.panelIndex].x2;
		var offsetIsX;
		var yOffset = 0;
		var xOffset = 0;
		var portraitMode = true;

		// Check if we are dealing with a portrait or landscape viewer
		if(panels.viewerWidth > panels.viewerHeight) {
			portraitMode = true;
		} else {
			portraitMode = false;
		}

		if(panelWidth > panelHeight || portraitMode==false) {
			var usingWidthAsMax = true;
			scaleFactor = panels.viewerWidth/panelWidth;
			offsetIsX = true;
		} else {
			var usingWidthAsMax = false;
			scaleFactor = panels.viewerHeight/panelHeight;
			offsetIsX = false;
		}

		var scaledPanelHeight = Math.floor(panelHeight*scaleFactor);
		var scaledPanelWdith = Math.floor(panelWidth*scaleFactor);

		// need to divide the offest by the scalefactor?
		if(offsetIsX) {
			yOffset = Math.floor((panels.viewerHeight-scaledPanelHeight)/2);
		} else {
			xOffset = Math.floor((panels.viewerWidth-scaledPanelWdith)/2);
		}

		console.log("Panel location: top:"+panelTop+
			', left:'+panelLeft+
			', bottom: '+panelBottom+
			', right:'+panelRight+
			', width: '+panelWidth+
			', height: '+panelHeight+
			', scalefactor: '+scaleFactor);
		console.log('Using a width offset of '+xOffset+' given width of '+scaledPanelHeight+'.');
		console.log('Using a height offset of '+yOffset+' given height of '+scaledPanelWdith+'.');
		console.log(panels.panel[panels.panelIndex]);
		console.log('Current index: '+panels.panelIndex);
		console.log('Panel length: '+panels.panel.length);

		// Perform the actual transformation
		var Xmove = -panelLeft+xOffset;
		var Ymove = -panelTop+yOffset;
		var comic = $(settings.panelViewerID).find('img');

		comic.css({transformOrigin:'0px 0px'})
			.animate({left:Xmove*scaleFactor,top:Ymove*scaleFactor,scale:scaleFactor});

		// Update location in panels object
		panels.panelIndex += 1;
	}

	/**
	* Interactive functions (UI)
	**/
	return this.each(function() {

		/*return $(settings.resetBtnID).click(function() {
			console.log('reset function activated');
			panels.panelIndex = 0;
			$('#comic').transition({x:0,y:0}).transition({scale:1});
		});*/

		return $(settings.showNextBtnID).click(function(event) {
			console.log('Next button activated');
			event.preventDefault();
			transformPanel();
		});

		return $(settings.showPrevBtnID).click(function(event) {
			console.log('Previous button activated');
			event.preventDefault();
			transformPanel();
		});

	});

};<|endoftext|>