<commit_before>
angular.module('ionic.ui.navBar', ['ionic.service.view', 'ngSanitize'])

/**
 * @ngdoc service
 * @name $ionicNavBarDelegate
 * @module ionic
 * @description
 * Delegate for controlling the {@link ionic.directive:ionNavBar} directive.
 *
 * @usage
 *
 * ```html
 * <body ng-controller="MyCtrl">
 *   <ion-nav-bar>
 *     <button ng-click="setNavTitle('banana')">
 *       Set title to banana!
 *     </button>
 *   </ion-nav-bar>
 * </body>
 * ```
 * ```js
 * function MyCtrl($scope, $ionicNavBarDelegate) {
 *   $scope.setNavTitle = function(title) {
 *     $ionicNavBarDelegate.setTitle(title);
 *   }
 * }
 * ```
 */
.service('$ionicNavBarDelegate', delegateService([
  /**
   * @ngdoc method
   * @name $ionicNavBarDelegate#back
   * @description Goes back in the view history.
   * @param {DOMEvent=} event The event object (eg from a tap event)
   */
  'back',
  /**
   * @ngdoc method
   * @name $ionicNavBarDelegate#align
   * @description Aligns the title with the buttons in a given direction.
   * @param {string=} direction The direction to the align the title text towards.
   * Available: 'left', 'right', 'center'. Default: 'center'.
   */
  'align',
  /**
   * @ngdoc method
   * @name $ionicNavBarDelegate#showBackButton
   * @description
   * Set whether the {@link ionic.directive:ionNavBackButton} should be shown
   * (if it exists).
   * @param {boolean} show Whether to show the back button.
   */
  'showBackButton',
  /**
   * @ngdoc method
   * @name $ionicNavBarDelegate#showBar
   * @description
   * Set whether the {@link ionic.directive:ionNavBar} should be shown.
   * @param {boolean} show Whether to show the bar.
   */
  'showBar',
  /**
   * @ngdoc method
   * @name $ionicNavBarDelegate#setTitle
   * @description
   * Set the title for the {@link ionic.directive:ionNavBar}.
   * @param {string} title The new title to show.
   */
  'setTitle',
  /**
   * @ngdoc method
   * @name $ionicNavBarDelegate#changeTitle
   * @description
   * Change the title, transitioning the new title in and the old one out in a given direction.
   * @param {string} title The new title to show.
   * @param {string} direction The direction to transition the new title in.
   * Available: 'forward', 'back'.
   */
  'changeTitle',
  /**
   * @ngdoc method
   * @name $ionicNavBarDelegate#getTitle
   * @returns {string} The current title of the navbar.
   */
  'getTitle',
  /**
   * @ngdoc method
   * @name $ionicNavBarDelegate#getPreviousTitle
   * @returns {string} The previous title of the navbar.
   */
  'getPreviousTitle'
  /**
   * @ngdoc method
   * @name $ionicNavBarDelegate#$getByHandle
   * @param {string} handle
   * @returns `delegateInstance` A delegate instance that controls only the
   * navBars with delegate-handle matching the given handle.
   *
   * Example: `$ionicNavBarDelegate.$getByHandle('myHandle').setTitle('newTitle')`
   */
]))

.controller('$ionicNavBar', [
  '$scope',
  '$element',
  '$attrs',
  '$ionicViewService',
  '$animate',
  '$compile',
  '$ionicNavBarDelegate',
function($scope, $element, $attrs, $ionicViewService, $animate, $compile, $ionicNavBarDelegate) {
  //Let the parent know about our controller too so that children of
  //sibling content elements can know about us
  $element.parent().data('$ionNavBarController', this);

  var deregisterInstance = $ionicNavBarDelegate._registerInstance(this, $attrs.delegateHandle);

  $scope.$on('$destroy', deregisterInstance);

  var self = this;

  this.leftButtonsElement = angular.element(
    $element[0].querySelector('.buttons.left-buttons')
  );
  this.rightButtonsElement = angular.element(
    $element[0].querySelector('.buttons.right-buttons')
  );

  this.back = function(e) {
    var backView = $ionicViewService.getBackView();
    backView && backView.go();
    e && (e.alreadyHandled = true);
    return false;
  };

  this.align = function(direction) {
    this._headerBarView.align(direction);
  };

  this.showBackButton = function(show) {
    $scope.backButtonShown = !!show;
  };

  this.showBar = function(show) {
    $scope.isInvisible = !show;
    $scope.$parent.$hasHeader = !!show;
  };

  this.setTitle = function(title) {
    $scope.oldTitle = $scope.title;
    $scope.title = title || '';
  };

  this.changeTitle = function(title, direction) {
    if ($scope.title === title) {
      return false;
    }
    this.setTitle(title);
    $scope.isReverse = direction == 'back';
    $scope.shouldAnimate = !!direction;

    if (!$scope.shouldAnimate) {
      //We're done!
      this._headerBarView.align();
    } else {
      this._animateTitles();
    }
    return true;
  };

  this.getTitle = function() {
    return $scope.title || '';
  };

  this.getPreviousTitle = function() {
    return $scope.oldTitle || '';
  };

  /**
   * Exposed for testing
   */
  this._animateTitles = function() {
    var oldTitleEl, newTitleEl, currentTitles;

    //If we have any title right now
    //(or more than one, they could be transitioning on switch),
    //replace the first one with an oldTitle element
    currentTitles = $element[0].querySelectorAll('.title');
    if (currentTitles.length) {
      oldTitleEl = $compile('

')($scope);
      angular.element(currentTitles[0]).replaceWith(oldTitleEl);
    }
    //Compile new title
    newTitleEl = $compile('

')($scope);

    //Animate in on next frame
    ionic.requestAnimationFrame(function() {

      oldTitleEl && $animate.leave(angular.element(oldTitleEl));

      var insert = oldTitleEl && angular.element(oldTitleEl) || null;
      $animate.enter(newTitleEl, $element, insert, function() {
        self._headerBarView.align();
      });

      //Cleanup any old titles leftover (besides the one we already did replaceWith on)
      angular.forEach(currentTitles, function(el) {
        if (el && el.parentNode) {
          //Use .remove() to cleanup things like .data()
          angular.element(el).remove();
        }
      });

      //$apply so bindings fire
      $scope.$digest();

      //Stop flicker of new title on ios7
      ionic.requestAnimationFrame(function() {
        newTitleEl[0].classList.remove('invisible');
      });
    });
  };
}])

/**
 * @ngdoc directive
 * @name ionNavBar
 * @module ionic
 * @delegate ionic.service:$ionicNavBarDelegate
 * @restrict E
 *
 * @description
 * If we have an {@link ionic.directive:ionNavView} directive, we can also create an
 * `<ion-nav-bar>`, which will create a topbar that updates as the application state changes.
 *
 * We can add a back button by putting an {@link ionic.directive:ionNavBackButton} inside.
 *
 * We can add buttons depending on the currently visible view using
 * {@link ionic.directive:ionNavButtons}.
 *
 * Assign an [animation class](/docs/components#animations) to the element to
 * enable animated changing of titles (recommended: 'slide-left-right' or 'nav-title-slide-ios7')
 *
 * @usage
 *
 * ```html
 * <body ng-app="starter">
 *   <!-- The nav bar that will be updated as we navigate -->
 *   <ion-nav-bar class="bar-positive nav-title-slide-ios7">
 *   </ion-nav-bar>
 *
 *   <!-- where the initial view template will be rendered -->
 *   <ion-nav-view></ion-nav-view>
 * </body>
 * ```
 *
 * @param {string=} delegate-handle The handle used to identify this navBar
 * with {@link ionic.service:$ionicNavBarDelegate}.
 * @param align-title {string=} Where to align the title of the navbar.
 * Available: 'left', 'right', 'center'. Defaults to 'center'.
 */
.directive('ionNavBar', ['$ionicViewService', '$rootScope', '$animate', '$compile',
function($ionicViewService, $rootScope, $animate, $compile) {

  return {
    restrict: 'E',
    controller: '$ionicNavBar',
    scope: true,
    compile: function(tElement, tAttrs) {
      //We cannot transclude here because it breaks element.data() inheritance on compile
      tElement
        .addClass('bar bar-header nav-bar')
        .append(
          '
 ' +
          '
' +
          '

' +
          '
 ' +
          '
'
        );

      return { pre: prelink };
      function prelink($scope, $element, $attr, navBarCtrl) {
        navBarCtrl._headerBarView = new ionic.views.HeaderBar({
          el: $element[0],
          alignTitle: $attr.alignTitle || 'center'
        });

        //defaults
        $scope.backButtonShown = false;
        $scope.shouldAnimate = true;
        $scope.isReverse = false;
        $scope.isInvisible = true;

        $scope.$on('$destroy', function() {
          $scope.$parent.$hasHeader = false;
        });

        $scope.$watch(function() {
          return ($scope.isReverse ? ' reverse' : '') +
            ($scope.isInvisible ? ' invisible' : '') +
            (!$scope.shouldAnimate ? ' no-animation' : '');
        }, function(className, oldClassName) {
          $element.removeClass(oldClassName);
          $element.addClass(className);
        });

      }
    }
  };
}])

/**
 * @ngdoc directive
 * @name ionNavBackButton
 * @module ionic
 * @restrict E
 * @parent ionNavBar
 * @description
 * Creates a back button inside an {@link ionic.directive:ionNavBar}.
 *
 * Will show up when the user is able to go back in the current navigation stack.
 *
 * By default, will go back when clicked.  If you wish for more advanced behavior, see the
 * examples below.
 *
 * @usage
 *
 * With default click action:
 *
 * ```html
 * <ion-nav-bar>
 *   <ion-nav-back-button class="button-icon">
 *     <i class="ion-arrow-left-c"></i> Back!
 *   </ion-nav-back-button>
 * </ion-nav-bar>
 * ```
 *
 * With custom click action, using {@link ionic.service:$ionicNavBarDelegate}:
 *
 * ```html
 * <ion-nav-bar ng-controller="MyCtrl">
 *   <ion-nav-back-button class="button-icon"
 *     ng-click="canGoBack && goBack()">
 *     <i class="ion-arrow-left-c"></i> Back
 *   </ion-nav-back-button>
 * </ion-nav-bar>
 * ```
 * ```js
 * function MyCtrl($scope, $ionicNavBarDelegate) {
 *   $scope.goBack = function() {
 *     $ionicNavBarDelegate.back();
 *   };
 * }
 * ```
 *
 * Displaying the previous title on the back button, again using
 * {@link ionic.service:$ionicNavBarDelegate}.
 *
 * ```html
 * <ion-nav-bar ng-controller="MyCtrl">
 *   <ion-nav-back-button class="button button-icon ion-arrow-left-c">
 *     {% raw %}{{getPreviousTitle() || 'Back'}}{% endraw %}
 *   </ion-nav-back-button>
 * </ion-nav-bar>
 * ```
 * ```js
 * function MyCtrl($scope, $ionicNavBarDelegate) {
 *   $scope.getPreviousTitle = function() {
 *     return $ionicNavBarDelegate.getPreviousTitle();
 *   };
 * }
 * ```
 */
.directive('ionNavBackButton', [
  '$ionicNgClick',
  '$animate',
function($ionicNgClick, $animate) {
  return {
    restrict: 'E',
    require: '^ionNavBar',
    compile: function(tElement, tAttrs) {
      tElement.addClass('button back-button ng-hide');
      return function($scope, $element, $attr, navBarCtrl) {
        if (!$attr.ngClick) {
          $scope.$navBack = navBarCtrl.back;
          $ionicNgClick($scope, $element, '$navBack($event)');
        }

        //If the current viewstate does not allow a back button,
        //always hide it.
        var deregisterListener = $scope.$parent.$on(
          '$viewHistory.historyChange',
          function(e, data) {
            $scope.hasBackButton = !!data.showBack;
          }
        );
        $scope.$on('$destroy', deregisterListener);

        //Make sure both that a backButton is allowed in the first place,
        //and that it is shown by the current view.
        $scope.$watch('!!(backButtonShown && hasBackButton)', ionic.animationFrameThrottle(function(show) {
          if (show) $animate.removeClass($element, 'ng-hide');
          else $animate.addClass($element, 'ng-hide');
        }));
      };
    }
  };
}])

/**
 * @ngdoc directive
 * @name ionNavButtons
 * @module ionic
 * @restrict E
 * @parent ionNavView
 *
 * @description
 * Use ionNavButtons to set the buttons on your {@link ionic.directive:ionNavBar}
 * from within an {@link ionic.directive:ionView}.
 *
 * Any buttons you declare will be placed onto the navbar's corresponding side,
 * and then destroyed when the user leaves their parent view.
 *
 * @usage
 * ```html
 * <ion-nav-bar>
 * </ion-nav-bar>
 * <ion-nav-view>
 *   <ion-view>
 *     <ion-nav-buttons side="left">
 *       <button class="button" ng-click="doSomething()">
 *         I'm a button on the left of the navbar!
 *       </button>
 *     </ion-nav-buttons>
 *     <ion-content>
 *       Some super content here!
 *     </ion-content>
 *   </ion-view>
 * </ion-nav-view>
 * ```
 *
 * @param {string} side The side to place the buttons on in the parent
 * {@link ionic.directive:ionNavBar}. Available: 'left' or 'right'.
 */
.directive('ionNavButtons', ['$compile', '$animate', function($compile, $animate) {
  return {
    require: '^ionNavBar',
    restrict: 'E',
    compile: function($element, $attrs) {
      var content = $element.contents().remove();
      return function($scope, $element, $attrs, navBarCtrl) {
        var navElement = $attrs.side === 'right' ?
          navBarCtrl.rightButtonsElement :
          navBarCtrl.leftButtonsElement;

        //Put all of our inside buttons into their own span,
        //so we can remove them all when this element dies -
        //even if the buttons have changed through an ng-repeat or the like,
        //we just remove their div parent and they are gone.
        var buttons = angular.element('').append(content);

        //Compile buttons inside content so they have access to everything
        //something inside content does (eg parent ionicScroll)
        $element.append(buttons);
        $compile(buttons)($scope);

        //Append buttons to navbar
        $animate.enter(buttons, navElement);

        //When our ion-nav-buttons container is destroyed,
        //destroy everything in the navbar
        $scope.$on('$destroy', function() {
          $animate.leave(buttons);
        });

        // The original element is just a completely empty <ion-nav-buttons> element.
        // make it invisible just to be sure it doesn't change any layout
        $element.css('display', 'none');
      };
    }
  };
}]);
<commit_msg>feat($ionicNavBarDelegate): showBar returns whether navbar is shown<commit_after>
angular.module('ionic.ui.navBar', ['ionic.service.view', 'ngSanitize'])

/**
 * @ngdoc service
 * @name $ionicNavBarDelegate
 * @module ionic
 * @description
 * Delegate for controlling the {@link ionic.directive:ionNavBar} directive.
 *
 * @usage
 *
 * ```html
 * <body ng-controller="MyCtrl">
 *   <ion-nav-bar>
 *     <button ng-click="setNavTitle('banana')">
 *       Set title to banana!
 *     </button>
 *   </ion-nav-bar>
 * </body>
 * ```
 * ```js
 * function MyCtrl($scope, $ionicNavBarDelegate) {
 *   $scope.setNavTitle = function(title) {
 *     $ionicNavBarDelegate.setTitle(title);
 *   }
 * }
 * ```
 */
.service('$ionicNavBarDelegate', delegateService([
  /**
   * @ngdoc method
   * @name $ionicNavBarDelegate#back
   * @description Goes back in the view history.
   * @param {DOMEvent=} event The event object (eg from a tap event)
   */
  'back',
  /**
   * @ngdoc method
   * @name $ionicNavBarDelegate#align
   * @description Aligns the title with the buttons in a given direction.
   * @param {string=} direction The direction to the align the title text towards.
   * Available: 'left', 'right', 'center'. Default: 'center'.
   */
  'align',
  /**
   * @ngdoc method
   * @name $ionicNavBarDelegate#showBackButton
   * @description
   * Set whether the {@link ionic.directive:ionNavBackButton} should be shown
   * (if it exists).
   * @param {boolean} show Whether to show the back button.
   */
  'showBackButton',
  /**
   * @ngdoc method
   * @name $ionicNavBarDelegate#showBar
   * @description
   * Set/get whether the {@link ionic.directive:ionNavBar} is shown.
   * @param {boolean} show Whether to show the bar.
   * @returns {boolean} Whether the bar is shown.
   */
  'showBar',
  /**
   * @ngdoc method
   * @name $ionicNavBarDelegate#setTitle
   * @description
   * Set the title for the {@link ionic.directive:ionNavBar}.
   * @param {string} title The new title to show.
   */
  'setTitle',
  /**
   * @ngdoc method
   * @name $ionicNavBarDelegate#changeTitle
   * @description
   * Change the title, transitioning the new title in and the old one out in a given direction.
   * @param {string} title The new title to show.
   * @param {string} direction The direction to transition the new title in.
   * Available: 'forward', 'back'.
   */
  'changeTitle',
  /**
   * @ngdoc method
   * @name $ionicNavBarDelegate#getTitle
   * @returns {string} The current title of the navbar.
   */
  'getTitle',
  /**
   * @ngdoc method
   * @name $ionicNavBarDelegate#getPreviousTitle
   * @returns {string} The previous title of the navbar.
   */
  'getPreviousTitle'
  /**
   * @ngdoc method
   * @name $ionicNavBarDelegate#$getByHandle
   * @param {string} handle
   * @returns `delegateInstance` A delegate instance that controls only the
   * navBars with delegate-handle matching the given handle.
   *
   * Example: `$ionicNavBarDelegate.$getByHandle('myHandle').setTitle('newTitle')`
   */
]))

.controller('$ionicNavBar', [
  '$scope',
  '$element',
  '$attrs',
  '$ionicViewService',
  '$animate',
  '$compile',
  '$ionicNavBarDelegate',
function($scope, $element, $attrs, $ionicViewService, $animate, $compile, $ionicNavBarDelegate) {
  //Let the parent know about our controller too so that children of
  //sibling content elements can know about us
  $element.parent().data('$ionNavBarController', this);

  var deregisterInstance = $ionicNavBarDelegate._registerInstance(this, $attrs.delegateHandle);

  $scope.$on('$destroy', deregisterInstance);

  var self = this;

  this.leftButtonsElement = angular.element(
    $element[0].querySelector('.buttons.left-buttons')
  );
  this.rightButtonsElement = angular.element(
    $element[0].querySelector('.buttons.right-buttons')
  );

  this.back = function(e) {
    var backView = $ionicViewService.getBackView();
    backView && backView.go();
    e && (e.alreadyHandled = true);
    return false;
  };

  this.align = function(direction) {
    this._headerBarView.align(direction);
  };

  this.showBackButton = function(show) {
    $scope.backButtonShown = !!show;
  };

  this.showBar = function(show) {
    if (arguments.length) {
      $scope.isInvisible = !show;
      $scope.$parent.$hasHeader = !!show;
    }
    return !$scope.isInvisible;
  };

  this.setTitle = function(title) {
    $scope.oldTitle = $scope.title;
    $scope.title = title || '';
  };

  this.changeTitle = function(title, direction) {
    if ($scope.title === title) {
      return false;
    }
    this.setTitle(title);
    $scope.isReverse = direction == 'back';
    $scope.shouldAnimate = !!direction;

    if (!$scope.shouldAnimate) {
      //We're done!
      this._headerBarView.align();
    } else {
      this._animateTitles();
    }
    return true;
  };

  this.getTitle = function() {
    return $scope.title || '';
  };

  this.getPreviousTitle = function() {
    return $scope.oldTitle || '';
  };

  /**
   * Exposed for testing
   */
  this._animateTitles = function() {
    var oldTitleEl, newTitleEl, currentTitles;

    //If we have any title right now
    //(or more than one, they could be transitioning on switch),
    //replace the first one with an oldTitle element
    currentTitles = $element[0].querySelectorAll('.title');
    if (currentTitles.length) {
      oldTitleEl = $compile('

')($scope);
      angular.element(currentTitles[0]).replaceWith(oldTitleEl);
    }
    //Compile new title
    newTitleEl = $compile('

')($scope);

    //Animate in on next frame
    ionic.requestAnimationFrame(function() {

      oldTitleEl && $animate.leave(angular.element(oldTitleEl));

      var insert = oldTitleEl && angular.element(oldTitleEl) || null;
      $animate.enter(newTitleEl, $element, insert, function() {
        self._headerBarView.align();
      });

      //Cleanup any old titles leftover (besides the one we already did replaceWith on)
      angular.forEach(currentTitles, function(el) {
        if (el && el.parentNode) {
          //Use .remove() to cleanup things like .data()
          angular.element(el).remove();
        }
      });

      //$apply so bindings fire
      $scope.$digest();

      //Stop flicker of new title on ios7
      ionic.requestAnimationFrame(function() {
        newTitleEl[0].classList.remove('invisible');
      });
    });
  };
}])

/**
 * @ngdoc directive
 * @name ionNavBar
 * @module ionic
 * @delegate ionic.service:$ionicNavBarDelegate
 * @restrict E
 *
 * @description
 * If we have an {@link ionic.directive:ionNavView} directive, we can also create an
 * `<ion-nav-bar>`, which will create a topbar that updates as the application state changes.
 *
 * We can add a back button by putting an {@link ionic.directive:ionNavBackButton} inside.
 *
 * We can add buttons depending on the currently visible view using
 * {@link ionic.directive:ionNavButtons}.
 *
 * Assign an [animation class](/docs/components#animations) to the element to
 * enable animated changing of titles (recommended: 'slide-left-right' or 'nav-title-slide-ios7')
 *
 * @usage
 *
 * ```html
 * <body ng-app="starter">
 *   <!-- The nav bar that will be updated as we navigate -->
 *   <ion-nav-bar class="bar-positive nav-title-slide-ios7">
 *   </ion-nav-bar>
 *
 *   <!-- where the initial view template will be rendered -->
 *   <ion-nav-view></ion-nav-view>
 * </body>
 * ```
 *
 * @param {string=} delegate-handle The handle used to identify this navBar
 * with {@link ionic.service:$ionicNavBarDelegate}.
 * @param align-title {string=} Where to align the title of the navbar.
 * Available: 'left', 'right', 'center'. Defaults to 'center'.
 */
.directive('ionNavBar', ['$ionicViewService', '$rootScope', '$animate', '$compile',
function($ionicViewService, $rootScope, $animate, $compile) {

  return {
    restrict: 'E',
    controller: '$ionicNavBar',
    scope: true,
    compile: function(tElement, tAttrs) {
      //We cannot transclude here because it breaks element.data() inheritance on compile
      tElement
        .addClass('bar bar-header nav-bar')
        .append(
          '
 ' +
          '
' +
          '

' +
          '
 ' +
          '
'
        );

      return { pre: prelink };
      function prelink($scope, $element, $attr, navBarCtrl) {
        navBarCtrl._headerBarView = new ionic.views.HeaderBar({
          el: $element[0],
          alignTitle: $attr.alignTitle || 'center'
        });

        //defaults
        $scope.backButtonShown = false;
        $scope.shouldAnimate = true;
        $scope.isReverse = false;
        $scope.isInvisible = true;

        $scope.$on('$destroy', function() {
          $scope.$parent.$hasHeader = false;
        });

        $scope.$watch(function() {
          return ($scope.isReverse ? ' reverse' : '') +
            ($scope.isInvisible ? ' invisible' : '') +
            (!$scope.shouldAnimate ? ' no-animation' : '');
        }, function(className, oldClassName) {
          $element.removeClass(oldClassName);
          $element.addClass(className);
        });

      }
    }
  };
}])

/**
 * @ngdoc directive
 * @name ionNavBackButton
 * @module ionic
 * @restrict E
 * @parent ionNavBar
 * @description
 * Creates a back button inside an {@link ionic.directive:ionNavBar}.
 *
 * Will show up when the user is able to go back in the current navigation stack.
 *
 * By default, will go back when clicked.  If you wish for more advanced behavior, see the
 * examples below.
 *
 * @usage
 *
 * With default click action:
 *
 * ```html
 * <ion-nav-bar>
 *   <ion-nav-back-button class="button-icon">
 *     <i class="ion-arrow-left-c"></i> Back!
 *   </ion-nav-back-button>
 * </ion-nav-bar>
 * ```
 *
 * With custom click action, using {@link ionic.service:$ionicNavBarDelegate}:
 *
 * ```html
 * <ion-nav-bar ng-controller="MyCtrl">
 *   <ion-nav-back-button class="button-icon"
 *     ng-click="canGoBack && goBack()">
 *     <i class="ion-arrow-left-c"></i> Back
 *   </ion-nav-back-button>
 * </ion-nav-bar>
 * ```
 * ```js
 * function MyCtrl($scope, $ionicNavBarDelegate) {
 *   $scope.goBack = function() {
 *     $ionicNavBarDelegate.back();
 *   };
 * }
 * ```
 *
 * Displaying the previous title on the back button, again using
 * {@link ionic.service:$ionicNavBarDelegate}.
 *
 * ```html
 * <ion-nav-bar ng-controller="MyCtrl">
 *   <ion-nav-back-button class="button button-icon ion-arrow-left-c">
 *     {% raw %}{{getPreviousTitle() || 'Back'}}{% endraw %}
 *   </ion-nav-back-button>
 * </ion-nav-bar>
 * ```
 * ```js
 * function MyCtrl($scope, $ionicNavBarDelegate) {
 *   $scope.getPreviousTitle = function() {
 *     return $ionicNavBarDelegate.getPreviousTitle();
 *   };
 * }
 * ```
 */
.directive('ionNavBackButton', [
  '$ionicNgClick',
  '$animate',
function($ionicNgClick, $animate) {
  return {
    restrict: 'E',
    require: '^ionNavBar',
    compile: function(tElement, tAttrs) {
      tElement.addClass('button back-button ng-hide');
      return function($scope, $element, $attr, navBarCtrl) {
        if (!$attr.ngClick) {
          $scope.$navBack = navBarCtrl.back;
          $ionicNgClick($scope, $element, '$navBack($event)');
        }

        //If the current viewstate does not allow a back button,
        //always hide it.
        var deregisterListener = $scope.$parent.$on(
          '$viewHistory.historyChange',
          function(e, data) {
            $scope.hasBackButton = !!data.showBack;
          }
        );
        $scope.$on('$destroy', deregisterListener);

        //Make sure both that a backButton is allowed in the first place,
        //and that it is shown by the current view.
        $scope.$watch('!!(backButtonShown && hasBackButton)', ionic.animationFrameThrottle(function(show) {
          if (show) $animate.removeClass($element, 'ng-hide');
          else $animate.addClass($element, 'ng-hide');
        }));
      };
    }
  };
}])

/**
 * @ngdoc directive
 * @name ionNavButtons
 * @module ionic
 * @restrict E
 * @parent ionNavView
 *
 * @description
 * Use ionNavButtons to set the buttons on your {@link ionic.directive:ionNavBar}
 * from within an {@link ionic.directive:ionView}.
 *
 * Any buttons you declare will be placed onto the navbar's corresponding side,
 * and then destroyed when the user leaves their parent view.
 *
 * @usage
 * ```html
 * <ion-nav-bar>
 * </ion-nav-bar>
 * <ion-nav-view>
 *   <ion-view>
 *     <ion-nav-buttons side="left">
 *       <button class="button" ng-click="doSomething()">
 *         I'm a button on the left of the navbar!
 *       </button>
 *     </ion-nav-buttons>
 *     <ion-content>
 *       Some super content here!
 *     </ion-content>
 *   </ion-view>
 * </ion-nav-view>
 * ```
 *
 * @param {string} side The side to place the buttons on in the parent
 * {@link ionic.directive:ionNavBar}. Available: 'left' or 'right'.
 */
.directive('ionNavButtons', ['$compile', '$animate', function($compile, $animate) {
  return {
    require: '^ionNavBar',
    restrict: 'E',
    compile: function($element, $attrs) {
      var content = $element.contents().remove();
      return function($scope, $element, $attrs, navBarCtrl) {
        var navElement = $attrs.side === 'right' ?
          navBarCtrl.rightButtonsElement :
          navBarCtrl.leftButtonsElement;

        //Put all of our inside buttons into their own span,
        //so we can remove them all when this element dies -
        //even if the buttons have changed through an ng-repeat or the like,
        //we just remove their div parent and they are gone.
        var buttons = angular.element('').append(content);

        //Compile buttons inside content so they have access to everything
        //something inside content does (eg parent ionicScroll)
        $element.append(buttons);
        $compile(buttons)($scope);

        //Append buttons to navbar
        $animate.enter(buttons, navElement);

        //When our ion-nav-buttons container is destroyed,
        //destroy everything in the navbar
        $scope.$on('$destroy', function() {
          $animate.leave(buttons);
        });

        // The original element is just a completely empty <ion-nav-buttons> element.
        // make it invisible just to be sure it doesn't change any layout
        $element.css('display', 'none');
      };
    }
  };
}]);
<|endoftext|>


<commit_before>import React, { StyleSheet, View, Component } from 'react-native';
import RNChart from 'react-native-chart';

class PercentageChart extends Component {
  constructor(props) {
    super(props);
    this.state = {
      studentData: [],
      chartData: [
        {
          name: 'BarChart',
          type: 'bar',
          color: '#219dff',
          widthPercent: 1,
          data: [],
        }
      ],
      xLabels: ['Average Student Response']
    }

  }

  componentWillReceiveProps(newData) {
    updatedStudentData = newData.average;
    var updatedColor;
    if(updatedStudentData[0] > 80) {
      updatedColor = 'green';
    } else if(updatedStudentData[0] > 40) {
      updatedColor = 'yellow';
    } else {
      updatedColor = 'red';
    }
    this.setState({
      studentData : updatedStudentData,
      color: updatedColor
    });
    return (
      <View style={styles.container}>
        <RNChart style={styles.chart}
          chartData={[{
          name: 'BarChart',
          type: 'bar',
          color: this.state.color,
          widthPercent: 1,
          data: newData.average,
        }]}
          verticalGridStep={5}
          xLabels={['Average Student Response']}
         />
      </View>
    );
  }

  render() {
    return (
      <View style={styles.container}>
        <RNChart style={styles.chart}
          chartData={[{
          name: 'BarChart',
          type: 'bar',
          color: this.state.color,
          widthPercent: 1,
          data: this.state.studentData
        }]}
          verticalGridStep={5}
          xLabels={this.state.xLabels}
         />
      </View>
    );
  }
}

const flag = true;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'white',
  },
  chart: {
    position: 'absolute',
    top: 16,
    left: 4,
    bottom: 4,
    right: 16,
  }
});

module.exports = PercentageChart;

<commit_msg>Soften graph feedback colors<commit_after>import React, { StyleSheet, View, Component } from 'react-native';
import RNChart from 'react-native-chart';

class PercentageChart extends Component {
  constructor(props) {
    super(props);
    this.state = {
      studentData: [],
      chartData: [
        {
          name: 'BarChart',
          type: 'bar',
          color: '#219dff',
          widthPercent: 1,
          data: [],
        }
      ],
      xLabels: ['Average Student Response']
    }

  }

  componentWillReceiveProps(newData) {
    updatedStudentData = newData.average;
    var updatedColor;

    // Change color based on average response
    if(updatedStudentData[0] > 80) {
      updatedColor = '#66ff99';
    } else if(updatedStudentData[0] > 40) {
      updatedColor = '#fcfa8b';
    } else {
      updatedColor = '#ff4f4d';
    }

    this.setState({
      studentData : updatedStudentData,
      color: updatedColor
    });
    return (
      <View style={styles.container}>
        <RNChart style={styles.chart}
          chartData={[{
          name: 'BarChart',
          type: 'bar',
          color: this.state.color,
          widthPercent: .5,
          data: newData.average,
        }]}
          verticalGridStep={5}
          xLabels={['Average Student Response']}
         />
      </View>
    );
  }

  render() {
    return (
      <View style={styles.container}>
        <RNChart style={styles.chart}
          chartData={[{
          name: 'BarChart',
          type: 'bar',
          color: this.state.color,
          widthPercent: .5,
          data: this.state.studentData
        }]}
          verticalGridStep={5}
          xLabels={this.state.xLabels}
         />
      </View>
    );
  }
}

const flag = true;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'white',
  },
  chart: {
    position: 'absolute',
    top: 15,
    left: 15,
    bottom: 4,
    right: 15,
  }
});

module.exports = PercentageChart;

<|endoftext|>


<commit_before>if (!Element.prototype.addEventListener) {
  let oListeners = {};
  let runListeners = function (oEvent) {
    if (!oEvent) {
      oEvent = window.event;
    }

    for (var iLstId = 0, iElId = 0, oEvtListeners = oListeners[oEvent.type]; iElId < oEvtListeners.aEls.length; iElId++) {
      if (oEvtListeners.aEls[iElId] === this) {
        for (iLstId; iLstId < oEvtListeners.aEvts[iElId].length; iLstId++) {
          oEvtListeners.aEvts[iElId][iLstId].call(this, oEvent);
        }
        break;
      }
    }
  };

  Element.prototype.addEventListener = function (sEventType, fListener) {
    if (oListeners.hasOwnProperty(sEventType)) {
      let oEvtListeners = oListeners[sEventType];
      let nElIdx;
      let iElId;

      for (nElIdx = -1, iElId = 0; iElId < oEvtListeners.aEls.length; iElId++) {
        if (oEvtListeners.aEls[iElId] === this) {
          nElIdx = iElId;
          break;
        }
      }

      if (nElIdx === -1) {
        oEvtListeners.aEls.push(this);
        oEvtListeners.aEvts.push([fListener]);
        this["on" + sEventType] = runListeners;
      } else {
        let aElListeners = oEvtListeners.aEvts[nElIdx];

        if (this["on" + sEventType] !== runListeners) {
          aElListeners.splice(0);
          this["on" + sEventType] = runListeners;
        }

        for (var iLstId = 0; iLstId < aElListeners.length; iLstId++) {
          if (aElListeners[iLstId] === fListener) {
            return;
          }
        }

        aElListeners.push(fListener);
      }
    } else {
      oListeners[sEventType] = { aEls: [this], aEvts: [ [fListener] ] };
      this["on" + sEventType] = runListeners;
    }
  };

  Element.prototype.removeEventListener = function (sEventType, fListener) {
    if (!oListeners.hasOwnProperty(sEventType)) {
      return;
    }

    let oEvtListeners = oListeners[sEventType];
    let nElIdx;
    let iElId;

    for (nElIdx = -1, iElId = 0; iElId < oEvtListeners.aEls.length; iElId++) {
      if (oEvtListeners.aEls[iElId] === this) {
        nElIdx = iElId;
        break;
      }
    }

    if (nElIdx === -1) {
      return;
    }

    for (let iLstId = 0, aElListeners = oEvtListeners.aEvts[nElIdx]; iLstId < aElListeners.length; iLstId++) {
      if (aElListeners[iLstId] === fListener) {
        aElListeners.splice(iLstId, 1);
      }
    }
  };
}
<commit_msg>Fix eslint errors caused by using double quotes<commit_after>if (!Element.prototype.addEventListener) {
  let oListeners = {};
  let runListeners = function (oEvent) {
    if (!oEvent) {
      oEvent = window.event;
    }

    for (var iLstId = 0, iElId = 0, oEvtListeners = oListeners[oEvent.type]; iElId < oEvtListeners.aEls.length; iElId++) {
      if (oEvtListeners.aEls[iElId] === this) {
        for (iLstId; iLstId < oEvtListeners.aEvts[iElId].length; iLstId++) {
          oEvtListeners.aEvts[iElId][iLstId].call(this, oEvent);
        }
        break;
      }
    }
  };

  Element.prototype.addEventListener = function (sEventType, fListener) {
    if (oListeners.hasOwnProperty(sEventType)) {
      let oEvtListeners = oListeners[sEventType];
      let nElIdx;
      let iElId;

      for (nElIdx = -1, iElId = 0; iElId < oEvtListeners.aEls.length; iElId++) {
        if (oEvtListeners.aEls[iElId] === this) {
          nElIdx = iElId;
          break;
        }
      }

      if (nElIdx === -1) {
        oEvtListeners.aEls.push(this);
        oEvtListeners.aEvts.push([fListener]);
        this['on' + sEventType] = runListeners;
      } else {
        let aElListeners = oEvtListeners.aEvts[nElIdx];

        if (this['on' + sEventType] !== runListeners) {
          aElListeners.splice(0);
          this['on' + sEventType] = runListeners;
        }

        for (var iLstId = 0; iLstId < aElListeners.length; iLstId++) {
          if (aElListeners[iLstId] === fListener) {
            return;
          }
        }

        aElListeners.push(fListener);
      }
    } else {
      oListeners[sEventType] = { aEls: [this], aEvts: [ [fListener] ] };
      this['on' + sEventType] = runListeners;
    }
  };

  Element.prototype.removeEventListener = function (sEventType, fListener) {
    if (!oListeners.hasOwnProperty(sEventType)) {
      return;
    }

    let oEvtListeners = oListeners[sEventType];
    let nElIdx;
    let iElId;

    for (nElIdx = -1, iElId = 0; iElId < oEvtListeners.aEls.length; iElId++) {
      if (oEvtListeners.aEls[iElId] === this) {
        nElIdx = iElId;
        break;
      }
    }

    if (nElIdx === -1) {
      return;
    }

    for (let iLstId = 0, aElListeners = oEvtListeners.aEvts[nElIdx]; iLstId < aElListeners.length; iLstId++) {
      if (aElListeners[iLstId] === fListener) {
        aElListeners.splice(iLstId, 1);
      }
    }
  };
}
<|endoftext|>


<commit_before>/*
Name:             bolcom.js
Description:      Module for node.js to access Bol.com Open API service.
Author:           Franklin van de Meent (https://frankl.in)
Source:           https://github.com/fvdm/nodejs-bolcom
Bugs & feedback:  https://github.com/fvdm/nodejs-bolcom/issues
License:          Unlicense / Public Domain

Service name:     Bol.com
Service docs:     https://developers.bol.com
*/

var https = require('https')
var querystring = require('querystring')
var api_key = null
var api_timeout = 5000

var app = {
  catalog: {},
  utils: {},
  account: {}
}

app.catalog.search = function( props, callback ) {
  talk( 'catalog', 'search', props, function( err, data ) {
    if( !err && data.products instanceof Array ) {
      for( var p=0; p < data.products.length; p++ ) {
        var product = data.products[p]

        var purls = {}
        for( var u=0; u < product.urls.length; u++ ) {
          var url = product.urls[u]
          purls[url.key] = url
        }
        data.products[p].urls = purls
        delete purls

        var pimgs = {}
        for( var m=0; m < product.images.length; m++ ) {
          var image = product.images[m]
          pimgs[image.key] = image
        }
        data.products[p].images = pimgs
        delete pimgs

        if( product.attributeGroups ) {
          var groups = {}
          for( var g=0; g < product.attributeGroups.length; g++ ) {
            var group = product.attributeGroups[g]
            groups[group.title] = {title: group.title}

            if( group.attributes ) {
              groups[group.title].attributes = {}
              for( var a=0; a < group.attributes.length; a++ ) {
                var attrib = group.attributes[a]
                groups[group.title].attributes[attrib.key] = attrib
              }
            }
          }
          data.products[p].attributeGroups = groups
          delete groups
        }
      }
    }
    callback( err, data )
  })
}

app.utils.ping = function( callback ) {
  talk( 'utils', 'ping', callback )
}

app.account.sessions = function( callback ) {
  talk( 'accounts', 'sessions', callback )
}

// Communicate
function talk( cat, method, params, callback ) {
  if( typeof params === 'function' ) {
    var callback = params
    var params = {}
  }
  params = params instanceof Object ? params : {}

  // check api key
  if( typeof api_key === 'string' && api_key.length > 0 ) {
    params.apikey = api_key
  } else {
    doCallback( new Error('missing apikey') )
    return
  }

  // prevent multiple callbacks
  var complete = false
  function doCallback( err, data ) {
    if( !complete ) {
      complete = true
      callback( err, data || null )
    }
  }

  // build request
  params.format = 'json'

  var options = {
    host: 'api.bol.com',
    path: '/'+ cat +'/v4/'+ method +'?'+ querystring.stringify(params),
    method: 'GET',
    headers: {
      'User-Agent': 'bolcom.js (https://frankl.in)'
    }
  }

  var request = https.request(options)

  // process response
  request.on( 'response', function(response) {
    var data = ''

    response.on( 'data', function(ch) { data += ch })

    response.on( 'close', function() {
      doCallback(new Error('request dropped'))
    })

    response.on( 'end', function() {
      var error = null
      if( response.statusCode != 200 ) {
        error = new Error('API error')
      }

      try {
        data = JSON.parse( data )
      } catch(e) {
        error = new Error('invalid response')
        error.err = e
      }

      if( error ) {
        error.code = response.statusCode
        error.headers = response.headers
        error.api = data instanceof Object ? data : {}
        error.body = data instanceof Object ? null : data
      }

      doCallback( error, data )
    })
  })

  // timeout
  request.on( 'socket', function( socket ) {
    if( api_timeout ) {
      socket.setTimeout( api_timeout )
      socket.on( 'timeout', function() {
        request.abort()
      })
    }
  })

  // error
  request.on( 'error', function( err ) {
    if( err == 'ECONNRESET' ) {
      var error = new Error('request timeout')
    } else {
      var error = new Error('request failed')
    }
    error.err = err
    doCallback( error )
  })

  // do it
  request.end()
}

module.exports = function(apikey, timeout) {
  api_key = apikey
  api_timeout = timeout || api_timeout
  return app
}<commit_msg>Minor comments<commit_after>/*
Name:             bolcom.js
Description:      Module for node.js to access Bol.com Open API service.
Author:           Franklin van de Meent (https://frankl.in)
Source:           https://github.com/fvdm/nodejs-bolcom
Bugs & feedback:  https://github.com/fvdm/nodejs-bolcom/issues
License:          Unlicense / Public Domain

Service name:     Bol.com
Service docs:     https://developers.bol.com
*/

var https = require('https')
var querystring = require('querystring')
var api_key = null
var api_timeout = 5000

var app = {
  catalog: {},
  utils: {},
  account: {}
}

app.catalog.search = function( props, callback ) {
  talk( 'catalog', 'search', props, function( err, data ) {
    if( !err && data.products instanceof Array ) {
      for( var p=0; p < data.products.length; p++ ) {
        var product = data.products[p]

        // urls
        var purls = {}
        for( var u=0; u < product.urls.length; u++ ) {
          var url = product.urls[u]
          purls[url.key] = url
        }
        data.products[p].urls = purls
        delete purls

        // images
        var pimgs = {}
        for( var m=0; m < product.images.length; m++ ) {
          var image = product.images[m]
          pimgs[image.key] = image
        }
        data.products[p].images = pimgs
        delete pimgs

        // includeattributes: true
        if( product.attributeGroups ) {
          var groups = {}
          for( var g=0; g < product.attributeGroups.length; g++ ) {
            var group = product.attributeGroups[g]
            groups[group.title] = {title: group.title}

            if( group.attributes ) {
              groups[group.title].attributes = {}
              for( var a=0; a < group.attributes.length; a++ ) {
                var attrib = group.attributes[a]
                groups[group.title].attributes[attrib.key] = attrib
              }
            }
          }
          data.products[p].attributeGroups = groups
          delete groups
        }
      }
    }
    callback( err, data )
  })
}

app.utils.ping = function( callback ) {
  talk( 'utils', 'ping', callback )
}

app.account.sessions = function( callback ) {
  talk( 'accounts', 'sessions', callback )
}

// Communicate
function talk( cat, method, params, callback ) {
  if( typeof params === 'function' ) {
    var callback = params
    var params = {}
  }
  params = params instanceof Object ? params : {}

  // check api key
  if( typeof api_key === 'string' && api_key.length > 0 ) {
    params.apikey = api_key
  } else {
    doCallback( new Error('missing apikey') )
    return
  }

  // prevent multiple callbacks
  var complete = false
  function doCallback( err, data ) {
    if( !complete ) {
      complete = true
      callback( err, data || null )
    }
  }

  // build request
  params.format = 'json'

  var options = {
    host: 'api.bol.com',
    path: '/'+ cat +'/v4/'+ method +'?'+ querystring.stringify(params),
    method: 'GET',
    headers: {
      'User-Agent': 'bolcom.js (https://frankl.in)'
    }
  }

  var request = https.request(options)

  // process response
  request.on( 'response', function(response) {
    var data = ''

    response.on( 'data', function(ch) { data += ch })

    response.on( 'close', function() {
      doCallback(new Error('request dropped'))
    })

    response.on( 'end', function() {
      var error = null
      if( response.statusCode != 200 ) {
        error = new Error('API error')
      }

      try {
        data = JSON.parse( data )
      } catch(e) {
        error = new Error('invalid response')
        error.err = e
      }

      if( error ) {
        error.code = response.statusCode
        error.headers = response.headers
        error.api = data instanceof Object ? data : {}
        error.body = data instanceof Object ? null : data
      }

      doCallback( error, data )
    })
  })

  // timeout
  request.on( 'socket', function( socket ) {
    if( api_timeout ) {
      socket.setTimeout( api_timeout )
      socket.on( 'timeout', function() {
        request.abort()
      })
    }
  })

  // error
  request.on( 'error', function( err ) {
    if( err == 'ECONNRESET' ) {
      var error = new Error('request timeout')
    } else {
      var error = new Error('request failed')
    }
    error.err = err
    doCallback( error )
  })

  // do it
  request.end()
}

module.exports = function(apikey, timeout) {
  api_key = apikey
  api_timeout = timeout || api_timeout
  return app
}<|endoftext|>


<commit_before>import React from 'react';
import {connect} from 'dva';
import {routerRedux} from 'dva/router';
import {Spin, Row, Col, Form, Button, Modal} from 'antd';
import {action, model, fun, config, modular} from '../../common';
import {
	OrderStep,
	BaseInfo,
	ResidentInfoTable,
	PayModal,
	ResidentSign,
	ResidentInspect,
	Newborn,
	ChronicDisease,
	NewestPolicy,
	NewestActivity,
	AntenatalCare,
	ChildHealth,
	Medication,
	Hypertension,
	Diabetes,
} from '../../components';
import styles from './OrderPage.less';

let residentInfoTable;
let baseInfo;
let payModal;
let need;

let entrustNumber;
let dataList;

const OrderPage = ( {
	loading,
	orderModel,
	workerModel,
	dispatch,
	route,
	user,
} ) => {
	fun.printLoader( 'orderPage' );
	const { userType, orderHandlerId, orderHandlerName } = user;
	const { currentStep, displayConfirm, submitDisabled, displayBack, displayNew } = orderModel ? orderModel : {};
	const { serviceDetail, residentList } = workerModel ? workerModel : {};
	const { currentData, display, disabled } = workerModel ? workerModel : orderModel;
	const { orgName, remainingBalance } = currentData;

	/** 获取页面path,初始化dataList */
	let path;
	if ( userType === config.userType.worker ) {
		path = route.path.substr( route.path.indexOf( '/' ) + 1 );
		dataList = residentList;
	} else {
		path = route.path;
		if ( !disabled ) {
			dataList = [];
		}
	}

	/** 医生端-校验表单输入数据*/
	const validAndConfirm = () => {
		baseInfo.validateFieldsAndScroll( ( errOut ) => {
			if ( !errOut ) {
				need.validateFieldsAndScroll( ( err ) => {
					if ( !err ) {
						dataList = residentInfoTable.getData();
						if ( dataList === undefined || dataList.length === 0 ) {
							Modal.error( {
								title: config.NODATA,
							} );
							return;
						}
						entrustNumber = dataList.length;
						dispatch( { type: fun.fuse( model.order, action.order_changeConfirmState ) } );
					}
				} );
			}
		} );
	};
	/** 医生端-显示确认支付窗口 */
	const showModal = ( e ) => {
		e.preventDefault();
		dispatch( {
			type: fun.fuse( model.app, action.APP_getItemPrice ),
			payload: { itemId: modular[ path ].ritRef, fun: payModal.showModal }
		} );
	};
	/** 医生端-提交表单数据 */
	const handleSubmit = ( expenseAccount ) => {
		baseInfo.validateFieldsAndScroll( ( errOut, valuesOut ) => {
			if ( !errOut ) {
				need.validateFieldsAndScroll( ( err, values ) => {
					if ( !err ) {
						let result = {
							data: Object.assign( values, valuesOut, { expenseAccount, residentQueryDtoList: dataList } ),
							fun: payModal.handleOver,
						};
						dispatch( { type: fun.fuse( modular[ path ].model, modular[ path ].action ), payload: result } );
					}
				} );
			}
		} );
	};
	/** 客服端-居民信息数据 */
	const orderData = {
		orderHandlerId,
		orderHandlerName,
		orderId: currentData.orderId,
		residentList: [],
	};
	/** 客服端-保存单条数据 */
	const saveRow = ( index, row ) => {
		orderData.residentList[ 0 ] = row;
		let result = {
			data: orderData,
			type: 'save',
		};
		dispatch( { type: fun.fuse( model.worker, action.worker_saveOrderDetail ), payload: result } );

	};
	/** 客服端-提交单条数据 */
	const submitRow = ( row, callBack ) => {
		orderData.residentList[ 0 ] = row;
		let result = {
			data: orderData,
			callBack: callBack,
			type: 'submit',
		};
		dispatch( { type: fun.fuse( model.worker, action.worker_saveOrderDetail ), payload: result } );
	};
	/** 客服端-返回列表页 */
	const backToList = () => {
		dispatch( routerRedux.push( { pathname: modular.index.url + modular.orderList.url, } ) );
	};
	/** 基本信息参数 */
	const baseInfoProps = {
		path,
		...currentData,
		entrustNumber: currentData.entrustNumber ? currentData.entrustNumber : entrustNumber,
		display: display,
		disabled: disabled,
	};
	/** 确认支付窗口参数 */
	const payModalProps = {
		handleSubmit: handleSubmit,
		remainingBalance: remainingBalance,
	};
	/** 居民信息样本参数 */
	const residentInfoProps = {
		name: modular[ path ].name,
		userType: userType,
		monitor: modular[ path ].monitor,
		data: dataList,
		disabled: disabled,
		onSave: ( i, r ) => saveRow( i, r ),
		onSubmit: ( r, callBack ) => submitRow( r, callBack ),
	};
	return (

			<Spin spinning={loading}>
				<PayModal ref={e => ( payModal = e )} {...payModalProps} />

{modular[ path ].cn + '委托表'}

				{userType === config.userType.doctor ?
					<OrderStep currentStep={currentStep}/>
					:
					<Button size="large" type="primary" className={styles.back} onClick={backToList}>返回</Button>
				}
				<Form onSubmit={showModal}>
					<BaseInfo {...baseInfoProps} ref={e => ( baseInfo = e )}/>
					{path === 'signFamily' ? <ResidentSign disabled={disabled} ref={e => ( need = e )} signSite={orgName}/> : ''}
					{path === 'residentSign' ? <ResidentSign disabled={disabled} ref={e => ( need = e )} signSite={orgName}/> : ''}
					{path === 'workeryyjmqy' ? <ResidentSign disabled={disabled} {...serviceDetail} /> : ''}
					{path === 'residentInspect' ? <ResidentInspect disabled={disabled} ref={e => ( need = e )} examineSite={orgName}/> : ''}
					{path === 'workeryyjmtj' ? <ResidentInspect disabled={disabled} {...serviceDetail} /> : ''}
					{path === 'newborn' ? <Newborn disabled={disabled} ref={e => ( need = e )}/> : ''}
					{path === 'workeryyxsfs' ? <Newborn disabled={disabled} {...serviceDetail} /> : ''}
					{path === 'postpartum' ? <Newborn disabled={disabled} ref={e => ( need = e )}/> : ''}
					{path === 'workeryychfs' ? <Newborn disabled={disabled} {...serviceDetail} /> : ''}

					{path === 'chronicDisease' ? <ChronicDisease disabled={disabled} ref={e => ( need = e )} interviewSite={orgName}/> : ''}
					{path === 'workermbsftz' ? <ChronicDisease disabled={disabled} {...serviceDetail} /> : ''}
					{path === 'newestPolicy' ? <NewestPolicy disabled={disabled} ref={e => ( need = e )}/> : ''}
					{path === 'workerzxzctz' ? <NewestPolicy disabled={disabled} {...serviceDetail} /> : ''}
					{path === 'newestActivity' ? <NewestActivity disabled={disabled} ref={e => ( need = e )}/> : ''}
					{path === 'workerzxhdtz' ? <NewestActivity disabled={disabled} {...serviceDetail} /> : ''}
					{path === 'antenatalCare' ? <AntenatalCare disabled={disabled} ref={e => ( need = e )} antenatalCareSite={orgName}/> : ''}
					{path === 'workeryfcjtz' ? <AntenatalCare disabled={disabled} {...serviceDetail} /> : ''}
					{path === 'childHealth' ? <ChildHealth disabled={disabled} ref={e => ( need = e )} interviewSite={orgName}/> : ''}
					{path === 'workeretsftz' ? <ChildHealth disabled={disabled} {...serviceDetail} /> : ''}

					{path === 'medication' ? <Medication disabled={disabled} ref={e => ( need = e )}/> : ''}
					{path === 'workeryytx00' ? <Medication disabled={disabled} {...serviceDetail} /> : ''}
					{path === 'curativeEffect' ? <Medication disabled={disabled} ref={e => ( need = e )}/> : ''}
					{path === 'workeryylxgz' ? <Medication disabled={disabled} {...serviceDetail} /> : ''}

					{path === 'hypertension' ? <Hypertension disabled={disabled} ref={e => ( need = e )}/> : ''}
					{path === 'workergxysf0' ? <Hypertension disabled={disabled} {...serviceDetail} /> : ''}
					{path === 'diabetes' ? <Diabetes disabled={disabled} ref={e => ( need = e )}/> : ''}
					{path === 'workertnbsf0' ? <Diabetes disabled={disabled} {...serviceDetail} /> : ''}

					<ResidentInfoTable {...residentInfoProps} ref={e => ( residentInfoTable = e )}/>
					{userType === config.userType.doctor ?

								<Button size="large" type="primary" onClick={validAndConfirm}>提交我的委托单信息</Button>

								<Row>
									<Col span={12}>
										<Button size="large" type="primary" htmlType="submit" style={{ width: 200 }} disabled={submitDisabled}
										        loading={loading}>确认委托并支付</Button>
									</Col>
									<Col span={12}>
										<Button size="large" type="primary" style={{ width: 200, display: displayBack }} onClick={validAndConfirm}>返回修改</Button>
										<Button size="large" type="primary" style={{ width: 200, display: displayNew }}
										        onClick={function () { location.reload() }}>新建委托单</Button>
									</Col>
								</Row>

 : ''}
				</Form>
			</Spin>

	);
};

const mapStateToProps = ( state ) => {
	return {
		...state,
		loading: state.orderModel ? state.loading.models.orderModel : state.loading.models.workerModel,
		user: state.appModel.user,
	};
};

export default connect( mapStateToProps )( Form.create()( OrderPage ) );
<commit_msg>orderPage<commit_after>import React from 'react';
import {connect} from 'dva';
import {routerRedux} from 'dva/router';
import {Spin, Row, Col, Form, Button, Modal} from 'antd';
import {action, model, fun, config, modular} from '../../common';
import {
	OrderStep,
	BaseInfo,
	ResidentInfoTable,
	PayModal,
	ResidentSign,
	ResidentInspect,
	Newborn,
	ChronicDisease,
	NewestPolicy,
	NewestActivity,
	AntenatalCare,
	ChildHealth,
	Medication,
	Hypertension,
	Diabetes,
} from '../../components';
import styles from './OrderPage.less';

let residentInfoTable;
let baseInfo;
let payModal;
let need;

let entrustNumber;
let dataList;

const OrderPage = ( {
	loading,
	orderModel,
	workerModel,
	dispatch,
	route,
	user,
} ) => {
	fun.printLoader( 'orderPage' );
	const { userType, orderHandlerId, orderHandlerName } = user;
	const { currentStep, displayConfirm, submitDisabled, displayBack, displayNew } = orderModel ? orderModel : {};
	const { serviceDetail, residentList } = workerModel ? workerModel : {};
	const { currentData, display, disabled } = workerModel ? workerModel : orderModel;
	const { orgName, remainingBalance } = currentData;

	/** 获取页面path,初始化dataList */
	let path = route.path.replace( '/', '' );
	if ( userType === config.userType.worker ) {
		dataList = residentList;
	} else {
		if ( !disabled ) {
			dataList = [];
		}
	}

	/** 医生端-校验表单输入数据*/
	const validAndConfirm = () => {
		baseInfo.validateFieldsAndScroll( ( errOut ) => {
			if ( !errOut ) {
				need.validateFieldsAndScroll( ( err ) => {
					if ( !err ) {
						dataList = residentInfoTable.getData();
						if ( dataList === undefined || dataList.length === 0 ) {
							Modal.error( {
								title: config.NODATA,
							} );
							return;
						}
						entrustNumber = dataList.length;
						dispatch( { type: fun.fuse( model.order, action.order_changeConfirmState ) } );
					}
				} );
			}
		} );
	};
	/** 医生端-显示确认支付窗口 */
	const showModal = ( e ) => {
		e.preventDefault();
		dispatch( {
			type: fun.fuse( model.app, action.APP_getItemPrice ),
			payload: { itemId: modular[ path ].ritRef, fun: payModal.showModal }
		} );
	};
	/** 医生端-提交表单数据 */
	const handleSubmit = ( expenseAccount ) => {
		baseInfo.validateFieldsAndScroll( ( errOut, valuesOut ) => {
			if ( !errOut ) {
				need.validateFieldsAndScroll( ( err, values ) => {
					if ( !err ) {
						let result = {
							data: Object.assign( values, valuesOut, { expenseAccount, residentQueryDtoList: dataList } ),
							fun: payModal.handleOver,
						};
						dispatch( { type: fun.fuse( modular[ path ].model, modular[ path ].action ), payload: result } );
					}
				} );
			}
		} );
	};
	/** 客服端-居民信息数据 */
	const orderData = {
		orderHandlerId,
		orderHandlerName,
		orderId: currentData.orderId,
		residentList: [],
	};
	/** 客服端-保存单条数据 */
	const saveRow = ( index, row ) => {
		orderData.residentList[ 0 ] = row;
		let result = {
			data: orderData,
			type: 'save',
		};
		dispatch( { type: fun.fuse( model.worker, action.worker_saveOrderDetail ), payload: result } );

	};
	/** 客服端-提交单条数据 */
	const submitRow = ( row, callBack ) => {
		orderData.residentList[ 0 ] = row;
		let result = {
			data: orderData,
			callBack: callBack,
			type: 'submit',
		};
		dispatch( { type: fun.fuse( model.worker, action.worker_saveOrderDetail ), payload: result } );
	};
	/** 客服端-返回列表页 */
	const backToList = () => {
		dispatch( routerRedux.push( { pathname: modular.index.url + modular.orderList.url, } ) );
	};
	/** 基本信息参数 */
	const baseInfoProps = {
		path,
		...currentData,
		entrustNumber: currentData.entrustNumber ? currentData.entrustNumber : entrustNumber,
		display: display,
		disabled: disabled,
	};
	/** 确认支付窗口参数 */
	const payModalProps = {
		handleSubmit: handleSubmit,
		remainingBalance: remainingBalance,
	};
	/** 居民信息样本参数 */
	const residentInfoProps = {
		name: modular[ path ].name,
		userType: userType,
		monitor: modular[ path ].monitor,
		data: dataList,
		disabled: disabled,
		onSave: ( i, r ) => saveRow( i, r ),
		onSubmit: ( r, callBack ) => submitRow( r, callBack ),
	};
	return (

			<Spin spinning={loading}>
				<PayModal ref={e => ( payModal = e )} {...payModalProps} />

{modular[ path ].cn + '委托表'}

				{userType === config.userType.doctor ?
					<OrderStep currentStep={currentStep}/>
					:
					<Button size="large" type="primary" className={styles.back} onClick={backToList}>返回</Button>
				}
				<Form onSubmit={showModal}>
					<BaseInfo {...baseInfoProps} ref={e => ( baseInfo = e )}/>
					{path === 'signFamily' ? <ResidentSign disabled={disabled} ref={e => ( need = e )} signSite={orgName}/> : ''}
					{path === 'residentSign' ? <ResidentSign disabled={disabled} ref={e => ( need = e )} signSite={orgName}/> : ''}
					{path === 'workeryyjmqy' ? <ResidentSign disabled={disabled} {...serviceDetail} /> : ''}
					{path === 'residentInspect' ? <ResidentInspect disabled={disabled} ref={e => ( need = e )} examineSite={orgName}/> : ''}
					{path === 'workeryyjmtj' ? <ResidentInspect disabled={disabled} {...serviceDetail} /> : ''}
					{path === 'newborn' ? <Newborn disabled={disabled} ref={e => ( need = e )}/> : ''}
					{path === 'workeryyxsfs' ? <Newborn disabled={disabled} {...serviceDetail} /> : ''}
					{path === 'postpartum' ? <Newborn disabled={disabled} ref={e => ( need = e )}/> : ''}
					{path === 'workeryychfs' ? <Newborn disabled={disabled} {...serviceDetail} /> : ''}

					{path === 'chronicDisease' ? <ChronicDisease disabled={disabled} ref={e => ( need = e )} interviewSite={orgName}/> : ''}
					{path === 'workermbsftz' ? <ChronicDisease disabled={disabled} {...serviceDetail} /> : ''}
					{path === 'newestPolicy' ? <NewestPolicy disabled={disabled} ref={e => ( need = e )}/> : ''}
					{path === 'workerzxzctz' ? <NewestPolicy disabled={disabled} {...serviceDetail} /> : ''}
					{path === 'newestActivity' ? <NewestActivity disabled={disabled} ref={e => ( need = e )}/> : ''}
					{path === 'workerzxhdtz' ? <NewestActivity disabled={disabled} {...serviceDetail} /> : ''}
					{path === 'antenatalCare' ? <AntenatalCare disabled={disabled} ref={e => ( need = e )} antenatalCareSite={orgName}/> : ''}
					{path === 'workeryfcjtz' ? <AntenatalCare disabled={disabled} {...serviceDetail} /> : ''}
					{path === 'childHealth' ? <ChildHealth disabled={disabled} ref={e => ( need = e )} interviewSite={orgName}/> : ''}
					{path === 'workeretsftz' ? <ChildHealth disabled={disabled} {...serviceDetail} /> : ''}

					{path === 'medication' ? <Medication disabled={disabled} ref={e => ( need = e )}/> : ''}
					{path === 'workeryytx00' ? <Medication disabled={disabled} {...serviceDetail} /> : ''}
					{path === 'curativeEffect' ? <Medication disabled={disabled} ref={e => ( need = e )}/> : ''}
					{path === 'workeryylxgz' ? <Medication disabled={disabled} {...serviceDetail} /> : ''}

					{path === 'hypertension' ? <Hypertension disabled={disabled} ref={e => ( need = e )}/> : ''}
					{path === 'workergxysf0' ? <Hypertension disabled={disabled} {...serviceDetail} /> : ''}
					{path === 'diabetes' ? <Diabetes disabled={disabled} ref={e => ( need = e )}/> : ''}
					{path === 'workertnbsf0' ? <Diabetes disabled={disabled} {...serviceDetail} /> : ''}

					<ResidentInfoTable {...residentInfoProps} ref={e => ( residentInfoTable = e )}/>
					{userType === config.userType.doctor ?

								<Button size="large" type="primary" onClick={validAndConfirm}>提交我的委托单信息</Button>

								<Row>
									<Col span={12}>
										<Button size="large" type="primary" htmlType="submit" style={{ width: 200 }} disabled={submitDisabled}
										        loading={loading}>确认委托并支付</Button>
									</Col>
									<Col span={12}>
										<Button size="large" type="primary" style={{ width: 200, display: displayBack }} onClick={validAndConfirm}>返回修改</Button>
										<Button size="large" type="primary" style={{ width: 200, display: displayNew }}
										        onClick={function () { location.reload() }}>新建委托单</Button>
									</Col>
								</Row>

 : ''}
				</Form>
			</Spin>

	);
};

const mapStateToProps = ( state ) => {
	return {
		...state,
		loading: state.orderModel ? state.loading.models.orderModel : state.loading.models.workerModel,
		user: state.appModel.user,
	};
};

export default connect( mapStateToProps )( Form.create()( OrderPage ) );
<|endoftext|>


<commit_before>import $ from 'jquery';
import { onMessage, addMessage } from '../messageQueue.js';
import { getCurrentScene } from '../currentScene.js';

export default class {
  constructor() {
    this.$frame = $('#game');
  }
  start() {
    this.messageBox = $('
');
    this.$frame.append(this.messageBox);
    onMessage((message) => this.displayMessage(message));
    addMessage(getCurrentScene().descriptionMessage());
  }
  displayMessage(message) {
    this.messageBox.children().addClass('disabled');
    this.messageBox.append(message);
    this.$frame.scrollTop(this.$frame[0].scrollHeight);
  }
}
<commit_msg>Initialize tooltips when showing message<commit_after>import $ from 'jquery';
import Tooltip from '../Tooltip.js';
import { onMessage, addMessage } from '../messageQueue.js';
import { getCurrentScene } from '../currentScene.js';

export default class {
  constructor() {
    this.$frame = $('#game');
  }
  start() {
    this.messageBox = $('
');
    this.$frame.append(this.messageBox);
    onMessage((message) => this.displayMessage(message));
    addMessage(getCurrentScene().descriptionMessage());
  }
  displayMessage(message) {
    this.messageBox.children().addClass('disabled');
    this.messageBox.append(message);
    for (var el of this.messageBox.find(".tooltip")) {
      new Tooltip(el);
    }
    this.$frame.scrollTop(this.$frame[0].scrollHeight);
  }
}
<|endoftext|>


<commit_before>/*!
 * Copyright (c) 2017, zoweb
 *
 * See the license in the LICENSE file (downloaded with this repository, in the root folder)
 * By using this code, you agree to the license in the file specified (the MIT license)
 */

(function (global, factory) {
    if (typeof module === "object" && typeof module.exports === "object") {
        module.exports = global.document ?
            factory(global, true) :
            w => factory(w);
    } else {
        factory(global);
    }
}(typeof window !== "undefined" ? window : this, (window, noGlobal) => {

const IS_BROWSER = typeof window !== "undefined";
const exports = {
    yessir: {}
};
const defineExportProperty = (proto, val) => {
    Object.defineProperty(exports.yessir, proto, val);
};

// say cheese
if (IS_BROWSER) console.log("      %cYes-Sir Assertion Libary\n" +
    "(c) zoweb 2017 | github/zoweb/yes-sir", "color:purple;font-weight:bold;");
else console.log(" __     __              _____ _      \n" +
    " \\ \\   / /             / ____(_)     \n" +
    "  \\ \\_/ /__  ___ _____| (___  _ _ __ \n" +
    "   \\   / _ \\/ __|______\\___ \\| | '__|\n" +
    "    | |  __/\\__ \\      ____) | | |   \n" +
    "    |_|\\___||___/     |_____/|_|_|   \n" +
    "                                     \n" +
    "                                     \n" +
    "          assertion library\n");

// %PAGE_CONTENTS%

// Export Yes-Sir
if (typeof noGlobal === "undefined") {
    // adds Exports object to window and sets window.YesSirNoConflict
    for (let current in exports) {
        if (!exports.hasOwnProperty(current)) continue;
        window[current] = exports[current];
    }

    /**
     * Returns the Yes-Sir object
     * @returns {Object} Yes-Sir object
     */
    window.YesSirNoConflict = function() {
        return exports;
    };
}

return exports;
}));<commit_msg>Added features, and removed bugs/annoyances<commit_after>/*!
 * Copyright (c) 2017, zoweb
 *
 * See the license in the LICENSE file (downloaded with this repository, in the root folder)
 * By using this code, you agree to the license in the file specified (the MIT license)
 */

(function (global, factory) {
    if (typeof module === "object" && typeof module.exports === "object") {
        module.exports = factory(module.exports, true);
    } else {
        factory(global);
    }
}(typeof window !== "undefined" ? window : this, (window, noGlobal) => {

const IS_BROWSER = typeof window !== "undefined";
const exports = {
    yessir: {}
};
const defineExportProperty = (proto, val) => {
    Object.defineProperty(exports.yessir, proto, val);
};

/*
// say cheese
if (IS_BROWSER) console.log("      %cYes-Sir Assertion Libary\n" +
    "(c) zoweb 2017 | github/zoweb/yes-sir", "color:purple;font-weight:bold;");
else console.log(" __     __              _____ _      \n" +
    " \\ \\   / /             / ____(_)     \n" +
    "  \\ \\_/ /__  ___ _____| (___  _ _ __ \n" +
    "   \\   / _ \\/ __|______\\___ \\| | '__|\n" +
    "    | |  __/\\__ \\      ____) | | |   \n" +
    "    |_|\\___||___/     |_____/|_|_|   \n" +
    "                                     \n" +
    "                                     \n" +
    "          assertion library\n");
*/

/* HEY THERE! I SEE YOU'RE INSPECTING THE SOURCE CODE! */
/* DO YOU WANT TO SPREAD THE WORD ABOUT Yes-Sir? IF YOUR */
/* ANSWER WAS "Yes, sir!", THEN MAKE SURE YOU UN-COMMENT OUT THE LINES BELOW "say cheese"! */

// %PAGE_CONTENTS%

// Export Yes-Sir
if (typeof noGlobal === "undefined") {
    // adds Exports object to window and sets window.YesSirNoConflict
    for (let current in exports) {
        if (!exports.hasOwnProperty(current)) continue;
        window[current] = exports[current];
    }

    /**
     * Returns the Yes-Sir object
     * @returns {Object} Yes-Sir object
     */
    window.YesSirNoConflict = function() {
        return exports;
    };
}/* else if (typeof module === "object" && typeof module.exports === "object") {
    exports.loadLanguage = function(location, languageName) {
        require(location);
        exports.setLanguage(languageName);
    };
}*/

return exports;
}));<|endoftext|>


<commit_before>head.ready(function() {

  $(document).ready(function() {
    // scrolling site
    if ($(window).width() > 961) {
      var pepe = $.fn.fullpage({
        slidesColor: ['#fff', '#4BBFC3', '#7BAABE', 'whitesmoke', '#ccddff'],
        anchors: ['firstPage', 'secondPage', '3rdPage', '4rdPage', 'lastPage'],
        menu: '#menu'
      });
    }
    if ($(window).width() < 960) {
      var pepe = $.fn.fullpage({
        slidesColor: ['#1bbc9b', '#4BBFC3', '#7BAABE', 'whitesmoke', '#ccddff'],
        anchors: ['firstPage', 'secondPage', '3rdPage', '4rdPage', 'lastPage'],
        menu: '#menu',
        autoScrolling: false
      });
    }

    //resize
    function res() {
      var innerHeight = $('#section1').height();
      $('.section2').css('height',innerHeight);
    }
    res();
    $(window).resize(function(){
      res();
    });

    //tab
    function tab() {
      $(".js-tab").each(function(){
        var tab_link = $(this).find("a");
        var tab_item = $(this).find("li");
        var tab_cont = $(this).parents(".js-tab-group").find(".js-tab-cont");
        tab_cont.hide();
        tab_item.first().addClass("is-active");
        $(this).parents(".js-tab-group").find(".js-tab1").fadeIn();
        tab_link.on("click", function() {
          var index = $(this).attr("href");
          tab_item.removeClass("is-active");
          $(this).parent().addClass("is-active");
          tab_cont.hide();
          $(this).parents(".js-tab-group").find("."+index).fadeIn();
          return false;
        });
        });
    } tab();
    // change slide for #section3
    $('.covering-media-img').hide();
    $('.js-covering-media-1').show();

    $('.js-covering-list-1').on('click', function() {
      $('.covering-media-img').hide();
      $('.js-covering-media-1').show();
      $('.covering-list-item').removeClass('is-active');
      $(this).addClass('is-active');
    });
    $('.js-covering-list-2').on('click', function() {
      $('.covering-media-img').hide();
      $('.js-covering-media-2').show();
      $('.covering-list-item').removeClass('is-active');
      $(this).addClass('is-active');
    });
    $('.js-covering-list-3').on('click', function() {
      $('.covering-media-img').hide();
      $('.js-covering-media-3').show();
      $('.covering-list-item').removeClass('is-active');
      $(this).addClass('is-active');
    });
    // change slide for #section4
    $( ".m-riverina" ).hover(
      function() {
        $( '.bowls-media-item' ).removeClass( "is-active" );
        $( '.bowls-media-riverina' ).addClass( "is-active" );
        $( '.bowls-item' ).removeClass( "is-active" )
        $( this ).addClass( "is-active" )
      }
    );
    $( ".m-xtrainer" ).hover(
      function() {
        $( '.bowls-media-item' ).removeClass( "is-active" );
        $( '.bowls-media-xtrainer' ).addClass( "is-active" );
        $( '.bowls-item' ).removeClass( "is-active" )
        $( this ).addClass( "is-active" )
      }
    );
    $( ".m-java" ).hover(
      function() {
        $( '.bowls-media-item' ).removeClass( "is-active" );
        $( '.bowls-media-java' ).addClass( "is-active" );
        $( '.bowls-item' ).removeClass( "is-active" )
        $( this ).addClass( "is-active" )
      }
    );
    $( ".m-vogue" ).hover(
      function() {
        $( '.bowls-media-item' ).removeClass( "is-active" );
        $( '.bowls-media-vogue' ).addClass( "is-active" );
        $( '.bowls-item' ).removeClass( "is-active" )
        $( this ).addClass( "is-active" )
      }
    );
    $( ".m-briliant" ).hover(
      function() {
        $( '.bowls-media-item' ).removeClass( "is-active" );
        $( '.bowls-media-briliant' ).addClass( "is-active" );
        $( '.bowls-item' ).removeClass( "is-active" )
        $( this ).addClass( "is-active" )
      }
    );

    // slick
    $('.responsive').slick({
      dots: false,
      infinite: false,
      speed: 300,
      slidesToShow: 5,
      slidesToScroll: 5,
      responsive: [
        {
          breakpoint: 970,
          settings: {
            slidesToShow: 1,
            slidesToScroll: 1,
            infinite: true,
            dots: false
          }
        },
      ]
    });
  });

  $('.bowls-item-btn').on('click', function() {
    $('.contact').fadeIn();
  });

});
<commit_msg>aaaaa<commit_after>head.ready(function() {

  Ezhi = {}

  var scrollTop = 0;
  var frames = 379;
  var swipeKd = 0;
  var loader = new PxLoader();
  var highResTimer = setTimeout(function () {
  }, 200);
  var testSpeed = 0;
  var scrollEvent = 0;
  var mobileWidth = 970;

  $(document).ready(function () {
      $(window).scrollTop(0);

      var progressBar = $('.js-loader-filler');
      var html = '';
      var domen = '';
      if (testSpeed == 1)
          domen = 'http://luxcoding.github.io/Limpid/build/';
      for (var i = 1; i <= frames; i++) {
          html += '

';
          loader.addImage(domen + 'photos_min/' + i + '.jpg');
          if (i == frames) {
              loader.addImage(domen + 'assets/i/back.jpg');
              loader.addImage(domen + 'assets/i/sprite.png');
              // loader.addImage(domen + 'assets/i/neo_logo_main_x2.png');
              loader.start();
          }
      }

      loader.addProgressListener(function (e) {
          var state = e.completedCount / e.totalCount * 100;
          var factor = $('.load-progress .loader-filler').width()/135;
          var stepX = (77/103*factor);
          var stepY = 27/100*factor;

          progressBar.css({left: stepX*state + 'px',top: stepY*state + 'px'});

      });

      loader.addCompletionListener(function () {
          $('.js-video-hedgehog').fadeIn(1000);
          $('.js-skip').fadeIn();
          $('.neo-logo-main').fadeIn(1000);
          $('.js-use-scroll').fadeIn();

          setTimeout(function () {
              $('body').removeClass('preload')
              $('.js-load-progress').hide();
          }, 1000);
      });

      $('.js-sequence').html(html);

      $('.js-video-slider').on('mousewheel', function (e) {
          var deltaY = e.deltaY > 0 ? 1 : -1;

          scrollImage(deltaY);

          return false;
      });

      //swipe
      $('.js-video-slider').on('move', function (e) {
          //чтобы листалось не сильно быстро, делаем соотношение 1 к 20.
          var deltaY = 0;

          if (e.deltaY > 0) {
              deltaY = 2;
          }
          if (e.deltaY < 0) {
              deltaY = -2;
          }

          if (deltaY != 0) {
              swipeKd += 1;
              if (swipeKd == 1) {
                  scrollImage(deltaY);
                  swipeKd = 0;
              }
          }

      });

      setInterval(function () {
          if (window.scrollTop > 0)
              scrollImage(-1);
          if (window.scrollTop < window.frames * -1)
              scrollImage(1);
      }, 1);

      $('.js-progress').slider({
          slide: function (event, ui) {
              var step = window.frames / 100;
              window.scrollTop = Math.round(step * ui.value * -1);
              scrollImage(0);
          }
      });

      /////////////
      ///CONTENT///
      /////////////

      $(document).on("click", ".content-after-video div.contacts span", function () {
          $(this).hide();
          $('.content-after-video div.contacts .hidden').slideDown(100);
          ga('send', 'event', 'Внутренняя', 'Клик', 'Контакты');

      });

      $(document).on("click", ".js-skip", function () {
          ga('send', 'event', 'Главная', 'Слайдер', 'Пропустить');
          scrollImage(frames * -1);
          return false;
      });

      ///center content///

      $(window).resize(function () {
          var H = $(this).height(),
              W = $(this).width();
          var ezh = H / 3 / 2;
          var text = (H - ezh) / 5 - 32;
          var plan = (H - 150 - 51 - 100 - $('.plan-gallery .photos img:visible').height()) / 2;
          var photo = (H - 100 - 20 - 51 - 150 - $('.photo-gallery .photos img:visible').height()) / 2;
          if (plan < 0) plan = 0;
    if(photo < 0) photo = 0;
    var mini_photos = photo + 30;
          $('.js-content-after-video').css({paddingTop: ezh});
          $('.js-logo-green').css({marginTop: ezh});
          $('.js-use-scroll').css({marginTop: H/5*4});
          $('.js-text-blocks').css({marginTop: text});
          $('.plan-gallery .photos img').css({marginTop: plan});
          $('.photo-gallery .photos img').css({marginTop: photo});
          $('.js-load-progress').css({marginTop: ezh});
          $('.neo-logo-main').css({marginTop: ezh})
    $('.photo-gallery .js-mini-photos').css({bottom:mini_photos});

      });

      $(window).resize();

      $('.js-skip').stop(1, 1).hide();
      $('.js-logo-green').stop(1, 1).hide();
      $('.js-use-scroll').stop(1, 1).hide();

      $(document).on('click', '.js-mini-photos li a', function () {
          if (!$(this).hasClass('active')) {
              gallery_step($(this).parents('li').index(), $(this).parents('.js-gallery'));
          }
          return false;
      });

      $(document).on('click', '.text-block-one a', function () {
          setTimeout(function () {
              $(window).resize()
          }, 100)
          $('.popup.plan-gallery').fadeIn();
    $('body').addClass('popup-open');
          $(window).scrollTop(0);
          ga('send', 'event', 'Внутренняя', 'Клик', 'Планировки');
          return false;
      });

      $(document).on('click', '.text-block-two a', function () {
          setTimeout(function () {
              $(window).resize()
          }, 100)
          $('.popup.photo-gallery').fadeIn();
          $(window).scrollTop(0);
    $('body').addClass('popup-open');
          ga('send', 'event', 'Внутренняя', 'Клик', 'Фото');
          return false;
      });

      $(document).on('click', '.js-close', function () {
          $(this).parents('.popup').fadeOut(100);
    $('body').removeClass('popup-open');
          return false;
      });

      $(document).on('click', '.js-nav', function () {
          var gallery = $(this).parents('.js-gallery');
          var count = $('.js-photos li', gallery).length;
          var current = $('.js-photos li:visible').index();
          if ($(this).hasClass('js-nav-right')) {
              if (current == (count - 1)) {
                  gallery_step(0, gallery);
              }
              else {
                  gallery_step(current + 1, gallery)
              }
          }
          else {
              if (current == 0) {
                  gallery_step((count - 1), gallery);
              }
              else {
                  gallery_step((current - 1), gallery)
              }
          }

      });

      $(document).on('click', 'footer .left', function () {
          $('.js-neo-logo').show();
          $('.js-neo-logo img').stop(1,1).animate({top:0});

          $(this).hide();
      });

      $(document).on('click', '.js-neo-logo', function () {

          $('.js-neo-logo img').animate({top:112},function(){
              $('.js-neo-logo').hide();
              $('footer .left').show();
          });

      });

      $('.plan-gallery .photos img').loupe();

      //debug
      /*    setTimeout(function(){
       scrollImage(frames*-1);
       },200)*/
      //end debug

  });

  function scrollImage(dir) {//движение списка с изображениями
      $('.js-load-progress').hide();
      clearTimeout(highResTimer);

      if ((dir <= 0 && scrollTop > (frames * -1) + 1) || (dir > 0 && scrollTop < 0)) {
          scrollTop = scrollTop + dir;
          $('.js-sequence').css({top: scrollTop * 100 + '%'});
          progress_update();
      }

      if (scrollTop < (frames * -1) + 2) {
          $('.js-video-hedgehog').stop(1, 1).fadeOut(1000, function () {
              $('body').removeClass('overflow');
          });
          $('body').removeClass('video');
          $('.js-content-after-video').fadeIn();
          ga('send', 'event', 'Главная', 'Слайдер', 'Конец');

      }

      highResTimer = setTimeout(function () {
          var i = (scrollTop * -1) + 1
          $('.js-sequence li').eq(i - 1).html('')
      }, 100);

      if (scrollTop < 0) {
          $('.js-skip').fadeOut();
          $('.neo-logo-main').fadeOut(800);
          $('.js-use-scroll').fadeOut();
          $('.js-progress').show();
          $('.progress-disable').show();

      }
      else {
          $('.js-skip').fadeIn();
          $('.neo-logo-main').fadeIn(800);
          $('.js-use-scroll').fadeIn();
          $('.js-progress').fadeOut();
          $('.progress-disable').hide();

      }

      if (scrollTop * -1 >= frames / 2 && scrollEvent == 0) {
          ga('send', 'event', 'Главная', 'Слайдер', 'Середина');
          scrollEvent = 1;
      }
      $(window).scrollTop(0);
  }

  function progress_update() {//прогресс бар с ежом
      var $hedgehog = $('.js-progress a');

      var step = 100 / window.frames;

      var margin = step * window.scrollTop * -1;

      $hedgehog.css({left: margin + '%'});
  }

  function moveToStart() {
      $(window).scrollTop(0);
      scrollImage(frames);
      $('body').addClass('overflow video');
      $('.js-video-hedgehog').stop(1, 1).show();
      $('.js-content-after-video').hide();
  }

  function gallery_step(step, gallery) {
      $('.js-mini-photos li.active', gallery).removeClass('active');
      $('.js-mini-photos li', gallery).eq(step).addClass('active');
      if($(window).width() <= mobileWidth ){
          $('.js-photos li', gallery).hide();
          $('.js-photos li', gallery).eq(step).show();
      }
      else {
          $('.js-photos li', gallery).fadeOut();
          $('.js-photos li', gallery).eq(step).fadeIn();
      }

  }

  $(document).ready(function() {

    // scrolling site
    if ($(window).width() > 961) {
      var pepe = $.fn.fullpage({
        slidesColor: ['#fff', '#4BBFC3', '#7BAABE', 'whitesmoke', '#ccddff'],
        anchors: ['firstPage', 'secondPage', '3rdPage', '4rdPage', 'lastPage'],
        menu: '#menu'
      });
    }
    if ($(window).width() < 960) {
      var pepe = $.fn.fullpage({
        slidesColor: ['#1bbc9b', '#4BBFC3', '#7BAABE', 'whitesmoke', '#ccddff'],
        anchors: ['firstPage', 'secondPage', '3rdPage', '4rdPage', 'lastPage'],
        menu: '#menu',
        autoScrolling: false
      });
    }

    //resize
    function res() {
      var innerHeight = $('#section1').height();
      $('.section2').css('height',innerHeight);
    }
    res();
    $(window).resize(function(){
      res();
    });

    //tab
    function tab() {
      $(".js-tab").each(function(){
        var tab_link = $(this).find("a");
        var tab_item = $(this).find("li");
        var tab_cont = $(this).parents(".js-tab-group").find(".js-tab-cont");
        tab_cont.hide();
        tab_item.first().addClass("is-active");
        $(this).parents(".js-tab-group").find(".js-tab1").fadeIn();
        tab_link.on("click", function() {
          var index = $(this).attr("href");
          tab_item.removeClass("is-active");
          $(this).parent().addClass("is-active");
          tab_cont.hide();
          $(this).parents(".js-tab-group").find("."+index).fadeIn();
          return false;
        });
        });
    } tab();
    // change slide for #section3
    $('.covering-media-img').hide();
    $('.js-covering-media-1').show();

    $('.js-covering-list-1').on('click', function() {
      $('.covering-media-img').hide();
      $('.js-covering-media-1').show();
      $('.covering-list-item').removeClass('is-active');
      $(this).addClass('is-active');
    });
    $('.js-covering-list-2').on('click', function() {
      $('.covering-media-img').hide();
      $('.js-covering-media-2').show();
      $('.covering-list-item').removeClass('is-active');
      $(this).addClass('is-active');
    });
    $('.js-covering-list-3').on('click', function() {
      $('.covering-media-img').hide();
      $('.js-covering-media-3').show();
      $('.covering-list-item').removeClass('is-active');
      $(this).addClass('is-active');
    });
    // change slide for #section4
    $( ".m-riverina" ).hover(
      function() {
        $( '.bowls-media-item' ).removeClass( "is-active" );
        $( '.bowls-media-riverina' ).addClass( "is-active" );
        $( '.bowls-item' ).removeClass( "is-active" )
        $( this ).addClass( "is-active" )
      }
    );
    $( ".m-xtrainer" ).hover(
      function() {
        $( '.bowls-media-item' ).removeClass( "is-active" );
        $( '.bowls-media-xtrainer' ).addClass( "is-active" );
        $( '.bowls-item' ).removeClass( "is-active" )
        $( this ).addClass( "is-active" )
      }
    );
    $( ".m-java" ).hover(
      function() {
        $( '.bowls-media-item' ).removeClass( "is-active" );
        $( '.bowls-media-java' ).addClass( "is-active" );
        $( '.bowls-item' ).removeClass( "is-active" )
        $( this ).addClass( "is-active" )
      }
    );
    $( ".m-vogue" ).hover(
      function() {
        $( '.bowls-media-item' ).removeClass( "is-active" );
        $( '.bowls-media-vogue' ).addClass( "is-active" );
        $( '.bowls-item' ).removeClass( "is-active" )
        $( this ).addClass( "is-active" )
      }
    );
    $( ".m-briliant" ).hover(
      function() {
        $( '.bowls-media-item' ).removeClass( "is-active" );
        $( '.bowls-media-briliant' ).addClass( "is-active" );
        $( '.bowls-item' ).removeClass( "is-active" )
        $( this ).addClass( "is-active" )
      }
    );

    // slick
    $('.responsive').slick({
      dots: false,
      infinite: false,
      speed: 300,
      slidesToShow: 5,
      slidesToScroll: 5,
      responsive: [
        {
          breakpoint: 970,
          settings: {
            slidesToShow: 1,
            slidesToScroll: 1,
            infinite: true,
            dots: false
          }
        },
      ]
    });
  });

  $('.bowls-item-btn').on('click', function() {
    $('.contact').fadeIn();
  });

});
<|endoftext|>