<commit_before>/*===============================================================================
************   Handle clicks and make them fast (on tap);   ************
===============================================================================*/
app.initClickEvents = function () {
    function handleClicks(e) {
        /*jshint validthis:true */
        var clicked = $(this);
        var url = clicked.attr('href');
        var isLink = clicked[0].nodeName.toLowerCase() === 'a';

        // Str to boolean for data attributes
        function toBoolean(str) {
            if (str === 'false') return false;
            if (str === 'true') return true;
            return undefined;
        }
        // Check if link is external
        if (isLink) {
            if (clicked.is(app.params.externalLinks)) return;
        }

        // Smart Select
        if (clicked.hasClass('smart-select')) {
            if (app.smartSelectOpen) app.smartSelectOpen(clicked);
        }

        // Open Panel
        if (clicked.hasClass('open-panel')) {
            if ($('.panel').length === 1) {
                if ($('.panel').hasClass('panel-left')) app.openPanel('left');
                else app.openPanel('right');
            }
            else {
                if (clicked.attr('data-panel') === 'right') app.openPanel('right');
                else app.openPanel('left');
            }
        }
        // Close Panel
        if (clicked.hasClass('close-panel')) {
            app.closePanel();
        }

        if (clicked.hasClass('panel-overlay') && app.params.panelsCloseByOutside) {
            app.closePanel();
        }
        // Popover
        if (clicked.hasClass('open-popover')) {
            var popover;
            if (clicked.attr('data-popover')) {
                popover = clicked.attr('data-popover');
            }
            else popover = '.popover';
            app.popover(popover, clicked);
        }
        if (clicked.hasClass('close-popover')) {
            app.closeModal('.popover.modal-in');
        }
        // Popup
        var popup;
        if (clicked.hasClass('open-popup')) {
            if (clicked.attr('data-popup')) {
                popup = clicked.attr('data-popup');
            }
            else popup = '.popup';
            app.popup(popup);
        }
        if (clicked.hasClass('close-popup')) {
            if (clicked.attr('data-popup')) {
                popup = clicked.attr('data-popup');
            }
            else popup = '.popup.modal-in';
            app.closeModal(popup);
        }
        // Login Screen
        var loginScreen;
        if (clicked.hasClass('open-login-screen')) {
            if (clicked.attr('data-login-screen')) {
                loginScreen = clicked.attr('data-login-screen');
            }
            else loginScreen = '.login-screen';
            app.loginScreen(loginScreen);
        }
        if (clicked.hasClass('close-login-screen')) {
            app.closeModal('.login-screen.modal-in');
        }
        // Close Modal
        if (clicked.hasClass('modal-overlay')) {
            if ($('.modal.modal-in').length > 0 && app.params.modalCloseByOutside)
                app.closeModal('.modal.modal-in');
            if ($('.actions-modal.modal-in').length > 0 && app.params.actionsCloseByOutside)
                app.closeModal('.actions-modal.modal-in');

            if ($('.popover.modal-in').length > 0) app.closeModal('.popover.modal-in');
        }
        if (clicked.hasClass('popup-overlay')) {
            if ($('.popup.modal-in').length > 0 && app.params.popupCloseByOutside)
                app.closeModal('.popup.modal-in');
        }

        // Picker
        if (clicked.hasClass('close-picker')) {
            var pickerToClose = $('.picker-modal.modal-in');
            if (pickerToClose.length > 0) {
                app.closeModal(pickerToClose);
            }
            else {
                pickerToClose = $('.popover.modal-in .picker-modal');
                if (pickerToClose.length > 0) {
                    app.closeModal(pickerToClose.parents('.popover'));
                }
            }
        }
        if (clicked.hasClass('open-picker')) {
            var pickerToOpen;
            if (clicked.attr('data-picker')) {
                pickerToOpen = clicked.attr('data-picker');
            }
            else pickerToOpen = '.picker-modal';
            app.pickerModal(pickerToOpen, clicked);
        }

        // Tabs
        var isTabLink;
        if (clicked.hasClass('tab-link')) {
            isTabLink = true;
            app.showTab(clicked.attr('data-tab') || clicked.attr('href'), clicked);
        }
        // Swipeout Close
        if (clicked.hasClass('swipeout-close')) {
            app.swipeoutClose(clicked.parents('.swipeout-opened'));
        }
        // Swipeout Delete
        if (clicked.hasClass('swipeout-delete')) {
            if (clicked.attr('data-confirm')) {
                var text = clicked.attr('data-confirm');
                var title = clicked.attr('data-confirm-title');
                if (title) {
                    app.confirm(text, title, function () {
                        app.swipeoutDelete(clicked.parents('.swipeout'));
                    });
                }
                else {
                    app.confirm(text, function () {
                        app.swipeoutDelete(clicked.parents('.swipeout'));
                    });
                }
            }
            else {
                app.swipeoutDelete(clicked.parents('.swipeout'));
            }

        }
        // Sortable
        if (clicked.hasClass('toggle-sortable')) {
            app.sortableToggle(clicked.data('sortable'));
        }
        if (clicked.hasClass('open-sortable')) {
            app.sortableOpen(clicked.data('sortable'));
        }
        if (clicked.hasClass('close-sortable')) {
            app.sortableClose(clicked.data('sortable'));
        }
        // Accordion
        if (clicked.hasClass('accordion-item-toggle') || (clicked.hasClass('item-link') && clicked.parent().hasClass('accordion-item'))) {
            var accordionItem = clicked.parent('.accordion-item');
            if (accordionItem.length === 0) accordionItem = clicked.parents('.accordion-item');
            if (accordionItem.length === 0) accordionItem = clicked.parents('li');
            app.accordionToggle(accordionItem);
        }

        // Load Page
        if (app.params.ajaxLinks && !clicked.is(app.params.ajaxLinks) || !isLink || !app.params.router) {
            return;
        }
        if (isLink) {
            e.preventDefault();
        }

        var validUrl = url && url.length > 0 && url !== '#' && !isTabLink;
        var template = clicked.attr('data-template');
        if (validUrl || clicked.hasClass('back') || template) {
            var view;
            if (clicked.attr('data-view')) {
                view = $(clicked.attr('data-view'))[0].f7View;
            }
            else {
                view = clicked.parents('.' + app.params.viewClass)[0] && clicked.parents('.' + app.params.viewClass)[0].f7View;
                if (view && view.params.linksView) {
                    if (typeof view.params.linksView === 'string') view = $(view.params.linksView)[0].f7View;
                    else if (view.params.linksView instanceof View) view = view.params.linksView;
                }
            }
            if (!view) {
                if (app.mainView) view = app.mainView;
            }
            if (!view) return;

            var pageName;
            if (!template) {
                if (url.indexOf('#') === 0 && url !== '#')  {
                    if (view.params.domCache) {
                        pageName = url.split('#')[1];
                        url = undefined;
                    }
                    else return;
                }
                if (url === '#' && !clicked.hasClass('back')) return;
            }
            else {
                url = undefined;
            }

            var animatePages;
            if (clicked.attr('data-animatePages')) {
                animatePages = toBoolean(clicked.attr('data-animatePages'));
            }
            else {
                if (clicked.hasClass('with-animation')) animatePages = true;
                if (clicked.hasClass('no-animation')) animatePages = false;
            }

            var options = {
                animatePages: animatePages,
                ignoreCache: toBoolean(clicked.attr('data-ignoreCache')),
                force: toBoolean(clicked.attr('data-force')),
                reload: toBoolean(clicked.attr('data-reload')),
                reloadPrevious: toBoolean(clicked.attr('data-reloadPrevious')),
                pageName: pageName,
                url: url
            };

            if (app.params.template7Pages) {
                options.contextName = clicked.attr('data-contextName');
                var context = clicked.attr('data-context');
                if (context) {
                    options.context = JSON.parse(context);
                }
            }
            if (template && template in t7.templates) {
                options.template = t7.templates[template];
            }

            if (clicked.hasClass('back')) view.router.back(options);
            else view.router.load(options);
        }
    }
    $(document).on('click', 'a, .open-panel, .close-panel, .panel-overlay, .modal-overlay, .popup-overlay, .swipeout-delete, .swipeout-close, .close-popup, .open-popup, .open-popover, .open-login-screen, .close-login-screen .smart-select, .toggle-sortable, .open-sortable, .close-sortable, .accordion-item-toggle, .close-picker', handleClicks);
};
<commit_msg>Prevent scrolling on overlays<commit_after>/*===============================================================================
************   Handle clicks and make them fast (on tap);   ************
===============================================================================*/
app.initClickEvents = function () {
    function handleClicks(e) {
        /*jshint validthis:true */
        var clicked = $(this);
        var url = clicked.attr('href');
        var isLink = clicked[0].nodeName.toLowerCase() === 'a';

        // Str to boolean for data attributes
        function toBoolean(str) {
            if (str === 'false') return false;
            if (str === 'true') return true;
            return undefined;
        }
        // Check if link is external
        if (isLink) {
            if (clicked.is(app.params.externalLinks)) return;
        }

        // Smart Select
        if (clicked.hasClass('smart-select')) {
            if (app.smartSelectOpen) app.smartSelectOpen(clicked);
        }

        // Open Panel
        if (clicked.hasClass('open-panel')) {
            if ($('.panel').length === 1) {
                if ($('.panel').hasClass('panel-left')) app.openPanel('left');
                else app.openPanel('right');
            }
            else {
                if (clicked.attr('data-panel') === 'right') app.openPanel('right');
                else app.openPanel('left');
            }
        }
        // Close Panel
        if (clicked.hasClass('close-panel')) {
            app.closePanel();
        }

        if (clicked.hasClass('panel-overlay') && app.params.panelsCloseByOutside) {
            app.closePanel();
        }
        // Popover
        if (clicked.hasClass('open-popover')) {
            var popover;
            if (clicked.attr('data-popover')) {
                popover = clicked.attr('data-popover');
            }
            else popover = '.popover';
            app.popover(popover, clicked);
        }
        if (clicked.hasClass('close-popover')) {
            app.closeModal('.popover.modal-in');
        }
        // Popup
        var popup;
        if (clicked.hasClass('open-popup')) {
            if (clicked.attr('data-popup')) {
                popup = clicked.attr('data-popup');
            }
            else popup = '.popup';
            app.popup(popup);
        }
        if (clicked.hasClass('close-popup')) {
            if (clicked.attr('data-popup')) {
                popup = clicked.attr('data-popup');
            }
            else popup = '.popup.modal-in';
            app.closeModal(popup);
        }
        // Login Screen
        var loginScreen;
        if (clicked.hasClass('open-login-screen')) {
            if (clicked.attr('data-login-screen')) {
                loginScreen = clicked.attr('data-login-screen');
            }
            else loginScreen = '.login-screen';
            app.loginScreen(loginScreen);
        }
        if (clicked.hasClass('close-login-screen')) {
            app.closeModal('.login-screen.modal-in');
        }
        // Close Modal
        if (clicked.hasClass('modal-overlay')) {
            if ($('.modal.modal-in').length > 0 && app.params.modalCloseByOutside)
                app.closeModal('.modal.modal-in');
            if ($('.actions-modal.modal-in').length > 0 && app.params.actionsCloseByOutside)
                app.closeModal('.actions-modal.modal-in');

            if ($('.popover.modal-in').length > 0) app.closeModal('.popover.modal-in');
        }
        if (clicked.hasClass('popup-overlay')) {
            if ($('.popup.modal-in').length > 0 && app.params.popupCloseByOutside)
                app.closeModal('.popup.modal-in');
        }

        // Picker
        if (clicked.hasClass('close-picker')) {
            var pickerToClose = $('.picker-modal.modal-in');
            if (pickerToClose.length > 0) {
                app.closeModal(pickerToClose);
            }
            else {
                pickerToClose = $('.popover.modal-in .picker-modal');
                if (pickerToClose.length > 0) {
                    app.closeModal(pickerToClose.parents('.popover'));
                }
            }
        }
        if (clicked.hasClass('open-picker')) {
            var pickerToOpen;
            if (clicked.attr('data-picker')) {
                pickerToOpen = clicked.attr('data-picker');
            }
            else pickerToOpen = '.picker-modal';
            app.pickerModal(pickerToOpen, clicked);
        }

        // Tabs
        var isTabLink;
        if (clicked.hasClass('tab-link')) {
            isTabLink = true;
            app.showTab(clicked.attr('data-tab') || clicked.attr('href'), clicked);
        }
        // Swipeout Close
        if (clicked.hasClass('swipeout-close')) {
            app.swipeoutClose(clicked.parents('.swipeout-opened'));
        }
        // Swipeout Delete
        if (clicked.hasClass('swipeout-delete')) {
            if (clicked.attr('data-confirm')) {
                var text = clicked.attr('data-confirm');
                var title = clicked.attr('data-confirm-title');
                if (title) {
                    app.confirm(text, title, function () {
                        app.swipeoutDelete(clicked.parents('.swipeout'));
                    });
                }
                else {
                    app.confirm(text, function () {
                        app.swipeoutDelete(clicked.parents('.swipeout'));
                    });
                }
            }
            else {
                app.swipeoutDelete(clicked.parents('.swipeout'));
            }

        }
        // Sortable
        if (clicked.hasClass('toggle-sortable')) {
            app.sortableToggle(clicked.data('sortable'));
        }
        if (clicked.hasClass('open-sortable')) {
            app.sortableOpen(clicked.data('sortable'));
        }
        if (clicked.hasClass('close-sortable')) {
            app.sortableClose(clicked.data('sortable'));
        }
        // Accordion
        if (clicked.hasClass('accordion-item-toggle') || (clicked.hasClass('item-link') && clicked.parent().hasClass('accordion-item'))) {
            var accordionItem = clicked.parent('.accordion-item');
            if (accordionItem.length === 0) accordionItem = clicked.parents('.accordion-item');
            if (accordionItem.length === 0) accordionItem = clicked.parents('li');
            app.accordionToggle(accordionItem);
        }

        // Load Page
        if (app.params.ajaxLinks && !clicked.is(app.params.ajaxLinks) || !isLink || !app.params.router) {
            return;
        }
        if (isLink) {
            e.preventDefault();
        }

        var validUrl = url && url.length > 0 && url !== '#' && !isTabLink;
        var template = clicked.attr('data-template');
        if (validUrl || clicked.hasClass('back') || template) {
            var view;
            if (clicked.attr('data-view')) {
                view = $(clicked.attr('data-view'))[0].f7View;
            }
            else {
                view = clicked.parents('.' + app.params.viewClass)[0] && clicked.parents('.' + app.params.viewClass)[0].f7View;
                if (view && view.params.linksView) {
                    if (typeof view.params.linksView === 'string') view = $(view.params.linksView)[0].f7View;
                    else if (view.params.linksView instanceof View) view = view.params.linksView;
                }
            }
            if (!view) {
                if (app.mainView) view = app.mainView;
            }
            if (!view) return;

            var pageName;
            if (!template) {
                if (url.indexOf('#') === 0 && url !== '#')  {
                    if (view.params.domCache) {
                        pageName = url.split('#')[1];
                        url = undefined;
                    }
                    else return;
                }
                if (url === '#' && !clicked.hasClass('back')) return;
            }
            else {
                url = undefined;
            }

            var animatePages;
            if (clicked.attr('data-animatePages')) {
                animatePages = toBoolean(clicked.attr('data-animatePages'));
            }
            else {
                if (clicked.hasClass('with-animation')) animatePages = true;
                if (clicked.hasClass('no-animation')) animatePages = false;
            }

            var options = {
                animatePages: animatePages,
                ignoreCache: toBoolean(clicked.attr('data-ignoreCache')),
                force: toBoolean(clicked.attr('data-force')),
                reload: toBoolean(clicked.attr('data-reload')),
                reloadPrevious: toBoolean(clicked.attr('data-reloadPrevious')),
                pageName: pageName,
                url: url
            };

            if (app.params.template7Pages) {
                options.contextName = clicked.attr('data-contextName');
                var context = clicked.attr('data-context');
                if (context) {
                    options.context = JSON.parse(context);
                }
            }
            if (template && template in t7.templates) {
                options.template = t7.templates[template];
            }

            if (clicked.hasClass('back')) view.router.back(options);
            else view.router.load(options);
        }
    }
    $(document).on('click', 'a, .open-panel, .close-panel, .panel-overlay, .modal-overlay, .popup-overlay, .swipeout-delete, .swipeout-close, .close-popup, .open-popup, .open-popover, .open-login-screen, .close-login-screen .smart-select, .toggle-sortable, .open-sortable, .close-sortable, .accordion-item-toggle, .close-picker', handleClicks);

    // Prevent scrolling on overlays
    function preventScrolling(e) {
        e.preventDefault();
    }
    if (app.support.touch) {
        $(document).on('touchstart', '.panel-overlay, .modal-overlay, .preloader-indicator-overlay, .popup-overlay, .searchbar-overlay', preventScrolling);
    }
};
<|endoftext|>


<commit_before>/* global NexT: true */

NexT.utils = NexT.$u = {
  /**
   * Wrap images with fancybox support.
   */
  wrapImageWithFancyBox: function () {
    $('.content img')
      .not('[hidden]')
      .not('.group-picture img, .post-gallery img')
      .each(function () {
        var $image = $(this);
        var imageTitle = $image.attr('title');
        var $imageWrapLink = $image.parent('a');

        if ($imageWrapLink.size() < 1) {
          $imageWrapLink = $image.wrap('').parent('a');
        }

        $imageWrapLink.addClass('fancybox fancybox.image');
        $imageWrapLink.attr('rel', 'group');

        if (imageTitle) {
          $imageWrapLink.append('
' + imageTitle + '
');

          //make sure img title tag will show correctly in fancybox
          $imageWrapLink.attr('title', imageTitle);
        }
      });

    $('.fancybox').fancybox({
      helpers: {
        overlay: {
          locked: false
        }
      }
    });
  },

  lazyLoadPostsImages: function () {
    $('#posts').find('img').lazyload({
      placeholder: '/images/loading.gif',
      effect: 'fadeIn'
    });
  },

  registerESCKeyEvent: function () {
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        $('.search-popup').hide();
        $('.search-popup-overlay').remove();
        $('body').css('overflow', '');
      }
    });
  },

  registerBackToTop: function () {
    var THRESHOLD = 50;
    var $top = $('.back-to-top');

    $(window).on('scroll', function () {
      $top.toggleClass('back-to-top-on', window.pageYOffset > THRESHOLD);

      var scrollTop = $(window).scrollTop();
      var docHeight = $('#content').height();
      var winHeight = $(window).height();
      var scrollPercent = (scrollTop) / (docHeight - winHeight);
      var scrollPercentRounded = Math.round(scrollPercent*100);
      var scrollPercentMaxed = (scrollPercentRounded > 100) ? 100 : scrollPercentRounded;
      $('#scrollpercent>span').html(scrollPercentMaxed);
    });

    $top.on('click', function () {
      $('body').velocity('scroll');
    });
  },

  /**
   * Transform embedded video to support responsive layout.
   * @see http://toddmotto.com/fluid-and-responsive-youtube-and-vimeo-videos-with-fluidvids-js/
   */
  embeddedVideoTransformer: function () {
    var $iframes = $('iframe');

    // Supported Players. Extend this if you need more players.
    var SUPPORTED_PLAYERS = [
      'www.youtube.com',
      'player.vimeo.com',
      'player.youku.com',
      'music.163.com',
      'www.tudou.com'
    ];
    var pattern = new RegExp( SUPPORTED_PLAYERS.join('|') );

    $iframes.each(function () {
      var iframe = this;
      var $iframe = $(this);
      var oldDimension = getDimension($iframe);
      var newDimension;

      if (this.src.search(pattern) > 0) {

        // Calculate the video ratio based on the iframe's w/h dimensions
        var videoRatio = getAspectRadio(oldDimension.width, oldDimension.height);

        // Replace the iframe's dimensions and position the iframe absolute
        // This is the trick to emulate the video ratio
        $iframe.width('100%').height('100%')
          .css({
            position: 'absolute',
            top: '0',
            left: '0'
          });

        // Wrap the iframe in a new
 which uses a dynamically fetched padding-top property
        // based on the video's w/h dimensions
        var wrap = document.createElement('div');
        wrap.className = 'fluid-vids';
        wrap.style.position = 'relative';
        wrap.style.marginBottom = '20px';
        wrap.style.width = '100%';
        wrap.style.paddingTop = videoRatio + '%';

        // Add the iframe inside our newly created

        var iframeParent = iframe.parentNode;
        iframeParent.insertBefore(wrap, iframe);
        wrap.appendChild(iframe);

        // Additional adjustments for 163 Music
        if (this.src.search('music.163.com') > 0) {
          newDimension = getDimension($iframe);
          var shouldRecalculateAspect = newDimension.width > oldDimension.width ||
                                        newDimension.height < oldDimension.height;

          // 163 Music Player has a fixed height, so we need to reset the aspect radio
          if (shouldRecalculateAspect) {
            wrap.style.paddingTop = getAspectRadio(newDimension.width, oldDimension.height) + '%';
          }
        }
      }
    });

    function getDimension($element) {
      return {
        width: $element.width(),
        height: $element.height()
      };
    }

    function getAspectRadio(width, height) {
      return height / width * 100;
    }
  },

  /**
   * Add `menu-item-active` class name to menu item
   * via comparing location.path with menu item's href.
   */
  addActiveClassToMenuItem: function () {
    var path = window.location.pathname;
    path = path === '/' ? path : path.substring(0, path.length - 1);
    $('.menu-item a[href="' + path + '"]').parent().addClass('menu-item-active');
  },

  hasMobileUA: function () {
    var nav = window.navigator;
    var ua = nav.userAgent;
    var pa = /iPad|iPhone|Android|Opera Mini|BlackBerry|webOS|UCWEB|Blazer|PSP|IEMobile|Symbian/g;

    return pa.test(ua);
  },

  isTablet: function () {
    return window.screen.width < 992 && window.screen.width > 767 && this.hasMobileUA();
  },

  isMobile: function () {
    return window.screen.width < 767 && this.hasMobileUA();
  },

  isDesktop: function () {
    return !this.isTablet() && !this.isMobile();
  },

  /**
   * Escape meta symbols in jQuery selectors.
   *
   * @param selector
   * @returns {string|void|XML|*}
   */
  escapeSelector: function (selector) {
    return selector.replace(/[!"$%&'()*+,.\/:;<=>?@[\\\]^`{|}~]/g, '\\$&');
  },

  displaySidebar: function () {
    if (!this.isDesktop() || this.isPisces()) {
      return;
    }
    $('.sidebar-toggle').trigger('click');
  },

  isMist: function () {
    return CONFIG.scheme === 'Mist';
  },

  isPisces: function () {
    return CONFIG.scheme === 'Pisces';
  },

  getScrollbarWidth: function () {
    var $div = $('
').addClass('scrollbar-measure').prependTo('body');
    var div = $div[0];
    var scrollbarWidth = div.offsetWidth - div.clientWidth;

    $div.remove();

    return scrollbarWidth;
  },

  /**
   * Affix behaviour for Sidebar.
   *
   * @returns {Boolean}
   */
  needAffix: function () {
    return this.isPisces();
  }
};
<commit_msg>FIX: invalid math of scroll percent. #1615<commit_after>/* global NexT: true */

NexT.utils = NexT.$u = {
  /**
   * Wrap images with fancybox support.
   */
  wrapImageWithFancyBox: function () {
    $('.content img')
      .not('[hidden]')
      .not('.group-picture img, .post-gallery img')
      .each(function () {
        var $image = $(this);
        var imageTitle = $image.attr('title');
        var $imageWrapLink = $image.parent('a');

        if ($imageWrapLink.size() < 1) {
          $imageWrapLink = $image.wrap('').parent('a');
        }

        $imageWrapLink.addClass('fancybox fancybox.image');
        $imageWrapLink.attr('rel', 'group');

        if (imageTitle) {
          $imageWrapLink.append('
' + imageTitle + '
');

          //make sure img title tag will show correctly in fancybox
          $imageWrapLink.attr('title', imageTitle);
        }
      });

    $('.fancybox').fancybox({
      helpers: {
        overlay: {
          locked: false
        }
      }
    });
  },

  lazyLoadPostsImages: function () {
    $('#posts').find('img').lazyload({
      placeholder: '/images/loading.gif',
      effect: 'fadeIn'
    });
  },

  registerESCKeyEvent: function () {
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        $('.search-popup').hide();
        $('.search-popup-overlay').remove();
        $('body').css('overflow', '');
      }
    });
  },

  registerBackToTop: function () {
    var THRESHOLD = 50;
    var $top = $('.back-to-top');

    $(window).on('scroll', function () {
      $top.toggleClass('back-to-top-on', window.pageYOffset > THRESHOLD);

      var scrollTop = $(window).scrollTop();
      var docHeight = $('#content').height();
      var winHeight = $(window).height();
      var contentMath = (docHeight > winHeight) ? (docHeight - winHeight) : ($(document).height() - winHeight);
      var scrollPercent = (scrollTop) / (contentMath);
      var scrollPercentRounded = Math.round(scrollPercent*100);
      var scrollPercentMaxed = (scrollPercentRounded > 100) ? 100 : scrollPercentRounded;
      $('#scrollpercent>span').html(scrollPercentMaxed);
    });

    $top.on('click', function () {
      $('body').velocity('scroll');
    });
  },

  /**
   * Transform embedded video to support responsive layout.
   * @see http://toddmotto.com/fluid-and-responsive-youtube-and-vimeo-videos-with-fluidvids-js/
   */
  embeddedVideoTransformer: function () {
    var $iframes = $('iframe');

    // Supported Players. Extend this if you need more players.
    var SUPPORTED_PLAYERS = [
      'www.youtube.com',
      'player.vimeo.com',
      'player.youku.com',
      'music.163.com',
      'www.tudou.com'
    ];
    var pattern = new RegExp( SUPPORTED_PLAYERS.join('|') );

    $iframes.each(function () {
      var iframe = this;
      var $iframe = $(this);
      var oldDimension = getDimension($iframe);
      var newDimension;

      if (this.src.search(pattern) > 0) {

        // Calculate the video ratio based on the iframe's w/h dimensions
        var videoRatio = getAspectRadio(oldDimension.width, oldDimension.height);

        // Replace the iframe's dimensions and position the iframe absolute
        // This is the trick to emulate the video ratio
        $iframe.width('100%').height('100%')
          .css({
            position: 'absolute',
            top: '0',
            left: '0'
          });

        // Wrap the iframe in a new
 which uses a dynamically fetched padding-top property
        // based on the video's w/h dimensions
        var wrap = document.createElement('div');
        wrap.className = 'fluid-vids';
        wrap.style.position = 'relative';
        wrap.style.marginBottom = '20px';
        wrap.style.width = '100%';
        wrap.style.paddingTop = videoRatio + '%';

        // Add the iframe inside our newly created

        var iframeParent = iframe.parentNode;
        iframeParent.insertBefore(wrap, iframe);
        wrap.appendChild(iframe);

        // Additional adjustments for 163 Music
        if (this.src.search('music.163.com') > 0) {
          newDimension = getDimension($iframe);
          var shouldRecalculateAspect = newDimension.width > oldDimension.width ||
                                        newDimension.height < oldDimension.height;

          // 163 Music Player has a fixed height, so we need to reset the aspect radio
          if (shouldRecalculateAspect) {
            wrap.style.paddingTop = getAspectRadio(newDimension.width, oldDimension.height) + '%';
          }
        }
      }
    });

    function getDimension($element) {
      return {
        width: $element.width(),
        height: $element.height()
      };
    }

    function getAspectRadio(width, height) {
      return height / width * 100;
    }
  },

  /**
   * Add `menu-item-active` class name to menu item
   * via comparing location.path with menu item's href.
   */
  addActiveClassToMenuItem: function () {
    var path = window.location.pathname;
    path = path === '/' ? path : path.substring(0, path.length - 1);
    $('.menu-item a[href="' + path + '"]').parent().addClass('menu-item-active');
  },

  hasMobileUA: function () {
    var nav = window.navigator;
    var ua = nav.userAgent;
    var pa = /iPad|iPhone|Android|Opera Mini|BlackBerry|webOS|UCWEB|Blazer|PSP|IEMobile|Symbian/g;

    return pa.test(ua);
  },

  isTablet: function () {
    return window.screen.width < 992 && window.screen.width > 767 && this.hasMobileUA();
  },

  isMobile: function () {
    return window.screen.width < 767 && this.hasMobileUA();
  },

  isDesktop: function () {
    return !this.isTablet() && !this.isMobile();
  },

  /**
   * Escape meta symbols in jQuery selectors.
   *
   * @param selector
   * @returns {string|void|XML|*}
   */
  escapeSelector: function (selector) {
    return selector.replace(/[!"$%&'()*+,.\/:;<=>?@[\\\]^`{|}~]/g, '\\$&');
  },

  displaySidebar: function () {
    if (!this.isDesktop() || this.isPisces()) {
      return;
    }
    $('.sidebar-toggle').trigger('click');
  },

  isMist: function () {
    return CONFIG.scheme === 'Mist';
  },

  isPisces: function () {
    return CONFIG.scheme === 'Pisces';
  },

  getScrollbarWidth: function () {
    var $div = $('
').addClass('scrollbar-measure').prependTo('body');
    var div = $div[0];
    var scrollbarWidth = div.offsetWidth - div.clientWidth;

    $div.remove();

    return scrollbarWidth;
  },

  /**
   * Affix behaviour for Sidebar.
   *
   * @returns {Boolean}
   */
  needAffix: function () {
    return this.isPisces();
  }
};
<|endoftext|>


<commit_before>export default angular.module('AppEnums', [])
    .service('EnumsSvc', ($rootScope, $http, $location) => {
        'ngInject';
        var baseUrl = '/assets/data';
        if ($location.host.match('github.io')) {
            baseUrl = '/LunAppAngular' + baseUrl;
        }
        return {
            getCountries: (success, error) => {
                $http.get(`${baseUrl}/countries.json`).then(success, error);
            },

            getCities: (success, error) => {
                $http.get(`${baseUrl}/cities.json`).then(success, error);
            }
        }
    })
<commit_msg>fix build => EnumsSvc => relative url for data on github hosts<commit_after>export default angular.module('AppEnums', [])
    .service('EnumsSvc', ($rootScope, $http, $location) => {
        'ngInject';
        var baseUrl = '/assets/data';
        if ($location.host().match('github.io')) {
            baseUrl = '/LunAppAngular' + baseUrl;
        }
        return {
            getCountries: (success, error) => {
                $http.get(`${baseUrl}/countries.json`).then(success, error);
            },

            getCities: (success, error) => {
                $http.get(`${baseUrl}/cities.json`).then(success, error);
            }
        }
    })
<|endoftext|>


<commit_before>import React, { createElement } from 'react';
import FilterMonitor from 'redux-devtools-filter-actions';
import LogMonitor from 'redux-devtools-log-monitor';
import ChartMonitor from 'redux-devtools-chart-monitor';
import SliderMonitor from 'redux-slider-monitor';
import DiffMonitor from './DiffMonitor';

function getMonitor() {
  if (!location.hash) return LogMonitor;
  const monitorTypes = location.hash.substr(1).split('/');
  switch (monitorTypes[0]) {
    case 'SliderMonitor': return SliderMonitor;
    case 'ChartMonitor': return ChartMonitor;
    case 'DiffMonitor': return DiffMonitor;
    default: return LogMonitor;
  }
}

export default (props) => (
  <FilterMonitor {...props}>{createElement(getMonitor())}</FilterMonitor>
);
<commit_msg>Set `preserveScrollTop` to `false` for `LogMonitor`<commit_after>import React, { createElement } from 'react';
import FilterMonitor from 'redux-devtools-filter-actions';
import LogMonitor from 'redux-devtools-log-monitor';
import ChartMonitor from 'redux-devtools-chart-monitor';
import SliderMonitor from 'redux-slider-monitor';
import DiffMonitor from './DiffMonitor';

const monitorTypes = location.hash ? location.hash.substr(1).split('/') : {};

function getMonitor() {
  switch (monitorTypes[0]) {
    case 'SliderMonitor': return createElement(SliderMonitor);
    case 'ChartMonitor': return createElement(ChartMonitor);
    case 'DiffMonitor': return createElement(DiffMonitor);
    default: return createElement(LogMonitor, { preserveScrollTop: false });
  }
}

export default (props) => (
  <FilterMonitor {...props}>{getMonitor()}</FilterMonitor>
);
<|endoftext|>


<commit_before>$(document).ready(function(){
    //====================================
    //--------- Functions ----------------
    //====================================

    //= source/debounce.js

    //====================================
    //--------- Setting libs -------------
    //====================================

    //====================================
    //--------- Custom Scripts -----------
    //====================================

	//= source/map.js
	//= source/button-top.js
	//= source/modal.js

});
<commit_msg>fix code style<commit_after>$(document).ready(function(){
    //====================================
    //--------- Functions ----------------
    //====================================

    //= source/debounce.js

    //====================================
    //--------- Setting libs -------------
    //====================================

    //====================================
    //--------- Custom Scripts -----------
    //====================================

    //= source/map.js
    //= source/button-top.js
    //= source/modal.js

});
<|endoftext|>


<commit_before>define([
  'summernote/base/renderer'
], function (renderer) {

  $.fn.jui = function () {
    var arr = Array.prototype.slice.call(arguments, 0);
    var method = arr.shift();

    if (this[0].jui) {
      var juiInstance = this[0].jui;
      if (juiInstance[method]) {
        return juiInstance[method].apply(juiInstance, arr);
      } else {
        return juiInstance;
      }
    }
  };

  var editor = renderer.create('
');
  var toolbar = renderer.create('
');
  var editingArea = renderer.create('
');
  var codable = renderer.create('<textarea class="note-codable"/>');
  var editable = renderer.create('
');
  var statusbar = renderer.create([
    '
',
    '
',
    '
',
    '
',
    '
',
    '
',
    '
'
  ].join(''));

  var buttonGroup = renderer.create('
');
  var button = renderer.create('<button class="note-btn btn ">', function ($node, options) {
    if (options && options.tooltip) {
      $node.attr({
        title: options.tooltip
      });

      window.jui.create('ui.tooltip', $node, {
        position : 'bottom'
      });

    }

    if (options && options.data && options.data.toggle === 'dropdown') {
      $node.on('click', function () {
        var dropdown = $(this).closest('.btngroup').find('.dropdown')[0].jui;
        if (dropdown.type === 'show') {
          dropdown.hide();
        } else {
          dropdown.show();
        }
      });
    }
  });

  var dropdown = renderer.create('
', function ($node, options) {
    var markup = $.isArray(options.items) ? options.items.map(function (item) {
      return '
' + item + '
';
    }).join('') : options.items;

    if (markup && markup !== '') {
      markup = $('
').html(markup);
      $node.append(markup);
    }

    window.jui.create('ui.dropdown', $node);
  });

  var dropdownCheck = renderer.create('
', function ($node, options) {
    var markup = $.isArray(options.items) ? options.items.map(function (item) {
      return '
 ' + item + '
';
    }).join('') : options.items;

    if (markup && markup !== '') {
      markup = $('
').html(markup);
      $node.append(markup);
    }

    window.jui.create('ui.dropdown', $node);
  });

  var palette = renderer.create('
', function ($node, options) {
    var contents = [];
    for (var row = 0, rowSize = options.colors.length; row < rowSize; row++) {
      var eventName = options.eventName;
      var colors = options.colors[row];
      var buttons = [];
      for (var col = 0, colSize = colors.length; col < colSize; col++) {
        var color = colors[col];
        buttons.push([
          '<button type="button" class="note-color-btn"',
          'style="background-color:', color, '" ',
          'data-event="', eventName, '" ',
          'data-value="', color, '" ',
          'title="', color, '" ',
          'data-toggle="button" tabindex="-1"></button>'
        ].join(''));
      }
      contents.push('
' + buttons.join('') + '
');
    }
    $node.html(contents.join(''));

    window.jui.create('ui.tooltip', $node.find('.note-color-btn'), {
      position : 'bottom'
    });
  });

  var dialog = renderer.create('
', function ($node, options) {
    $node.html([
      (options.title ?
      '
' +
        '

' +
        '
' + options.title + '
' +
      '
' : ''
      )
    ].join(''));

    var $body = $('
').html(options.body);
    $node.append($body);

    if (options.footer) {
      var $footer = $('
').html(options.footer);
      $node.append($footer);
    }

    window.jui.create('uix.window', $node, {
      modal : true
    });

  });

  var ui = {
    editor: editor,
    toolbar: toolbar,
    editingArea: editingArea,
    codable: codable,
    editable: editable,
    statusbar: statusbar,
    buttonGroup: buttonGroup,
    button: button,
    dropdown: dropdown,
    dropdownCheck: dropdownCheck,
    palette: palette,
    dialog: dialog,

    createLayout: function ($note) {
      var $editor = ui.editor([
        ui.toolbar(),
        ui.editingArea([
          ui.codable(),
          ui.editable()
        ]),
        ui.statusbar()
      ]).render();

      $editor.insertAfter($note);

      return {
        note: $note,
        editor: $editor,
        toolbar: $editor.find('.note-toolbar'),
        editingArea: $editor.find('.note-editing-area'),
        editable: $editor.find('.note-editable'),
        codable: $editor.find('.note-codable'),
        statusbar: $editor.find('.note-statusbar')
      };
    }
  };
  return ui;
});
<commit_msg>fixed tooltip event<commit_after>define([
  'summernote/base/renderer'
], function (renderer) {

  $.fn.jui = function () {
    var arr = Array.prototype.slice.call(arguments, 0);
    var method = arr.shift();

    if (this[0].jui) {
      var juiInstance = this[0].jui;
      if (juiInstance[method]) {
        return juiInstance[method].apply(juiInstance, arr);
      } else {
        return juiInstance;
      }
    }
  };

  var editor = renderer.create('
');
  var toolbar = renderer.create('
');
  var editingArea = renderer.create('
');
  var codable = renderer.create('<textarea class="note-codable"/>');
  var editable = renderer.create('
');
  var statusbar = renderer.create([
    '
',
    '
',
    '
',
    '
',
    '
',
    '
',
    '
'
  ].join(''));

  var buttonGroup = renderer.create('
');
  var button = renderer.create('<button class="note-btn btn ">', function ($node, options) {
    if (options && options.tooltip) {
      $node.attr({
        title: options.tooltip
      });

      window.jui.create('ui.tooltip', $node, {
        position : 'bottom',
        showType : 'mouseenter',
        hideType : 'mouseleave'
      });

    }

    if (options && options.data && options.data.toggle === 'dropdown') {
      $node.on('click', function () {
        var dropdown = $(this).closest('.btngroup').find('.dropdown')[0].jui;
        if (dropdown.type === 'show') {
          dropdown.hide();
        } else {
          dropdown.show();
        }
      });
    }
  });

  var dropdown = renderer.create('
', function ($node, options) {
    var markup = $.isArray(options.items) ? options.items.map(function (item) {
      return '
' + item + '
';
    }).join('') : options.items;

    if (markup && markup !== '') {
      markup = $('
').html(markup);
      $node.append(markup);
    }

    window.jui.create('ui.dropdown', $node);
  });

  var dropdownCheck = renderer.create('
', function ($node, options) {
    var markup = $.isArray(options.items) ? options.items.map(function (item) {
      return '
 ' + item + '
';
    }).join('') : options.items;

    if (markup && markup !== '') {
      markup = $('
').html(markup);
      $node.append(markup);
    }

    window.jui.create('ui.dropdown', $node);
  });

  var palette = renderer.create('
', function ($node, options) {
    var contents = [];
    for (var row = 0, rowSize = options.colors.length; row < rowSize; row++) {
      var eventName = options.eventName;
      var colors = options.colors[row];
      var buttons = [];
      for (var col = 0, colSize = colors.length; col < colSize; col++) {
        var color = colors[col];
        buttons.push([
          '<button type="button" class="note-color-btn"',
          'style="background-color:', color, '" ',
          'data-event="', eventName, '" ',
          'data-value="', color, '" ',
          'title="', color, '" ',
          'data-toggle="button" tabindex="-1"></button>'
        ].join(''));
      }
      contents.push('
' + buttons.join('') + '
');
    }
    $node.html(contents.join(''));

    window.jui.create('ui.tooltip', $node.find('.note-color-btn'), {
      position : 'bottom',
      showType : 'mouseenter',
      hideType : 'mouseleave'
    });
  });

  var dialog = renderer.create('
', function ($node, options) {
    $node.html([
      (options.title ?
      '
' +
        '

' +
        '
' + options.title + '
' +
      '
' : ''
      )
    ].join(''));

    var $body = $('
').html(options.body);
    $node.append($body);

    if (options.footer) {
      var $footer = $('
').html(options.footer);
      $node.append($footer);
    }

    window.jui.create('uix.window', $node, {
      modal : true
    });

  });

  var ui = {
    editor: editor,
    toolbar: toolbar,
    editingArea: editingArea,
    codable: codable,
    editable: editable,
    statusbar: statusbar,
    buttonGroup: buttonGroup,
    button: button,
    dropdown: dropdown,
    dropdownCheck: dropdownCheck,
    palette: palette,
    dialog: dialog,

    createLayout: function ($note) {
      var $editor = ui.editor([
        ui.toolbar(),
        ui.editingArea([
          ui.codable(),
          ui.editable()
        ]),
        ui.statusbar()
      ]).render();

      $editor.insertAfter($note);

      return {
        note: $note,
        editor: $editor,
        toolbar: $editor.find('.note-toolbar'),
        editingArea: $editor.find('.note-editing-area'),
        editable: $editor.find('.note-editable'),
        codable: $editor.find('.note-codable'),
        statusbar: $editor.find('.note-statusbar')
      };
    }
  };
  return ui;
});
<|endoftext|>


<commit_before>$(function() {

  console.log('Ready *__*');
  d3.select("body")
    .append("p")
    .text("New paragraph!");

});

// filter data
// [filter condition]
// year: { start: START_YEAR, end: END_YEAR} -> { start: 2008, end: 2009}
// sex: ARRAY -> 0 (unknown), 1 (female), 2 (male)
// age: ARRAY -> 0 (unknown), 1 (<=18), 2 (19-35), 3 (36-55), 4 (>=56)
// alcohol: ARRAY -> 0 (unknown), 1 (no), 2 (yes)
// safety: ARRAY -> 0 (unknown), 1 (no), 2 (yes)
// vehicle: ARRAY -> 0 (unknown), 1 (no), 2 (motocycle), 3 (bicycle), 4 (car), 5 (pickup & truck)
// hitBy: ARRAY -> 0 (unknown), 1 (no), 2 (motocycle), 3 (bicycle), 4 (car), 5 (pickup & truck)
// time: {start: [DAY, HOUR], end: [DAY, HOUR]}
// [Ex]
// {year: [2008, 2015], sex: [1], alcohol: [1, 2], safety: [1], vehicle: [1, 2, 3], hitBy: [1]}
function genericMapper(value, mapper) {
  if (value in mapper) { return mapper[value]; }
  return -1;
}
function findMatchWithArrayFilter(arrayFilter, entry) {
  var bool = false;
  for (var i = 0, len = arrayFilter.length; i < len; ++i) {
    if (arrayFilter[i] === entry) {
      bool = true;
      break;
    }
  }
  return bool;
}
function timeWrapper(day, hour) {
  // Change to int.
  day = parseInt(day); hour = parseInt(hour);
  // Transform both to one time variable.
  day = (day > 20)? (day - 31) : day;
  hour = (hour === 24)? 0 : hour;
  var time = day * 24 + hour;
  return time;
}

function filterUtil(data, filter) {
  // Check if all filters are specified. If not, error and return empty array.
  if (!(filter.year && filter.year.start && filter.year.end &&
        filter.time && filter.time.start && filter.time.end &&
        filter.sex &&
        filter.alcohol &&
        filter.safety &&
        filter.vehicle &&
        filter.hitBy)) {
    console.error('Please specify all filters. For now, we will just return empty result for you.');
    return [];
  }
  var result = data.filter(function(d) {
    var sex_map = {'unknown' : 0, 'หญิง' : 1, 'ชาย' : 2};
    var alcohol_map = {'unknown' : 0, 'ไม่ดื่ม' : 1, 'ดื่ม' : 2};
    var safety_map = {'unknown' : 0, 'ไม่ใส่' : 1, 'ใส่หมวก' : 2, 'เข็มขัด' : 2};
    var vehicle_map = {
      'unknown' : 0, 'อื่นๆ' : 0,
      'ไม่มี/ล้มเอง' : 1,
      'จักรยานยนต์' : 2,
      'รถจักรยาน' : 3,
      'รถเก๋ง/แท็กซี่' : 4, 'สามล้อเครื่อง' : 4, 'รถตู้' : 4, 'รถโดยสาร 4 ล้อ' : 4,
      'รถบรรทุก' : 5, 'รถโดยสารใหญ่' : 5, 'ปิคอัพ' : 5,
    };
    var time = timeWrapper(d['วันที่เกิดเหตุ'], d['เวลาเกิดเหตุ']);
    var time_filter_start = timeWrapper(filter.time.start[0], filter.time.start[1]);
    var time_filter_end = timeWrapper(filter.time.end[0], filter.time.end[1]);
    var time_filter = (time >= time_filter_start) && (time <= time_filter_end);
    var year_filter = (d.year >= filter.year.start) && (d.year <= filter.year.end);
    var sex_filter = findMatchWithArrayFilter(filter.sex, genericMapper(d['เพศ'], sex_map));
    var alcohol_filter = findMatchWithArrayFilter(filter.alcohol, genericMapper(d['การดื่มสุรา'], alcohol_map));
    var safety_filter = findMatchWithArrayFilter(filter.safety, genericMapper(d['มาตรการ'], safety_map));
    var vehicle_filter = findMatchWithArrayFilter(filter.vehicle, genericMapper(d['รถผู้บาดเจ็บ'], vehicle_map));
    var hitBy_filter = findMatchWithArrayFilter(filter.hitBy, genericMapper(d['รถคู่กรณี'], vehicle_map));
    // console.log(d);
    // console.log("year: " + year_filter +
    //   " time: " + time + " " + time_filter_start + " " + time_filter_end +
    //   " time reult: " + time_filter +
    //   " sex: " + sex_filter +
    //   " alcohol: " + alcohol_filter +
    //   " safety: " + safety_filter +
    //   " vehicle: " + vehicle_filter +
    //   " hitBy: " + hitBy_filter);
    return year_filter && time_filter && sex_filter && alcohol_filter && safety_filter && vehicle_filter && hitBy_filter;
  });
  return result;
}

function prefilterUtil(data) {
  var result = {};
  for (var i = 0, len = data.length; i < len; ++i) {
    var day = parseInt(day), hour = parseInt(hour);
    hour = (hour === 24)? 0 : hour;
    if (!(day in result)){
      result[day] = {};
    }
    if (!(hour in result[day])) {
      result[day][hour] = [];
    }
    result[day][hour] = data[i];
  }
  return result;
}

//   // Global var for all loaded .csv data
//   var dataset;

//   d3.csv("/public/data/175_samples_all_newyear_casualties.csv", function(error, data) {
//     if (error) { // when data is failed to load, do nothing.
//       console.error(error);
//     } else {
//       // data is loaded successfully, we can start to visualize it.
//       dataset = data;
//       console.log("original");
//       console.log(data);
//       // call other functions here
//       console.log("after filter");
//       var myfilter = {
//         year: {start: 2008, end: 2009},
//         time: {start: [28, 0], end: [1, 1]},
//         sex: [1],
//         alcohol: [1],
//         safety: [1],
//         vehicle: [2],
//         hitBy: [1,2,3,4,5],
//       };
//       console.log(filterUtil(data, myfilter));
//     }
//   });

<commit_msg>Fix wrong day and hour values<commit_after>$(function() {

  console.log('Ready *__*');
  d3.select("body")
    .append("p")
    .text("New paragraph!");

});

// filter data
// [filter condition]
// year: { start: START_YEAR, end: END_YEAR} -> { start: 2008, end: 2009}
// sex: ARRAY -> 0 (unknown), 1 (female), 2 (male)
// age: ARRAY -> 0 (unknown), 1 (<=18), 2 (19-35), 3 (36-55), 4 (>=56)
// alcohol: ARRAY -> 0 (unknown), 1 (no), 2 (yes)
// safety: ARRAY -> 0 (unknown), 1 (no), 2 (yes)
// vehicle: ARRAY -> 0 (unknown), 1 (no), 2 (motocycle), 3 (bicycle), 4 (car), 5 (pickup & truck)
// hitBy: ARRAY -> 0 (unknown), 1 (no), 2 (motocycle), 3 (bicycle), 4 (car), 5 (pickup & truck)
// time: {start: [DAY, HOUR], end: [DAY, HOUR]}
// [Ex]
// {year: [2008, 2015], sex: [1], alcohol: [1, 2], safety: [1], vehicle: [1, 2, 3], hitBy: [1]}
function genericMapper(value, mapper) {
  if (value in mapper) { return mapper[value]; }
  return -1;
}
function findMatchWithArrayFilter(arrayFilter, entry) {
  var bool = false;
  for (var i = 0, len = arrayFilter.length; i < len; ++i) {
    if (arrayFilter[i] === entry) {
      bool = true;
      break;
    }
  }
  return bool;
}
function timeWrapper(day, hour) {
  // Change to int.
  day = parseInt(day); hour = parseInt(hour);
  // Transform both to one time variable.
  day = (day > 20)? (day - 31) : day;
  hour = (hour === 24)? 0 : hour;
  var time = day * 24 + hour;
  return time;
}

function filterUtil(data, filter) {
  // Check if all filters are specified. If not, error and return empty array.
  if (!(filter.year && filter.year.start && filter.year.end &&
        filter.time && filter.time.start && filter.time.end &&
        filter.sex &&
        filter.alcohol &&
        filter.safety &&
        filter.vehicle &&
        filter.hitBy)) {
    console.error('Please specify all filters. For now, we will just return empty result for you.');
    return [];
  }
  var result = data.filter(function(d) {
    var sex_map = {'unknown' : 0, 'หญิง' : 1, 'ชาย' : 2};
    var alcohol_map = {'unknown' : 0, 'ไม่ดื่ม' : 1, 'ดื่ม' : 2};
    var safety_map = {'unknown' : 0, 'ไม่ใส่' : 1, 'ใส่หมวก' : 2, 'เข็มขัด' : 2};
    var vehicle_map = {
      'unknown' : 0, 'อื่นๆ' : 0,
      'ไม่มี/ล้มเอง' : 1,
      'จักรยานยนต์' : 2,
      'รถจักรยาน' : 3,
      'รถเก๋ง/แท็กซี่' : 4, 'สามล้อเครื่อง' : 4, 'รถตู้' : 4, 'รถโดยสาร 4 ล้อ' : 4,
      'รถบรรทุก' : 5, 'รถโดยสารใหญ่' : 5, 'ปิคอัพ' : 5,
    };
    var time = timeWrapper(d['วันที่เกิดเหตุ'], d['เวลาเกิดเหตุ']);
    var time_filter_start = timeWrapper(filter.time.start[0], filter.time.start[1]);
    var time_filter_end = timeWrapper(filter.time.end[0], filter.time.end[1]);
    var time_filter = (time >= time_filter_start) && (time <= time_filter_end);
    var year_filter = (d.year >= filter.year.start) && (d.year <= filter.year.end);
    var sex_filter = findMatchWithArrayFilter(filter.sex, genericMapper(d['เพศ'], sex_map));
    var alcohol_filter = findMatchWithArrayFilter(filter.alcohol, genericMapper(d['การดื่มสุรา'], alcohol_map));
    var safety_filter = findMatchWithArrayFilter(filter.safety, genericMapper(d['มาตรการ'], safety_map));
    var vehicle_filter = findMatchWithArrayFilter(filter.vehicle, genericMapper(d['รถผู้บาดเจ็บ'], vehicle_map));
    var hitBy_filter = findMatchWithArrayFilter(filter.hitBy, genericMapper(d['รถคู่กรณี'], vehicle_map));
    // console.log(d);
    // console.log("year: " + year_filter +
    //   " time: " + time + " " + time_filter_start + " " + time_filter_end +
    //   " time reult: " + time_filter +
    //   " sex: " + sex_filter +
    //   " alcohol: " + alcohol_filter +
    //   " safety: " + safety_filter +
    //   " vehicle: " + vehicle_filter +
    //   " hitBy: " + hitBy_filter);
    return year_filter && time_filter && sex_filter && alcohol_filter && safety_filter && vehicle_filter && hitBy_filter;
  });
  return result;
}

function prefilterUtil(data) {
  var result = {};
  for (var i = 0, len = data.length; i < len; ++i) {
    var day = parseInt(data[i]['วันที่เกิดเหตุ']);
    var hour = parseInt(data[i]['เวลาเกิดเหตุ']);
    hour = (hour === 24)? 0 : hour;
    if (!(day in result)){
      result[day] = {};
    }
    if (!(hour in result[day])) {
      result[day][hour] = [];
    }
    result[day][hour] = data[i];
  }
  return result;
}

//   // Global var for all loaded .csv data
//   var dataset;

//   d3.csv("/public/data/175_samples_all_newyear_casualties.csv", function(error, data) {
//     if (error) { // when data is failed to load, do nothing.
//       console.error(error);
//     } else {
//       // data is loaded successfully, we can start to visualize it.
//       dataset = data;
//       console.log("original");
//       console.log(data);
//       // call other functions here
//       console.log("after filter");
//       var myfilter = {
//         year: {start: 2008, end: 2009},
//         time: {start: [28, 0], end: [1, 1]},
//         sex: [1],
//         alcohol: [1],
//         safety: [1],
//         vehicle: [2],
//         hitBy: [1,2,3,4,5],
//       };
//       console.log(filterUtil(data, myfilter));
//     }
//   });

<|endoftext|>


<commit_before>/*!
 * Innovare.Map.Main JavaScript Library v0.1
 * https://github.com/innova-re/map
 *
 * Copyright 2014, Antonio Pierro
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * References:
 * - https://www.youtube.com/playlist?list=PLcUid3OP_4OVX8zp-ZTcyOsp6C9CJCqd0
 * - http://www.html5canvastutorials.com/labs/html5-canvas-interactive-building-map/
 * - http://mrdoob.com/projects/voxels/#A/
 * - https://threejsdoc.appspot.com/doc/index.html#CubeGeometry
 */
(function (window, $, THREE, PI, requestAnimationFrame) {
	'use strict';

	var Building = function () {
		this.innerWidth = window.innerWidth;
		this.innerHeight = window.innerHeight;
		this.planeVertex = 100;
		this.floorHeight = 17;
		this.renderer = this.getRenderer();
		this.camera = this.getCamera();
		this.scene = this.getScene();
		this.plane = this.getPlane();
		this.cubeVertex = this.planeVertex * 0.5;
		this.cube = this.getCube(this.cubeVertex);
		this.cube2 = this.getCube(this.cubeVertex);
		this.cube3 = this.getCube(this.cubeVertex);
		this.cube4 = this.getCube(this.cubeVertex * 0.4, {
			opacity: 0.9,
			color: 'red'
		});
		this.controls = new THREE.OrbitControls(this.camera, this.renderer.domElement);
	};

	Building.prototype = {

		constructor: Building,

		init: function () {
			this.setSize();
			this.addObjects();
			this.setAxisHelper();
			this.setPosiotions();
			this.animate();
			window.t = this;
			window.building = this;
			this.renderer.domElement.addEventListener( 'click', function() {console.log(this)}, false );
		},

		addObjects: function () {
			$('body').append(this.renderer.domElement);
			this.scene.add(this.plane);
			this.scene.add(this.cube);
			this.scene.add(this.cube2);
			this.scene.add(this.cube3);
			this.scene.add(this.cube4);
			new THREE.Stair(this.scene, {
				x: this.cubeVertex / 2,
				z: -this.cubeVertex / 2,
				y: 0,
				height: this.floorHeight - 2
			});
			new THREE.Stair(this.scene, {
				x: -this.cubeVertex / 2,
				z: -this.cubeVertex / 2,
				y:0,
				height: this.floorHeight - 2
			});
			new THREE.Stair(this.scene, {
				x: -this.cubeVertex / 2,
				z: -this.cubeVertex / 2,
				y: this.floorHeight,
				height: this.floorHeight * 2
			});
			new THREE.Stair(this.scene, {
				x: this.cubeVertex / 2,
				z: -this.cubeVertex / 2,
				y: this.floorHeight,
				height: this.floorHeight * 2
			});
		},

		animate: function () {
			this.renderer.render(this.scene, this.camera);
			requestAnimationFrame($.proxy(this.animate, this));
		},

		getCamera: function () {
			return new THREE.PerspectiveCamera(60, this.innerWidth / this.innerHeight, 0.1, 20000 );
		},

		getCube: function (vertex, material) {
			var material = material || {
				color: '#' + Math.floor(Math.random()*16777215).toString(16),
				opacity: 0.5,
				transparent: true
			};
			return new THREE.Mesh(
				new THREE.BoxGeometry(vertex, this.floorHeight, vertex),
				new THREE.LineBasicMaterial(material)
			);
		},

		getPlane: function () {
			return new THREE.Mesh(
				new THREE.PlaneGeometry(this.planeVertex, this.planeVertex, 10, 10),
				new THREE.MeshBasicMaterial({ color: 0x7f7f7f, wireframe: true })
			);
		},

		getRadians: function (degrees) {
			return degrees * PI / 180;
		},

		getRenderer: function () {
			return new THREE.WebGLRenderer({
				shadowMapEnabled: true,
				antialias: true
			});
		},

		getScene: function () {
			return new THREE.Scene();
		},

		/*
		 * An axis object to visualize the the 3 axes in a simple way.
		 * The X axis is red. The Y axis is green. The Z axis is blue.
		*/
		setAxisHelper: function () {
			this.scene.add(new THREE.AxisHelper(this.planeVertex));
		},

		setPosiotions: function () {
			this.camera.position.set(0, 0, this.planeVertex * 1.5);
			this.plane.rotation.set(this.getRadians(90), 0, 0);
			this.cube.position.y = this.floorHeight * 0.5;
			this.cube2.position.y = this.floorHeight * 1.5;
			this.cube3.position.y = this.floorHeight * 2.5;
			this.cube4.position.y = this.floorHeight * 2.5;
			this.cube4.position.x = this.cubeVertex / 3;
			this.cube4.position.z = this.cubeVertex / 3.5;
		},

		setSize: function () {
			this.renderer.setSize(this.innerWidth, this.innerHeight);
			this.renderer.setClearColor(0xffffff, 1);
		}
	};

	$(function () {
		var building = new Building();

		building.init();
	});

})(this, this.jQuery, this.THREE, this.Math.PI, this.requestAnimationFrame);
<commit_msg>removed useless variables<commit_after>/*!
 * Innovare.Map.Main JavaScript Library v0.1
 * https://github.com/innova-re/map
 *
 * Copyright 2014, Antonio Pierro
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * References:
 * - https://www.youtube.com/playlist?list=PLcUid3OP_4OVX8zp-ZTcyOsp6C9CJCqd0
 * - http://www.html5canvastutorials.com/labs/html5-canvas-interactive-building-map/
 * - http://mrdoob.com/projects/voxels/#A/
 * - https://threejsdoc.appspot.com/doc/index.html#CubeGeometry
 */
(function (window, $, THREE, PI, requestAnimationFrame) {
	'use strict';

	var Building = function () {
		this.innerWidth = window.innerWidth;
		this.innerHeight = window.innerHeight;
		this.planeVertex = 100;
		this.floorHeight = 17;
		this.cubeVertex = this.planeVertex * 0.5;
		this.renderer = this.getRenderer();
		this.camera = this.getCamera();
		this.scene = this.getScene();
		this.plane = this.getPlane();
		this.cube = this.getCube(this.cubeVertex);
		this.cube2 = this.getCube(this.cubeVertex);
		this.cube3 = this.getCube(this.cubeVertex);
		this.cube4 = this.getCube(this.cubeVertex * 0.4, {
			opacity: 0.9,
			color: 'red'
		});
		this.controls = new THREE.OrbitControls(this.camera, this.renderer.domElement);
	};

	Building.prototype = {

		constructor: Building,

		init: function () {
			this.setSize();
			this.addObjects();
			this.setAxisHelper();
			this.setPosiotions();
			this.animate();
			window.t = this;
			window.building = this;
			this.renderer.domElement.addEventListener( 'click', function() {console.log(this)}, false );
		},

		addObjects: function () {
			$('body').append(this.renderer.domElement);
			this.scene.add(this.plane);
			this.scene.add(this.cube);
			this.scene.add(this.cube2);
			this.scene.add(this.cube3);
			this.scene.add(this.cube4);
			new THREE.Stair(this.scene, {
				x: this.cubeVertex / 2,
				z: -this.cubeVertex / 2,
				y: 0,
				height: this.floorHeight - 2
			});
			new THREE.Stair(this.scene, {
				x: -this.cubeVertex / 2,
				z: -this.cubeVertex / 2,
				y:0,
				height: this.floorHeight - 2
			});
			new THREE.Stair(this.scene, {
				x: this.cubeVertex / 2,
				z: -this.cubeVertex / 2,
				y: this.floorHeight,
				height: this.floorHeight * 2
			});
		},

		animate: function () {
			this.renderer.render(this.scene, this.camera);
			requestAnimationFrame($.proxy(this.animate, this));
		},

		getCamera: function () {
			return new THREE.PerspectiveCamera(60, this.innerWidth / this.innerHeight, 0.1, 20000 );
		},

		getCube: function (vertex, material) {
			var material = material || {
				color: '#' + Math.floor(Math.random()*16777215).toString(16),
				opacity: 0.5,
				transparent: true
			};
			return new THREE.Mesh(
				new THREE.BoxGeometry(vertex, this.floorHeight, vertex),
				new THREE.LineBasicMaterial(material)
			);
		},

		getPlane: function () {
			return new THREE.Mesh(
				new THREE.PlaneGeometry(this.planeVertex, this.planeVertex, 10, 10),
				new THREE.MeshBasicMaterial({ color: 0x7f7f7f, wireframe: true })
			);
		},

		getRadians: function (degrees) {
			return degrees * PI / 180;
		},

		getRenderer: function () {
			return new THREE.WebGLRenderer({
				shadowMapEnabled: true,
				antialias: true
			});
		},

		getScene: function () {
			return new THREE.Scene();
		},

		/*
		 * An axis object to visualize the the 3 axes in a simple way.
		 * The X axis is red. The Y axis is green. The Z axis is blue.
		*/
		setAxisHelper: function () {
			this.scene.add(new THREE.AxisHelper(this.planeVertex));
		},

		setPosiotions: function () {
			this.camera.position.set(0, 0, this.planeVertex * 1.5);
			this.plane.rotation.set(this.getRadians(90), 0, 0);
			this.cube.position.y = this.floorHeight * 0.5;
			this.cube2.position.y = this.floorHeight * 1.5;
			this.cube3.position.y = this.floorHeight * 2.5;
			this.cube4.position.y = this.floorHeight * 2.5;
			this.cube4.position.x = this.cubeVertex / 3;
			this.cube4.position.z = this.cubeVertex / 3.5;
		},

		setSize: function () {
			this.renderer.setSize(this.innerWidth, this.innerHeight);
			this.renderer.setClearColor(0xffffff, 1);
		}
	};

	$(function () {
		var building = new Building();

		building.init();
	});

})(this, this.jQuery, this.THREE, this.Math.PI, this.requestAnimationFrame);
<|endoftext|>


<commit_before>
/**
 * Object represent the abstract class of all UI Objects.
 * @abstract
 * @name Object
 * @class Object
 * @memberOf ch
 * @requires ch.Get
 * @requires ch.Factory
 * @see ch.Controllers
 * @see ch.Floats
 * @see ch.Navs
 * @see ch.Watcher
 */

ch.object = function(){

    /**
     * Reference to a internal component instance, saves all the information and configuration properties.
     * @private
     * @name that
     * @type {Object}
     * @memberOf ch.Object
     */
	var that = this;
	var conf = that.conf;

/**
 *  Public Members
 */
	that.prevent = function(event) {
		if (event && typeof event == "object") {
		    event.preventDefault();
			event.stopPropagation();
		};

		return that;
	};

	//TODO: Analizar si unificar that.content (get and set) con that.loadContent(load).
	that.content = function(content){

		if ( content === undefined ) {

			var content = conf.content || conf.msg;
			return (content) ? (( ch.utils.isSelector(content) ) ? $(content) : content) : ((conf.ajax === true) ? (that.$trigger.attr('href') || that.$trigger.parents('form').attr('action')) : conf.ajax );

		} else {

			var cache = conf.cache;

			conf.cache = false;

			if ( ch.utils.isUrl(content) ) {
				conf.content = undefined;
				conf.ajax = content;
			} else {
				conf.ajax = false;
				conf.content = content;
			};

			that.$content.html(that.loadContent());
			that.position("refresh");

			conf.cache = cache;

			return that["public"];
		};

	};

	that.loadContent = function() {
		// TODO: Properties validation
		//if( self.ajax && (self.content || self.msg) ) { alert('CH: "Ajax" and "Content" can\'t live together.'); return; };

		if( conf.ajax === true){

			// Load URL from href or form action
			conf.ajaxUrl = that.$element.attr('href') || that.$element.parents('form').attr('action');

			// Ajax parameters
			conf.ajaxParams = 'x=x'; // TODO refactor con el header de ajax

			// If trigger is a form button...
			if(that.$element.attr('type') == 'submit'){
				conf.ajaxType = that.$element.parents('form').attr('method') || 'GET';
				var serialized = that.$element.parents('form').serialize();
				conf.ajaxParams = conf.ajaxParams + ((serialized != '') ? '&' + serialized : '');
			};

			// Returns ajax results

			ch.get({method:"content", that:that});

			return '

';

		} else if ( conf.ajax || (conf.msg && ch.utils.isUrl(conf.msg)) ){
			// Set url
			conf.ajaxUrl = conf.ajax || conf.msg;

			// Ajax parameters
			conf.ajaxParams = 'x=x'; // TODO refactor con el header de ajax

			// Returns ajax results

			ch.get({method:"content", that:that});
			return '

';

		} else {
			var content = conf.content || conf.msg;
			return ( ch.utils.isSelector(content) ) ? $(content).detach().clone().removeClass("ch-hide").show() : content;
		};

	};

	that.callbacks = function(when){
		if( ch.utils.hasOwn(conf, when) ) {
			var context = ( that.controller ) ? that.controller["public"] : that["public"];
			return conf[when].call( context );
		};
	};

	that.position = function(o){

		switch(typeof o) {

			case "object":
				conf.position.context = o.context || conf.position.context;
				conf.position.points = o.points || conf.position.points;
				conf.position.offset = o.offset || conf.position.offset;
				conf.position.fixed = o.fixed || conf.position.fixed;

				ch.positioner(conf.position);
				return that["public"];
				break;

			case "string":
				if(o != "refresh"){
					alert("ChicoUI error: position() expected to find \"refresh\" parameter.");
				};

				ch.positioner(conf.position);
				return that["public"];
				break;

			case "undefined":
				return conf.position;
			    break;
		};

	};

 	that["public"] = {};

	return that;
};
<commit_msg>Add more inteligence to .content on object.js<commit_after>
/**
 * Object represent the abstract class of all UI Objects.
 * @abstract
 * @name Object
 * @class Object
 * @memberOf ch
 * @requires ch.Get
 * @requires ch.Factory
 * @see ch.Controllers
 * @see ch.Floats
 * @see ch.Navs
 * @see ch.Watcher
 */

ch.object = function(){

    /**
     * Reference to a internal component instance, saves all the information and configuration properties.
     * @private
     * @name that
     * @type {Object}
     * @memberOf ch.Object
     */
	var that = this;
	var conf = that.conf;

/**
 *  Public Members
 */
	that.prevent = function(event) {
		if (event && typeof event == "object") {
		    event.preventDefault();
			event.stopPropagation();
		};

		return that;
	};

	//TODO: Analizar si unificar that.content (get and set) con that.loadContent(load).
	that.content = function(content){

		if ( content === undefined ) {

			var content = conf.content || conf.msg;
			return (content) ? (( ch.utils.isSelector(content) ) ? $(content) : content) : ((conf.ajax === true) ? (that.$trigger.attr('href') || that.$trigger.parents('form').attr('action')) : conf.ajax );

		} else {

			var cache = conf.cache;

			conf.cache = false;

			if ( ch.utils.isUrl(content) ) {
				conf.content = undefined;
				conf.ajax = content;
			} else {
				conf.ajax = false;
				conf.content = content;
			};

			if ( ch.utils.hasOwn(that, "$content") ) {
				that.$content.html(that.loadContent());
				that.position("refresh");
			};

			conf.cache = cache;

			return that["public"];
		};

	};

	that.loadContent = function() {
		// TODO: Properties validation
		//if( self.ajax && (self.content || self.msg) ) { alert('CH: "Ajax" and "Content" can\'t live together.'); return; };

		if( conf.ajax === true){

			// Load URL from href or form action
			conf.ajaxUrl = that.$element.attr('href') || that.$element.parents('form').attr('action');

			// Ajax parameters
			conf.ajaxParams = 'x=x'; // TODO refactor con el header de ajax

			// If trigger is a form button...
			if(that.$element.attr('type') == 'submit'){
				conf.ajaxType = that.$element.parents('form').attr('method') || 'GET';
				var serialized = that.$element.parents('form').serialize();
				conf.ajaxParams = conf.ajaxParams + ((serialized != '') ? '&' + serialized : '');
			};

			// Returns ajax results

			ch.get({method:"content", that:that});

			return '

';

		} else if ( conf.ajax || (conf.msg && ch.utils.isUrl(conf.msg)) ){
			// Set url
			conf.ajaxUrl = conf.ajax || conf.msg;

			// Ajax parameters
			conf.ajaxParams = 'x=x'; // TODO refactor con el header de ajax

			// Returns ajax results

			ch.get({method:"content", that:that});
			return '

';

		} else {
			var content = conf.content || conf.msg;
			return ( ch.utils.isSelector(content) ) ? $(content).detach().clone().removeClass("ch-hide").show() : content;
		};

	};

	that.callbacks = function(when){
		if( ch.utils.hasOwn(conf, when) ) {
			var context = ( that.controller ) ? that.controller["public"] : that["public"];
			return conf[when].call( context );
		};
	};

	that.position = function(o){

		switch(typeof o) {

			case "object":
				conf.position.context = o.context || conf.position.context;
				conf.position.points = o.points || conf.position.points;
				conf.position.offset = o.offset || conf.position.offset;
				conf.position.fixed = o.fixed || conf.position.fixed;

				ch.positioner(conf.position);
				return that["public"];
				break;

			case "string":
				if(o != "refresh"){
					alert("ChicoUI error: position() expected to find \"refresh\" parameter.");
				};

				ch.positioner(conf.position);
				return that["public"];
				break;

			case "undefined":
				return conf.position;
			    break;
		};

	};

 	that["public"] = {};

	return that;
};
<|endoftext|>


<commit_before>(function() {
  'use strict';

  function Player(game, x, y, health, cursors) {
    Phaser.Sprite.call(this, game, x, y, 'player');
    this.cursors = cursors;
    this.sprintKey = game.input.keyboard.addKey(Phaser.Keyboard.SHIFT);
    this.scale.setTo(0.25,0.25);
    this.game   = game;
    this.health = health;
    this.anchor.setTo(0.5, 0.5);
    this.animations.add('walk-left', [8,9,10,11], 10, true);
    this.animations.add('walk-right', [12,13,14,15], 10, true);
    this.animations.add('walk-up', [0,1,2,3], 10, true);
    this.animations.add('walk-down', [4,5,6,7], 10, true);
    this.body.collideWorldBounds = true;
    this.stamina = 50;
    this.currBreath = this.stamina;
  }

  Player.prototype = Object.create(Phaser.Sprite.prototype);

  Player.prototype.update = function() {
    this.body.velocity.setTo(0,0);
     if (this.cursors.up.isDown) {
        this.body.velocity.y = -100;
        this.animations.play('walk-up');
      }
      if (this.cursors.left.isDown) {
        this.body.velocity.x = -100;
        this.animations.play('walk-left');
      }
      if (this.cursors.right.isDown) {
        this.body.velocity.x = 100;
        this.animations.play('walk-right');
      }
      if (this.cursors.down.isDown) {
        this.body.velocity.y = 100;
        this.animations.play('walk-down');
      }

      if(this.sprintKey.isDown && this.currBreath > 1) {
        this.body.velocity.multiply(2,2);
        this.currBreath--;
      } else if (this.currBreath < this.stamina) {
        this.currBreath += 0.2;
      }
  };

  window.Darwinator = window.Darwinator || {};
  window.Darwinator.Player = Player;

}());<commit_msg>Player animation now correcly stop when not moving<commit_after>(function() {
  'use strict';

  function Player(game, x, y, health, cursors) {
    Phaser.Sprite.call(this, game, x, y, 'player');
    this.cursors = cursors;
    this.sprintKey = game.input.keyboard.addKey(Phaser.Keyboard.SHIFT);
    this.scale.setTo(0.25,0.25);
    this.game   = game;
    this.health = health;
    this.anchor.setTo(0.5, 0.5);
    this.animations.add('walk-left', [8,9,10,11], 10, true);
    this.animations.add('walk-right', [12,13,14,15], 10, true);
    this.animations.add('walk-up', [0,1,2,3], 10, true);
    this.animations.add('walk-down', [4,5,6,7], 10, true);
    this.body.collideWorldBounds = true;
    this.stamina = 50;
    this.currBreath = this.stamina;
  }

  Player.prototype = Object.create(Phaser.Sprite.prototype);

  Player.prototype.update = function() {
    this.body.velocity.setTo(0,0);
     if (this.cursors.up.isDown) {
        this.body.velocity.y = -100;
        this.animations.play('walk-up');
      } else if (this.cursors.left.isDown) {
        this.body.velocity.x = -100;
        this.animations.play('walk-left');
      } else if (this.cursors.right.isDown) {
        this.body.velocity.x = 100;
        this.animations.play('walk-right');
      } else if (this.cursors.down.isDown) {
        this.body.velocity.y = 100;
        this.animations.play('walk-down');
      } else {
        this.animations.stop();
        this.body.frame = 4;
      }

      if(this.sprintKey.isDown && this.currBreath > 1) {
        this.body.velocity.multiply(2,2);
        this.currBreath--;
      } else if (this.currBreath < this.stamina) {
        this.currBreath += 0.2;
      }
  };

  window.Darwinator = window.Darwinator || {};
  window.Darwinator.Player = Player;

}());<|endoftext|>


<commit_before>/*
---
description: Code parsing engine for Lighter.

license: MIT-style

authors:
- Jose Prado

requires:
  core/1.2.4: '*'

provides: [Parser]

...
*/
(function(){

var Parser = this.Parser = new Class({

    /**
     * @constructs
     * @param {Fuel} fuel The fuel to use for parsing.
     */
    initialize: function(fuel)
    {
        this.fuel = fuel;
    },

    /**
     * Parses source code using fuel regex rules and returns the array of
     * tokens.
     *
     * @param {String} code     The source code to parse.
     * @param {Number} [offset] Optional offset to add to the found index.
     */
    parse: function(code, offset)
    {
        var wicks = this._parse(code, offset),
            text  = null,
            wick  = null;

        for (var i = 0, pointer = 0; i < wicks.length; i++) {
            if (pointer < wicks[i].index) {
                text = code.substring(pointer, wicks[i].index)
                wick = new Wick(text, 'unknown', pointer);
                wicks.splice(i, 0, wick);
            }
            pointer = wicks[i].end;
        }

        if (pointer < code.length) {
            text = code.substring(pointer, code.length);
            wick = new Wick(text, 'unknown', pointer);
            wicks.push(wick);
        }

        return wicks;
    },

    /**
     * Parsing strategy method which child classes must override.
     */
    _parse: function(code, offset)
    {
        throw new Error('Extending classes must override the _parse method.');
    }
});

})();
<commit_msg>Added some comments, implemented a fluent interface, and added get/set fuel methods.<commit_after>/*
---
description: Code parsing engine for Lighter.

license: MIT-style

authors:
- Jose Prado

requires:
  core/1.2.4: '*'

provides: [Parser]

...
*/
(function(){

var Parser = this.Parser = new Class({

    /**
     * @constructs
     * @param {Fuel} fuel The fuel to use for parsing.
     */
    initialize: function(fuel)
    {
        this.setFuel(fuel);

        return this;
    },

    getFuel: function()
    {
    	return this.fuel;
    },

    setFuel: function(fuel)
    {
    	this.fuel = fuel;

    	return this;
    },

    /**
     * Parses source code using fuel regex rules and returns the array of
     * tokens.
     *
     * @param {String} code     The source code to parse.
     * @param {Number} [offset] Optional offset to add to the found index.
     */
    parse: function(code, offset)
    {
        var wicks = this._parse(code, offset),
            text  = null,
            wick  = null;

        // Add code between matches as an unknown wick to the wick array.
        for (var i = 0, pointer = 0; i < wicks.length; i++) {
            if (pointer < wicks[i].index) {
                text = code.substring(pointer, wicks[i].index)
                wick = new Wick(text, 'unknown', pointer);
                wicks.splice(i, 0, wick);
            }
            pointer = wicks[i].end;
        }

        // Add the final unmatched piece if it exists.
        if (pointer < code.length) {
            text = code.substring(pointer, code.length);
            wick = new Wick(text, 'unknown', pointer);
            wicks.push(wick);
        }

        return wicks;
    },

    /**
     * Parsing strategy method which child classes must override.
     */
    _parse: function(code, offset)
    {
        throw new Error('Extending classes must override the _parse method.');
    }
});

})();
<|endoftext|>


<commit_before><commit_msg>remove RectAreaLigthUniformsLib.js<commit_after><|endoftext|>


<commit_before>/** @module delite/FormWidget */
define([
	"dcl/dcl",
	"dojo/window", // winUtils.scrollIntoView
	"dojo/dom-style", // domStyle
	"./Widget",
	"./Invalidating"
], function (dcl, winUtils, domStyle, Widget, Invalidating) {

	/**
	 * Base class for widgets that extend `HTMLElement`, but conceptually correspond
	 * to native HTML elements such as `<checkbox>` or `<button>`,
	 * which can be children of a `<form>` node.
	 *
	 * @mixin module:delite/FormWidget
	 * @augments module:delite/Widget
	 * @augments module:delite/Invalidating
	 */
	return dcl([Widget, Invalidating], /** @lends module:delite/FormWidget# */ {

		/**
		 * Name used when submitting form; same as "name" attribute or plain HTML elements.
		 * @member {string} module:delite/FormWidget.name
		 */
		name: "",

		/**
		 * Corresponds to the native HTML `<input>` element's attribute.
		 * @member {string} module:delite/FormWidget.alt
		 */
		alt: "",

		/**
		 * Corresponds to the native HTML `<input>` element's attribute.
		 * @member {string} module:delite/FormWidget.value
		 */
		value: "",

		/**
		 * The order in which fields are traversed when user hits the tab key.
		 * @member {number} module:delite/FormWidget.tabIndex
		 * @default 0
		 */
		tabIndex: 0,

		/**
		 * Concatenated list of node names that can receive focus during tab operations.
		 * @member {string} FormWidget#tabStops
		 * @default "focusNode"
		 */
		tabStops: "focusNode", // should be "" if the widget's only tab stop is the outer root node

		/**
		 * If set to true, the widget will not respond to user input and will not be included in form submission.
		 * @member {boolean} FormWidget#disabled
		 * @default false
		 */
		disabled: false,

		preCreate: function () {
			this.addInvalidatingProperties(
				"disabled",
				"tabStops",
				"tabIndex"
			);
		},

		refreshRendering: dcl.after(function (args) {
			// Handle disabled and tabIndex, across the tabStops and root node.
			// No special processing is needed for tabStops other than just to refresh disable and tabIndex.
			var props = args[0];
			var self = this;
			var tabStops = this.tabStops.split(/[ ,]/);
			if (props.tabStops || props.disabled) {
				var isDisabled = this.disabled;
				if (this.valueNode && this.valueNode !== this) {
					this.valueNode.disabled = isDisabled; // prevent submit
				}
				tabStops.forEach(
					function (nodeName) {
						var node = self[nodeName];
						if (node !== self) {
							node.disabled = isDisabled;
						}
						// let JAWS know
						node.setAttribute("aria-disabled", "" + isDisabled);
					},
					this
				);
				if (!isDisabled) {
					this.removeAttribute("disabled");
				}
			}
			if (props.tabStops || props.tabIndex || props.disabled) {
				tabStops.forEach(
					function (nodeName) {
						var node = self[nodeName];
						if (node !== self) {
							if (self.disabled) {
								node.removeAttribute("tabindex");
							} else {
								node.tabIndex = self._get("tabIndex");
							}
						}
					},
					this
				);
			}
			return props; // for after advice
		}),

		/**
		 * Returns whether or not this widget is focusable.  Used internally by delite.
		 * @returns {boolean}
		 * @protected
		 */
		isFocusable: function () {
			return !this.disabled && this.focusNode && (domStyle.get(this, "display") !== "none");
		},

		/**
		 * Put focus on this widget.
		 */
		focus: function () {
			if (!this.disabled && this.focusNode.focus) {
				try {
					this.focusNode.focus();
				} catch (e) {
					// squelch errors from hidden nodes
				}
			}
		}
	});
});
<commit_msg>FormWidget.js: use native methods rather than dojo/dom-style.<commit_after>/** @module delite/FormWidget */
define([
	"dcl/dcl",
	"dojo/window", // winUtils.scrollIntoView
	"./Widget",
	"./Invalidating"
], function (dcl, winUtils, Widget, Invalidating) {

	/**
	 * Base class for widgets that extend `HTMLElement`, but conceptually correspond
	 * to native HTML elements such as `<checkbox>` or `<button>`,
	 * which can be children of a `<form>` node.
	 *
	 * @mixin module:delite/FormWidget
	 * @augments module:delite/Widget
	 * @augments module:delite/Invalidating
	 */
	return dcl([Widget, Invalidating], /** @lends module:delite/FormWidget# */ {

		/**
		 * Name used when submitting form; same as "name" attribute or plain HTML elements.
		 * @member {string} module:delite/FormWidget.name
		 */
		name: "",

		/**
		 * Corresponds to the native HTML `<input>` element's attribute.
		 * @member {string} module:delite/FormWidget.alt
		 */
		alt: "",

		/**
		 * Corresponds to the native HTML `<input>` element's attribute.
		 * @member {string} module:delite/FormWidget.value
		 */
		value: "",

		/**
		 * The order in which fields are traversed when user hits the tab key.
		 * @member {number} module:delite/FormWidget.tabIndex
		 * @default 0
		 */
		tabIndex: 0,

		/**
		 * Concatenated list of node names that can receive focus during tab operations.
		 * @member {string} FormWidget#tabStops
		 * @default "focusNode"
		 */
		tabStops: "focusNode", // should be "" if the widget's only tab stop is the outer root node

		/**
		 * If set to true, the widget will not respond to user input and will not be included in form submission.
		 * @member {boolean} FormWidget#disabled
		 * @default false
		 */
		disabled: false,

		preCreate: function () {
			this.addInvalidatingProperties(
				"disabled",
				"tabStops",
				"tabIndex"
			);
		},

		refreshRendering: dcl.after(function (args) {
			// Handle disabled and tabIndex, across the tabStops and root node.
			// No special processing is needed for tabStops other than just to refresh disable and tabIndex.
			var props = args[0];
			var self = this;
			var tabStops = this.tabStops.split(/[ ,]/);
			if (props.tabStops || props.disabled) {
				var isDisabled = this.disabled;
				if (this.valueNode && this.valueNode !== this) {
					this.valueNode.disabled = isDisabled; // prevent submit
				}
				tabStops.forEach(
					function (nodeName) {
						var node = self[nodeName];
						if (node !== self) {
							node.disabled = isDisabled;
						}
						// let JAWS know
						node.setAttribute("aria-disabled", "" + isDisabled);
					},
					this
				);
				if (!isDisabled) {
					this.removeAttribute("disabled");
				}
			}
			if (props.tabStops || props.tabIndex || props.disabled) {
				tabStops.forEach(
					function (nodeName) {
						var node = self[nodeName];
						if (node !== self) {
							if (self.disabled) {
								node.removeAttribute("tabindex");
							} else {
								node.tabIndex = self._get("tabIndex");
							}
						}
					},
					this
				);
			}
			return props; // for after advice
		}),

		/**
		 * Returns whether or not this widget is focusable.  Used internally by delite.
		 * @returns {boolean}
		 * @protected
		 */
		isFocusable: function () {
			return !this.disabled && this.focusNode && (getComputedStyle(this).display !== "none");
		},

		/**
		 * Put focus on this widget.
		 */
		focus: function () {
			if (!this.disabled && this.focusNode.focus) {
				try {
					this.focusNode.focus();
				} catch (e) {
					// squelch errors from hidden nodes
				}
			}
		}
	});
});
<|endoftext|>