<commit_before>import style from './style.css';

import classnames from 'classnames';
import React, { Component, PropTypes } from 'react';
import QueueAnim from 'rc-queue-anim';
import TweenOne from 'rc-tween-one';
import OverPack from 'rc-scroll-anim/lib/ScrollOverPack';
import { Tabs, Icon } from 'antd';

import LineCahrt from './components/LineCahrt';
import { formatNumberRgx } from 'utils/commons';

const TabPane = Tabs.TabPane;

class SecondPage extends Component {
  static propTypes = {
    style: PropTypes.string,
    className: PropTypes.string,
    id: PropTypes.string,
  };

  static defaultProps = {
    className: '',
  };

  constructor(props, context) {
    super(props, context);
    this.state = {};
  }

  /* eslint-disable */
  render() {
    const { className } = this.props;
    const submitCount = 2216008;
    const [dayName, monthName, yearName] = ['dayLineChart', 'monthLineChart', 'yearLineChart'];
    const dayData = {
      time: ['00:00', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00', '07:00', '08:00', '09:00', '10:00', '11:00',
             '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00'],
      count: [150, 100, 200, 350, 200, 300, 100, 150, 100, 200, 350, 200, 300, 100, 150, 100, 200, 350, 200, 300, 100, 200, 300, 200],
    };
    const monthData = {
      time: ['2016-10-01', '2016-10-02', '2016-10-03', '2016-10-04', '2016-10-05', '2016-10-06', '2016-10-07', '2016-10-08', '2016-10-09', '2016-10-10',
        '2016-10-11', '2016-10-12', '2016-10-13', '2016-10-14', '2016-10-15', '2016-10-16', '2016-10-17', '2016-10-18', '2016-10-19', '2016-10-20',
        '2016-10-21', '2016-10-22', '2016-10-23', '2016-10-24', '2016-10-25', '2016-10-26', '2016-10-27', '2016-10-28', '2016-10-29', '2016-10-30', '2016-10-31'],
      count: [1500, 1000, 2000, 3500, 2000, 3000, 1000, 1500, 1000, 2000, 3500, 2000, 3000, 1000, 1500, 1000, 2000, 3500, 2000, 3000, 1000, 4000, 3000, 3000, 1000, 2000, 3500, 2000, 3000, 1000, 1500],
    };
    const yearData = {
      time: ['2016-01月', '2016-02月', '2016-03月', '2016-04月', '2016-05月', '2016-06月', '2016-07月', '2016-08月', '2016-09月', '2016-10月', '2016-11月', '2016-12月'],
      count: [15000, 10000, 20000, 35000, 20000, 30000, 10000, 15000, 10000, 20000, 35000, 20000],
    };

    return (

        <OverPack
          className={`content-template ${this.props.className}`}
          hideProps={{ img: { reverse: true } }}
          location={this.props.id}
          className={style.content}
        >
          <TweenOne
            key="img"
            animation={{ x: '-=30', opacity: 0, type: 'from' }}
            className={`${this.props.className}-img`}
          >

              提交总数
              {formatNumberRgx(submitCount)}

          </TweenOne>
          <QueueAnim
            className={`${this.props.className}-text`}
            key="text"
            leaveReverse
            ease={['easeOutCubic', 'easeInCubic']}
            className={style.echart}
          >
            <Tabs key="tabs" tabPosition="left">
              <TabPane tab={<Icon type="dot-chart" />最近一天} key="1">
                <LineCahrt
                  idName={dayName}
                  data={dayData}
              />
              </TabPane>
              <TabPane tab={<Icon type="bar-chart" />最近一月} key="2">
                <LineCahrt
                  idName={monthName}
                  data={monthData}
                />
              </TabPane>
              <TabPane tab={<Icon type="area-chart" />最近一年} key="3">
                <LineCahrt
                  idName={yearName}
                  data={yearData}
                />
              </TabPane>
            </Tabs>
          </QueueAnim>
        </OverPack>

    );
  }
}

export default SecondPage;
<commit_msg>chore(SecondPage.js): 规范命名和导入<commit_after>import style from './style.css';

import classnames from 'classnames';
import React, { Component, PropTypes } from 'react';
import { Tabs, Icon } from 'antd';
import QueueAnim from 'rc-queue-anim';
import TweenOne from 'rc-tween-one';
import OverPack from 'rc-scroll-anim/lib/ScrollOverPack';

import LineCahrt from './components/LineCahrt';
import { formatNumberRgx } from 'utils/commons';

const TabPane = Tabs.TabPane;

class SecondPage extends Component {
  static propTypes = {
    style: PropTypes.string,
    className: PropTypes.string,
    id: PropTypes.string,
  };

  static defaultProps = {
    className: '',
  };

  constructor(props, context) {
    super(props, context);
    this.state = {};
  }

  /* eslint-disable */
  render() {
    const { className } = this.props;
    const submitCount = 2216008;
    const [dayIdName, monthIdName, yearIdName] = ['dayLineChart', 'monthLineChart', 'yearLineChart'];
    const dayData = {
      time: ['00:00', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00', '07:00', '08:00', '09:00', '10:00', '11:00',
             '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00'],
      count: [150, 100, 200, 350, 200, 300, 100, 150, 100, 200, 350, 200, 300, 100, 150, 100, 200, 350, 200, 300, 100, 200, 300, 200],
    };
    const monthData = {
      time: ['2016-10-01', '2016-10-02', '2016-10-03', '2016-10-04', '2016-10-05', '2016-10-06', '2016-10-07', '2016-10-08', '2016-10-09', '2016-10-10',
        '2016-10-11', '2016-10-12', '2016-10-13', '2016-10-14', '2016-10-15', '2016-10-16', '2016-10-17', '2016-10-18', '2016-10-19', '2016-10-20',
        '2016-10-21', '2016-10-22', '2016-10-23', '2016-10-24', '2016-10-25', '2016-10-26', '2016-10-27', '2016-10-28', '2016-10-29', '2016-10-30', '2016-10-31'],
      count: [1500, 1000, 2000, 3500, 2000, 3000, 1000, 1500, 1000, 2000, 3500, 2000, 3000, 1000, 1500, 1000, 2000, 3500, 2000, 3000, 1000, 4000, 3000, 3000, 1000, 2000, 3500, 2000, 3000, 1000, 1500],
    };
    const yearData = {
      time: ['2016-01月', '2016-02月', '2016-03月', '2016-04月', '2016-05月', '2016-06月', '2016-07月', '2016-08月', '2016-09月', '2016-10月', '2016-11月', '2016-12月'],
      count: [15000, 10000, 20000, 35000, 20000, 30000, 10000, 15000, 10000, 20000, 35000, 20000],
    };

    return (

        <OverPack
          className={`content-template ${this.props.className}`}
          hideProps={{ img: { reverse: true } }}
          location={this.props.id}
          className={style.content}
        >
          <TweenOne
            key="img"
            animation={{ x: '-=30', opacity: 0, type: 'from' }}
            className={`${this.props.className}-img`}
          >

              提交总数
              {formatNumberRgx(submitCount)}

          </TweenOne>
          <QueueAnim
            className={`${this.props.className}-text`}
            key="text"
            leaveReverse
            ease={['easeOutCubic', 'easeInCubic']}
            className={style.echart}
          >
            <Tabs key="tabs" tabPosition="left">
              <TabPane tab={<Icon type="dot-chart" />最近一天} key="1">
                <LineCahrt
                  idName={dayIdName}
                  data={dayData}
              />
              </TabPane>
              <TabPane tab={<Icon type="bar-chart" />最近一月} key="2">
                <LineCahrt
                  idName={monthIdName}
                  data={monthData}
                />
              </TabPane>
              <TabPane tab={<Icon type="area-chart" />最近一年} key="3">
                <LineCahrt
                  idName={yearIdName}
                  data={yearData}
                />
              </TabPane>
            </Tabs>
          </QueueAnim>
        </OverPack>

    );
  }
}

export default SecondPage;
<|endoftext|>


<commit_before>/*!
 * Lightbox v2.9.0
 * by Lokesh Dhakar
 *
 * More info:
 * http://lokeshdhakar.com/projects/lightbox2/
 *
 * Copyright 2007, 2015 Lokesh Dhakar
 * Released under the MIT license
 * https://github.com/lokesh/lightbox2/blob/master/LICENSE
 *
 * @preserve
 */

// Uses Node, AMD or browser globals to create a module.
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node. Does not work with strict CommonJS, but
        // only CommonJS-like environments that support module.exports,
        // like Node.
        module.exports = factory(require('jquery'));
    } else {
        // Browser globals (root is window)
        root.lightbox = factory(root.jQuery);
    }
}(this, function ($) {

  function Lightbox(options) {
    this.album = [];
    this.currentImageIndex = void 0;
    this.init();

    // options
    this.options = $.extend({}, this.constructor.defaults);
    this.option(options);
  }

  // Descriptions of all options available on the demo site:
  // http://lokeshdhakar.com/projects/lightbox2/index.html#options
  Lightbox.defaults = {
    albumLabel: 'Image %1 of %2',
    alwaysShowNavOnTouchDevices: false,
    fadeDuration: 600,
    fitImagesInViewport: true,
    imageFadeDuration: 600,
    // maxWidth: 800,
    // maxHeight: 600,
    positionFromTop: 50,
    resizeDuration: 700,
    showImageNumberLabel: true,
    wrapAround: false,
    disableScrolling: false,
    /*
    Sanitize Title
    If the caption data is trusted, for example you are hardcoding it in, then leave this to false.
    This will free you to add html tags, such as links, in the caption.

    If the caption data is user submitted or from some other untrusted source, then set this to true
    to prevent xss and other injection attacks.
     */
    sanitizeTitle: false
  };

  Lightbox.prototype.option = function(options) {
    $.extend(this.options, options);
  };

  Lightbox.prototype.imageCountLabel = function(currentImageNum, totalImages) {
    return this.options.albumLabel.replace(/%1/g, currentImageNum).replace(/%2/g, totalImages);
  };

  Lightbox.prototype.init = function() {
    var self = this;
    // Both enable and build methods require the body tag to be in the DOM.
    $(document).ready(function() {
      self.enable();
      self.build();
    });
  };

  // Loop through anchors and areamaps looking for either data-lightbox attributes or rel attributes
  // that contain 'lightbox'. When these are clicked, start lightbox.
  Lightbox.prototype.enable = function() {
    var self = this;
    $('body').on('click', 'a[rel^=lightbox], area[rel^=lightbox], a[data-lightbox], area[data-lightbox]', function(event) {
      self.start($(event.currentTarget));
      return false;
    });
  };

  // Build html for the lightbox and the overlay.
  // Attach event handlers to the new DOM elements. click click click
  Lightbox.prototype.build = function() {
    var self = this;
    $('

').appendTo($('body'));

    // Cache jQuery objects
    this.$lightbox       = $('#lightbox');
    this.$overlay        = $('#lightboxOverlay');
    this.$outerContainer = this.$lightbox.find('.lb-outerContainer');
    this.$container      = this.$lightbox.find('.lb-container');
    this.$image          = this.$lightbox.find('.lb-image');
    this.$nav            = this.$lightbox.find('.lb-nav');

    // Store css values for future lookup
    this.containerPadding = {
      top: parseInt(this.$container.css('padding-top'), 10),
      right: parseInt(this.$container.css('padding-right'), 10),
      bottom: parseInt(this.$container.css('padding-bottom'), 10),
      left: parseInt(this.$container.css('padding-left'), 10)
    };

    this.imageBorderWidth = {
      top: parseInt(this.$image.css('border-top-width'), 10),
      right: parseInt(this.$image.css('border-right-width'), 10),
      bottom: parseInt(this.$image.css('border-bottom-width'), 10),
      left: parseInt(this.$image.css('border-left-width'), 10)
    };

    // Attach event handlers to the newly minted DOM elements
    this.$overlay.hide().on('click', function() {
      self.end();
      return false;
    });

    this.$lightbox.hide().on('click', function(event) {
      if ($(event.target).attr('id') === 'lightbox') {
        self.end();
      }
      return false;
    });

    this.$outerContainer.on('click', function(event) {
      if ($(event.target).attr('id') === 'lightbox') {
        self.end();
      }
      return false;
    });

    this.$lightbox.find('.lb-prev').on('click', function() {
      if (self.currentImageIndex === 0) {
        self.changeImage(self.album.length - 1);
      } else {
        self.changeImage(self.currentImageIndex - 1);
      }
      return false;
    });

    this.$lightbox.find('.lb-next').on('click', function() {
      if (self.currentImageIndex === self.album.length - 1) {
        self.changeImage(0);
      } else {
        self.changeImage(self.currentImageIndex + 1);
      }
      return false;
    });

    /*
      Show context menu for image on right-click

      There is a div containing the navigation that spans the entire image and lives above of it. If
      you right-click, you are right clicking this div and not the image. This prevents users from
      saving the image or using other context menu actions with the image.

      To fix this, when we detect the right mouse button is pressed down, but not yet clicked, we
      set pointer-events to none on the nav div. This is so that the upcoming right-click event on
      the next mouseup will bubble down to the image. Once the right-click/contextmenu event occurs
      we set the pointer events back to auto for the nav div so it can capture hover and left-click
      events as usual.
     */
    this.$nav.on('mousedown', function(event) {
      if (event.which === 3) {
        self.$nav.css('pointer-events', 'none');

        self.$lightbox.one('contextmenu', function() {
          setTimeout(function() {
              this.$nav.css('pointer-events', 'auto');
          }.bind(self), 0);
        });
      }
    });

    this.$lightbox.find('.lb-loader, .lb-close').on('click', function() {
      self.end();
      return false;
    });
  };

  // Show overlay and lightbox. If the image is part of a set, add siblings to album array.
  Lightbox.prototype.start = function($link) {
    var self    = this;
    var $window = $(window);

    $window.on('resize', $.proxy(this.sizeOverlay, this));

    $('select, object, embed').css({
      visibility: 'hidden'
    });

    this.sizeOverlay();

    this.album = [];
    var imageNumber = 0;

    function addToAlbum($link) {
      self.album.push({
        link: $link.attr('href'),
        title: $link.attr('data-title') || $link.attr('title')
      });
    }

    // Support both data-lightbox attribute and rel attribute implementations
    var dataLightboxValue = $link.attr('data-lightbox');
    var $links;

    if (dataLightboxValue) {
      $links = $($link.prop('tagName') + '[data-lightbox="' + dataLightboxValue + '"]');
      for (var i = 0; i < $links.length; i = ++i) {
        addToAlbum($($links[i]));
        if ($links[i] === $link[0]) {
          imageNumber = i;
        }
      }
    } else {
      if ($link.attr('rel') === 'lightbox') {
        // If image is not part of a set
        addToAlbum($link);
      } else {
        // If image is part of a set
        $links = $($link.prop('tagName') + '[rel="' + $link.attr('rel') + '"]');
        for (var j = 0; j < $links.length; j = ++j) {
          addToAlbum($($links[j]));
          if ($links[j] === $link[0]) {
            imageNumber = j;
          }
        }
      }
    }

    // Position Lightbox
    var top  = $window.scrollTop() + this.options.positionFromTop;
    var left = $window.scrollLeft();
    this.$lightbox.css({
      top: top + 'px',
      left: left + 'px'
    }).fadeIn(this.options.fadeDuration);

    // Disable scrolling of the page while open
    if (this.options.disableScrolling) {
      $('body').addClass('lb-disable-scrolling');
    }

    this.changeImage(imageNumber);
  };

  // Hide most UI elements in preparation for the animated resizing of the lightbox.
  Lightbox.prototype.changeImage = function(imageNumber) {
    var self = this;

    this.disableKeyboardNav();
    var $image = this.$lightbox.find('.lb-image');

    this.$overlay.fadeIn(this.options.fadeDuration);

    $('.lb-loader').fadeIn('slow');
    this.$lightbox.find('.lb-image, .lb-nav, .lb-prev, .lb-next, .lb-dataContainer, .lb-numbers, .lb-caption').hide();

    this.$outerContainer.addClass('animating');

    // When image to show is preloaded, we send the width and height to sizeContainer()
    var preloader = new Image();
    preloader.onload = function() {
      var $preloader;
      var imageHeight;
      var imageWidth;
      var maxImageHeight;
      var maxImageWidth;
      var windowHeight;
      var windowWidth;

      $image.attr('src', self.album[imageNumber].link);

      $preloader = $(preloader);

      $image.width(preloader.width);
      $image.height(preloader.height);

      if (self.options.fitImagesInViewport) {
        // Fit image inside the viewport.
        // Take into account the border around the image and an additional 10px gutter on each side.

        windowWidth    = $(window).width();
        windowHeight   = $(window).height();
        maxImageWidth  = windowWidth - self.containerPadding.left - self.containerPadding.right - self.imageBorderWidth.left - self.imageBorderWidth.right - 20;
        maxImageHeight = windowHeight - self.containerPadding.top - self.containerPadding.bottom - self.imageBorderWidth.top - self.imageBorderWidth.bottom - 120;

        // Check if image size is larger then maxWidth|maxHeight in settings
        if (self.options.maxWidth && self.options.maxWidth < maxImageWidth) {
          maxImageWidth = self.options.maxWidth;
        }
        if (self.options.maxHeight && self.options.maxHeight < maxImageWidth) {
          maxImageHeight = self.options.maxHeight;
        }

        // Is the current image's width or height is greater than the maxImageWidth or maxImageHeight
        // option than we need to size down while maintaining the aspect ratio.
        if ((preloader.width > maxImageWidth) || (preloader.height > maxImageHeight)) {
          if ((preloader.width / maxImageWidth) > (preloader.height / maxImageHeight)) {
            imageWidth  = maxImageWidth;
            imageHeight = parseInt(preloader.height / (preloader.width / imageWidth), 10);
            $image.width(imageWidth);
            $image.height(imageHeight);
          } else {
            imageHeight = maxImageHeight;
            imageWidth = parseInt(preloader.width / (preloader.height / imageHeight), 10);
            $image.width(imageWidth);
            $image.height(imageHeight);
          }
        }
      }
      self.sizeContainer($image.width(), $image.height());
    };

    preloader.src          = this.album[imageNumber].link;
    this.currentImageIndex = imageNumber;
  };

  // Stretch overlay to fit the viewport
  Lightbox.prototype.sizeOverlay = function() {
    this.$overlay
      .width($(document).width())
      .height($(document).height());
  };

  // Animate the size of the lightbox to fit the image we are showing
  Lightbox.prototype.sizeContainer = function(imageWidth, imageHeight) {
    var self = this;

    var oldWidth  = this.$outerContainer.outerWidth();
    var oldHeight = this.$outerContainer.outerHeight();
    var newWidth  = imageWidth + this.containerPadding.left + this.containerPadding.right + this.imageBorderWidth.left + this.imageBorderWidth.right;
    var newHeight = imageHeight + this.containerPadding.top + this.containerPadding.bottom + this.imageBorderWidth.top + this.imageBorderWidth.bottom;

    function postResize() {
      self.$lightbox.find('.lb-dataContainer').width(newWidth);
      self.$lightbox.find('.lb-prevLink').height(newHeight);
      self.$lightbox.find('.lb-nextLink').height(newHeight);
      self.showImage();
    }

    if (oldWidth !== newWidth || oldHeight !== newHeight) {
      this.$outerContainer.animate({
        width: newWidth,
        height: newHeight
      }, this.options.resizeDuration, 'swing', function() {
        postResize();
      });
    } else {
      postResize();
    }
  };

  // Display the image and its details and begin preload neighboring images.
  Lightbox.prototype.showImage = function() {
    this.$lightbox.find('.lb-loader').stop(true).hide();
    this.$lightbox.find('.lb-image').fadeIn(this.options.imageFadeDuration);

    this.updateNav();
    this.updateDetails();
    this.preloadNeighboringImages();
    this.enableKeyboardNav();
  };

  // Display previous and next navigation if appropriate.
  Lightbox.prototype.updateNav = function() {
    // Check to see if the browser supports touch events. If so, we take the conservative approach
    // and assume that mouse hover events are not supported and always show prev/next navigation
    // arrows in image sets.
    var alwaysShowNav = false;
    try {
      document.createEvent('TouchEvent');
      alwaysShowNav = (this.options.alwaysShowNavOnTouchDevices) ? true : false;
    } catch (e) {}

    this.$lightbox.find('.lb-nav').show();

    if (this.album.length > 1) {
      if (this.options.wrapAround) {
        if (alwaysShowNav) {
          this.$lightbox.find('.lb-prev, .lb-next').css('opacity', '1');
        }
        this.$lightbox.find('.lb-prev, .lb-next').show();
      } else {
        if (this.currentImageIndex > 0) {
          this.$lightbox.find('.lb-prev').show();
          if (alwaysShowNav) {
            this.$lightbox.find('.lb-prev').css('opacity', '1');
          }
        }
        if (this.currentImageIndex < this.album.length - 1) {
          this.$lightbox.find('.lb-next').show();
          if (alwaysShowNav) {
            this.$lightbox.find('.lb-next').css('opacity', '1');
          }
        }
      }
    }
  };

  // Display caption, image number, and closing button.
  Lightbox.prototype.updateDetails = function() {
    var self = this;

    // Enable anchor clicks in the injected caption html.
    // Thanks Nate Wright for the fix. @https://github.com/NateWr
    if (typeof this.album[this.currentImageIndex].title !== 'undefined' &&
      this.album[this.currentImageIndex].title !== '') {
      var $caption = this.$lightbox.find('.lb-caption');
      if (this.options.sanitizeTitle) {
        $caption.text(this.album[this.currentImageIndex].title);
      } else {
        $caption.html(this.album[this.currentImageIndex].title);
      }
      $caption.fadeIn('fast')
        .find('a').on('click', function(event) {
          if ($(this).attr('target') !== undefined) {
            window.open($(this).attr('href'), $(this).attr('target'));
          } else {
            location.href = $(this).attr('href');
          }
        });
    }

    if (this.album.length > 1 && this.options.showImageNumberLabel) {
      var labelText = this.imageCountLabel(this.currentImageIndex + 1, this.album.length);
      this.$lightbox.find('.lb-number').text(labelText).fadeIn('fast');
    } else {
      this.$lightbox.find('.lb-number').hide();
    }

    this.$outerContainer.removeClass('animating');

    this.$lightbox.find('.lb-dataContainer').fadeIn(this.options.resizeDuration, function() {
      return self.sizeOverlay();
    });
  };

  // Preload previous and next images in set.
  Lightbox.prototype.preloadNeighboringImages = function() {
    if (this.album.length > this.currentImageIndex + 1) {
      var preloadNext = new Image();
      preloadNext.src = this.album[this.currentImageIndex + 1].link;
    }
    if (this.currentImageIndex > 0) {
      var preloadPrev = new Image();
      preloadPrev.src = this.album[this.currentImageIndex - 1].link;
    }
  };

  Lightbox.prototype.enableKeyboardNav = function() {
    $(document).on('keyup.keyboard', $.proxy(this.keyboardAction, this));
  };

  Lightbox.prototype.disableKeyboardNav = function() {
    $(document).off('.keyboard');
  };

  Lightbox.prototype.keyboardAction = function(event) {
    var KEYCODE_ESC        = 27;
    var KEYCODE_LEFTARROW  = 37;
    var KEYCODE_RIGHTARROW = 39;

    var keycode = event.keyCode;
    var key     = String.fromCharCode(keycode).toLowerCase();
    if (keycode === KEYCODE_ESC || key.match(/x|o|c/)) {
      this.end();
    } else if (key === 'p' || keycode === KEYCODE_LEFTARROW) {
      if (this.currentImageIndex !== 0) {
        this.changeImage(this.currentImageIndex - 1);
      } else if (this.options.wrapAround && this.album.length > 1) {
        this.changeImage(this.album.length - 1);
      }
    } else if (key === 'n' || keycode === KEYCODE_RIGHTARROW) {
      if (this.currentImageIndex !== this.album.length - 1) {
        this.changeImage(this.currentImageIndex + 1);
      } else if (this.options.wrapAround && this.album.length > 1) {
        this.changeImage(0);
      }
    }
  };

  // Closing time. :-(
  Lightbox.prototype.end = function() {
    this.disableKeyboardNav();
    $(window).off('resize', this.sizeOverlay);
    this.$lightbox.fadeOut(this.options.fadeDuration);
    this.$overlay.fadeOut(this.options.fadeDuration);
    $('select, object, embed').css({
      visibility: 'visible'
    });
    if (this.options.disableScrolling) {
      $('body').removeClass('lb-disable-scrolling');
    }
  };

  return new Lightbox();
}));
<commit_msg>Remove the now ignored directory "lightbox"<commit_after><|endoftext|>


<commit_before>#!/usr/bin/env node

var filewalker = require('filewalker');
var browserify = require('browserify')();
var rimraf = require('rimraf')
var UglifyJS = require("uglify-js");
var path = require('path');
var mkdirp = require('mkdirp');
var exec = require('child_process').exec;
var fs = require('fs');

var typescriptFiles = [];
var compiledFiles = [];
var sourceDirectory = './server';
var distDirectory = './dist';
var distFile = 'deploy.js';
var mainFile = 'main.js';

filewalker(sourceDirectory)
    .on('file', function (filePath, s) {
        if (path.extname(filePath) === '.ts') {
            typescriptFiles.push(filePath);
        }
    })
    .on('done', function () {
        servicenowify.compileAll(typescriptFiles, function (err) {
            servicenowify.browserifyAll(sourceDirectory + '/' + mainFile, function (err, code) {
                if (!err) {
                    servicenowify.fixBlockScoping(code, function (err, fixedCode) {
                        servicenowify.uglifyAll(fixedCode, function (err, uglifiedCode) {
                            mkdirp(distDirectory + '/', function (err) {
                                if (err)
                                    console.error(err)
                                else {
                                    fs.writeFileSync(distDirectory + '/' + distFile, uglifiedCode, 'UTF8');

                                    for (var key in compiledFiles) {
                                        var filesToClean = compiledFiles.length;
                                        servicenowify.clean(sourceDirectory + '/' + compiledFiles[key].substring(0, compiledFiles[key].length - 2) + 'js', function (err) {
                                            filesToClean--;
                                            if (!filesToClean) {
                                                console.log('Build complete!')
                                            }
                                        });
                                    }
                                }
                            });

                        });
                    });
                } else {
                    console.log('Unable to browserify source directory')
                }
            });
        });
    })
    .walk();

// Build

servicenowify = {
    /*
     Takes an Array of files and attempts to compile them. Requires tsc compiler to be installed at OS level. Fires callback on completion.
     */
    compileAll: function (files, callback) {
        for (var key in files) {
            var filesToCompile = files.length;
            var compilationError = false;
            var command = "tsc " + sourceDirectory + '/' + files[key] + " --module commonjs";
            (function (filename) {
                exec(command, function (error) {
                    if (error !== null) {
                        console.error('Unable to compile file: ' + filename + ', err: ' + error);
                        compilationError = true;
                    } else {
                        compiledFiles.push(filename);
                    }

                    filesToCompile--;
                    if (!filesToCompile) {
                        callback(compilationError);
                    }
                });
            })(files[key])
        }
    },
    /*
     Takes an file and browserify's it, standard stuff from that package. Produces a single file including all dependencies at the target location.
     */
    browserifyAll: function (file, callback) {
        browserify.add(file);
        browserify.bundle(function (error, code) {
            callback(error, code);
        });
    },
    /*
     Takes an file and uglify's it, standard stuff from that package. Produces a single file at the target location.
     */
    uglifyAll: function (fileContents, callback) {
        var result = UglifyJS.minify(fileContents, {fromString: true});
        callback(null, result.code);
    },
    /*
     Fix Block Scoping - ServiceNow has a poor implementation of JavaScript, causing a single error in the Uglified code. We have to fix this by scoping a variable.
     */
    fixBlockScoping: function (code, callback) {
        var fixedCode = '(e = function' + code.toString().substring(11);
        callback(null, fixedCode);
    },
    /*
     Generic cleaning function, uses rimraf to take care of things
     */
    clean: function (file, callback) {
        rimraf(file, callback);
    }
};
<commit_msg>Removing semicolons because fashion..<commit_after>#!/usr/bin/env node

var filewalker = require('filewalker');
var browserify = require('browserify')();
var rimraf = require('rimraf')
var UglifyJS = require("uglify-js");
var path = require('path');
var mkdirp = require('mkdirp');
var exec = require('child_process').exec;
var fs = require('fs');

var typescriptFiles = [];
var compiledFiles = [];
var sourceDirectory = './server';
var distDirectory = './dist';
var distFile = 'deploy.js';
var mainFile = 'main.js';

filewalker(sourceDirectory)
    .on('file', function (filePath, s) {
        if (path.extname(filePath) === '.ts') {
            typescriptFiles.push(filePath)
        }
    })
    .on('done', function () {
        servicenowify.compileAll(typescriptFiles, function (err) {
            servicenowify.browserifyAll(sourceDirectory + '/' + mainFile, function (err, code) {
                if (!err) {
                    servicenowify.fixBlockScoping(code, function (err, fixedCode) {
                        servicenowify.uglifyAll(fixedCode, function (err, uglifiedCode) {
                            mkdirp(distDirectory + '/', function (err) {
                                if (err)
                                    console.error(err)
                                else {
                                    fs.writeFileSync(distDirectory + '/' + distFile, uglifiedCode, 'UTF8')

                                    for (var key in compiledFiles) {
                                        var filesToClean = compiledFiles.length
                                        servicenowify.clean(sourceDirectory + '/' + compiledFiles[key].substring(0, compiledFiles[key].length - 2) + 'js', function (err) {
                                            filesToClean--
                                            if (!filesToClean) {
                                                console.log('Build complete!')
                                            }
                                        })
                                    }
                                }
                            })
                        })
                    })
                } else {
                    console.log('Unable to browserify source directory')
                }
            })
        })
    })
    .walk()

// Build

servicenowify = {
    /*
     Takes an Array of files and attempts to compile them. Requires tsc compiler to be installed at OS level. Fires callback on completion.
     */
    compileAll: function (files, callback) {
        for (var key in files) {
            var filesToCompile = files.length;
            var compilationError = false;
            var command = "tsc " + sourceDirectory + '/' + files[key] + " --module commonjs";
            (function (filename) {
                exec(command, function (error) {
                    if (error !== null) {
                        console.error('Unable to compile file: ' + filename + ', err: ' + error);
                        compilationError = true;
                    } else {
                        compiledFiles.push(filename);
                    }

                    filesToCompile--;
                    if (!filesToCompile) {
                        callback(compilationError);
                    }
                });
            })(files[key])
        }
    },
    /*
     Takes an file and browserify's it, standard stuff from that package. Produces a single file including all dependencies at the target location.
     */
    browserifyAll: function (file, callback) {
        browserify.add(file);
        browserify.bundle(function (error, code) {
            callback(error, code);
        });
    },
    /*
     Takes an file and uglify's it, standard stuff from that package. Produces a single file at the target location.
     */
    uglifyAll: function (fileContents, callback) {
        var result = UglifyJS.minify(fileContents, {fromString: true});
        callback(null, result.code);
    },
    /*
     Fix Block Scoping - ServiceNow has a poor implementation of JavaScript, causing a single error in the Uglified code. We have to fix this by scoping a variable.
     */
    fixBlockScoping: function (code, callback) {
        var fixedCode = '(e = function' + code.toString().substring(11);
        callback(null, fixedCode);
    },
    /*
     Generic cleaning function, uses rimraf to take care of things
     */
    clean: function (file, callback) {
        rimraf(file, callback);
    }
};
<|endoftext|>


<commit_before>/*
Script: MooEditable.js
	MooEditable class for contentEditable-capable browsers

License:
	MIT-style license.

Author:
	Lim Chee Aun <cheeaun@gmail.com>

Contributor(s):
	Marc Fowler <marc.fowler@defraction.net>

Credits:
	- Most code is based on Stefan's work "Safari Supports Content Editing!" <http://www.xs4all.nl/~hhijdra/stefan/ContentEditable.html>
	- Main reference from Peter-Paul Koch's "execCommand compatibility" research <http://www.quirksmode.org/dom/execCommand.html>
	- Some ideas inspired by TinyMCE <http://tinymce.moxiecode.com/>
	- Some functions inspired by Inviz's "Most tiny wysiwyg you ever seen" <http://forum.mootools.net/viewtopic.php?id=746>, <http://forum.mootools.net/viewtopic.php?id=5740>
	- Some regex from Cameron Adams's widgEditor <http://themaninblue.com/experiment/widgEditor/>
	- IE support referring Robert Bredlau's "Rich Text Editing" part 1 and 2 articles <http://www.rbredlau.com/drupal/node/6>
	- Tango icons from the Tango Desktop Project <http://tango.freedesktop.org/>
	- Additional tango icons from Tango OpenOffice set by Jimmacs <http://www.gnome-look.org/content/show.php/Tango+OpenOffice?content=54799>
*/

var MooEditable = new Class({

//	Implements: [Events, Options],

	options:{
		toolbar: true,
		buttons: 'bold,italic,strikethrough,separator,insertunorderedlist,insertorderedlist,indent,outdent,separator,undo,redo,separator,createlink,unlink,toggleview',
		text: {
			'bold': 'Bold',
			'italic': 'Italic',
			'strikethrough': 'Strikethrough',
			'insertunorderedlist': 'Unordered List',
			'insertorderedlist': 'Ordered List',
			'indent': 'Indent',
			'outdent': 'Outdent',
			'undo': 'Undo',
			'redo': 'Redo',
			'createlink': 'Add Hyperlink',
			'unlink': 'Remove Hyperlink',
			'separator': '|',
			'toggleview': 'Toggle View'
		}
	},

	initialize: function(elements,options){
		this.setOptions(options);
		$$(elements).each(this.build, this);
	},

	build: function(el){
		var id = el.className ? el.className : el.id ? el.id : 'mooeditable';
		var elStyles = el.getStyles('width','height','padding','margin','border','border-width');
		var sides = ['top','right','bottom','left'];
		for (var i = 0; i < sides.length; i++) {
			elStyles['padding-' + sides[i]] = elStyles['padding'].split(' ')[i];
			elStyles['border-' + sides[i] + '-width'] = elStyles['border-width'].split(' ')[i];
		}

		// Build the container
		var container = new Element('div',{
			'class': id + '-container',
			'styles': {
				'width': elStyles['width'].toInt() + elStyles['padding-right'].toInt() + elStyles['padding-left'].toInt() + elStyles['border-right-width'].toInt() + elStyles['border-left-width'].toInt(),
				'margin': elStyles['margin']
			}
		});

		// Put textarea inside container
		container.inject(el, 'before');
		el.setStyles({
			'margin': 0,
			'display': 'none',
			'resize': 'none', // disable resizable textareas in Safari
			'outline': 'none' // disable focus ring in Safari
		});
//		if(Browser.Engine.trident){
		if(window.ie){
			// Fix IE bug, refer "IE/Win Inherited Margins on Form Elements" <http://positioniseverything.net/explorer/inherited_margin.html>
			var span = new Element('span');
			span.inject(container, 'bottom');
			el.inject(span, 'bottom');
		}
		else el.inject(container, 'bottom');

		// Build the iframe
		var iframe = new Element('iframe',{
			'class': id + '-iframe',
			'styles':{
				'width': elStyles['width'].toInt() + elStyles['padding-right'].toInt() + elStyles['padding-left'].toInt(),
				'height': elStyles['height'].toInt() + elStyles['padding-top'].toInt() + elStyles['padding-bottom'].toInt(),
				'border': elStyles['border']
			}
		});
		iframe.inject(container, 'top');

		// Build the content of iframe
		var doc = iframe.contentWindow.document;
		doc.open();
		doc.write('');
		doc.write('');
		doc.write('
'+el.value+'
');
		doc.write('');
		doc.close();

		// Turn on Design Mode
		doc.designMode = 'on';

		// Update the event for textarea's corresponding labels
		if(el.id) $$('label[for="'+el.id+'"]').addEvent('click', function(e){
			if(iframe.getStyle('display') != 'none'){
				e = new Event(e).stop();
				iframe.contentWindow.focus();
			}
		});

		// Ensures textarea content is always updated
		var events = ['mousedown', 'mouseup', 'mouseout', 'mouseover', 'click', 'keydown', 'keyup', 'keypress'];
		for(var i = 0; i < events.length; i++){
			if($type(document.addEventListener) == 'function'){
				doc.addEventListener(events[i], function(oEvent){
					el.value = this.cleanup(doc.getElementById('editable').innerHTML);
				}.bind(this), false);
			}
			else{
				iframe.contentWindow.document.attachEvent('on' + events[i], function(){
					el.value = this.cleanup(iframe.contentWindow.document.getElementById('editable').innerHTML);
				}.bind(this));
			}
		}

		if(this.options.toolbar) this.buildToolbar(el,iframe,id);
	},

	buildToolbar: function(el,iframe,id){
		var toolbar = new Element('div',{
			'class': id + '-toolbar'
		});
		toolbar.inject(iframe, 'before');

		var toolbarButtons = this.options.buttons.split(',');

		for (var i=0 ; i<toolbarButtons.length ; i++){
			var command = toolbarButtons[i];
			var b;
			if (command == 'separator'){
				b = new Element('span',{
					'class': 'toolbar-separator'
				});
			}
			else{
				b = new Element('button',{
					'class': command+'-button toolbar-button',
					'title': this.options.text[command]
				});
			}
//			b.set('text', this.options.text[command]);
			b.setText(this.options.text[command]);
			b.inject(toolbar, 'bottom');
		}

		toolbar.getElements('.toolbar-button').each(function(item){
			item.addEvent('click', function(e){
				e = new Event(e).stop();
				if (!item.hasClass('disabled')){
					var command = item.className.split(' ')[0].split('-')[0];
					this.action(command, el, iframe, toolbar);
				}
				iframe.contentWindow.focus();
			}.bind(this));

			// remove focus rings off the buttons in Firefox
			item.addEvent('mousedown', function(e){ new Event(e).stop(); });

			// add hover effect for IE6
//			if(Browser.Engine.trident4) item.addEvents({
			if(window.ie6) item.addEvents({
				'mouseenter': function(e){ this.addClass('hover'); },
				'mouseleave': function(e){ this.removeClass('hover'); }
			});
		}.bind(this));
	},

	action: function(command, el, iframe, toolbar){
		var win = iframe.contentWindow;
		var doc = win.document;
		var selection = '';
		switch(command){
			case 'createlink':
				if (doc.selection){
					selection = doc.selection.createRange().text;
					if (selection == ''){
						alert("Please select the text you wish to hyperlink.");
						break;
					}
				}
				else{
					selection = win.getSelection();
					if (selection == ''){
						alert("Please select the text you wish to hyperlink.");
						break;
					}
				}
				var url = prompt('Enter URL','http://');
				if (url) this.execute(el, doc, command, false, url.trim());
				break;
			case 'toggleview':
				this.toggle(el,iframe,toolbar);
				break;
			default:
//				if (!Browser.Engine.trident) this.execute(el, doc, 'styleWithCSS', false, this.options.styleWithCSS);
				if (!window.ie) this.execute(el, doc, 'styleWithCSS', false, false);
				this.execute(el, doc, command, false, '');
		}
	},

	execute: function(el, doc, command, param1, param2){
	    if (!this.busy){
			this.busy = true;
			doc.execCommand(command, param1, param2);
			el.value = this.cleanup(doc.getElementById('editable').innerHTML);
			this.busy = false;
		}
		return false;
	},

	toggle: function(el,iframe,toolbar) {
		if (iframe.getStyle('display') == 'none') {
			iframe.setStyle('display', '');
			var doc = iframe.contentWindow.document;
			(function(){
			doc.getElementById('editable').innerHTML = el.value;
			}).delay(1); // dealing with Adobe AIR's webkit bug
			toolbar.getElements('.toolbar-button').each(function(item){
				item.removeClass('disabled');
//				item.set('opacity', 1);
				item.setOpacity(1);
			});
			el.setStyle('display', 'none');
		} else {
			el.setStyle('display', '');
			var doc = iframe.contentWindow.document;
			el.value = this.cleanup(doc.getElementById('editable').innerHTML);
			toolbar.getElements('.toolbar-button').each(function(item){
				if (!item.hasClass('toggleview-button')) {
					item.addClass('disabled');
//					item.set('opacity', 0.4);
					item.setOpacity(0.4);
				}
			});
			iframe.setStyle('display', 'none');
		}
	},

	cleanup: function(source){
		// Webkit cleanup
		source = source.replace(/
/gi, "
");
		source = source.replace(/(.*)<\/span>/gi, '$1');
		source = source.replace(/ class="Apple-style-span"/gi, '');
		source = source.replace(//gi, '');

		// Remove padded paragraphs
		source = source.replace(/
\s*
\s*<\/p>/gi, '
\u00a0
');
		source = source.replace(/
( |\s)*<\/p>/gi, '
\u00a0
');
		source = source.replace(/\s*
\s*<\/p>/gi, '
');

		// Replace improper BRs
		source = source.replace(/
/gi, "
");

		// Remove trailing BRs
		source = source.replace(/
$/gi, '');

		// Remove useless BRs
		source = source.replace(/>
/gi, '>');

		// Remove BRs right before the end of blocks
		source = source.replace(/
\s*<\/(h1|h2|h3|h4|h5|h6|li|p)/gi, '</$1');

		// Remove empty tags
		source = source.replace(/(<[^\/]>|<[^\/][^>]*[^\/]>)\s*<\/[^>]*>/gi, '');

		// Semantic conversion
		source = source.replace(/(.*)<\/span>/gi, '$1');
		source = source.replace(/(.*)<\/span>/gi, '$1');
		source = source.replace(/)/g, "<strong$1");
		source = source.replace(/<\/b(\s+|>)/g, "</strong$1");
		source = source.replace(/)/g, "<em$1");
		source = source.replace(/<\/i(\s+|>)/g, "</em$1");

		// Replace uppercase element names with lowercase
		source = source.replace(/<[^> ]*/g, function(match){return match.toLowerCase();});

		// Replace uppercase attribute names with lowercase
		source = source.replace(/<[^>]*>/g, function(match){
			match = match.replace(/ [^=]+=/g, function(match2){return match2.toLowerCase();});
			return match;
		});

		// Put quotes around unquoted attributes
		source = source.replace(/<[^>]*>/g, function(match){
			match = match.replace(/( [^=]+=)([^"][^ >]*)/g, "$1\"$2\"");
			return match;
		});

		// Final trim
		source = source.trim();

		return source;
	}
});

MooEditable.implement(new Options, new Events);
<commit_msg>Set the property for $Id keyword. Added proper doc-blocks to see if Google Code will pick up on the changes. If this fails, my experimentation might continue.<commit_after>/*
 *  $Id$
 *
 * The MIT License
 *
 * Copyright (c) 2007 Lim Chee Aun <cheeaun@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/**
 * MooEditable.js
 * MooEditable class for contentEditable-capable browsers
 *
 * @package     MooEditable
 * @subpackage  Core
 * @author      Lim Chee Aun <cheeaun@gmail.com>
 * @author      Marc Fowler <marc.fowler@defraction.net>
 * @license     http://www.opensource.org/licenses/mit-license.php MIT License
 * @link        http://code.google.com/p/mooeditable/
 * @since       1.0
 * @version     $Revision: 8 $
 * @credits     Most code is based on Stefan's work "Safari Supports Content Editing!"
 *                  <http://www.xs4all.nl/~hhijdra/stefan/ContentEditable.html>
 *              Main reference from Peter-Paul Koch's "execCommand compatibility" research
 *                  <http://www.quirksmode.org/dom/execCommand.html>
 *              Some ideas inspired by TinyMCE <http://tinymce.moxiecode.com/>
 *              Some functions inspired by Inviz's "Most tiny wysiwyg you ever seen"
 *                  <http://forum.mootools.net/viewtopic.php?id=746>,
 *                  <http://forum.mootools.net/viewtopic.php?id=5740>
 *              Some regex from Cameron Adams's widgEditor
 *                  <http://themaninblue.com/experiment/widgEditor/>
 *              IE support referring Robert Bredlau's "Rich Text Editing" part 1 and 2 articles
 *                  <http://www.rbredlau.com/drupal/node/6>
 *              Tango icons from the Tango Desktop Project
 *                  <http://tango.freedesktop.org/>
 *              Additional tango icons from Tango OpenOffice set by Jimmacs
 *                  <http://www.gnome-look.org/content/show.php/Tango+OpenOffice?content=54799>
 */

var MooEditable = new Class({

//	Implements: [Events, Options],

	options:{
		toolbar: true,
		buttons: 'bold,italic,strikethrough,separator,insertunorderedlist,insertorderedlist,indent,outdent,separator,undo,redo,separator,createlink,unlink,toggleview',
		text: {
			'bold': 'Bold',
			'italic': 'Italic',
			'strikethrough': 'Strikethrough',
			'insertunorderedlist': 'Unordered List',
			'insertorderedlist': 'Ordered List',
			'indent': 'Indent',
			'outdent': 'Outdent',
			'undo': 'Undo',
			'redo': 'Redo',
			'createlink': 'Add Hyperlink',
			'unlink': 'Remove Hyperlink',
			'separator': '|',
			'toggleview': 'Toggle View'
		}
	},

	initialize: function(elements,options){
		this.setOptions(options);
		$$(elements).each(this.build, this);
	},

	build: function(el){
		var id = el.className ? el.className : el.id ? el.id : 'mooeditable';
		var elStyles = el.getStyles('width','height','padding','margin','border','border-width');
		var sides = ['top','right','bottom','left'];
		for (var i = 0; i < sides.length; i++) {
			elStyles['padding-' + sides[i]] = elStyles['padding'].split(' ')[i];
			elStyles['border-' + sides[i] + '-width'] = elStyles['border-width'].split(' ')[i];
		}

		// Build the container
		var container = new Element('div',{
			'class': id + '-container',
			'styles': {
				'width': elStyles['width'].toInt() + elStyles['padding-right'].toInt() + elStyles['padding-left'].toInt() + elStyles['border-right-width'].toInt() + elStyles['border-left-width'].toInt(),
				'margin': elStyles['margin']
			}
		});

		// Put textarea inside container
		container.inject(el, 'before');
		el.setStyles({
			'margin': 0,
			'display': 'none',
			'resize': 'none', // disable resizable textareas in Safari
			'outline': 'none' // disable focus ring in Safari
		});
//		if(Browser.Engine.trident){
		if(window.ie){
			// Fix IE bug, refer "IE/Win Inherited Margins on Form Elements" <http://positioniseverything.net/explorer/inherited_margin.html>
			var span = new Element('span');
			span.inject(container, 'bottom');
			el.inject(span, 'bottom');
		}
		else el.inject(container, 'bottom');

		// Build the iframe
		var iframe = new Element('iframe',{
			'class': id + '-iframe',
			'styles':{
				'width': elStyles['width'].toInt() + elStyles['padding-right'].toInt() + elStyles['padding-left'].toInt(),
				'height': elStyles['height'].toInt() + elStyles['padding-top'].toInt() + elStyles['padding-bottom'].toInt(),
				'border': elStyles['border']
			}
		});
		iframe.inject(container, 'top');

		// Build the content of iframe
		var doc = iframe.contentWindow.document;
		doc.open();
		doc.write('');
		doc.write('');
		doc.write('
'+el.value+'
');
		doc.write('');
		doc.close();

		// Turn on Design Mode
		doc.designMode = 'on';

		// Update the event for textarea's corresponding labels
		if(el.id) $$('label[for="'+el.id+'"]').addEvent('click', function(e){
			if(iframe.getStyle('display') != 'none'){
				e = new Event(e).stop();
				iframe.contentWindow.focus();
			}
		});

		// Ensures textarea content is always updated
		var events = ['mousedown', 'mouseup', 'mouseout', 'mouseover', 'click', 'keydown', 'keyup', 'keypress'];
		for(var i = 0; i < events.length; i++){
			if($type(document.addEventListener) == 'function'){
				doc.addEventListener(events[i], function(oEvent){
					el.value = this.cleanup(doc.getElementById('editable').innerHTML);
				}.bind(this), false);
			}
			else{
				iframe.contentWindow.document.attachEvent('on' + events[i], function(){
					el.value = this.cleanup(iframe.contentWindow.document.getElementById('editable').innerHTML);
				}.bind(this));
			}
		}

		if(this.options.toolbar) this.buildToolbar(el,iframe,id);
	},

	buildToolbar: function(el,iframe,id){
		var toolbar = new Element('div',{
			'class': id + '-toolbar'
		});
		toolbar.inject(iframe, 'before');

		var toolbarButtons = this.options.buttons.split(',');

		for (var i=0 ; i<toolbarButtons.length ; i++){
			var command = toolbarButtons[i];
			var b;
			if (command == 'separator'){
				b = new Element('span',{
					'class': 'toolbar-separator'
				});
			}
			else{
				b = new Element('button',{
					'class': command+'-button toolbar-button',
					'title': this.options.text[command]
				});
			}
//			b.set('text', this.options.text[command]);
			b.setText(this.options.text[command]);
			b.inject(toolbar, 'bottom');
		}

		toolbar.getElements('.toolbar-button').each(function(item){
			item.addEvent('click', function(e){
				e = new Event(e).stop();
				if (!item.hasClass('disabled')){
					var command = item.className.split(' ')[0].split('-')[0];
					this.action(command, el, iframe, toolbar);
				}
				iframe.contentWindow.focus();
			}.bind(this));

			// remove focus rings off the buttons in Firefox
			item.addEvent('mousedown', function(e){ new Event(e).stop(); });

			// add hover effect for IE6
//			if(Browser.Engine.trident4) item.addEvents({
			if(window.ie6) item.addEvents({
				'mouseenter': function(e){ this.addClass('hover'); },
				'mouseleave': function(e){ this.removeClass('hover'); }
			});
		}.bind(this));
	},

	action: function(command, el, iframe, toolbar){
		var win = iframe.contentWindow;
		var doc = win.document;
		var selection = '';
		switch(command){
			case 'createlink':
				if (doc.selection){
					selection = doc.selection.createRange().text;
					if (selection == ''){
						alert("Please select the text you wish to hyperlink.");
						break;
					}
				}
				else{
					selection = win.getSelection();
					if (selection == ''){
						alert("Please select the text you wish to hyperlink.");
						break;
					}
				}
				var url = prompt('Enter URL','http://');
				if (url) this.execute(el, doc, command, false, url.trim());
				break;
			case 'toggleview':
				this.toggle(el,iframe,toolbar);
				break;
			default:
//				if (!Browser.Engine.trident) this.execute(el, doc, 'styleWithCSS', false, this.options.styleWithCSS);
				if (!window.ie) this.execute(el, doc, 'styleWithCSS', false, false);
				this.execute(el, doc, command, false, '');
		}
	},

	execute: function(el, doc, command, param1, param2){
	    if (!this.busy){
			this.busy = true;
			doc.execCommand(command, param1, param2);
			el.value = this.cleanup(doc.getElementById('editable').innerHTML);
			this.busy = false;
		}
		return false;
	},

	toggle: function(el,iframe,toolbar) {
		if (iframe.getStyle('display') == 'none') {
			iframe.setStyle('display', '');
			var doc = iframe.contentWindow.document;
			(function(){
			doc.getElementById('editable').innerHTML = el.value;
			}).delay(1); // dealing with Adobe AIR's webkit bug
			toolbar.getElements('.toolbar-button').each(function(item){
				item.removeClass('disabled');
//				item.set('opacity', 1);
				item.setOpacity(1);
			});
			el.setStyle('display', 'none');
		} else {
			el.setStyle('display', '');
			var doc = iframe.contentWindow.document;
			el.value = this.cleanup(doc.getElementById('editable').innerHTML);
			toolbar.getElements('.toolbar-button').each(function(item){
				if (!item.hasClass('toggleview-button')) {
					item.addClass('disabled');
//					item.set('opacity', 0.4);
					item.setOpacity(0.4);
				}
			});
			iframe.setStyle('display', 'none');
		}
	},

	cleanup: function(source){
		// Webkit cleanup
		source = source.replace(/
/gi, "
");
		source = source.replace(/(.*)<\/span>/gi, '$1');
		source = source.replace(/ class="Apple-style-span"/gi, '');
		source = source.replace(//gi, '');

		// Remove padded paragraphs
		source = source.replace(/
\s*
\s*<\/p>/gi, '
\u00a0
');
		source = source.replace(/
( |\s)*<\/p>/gi, '
\u00a0
');
		source = source.replace(/\s*
\s*<\/p>/gi, '
');

		// Replace improper BRs
		source = source.replace(/
/gi, "
");

		// Remove trailing BRs
		source = source.replace(/
$/gi, '');

		// Remove useless BRs
		source = source.replace(/>
/gi, '>');

		// Remove BRs right before the end of blocks
		source = source.replace(/
\s*<\/(h1|h2|h3|h4|h5|h6|li|p)/gi, '</$1');

		// Remove empty tags
		source = source.replace(/(<[^\/]>|<[^\/][^>]*[^\/]>)\s*<\/[^>]*>/gi, '');

		// Semantic conversion
		source = source.replace(/(.*)<\/span>/gi, '$1');
		source = source.replace(/(.*)<\/span>/gi, '$1');
		source = source.replace(/)/g, "<strong$1");
		source = source.replace(/<\/b(\s+|>)/g, "</strong$1");
		source = source.replace(/)/g, "<em$1");
		source = source.replace(/<\/i(\s+|>)/g, "</em$1");

		// Replace uppercase element names with lowercase
		source = source.replace(/<[^> ]*/g, function(match){return match.toLowerCase();});

		// Replace uppercase attribute names with lowercase
		source = source.replace(/<[^>]*>/g, function(match){
			match = match.replace(/ [^=]+=/g, function(match2){return match2.toLowerCase();});
			return match;
		});

		// Put quotes around unquoted attributes
		source = source.replace(/<[^>]*>/g, function(match){
			match = match.replace(/( [^=]+=)([^"][^ >]*)/g, "$1\"$2\"");
			return match;
		});

		// Final trim
		source = source.trim();

		return source;
	}
});

MooEditable.implement(new Options, new Events);
<|endoftext|>


<commit_before>(function ($, undefined) {

    var ms = $.mobiscroll,
        util = ms.util,
        defaults = {
            inputClass: '',
            invalid: [],
            rtl: false,
            showInput: true,
            group: false,
            groupLabel: 'Groups',
            checkIcon: 'checkmark',
            dataText: 'text',
            dataValue: 'value',
            dataGroup: 'group',
            dataDisabled: 'disabled'
        };

    ms.presetShort('select');

    ms.presets.scroller.select = function (inst) {
        var change,
            group,
            groupWheelIdx,
            headerText,
            i,
            input,
            optionWheelIdx,
            option,
            origValues,
            prevGroup,
            timer,
            orig = $.extend({}, inst.settings),
            s = $.extend(inst.settings, defaults, orig),
            layout = s.layout || (/top|bottom/.test(s.display) ? 'liquid' : ''),
            isLiquid = layout == 'liquid',
            elm = $(this),
            multiple = s.multiple || elm.prop('multiple'),
            id = this.id + '_dummy',
            lbl = $('label[for="' + this.id + '"]').attr('for', id),
            label = s.label !== undefined ? s.label : (lbl.length ? lbl.text() : elm.attr('name')),
            selectedClass = 'dw-msel mbsc-ic mbsc-ic-' + s.checkIcon,
            origReadOnly = s.readonly,
            data = s.data,
            hasData = !!data,
            hasGroups = hasData ? data[0][s.dataGroup] : $('optgroup', elm).length,
            defaultValue = hasData ? data[0][s.dataValue] : $('option', elm).attr('value'),
            groupWheel = hasGroups && s.group,
            groupHdr = hasGroups && !groupWheel,
            values = elm.val(),
            invalid = [],
            selectedValues = {},
            options = {},
            groups = {};

        function prepareData() {
            var gr,
                lbl,
                opt,
                txt,
                val,
                c = 0,
                groupIndexes = {};

            if (hasData) {
                $.each(data, function (i, v) {
                    txt = v[s.dataText];
                    val = v[s.dataValue];
                    lbl = v[s.dataGroup];
                    opt = {
                        value: val,
                        text: txt
                    };
                    options[val] = opt;

                    if (hasGroups) {
                        if (groupIndexes[lbl] === undefined) {
                            gr = { label: lbl, options: [] };
                            groups[c] = gr;
                            groupIndexes[lbl] = c;
                            c++;
                        } else {
                            gr = groups[groupIndexes[lbl]];
                        }
                        opt.group = groupIndexes[lbl];
                        gr.options.push(opt);
                    }
                    if (v[s.dataDisabled]) {
                        invalid.push(val);
                    }
                });
            } else {
                if (hasGroups) {
                    $('optgroup', elm).each(function (i) {
                        groups[i] = { label: this.label, options: [] };
                        $('option', this).each(function () {
                            opt = {
                                value: this.value,
                                text: this.text,
                                group: i
                            };
                            options[this.value] = opt;
                            groups[i].options.push(opt);
                            if (this.disabled) {
                                invalid.push(this.value);
                            }
                        });
                    });
                } else {
                    $('option', elm).each(function () {
                        options[this.value] = {
                            value: this.value,
                            text: this.text
                        };
                        if (this.disabled) {
                            invalid.push(this.value);
                        }
                    });
                }
            }
        }

        function genValues(data, keys, values) {
            $.each(data, function (i, v) {
                values.push(v.text);
                keys.push(v.value);
            });
        }

        function genWheels() {
            var wheel,
                wg = 0,
                values = [],
                keys = [],
                w = [[]];

            // Generate group wheel
            if (groupWheel) {
                $.each(groups, function (i, v) {
                    values.push(v.label);
                    keys.push(i);
                });

                wheel = {
                    values: values,
                    keys: keys,
                    label: s.groupLabel
                };

                if (isLiquid) {
                    w[0][wg] = wheel;
                } else {
                    w[wg] = [wheel];
                }

                wg++;
            }

            values = [];
            keys = [];

            if (groupHdr) { // Generate options wheel with group headers
                $.each(groups, function (i, gr) {
                    values.push(gr.label);
                    keys.push('__group' + i);
                    invalid.push('__group' + i);
                    genValues(gr.options, keys, values);
                });
            } else { // Generate options wheel (for selected group or all, if not grouped)
                genValues(groupWheel ? groups[group].options : options, keys, values);
            }

            wheel = {
                multiple: multiple,
                values: values,
                keys: keys,
                label: label
            };

            if (isLiquid) {
                w[0][wg] = wheel;
            } else {
                w[wg] = [wheel];
            }

            return w;
        }

        function getOption(v) {
            option = multiple ? (v ? v[0] : defaultValue) : (v === undefined || v === null || v === '' ? defaultValue : v);

            if (groupWheel) {
                group = options[option].group;
            }
        }

        function getVal(temp, group) {
            var val = temp ? inst._tempWheelArray : (inst._hasValue ? inst._wheelArray : null);
            return val ? (s.group && group ? val : val[optionWheelIdx]) : null;
        }

        function onFill(v, change) {
            var txt,
                val,
                sel = [],
                i = 0;

            if (multiple) {
                val = [];

                for (i in selectedValues) {
                    sel.push(options[i].text);
                    val.push(i);
                }

                txt = sel.join(', ');
            } else {
                val = v;
                txt = options[v].text;
            }

            input.val(txt);
            elm.val(val);

            if (change) {
                inst._preventChange = true;
                elm.change();
            }
        }

        function onTap(li) {
            var val = li.attr('data-val'),
                selected = li.hasClass('dw-msel');

            if (multiple && li.closest('.dwwl').hasClass('dwwms')) {
                if (li.hasClass('dw-v')) {
                    if (selected) {
                        li.removeClass(selectedClass).removeAttr('aria-selected');
                        delete selectedValues[val];
                    } else {
                        li.addClass(selectedClass).attr('aria-selected', 'true');
                        selectedValues[val] = val;
                    }
                }
                return false;
            }
        }

        if (!s.invalid.length) {
            s.invalid = invalid;
        }

        if (groupWheel) {
            groupWheelIdx = 0;
            optionWheelIdx = 1;
        } else {
            groupWheelIdx = -1;
            optionWheelIdx = 0;
        }

        if (multiple) {
            if (values && !$.isArray(values)) {
                values = values.split(',');
            }
            for (i = 0; i < values.length; i++) {
                selectedValues[values[i]] = values[i];
            }
        }

        prepareData();

        getOption(elm.val());

        $('#' + id).remove();

        input = $('<input type="text" id="' + id + '" class="' + s.inputClass + '" placeholder="' + (s.placeholder || '') + '" readonly />');

        if (s.showInput) {
            input.insertBefore(elm);
        }

        inst.attachShow(input);

        elm.addClass('dw-hsel').attr('tabindex', -1).closest('.ui-field-contain').trigger('create');

        onFill(option);

        // Extended methods
        // ---

        inst.setVal = function (val, fill, change, temp, time) {
            if (multiple) {
                if (val && !$.isArray(val)) {
                    val = val.split(',');
                }
                selectedValues = util.arrayToObject(val);
                val = val ? val[0] : null;
            }
            inst._setVal(val, fill, change, temp, time);
        };

        inst.getVal = function (temp, group) {
            if (multiple) {
                return util.objectToArray(selectedValues);
            }
            return getVal(temp, group);
        };

        // @deprecated since 2.14.0, backward compatibility code
        // ---
        inst.getValues = inst.getVal;

        inst.getValue = getVal;
        // ---

        // ---

        return {
            width: 50,
            layout: layout,
            headerText: false,
            anchor: input,
            formatResult: function (d) {
                return d[optionWheelIdx];
            },
            parseValue: function (val) {
                getOption(val === undefined ? elm.val() : val);

                return groupWheel ? [group, option] : [option];
            },
            onValueTap: onTap,
            onValueFill: onFill,
            onBeforeShow: function () {
                if (multiple && s.counter) {
                    s.headerText = function () {
                        var length = 0;
                        $.each(selectedValues, function () {
                            length++;
                        });
                        return length + ' ' + s.selectedText;
                    };
                }

                // In header text replace {value} with the option text instead of the value
                headerText = s.headerText + '';
                if (/{value}/.test(headerText)) {
                    s.headerText = function (v) {
                        return headerText.replace(/\{value\}/i, options[v].text);
                    };
                }

                getOption(elm.val());

                if (groupWheel) {
                    prevGroup = group;
                    inst._tempWheelArray = [group, option];
                }

                prepareData();

                s.wheels = genWheels();
            },
            onMarkupReady: function (dw) {
                dw.addClass('dw-select');

                $('.dwwl' + groupWheelIdx, dw).on('mousedown touchstart', function () {
                    clearTimeout(timer);
                });

                if (groupHdr) {
                    $('.dw', dw).addClass('dw-select-gr');
                    $('.dw-li[data-val^="__group"]', dw).addClass('dw-w-gr');
                }

                if (multiple) {
                    dw.addClass('dwms');

                    $('.dwwl', dw).on('keydown', function (e) {
                        if (e.keyCode == 32) { // Space
                            e.preventDefault();
                            e.stopPropagation();
                            onTap($('.dw-sel', this));
                        }
                    }).eq(optionWheelIdx).addClass('dwwms').attr('aria-multiselectable', 'true');

                    origValues = $.extend({}, selectedValues);
                }
            },
            validate: function (dw, i, time) {
                var j,
                    v,
                    temp = inst.getArrayVal(true),
                    t = $('.dw-ul', dw).eq(optionWheelIdx);

                if (i === undefined && multiple) {
                    v = selectedValues;
                    j = 0;

                    $('.dwwl' + optionWheelIdx + ' .dw-li', dw).removeClass(selectedClass).removeAttr('aria-selected');

                    for (j in v) {
                        $('.dwwl' + optionWheelIdx + ' .dw-li[data-val="' + v[j] + '"]', dw).addClass(selectedClass).attr('aria-selected', 'true');
                    }
                }

                if (groupWheel && (i === undefined || i === groupWheelIdx)) {
                    group = +temp[groupWheelIdx];
                    if (group !== prevGroup) {
                        option = groups[group].options[0].value;
                        s.wheels = genWheels();
                        if (!change) {
                            inst._tempWheelArray = [group, option];
                            s.readonly = [false, true];
                            clearTimeout(timer);
                            timer = setTimeout(function () {
                                change = true;
                                prevGroup = group;
                                inst.changeWheel([optionWheelIdx], undefined, true);
                                s.readonly = origReadOnly;
                            }, time * 1000);
                            return false;
                        }
                    } else {
                        s.readonly = origReadOnly;
                    }
                } else {
                    option = temp[optionWheelIdx];
                }

                $.each(s.invalid, function (i, v) {
                    $('.dw-li[data-val="' + v + '"]', t).removeClass('dw-v');
                });

                change = false;
            },
            onClear: function (dw) {
                selectedValues = {};
                input.val('');
                $('.dwwl' + optionWheelIdx + ' .dw-li', dw).removeClass(selectedClass).removeAttr('aria-selected');
            },
            onCancel: function () {
                if (!inst.live && multiple) {
                    selectedValues = $.extend({}, origValues);
                }
            },
            onDestroy: function () {
                input.remove();
                elm.removeClass('dw-hsel').removeAttr('tabindex');
            }
        };
    };

})(jQuery);
<commit_msg>Multiple select fix<commit_after>(function ($, undefined) {

    var ms = $.mobiscroll,
        util = ms.util,
        defaults = {
            inputClass: '',
            invalid: [],
            rtl: false,
            showInput: true,
            group: false,
            groupLabel: 'Groups',
            checkIcon: 'checkmark',
            dataText: 'text',
            dataValue: 'value',
            dataGroup: 'group',
            dataDisabled: 'disabled'
        };

    ms.presetShort('select');

    ms.presets.scroller.select = function (inst) {
        var change,
            group,
            groupWheelIdx,
            headerText,
            i,
            input,
            optionWheelIdx,
            option,
            origValues,
            prevGroup,
            timer,
            orig = $.extend({}, inst.settings),
            s = $.extend(inst.settings, defaults, orig),
            layout = s.layout || (/top|bottom/.test(s.display) ? 'liquid' : ''),
            isLiquid = layout == 'liquid',
            elm = $(this),
            multiple = s.multiple || elm.prop('multiple'),
            id = this.id + '_dummy',
            lbl = $('label[for="' + this.id + '"]').attr('for', id),
            label = s.label !== undefined ? s.label : (lbl.length ? lbl.text() : elm.attr('name')),
            selectedClass = 'dw-msel mbsc-ic mbsc-ic-' + s.checkIcon,
            origReadOnly = s.readonly,
            data = s.data,
            hasData = !!data,
            hasGroups = hasData ? data[0][s.dataGroup] : $('optgroup', elm).length,
            defaultValue = hasData ? data[0][s.dataValue] : $('option', elm).attr('value'),
            groupWheel = hasGroups && s.group,
            groupHdr = hasGroups && !groupWheel,
            values = elm.val() || [],
            invalid = [],
            selectedValues = {},
            options = {},
            groups = {};

        function prepareData() {
            var gr,
                lbl,
                opt,
                txt,
                val,
                c = 0,
                groupIndexes = {};

            if (hasData) {
                $.each(data, function (i, v) {
                    txt = v[s.dataText];
                    val = v[s.dataValue];
                    lbl = v[s.dataGroup];
                    opt = {
                        value: val,
                        text: txt
                    };
                    options[val] = opt;

                    if (hasGroups) {
                        if (groupIndexes[lbl] === undefined) {
                            gr = { label: lbl, options: [] };
                            groups[c] = gr;
                            groupIndexes[lbl] = c;
                            c++;
                        } else {
                            gr = groups[groupIndexes[lbl]];
                        }
                        opt.group = groupIndexes[lbl];
                        gr.options.push(opt);
                    }
                    if (v[s.dataDisabled]) {
                        invalid.push(val);
                    }
                });
            } else {
                if (hasGroups) {
                    $('optgroup', elm).each(function (i) {
                        groups[i] = { label: this.label, options: [] };
                        $('option', this).each(function () {
                            opt = {
                                value: this.value,
                                text: this.text,
                                group: i
                            };
                            options[this.value] = opt;
                            groups[i].options.push(opt);
                            if (this.disabled) {
                                invalid.push(this.value);
                            }
                        });
                    });
                } else {
                    $('option', elm).each(function () {
                        options[this.value] = {
                            value: this.value,
                            text: this.text
                        };
                        if (this.disabled) {
                            invalid.push(this.value);
                        }
                    });
                }
            }
        }

        function genValues(data, keys, values) {
            $.each(data, function (i, v) {
                values.push(v.text);
                keys.push(v.value);
            });
        }

        function genWheels() {
            var wheel,
                wg = 0,
                values = [],
                keys = [],
                w = [[]];

            // Generate group wheel
            if (groupWheel) {
                $.each(groups, function (i, v) {
                    values.push(v.label);
                    keys.push(i);
                });

                wheel = {
                    values: values,
                    keys: keys,
                    label: s.groupLabel
                };

                if (isLiquid) {
                    w[0][wg] = wheel;
                } else {
                    w[wg] = [wheel];
                }

                wg++;
            }

            values = [];
            keys = [];

            if (groupHdr) { // Generate options wheel with group headers
                $.each(groups, function (i, gr) {
                    values.push(gr.label);
                    keys.push('__group' + i);
                    invalid.push('__group' + i);
                    genValues(gr.options, keys, values);
                });
            } else { // Generate options wheel (for selected group or all, if not grouped)
                genValues(groupWheel ? groups[group].options : options, keys, values);
            }

            wheel = {
                multiple: multiple,
                values: values,
                keys: keys,
                label: label
            };

            if (isLiquid) {
                w[0][wg] = wheel;
            } else {
                w[wg] = [wheel];
            }

            return w;
        }

        function getOption(v) {
            option = multiple ? (v ? v[0] : defaultValue) : (v === undefined || v === null || v === '' ? defaultValue : v);

            if (groupWheel) {
                group = options[option].group;
            }
        }

        function getVal(temp, group) {
            var val = temp ? inst._tempWheelArray : (inst._hasValue ? inst._wheelArray : null);
            return val ? (s.group && group ? val : val[optionWheelIdx]) : null;
        }

        function onFill(v, change) {
            var txt,
                val,
                sel = [],
                i = 0;

            if (multiple) {
                val = [];

                for (i in selectedValues) {
                    sel.push(options[i].text);
                    val.push(i);
                }

                txt = sel.join(', ');
            } else {
                val = v;
                txt = options[v].text;
            }

            input.val(txt);
            elm.val(val);

            if (change) {
                inst._preventChange = true;
                elm.change();
            }
        }

        function onTap(li) {
            var val = li.attr('data-val'),
                selected = li.hasClass('dw-msel');

            if (multiple && li.closest('.dwwl').hasClass('dwwms')) {
                if (li.hasClass('dw-v')) {
                    if (selected) {
                        li.removeClass(selectedClass).removeAttr('aria-selected');
                        delete selectedValues[val];
                    } else {
                        li.addClass(selectedClass).attr('aria-selected', 'true');
                        selectedValues[val] = val;
                    }
                }
                return false;
            }
        }

        if (!s.invalid.length) {
            s.invalid = invalid;
        }

        if (groupWheel) {
            groupWheelIdx = 0;
            optionWheelIdx = 1;
        } else {
            groupWheelIdx = -1;
            optionWheelIdx = 0;
        }

        if (multiple) {
            if (values && !$.isArray(values)) {
                values = values.split(',');
            }
            for (i = 0; i < values.length; i++) {
                selectedValues[values[i]] = values[i];
            }
        }

        prepareData();

        getOption(elm.val());

        $('#' + id).remove();

        input = $('<input type="text" id="' + id + '" class="' + s.inputClass + '" placeholder="' + (s.placeholder || '') + '" readonly />');

        if (s.showInput) {
            input.insertBefore(elm);
        }

        inst.attachShow(input);

        elm.addClass('dw-hsel').attr('tabindex', -1).closest('.ui-field-contain').trigger('create');

        onFill(option);

        // Extended methods
        // ---

        inst.setVal = function (val, fill, change, temp, time) {
            if (multiple) {
                if (val && !$.isArray(val)) {
                    val = val.split(',');
                }
                selectedValues = util.arrayToObject(val);
                val = val ? val[0] : null;
            }
            inst._setVal(val, fill, change, temp, time);
        };

        inst.getVal = function (temp, group) {
            if (multiple) {
                return util.objectToArray(selectedValues);
            }
            return getVal(temp, group);
        };

        // @deprecated since 2.14.0, backward compatibility code
        // ---
        inst.getValues = inst.getVal;

        inst.getValue = getVal;
        // ---

        // ---

        return {
            width: 50,
            layout: layout,
            headerText: false,
            anchor: input,
            formatResult: function (d) {
                return d[optionWheelIdx];
            },
            parseValue: function (val) {
                getOption(val === undefined ? elm.val() : val);

                return groupWheel ? [group, option] : [option];
            },
            onValueTap: onTap,
            onValueFill: onFill,
            onBeforeShow: function () {
                if (multiple && s.counter) {
                    s.headerText = function () {
                        var length = 0;
                        $.each(selectedValues, function () {
                            length++;
                        });
                        return length + ' ' + s.selectedText;
                    };
                }

                // In header text replace {value} with the option text instead of the value
                headerText = s.headerText + '';
                if (/{value}/.test(headerText)) {
                    s.headerText = function (v) {
                        return headerText.replace(/\{value\}/i, options[v].text);
                    };
                }

                getOption(elm.val());

                if (groupWheel) {
                    prevGroup = group;
                    inst._tempWheelArray = [group, option];
                }

                prepareData();

                s.wheels = genWheels();
            },
            onMarkupReady: function (dw) {
                dw.addClass('dw-select');

                $('.dwwl' + groupWheelIdx, dw).on('mousedown touchstart', function () {
                    clearTimeout(timer);
                });

                if (groupHdr) {
                    $('.dw', dw).addClass('dw-select-gr');
                    $('.dw-li[data-val^="__group"]', dw).addClass('dw-w-gr');
                }

                if (multiple) {
                    dw.addClass('dwms');

                    $('.dwwl', dw).on('keydown', function (e) {
                        if (e.keyCode == 32) { // Space
                            e.preventDefault();
                            e.stopPropagation();
                            onTap($('.dw-sel', this));
                        }
                    }).eq(optionWheelIdx).addClass('dwwms').attr('aria-multiselectable', 'true');

                    origValues = $.extend({}, selectedValues);
                }
            },
            validate: function (dw, i, time) {
                var j,
                    v,
                    temp = inst.getArrayVal(true),
                    t = $('.dw-ul', dw).eq(optionWheelIdx);

                if (i === undefined && multiple) {
                    v = selectedValues;
                    j = 0;

                    $('.dwwl' + optionWheelIdx + ' .dw-li', dw).removeClass(selectedClass).removeAttr('aria-selected');

                    for (j in v) {
                        $('.dwwl' + optionWheelIdx + ' .dw-li[data-val="' + v[j] + '"]', dw).addClass(selectedClass).attr('aria-selected', 'true');
                    }
                }

                if (groupWheel && (i === undefined || i === groupWheelIdx)) {
                    group = +temp[groupWheelIdx];
                    if (group !== prevGroup) {
                        option = groups[group].options[0].value;
                        s.wheels = genWheels();
                        if (!change) {
                            inst._tempWheelArray = [group, option];
                            s.readonly = [false, true];
                            clearTimeout(timer);
                            timer = setTimeout(function () {
                                change = true;
                                prevGroup = group;
                                inst.changeWheel([optionWheelIdx], undefined, true);
                                s.readonly = origReadOnly;
                            }, time * 1000);
                            return false;
                        }
                    } else {
                        s.readonly = origReadOnly;
                    }
                } else {
                    option = temp[optionWheelIdx];
                }

                $.each(s.invalid, function (i, v) {
                    $('.dw-li[data-val="' + v + '"]', t).removeClass('dw-v');
                });

                change = false;
            },
            onClear: function (dw) {
                selectedValues = {};
                input.val('');
                $('.dwwl' + optionWheelIdx + ' .dw-li', dw).removeClass(selectedClass).removeAttr('aria-selected');
            },
            onCancel: function () {
                if (!inst.live && multiple) {
                    selectedValues = $.extend({}, origValues);
                }
            },
            onDestroy: function () {
                input.remove();
                elm.removeClass('dw-hsel').removeAttr('tabindex');
            }
        };
    };

})(jQuery);
<|endoftext|>


<commit_before>/*! cross-console 0.3.0 2013-10-17 */
!function(a){"use strict";var b,c,d={},e=a||window||this,f=e.console,g=Array.prototype.slice,h=["CC.filter","CC.history"],i=e.localStorage&&e.JSON;f&&(d=Object.create(f)),"undefined"!=typeof module?module.exports=d:e.cconsole=d,d.settings={persistConfig:{filter:h[0],history:h[1]},persist:i,standBy:!1,timestamp:!0,debug:!1,environment:"production",history:i?JSON.parse(e.localStorage.getItem(h[1]))||[]:[],maxHistory:100,filter:i?JSON.parse(e.localStorage.getItem(h[0]))||!1:!1,notify:function(){}},b=function(a,b){try{setTimeout(function(){e.localStorage.setItem(a,b)},50)}catch(d){c("error",d.message)}},c=function(a,b){f.firebug?f[a].apply(e,b):f[a]?f[a].apply(f,b):f.log.apply(f,b)},d.set=function(a){if("undefined"==typeof a||"object"!=typeof a||a instanceof String||a instanceof Array)throw Error("You must pass an plain object to set settings. EG: { }");for(var b in a)a.hasOwnProperty(b)&&(d.settings[b]=a[b])},d.clearFilter=function(){d.settings.filter=!1,d.settings.persist&&b(d.settings.persistConfig.filter,!1)},d.setFilter=function(a){if("string"!=typeof a&&!(a instanceof String))throw new Error("Filters must be of type string");d.settings.filter=a,d.settings.persist&&b(d.settings.persistConfig.filter,a)};var j=["error","warn","debug"],k=["log","info","assert","clear","count","dir","dirxml","exception","group","groupCollapsed","groupEnd","markTimeline","profile","profileEnd","table","time","timeEnd","timeStamp","trace","memory","profiles"],l=k.length,m=function(){var a=[],b=15;return function(c,d){if(b--<1)return"<Depth Restricted>";if(c&&d&&["[object Object]","[object Array]"].indexOf(Object.prototype.toString.call(d))>-1){if(a.indexOf(d)>-1)return"<Circular Reference>";a.push(d)}else if(c&&d&&"[object String]"!==Object.prototype.toString.call(d))return d.toString();return d}},n=function(a){d.settings.history.unshift(a),d.settings.history.length>d.settings.maxHistory&&d.settings.history.pop(),d.settings.persist&&b(d.settings.persistConfig.history,e.JSON.stringify(d.settings.history,m(),""))},o=function(a){d[a]=function(){var b=g.call(arguments);try{if(d.settings.standBy)return c(a,b),void 0;if("production"===d.settings.environment)return;if(!f||!d.settings.debug||d.settings.filter&&b[0].indexOf(d.settings.filter)<0)return;n([a].concat(b)),c(a,b)}catch(e){if(d.settings.debug)throw new Error(e)}}},p=function(a,b){d[b]=function(){var a=g.call(arguments);try{if(d.settings.standBy)return c(b,a),void 0;if("error"!==b&&"production"===d.settings.environment)return;var e,h,i=new Error,j=i&&i.stack,k=[""],l="",m=/\//g,o=["error","warn"];if(j&&"string"==typeof j)try{k=j.split(/\r\n|\r|\n/),k=k[k.length-1].split(/\//)}catch(p){k=["Failed to retrieve stack trace."]}if(h=k[k.length-1].split(/:/),"debug"!==b?(a.push(h[0]+" Line "+h[1]),l=h[0].replace(m,"~")+":"+h[1]):a.push((new Error&&(new Error).stack?(new Error).stack:"").split(/\r\n|\r|\n/)),!f||o.indexOf(b)<0&&(!d.settings.debug||d.settings.filter&&a[0].indexOf(d.settings.filter)<0))return;if(d.settings.timestamp&&a.unshift((new Date).toISOString()),e=[b].concat(a),n(e),"production"===d.settings.environment)return d.settings.notify(e,l),void 0;c(b,a)}catch(q){if(d.settings.debug)throw new Error(q)}}};for(e.console=d;--l>=0;)o(k[l]);for(l=j.length;--l>=0;)f[j[l]]=f[j[l]]||function(){},f[j[l]]=Function.prototype.bind.call(f[j[l]],f),p(l,j[l])}(this);<commit_msg>Built code<commit_after>/*! cross-console 0.3.1 2013-12-10 */
!function(a){"use strict";var b,c,d={},e=a||window||this,f=e.console,g=Array.prototype.slice,h=["CC.filter","CC.history"],i=e.localStorage&&e.JSON;f&&(d=Object.create(f)),"undefined"!=typeof module?module.exports=d:e.cconsole=d,d.settings={persistConfig:{filter:h[0],history:h[1]},persist:i,standBy:!1,timestamp:!0,debug:!1,environment:"production",history:i?JSON.parse(e.localStorage.getItem(h[1]))||[]:[],maxHistory:100,filter:i?JSON.parse(e.localStorage.getItem(h[0]))||!1:!1,notify:function(){}},b=function(a,b){try{setTimeout(function(){e.localStorage.setItem(a,b)},50)}catch(d){c("error",d.message)}},c=function(a,b){return f.firebug?(f[a].apply(e,b),void 0):f[a]&&f[a].apply?(f[a].apply(f,b),void 0):(f.log&&f.log.apply&&f.log.apply(f,b),void 0)},d.set=function(a){if("undefined"==typeof a||"object"!=typeof a||a instanceof String||a instanceof Array)throw Error("You must pass an plain object to set settings. EG: { }");for(var b in a)a.hasOwnProperty(b)&&(d.settings[b]=a[b])},d.clearFilter=function(){d.settings.filter=!1,d.settings.persist&&b(d.settings.persistConfig.filter,!1)},d.setFilter=function(a){if("string"!=typeof a&&!(a instanceof String))throw new Error("Filters must be of type string");d.settings.filter=a,d.settings.persist&&b(d.settings.persistConfig.filter,a)};var j=["error","warn","debug"],k=["log","info","assert","clear","count","dir","dirxml","exception","group","groupCollapsed","groupEnd","markTimeline","profile","profileEnd","table","time","timeEnd","timeStamp","trace","memory","profiles"],l=k.length,m=function(){var a=[],b=15;return function(c,d){if(b--<1)return"<Depth Restricted>";if(c&&d&&["[object Object]","[object Array]"].indexOf(Object.prototype.toString.call(d))>-1){if(a.indexOf(d)>-1)return"<Circular Reference>";a.push(d)}else if(c&&d&&"[object String]"!==Object.prototype.toString.call(d))return d.toString();return d}},n=function(a){d.settings.history.unshift(a),d.settings.history.length>d.settings.maxHistory&&d.settings.history.pop(),d.settings.persist&&b(d.settings.persistConfig.history,e.JSON.stringify(d.settings.history,m(),""))},o=function(a){d[a]=function(){var b=g.call(arguments);try{if(d.settings.standBy)return c(a,b),void 0;if("production"===d.settings.environment)return;if(!f||!d.settings.debug||d.settings.filter&&b[0].indexOf(d.settings.filter)<0)return;n([a].concat(b)),c(a,b)}catch(e){if(d.settings.debug)throw new Error(e)}}},p=function(a,b){d[b]=function(){var a=g.call(arguments);try{if(d.settings.standBy)return c(b,a),void 0;if("error"!==b&&"production"===d.settings.environment)return;var e,h,i=new Error,j=i&&i.stack,k=[""],l="",m=/\//g,o=["error","warn"];if(j&&"string"==typeof j)try{k=j.split(/\r\n|\r|\n/),k=k[k.length-1].split(/\//)}catch(p){k=["Failed to retrieve stack trace."]}if(h=k[k.length-1].split(/:/),"debug"!==b?(a.push(h[0]+" Line "+h[1]),l=h[0].replace(m,"~")+":"+h[1]):a.push((new Error&&(new Error).stack?(new Error).stack:"").split(/\r\n|\r|\n/)),!f||o.indexOf(b)<0&&(!d.settings.debug||d.settings.filter&&a[0].indexOf(d.settings.filter)<0))return;if(d.settings.timestamp&&a.unshift((new Date).toISOString()),e=[b].concat(a),n(e),"production"===d.settings.environment)return d.settings.notify(e,l),void 0;c(b,a)}catch(q){if(d.settings.debug)throw new Error(q)}}};for(e.console=d;--l>=0;)o(k[l]);for(l=j.length;--l>=0;)f[j[l]]=f[j[l]]||function(){},f[j[l]]=Function.prototype.bind.call(f[j[l]],f),p(l,j[l])}(this);<|endoftext|>