<commit_before>(function ($, window, document, undefined) {
  'use strict';

  Foundation.libs.forms = {
    name: 'forms',

    version: '4.1.6',

    cache: {},

    settings: {
      disable_class: 'no-custom',
      last_combo : null
    },

    init: function (scope, method, options) {

      if (typeof method === 'object') {
        $.extend(true, this.settings, method);
      }

      if (typeof method != 'string') {
        if (!this.settings.init) {
          this.events();
        }

        this.assemble();

        return this.settings.init;
      } else {
        return this[method].call(this, options);
      }
    },

    assemble: function () {
      $('form.custom input[type="radio"]', $(this.scope)).not('[data-customforms="disabled"]')
        .each(this.append_custom_markup);
      $('form.custom input[type="checkbox"]', $(this.scope)).not('[data-customforms="disabled"]')
        .each(this.append_custom_markup);
      $('form.custom select', $(this.scope))
        .not('[data-customforms="disabled"]')
        .not('[multiple=multiple]')
        .each(this.append_custom_select);
    },

    events: function () {
      var self = this;

      $(this.scope)
        .on('click.fndtn.forms', 'form.custom span.custom.checkbox', function (e) {
          e.preventDefault();
          e.stopPropagation();
          self.toggle_checkbox($(this));
        })
        .on('click.fndtn.forms', 'form.custom span.custom.radio', function (e) {
          e.preventDefault();
          e.stopPropagation();
          self.toggle_radio($(this));
        })
        .on('change.fndtn.forms', 'form.custom select:not([data-customforms="disabled"])', function (e, force_refresh) {
          self.refresh_custom_select($(this), force_refresh);
        })
        .on('click.fndtn.forms', 'form.custom label', function (e) {
          if ($(e.target).is('label')) {
            var $associatedElement = $('#' + self.escape($(this).attr('for')) + ':not([data-customforms="disabled"])'),
              $customCheckbox,
              $customRadio;

            if ($associatedElement.length !== 0) {
              if ($associatedElement.attr('type') === 'checkbox') {
                e.preventDefault();
                $customCheckbox = $(this).find('span.custom.checkbox');
                //the checkbox might be outside after the label or inside of another element
                if ($customCheckbox.length == 0) {
                  $customCheckbox = $associatedElement.add(this).siblings('span.custom.checkbox').first();
                }
                self.toggle_checkbox($customCheckbox);
              } else if ($associatedElement.attr('type') === 'radio') {
                e.preventDefault();
                $customRadio = $(this).find('span.custom.radio');
                //the radio might be outside after the label or inside of another element
                if ($customRadio.length == 0) {
                  $customRadio = $associatedElement.add(this).siblings('span.custom.radio').first();
                }
                self.toggle_radio($customRadio);
              }
            }
          }
        })
        .on('mousedown.fndtn.forms', 'form.custom div.custom.dropdown', function () {
          return false;
        })
        .on('click.fndtn.forms', 'form.custom div.custom.dropdown a.current, form.custom div.custom.dropdown a.selector', function (e) {
          var $this = $(this),
              $dropdown = $this.closest('div.custom.dropdown'),
              $select = getFirstPrevSibling($dropdown, 'select');

          // make sure other dropdowns close
          if (!$dropdown.hasClass('open')) $(self.scope).trigger('click');

          e.preventDefault();
          if (false === $select.is(':disabled')) {
            $dropdown.toggleClass('open');

            if ($dropdown.hasClass('open')) {
              $(self.scope).on('click.fndtn.forms.customdropdown', function () {
                $dropdown.removeClass('open');
                $(self.scope).off('.fndtn.forms.customdropdown');
              });
            } else {
              $(self.scope).on('.fndtn.forms.customdropdown');
            }
            return false;
          }
        })
        .on('click.fndtn.forms touchend.fndtn.forms', 'form.custom div.custom.dropdown li', function (e) {
          var $this = $(this),
              $customDropdown = $this.closest('div.custom.dropdown'),
              $select = getFirstPrevSibling($customDropdown, 'select'),
              selectedIndex = 0;

          e.preventDefault();
          e.stopPropagation();

          if (!$(this).hasClass('disabled')) {
            $('div.dropdown').not($customDropdown).removeClass('open');

            var $oldThis = $this.closest('ul')
              .find('li.selected');
            $oldThis.removeClass('selected');

            $this.addClass('selected');

            $customDropdown.removeClass('open')
              .find('a.current')
              .text($this.text());

            $this.closest('ul').find('li').each(function (index) {
              if ($this[0] == this) {
                selectedIndex = index;
              }
            });
            $select[0].selectedIndex = selectedIndex;

            //store the old value in data
            $select.data('prevalue', $oldThis.html());
            $select.trigger('change');
          }
      });

      $(window).on('keydown', function (e) {
        var focus = document.activeElement,
            self = Foundation.libs.forms,
            dropdown = $('.custom.dropdown.open');

        if (dropdown.length > 0) {
          e.preventDefault();

          if (e.which === 13) {
            dropdown.find('li.selected').trigger('click');
          }

          if (e.which === 27) {
            dropdown.removeClass('open');
          }

          if (e.which >= 65 && e.which <= 90) {
            var next = self.go_to(dropdown, e.which),
                current = dropdown.find('li.selected');

            if (next) {
              current.removeClass('selected');
              self.scrollTo(next.addClass('selected'), 300);
            }
          }

          if (e.which === 38) {
            var current = dropdown.find('li.selected'),
                prev = current.prev(':not(.disabled)');

            if (prev.length > 0) {
              prev.parent()[0].scrollTop = prev.parent().scrollTop() - self.outerHeight(prev);
              current.removeClass('selected');
              prev.addClass('selected');
            }
          } else if (e.which === 40) {
            var current = dropdown.find('li.selected'),
                next = current.next(':not(.disabled)');

            if (next.length > 0) {
              next.parent()[0].scrollTop = next.parent().scrollTop() + self.outerHeight(next);
              current.removeClass('selected');
              next.addClass('selected');
            }
          }
        }
      });

      this.settings.init = true;
    },

    go_to: function (dropdown, character) {
      var lis = dropdown.find('li'),
          count = lis.length;

      if (count > 0) {
        for (var i = 0; i < count; i++) {
          var first_letter = lis.eq(i).text().charAt(0).toLowerCase();
          if (first_letter === String.fromCharCode(character).toLowerCase()) return lis.eq(i);
        }
      }
    },

    scrollTo: function (el, duration) {
      if (duration < 0) return;
      var parent = el.parent();
      var li_height = this.outerHeight(el);
      var difference = (li_height * (el.index())) - parent.scrollTop();
      var perTick = difference / duration * 10;

      this.scrollToTimerCache = setTimeout(function () {
        if (!isNaN(parseInt(perTick, 10))) {
          parent[0].scrollTop = parent.scrollTop() + perTick;
          this.scrollTo(el, duration - 10);
        }
      }.bind(this), 10);
    },

    append_custom_markup: function (idx, sel) {
      var $this = $(sel),
          type = $this.attr('type'),
          $span = $this.next('span.custom.' + type);

      if (!$this.parent().hasClass('switch')) {
        $this.addClass('hidden-field');
      }

      if ($span.length === 0) {
        $span = $('').insertAfter($this);
      }

      $span.toggleClass('checked', $this.is(':checked'));
      $span.toggleClass('disabled', $this.is(':disabled'));
    },

    append_custom_select: function (idx, sel) {
        var self = Foundation.libs.forms,
            $this = $(sel),
            $customSelect = $this.next('div.custom.dropdown'),
            $customList = $customSelect.find('ul'),
            $selectCurrent = $customSelect.find(".current"),
            $selector = $customSelect.find(".selector"),
            $options = $this.find('option'),
            $selectedOption = $options.filter(':selected'),
            copyClasses = $this.attr('class') ? $this.attr('class').split(' ') : [],
            maxWidth = 0,
            liHtml = '',
            $listItems,
            $currentSelect = false;

        if ($this.hasClass(self.settings.disable_class)) return;

        if ($customSelect.length === 0) {
          var customSelectSize = $this.hasClass('small') ? 'small' : $this.hasClass('medium') ? 'medium' : $this.hasClass('large') ? 'large' : $this.hasClass('expand') ? 'expand' : '';

          $customSelect = $('

');

          $selector = $customSelect.find(".selector");
          $customList = $customSelect.find("ul");

          liHtml = $options.map(function () {
            return "
" + $(this).html() + "
";
          }).get().join('');

          $customList.append(liHtml);

          $currentSelect = $customSelect
            .prepend('' + $selectedOption.html() + '')
            .find(".current");

          $this.after($customSelect)
            .addClass('hidden-field');
        } else {
          liHtml = $options.map(function () {
              return "
" + $(this).html() + "
";
            })
            .get().join('');

          $customList.html('')
            .append(liHtml);

        } // endif $customSelect.length === 0

        self.assign_id($this, $customSelect);
        $customSelect.toggleClass('disabled', $this.is(':disabled'));
        $listItems = $customList.find('li');

        // cache list length
        self.cache[$customSelect.data('id')] = $listItems.length;

        $options.each(function (index) {
          if (this.selected) {
            $listItems.eq(index).addClass('selected');

            if ($currentSelect) {
              $currentSelect.html($(this).html());
            }
          }
          if ($(this).is(':disabled')) {
            $listItems.eq(index).addClass('disabled');
          }
        });

        //
        // If we're not specifying a predetermined form size.
        //
        if (!$customSelect.is('.small, .medium, .large, .expand')) {

          // ------------------------------------------------------------------------------------
          // This is a work-around for when elements are contained within hidden parents.
          // For example, when custom-form elements are inside of a hidden reveal modal.
          //
          // We need to display the current custom list element as well as hidden parent elements
          // in order to properly calculate the list item element's width property.
          // -------------------------------------------------------------------------------------

          $customSelect.addClass('open');
          //
          // Quickly, display all parent elements.
          // This should help us calcualate the width of the list item's within the drop down.
          //
          var self = Foundation.libs.forms;
          self.hidden_fix.adjust($customList);

          maxWidth = (self.outerWidth($listItems) > maxWidth) ? self.outerWidth($listItems) : maxWidth;

          Foundation.libs.forms.hidden_fix.reset();

          $customSelect.removeClass('open');

        } // endif

    },

    assign_id: function ($select, $customSelect) {
      var id = [+new Date(), Foundation.random_str(5)].join('-');
      $select.attr('data-id', id);
      $customSelect.attr('data-id', id);
    },

    refresh_custom_select: function ($select, force_refresh) {
      var self = this;
      var maxWidth = 0,
          $customSelect = $select.next(),
          $options = $select.find('option'),
          $listItems = $customSelect.find('li');

      if ($listItems.length != this.cache[$customSelect.data('id')] || force_refresh) {
        $customSelect.find('ul').html('');

        $options.each(function () {
          var $li = $('
' + $(this).html() + '
');
          $customSelect.find('ul').append($li);
        });

        // re-populate
        $options.each(function (index) {
          if (this.selected) {
            $customSelect.find('li').eq(index).addClass('selected');
            $customSelect.find('.current').html($(this).html());
          }
          if ($(this).is(':disabled')) {
            $customSelect.find('li').eq(index).addClass('disabled');
          }
        });

        // fix width
        $customSelect.removeAttr('style')
          .find('ul').removeAttr('style');
        $customSelect.find('li').each(function () {
          $customSelect.addClass('open');
          if (self.outerWidth($(this)) > maxWidth) {
            maxWidth = self.outerWidth($(this));
          }
          $customSelect.removeClass('open');
        });

        $listItems = $customSelect.find('li');
        // cache list length
        this.cache[$customSelect.data('id')] = $listItems.length;
      }
    },

    toggle_checkbox: function ($element) {
      var $input = $element.prev(),
          input = $input[0];

      if (false === $input.is(':disabled')) {
        input.checked = ((input.checked) ? false : true);
        $element.toggleClass('checked');

        $input.trigger('change');
      }
    },

    toggle_radio: function ($element) {
        var $input = $element.prev(),
            $form = $input.closest('form.custom'),
            input = $input[0];

        if (false === $input.is(':disabled')) {
          $form.find('input[type="radio"][name="' + this.escape($input.attr('name')) + '"]')
            .next().not($element).removeClass('checked');

          if (!$element.hasClass('checked')) {
            $element.toggleClass('checked');
          }

          input.checked = $element.hasClass('checked');

          $input.trigger('change');
        }
    },

    escape: function (text) {
      return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    },

    hidden_fix: {
        /**
         * Sets all hidden parent elements and self to visibile.
         *
         * @method adjust
         * @param {jQuery Object} $child
         */

        // We'll use this to temporarily store style properties.
        tmp: [],

        // We'll use this to set hidden parent elements.
        hidden: null,

        adjust: function ($child) {
          // Internal reference.
          var _self = this;

          // Set all hidden parent elements, including this element.
          _self.hidden = $child.parents().andSelf().filter(":hidden");

          // Loop through all hidden elements.
          _self.hidden.each(function () {

            // Cache the element.
            var $elem = $(this);

            // Store the style attribute.
            // Undefined if element doesn't have a style attribute.
            _self.tmp.push($elem.attr('style'));

            // Set the element's display property to block,
            // but ensure it's visibility is hidden.
            $elem.css({
                'visibility': 'hidden',
                'display': 'block'
            });
          });

        }, // end adjust

        /**
         * Resets the elements previous state.
         *
         * @method reset
         */
        reset: function () {
          // Internal reference.
          var _self = this;
          // Loop through our hidden element collection.
          _self.hidden.each(function (i) {
            // Cache this element.
            var $elem = $(this),
                _tmp = _self.tmp[i]; // Get the stored 'style' value for this element.

            // If the stored value is undefined.
            if (_tmp === undefined)
            // Remove the style attribute.
            $elem.removeAttr('style');
            else
            // Otherwise, reset the element style attribute.
            $elem.attr('style', _tmp);
          });
          // Reset the tmp array.
          _self.tmp = [];
          // Reset the hidden elements variable.
          _self.hidden = null;

        } // end reset
    },

    off: function () {
      $(this.scope).off('.fndtn.forms');
    }
  };

  var getFirstPrevSibling = function($el, selector) {
    var $el = $el.prev();
    while ($el.length) {
      if ($el.is(selector)) return $el;
      $el = $el.prev();
    }
    return $();
  };
}(Foundation.zj, this, this.document));
<commit_msg>Change andSelf call (deprecated in jQuery 1.8+) to addBack.<commit_after>(function ($, window, document, undefined) {
  'use strict';

  Foundation.libs.forms = {
    name: 'forms',

    version: '4.1.6',

    cache: {},

    settings: {
      disable_class: 'no-custom',
      last_combo : null
    },

    init: function (scope, method, options) {

      if (typeof method === 'object') {
        $.extend(true, this.settings, method);
      }

      if (typeof method != 'string') {
        if (!this.settings.init) {
          this.events();
        }

        this.assemble();

        return this.settings.init;
      } else {
        return this[method].call(this, options);
      }
    },

    assemble: function () {
      $('form.custom input[type="radio"]', $(this.scope)).not('[data-customforms="disabled"]')
        .each(this.append_custom_markup);
      $('form.custom input[type="checkbox"]', $(this.scope)).not('[data-customforms="disabled"]')
        .each(this.append_custom_markup);
      $('form.custom select', $(this.scope))
        .not('[data-customforms="disabled"]')
        .not('[multiple=multiple]')
        .each(this.append_custom_select);
    },

    events: function () {
      var self = this;

      $(this.scope)
        .on('click.fndtn.forms', 'form.custom span.custom.checkbox', function (e) {
          e.preventDefault();
          e.stopPropagation();
          self.toggle_checkbox($(this));
        })
        .on('click.fndtn.forms', 'form.custom span.custom.radio', function (e) {
          e.preventDefault();
          e.stopPropagation();
          self.toggle_radio($(this));
        })
        .on('change.fndtn.forms', 'form.custom select:not([data-customforms="disabled"])', function (e, force_refresh) {
          self.refresh_custom_select($(this), force_refresh);
        })
        .on('click.fndtn.forms', 'form.custom label', function (e) {
          if ($(e.target).is('label')) {
            var $associatedElement = $('#' + self.escape($(this).attr('for')) + ':not([data-customforms="disabled"])'),
              $customCheckbox,
              $customRadio;

            if ($associatedElement.length !== 0) {
              if ($associatedElement.attr('type') === 'checkbox') {
                e.preventDefault();
                $customCheckbox = $(this).find('span.custom.checkbox');
                //the checkbox might be outside after the label or inside of another element
                if ($customCheckbox.length == 0) {
                  $customCheckbox = $associatedElement.add(this).siblings('span.custom.checkbox').first();
                }
                self.toggle_checkbox($customCheckbox);
              } else if ($associatedElement.attr('type') === 'radio') {
                e.preventDefault();
                $customRadio = $(this).find('span.custom.radio');
                //the radio might be outside after the label or inside of another element
                if ($customRadio.length == 0) {
                  $customRadio = $associatedElement.add(this).siblings('span.custom.radio').first();
                }
                self.toggle_radio($customRadio);
              }
            }
          }
        })
        .on('mousedown.fndtn.forms', 'form.custom div.custom.dropdown', function () {
          return false;
        })
        .on('click.fndtn.forms', 'form.custom div.custom.dropdown a.current, form.custom div.custom.dropdown a.selector', function (e) {
          var $this = $(this),
              $dropdown = $this.closest('div.custom.dropdown'),
              $select = getFirstPrevSibling($dropdown, 'select');

          // make sure other dropdowns close
          if (!$dropdown.hasClass('open')) $(self.scope).trigger('click');

          e.preventDefault();
          if (false === $select.is(':disabled')) {
            $dropdown.toggleClass('open');

            if ($dropdown.hasClass('open')) {
              $(self.scope).on('click.fndtn.forms.customdropdown', function () {
                $dropdown.removeClass('open');
                $(self.scope).off('.fndtn.forms.customdropdown');
              });
            } else {
              $(self.scope).on('.fndtn.forms.customdropdown');
            }
            return false;
          }
        })
        .on('click.fndtn.forms touchend.fndtn.forms', 'form.custom div.custom.dropdown li', function (e) {
          var $this = $(this),
              $customDropdown = $this.closest('div.custom.dropdown'),
              $select = getFirstPrevSibling($customDropdown, 'select'),
              selectedIndex = 0;

          e.preventDefault();
          e.stopPropagation();

          if (!$(this).hasClass('disabled')) {
            $('div.dropdown').not($customDropdown).removeClass('open');

            var $oldThis = $this.closest('ul')
              .find('li.selected');
            $oldThis.removeClass('selected');

            $this.addClass('selected');

            $customDropdown.removeClass('open')
              .find('a.current')
              .text($this.text());

            $this.closest('ul').find('li').each(function (index) {
              if ($this[0] == this) {
                selectedIndex = index;
              }
            });
            $select[0].selectedIndex = selectedIndex;

            //store the old value in data
            $select.data('prevalue', $oldThis.html());
            $select.trigger('change');
          }
      });

      $(window).on('keydown', function (e) {
        var focus = document.activeElement,
            self = Foundation.libs.forms,
            dropdown = $('.custom.dropdown.open');

        if (dropdown.length > 0) {
          e.preventDefault();

          if (e.which === 13) {
            dropdown.find('li.selected').trigger('click');
          }

          if (e.which === 27) {
            dropdown.removeClass('open');
          }

          if (e.which >= 65 && e.which <= 90) {
            var next = self.go_to(dropdown, e.which),
                current = dropdown.find('li.selected');

            if (next) {
              current.removeClass('selected');
              self.scrollTo(next.addClass('selected'), 300);
            }
          }

          if (e.which === 38) {
            var current = dropdown.find('li.selected'),
                prev = current.prev(':not(.disabled)');

            if (prev.length > 0) {
              prev.parent()[0].scrollTop = prev.parent().scrollTop() - self.outerHeight(prev);
              current.removeClass('selected');
              prev.addClass('selected');
            }
          } else if (e.which === 40) {
            var current = dropdown.find('li.selected'),
                next = current.next(':not(.disabled)');

            if (next.length > 0) {
              next.parent()[0].scrollTop = next.parent().scrollTop() + self.outerHeight(next);
              current.removeClass('selected');
              next.addClass('selected');
            }
          }
        }
      });

      this.settings.init = true;
    },

    go_to: function (dropdown, character) {
      var lis = dropdown.find('li'),
          count = lis.length;

      if (count > 0) {
        for (var i = 0; i < count; i++) {
          var first_letter = lis.eq(i).text().charAt(0).toLowerCase();
          if (first_letter === String.fromCharCode(character).toLowerCase()) return lis.eq(i);
        }
      }
    },

    scrollTo: function (el, duration) {
      if (duration < 0) return;
      var parent = el.parent();
      var li_height = this.outerHeight(el);
      var difference = (li_height * (el.index())) - parent.scrollTop();
      var perTick = difference / duration * 10;

      this.scrollToTimerCache = setTimeout(function () {
        if (!isNaN(parseInt(perTick, 10))) {
          parent[0].scrollTop = parent.scrollTop() + perTick;
          this.scrollTo(el, duration - 10);
        }
      }.bind(this), 10);
    },

    append_custom_markup: function (idx, sel) {
      var $this = $(sel),
          type = $this.attr('type'),
          $span = $this.next('span.custom.' + type);

      if (!$this.parent().hasClass('switch')) {
        $this.addClass('hidden-field');
      }

      if ($span.length === 0) {
        $span = $('').insertAfter($this);
      }

      $span.toggleClass('checked', $this.is(':checked'));
      $span.toggleClass('disabled', $this.is(':disabled'));
    },

    append_custom_select: function (idx, sel) {
        var self = Foundation.libs.forms,
            $this = $(sel),
            $customSelect = $this.next('div.custom.dropdown'),
            $customList = $customSelect.find('ul'),
            $selectCurrent = $customSelect.find(".current"),
            $selector = $customSelect.find(".selector"),
            $options = $this.find('option'),
            $selectedOption = $options.filter(':selected'),
            copyClasses = $this.attr('class') ? $this.attr('class').split(' ') : [],
            maxWidth = 0,
            liHtml = '',
            $listItems,
            $currentSelect = false;

        if ($this.hasClass(self.settings.disable_class)) return;

        if ($customSelect.length === 0) {
          var customSelectSize = $this.hasClass('small') ? 'small' : $this.hasClass('medium') ? 'medium' : $this.hasClass('large') ? 'large' : $this.hasClass('expand') ? 'expand' : '';

          $customSelect = $('

');

          $selector = $customSelect.find(".selector");
          $customList = $customSelect.find("ul");

          liHtml = $options.map(function () {
            return "
" + $(this).html() + "
";
          }).get().join('');

          $customList.append(liHtml);

          $currentSelect = $customSelect
            .prepend('' + $selectedOption.html() + '')
            .find(".current");

          $this.after($customSelect)
            .addClass('hidden-field');
        } else {
          liHtml = $options.map(function () {
              return "
" + $(this).html() + "
";
            })
            .get().join('');

          $customList.html('')
            .append(liHtml);

        } // endif $customSelect.length === 0

        self.assign_id($this, $customSelect);
        $customSelect.toggleClass('disabled', $this.is(':disabled'));
        $listItems = $customList.find('li');

        // cache list length
        self.cache[$customSelect.data('id')] = $listItems.length;

        $options.each(function (index) {
          if (this.selected) {
            $listItems.eq(index).addClass('selected');

            if ($currentSelect) {
              $currentSelect.html($(this).html());
            }
          }
          if ($(this).is(':disabled')) {
            $listItems.eq(index).addClass('disabled');
          }
        });

        //
        // If we're not specifying a predetermined form size.
        //
        if (!$customSelect.is('.small, .medium, .large, .expand')) {

          // ------------------------------------------------------------------------------------
          // This is a work-around for when elements are contained within hidden parents.
          // For example, when custom-form elements are inside of a hidden reveal modal.
          //
          // We need to display the current custom list element as well as hidden parent elements
          // in order to properly calculate the list item element's width property.
          // -------------------------------------------------------------------------------------

          $customSelect.addClass('open');
          //
          // Quickly, display all parent elements.
          // This should help us calcualate the width of the list item's within the drop down.
          //
          var self = Foundation.libs.forms;
          self.hidden_fix.adjust($customList);

          maxWidth = (self.outerWidth($listItems) > maxWidth) ? self.outerWidth($listItems) : maxWidth;

          Foundation.libs.forms.hidden_fix.reset();

          $customSelect.removeClass('open');

        } // endif

    },

    assign_id: function ($select, $customSelect) {
      var id = [+new Date(), Foundation.random_str(5)].join('-');
      $select.attr('data-id', id);
      $customSelect.attr('data-id', id);
    },

    refresh_custom_select: function ($select, force_refresh) {
      var self = this;
      var maxWidth = 0,
          $customSelect = $select.next(),
          $options = $select.find('option'),
          $listItems = $customSelect.find('li');

      if ($listItems.length != this.cache[$customSelect.data('id')] || force_refresh) {
        $customSelect.find('ul').html('');

        $options.each(function () {
          var $li = $('
' + $(this).html() + '
');
          $customSelect.find('ul').append($li);
        });

        // re-populate
        $options.each(function (index) {
          if (this.selected) {
            $customSelect.find('li').eq(index).addClass('selected');
            $customSelect.find('.current').html($(this).html());
          }
          if ($(this).is(':disabled')) {
            $customSelect.find('li').eq(index).addClass('disabled');
          }
        });

        // fix width
        $customSelect.removeAttr('style')
          .find('ul').removeAttr('style');
        $customSelect.find('li').each(function () {
          $customSelect.addClass('open');
          if (self.outerWidth($(this)) > maxWidth) {
            maxWidth = self.outerWidth($(this));
          }
          $customSelect.removeClass('open');
        });

        $listItems = $customSelect.find('li');
        // cache list length
        this.cache[$customSelect.data('id')] = $listItems.length;
      }
    },

    toggle_checkbox: function ($element) {
      var $input = $element.prev(),
          input = $input[0];

      if (false === $input.is(':disabled')) {
        input.checked = ((input.checked) ? false : true);
        $element.toggleClass('checked');

        $input.trigger('change');
      }
    },

    toggle_radio: function ($element) {
        var $input = $element.prev(),
            $form = $input.closest('form.custom'),
            input = $input[0];

        if (false === $input.is(':disabled')) {
          $form.find('input[type="radio"][name="' + this.escape($input.attr('name')) + '"]')
            .next().not($element).removeClass('checked');

          if (!$element.hasClass('checked')) {
            $element.toggleClass('checked');
          }

          input.checked = $element.hasClass('checked');

          $input.trigger('change');
        }
    },

    escape: function (text) {
      return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    },

    hidden_fix: {
        /**
         * Sets all hidden parent elements and self to visibile.
         *
         * @method adjust
         * @param {jQuery Object} $child
         */

        // We'll use this to temporarily store style properties.
        tmp: [],

        // We'll use this to set hidden parent elements.
        hidden: null,

        adjust: function ($child) {
          // Internal reference.
          var _self = this;

          // Set all hidden parent elements, including this element.
          _self.hidden = $child.parents().addBack().filter(":hidden");

          // Loop through all hidden elements.
          _self.hidden.each(function () {

            // Cache the element.
            var $elem = $(this);

            // Store the style attribute.
            // Undefined if element doesn't have a style attribute.
            _self.tmp.push($elem.attr('style'));

            // Set the element's display property to block,
            // but ensure it's visibility is hidden.
            $elem.css({
                'visibility': 'hidden',
                'display': 'block'
            });
          });

        }, // end adjust

        /**
         * Resets the elements previous state.
         *
         * @method reset
         */
        reset: function () {
          // Internal reference.
          var _self = this;
          // Loop through our hidden element collection.
          _self.hidden.each(function (i) {
            // Cache this element.
            var $elem = $(this),
                _tmp = _self.tmp[i]; // Get the stored 'style' value for this element.

            // If the stored value is undefined.
            if (_tmp === undefined)
            // Remove the style attribute.
            $elem.removeAttr('style');
            else
            // Otherwise, reset the element style attribute.
            $elem.attr('style', _tmp);
          });
          // Reset the tmp array.
          _self.tmp = [];
          // Reset the hidden elements variable.
          _self.hidden = null;

        } // end reset
    },

    off: function () {
      $(this.scope).off('.fndtn.forms');
    }
  };

  var getFirstPrevSibling = function($el, selector) {
    var $el = $el.prev();
    while ($el.length) {
      if ($el.is(selector)) return $el;
      $el = $el.prev();
    }
    return $();
  };
}(Foundation.zj, this, this.document));
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief tests for routing
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Esteban Lombeyda
/// @author Copyright 2014, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var internal = require("internal");
var jsunity = require("jsunity");
var arangodb = require("org/arangodb");

// -----------------------------------------------------------------------------
// --SECTION--                                                        test suite
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief single tests when server is running in ReadOnly mode
////////////////////////////////////////////////////////////////////////////////
function dropDatabaseTestSuite () {
  var db;
  return {

    ////////////////////////////////////////////////////////////////////////////////
    /// @brief set up
    ////////////////////////////////////////////////////////////////////////////////

    setUp : function () {
      db = require("internal").db;
      db._changeMode("Normal");
      db._createDatabase("testDB");
      db._changeMode("ReadOnly");
    },
          tearDown : function () {
            try {
              db._changeMode("Normal");
              db._dropDatabase("testDB");
            } catch (e) {
            }
          },

          ////////////////////////////////////////////////////////////////////////////////
          /// @brief test: creation of a data base in read only modes should faill
          ////////////////////////////////////////////////////////////////////////////////

          testCreateDatabase: function () {
            var not_modified = false;
            try {
              db._createDatabase("xxxDB");
            }catch (e) {
              not_modified = true;
              assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
            }
            assertTrue(not_modified);
          },

          ////////////////////////////////////////////////////////////////////////////////
          /// @brief test: droping of a data base in read only mode should be posible
          ////////////////////////////////////////////////////////////////////////////////

          testDropDatabase: function () {
            var modified = false;
            try {
              db._dropDatabase("testDB");
              modified = true;
            }catch (e) {
              not_modified = false;
            }
            assertTrue(modified);
          },
  };
}
////////////////////////////////////////////////////////////////////////////////
/// @brief single tests when server is running in ReadOnly mode
////////////////////////////////////////////////////////////////////////////////
function readOnlyDatabaseSuite () {
  var db;
  var collection;
  return {

    ////////////////////////////////////////////////////////////////////////////////
    /// @brief set up
    ////////////////////////////////////////////////////////////////////////////////

    setUp : function () {
      db = require("internal").db;
      collection = db._createDocumentCollection("testCol");
      collection.save({_key: "testDocKey", a: 2 });
      db._changeMode("ReadOnly");
    },
          tearDown : function () {
            try {
              db._changeMode("Normal");
              collection.drop("testCol");
            } catch (e) {
             print(e);
            }
          },

          ////////////////////////////////////////////////////////////////////////////////
          /// @brief test: simple routing (prefix)
          ////////////////////////////////////////////////////////////////////////////////

          testCreateDocumentCollection: function () {
            var not_modified = false;
            try {
              db._createDocumentCollection("abcDC");
            }catch (e) {
              not_modified = true;
              assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
            }
            assertTrue(not_modified);
          },

          ////////////////////////////////////////////////////////////////////////////////
          /// @brief test: simple routing (parameter)
          ////////////////////////////////////////////////////////////////////////////////

          testDropCollection: function () {
            var not_modified = false;
            try {
              db._createDocumentCollection("xxxDC");
              not_modified = true;
            }catch (e) {
            }
            assertFalse(not_modified);
          },

          ////////////////////////////////////////////////////////////////////////////////
          /// @brief test: simple routing (optional)
          ////////////////////////////////////////////////////////////////////////////////

          testInsertDocument: function () {
            var modified = false;
            try {
            collection.save({a:1, b:2});
              modified = true;
            }catch (e) {
              assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
            }
            assertFalse(modified);
          },

          ////////////////////////////////////////////////////////////////////////////////
          /// @brief test: simple routing (optional)
          ////////////////////////////////////////////////////////////////////////////////

          testUpdateDocument: function () {
            var modified = false;
            try {
            collection.update("testDocKey", {name: "testing", a: 3});
              modified = true;
            }catch (e) {
              assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
            }
            assertFalse(modified);
          },

          ////////////////////////////////////////////////////////////////////////////////
          /// @brief test: simple routing (prefix vs non-prefix)
          ////////////////////////////////////////////////////////////////////////////////

          testRemoveDocument: function () {
            var modified = false;
            try {
            var removed = collection.remove("testDocKey");
            assertFalse(removed);
              modified = true;
            }catch (e) {
              assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
            }
            assertFalse(modified);
          },

          ////////////////////////////////////////////////////////////////////////////////
          /// @brief test: content string
          ////////////////////////////////////////////////////////////////////////////////

          testCreateBitArrayIndex: function () {
            var modified = false;
            try {
            collection.ensureBitarray("a", [1,2,3,4]);
            modified = true;
            }catch (e) {
              assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
            }
            assertFalse(modified);
          },
          testCreateHashIndex: function () {
            var modified = false;
            try {
              collection.ensureIndex({ type: "hash", fields: [ "name" ], unique: true });
              modified = true;
            }catch (e) {
              assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
            }
            assertFalse(modified);
          },
          testCreateGeoIndex: function () {
            var modified = false;
            try {
              collection.ensureIndex({ type: "geo1", fields: [ "x" ], unique: true });
              modified = true;
            }catch (e) {
              assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
            }
            assertFalse(modified);
          },
          testCreateGeo2Index: function () {
            var modified = false;
            try {
              collection.ensureIndex({ type: "geo2", fields: [ "x", "y" ], unique: true });
              modified = true;
            }catch (e) {
              assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
            }
            assertFalse(modified);
          },
          testCreateSkipListIndex: function () {
            var modified = false;
            try {
              collection.ensureIndex({ type: "skiplist", fields: [ "x" ]});
              modified = true;
            }catch (e) {
              assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
            }
            assertFalse(modified);
          },

  };
}

// -----------------------------------------------------------------------------
// --SECTION--                                                              main
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief executes the test suites
////////////////////////////////////////////////////////////////////////////////

jsunity.run(dropDatabaseTestSuite);
jsunity.run(readOnlyDatabaseSuite);

return jsunity.done();

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "\\(/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @\\}\\)"
// End:
<commit_msg>formating<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief tests for readonly mode of arango
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Esteban Lombeyda
/// @author Copyright 2014, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var internal = require("internal");
var jsunity = require("jsunity");
var arangodb = require("org/arangodb");

// -----------------------------------------------------------------------------
// --SECTION--                                                        test suite
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief single tests when server is running in ReadOnly mode
////////////////////////////////////////////////////////////////////////////////
function dropDatabaseTestSuite () {
  var db;
  return {

    ////////////////////////////////////////////////////////////////////////////////
    /// @brief set up
    ////////////////////////////////////////////////////////////////////////////////

    setUp : function () {
      db = require("internal").db;
      db._changeMode("Normal");
      db._createDatabase("testDB");
      db._changeMode("ReadOnly");
    },
    tearDown : function () {
      try {
        db._changeMode("Normal");
        db._dropDatabase("testDB");
        } catch (e) {
        }
    },

    ////////////////////////////////////////////////////////////////////////////////
    /// @brief test: creation of a data base in read only modes should faill
    ////////////////////////////////////////////////////////////////////////////////

    testCreateDatabase: function () {
      var not_modified = false;
      try {
        db._createDatabase("xxxDB");
        } catch (e) {
          not_modified = true;
          assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
        }
      assertTrue(not_modified);
      },

      ////////////////////////////////////////////////////////////////////////////////
      /// @brief test: droping of a data base in read only mode should be posible
      ////////////////////////////////////////////////////////////////////////////////

      testDropDatabase: function () {
        var modified = false;
        try {
          db._dropDatabase("testDB");
          modified = true;
        } catch (e) {
          not_modified = false;
        }
        assertTrue(modified);
     },
  };
}
////////////////////////////////////////////////////////////////////////////////
/// @brief single tests when server is running in ReadOnly mode
////////////////////////////////////////////////////////////////////////////////
function readOnlyDatabaseSuite () {
  var db;
  var collection;
  return {

    ////////////////////////////////////////////////////////////////////////////////
    /// @brief set up
    ////////////////////////////////////////////////////////////////////////////////

    setUp : function () {
      db = require("internal").db;
      collection = db._createDocumentCollection("testCol");
      collection.save({_key: "testDocKey", a: 2 });
      db._changeMode("ReadOnly");
    },
    tearDown : function () {
      try {
        db._changeMode("Normal");
        collection.drop("testCol");
      } catch (e) {
        print(e);
      }
    },

    ////////////////////////////////////////////////////////////////////////////////
    /// @brief test: simple routing (prefix)
    ////////////////////////////////////////////////////////////////////////////////

    testCreateDocumentCollection: function () {
      var not_modified = false;
      try {
        db._createDocumentCollection("abcDC");
        } catch (e) {
          not_modified = true;
          assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
        }
      assertTrue(not_modified);
    },

    ////////////////////////////////////////////////////////////////////////////////
    /// @brief test: simple routing (parameter)
    ////////////////////////////////////////////////////////////////////////////////

    testDropCollection: function () {
      var not_modified = false;
      try {
        db._createDocumentCollection("xxxDC");
        not_modified = true;
        } catch (e) {
      }
      assertFalse(not_modified);
    },

    ////////////////////////////////////////////////////////////////////////////////
    /// @brief test: simple routing (optional)
    ////////////////////////////////////////////////////////////////////////////////

    testInsertDocument: function () {
      var modified = false;
      try {
        collection.save({a:1, b:2});
        modified = true;
        } catch (e) {
          assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
        }
        assertFalse(modified);
      },

      ////////////////////////////////////////////////////////////////////////////////
      /// @brief test: simple routing (optional)
      ////////////////////////////////////////////////////////////////////////////////

      testUpdateDocument: function () {
        var modified = false;
        try {
          collection.update("testDocKey", {name: "testing", a: 3});
          modified = true;
          } catch (e) {
            assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
          }
        assertFalse(modified);
      },

      ////////////////////////////////////////////////////////////////////////////////
      /// @brief test: simple routing (prefix vs non-prefix)
      ////////////////////////////////////////////////////////////////////////////////

      testRemoveDocument: function () {
        var modified = false;
        try {
          var removed = collection.remove("testDocKey");
          assertFalse(removed);
          modified = true;
        } catch (e) {
          assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
        }
        assertFalse(modified);
      },

      ////////////////////////////////////////////////////////////////////////////////
      /// @brief test: content string
      ////////////////////////////////////////////////////////////////////////////////

      testCreateBitArrayIndex: function () {
        var modified = false;
        try {
          collection.ensureBitarray("a", [1,2,3,4]);
          modified = true;
          } catch (e) {
            assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
          }
        assertFalse(modified);
      },

      testCreateHashIndex: function () {
        var modified = false;
        try {
          collection.ensureIndex({ type: "hash", fields: [ "name" ], unique: true });
          modified = true;
          } catch (e) {
            assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
          }
        assertFalse(modified);
      },

      testCreateGeoIndex: function () {
        var modified = false;
        try {
          collection.ensureIndex({ type: "geo1", fields: [ "x" ], unique: true });
          modified = true;
          } catch (e) {
            assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
          }
        assertFalse(modified);
       },

       testCreateGeo2Index: function () {
         var modified = false;
         try {
           collection.ensureIndex({ type: "geo2", fields: [ "x", "y" ], unique: true });
           modified = true;
         } catch (e) {
           assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
         }
         assertFalse(modified);
       },

       testCreateSkipListIndex: function () {
         var modified = false;
         try {
           collection.ensureIndex({ type: "skiplist", fields: [ "x" ]});
           modified = true;
         } catch (e) {
           assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
         }
         assertFalse(modified);
       },

  };
}

// -----------------------------------------------------------------------------
// --SECTION--                                                              main
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief executes the test suites
////////////////////////////////////////////////////////////////////////////////

jsunity.run(dropDatabaseTestSuite);
jsunity.run(readOnlyDatabaseSuite);

return jsunity.done();

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "\\(/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @\\}\\)"
// End:
<|endoftext|>


<commit_before>var d3 = require('d3')
,   Marty = require('marty');

var format = d3.time.format('%y-%b').parse;

var data = {
    Charizard: {
        usage: {
            ou: [
                {x: format('14-JAN'), y: .40},
                {x: format('14-FEB'), y: .30},
                {x: format('14-MAR'), y: .10},
                {x: format('14-APR'), y: .5},
                {x: format('14-MAY'), y: .8},
                {x: format('14-JUN'), y: .15},
                {x: format('14-JUL'), y: .20}
            ]
        }

    },
    Bulbasaur: {
        usage: {
            ou: [
                {x: format('14-JAN'), y: .30},
                {x: format('14-FEB'), y: .80},
                {x: format('14-MAR'), y: .20},
                {x: format('14-APR'), y: .99},
                {x: format('14-MAY'), y: .80},
                {x: format('14-JUN'), y: .42},
                {x: format('14-JUL'), y: .10}
            ]
        }
    }

};

var Service = Marty.createStateSource({
    getUsage: function(pokemon) {
        return data[pokemon];
    }
});

module.exports = Service;<commit_msg>something's weird with this file<commit_after>var d3 = require('d3')
,   Marty = require('marty');

var format = d3.time.format('%y-%b').parse;

var data = {
    Charizard: {
        usage: {
            ou: [
                {x: format('14-JAN'), y: .40},
                {x: format('14-FEB'), y: .30},
                {x: format('14-MAR'), y: .10},
                {x: format('14-APR'), y: .5},
                {x: format('14-MAY'), y: .8},
                {x: format('14-JUN'), y: .15},
                {x: format('14-JUL'), y: .20}
            ]
        }

    },
    Bulbasaur: {
        usage: {
            ou: [
                {x: format('14-JAN'), y: .30},
                {x: format('14-FEB'), y: .80},
                {x: format('14-MAR'), y: .20},
                {x: format('14-APR'), y: .99},
                {x: format('14-MAY'), y: .80},
                {x: format('14-JUN'), y: .42},
                {x: format('14-JUL'), y: .10}
            ]
        }
    }

};

var Service = Marty.createStateSource({
    getUsage: function(pokemon) {
        return data[pokemon];
    }
});

module.exports = Service;<|endoftext|>


<commit_before>/**
* heatmap plotting using d3
* Isaak Y Tecle <iyt2@cornell.edu>
*
*/

var solGS = solGS || function solGS() {};

solGS.heatmap = {

    plot: function (data, heatmapCanvasDiv, heatmapPlotDiv, downloadLinks) {

	data = JSON.parse(data);

	var labels = data.labels.splice(0,20);
	//var labels = data.labels;
	var values = data.values;
	var nLabels = labels.length;

	var corr = [];
	var coefs = [];

        for (var i=0;  i<values.length; i++) {

	    if (i < 20) {
	    var rw = values[i];

	    for (var j = 0; j<nLabels; j++) {
		var clNm = labels[j];

		var rwVl = rw[clNm];

		if (rwVl === undefined) {rwVl = 'NA';}

		if (j < 20) {

		corr.push({"row": i, "col": j, "value": rwVl});

		if (rwVl != 'NA') {
		    coefs.push(rwVl);
		}
		}
	}
	    }
	}

	if (heatmapCanvasDiv.match(/#/) == null) {heatmapCanvasDiv = '#' + heatmapCanvasDiv;}

	if (heatmapPlotDiv) {
	    if (heatmapPlotDiv.match(/#/) == null) {heatmapPlotDiv = '#' + heatmapPlotDiv;}
	} else {
	    heatmapPlotDiv =  "#heatmap_plot";
	}

	var heatmapCanvas = heatmapCanvasDiv;

	var plotExists = jQuery(heatmapCanvas).text();
	console.log('plotexist ', plotExists)

	var height = 400;
	var width  = 400;

	if (nLabels < 8) {
            height = height * 0.5;
            width  = width  * 0.5;
	}

	var pad    = {left:70, top:30, right:100, bottom: 90};
	var totalH = height + pad.top + pad.bottom;
	var totalW = width + pad.left + pad.right;

	var nve  = "#6A0888";
	var pve  = "#86B404";
	var nral = "blue";

	var rmax = d3.max(coefs);
	var rmin = d3.min(coefs);

	if (rmin >= 0 && rmax > 0 ) {
            rmax = rmax;
	} else if (rmin < 0 && -rmin > rmax )  {
            rmax = -rmin;
	}

	var corXscale = d3.scale.ordinal().domain(d3.range(nLabels)).rangeBands([0, width]);
	var corYscale = d3.scale.ordinal().domain(d3.range(nLabels)).rangeBands([height, 0]);
	var corZscale = d3.scale.linear().domain([-rmax, rmax]).range([nve, pve]);

	var xAxisScale = d3.scale.ordinal()
            .domain(labels)
            .rangeBands([0, width]);

	var yAxisScale = d3.scale.ordinal()
            .domain(labels)
            .rangeRoundBands([height, 0]);

	var svg = d3.select(heatmapCanvas)
            .append("svg")
            .attr("height", totalH)
            .attr("width", totalW);

	var xAxis = d3.svg.axis()
            .scale(xAxisScale)
            .orient("bottom");

	var yAxis = d3.svg.axis()
            .scale(yAxisScale)
            .orient("left");

	var corrplot = svg.append("g")
            .attr("id", heatmapPlotDiv)
            .attr("transform", "translate(" + pad.left + "," + pad.top + ")");

	corrplot.append("g")
            .attr("class", "x axis")
            .attr("transform", "translate(0," + height +")")
            .call(xAxis)
            .selectAll("text")
            .attr("y", 0)
            .attr("x", 10)
            .attr("dy", ".1em")
            .attr("transform", "rotate(90)")
            .attr("fill", "#523CB5")
            .style({"text-anchor":"start", "fill": "#523CB5"});

	corrplot.append("g")
            .attr("class", "y axis")
            .attr("transform", "translate(0,0)")
            .call(yAxis)
            .selectAll("text")
            .attr("y", 0)
            .attr("x", -10)
            .attr("dy", ".1em")
            .attr("fill", "#523CB5")
            .style("fill", "#523CB5");

	var cell = corrplot.selectAll("rect")
            .data(corr)
            .enter().append("rect")
            .attr("class", "cell")
            .attr("x", function (d) {return corXscale(d.col)})
            .attr("y", function (d) {return corYscale(d.row)})
            .attr("width", corXscale.rangeBand())
            .attr("height", corYscale.rangeBand())
            .attr("fill", function (d) {
                if (d.value == 'NA') {
		    return "white";
		} else if (d.value == 0) {
		    return nral;
		} else { return corZscale(d.value);}
            })
            .attr("stroke", "white")
            .attr("stroke-width", 1)
            .on("mouseover", function (d) {
                if(d.value != 'NA') {
                    d3.select(this)
                        .attr("stroke", "green")
                    corrplot.append("text")
                        .attr("id", "corrtext")
                        .text("[" + labels[d.row]
                              + " vs. " + labels[d.col]
                              + ": " + d3.format(".2f")(d.value)
                              + "]")
                        .style("fill", function () {
                            if (d.value > 0)
                            { return pve; }
                            else if (d.value < 0)
                            { return nve; }
			    else if (d.value == 0) {
				return nral;
			    }

                        })
                        .attr("x", totalW * 0.5)
                        .attr("y", totalH * 0.5)
                        .attr("font-weight", "bold")
                        .attr("dominant-baseline", "middle")
                        .attr("text-anchor", "middle")
                }
            })
            .on("mouseout", function() {
                d3.selectAll("text.corrlabel").remove()
                d3.selectAll("text#corrtext").remove()
                d3.select(this).attr("stroke","white")
            });

	corrplot.append("rect")
            .attr("height", height)
            .attr("width", width)
            .attr("fill", "none")
            .attr("stroke", "#523CB5")
            .attr("stroke-width", 1)
            .attr("pointer-events", "none");

	var legendValues = [];

	if (d3.min(coefs) > 0 && d3.max(coefs) > 0 ) {
            legendValues = [[0, 0], [1, d3.max(coefs)]];
	} else if (d3.min(coefs) < 0 && d3.max(coefs) < 0 )  {
            legendValues = [[0, d3.min(coefs)], [1, 0]];
	} else {
            legendValues = [[0, d3.min(coefs)], [1, 0], [2, d3.max(coefs)]];
	}

	var legend = corrplot.append("g")
            .attr("class", "cell")
            .attr("transform", "translate(" + (width + 10) + "," +  (height * 0.25) + ")")
            .attr("height", 100)
            .attr("width", 100);

	var recLH = 20;
	var recLW = 20;

	legend = legend.selectAll("rect")
            .data(legendValues)
            .enter()
            .append("rect")
            .attr("x", function (d) { return 1;})
            .attr("y", function (d) { return 1 + (d[0] * recLH) + (d[0] * 5); })
            .attr("width", recLH)
            .attr("height", recLW)
            .style("stroke", "black")
            .attr("fill", function (d) {
		if (d == 'NA') {return "white"}
		else {return corZscale(d[1])}
            });

	var legendTxt = corrplot.append("g")
            .attr("transform", "translate(" + (width + 40) + ","
		  + ((height * 0.25) + (0.5 * recLW)) + ")")
            .attr("id", "legendtext");

	legendTxt.selectAll("text")
            .data(legendValues)
            .enter()
            .append("text")
            .attr("fill", "#523CB5")
            .style("fill", "#523CB5")
            .attr("x", 1)
            .attr("y", function (d) { return 1 + (d[0] * recLH) + (d[0] * 5); })
            .text(function (d) {
		if (d[1] > 0) { return '> 0'; }
		else if (d[1] < 0) { return '< 0'; }
		else if (d[1] == 0 ){ return '0'; }
            })
            .attr("dominant-baseline", "middle")
            .attr("text-anchor", "start");

	if (downloadLinks) {
	    jQuery(heatmapCanvas).append('
' + downloadLinks + '
');
	}

    },

///////
}

<commit_msg>scale label color<commit_after>/**
* heatmap plotting using d3
* Isaak Y Tecle <iyt2@cornell.edu>
*
*/

var solGS = solGS || function solGS() {};

solGS.heatmap = {

    plot: function (data, heatmapCanvasDiv, heatmapPlotDiv, downloadLinks) {

	data = JSON.parse(data);

	var labels = data.labels.splice(0,20);
	//var labels = data.labels;
	var values = data.values;
	var nLabels = labels.length;

	var corr = [];
	var coefs = [];

        for (var i=0;  i<values.length; i++) {

	    if (i < 20) {
	    var rw = values[i];

	    for (var j = 0; j<nLabels; j++) {
		var clNm = labels[j];

		var rwVl = rw[clNm];

		if (rwVl === undefined) {rwVl = 'NA';}

		if (j < 20) {

		corr.push({"row": i, "col": j, "value": rwVl});

		if (rwVl != 'NA') {
		    coefs.push(rwVl);
		}
		}
	}
	    }
	}

	if (heatmapCanvasDiv.match(/#/) == null) {heatmapCanvasDiv = '#' + heatmapCanvasDiv;}

	if (heatmapPlotDiv) {
	    if (heatmapPlotDiv.match(/#/) == null) {heatmapPlotDiv = '#' + heatmapPlotDiv;}
	} else {
	    heatmapPlotDiv =  "#heatmap_plot";
	}

	var heatmapCanvas = heatmapCanvasDiv;

	var plotExists = jQuery(heatmapCanvas).text();
	console.log('plotexist ', plotExists)

	var height = 400;
	var width  = 400;

	if (nLabels < 8) {
            height = height * 0.5;
            width  = width  * 0.5;
	}

	var pad    = {left:70, top:30, right:100, bottom: 90};
	var totalH = height + pad.top + pad.bottom;
	var totalW = width + pad.left + pad.right;

	var nve  = "#6A0888";
	var pve  = "#86B404";
	var nral = "blue";

	var rmax = d3.max(coefs);
	var rmin = d3.min(coefs);

	if (rmin >= 0 && rmax > 0 ) {
            rmax = rmax;
	} else if (rmin < 0 && -rmin > rmax )  {
            rmax = -rmin;
	}

	var corXscale = d3.scale.ordinal().domain(d3.range(nLabels)).rangeBands([0, width]);
	var corYscale = d3.scale.ordinal().domain(d3.range(nLabels)).rangeBands([height, 0]);
	var corZscale = d3.scale.linear().domain([-rmax, rmax]).range([nve, pve]);

	var xAxisScale = d3.scale.ordinal()
            .domain(labels)
            .rangeBands([0, width]);

	var yAxisScale = d3.scale.ordinal()
            .domain(labels)
            .rangeRoundBands([height, 0]);

	var svg = d3.select(heatmapCanvas)
            .append("svg")
            .attr("height", totalH)
            .attr("width", totalW);

	var xAxis = d3.svg.axis()
            .scale(xAxisScale)
            .orient("bottom");

	var yAxis = d3.svg.axis()
            .scale(yAxisScale)
            .orient("left");

	var corrplot = svg.append("g")
            .attr("id", heatmapPlotDiv)
            .attr("transform", "translate(" + pad.left + "," + pad.top + ")");

	corrplot.append("g")
            .attr("class", "x axis")
            .attr("transform", "translate(0," + height +")")
            .call(xAxis)
            .selectAll("text")
            .attr("y", 0)
            .attr("x", 10)
            .attr("dy", ".1em")
            .attr("transform", "rotate(90)")
            .attr("fill", "#523CB5")
            .style({"text-anchor":"start", "fill": "#523CB5"});

	corrplot.append("g")
            .attr("class", "y axis")
            .attr("transform", "translate(0,0)")
            .call(yAxis)
            .selectAll("text")
            .attr("y", 0)
            .attr("x", -10)
            .attr("dy", ".1em")
            .attr("fill", "#523CB5")
            .style("fill", "#523CB5");

	var cell = corrplot.selectAll("rect")
            .data(corr)
            .enter().append("rect")
            .attr("class", "cell")
            .attr("x", function (d) {return corXscale(d.col)})
            .attr("y", function (d) {return corYscale(d.row)})
            .attr("width", corXscale.rangeBand())
            .attr("height", corYscale.rangeBand())
            .attr("fill", function (d) {
                if (d.value == 'NA') {
		    return "white";
		} else if (d.value == 0) {
		    return nral;
		} else { return corZscale(d.value);}
            })
            .attr("stroke", "white")
            .attr("stroke-width", 1)
            .on("mouseover", function (d) {
                if(d.value != 'NA') {
                    d3.select(this)
                        .attr("stroke", "green")
                    corrplot.append("text")
                        .attr("id", "corrtext")
                        .text("[" + labels[d.row]
                              + " vs. " + labels[d.col]
                              + ": " + d3.format(".3f")(d.value)
                              + "]")
                        .style("fill", function () {
                            if (d.value != 0)
                            { return corZscale(d.value); }
			    else if (d.value == 0) {
				return nral;
			    }

                        })
                        .attr("x", totalW * 0.5)
                        .attr("y", totalH * 0.5)
                        .attr("font-weight", "bold")
                        .attr("dominant-baseline", "middle")
                        .attr("text-anchor", "middle")
                }
            })
            .on("mouseout", function() {
                d3.selectAll("text.corrlabel").remove()
                d3.selectAll("text#corrtext").remove()
                d3.select(this).attr("stroke","white")
            });

	corrplot.append("rect")
            .attr("height", height)
            .attr("width", width)
            .attr("fill", "none")
            .attr("stroke", "#523CB5")
            .attr("stroke-width", 1)
            .attr("pointer-events", "none");

	var legendValues = [];

	if (d3.min(coefs) > 0 && d3.max(coefs) > 0 ) {
            legendValues = [[0, 0], [1, d3.max(coefs)]];
	} else if (d3.min(coefs) < 0 && d3.max(coefs) < 0 )  {
            legendValues = [[0, d3.min(coefs)], [1, 0]];
	} else {
            legendValues = [[0, d3.min(coefs)], [1, 0], [2, d3.max(coefs)]];
	}

	var legend = corrplot.append("g")
            .attr("class", "cell")
            .attr("transform", "translate(" + (width + 10) + "," +  (height * 0.25) + ")")
            .attr("height", 100)
            .attr("width", 100);

	var recLH = 20;
	var recLW = 20;

	legend = legend.selectAll("rect")
            .data(legendValues)
            .enter()
            .append("rect")
            .attr("x", function (d) { return 1;})
            .attr("y", function (d) { return 1 + (d[0] * recLH) + (d[0] * 5); })
            .attr("width", recLH)
            .attr("height", recLW)
            .style("stroke", "black")
            .attr("fill", function (d) {
		if (d == 'NA') {return "white"}
		else {return corZscale(d[1])}
            });

	var legendTxt = corrplot.append("g")
            .attr("transform", "translate(" + (width + 40) + ","
		  + ((height * 0.25) + (0.5 * recLW)) + ")")
            .attr("id", "legendtext");

	legendTxt.selectAll("text")
            .data(legendValues)
            .enter()
            .append("text")
            .attr("fill", "#523CB5")
            .style("fill", "#523CB5")
            .attr("x", 1)
            .attr("y", function (d) { return 1 + (d[0] * recLH) + (d[0] * 5); })
            .text(function (d) {
		if (d[1] > 0) { return '> 0'; }
		else if (d[1] < 0) { return '< 0'; }
		else if (d[1] == 0 ){ return '0'; }
            })
            .attr("dominant-baseline", "middle")
            .attr("text-anchor", "start");

	if (downloadLinks) {
	    jQuery(heatmapCanvas).append('
' + downloadLinks + '
');
	}

    },

///////
}

<|endoftext|>


<commit_before>define('tempo30/app/update-overpass', [
    'rsvp',
    'fs',
    'request',
    'text!tempo30/overpass/strassenliste.txt',
    'text!tempo30/overpass/strassenliste-test.txt',
    'tempo30/model/osm-points-tags',
], function (RSVP, fs, request, opStrassen, opStrassenTest, osmTags) {

    'use strict';

    var baseurl='http://overpass-api.de/api/interpreter';
    var strassenFile='/tmp/tempo30-strassenliste.json';
    var osmPoiFile='/tmp/tempo30-osm-poi.json';
    var dataStrassenFile='data/strassenliste.json';
    var dataOsmPoiFile='data/osm-poi.json';
    var refreshTime= 24*60*60;

    // create_action is only executed if file is older than a time or it does not exists
    function fileIsOlderOrNotExists(file, time_in_sec, create_action) {
	return new RSVP.Promise(function(resolve, reject){
	    fs.stat(file, function(err, stat) {
		if(err === null) {
		    var mstamp = new Date(stat.mtime).getTime() / 1000;
		    var now = new Date().getTime() / 1000;
		    if (time_in_sec < (now-mstamp)) {
			create_action().then(resolve);
		    } else {
			console.log('skipping new creation of '+file);
			resolve();
		    }
		} else if(err.code == 'ENOENT') {
		    // file does not exist
		    create_action().then(resolve).catch(err);
		} else {
		    reject(err);
		}
	    });
	});
    }

    function getOverpassResult(data) {
	return new RSVP.Promise(function(resolve, reject){
            var url = baseurl + '?data=' +
		encodeURIComponent(data);
            console.log(url);
            request(url, function (error, response, content) {
		if (!error && response.statusCode == 200) {
                    resolve(content);
		} else {
		    reject(error,response);
		}
	    });
	});
    }

    function getOSMPoiOverpassQuery() {
	var query= '[out:json][timeout:60];(';
	for (var i = 0; i < osmTags.length; i++) {
	    query=query+'node["'+osmTags[i].k+'"="'+osmTags[i].v+'"](BBOX);';
	    query=query+'way["'+osmTags[i].k+'"="'+osmTags[i].v+'"](BBOX);';
	}
	query = query+ ');out tags center;';
	query = query.replace(new RegExp('BBOX','g'),'53.40912254769818,9.741439819335938,53.72962293149973,10.224151611328125');
	return query;
    }

    function saveStrListenResult(testmode, o, cb, cbErr)  {
	var arr=o.split(/\r?\n/).sort();
	var ret = [arr[0]];
	for (var i = 1; i < arr.length; i++) { // start loop at 1 as element 0 can never be a duplicate
	    if (arr[i-1] !== arr[i]) {
		ret.push(arr[i]);
	    }
	}
	console.log(ret);
	var outStr;
        if (testmode) {
            outStr=JSON.stringify(ret, null, 2);
        } else {
            outStr=JSON.stringify(ret);
        }
        fs.writeFile(strassenFile, outStr, function(error) {
            if(error) {
		cbErr(error);
                return;
            }
            console.log('The Street File was saved!');
	    cb();
        });
    }

    function saveOsmPoi(outStr, cb, errcb) {
	fs.writeFile(osmPoiFile, outStr, function(error) {
            if(error) {
                errcb(error);
                return;
            }
            console.log('The OSM-POI File was saved!');
	    cb();
        });
    }

    function copyFile(source, target, cb) {
	var cbCalled = false;

	var rd = fs.createReadStream(source);
	rd.on("error", function(err) {
	    done(err);
	});
	var wr = fs.createWriteStream(target);
	wr.on("error", function(err) {
	    done(err);
	});
	wr.on("close", function(ex) {
	    done();
	});
	rd.pipe(wr);

	function done(err) {
	    console.log('copied '+source+' to '+target);
	    if (!cbCalled) {
		cb(err);
		cbCalled = true;
	    }
	}
    }
    return function(testmode, done, err) {
	fileIsOlderOrNotExists(osmPoiFile, refreshTime, function () {
	    return new RSVP.Promise(function(resolve, reject){
		getOverpassResult(getOSMPoiOverpassQuery()).then(function (o) {
		    saveOsmPoi(o, resolve, reject);
		});
	    });
	}).then(function () {
	    copyFile(osmPoiFile, dataOsmPoiFile, function () {
		fileIsOlderOrNotExists(strassenFile, refreshTime, function () {
		    return new RSVP.Promise(function(resolve, reject){
			var opQuery;
			if (testmode) {
			    opQuery = opStrassenTest;
			} else {
			    opQuery = opStrassen;
			}
			console.log('Asking for Strassenliste', opQuery);
			return getOverpassResult(opQuery).then(function (o) {
			    saveStrListenResult(testmode, o, resolve, reject);
			});
		    });

		}).then( function() {
		    copyFile(strassenFile, dataStrassenFile, function () {
			done();
		    });
		}).catch(function(reason){
		    console.log('err',reason);
		    err();
		});
	    });
	}).catch(function(reason){
	    console.log('err',reason);
	    err();
	});

    };

});<commit_msg>create data directory<commit_after>define('tempo30/app/update-overpass', [
    'rsvp',
    'fs',
    'request',
    'text!tempo30/overpass/strassenliste.txt',
    'text!tempo30/overpass/strassenliste-test.txt',
    'tempo30/model/osm-points-tags',
], function (RSVP, fs, request, opStrassen, opStrassenTest, osmTags) {

    'use strict';

    var baseurl='http://overpass-api.de/api/interpreter';
    var strassenFile='/tmp/tempo30-strassenliste.json';
    var osmPoiFile='/tmp/tempo30-osm-poi.json';
    var dataStrassenFile='data/strassenliste.json';
    var dataOsmPoiFile='data/osm-poi.json';
    var refreshTime= 20*60*60;

    // create_action is only executed if file is older than a time or it does not exists
    function fileIsOlderOrNotExists(file, time_in_sec, create_action) {
	return new RSVP.Promise(function(resolve, reject){
	    fs.stat(file, function(err, stat) {
		if(err === null) {
		    var mstamp = new Date(stat.mtime).getTime() / 1000;
		    var now = new Date().getTime() / 1000;
		    if (time_in_sec < (now-mstamp)) {
			create_action().then(resolve);
		    } else {
			console.log('skipping new creation of '+file);
			resolve();
		    }
		} else if(err.code == 'ENOENT') {
		    // file does not exist
		    create_action().then(resolve).catch(err);
		} else {
		    reject(err);
		}
	    });
	});
    }

    function getOverpassResult(data) {
	return new RSVP.Promise(function(resolve, reject){
            var url = baseurl + '?data=' +
		encodeURIComponent(data);
            console.log(url);
            request(url, function (error, response, content) {
		if (!error && response.statusCode == 200) {
                    resolve(content);
		} else {
		    reject(error,response);
		}
	    });
	});
    }

    function getOSMPoiOverpassQuery() {
	var query= '[out:json][timeout:60];(';
	for (var i = 0; i < osmTags.length; i++) {
	    query=query+'node["'+osmTags[i].k+'"="'+osmTags[i].v+'"](BBOX);';
	    query=query+'way["'+osmTags[i].k+'"="'+osmTags[i].v+'"](BBOX);';
	}
	query = query+ ');out tags center;';
	query = query.replace(new RegExp('BBOX','g'),'53.40912254769818,9.741439819335938,53.72962293149973,10.224151611328125');
	return query;
    }

    function saveStrListenResult(testmode, o, cb, cbErr)  {
	var arr=o.split(/\r?\n/).sort();
	var ret = [arr[0]];
	for (var i = 1; i < arr.length; i++) { // start loop at 1 as element 0 can never be a duplicate
	    if (arr[i-1] !== arr[i]) {
		ret.push(arr[i]);
	    }
	}
	console.log(ret);
	var outStr;
        if (testmode) {
            outStr=JSON.stringify(ret, null, 2);
        } else {
            outStr=JSON.stringify(ret);
        }
        fs.writeFile(strassenFile, outStr, function(error) {
            if(error) {
		cbErr(error);
                return;
            }
            console.log('The Street File was saved!');
	    cb();
        });
    }

    function saveOsmPoi(outStr, cb, errcb) {
	fs.writeFile(osmPoiFile, outStr, function(error) {
            if(error) {
                errcb(error);
                return;
            }
            console.log('The OSM-POI File was saved!');
	    cb();
        });
    }

    function copyFile(source, target, cb) {
	var cbCalled = false;

	var rd = fs.createReadStream(source);
	rd.on("error", function(err) {
	    done(err);
	});
	var wr = fs.createWriteStream(target);
	wr.on("error", function(err) {
	    done(err);
	});
	wr.on("close", function(ex) {
	    done();
	});
	rd.pipe(wr);

	function done(err) {
	    console.log('copied '+source+' to '+target);
	    if (!cbCalled) {
		cb(err);
		cbCalled = true;
	    }
	}
    }
    return function(testmode, done, err) {
	fileIsOlderOrNotExists(osmPoiFile, refreshTime, function () {
	    return new RSVP.Promise(function(resolve, reject){
		getOverpassResult(getOSMPoiOverpassQuery()).then(function (o) {
		    saveOsmPoi(o, resolve, reject);
		});
	    });
	}).then(function () {
	    copyFile(osmPoiFile, dataOsmPoiFile, function () {
		fileIsOlderOrNotExists(strassenFile, refreshTime, function () {
		    return new RSVP.Promise(function(resolve, reject){
			var opQuery;
			if (testmode) {
			    opQuery = opStrassenTest;
			} else {
			    opQuery = opStrassen;
			}
			console.log('Asking for Strassenliste', opQuery);
			return getOverpassResult(opQuery).then(function (o) {
			    saveStrListenResult(testmode, o, resolve, reject);
			});
		    });

		}).then( function() {
		    copyFile(strassenFile, dataStrassenFile, function () {
			done();
		    });
		}).catch(function(reason){
		    console.log('err',reason);
		    err();
		});
	    });
	}).catch(function(reason){
	    console.log('err',reason);
	    err();
	});

    };

});
<|endoftext|>


<commit_before>(function(jQuery) {

  var $ = jQuery;
  var GBROWSE = '/gbrowse_phavu1.0?query=ref=Pv04;start=15056944;stop=15058034;add=Pv04+Marker+BM199+15056944..15057534;h_feat=BM199@yellow;style=Marker+bgcolor=red';

  var tour = new Tour({
    name: 'qtl-search-to-gbrowse',
    debug: true,
    orphan: true,
    steps : [
      {
      	path: '/tours',
      	title: 'Welcome to LIS!',
      	content: 'Let\'s go the legumeinfo.org homepage, where the QTL Tour will begin.
Use the Next button or → (right arrow key) to advance the tour. Use the Prev button or ← (left arrow key) to step back.',
      	placement: 'bottom',
      	element: '#site-name',
	reflex: true,
      },
      {
      	path: '/',
      	title: 'QTL Tour: Getting started',
      	content: 'This tour will provide an example of navigating LIS from the genetic location of a published QTL to the associated region of the annotated genome for the species in which it was found.
 Now press the QTL Search button, or use the Next button or press →.',
      	placement: 'bottom',
      	element: "[href='/search/qtl']",
	reflex: true,
      },
      {
      	path: '/search/qtl',
      	title: 'QTL Tour: Finding the desired QTL',
      	content: 'All of the QTLs that have been curated into LIS from the literature are displayed in the paged results below, and can be filtered using the search fields above. We entered "Seed yield" in the QTL name field. The Apply button will apply the search parameters. Now press Next or →',
      	placement: 'bottom',
      	element: '#edit-qtl-name',
	reflex: true,
      	onShown: function(tour) {
      	  $('#edit-qtl-name')[0].value='Seed yield';
      	},
      },
      {
      	path: '/search/qtl?organism=Phaseolus%20vulgaris&trait_class=All&expt_pub_symbol_op=%3D&expt_pub_symbol=&qtl_name_op=%3D&qtl_name=seed%20yield',
      	title: 'QTL Tour: The list of QTL matching the query',
      	content: 'Let us look at the details for a specific "seed yield" QTL.',
      	element: "[href='/feature/Phaseolus/vulgaris/QTL/phavu.Seed-yield-2-5']",
	reflex: true,
      	placement: 'bottom',
      },
      {
      	path: '/feature/Phaseolus/vulgaris/QTL/phavu.Seed-yield-2-5',
      	title: 'QTL Tour: Information about the selected QTL',
      	content: "The QTL Details link will reveal this QTL's place on the chromosome.",
      	placement: 'right',
      	element: "[href='?pane=qtl_details']",
	reflex: true,
	onNext: function(tour) {
	  var el = $("[href='?pane=qtl_details']")[0];
	  if(el) {
	    el.click();
	  }
	}
      },
      {
	path: '/feature/Phaseolus/vulgaris/QTL/phavu.Seed-yield-2-5#pane=qtl_details',
      	title: 'QTL Tour: BM199 = Nearest Marker',
      	content: 'This is the marker that had the strongest association with variation in the trait for this QTL, among those used in the mapping experiment. Since the marker has sequence information associated with it, we can find its position in the genome sequence to find the general region in which the gene responsible for the QTL may be found- note, however that the marker is not guaranteed to be very close to any candidate gene, and you should use this only as a very general guide.',
      	placement: 'right',
      	element: "#tripal_feature-table-base > tbody > tr:nth-child(3) > td > a",
	reflex: true,
	onShow: function(tour) {
	  if(location.hash.indexOf('qtl_details') === -1) {
	    var el = $("[href='?pane=qtl_details']")[0];
	    if(el) {
	      el.click();
	    }
	  }
	}
      },
      {
	path: '/node/1360783', /* url must match prev reflex element url */
      	title: 'QTL Tour: Marker Overview',
      	content: 'The "Overview" links to articles and descriptions of the marker. To find this marker on the phaseolus map, we can look under "Marker Positions".',
      	element: "[href='?pane=positions']",
	reflex: true,
      	placement: 'bottom',
	onNext: function(tour) {
	  var el = $("[href='?pane=positions']")[0];
	  if(el) {
	    el.click();
	  }
	}
      },
      {
	path: '/node/1360783#pane=positions',
      	title: 'QTL Tour: Genome Browser',
      	content: 'The linked GBrowse map will show you annotations on the genome.',
      	element: "[href='/gbrowse_phavu1.0?query=ref=Pv04;start=15056944;stop=15058034;add=Pv04+Marker+BM199+15056944..15057534;h_feat=BM199@yellow;style=Marker+bgcolor=red']",
	reflex: true,
      	placement: 'top',
	onShow: function(tour) {
	  if(location.hash.indexOf('positions') === -1) {
	    var el = $("[href='?pane=positions']")[0];
	    if(el) {
	      el.click();
	    }
	  }
	}
      },
      {
	path: GBROWSE,
	title: 'QTL Tour: GBrowse',
	content: 'Loading GBrowse...',
	placement: 'top',
	onShown: function(tour) {
	  // wait for dynamic content with a loading dialog.
	  if(tour.skipStep) {
	    tour.skipStep = false;
	    tour.prev();
	    return;
	  }
	  var promise = lisTours.waitForContent(
	    tour,
	    function() {
	      return $('#frameviewer').contents().find('#centromere_image')[0];
	    });
	  // advance automatically to next step when done loading
	  promise.then(function() {
	    tour.next();
	  });
	  return promise;
	}
      },
      {
	path: GBROWSE,
	title: 'QTL Tour: GBrowse',
	content: 'GBrowse allows you to visualize syntenic relationships between legumes of your choice. The red bar is the lowest flanking marker for "seed yield".',
	element: '#frameviewer',
	placement: 'top',
	onPrev: function(tour) {
	  tour.skipStep = true;
	}
      },
      {
	path: GBROWSE,
        title: 'QTL Tour: Our track in GBrowse',
        content: 'Also visible is the lowest flanking marker, BM199. All the tracks can be dragged to rearrange them.',
	element: '#frameviewer',
	placement: 'top',
      }, {
	path: GBROWSE,
        title: 'QTL Tour: GBrowse Settings',
        content: 'You can choose which tracks to display through the navigation bar (Select Tracks).',
	element: '#frameviewer',
	placement: 'top'
      },
      {
	path: '/',
	title: 'QTL Tour: Completed',
	content: 'Congratulations, you have finished the QTL Tour! Summary: We navigated LIS from the genetic location of a published QTL to the associated region of the annotated genome for Phaseolus Vulgaris. Now press End Tour.'
      }
    ]
  });

  lisTours.register(tour);

}(window.__jquery));
<commit_msg>fix minor inconsistency in titles<commit_after>(function(jQuery) {

  var $ = jQuery;
  var GBROWSE = '/gbrowse_phavu1.0?query=ref=Pv04;start=15056944;stop=15058034;add=Pv04+Marker+BM199+15056944..15057534;h_feat=BM199@yellow;style=Marker+bgcolor=red';

  var tour = new Tour({
    name: 'qtl-search-to-gbrowse',
    debug: true,
    orphan: true,
    steps : [
      {
      	path: '/tours',
      	title: 'QTL Tour: Welcome to LIS!',
      	content: 'Let\'s go the legumeinfo.org homepage, where the QTL Tour will begin.
Use the Next button or → (right arrow key) to advance the tour. Use the Prev button or ← (left arrow key) to step back.',
      	placement: 'bottom',
      	element: '#site-name',
	reflex: true,
      },
      {
      	path: '/',
      	title: 'QTL Tour: Getting started',
      	content: 'This tour will provide an example of navigating LIS from the genetic location of a published QTL to the associated region of the annotated genome for the species in which it was found.
 Now press the QTL Search button, or use the Next button or press →.',
      	placement: 'bottom',
      	element: "[href='/search/qtl']",
	reflex: true,
      },
      {
      	path: '/search/qtl',
      	title: 'QTL Tour: Finding the desired QTL',
      	content: 'All of the QTLs that have been curated into LIS from the literature are displayed in the paged results below, and can be filtered using the search fields above. We entered "Seed yield" in the QTL name field. The Apply button will apply the search parameters. Now press Next or →',
      	placement: 'bottom',
      	element: '#edit-qtl-name',
	reflex: true,
      	onShown: function(tour) {
      	  $('#edit-qtl-name')[0].value='Seed yield';
      	},
      },
      {
      	path: '/search/qtl?organism=Phaseolus%20vulgaris&trait_class=All&expt_pub_symbol_op=%3D&expt_pub_symbol=&qtl_name_op=%3D&qtl_name=seed%20yield',
      	title: 'QTL Tour: The list of QTL matching the query',
      	content: 'Let us look at the details for a specific "seed yield" QTL.',
      	element: "[href='/feature/Phaseolus/vulgaris/QTL/phavu.Seed-yield-2-5']",
	reflex: true,
      	placement: 'bottom',
      },
      {
      	path: '/feature/Phaseolus/vulgaris/QTL/phavu.Seed-yield-2-5',
      	title: 'QTL Tour: Information about the selected QTL',
      	content: "The QTL Details link will reveal this QTL's place on the chromosome.",
      	placement: 'right',
      	element: "[href='?pane=qtl_details']",
	reflex: true,
	onNext: function(tour) {
	  var el = $("[href='?pane=qtl_details']")[0];
	  if(el) {
	    el.click();
	  }
	}
      },
      {
	path: '/feature/Phaseolus/vulgaris/QTL/phavu.Seed-yield-2-5#pane=qtl_details',
      	title: 'QTL Tour: BM199 = Nearest Marker',
      	content: 'This is the marker that had the strongest association with variation in the trait for this QTL, among those used in the mapping experiment. Since the marker has sequence information associated with it, we can find its position in the genome sequence to find the general region in which the gene responsible for the QTL may be found- note, however that the marker is not guaranteed to be very close to any candidate gene, and you should use this only as a very general guide.',
      	placement: 'right',
      	element: "#tripal_feature-table-base > tbody > tr:nth-child(3) > td > a",
	reflex: true,
	onShow: function(tour) {
	  if(location.hash.indexOf('qtl_details') === -1) {
	    var el = $("[href='?pane=qtl_details']")[0];
	    if(el) {
	      el.click();
	    }
	  }
	}
      },
      {
	path: '/node/1360783', /* url must match prev reflex element url */
      	title: 'QTL Tour: Marker Overview',
      	content: 'The "Overview" links to articles and descriptions of the marker. To find this marker on the phaseolus map, we can look under "Marker Positions".',
      	element: "[href='?pane=positions']",
	reflex: true,
      	placement: 'bottom',
	onNext: function(tour) {
	  var el = $("[href='?pane=positions']")[0];
	  if(el) {
	    el.click();
	  }
	}
      },
      {
	path: '/node/1360783#pane=positions',
      	title: 'QTL Tour: Genome Browser',
      	content: 'The linked GBrowse map will show you annotations on the genome.',
      	element: "[href='/gbrowse_phavu1.0?query=ref=Pv04;start=15056944;stop=15058034;add=Pv04+Marker+BM199+15056944..15057534;h_feat=BM199@yellow;style=Marker+bgcolor=red']",
	reflex: true,
      	placement: 'top',
	onShow: function(tour) {
	  if(location.hash.indexOf('positions') === -1) {
	    var el = $("[href='?pane=positions']")[0];
	    if(el) {
	      el.click();
	    }
	  }
	}
      },
      {
	path: GBROWSE,
	title: 'QTL Tour: GBrowse',
	content: 'Loading GBrowse...',
	placement: 'top',
	onShown: function(tour) {
	  // wait for dynamic content with a loading dialog.
	  if(tour.skipStep) {
	    tour.skipStep = false;
	    tour.prev();
	    return;
	  }
	  var promise = lisTours.waitForContent(
	    tour,
	    function() {
	      return $('#frameviewer').contents().find('#centromere_image')[0];
	    });
	  // advance automatically to next step when done loading
	  promise.then(function() {
	    tour.next();
	  });
	  return promise;
	}
      },
      {
	path: GBROWSE,
	title: 'QTL Tour: GBrowse',
	content: 'GBrowse allows you to visualize syntenic relationships between legumes of your choice. The red bar is the lowest flanking marker for "seed yield".',
	element: '#frameviewer',
	placement: 'top',
	onPrev: function(tour) {
	  tour.skipStep = true;
	}
      },
      {
	path: GBROWSE,
        title: 'QTL Tour: Our track in GBrowse',
        content: 'Also visible is the lowest flanking marker, BM199. All the tracks can be dragged to rearrange them.',
	element: '#frameviewer',
	placement: 'top',
      }, {
	path: GBROWSE,
        title: 'QTL Tour: GBrowse Settings',
        content: 'You can choose which tracks to display through the navigation bar (Select Tracks).',
	element: '#frameviewer',
	placement: 'top'
      },
      {
	path: '/',
	title: 'QTL Tour: Completed',
	content: 'Congratulations, you have finished the QTL Tour! Summary: We navigated LIS from the genetic location of a published QTL to the associated region of the annotated genome for Phaseolus Vulgaris. Now press End Tour.'
      }
    ]
  });

  lisTours.register(tour);

}(window.__jquery));
<|endoftext|>