<commit_before>/* eslint no-param-reassign: "off" */
import $ from '../../utils/dom';
import Utils from '../../utils/utils';
import Support from '../../utils/support';

import SwiperClass from '../../utils/class';

import update from './update/index';
import translate from './translate/index';
import transition from './transition/index';
import slide from './slide/index';
import loop from './loop/index';
import grabCursor from './grab-cursor/index';
import manipulation from './manipulation/index';
import events from './events/index';
import breakpoints from './breakpoints/index';
import classes from './classes/index';
import images from './images/index';
import checkOverflow from './check-overflow/index';

import defaults from './defaults';

const prototypes = {
  update,
  translate,
  transition,
  slide,
  loop,
  grabCursor,
  manipulation,
  events,
  breakpoints,
  checkOverflow,
  classes,
  images,
};

const extendedDefaults = {};

class Swiper extends SwiperClass {
  constructor(...args) {
    let el;
    let params;
    if (args.length === 1 && args[0].constructor && args[0].constructor === Object) {
      params = args[0];
    } else {
      [el, params] = args;
    }
    if (!params) params = {};

    params = Utils.extend({}, params);
    if (el && !params.el) params.el = el;

    super(params);

    Object.keys(prototypes).forEach((prototypeGroup) => {
      Object.keys(prototypes[prototypeGroup]).forEach((protoMethod) => {
        if (!Swiper.prototype[protoMethod]) {
          Swiper.prototype[protoMethod] = prototypes[prototypeGroup][protoMethod];
        }
      });
    });

    // Swiper Instance
    const swiper = this;
    if (typeof swiper.modules === 'undefined') {
      swiper.modules = {};
    }
    Object.keys(swiper.modules).forEach((moduleName) => {
      const module = swiper.modules[moduleName];
      if (module.params) {
        const moduleParamName = Object.keys(module.params)[0];
        const moduleParams = module.params[moduleParamName];
        if (typeof moduleParams !== 'object' || moduleParams === null) return;
        if (!(moduleParamName in params && 'enabled' in moduleParams)) return;
        if (params[moduleParamName] === true) {
          params[moduleParamName] = { enabled: true };
        }
        if (
          typeof params[moduleParamName] === 'object'
          && !('enabled' in params[moduleParamName])
        ) {
          params[moduleParamName].enabled = true;
        }
        if (!params[moduleParamName]) params[moduleParamName] = { enabled: false };
      }
    });

    // Extend defaults with modules params
    const swiperParams = Utils.extend({}, defaults);
    swiper.useModulesParams(swiperParams);

    // Extend defaults with passed params
    swiper.params = Utils.extend({}, swiperParams, extendedDefaults, params);
    swiper.originalParams = Utils.extend({}, swiper.params);
    swiper.passedParams = Utils.extend({}, params);

    // Save Dom lib
    swiper.$ = $;

    // Find el
    const $el = $(swiper.params.el);
    el = $el[0];

    if (!el) {
      return undefined;
    }

    if ($el.length > 1) {
      const swipers = [];
      $el.each((index, containerEl) => {
        const newParams = Utils.extend({}, params, { el: containerEl });
        swipers.push(new Swiper(newParams));
      });
      return swipers;
    }

    el.swiper = swiper;
    $el.data('swiper', swiper);

    // Find Wrapper
    let $wrapperEl;
    if (el && el.shadowRoot && el.shadowRoot.querySelector) {
      $wrapperEl = $(el.shadowRoot.querySelector(`.${swiper.params.wrapperClass}`));
      // Children needs to return slot items
      $wrapperEl.children = (options) => $el.children(options);
    } else {
      $wrapperEl = $el.children(`.${swiper.params.wrapperClass}`);
    }
    // Extend Swiper
    Utils.extend(swiper, {
      $el,
      el,
      $wrapperEl,
      wrapperEl: $wrapperEl[0],

      // Classes
      classNames: [],

      // Slides
      slides: $(),
      slidesGrid: [],
      snapGrid: [],
      slidesSizesGrid: [],

      // isDirection
      isHorizontal() {
        return swiper.params.direction === 'horizontal';
      },
      isVertical() {
        return swiper.params.direction === 'vertical';
      },
      // RTL
      rtl: (el.dir.toLowerCase() === 'rtl' || $el.css('direction') === 'rtl'),
      rtlTranslate: swiper.params.direction === 'horizontal' && (el.dir.toLowerCase() === 'rtl' || $el.css('direction') === 'rtl'),
      wrongRTL: $wrapperEl.css('display') === '-webkit-box',

      // Indexes
      activeIndex: 0,
      realIndex: 0,

      //
      isBeginning: true,
      isEnd: false,

      // Props
      translate: 0,
      previousTranslate: 0,
      progress: 0,
      velocity: 0,
      animating: false,

      // Locks
      allowSlideNext: swiper.params.allowSlideNext,
      allowSlidePrev: swiper.params.allowSlidePrev,

      // Touch Events
      touchEvents: (function touchEvents() {
        const touch = ['touchstart', 'touchmove', 'touchend', 'touchcancel'];
        let desktop = ['mousedown', 'mousemove', 'mouseup'];
        if (Support.pointerEvents) {
          desktop = ['pointerdown', 'pointermove', 'pointerup'];
        }
        swiper.touchEventsTouch = {
          start: touch[0],
          move: touch[1],
          end: touch[2],
          cancel: touch[3],
        };
        swiper.touchEventsDesktop = {
          start: desktop[0],
          move: desktop[1],
          end: desktop[2],
        };
        return Support.touch || !swiper.params.simulateTouch ? swiper.touchEventsTouch : swiper.touchEventsDesktop;
      }()),
      touchEventsData: {
        isTouched: undefined,
        isMoved: undefined,
        allowTouchCallbacks: undefined,
        touchStartTime: undefined,
        isScrolling: undefined,
        currentTranslate: undefined,
        startTranslate: undefined,
        allowThresholdMove: undefined,
        // Form elements to match
        formElements: 'input, select, option, textarea, button, video',
        // Last click time
        lastClickTime: Utils.now(),
        clickTimeout: undefined,
        // Velocities
        velocities: [],
        allowMomentumBounce: undefined,
        isTouchEvent: undefined,
        startMoving: undefined,
      },

      // Clicks
      allowClick: true,

      // Touches
      allowTouchMove: swiper.params.allowTouchMove,

      touches: {
        startX: 0,
        startY: 0,
        currentX: 0,
        currentY: 0,
        diff: 0,
      },

      // Images
      imagesToLoad: [],
      imagesLoaded: 0,

    });

    // Install Modules
    swiper.useModules();

    // Init
    if (swiper.params.init) {
      swiper.init();
    }

    // Return app instance
    return swiper;
  }

  slidesPerViewDynamic() {
    const swiper = this;
    const {
      params, slides, slidesGrid, size: swiperSize, activeIndex,
    } = swiper;
    let spv = 1;
    if (params.centeredSlides) {
      let slideSize = slides[activeIndex].swiperSlideSize;
      let breakLoop;
      for (let i = activeIndex + 1; i < slides.length; i += 1) {
        if (slides[i] && !breakLoop) {
          slideSize += slides[i].swiperSlideSize;
          spv += 1;
          if (slideSize > swiperSize) breakLoop = true;
        }
      }
      for (let i = activeIndex - 1; i >= 0; i -= 1) {
        if (slides[i] && !breakLoop) {
          slideSize += slides[i].swiperSlideSize;
          spv += 1;
          if (slideSize > swiperSize) breakLoop = true;
        }
      }
    } else {
      for (let i = activeIndex + 1; i < slides.length; i += 1) {
        if (slidesGrid[i] - slidesGrid[activeIndex] < swiperSize) {
          spv += 1;
        }
      }
    }
    return spv;
  }

  update() {
    const swiper = this;
    if (!swiper || swiper.destroyed) return;
    const { snapGrid, params } = swiper;
    // Breakpoints
    if (params.breakpoints) {
      swiper.setBreakpoint();
    }
    swiper.updateSize();
    swiper.updateSlides();
    swiper.updateProgress();
    swiper.updateSlidesClasses();

    function setTranslate() {
      const translateValue = swiper.rtlTranslate ? swiper.translate * -1 : swiper.translate;
      const newTranslate = Math.min(Math.max(translateValue, swiper.maxTranslate()), swiper.minTranslate());
      swiper.setTranslate(newTranslate);
      swiper.updateActiveIndex();
      swiper.updateSlidesClasses();
    }
    let translated;
    if (swiper.params.freeMode) {
      setTranslate();
      if (swiper.params.autoHeight) {
        swiper.updateAutoHeight();
      }
    } else {
      if ((swiper.params.slidesPerView === 'auto' || swiper.params.slidesPerView > 1) && swiper.isEnd && !swiper.params.centeredSlides) {
        translated = swiper.slideTo(swiper.slides.length - 1, 0, false, true);
      } else {
        translated = swiper.slideTo(swiper.activeIndex, 0, false, true);
      }
      if (!translated) {
        setTranslate();
      }
    }
    if (params.watchOverflow && snapGrid !== swiper.snapGrid) {
      swiper.checkOverflow();
    }
    swiper.emit('update');
  }

  changeDirection(newDirection, needUpdate = true) {
    const swiper = this;
    const currentDirection = swiper.params.direction;
    if (!newDirection) {
      // eslint-disable-next-line
      newDirection = currentDirection === 'horizontal' ? 'vertical' : 'horizontal';
    }
    if ((newDirection === currentDirection) || (newDirection !== 'horizontal' && newDirection !== 'vertical')) {
      return swiper;
    }

    swiper.$el
      .removeClass(`${swiper.params.containerModifierClass}${currentDirection}`)
      .addClass(`${swiper.params.containerModifierClass}${newDirection}`);

    swiper.params.direction = newDirection;

    swiper.slides.each((slideIndex, slideEl) => {
      if (newDirection === 'vertical') {
        slideEl.style.width = '';
      } else {
        slideEl.style.height = '';
      }
    });

    swiper.emit('changeDirection');
    if (needUpdate) swiper.update();

    return swiper;
  }

  init() {
    const swiper = this;
    if (swiper.initialized) return;

    swiper.emit('beforeInit');

    // Set breakpoint
    if (swiper.params.breakpoints) {
      swiper.setBreakpoint();
    }

    // Add Classes
    swiper.addClasses();

    // Create loop
    if (swiper.params.loop) {
      swiper.loopCreate();
    }

    // Update size
    swiper.updateSize();

    // Update slides
    swiper.updateSlides();

    if (swiper.params.watchOverflow) {
      swiper.checkOverflow();
    }

    // Set Grab Cursor
    if (swiper.params.grabCursor) {
      swiper.setGrabCursor();
    }

    if (swiper.params.preloadImages) {
      swiper.preloadImages();
    }

    // Slide To Initial Slide
    if (swiper.params.loop) {
      swiper.slideTo(swiper.params.initialSlide + swiper.loopedSlides, 0, swiper.params.runCallbacksOnInit);
    } else {
      swiper.slideTo(swiper.params.initialSlide, 0, swiper.params.runCallbacksOnInit);
    }

    // Attach events
    swiper.attachEvents();

    // Init Flag
    swiper.initialized = true;

    // Emit
    swiper.emit('init');
  }

  destroy(deleteInstance = true, cleanStyles = true) {
    const swiper = this;
    const {
      params, $el, $wrapperEl, slides,
    } = swiper;

    if (typeof swiper.params === 'undefined' || swiper.destroyed) {
      return null;
    }

    swiper.emit('beforeDestroy');

    // Init Flag
    swiper.initialized = false;

    // Detach events
    swiper.detachEvents();

    // Destroy loop
    if (params.loop) {
      swiper.loopDestroy();
    }

    // Cleanup styles
    if (cleanStyles) {
      swiper.removeClasses();
      $el.removeAttr('style');
      $wrapperEl.removeAttr('style');
      if (slides && slides.length) {
        slides
          .removeClass([
            params.slideVisibleClass,
            params.slideActiveClass,
            params.slideNextClass,
            params.slidePrevClass,
          ].join(' '))
          .removeAttr('style')
          .removeAttr('data-swiper-slide-index');
      }
    }

    swiper.emit('destroy');

    // Detach emitter events
    Object.keys(swiper.eventsListeners).forEach((eventName) => {
      swiper.off(eventName);
    });

    if (deleteInstance !== false) {
      swiper.$el[0].swiper = null;
      swiper.$el.data('swiper', null);
      Utils.deleteProps(swiper);
    }
    swiper.destroyed = true;

    return null;
  }

  static extendDefaults(newDefaults) {
    Utils.extend(extendedDefaults, newDefaults);
  }

  static get extendedDefaults() {
    return extendedDefaults;
  }

  static get defaults() {
    return defaults;
  }

  static get Class() {
    return SwiperClass;
  }

  static get $() {
    return $;
  }
}

export default Swiper;
<commit_msg>add label to formElements<commit_after>/* eslint no-param-reassign: "off" */
import $ from '../../utils/dom';
import Utils from '../../utils/utils';
import Support from '../../utils/support';

import SwiperClass from '../../utils/class';

import update from './update/index';
import translate from './translate/index';
import transition from './transition/index';
import slide from './slide/index';
import loop from './loop/index';
import grabCursor from './grab-cursor/index';
import manipulation from './manipulation/index';
import events from './events/index';
import breakpoints from './breakpoints/index';
import classes from './classes/index';
import images from './images/index';
import checkOverflow from './check-overflow/index';

import defaults from './defaults';

const prototypes = {
  update,
  translate,
  transition,
  slide,
  loop,
  grabCursor,
  manipulation,
  events,
  breakpoints,
  checkOverflow,
  classes,
  images,
};

const extendedDefaults = {};

class Swiper extends SwiperClass {
  constructor(...args) {
    let el;
    let params;
    if (args.length === 1 && args[0].constructor && args[0].constructor === Object) {
      params = args[0];
    } else {
      [el, params] = args;
    }
    if (!params) params = {};

    params = Utils.extend({}, params);
    if (el && !params.el) params.el = el;

    super(params);

    Object.keys(prototypes).forEach((prototypeGroup) => {
      Object.keys(prototypes[prototypeGroup]).forEach((protoMethod) => {
        if (!Swiper.prototype[protoMethod]) {
          Swiper.prototype[protoMethod] = prototypes[prototypeGroup][protoMethod];
        }
      });
    });

    // Swiper Instance
    const swiper = this;
    if (typeof swiper.modules === 'undefined') {
      swiper.modules = {};
    }
    Object.keys(swiper.modules).forEach((moduleName) => {
      const module = swiper.modules[moduleName];
      if (module.params) {
        const moduleParamName = Object.keys(module.params)[0];
        const moduleParams = module.params[moduleParamName];
        if (typeof moduleParams !== 'object' || moduleParams === null) return;
        if (!(moduleParamName in params && 'enabled' in moduleParams)) return;
        if (params[moduleParamName] === true) {
          params[moduleParamName] = { enabled: true };
        }
        if (
          typeof params[moduleParamName] === 'object'
          && !('enabled' in params[moduleParamName])
        ) {
          params[moduleParamName].enabled = true;
        }
        if (!params[moduleParamName]) params[moduleParamName] = { enabled: false };
      }
    });

    // Extend defaults with modules params
    const swiperParams = Utils.extend({}, defaults);
    swiper.useModulesParams(swiperParams);

    // Extend defaults with passed params
    swiper.params = Utils.extend({}, swiperParams, extendedDefaults, params);
    swiper.originalParams = Utils.extend({}, swiper.params);
    swiper.passedParams = Utils.extend({}, params);

    // Save Dom lib
    swiper.$ = $;

    // Find el
    const $el = $(swiper.params.el);
    el = $el[0];

    if (!el) {
      return undefined;
    }

    if ($el.length > 1) {
      const swipers = [];
      $el.each((index, containerEl) => {
        const newParams = Utils.extend({}, params, { el: containerEl });
        swipers.push(new Swiper(newParams));
      });
      return swipers;
    }

    el.swiper = swiper;
    $el.data('swiper', swiper);

    // Find Wrapper
    let $wrapperEl;
    if (el && el.shadowRoot && el.shadowRoot.querySelector) {
      $wrapperEl = $(el.shadowRoot.querySelector(`.${swiper.params.wrapperClass}`));
      // Children needs to return slot items
      $wrapperEl.children = (options) => $el.children(options);
    } else {
      $wrapperEl = $el.children(`.${swiper.params.wrapperClass}`);
    }
    // Extend Swiper
    Utils.extend(swiper, {
      $el,
      el,
      $wrapperEl,
      wrapperEl: $wrapperEl[0],

      // Classes
      classNames: [],

      // Slides
      slides: $(),
      slidesGrid: [],
      snapGrid: [],
      slidesSizesGrid: [],

      // isDirection
      isHorizontal() {
        return swiper.params.direction === 'horizontal';
      },
      isVertical() {
        return swiper.params.direction === 'vertical';
      },
      // RTL
      rtl: (el.dir.toLowerCase() === 'rtl' || $el.css('direction') === 'rtl'),
      rtlTranslate: swiper.params.direction === 'horizontal' && (el.dir.toLowerCase() === 'rtl' || $el.css('direction') === 'rtl'),
      wrongRTL: $wrapperEl.css('display') === '-webkit-box',

      // Indexes
      activeIndex: 0,
      realIndex: 0,

      //
      isBeginning: true,
      isEnd: false,

      // Props
      translate: 0,
      previousTranslate: 0,
      progress: 0,
      velocity: 0,
      animating: false,

      // Locks
      allowSlideNext: swiper.params.allowSlideNext,
      allowSlidePrev: swiper.params.allowSlidePrev,

      // Touch Events
      touchEvents: (function touchEvents() {
        const touch = ['touchstart', 'touchmove', 'touchend', 'touchcancel'];
        let desktop = ['mousedown', 'mousemove', 'mouseup'];
        if (Support.pointerEvents) {
          desktop = ['pointerdown', 'pointermove', 'pointerup'];
        }
        swiper.touchEventsTouch = {
          start: touch[0],
          move: touch[1],
          end: touch[2],
          cancel: touch[3],
        };
        swiper.touchEventsDesktop = {
          start: desktop[0],
          move: desktop[1],
          end: desktop[2],
        };
        return Support.touch || !swiper.params.simulateTouch ? swiper.touchEventsTouch : swiper.touchEventsDesktop;
      }()),
      touchEventsData: {
        isTouched: undefined,
        isMoved: undefined,
        allowTouchCallbacks: undefined,
        touchStartTime: undefined,
        isScrolling: undefined,
        currentTranslate: undefined,
        startTranslate: undefined,
        allowThresholdMove: undefined,
        // Form elements to match
        formElements: 'input, select, option, textarea, button, video, label',
        // Last click time
        lastClickTime: Utils.now(),
        clickTimeout: undefined,
        // Velocities
        velocities: [],
        allowMomentumBounce: undefined,
        isTouchEvent: undefined,
        startMoving: undefined,
      },

      // Clicks
      allowClick: true,

      // Touches
      allowTouchMove: swiper.params.allowTouchMove,

      touches: {
        startX: 0,
        startY: 0,
        currentX: 0,
        currentY: 0,
        diff: 0,
      },

      // Images
      imagesToLoad: [],
      imagesLoaded: 0,

    });

    // Install Modules
    swiper.useModules();

    // Init
    if (swiper.params.init) {
      swiper.init();
    }

    // Return app instance
    return swiper;
  }

  slidesPerViewDynamic() {
    const swiper = this;
    const {
      params, slides, slidesGrid, size: swiperSize, activeIndex,
    } = swiper;
    let spv = 1;
    if (params.centeredSlides) {
      let slideSize = slides[activeIndex].swiperSlideSize;
      let breakLoop;
      for (let i = activeIndex + 1; i < slides.length; i += 1) {
        if (slides[i] && !breakLoop) {
          slideSize += slides[i].swiperSlideSize;
          spv += 1;
          if (slideSize > swiperSize) breakLoop = true;
        }
      }
      for (let i = activeIndex - 1; i >= 0; i -= 1) {
        if (slides[i] && !breakLoop) {
          slideSize += slides[i].swiperSlideSize;
          spv += 1;
          if (slideSize > swiperSize) breakLoop = true;
        }
      }
    } else {
      for (let i = activeIndex + 1; i < slides.length; i += 1) {
        if (slidesGrid[i] - slidesGrid[activeIndex] < swiperSize) {
          spv += 1;
        }
      }
    }
    return spv;
  }

  update() {
    const swiper = this;
    if (!swiper || swiper.destroyed) return;
    const { snapGrid, params } = swiper;
    // Breakpoints
    if (params.breakpoints) {
      swiper.setBreakpoint();
    }
    swiper.updateSize();
    swiper.updateSlides();
    swiper.updateProgress();
    swiper.updateSlidesClasses();

    function setTranslate() {
      const translateValue = swiper.rtlTranslate ? swiper.translate * -1 : swiper.translate;
      const newTranslate = Math.min(Math.max(translateValue, swiper.maxTranslate()), swiper.minTranslate());
      swiper.setTranslate(newTranslate);
      swiper.updateActiveIndex();
      swiper.updateSlidesClasses();
    }
    let translated;
    if (swiper.params.freeMode) {
      setTranslate();
      if (swiper.params.autoHeight) {
        swiper.updateAutoHeight();
      }
    } else {
      if ((swiper.params.slidesPerView === 'auto' || swiper.params.slidesPerView > 1) && swiper.isEnd && !swiper.params.centeredSlides) {
        translated = swiper.slideTo(swiper.slides.length - 1, 0, false, true);
      } else {
        translated = swiper.slideTo(swiper.activeIndex, 0, false, true);
      }
      if (!translated) {
        setTranslate();
      }
    }
    if (params.watchOverflow && snapGrid !== swiper.snapGrid) {
      swiper.checkOverflow();
    }
    swiper.emit('update');
  }

  changeDirection(newDirection, needUpdate = true) {
    const swiper = this;
    const currentDirection = swiper.params.direction;
    if (!newDirection) {
      // eslint-disable-next-line
      newDirection = currentDirection === 'horizontal' ? 'vertical' : 'horizontal';
    }
    if ((newDirection === currentDirection) || (newDirection !== 'horizontal' && newDirection !== 'vertical')) {
      return swiper;
    }

    swiper.$el
      .removeClass(`${swiper.params.containerModifierClass}${currentDirection}`)
      .addClass(`${swiper.params.containerModifierClass}${newDirection}`);

    swiper.params.direction = newDirection;

    swiper.slides.each((slideIndex, slideEl) => {
      if (newDirection === 'vertical') {
        slideEl.style.width = '';
      } else {
        slideEl.style.height = '';
      }
    });

    swiper.emit('changeDirection');
    if (needUpdate) swiper.update();

    return swiper;
  }

  init() {
    const swiper = this;
    if (swiper.initialized) return;

    swiper.emit('beforeInit');

    // Set breakpoint
    if (swiper.params.breakpoints) {
      swiper.setBreakpoint();
    }

    // Add Classes
    swiper.addClasses();

    // Create loop
    if (swiper.params.loop) {
      swiper.loopCreate();
    }

    // Update size
    swiper.updateSize();

    // Update slides
    swiper.updateSlides();

    if (swiper.params.watchOverflow) {
      swiper.checkOverflow();
    }

    // Set Grab Cursor
    if (swiper.params.grabCursor) {
      swiper.setGrabCursor();
    }

    if (swiper.params.preloadImages) {
      swiper.preloadImages();
    }

    // Slide To Initial Slide
    if (swiper.params.loop) {
      swiper.slideTo(swiper.params.initialSlide + swiper.loopedSlides, 0, swiper.params.runCallbacksOnInit);
    } else {
      swiper.slideTo(swiper.params.initialSlide, 0, swiper.params.runCallbacksOnInit);
    }

    // Attach events
    swiper.attachEvents();

    // Init Flag
    swiper.initialized = true;

    // Emit
    swiper.emit('init');
  }

  destroy(deleteInstance = true, cleanStyles = true) {
    const swiper = this;
    const {
      params, $el, $wrapperEl, slides,
    } = swiper;

    if (typeof swiper.params === 'undefined' || swiper.destroyed) {
      return null;
    }

    swiper.emit('beforeDestroy');

    // Init Flag
    swiper.initialized = false;

    // Detach events
    swiper.detachEvents();

    // Destroy loop
    if (params.loop) {
      swiper.loopDestroy();
    }

    // Cleanup styles
    if (cleanStyles) {
      swiper.removeClasses();
      $el.removeAttr('style');
      $wrapperEl.removeAttr('style');
      if (slides && slides.length) {
        slides
          .removeClass([
            params.slideVisibleClass,
            params.slideActiveClass,
            params.slideNextClass,
            params.slidePrevClass,
          ].join(' '))
          .removeAttr('style')
          .removeAttr('data-swiper-slide-index');
      }
    }

    swiper.emit('destroy');

    // Detach emitter events
    Object.keys(swiper.eventsListeners).forEach((eventName) => {
      swiper.off(eventName);
    });

    if (deleteInstance !== false) {
      swiper.$el[0].swiper = null;
      swiper.$el.data('swiper', null);
      Utils.deleteProps(swiper);
    }
    swiper.destroyed = true;

    return null;
  }

  static extendDefaults(newDefaults) {
    Utils.extend(extendedDefaults, newDefaults);
  }

  static get extendedDefaults() {
    return extendedDefaults;
  }

  static get defaults() {
    return defaults;
  }

  static get Class() {
    return SwiperClass;
  }

  static get $() {
    return $;
  }
}

export default Swiper;
<|endoftext|>


<commit_before>import React, { Component } from 'react';

export default class Cuisine extends Component {
    render() {
        return(

Mutfak

Cuisine

Turkish Meze

Turkish Meze consists of a wide variety of small plates & can be treated an appitizer. Common meze dishes include sliced melon, strained yogurt with herbs, eggplant salad, and fried calamari.

Döner Kebab

The poster boy of Turkish cuisine, the döner kebab is a world-famous Turkish kebab usually consisting of lamb cooked on a vertical rotisserie.

Türk yemeği

Turkish food

They say the history of a country can be seen in its food, & Turkish food is certainly no exception. The Greeks, Persians, Arabs, & other groups have all left their mark to form what is one of the most unique yet familiar cuisines in the world. A meal in Turkey can consist of anything from kebabs with massive swaths of meat to stuffed vegetables (Dolma). Popular beverages are Turkish tea & rakı, a clear alcoholic drink from in the Balkans. Turkish delight & baklava are Turkey's most famous desserts. Dig in!

Baklava

Adana Kebab

Rakı

Turkish Delight

Turkish delight, or 'lokum' in Turkish, is a variety of desserts made from sugar and gel. You can find a plethora of different flavors including pistachio, walnut & cinnamon.

Dolma

Dolma is a family of stuffed vegetable dishes that can be found all over the Balkans, Middle East, & Central Asia. Common vegetables to stuff include tomato, pepper, onion, zucchini, eggplant, and garlic.

Simit

Simit is a circular bread with sesame seeds & is the Turkish equivalent of a bagel. Its texture, size, & sweetness varies by region.

Kokoreç

Kokoreç is a dish consisting of lamb or goat intestines wrapped around either seasoned meat or bread. In Turkey it's served mostly as fast-food.

        );
    }
}
<commit_msg>Update Cuisine.js<commit_after>import React, { Component } from 'react';

export default class Cuisine extends Component {
    render() {
        return(

Mutfak

Cuisine

Turkish Meze

Turkish Meze consists of a wide variety of small plates & can be treated an appitizer. Common meze dishes include sliced melon, strained yogurt with herbs, eggplant salad, and fried calamari.

Döner Kebab

The poster boy of Turkish cuisine, the döner kebab is a world-famous Turkish kebab usually consisting of lamb cooked on a vertical rotisserie.

Türk yemeği

Turkish food

They say the history of a country can be seen in its food, & Turkish food is certainly no exception. The Greeks, Persians, Arabs, & other groups have all left their mark to form what is one of the most unique yet familiar cuisines in the world. A meal in Turkey can consist of anything from kebabs with massive swaths of meat to stuffed vegetables (Dolma). Popular beverages are Turkish tea & rakı, a clear alcoholic drink from in the Balkans. Turkish delight & baklava are Turkey's most famous desserts. Dig in!

Baklava

Adana Kebab

Rakı

Turkish Delight

Turkish delight, or 'lokum' in Turkish, is a variety of desserts made from sugar and gel. You can find a plethora of different flavors including pistachio, walnut & cinnamon.

Dolma

Dolma is a family of stuffed vegetable dishes that can be found all over the Balkans, Middle East, & Central Asia. Common vegetables to stuff include tomato, pepper, onion, zucchini, eggplant, and garlic.

Simit

Simit is a circular bread with sesame seeds & is the Turkish equivalent of a bagel. Its texture, size, & sweetness varies by region.

Kokoreç

Kokoreç is a dish consisting of lamb or goat intestines wrapped around either seasoned meat or bread. In Turkey it's served mostly as fast-food.

        );
    }
}
<|endoftext|>


<commit_before>import React from 'react'
import '../../assets/stylesheets/application.css';
import { Link } from 'react-router-dom'
import { setExistingContractParams } from '../../utils/blockchainHelpers'
import { defaultCompanyStartDate } from './utils'
import { defaultCompanyEndDate } from '../../utils/utils'
import { StepNavigation } from '../Common/StepNavigation'
import { InputField } from '../Common/InputField'
import { RadioInputField } from '../Common/RadioInputField'
import { CrowdsaleBlock } from '../Common/CrowdsaleBlock'
import { WhitelistInputBlock } from '../Common/WhitelistInputBlock'
import { NAVIGATION_STEPS, VALIDATION_MESSAGES, VALIDATION_TYPES, TEXT_FIELDS, CONTRACT_TYPES } from '../../utils/constants'
import { inject, observer } from 'mobx-react'
import { warningOnMainnetAlert } from '../../utils/alerts'
const { CROWDSALE_SETUP } = NAVIGATION_STEPS
const { EMPTY, VALID } = VALIDATION_TYPES
const { START_TIME, END_TIME, MINCAP, RATE, SUPPLY, WALLET_ADDRESS, CROWDSALE_SETUP_NAME, ALLOWMODIFYING, DISABLEWHITELISTING } = TEXT_FIELDS

@inject('contractStore', 'crowdsaleBlockListStore', 'pricingStrategyStore', 'web3Store', 'tierStore') @observer
export class stepThree extends React.Component{
  constructor(props) {
    super(props);
    const { contractStore, crowdsaleBlockListStore, tierStore } = props
    window.scrollTo(0, 0);
    if (contractStore.crowdsale.addr.length > 0) {
      contractStore.setContractProperty('pricingStrategy','addr',[]);
      setExistingContractParams(contractStore.abi, contractStore.addr[0], contractStore.setContractProperty);
    }
    crowdsaleBlockListStore.emptyList()
    tierStore.setTierProperty("Tier 1", 'tier', 0)
    tierStore.setTierProperty( "off", 'updatable', 0)
    tierStore.setTierProperty( "yes", 'whitelistdisabled', 0)
  }

  showErrorMessages = (parent) => {
    this.props.tierStore.invalidateToken();
  }

  changeState = (event, parent, key, property) => {
    if (property.indexOf("whitelist_") === 0) {
      const { tierStore } = this.props
      const whitelistInputProps = { ...tierStore.tiers[key].whitelistInput }
      const prop = property.split("_")[1]

      whitelistInputProps[prop] = event.target.value
      tierStore.setTierProperty(whitelistInputProps, 'whitelistInput', key)
    }
  }

  addCrowdsale() {
    const { crowdsaleBlockListStore, tierStore } = this.props
    let num = crowdsaleBlockListStore.blockList.length + 1;
    const newTier = {
      tier: "Tier " + (num + 1),
      supply: 0,
      rate: 0,
      updatable: "off",
      whitelist:[],
      whitelistElements: [],
      whitelistInput: {}
    }

    const newTierValidations = {
      tier: VALID,
      startTime: VALID,
      endTime: VALID,
      supply: EMPTY,
      rate: EMPTY
    }

    tierStore.addTier(newTier)
    tierStore.addTierValidations(newTierValidations)
    //newState.crowdsale[num].startTime = newState.crowdsale[num - 1].endTime;
    //newState.crowdsale[num].endTime = defaultCompanyEndDate(newState.crowdsale[num].startTime);
    this.addCrowdsaleBlock(num)
  }

  updateCrowdsaleBlockListStore = (event, property, index) => {
    const { crowdsaleBlockListStore } = this.props
    const value = event.target.value;
    crowdsaleBlockListStore.setCrowdsaleBlockProperty(value, property, index);
    crowdsaleBlockListStore.validateCrowdsaleListBlockProperty(property, index);
  }

  updateTierStore = (event, property, index) => {
    const { tierStore } = this.props
    const value = event.target.value;
    tierStore.setTierProperty(value, property, index);
    tierStore.validateTiers(property, index)
  }

  updatePricingStrategyStore = (event, index, property) => {
    const { pricingStrategyStore } = this.props
    const value = event.target.value;
    pricingStrategyStore.setStrategyProperty(value, property, index);
  }

  gotoDeploymentStage() {
    this.setState({
      redirect: true
    });
  }

  addCrowdsaleBlock(num) {
    this.props.crowdsaleBlockListStore.addCrowdsaleItem(
      <CrowdsaleBlock num = {num}/>
    )
  }

  renderStandardLink () {
    return <Link to={{ pathname: '/4', query: { changeState: this.changeState } }} className="button button_fill">Continue</Link>
  }

  renderLink () {
    return

 this.addCrowdsale()} className="button button_fill_secondary"> Add Tier

      <Link to={{ pathname: '/4', query: { state: this.state, changeState: this.changeState } }} className="button button_fill">Continue</Link>

  }

  renderStandardLinkComponent () {
    if(this.props.tierStore.areTiersValid){
      return this.renderStandardLink()
    }

    return

 this.addCrowdsale()} className="button button_fill_secondary"> Add Tier

 warningOnMainnetAlert(this.state.crowdsale.length, () => this.gotoDeploymentStage())} className="button button_fill"> Continue

  }

  renderLinkComponent () {
    if(this.props.tierStore.areTiersValid){
      return this.renderLink()
    }

    return

 this.addCrowdsale()} className="button button_fill_secondary"> Add Tier

 Continue

  }

    componentDidMount () {
      const { tierStore, web3Store } = this.props
      const { curAddress } = web3Store
      tierStore.setTierProperty(curAddress, 'walletAddress', 0)
      tierStore.setTierProperty(defaultCompanyStartDate(), 'startTime', 0)
      tierStore.setTierProperty(defaultCompanyEndDate(tierStore.tiers[0].startTime), 'endTime', 0)
    }

  render() {
    const { contractStore, pricingStrategyStore, crowdsaleBlockListStore, tierStore } = this.props
    let globalSettingsBlock =

Global limits

        <InputField
          side='left'
          type='number'
          title={MINCAP}
          value={tierStore.globalMinCap}
          valid={VALID}
          errorMessage={VALIDATION_MESSAGES.MINCAP}
          onChange={(e) => tierStore.setGlobalMinCap(e.target.value)}
          description={`Minimum amount tokens to buy. Not a minimal size of a transaction. If minCap is 1 and user bought 1 token in a previous transaction and buying 0.1 token it will allow him to buy.`}
        />

    if ( contractStore.contractType === CONTRACT_TYPES.standard) {
      return (

          <StepNavigation activeStep={CROWDSALE_SETUP}/>

Crowdsale setup

                The most important and exciting part of the crowdsale process. Here you can define parameters of your crowdsale campaign.

              <InputField
                side='left'
                type='datetime-local'
                title={START_TIME}
                value={tierStore.tiers[0].startTime}
                valid={tierStore.validTiers[0].startTime}
                errorMessage={VALIDATION_MESSAGES.START_TIME}
                onChange={(e) => this.updateTierStore(e, 'startTime', 0)}
                description={`Date and time when the tier starts. Can't be in the past from the current moment.`}
              />
              <InputField
                side='right'
                type='datetime-local'
                title={END_TIME}
                value={tierStore.tiers[0].endTime}
                valid={tierStore.validTiers[0].endTime}
                errorMessage={VALIDATION_MESSAGES.END_TIME}
                onChange={(e) => this.updateTierStore(e, 'endTime', 0)}
                description={`Date and time when the tier ends. Can be only in the future.`}
              />

              <InputField
                side='left'
                type='text'
                title={WALLET_ADDRESS}
                value={tierStore.tiers[0].walletAddress}
                valid={tierStore.validTiers[0].walletAddress}
                errorMessage={VALIDATION_MESSAGES.WALLET_ADDRESS}
                onChange={(e) => this.updateTierStore(e, 'walletAddress', 0)}
                description={`Address where the money goes immediately after each successful transactions. We recommend to setup a multisig wallet with hardware based signers.`}
              />
              <InputField
                side='right'
                type='number'
                title={SUPPLY}
                value={tierStore.tiers[0].supply}
                valid={tierStore.validTiers[0].supply}
                errorMessage={VALIDATION_MESSAGES.SUPPLY}
                onChange={(e) => this.updateTierStore(e, 'supply', 0)}
                description={`How many tokens will be sold on this tier. Cap of crowdsale equals to sum of supply of all tiers`}
              />

              <InputField
                side='left'
                type='number'
                title={RATE}
                value={pricingStrategyStore.strategies[0].rate}
                valid={true}
                errorMessage={VALIDATION_MESSAGES.RATE}
                onChange={(e) => this.updatePricingStrategyStore(e, 'rate', 0)}
                description={`Exchange rate Ethereum to Tokens. If it's 100, then for 1 Ether you can buy 100 tokens`}
              />

            {this.renderStandardLinkComponent()}

      )
    } else if (contractStore.contractType === CONTRACT_TYPES.whitelistwithcap) {
      let whitelistInputBlock =

Whitelist

<WhitelistInputBlock
              num={0}
              onChange={(e, cntrct, num, prop) => this.changeState(e, cntrct, 0, prop)}
            ></WhitelistInputBlock>
;
      return (

          <StepNavigation activeStep={CROWDSALE_SETUP}/>

Crowdsale setup

              The most important and exciting part of the crowdsale process. Here you can define parameters of your crowdsale campaign.

              <InputField
                side='left'
                type='text'
                title={CROWDSALE_SETUP_NAME}
                value={tierStore.tiers[0].tier}
                valid={tierStore.validTiers[0].tier}
                errorMessage={VALIDATION_MESSAGES.TIER}
                onChange={(e) => this.updateTierStore(e, 'tier', 0)}
                description={`Name of a tier, e.g. PrePreIco, PreICO, ICO with bonus A, ICO with bonus B, etc. We simplified that and will increment a number after each tier.`}
              />
              <InputField
                side='right'
                type='text'
                title={WALLET_ADDRESS}
                value={tierStore.tiers[0].walletAddress}
                valid={tierStore.validTiers[0].walletAddress}
                errorMessage={VALIDATION_MESSAGES.WALLET_ADDRESS}
                onChange={(e) => this.updateTierStore(e, 'walletAddress', 0)}
                description={`Where the money goes after investors transactions. Immediately after each transaction. We recommend to setup a multisig wallet with hardware based signers.`}
              />

              <InputField
                side='left'
                type='datetime-local'
                title={START_TIME}
                value={tierStore.tiers[0].startTime}
                valid={tierStore.validTiers[0].startTime}
                errorMessage={VALIDATION_MESSAGES.START_TIME}
                onChange={(e) => this.updateTierStore(e, 'startTime', 0)}
                description={`Date and time when the tier starts. Can't be in the past from the current moment.`}
              />
              <InputField
                side='right'
                type='datetime-local'
                title={END_TIME}
                value={tierStore.tiers[0].endTime}
                valid={tierStore.validTiers[0].endTime}
                errorMessage={VALIDATION_MESSAGES.END_TIME}
                onChange={(e) => this.updateTierStore(e, 'endTime', 0)}
                description={`Date and time when the tier ends. Can be only in the future.`}
              />

              <InputField
                side='left'
                type='number'
                title={RATE}
                value={tierStore.tiers[0].rate}
                valid={tierStore.validTiers[0].rate}
                errorMessage={VALIDATION_MESSAGES.RATE}
                onChange={(e) => this.updateTierStore(e, 'rate', 0)}
                description={`Exchange rate Ethereum to Tokens. If it's 100, then for 1 Ether you can buy 100 tokens`}
              />
              <InputField
                side='right'
                type='number'
                title={SUPPLY}
                value={tierStore.tiers[0].supply}
                valid={tierStore.validTiers[0].supply}
                errorMessage={VALIDATION_MESSAGES.SUPPLY}
                onChange={(e) => this.updateTierStore(e, 'supply', 0)}
                description={`How many tokens will be sold on this tier. Cap of crowdsale equals to sum of supply of all tiers`}
              />

              <RadioInputField
                  side='left'
                  title={ALLOWMODIFYING}
                  items={["on", "off"]}
                  vals={["on", "off"]}
                  state={this.state}
                  num={0}
                  defaultValue={tierStore.tiers[0].updatable}
                  name='crowdsale-updatable-0'
                  onChange={(e) => this.updateTierStore(e, 'updatable', 0)}
                  description={`Pandora box feature. If it's enabled, a creator of the crowdsale can modify Start time, End time, Rate, Limit after publishing.`}
              />
              <RadioInputField
                  side='right'
                  title={DISABLEWHITELISTING}
                  items={["yes", "no"]}
                  vals={["yes", "no"]}
                  state={this.state}
                  num={0}
                  defaultValue={tierStore.tiers[0].whitelistdisabled}
                  name='crowdsale-whitelistdisabled-0'
                  onChange={(e) => this.updateTierStore(e, 'whitelistdisabled', 0)}
                  description={`Disables whitelistings. Anyone can buy on the tier.`}
              />

              {tierStore.tiers[0].whitelistdisabled === "no"?"":globalSettingsBlock}

            {tierStore.tiers[0].whitelistdisabled === "yes"?"":whitelistInputBlock}

{crowdsaleBlockListStore.blockList}

            {this.renderLinkComponent()}

      )
    }
  }
}
<commit_msg>Validate times before continuing<commit_after>import React from 'react'
import '../../assets/stylesheets/application.css';
import { Link } from 'react-router-dom'
import { setExistingContractParams } from '../../utils/blockchainHelpers'
import { defaultCompanyStartDate } from './utils'
import { defaultCompanyEndDate } from '../../utils/utils'
import { StepNavigation } from '../Common/StepNavigation'
import { InputField } from '../Common/InputField'
import { RadioInputField } from '../Common/RadioInputField'
import { CrowdsaleBlock } from '../Common/CrowdsaleBlock'
import { WhitelistInputBlock } from '../Common/WhitelistInputBlock'
import { NAVIGATION_STEPS, VALIDATION_MESSAGES, VALIDATION_TYPES, TEXT_FIELDS, CONTRACT_TYPES } from '../../utils/constants'
import { inject, observer } from 'mobx-react'
import { warningOnMainnetAlert } from '../../utils/alerts'
const { CROWDSALE_SETUP } = NAVIGATION_STEPS
const { EMPTY, VALID } = VALIDATION_TYPES
const { START_TIME, END_TIME, MINCAP, RATE, SUPPLY, WALLET_ADDRESS, CROWDSALE_SETUP_NAME, ALLOWMODIFYING, DISABLEWHITELISTING } = TEXT_FIELDS

@inject('contractStore', 'crowdsaleBlockListStore', 'pricingStrategyStore', 'web3Store', 'tierStore') @observer
export class stepThree extends React.Component{
  constructor(props) {
    super(props);
    const { contractStore, crowdsaleBlockListStore, tierStore } = props
    window.scrollTo(0, 0);
    if (contractStore.crowdsale.addr.length > 0) {
      contractStore.setContractProperty('pricingStrategy','addr',[]);
      setExistingContractParams(contractStore.abi, contractStore.addr[0], contractStore.setContractProperty);
    }
    crowdsaleBlockListStore.emptyList()
    tierStore.setTierProperty("Tier 1", 'tier', 0)
    tierStore.setTierProperty( "off", 'updatable', 0)
    tierStore.setTierProperty( "yes", 'whitelistdisabled', 0)
  }

  showErrorMessages = (parent) => {
    this.props.tierStore.invalidateToken();
  }

  changeState = (event, parent, key, property) => {
    if (property.indexOf("whitelist_") === 0) {
      const { tierStore } = this.props
      const whitelistInputProps = { ...tierStore.tiers[key].whitelistInput }
      const prop = property.split("_")[1]

      whitelistInputProps[prop] = event.target.value
      tierStore.setTierProperty(whitelistInputProps, 'whitelistInput', key)
    }
  }

  addCrowdsale() {
    const { crowdsaleBlockListStore, tierStore } = this.props
    let num = crowdsaleBlockListStore.blockList.length + 1;
    const newTier = {
      tier: "Tier " + (num + 1),
      supply: 0,
      rate: 0,
      updatable: "off",
      whitelist:[],
      whitelistElements: [],
      whitelistInput: {}
    }

    const newTierValidations = {
      tier: VALID,
      startTime: VALID,
      endTime: VALID,
      supply: EMPTY,
      rate: EMPTY
    }

    tierStore.addTier(newTier)
    tierStore.addTierValidations(newTierValidations)
    //newState.crowdsale[num].startTime = newState.crowdsale[num - 1].endTime;
    //newState.crowdsale[num].endTime = defaultCompanyEndDate(newState.crowdsale[num].startTime);
    this.addCrowdsaleBlock(num)
  }

  updateCrowdsaleBlockListStore = (event, property, index) => {
    const { crowdsaleBlockListStore } = this.props
    const value = event.target.value;
    crowdsaleBlockListStore.setCrowdsaleBlockProperty(value, property, index);
    crowdsaleBlockListStore.validateCrowdsaleListBlockProperty(property, index);
  }

  updateTierStore = (event, property, index) => {
    const { tierStore } = this.props
    const value = event.target.value;
    tierStore.setTierProperty(value, property, index);
    tierStore.validateTiers(property, index)
  }

  updatePricingStrategyStore = (event, index, property) => {
    const { pricingStrategyStore } = this.props
    const value = event.target.value;
    pricingStrategyStore.setStrategyProperty(value, property, index);
  }

  gotoDeploymentStage() {
    this.setState({
      redirect: true
    });
  }

  addCrowdsaleBlock(num) {
    this.props.crowdsaleBlockListStore.addCrowdsaleItem(
      <CrowdsaleBlock num = {num}/>
    )
  }

  renderStandardLink () {
    return <Link to={{ pathname: '/4', query: { changeState: this.changeState } }} className="button button_fill">Continue</Link>
  }

  renderLink () {
    return

 this.addCrowdsale()} className="button button_fill_secondary"> Add Tier

      <Link to={{ pathname: '/4', query: { state: this.state, changeState: this.changeState } }}
            onClick={e => this.beforeNavigate(e)}
            className="button button_fill"
      >Continue</Link>

  }

  beforeNavigate = e => {
    e.preventDefault()
    e.stopPropagation()

    const { tierStore } = this.props

    for (let index = 0; index < tierStore.tiers.length; index++) {
      tierStore.validateTiers('endTime', index)
      tierStore.validateTiers('startTime', index)
    }

    if (tierStore.areTiersValid) {
      this.props.history.push('/4')
    } else {
      this.showErrorMessages(e)
    }
  }

  renderStandardLinkComponent () {
    if(this.props.tierStore.areTiersValid){
      return this.renderStandardLink()
    }

    return

 this.addCrowdsale()} className="button button_fill_secondary"> Add Tier

 warningOnMainnetAlert(this.state.crowdsale.length, () => this.gotoDeploymentStage())} className="button button_fill"> Continue

  }

  renderLinkComponent () {
    if(this.props.tierStore.areTiersValid){
      return this.renderLink()
    }

    return

 this.addCrowdsale()} className="button button_fill_secondary"> Add Tier

 Continue

  }

    componentDidMount () {
      const { tierStore, web3Store } = this.props
      const { curAddress } = web3Store
      tierStore.setTierProperty(curAddress, 'walletAddress', 0)
      tierStore.setTierProperty(defaultCompanyStartDate(), 'startTime', 0)
      tierStore.setTierProperty(defaultCompanyEndDate(tierStore.tiers[0].startTime), 'endTime', 0)
    }

  render() {
    const { contractStore, pricingStrategyStore, crowdsaleBlockListStore, tierStore } = this.props
    let globalSettingsBlock =

Global limits

        <InputField
          side='left'
          type='number'
          title={MINCAP}
          value={tierStore.globalMinCap}
          valid={VALID}
          errorMessage={VALIDATION_MESSAGES.MINCAP}
          onChange={(e) => tierStore.setGlobalMinCap(e.target.value)}
          description={`Minimum amount tokens to buy. Not a minimal size of a transaction. If minCap is 1 and user bought 1 token in a previous transaction and buying 0.1 token it will allow him to buy.`}
        />

    if ( contractStore.contractType === CONTRACT_TYPES.standard) {
      return (

          <StepNavigation activeStep={CROWDSALE_SETUP}/>

Crowdsale setup

                The most important and exciting part of the crowdsale process. Here you can define parameters of your crowdsale campaign.

              <InputField
                side='left'
                type='datetime-local'
                title={START_TIME}
                value={tierStore.tiers[0].startTime}
                valid={tierStore.validTiers[0].startTime}
                errorMessage={VALIDATION_MESSAGES.START_TIME}
                onChange={(e) => this.updateTierStore(e, 'startTime', 0)}
                description={`Date and time when the tier starts. Can't be in the past from the current moment.`}
              />
              <InputField
                side='right'
                type='datetime-local'
                title={END_TIME}
                value={tierStore.tiers[0].endTime}
                valid={tierStore.validTiers[0].endTime}
                errorMessage={VALIDATION_MESSAGES.END_TIME}
                onChange={(e) => this.updateTierStore(e, 'endTime', 0)}
                description={`Date and time when the tier ends. Can be only in the future.`}
              />

              <InputField
                side='left'
                type='text'
                title={WALLET_ADDRESS}
                value={tierStore.tiers[0].walletAddress}
                valid={tierStore.validTiers[0].walletAddress}
                errorMessage={VALIDATION_MESSAGES.WALLET_ADDRESS}
                onChange={(e) => this.updateTierStore(e, 'walletAddress', 0)}
                description={`Address where the money goes immediately after each successful transactions. We recommend to setup a multisig wallet with hardware based signers.`}
              />
              <InputField
                side='right'
                type='number'
                title={SUPPLY}
                value={tierStore.tiers[0].supply}
                valid={tierStore.validTiers[0].supply}
                errorMessage={VALIDATION_MESSAGES.SUPPLY}
                onChange={(e) => this.updateTierStore(e, 'supply', 0)}
                description={`How many tokens will be sold on this tier. Cap of crowdsale equals to sum of supply of all tiers`}
              />

              <InputField
                side='left'
                type='number'
                title={RATE}
                value={pricingStrategyStore.strategies[0].rate}
                valid={true}
                errorMessage={VALIDATION_MESSAGES.RATE}
                onChange={(e) => this.updatePricingStrategyStore(e, 'rate', 0)}
                description={`Exchange rate Ethereum to Tokens. If it's 100, then for 1 Ether you can buy 100 tokens`}
              />

            {this.renderStandardLinkComponent()}

      )
    } else if (contractStore.contractType === CONTRACT_TYPES.whitelistwithcap) {
      let whitelistInputBlock =

Whitelist

<WhitelistInputBlock
              num={0}
              onChange={(e, cntrct, num, prop) => this.changeState(e, cntrct, 0, prop)}
            ></WhitelistInputBlock>
;
      return (

          <StepNavigation activeStep={CROWDSALE_SETUP}/>

Crowdsale setup

              The most important and exciting part of the crowdsale process. Here you can define parameters of your crowdsale campaign.

              <InputField
                side='left'
                type='text'
                title={CROWDSALE_SETUP_NAME}
                value={tierStore.tiers[0].tier}
                valid={tierStore.validTiers[0].tier}
                errorMessage={VALIDATION_MESSAGES.TIER}
                onChange={(e) => this.updateTierStore(e, 'tier', 0)}
                description={`Name of a tier, e.g. PrePreIco, PreICO, ICO with bonus A, ICO with bonus B, etc. We simplified that and will increment a number after each tier.`}
              />
              <InputField
                side='right'
                type='text'
                title={WALLET_ADDRESS}
                value={tierStore.tiers[0].walletAddress}
                valid={tierStore.validTiers[0].walletAddress}
                errorMessage={VALIDATION_MESSAGES.WALLET_ADDRESS}
                onChange={(e) => this.updateTierStore(e, 'walletAddress', 0)}
                description={`Where the money goes after investors transactions. Immediately after each transaction. We recommend to setup a multisig wallet with hardware based signers.`}
              />

              <InputField
                side='left'
                type='datetime-local'
                title={START_TIME}
                value={tierStore.tiers[0].startTime}
                valid={tierStore.validTiers[0].startTime}
                errorMessage={VALIDATION_MESSAGES.START_TIME}
                onChange={(e) => this.updateTierStore(e, 'startTime', 0)}
                description={`Date and time when the tier starts. Can't be in the past from the current moment.`}
              />
              <InputField
                side='right'
                type='datetime-local'
                title={END_TIME}
                value={tierStore.tiers[0].endTime}
                valid={tierStore.validTiers[0].endTime}
                errorMessage={VALIDATION_MESSAGES.END_TIME}
                onChange={(e) => this.updateTierStore(e, 'endTime', 0)}
                description={`Date and time when the tier ends. Can be only in the future.`}
              />

              <InputField
                side='left'
                type='number'
                title={RATE}
                value={tierStore.tiers[0].rate}
                valid={tierStore.validTiers[0].rate}
                errorMessage={VALIDATION_MESSAGES.RATE}
                onChange={(e) => this.updateTierStore(e, 'rate', 0)}
                description={`Exchange rate Ethereum to Tokens. If it's 100, then for 1 Ether you can buy 100 tokens`}
              />
              <InputField
                side='right'
                type='number'
                title={SUPPLY}
                value={tierStore.tiers[0].supply}
                valid={tierStore.validTiers[0].supply}
                errorMessage={VALIDATION_MESSAGES.SUPPLY}
                onChange={(e) => this.updateTierStore(e, 'supply', 0)}
                description={`How many tokens will be sold on this tier. Cap of crowdsale equals to sum of supply of all tiers`}
              />

              <RadioInputField
                  side='left'
                  title={ALLOWMODIFYING}
                  items={["on", "off"]}
                  vals={["on", "off"]}
                  state={this.state}
                  num={0}
                  defaultValue={tierStore.tiers[0].updatable}
                  name='crowdsale-updatable-0'
                  onChange={(e) => this.updateTierStore(e, 'updatable', 0)}
                  description={`Pandora box feature. If it's enabled, a creator of the crowdsale can modify Start time, End time, Rate, Limit after publishing.`}
              />
              <RadioInputField
                  side='right'
                  title={DISABLEWHITELISTING}
                  items={["yes", "no"]}
                  vals={["yes", "no"]}
                  state={this.state}
                  num={0}
                  defaultValue={tierStore.tiers[0].whitelistdisabled}
                  name='crowdsale-whitelistdisabled-0'
                  onChange={(e) => this.updateTierStore(e, 'whitelistdisabled', 0)}
                  description={`Disables whitelistings. Anyone can buy on the tier.`}
              />

              {tierStore.tiers[0].whitelistdisabled === "no"?"":globalSettingsBlock}

            {tierStore.tiers[0].whitelistdisabled === "yes"?"":whitelistInputBlock}

{crowdsaleBlockListStore.blockList}

            {this.renderLinkComponent()}

      )
    }
  }
}
<|endoftext|>


<commit_before>import React from 'react';
import * as d3 from 'd3';
import ReactFauxDOM from 'react-faux-dom';
import { FormattedMessage, injectIntl } from 'react-intl';

const DEFAULT_WIDTH = 530;
const DEFAULT_MIN_BUBBLE_RADIUS = 5;
const DEFAULT_MAX_BUBBLE_RADIUS = 70;
const DEFAULT_HEIGHT = 200;

// options for bubble `placement`
export const PLACEMENT_AUTO = 'PLACEMENT_AUTO';
export const PLACEMENT_HORIZONTAL = 'PLACEMENT_HORIZONTAL';
const DEFAULT_PLACEMENT = PLACEMENT_AUTO;

const localMessages = {
  noData: { id: 'chart.bubble.noData', defaultMessage: 'Sorry, but we don\'t have any data to draw this chart.' },
};

/**
 * Draw a bubble chart with labels.  Values are mapped to area, not radius.
 */
class BubbleChart extends React.Component {

  render() {
    const { data, width, height, maxBubbleRadius, minBubbleRadius, placement, domId } = this.props;

    // bail if no data
    if (data.length === 0) {
      return (

<FormattedMessage {...localMessages.noData} />

      );
    }

    // const { formatNumber } = this.props.intl;
    const options = {
      width,
      height,
      maxBubbleRadius,
      minBubbleRadius,
      placement,
    };
    if ((width === null) || (width === undefined)) {
      options.width = DEFAULT_WIDTH;
    }
    if ((height === null) || (height === undefined)) {
      options.height = DEFAULT_HEIGHT;
    }
    if ((minBubbleRadius === null) || (minBubbleRadius === undefined)) {
      options.minBubbleRadius = DEFAULT_MIN_BUBBLE_RADIUS;
    }
    if ((maxBubbleRadius === null) || (maxBubbleRadius === undefined)) {
      options.maxBubbleRadius = DEFAULT_MAX_BUBBLE_RADIUS;
    }
    if ((placement === null) || (placement === undefined)) {
      options.placement = DEFAULT_PLACEMENT;
    }

    // prep the data and some config (scale by sqrt of value so we map to area, not radius)
    const maxValue = d3.max(data.map(d => d.value));
    const radius = d3.scaleSqrt().domain([0, maxValue]).range([0, options.maxBubbleRadius]);
    let circles = null;
    let hierarchialData = null;
    let pack = null;

    switch (options.placement) {
      case PLACEMENT_HORIZONTAL:
        circles = data.map((d, idx, list) => {
          let xOffset = 0;
          if (idx > 0) {
            const preceeding = list.slice(0, idx);
            const diameters = preceeding.map(d2 => (radius(d2.value) * 2) + 10);
            xOffset = d3.sum(diameters);
          }
          xOffset += radius(d.value);
          return {
            ...d,
            r: radius(d.value),
            y: 0,
            x: xOffset,
          };
        });
        break;
      case PLACEMENT_AUTO:

        hierarchialData = [].concat(data).concat([{ name: 'top', id: 'top', value: 0, x: 0, y: 0 }]);
        hierarchialData = d3.stratify()
          .id((d, idx) => ((d.centerText ? d.centerText : d.name) ? d.name : idx))
          .parentId(d => (d.centerText || d.name === undefined ? 'top' : undefined))(hierarchialData)
          .sum(d => d.value)
          .sort((a, b) => b.value - a.value);

        pack = d3.pack().size([options.width, options.height]);

        circles = pack(hierarchialData).descendants();
        break;
      default:
        const error = { message: `BubbleChart received invalid placement option of ${options.placement}` };
        throw error;
    }
    let content = null;
    if (circles && circles.length > 0) {
      // render it all
      const node = ReactFauxDOM.createElement('div');
      const div = d3.select(node).append('div').attr('id', 'bubble-chart-wrapper');
      const svg = div.append('svg:svg');
      svg.attr('id', domId)
        .attr('width', options.width)
        .attr('height', options.height)
        .attr('class', 'bubble-chart');
      // rollover tooltip
      const rollover = d3.select('body').append('div')
        .attr('class', 'bubble-chart-tooltip')
        .style('opacity', 0);

      // only center align if auto layout
      const horizontalTranslaton = (options.placement === PLACEMENT_HORIZONTAL) ? 0 : options.width / 2;
      const bubbles = svg.append('g')
          .attr('transform', `translate(${horizontalTranslaton},${options.height / 2})`)
          .selectAll('.bubble')
          .data(circles)
          .enter();

      // create the bubbles
      /* Note:
       * for horizontal placement, the we calc the placement and the attr fields are accessed at top level,
         for AUTO, it is auto-packed and the attr fields we want are stored in the data obj
       */
      const midW = options.width / 2;
      const midH = options.height / 2;

      if (options.placement === PLACEMENT_HORIZONTAL) {
        bubbles.append('circle')
          .attr('r', d => d.r)
          .attr('cx', d => d.x)
          .attr('cy', d => d.y)
          .style('fill', d => d.fill || '');
      } else if (options.placement === PLACEMENT_AUTO) {
        bubbles.append('circle')
          .style('fill', d => ((d.fill ? d.fill : d.data) ? d.data.fill : ''))
          .style('fill-opacity', d => (d.parent !== null ? 1 : 0))
          .style('display', d => (d.parent !== null ? 'inline' : 'none'))
          .attr('transform', d => `translate(${d.x - midW},${d.y - midH})`)
          .attr('r', d => d.r);
      }
      // add tooltip to bubbles
      bubbles.selectAll('circle').on('mouseover', (d) => {
        const pixel = 'px';
        rollover.transition().duration(200).style('opacity', 0.9);
        rollover.html((d.rolloverText ? d.rolloverText : d.data) ? d.data.rolloverText : '')
          .style('left', d3.event.pageX + pixel)
          .style('top', d3.event.pageY + pixel);
      })
      .on('mouseout', () => {
        rollover.transition().duration(500).style('opacity', 0);
      });

      // add center labels
      bubbles.append('text')
        .attr('x', d => d.x - midW)
        .attr('y', d => (d.y - midH))
        .attr('text-anchor', 'middle')
        .attr('fill', d => `${d.centerTextColor} !important` || '')
        .attr('font-family', 'Lato, Helvetica, sans')
        .attr('font-size', '10px')
        .text(d => ((d.centerText ? d.centerText : d.data) ? d.data.centerText : ''));

      // add top labels
      bubbles.append('text')
        .attr('x', d => d.x)
        .attr('y', d => d.y - d.r - 7)
        .attr('text-anchor', 'middle')
        .attr('fill', d => `${d.aboveTextColor} !important` || '')
        .attr('font-family', 'Lato, Helvetica, sans')
        .attr('font-size', '10px')
        .text(d => ((d.aboveText ? d.aboveText : d.data) ? d.data.aboveText : ''));

      // add bottom labels
      bubbles.append('text')
        .attr('x', d => d.x)
        .attr('y', d => d.y + d.r + 15)
        .attr('text-anchor', 'middle')
        .attr('fill', d => `${d.belowTextColor} !important` || '')
        .attr('font-family', 'Lato, Helvetica, sans')
        .attr('font-size', '10px')
        .text(d => ((d.belowText ? d.belowText : d.data) ? d.data.belowText : ''));

      content = node.toReact();
    }

    return content;
  }
}

BubbleChart.propTypes = {
  intl: React.PropTypes.object.isRequired,
  /*
  [{
    'value': number,
    'fill': string(optional),
    'centerText': string(optional),
    'centerTextColor': string(optional),
    'aboveText': string(optional),
    'aboveTextColor': string(optional),
    'belowText': string(optional),
    'belowTextColor': string(optional),
    'rolloverText': string(optional),
  }]
  */
  data: React.PropTypes.array.isRequired,
  domId: React.PropTypes.string.isRequired,  // to make download work
  width: React.PropTypes.number,
  height: React.PropTypes.number,
  placement: React.PropTypes.string,
  maxBubbleRadius: React.PropTypes.number,
  minBubbleRadius: React.PropTypes.number,
};

export default injectIntl(BubbleChart);
<commit_msg>#418 correction in logic<commit_after>import React from 'react';
import * as d3 from 'd3';
import ReactFauxDOM from 'react-faux-dom';
import { FormattedMessage, injectIntl } from 'react-intl';

const DEFAULT_WIDTH = 530;
const DEFAULT_MIN_BUBBLE_RADIUS = 5;
const DEFAULT_MAX_BUBBLE_RADIUS = 70;
const DEFAULT_HEIGHT = 200;

// options for bubble `placement`
export const PLACEMENT_AUTO = 'PLACEMENT_AUTO';
export const PLACEMENT_HORIZONTAL = 'PLACEMENT_HORIZONTAL';
const DEFAULT_PLACEMENT = PLACEMENT_AUTO;

const localMessages = {
  noData: { id: 'chart.bubble.noData', defaultMessage: 'Sorry, but we don\'t have any data to draw this chart.' },
};

/**
 * Draw a bubble chart with labels.  Values are mapped to area, not radius.
 */
class BubbleChart extends React.Component {

  render() {
    const { data, width, height, maxBubbleRadius, minBubbleRadius, placement, domId } = this.props;

    // bail if no data
    if (data.length === 0) {
      return (

<FormattedMessage {...localMessages.noData} />

      );
    }

    // const { formatNumber } = this.props.intl;
    const options = {
      width,
      height,
      maxBubbleRadius,
      minBubbleRadius,
      placement,
    };
    if ((width === null) || (width === undefined)) {
      options.width = DEFAULT_WIDTH;
    }
    if ((height === null) || (height === undefined)) {
      options.height = DEFAULT_HEIGHT;
    }
    if ((minBubbleRadius === null) || (minBubbleRadius === undefined)) {
      options.minBubbleRadius = DEFAULT_MIN_BUBBLE_RADIUS;
    }
    if ((maxBubbleRadius === null) || (maxBubbleRadius === undefined)) {
      options.maxBubbleRadius = DEFAULT_MAX_BUBBLE_RADIUS;
    }
    if ((placement === null) || (placement === undefined)) {
      options.placement = DEFAULT_PLACEMENT;
    }

    // prep the data and some config (scale by sqrt of value so we map to area, not radius)
    const maxValue = d3.max(data.map(d => d.value));
    const radius = d3.scaleSqrt().domain([0, maxValue]).range([0, options.maxBubbleRadius]);
    let circles = null;
    let hierarchialData = null;
    let pack = null;

    switch (options.placement) {
      case PLACEMENT_HORIZONTAL:
        circles = data.map((d, idx, list) => {
          let xOffset = 0;
          if (idx > 0) {
            const preceeding = list.slice(0, idx);
            const diameters = preceeding.map(d2 => (radius(d2.value) * 2) + 10);
            xOffset = d3.sum(diameters);
          }
          xOffset += radius(d.value);
          return {
            ...d,
            r: radius(d.value),
            y: 0,
            x: xOffset,
          };
        });
        break;
      case PLACEMENT_AUTO:

        hierarchialData = [].concat(data).concat([{ name: 'top', id: 'top', value: 0, x: 0, y: 0 }]);
        hierarchialData = d3.stratify()
          .id((d, idx) => ((d.centerText ? d.centerText : d.name) ? d.name : idx))
          .parentId(d => (d.centerText || d.name === undefined ? 'top' : undefined))(hierarchialData)
          .sum(d => d.value)
          .sort((a, b) => b.value - a.value);

        pack = d3.pack().size([options.width, options.height]);

        circles = pack(hierarchialData).descendants();
        break;
      default:
        const error = { message: `BubbleChart received invalid placement option of ${options.placement}` };
        throw error;
    }
    let content = null;
    if (circles && circles.length > 0) {
      // render it all
      const node = ReactFauxDOM.createElement('div');
      const div = d3.select(node).append('div').attr('id', 'bubble-chart-wrapper');
      const svg = div.append('svg:svg');
      svg.attr('id', domId)
        .attr('width', options.width)
        .attr('height', options.height)
        .attr('class', 'bubble-chart');
      // rollover tooltip
      const rollover = d3.select('body').append('div')
        .attr('class', 'bubble-chart-tooltip')
        .style('opacity', 0);

      // only center align if auto layout
      const horizontalTranslaton = (options.placement === PLACEMENT_HORIZONTAL) ? 0 : options.width / 2;
      const bubbles = svg.append('g')
          .attr('transform', `translate(${horizontalTranslaton},${options.height / 2})`)
          .selectAll('.bubble')
          .data(circles)
          .enter();

      // create the bubbles
      /* Note:
       * for horizontal placement, the we calc the placement and the attr fields are accessed at top level,
         for AUTO, it is auto-packed and the attr fields we want are stored in the data obj
       */
      const midW = options.width / 2;
      const midH = options.height / 2;

      if (options.placement === PLACEMENT_HORIZONTAL) {
        bubbles.append('circle')
          .attr('r', d => d.r)
          .attr('cx', d => d.x)
          .attr('cy', d => d.y)
          .style('fill', d => d.fill || '');
      } else if (options.placement === PLACEMENT_AUTO) {
        bubbles.append('circle')
          .style('fill', d => ((d.fill ? d.fill : d.data) ? d.data.fill : ''))
          .style('fill-opacity', d => (d.parent !== null ? 1 : 0))
          .style('display', d => (d.parent !== null ? 'inline' : 'none'))
          .attr('transform', d => `translate(${d.x - midW},${d.y - midH})`)
          .attr('r', d => d.r);
      }
      // add tooltip to bubbles
      bubbles.selectAll('circle').on('mouseover', (d) => {
        const pixel = 'px';
        rollover.transition().duration(200).style('opacity', 0.9);
        rollover.html(() => {
          if (d.rolloverText) return d.rolloverText;
          else if (d.data && d.data.rolloverText) return d.data.rolloverText;
          return '';
        })
        .style('left', d3.event.pageX + pixel)
        .style('top', d3.event.pageY + pixel);
      })
      .on('mouseout', () => {
        rollover.transition().duration(500).style('opacity', 0);
      });

      // add center labels
      bubbles.append('text')
        .attr('x', d => d.x - midW)
        .attr('y', d => (d.y - midH))
        .attr('text-anchor', 'middle')
        .attr('fill', d => `${d.centerTextColor} !important` || '')
        .attr('font-family', 'Lato, Helvetica, sans')
        .attr('font-size', '10px')
        .text((d) => {
          if (d.centerText) return d.centerText;
          else if (d.data && d.data.centerText) return d.data.centerText;
          return '';
        });
      // add top labels
      bubbles.append('text')
        .attr('x', d => d.x)
        .attr('y', d => d.y - d.r - 7)
        .attr('text-anchor', 'middle')
        .attr('fill', d => `${d.aboveTextColor} !important` || '')
        .attr('font-family', 'Lato, Helvetica, sans')
        .attr('font-size', '10px')
        .text((d) => {
          if (d.aboveText) return d.aboveText;
          else if (d.data && d.data.aboveText) return d.data.aboveText;
          return '';
        });

      // add bottom labels
      bubbles.append('text')
        .attr('x', d => d.x)
        .attr('y', d => d.y + d.r + 15)
        .attr('text-anchor', 'middle')
        .attr('fill', d => `${d.belowTextColor} !important` || '')
        .attr('font-family', 'Lato, Helvetica, sans')
        .attr('font-size', '10px')
        .text((d) => {
          if (d.belowText) return d.belowText;
          else if (d.data && d.data.belowText) return d.data.belowText;
          return '';
        });
      content = node.toReact();
    }

    return content;
  }
}

BubbleChart.propTypes = {
  intl: React.PropTypes.object.isRequired,
  /*
  [{
    'value': number,
    'fill': string(optional),
    'centerText': string(optional),
    'centerTextColor': string(optional),
    'aboveText': string(optional),
    'aboveTextColor': string(optional),
    'belowText': string(optional),
    'belowTextColor': string(optional),
    'rolloverText': string(optional),
  }]
  */
  data: React.PropTypes.array.isRequired,
  domId: React.PropTypes.string.isRequired,  // to make download work
  width: React.PropTypes.number,
  height: React.PropTypes.number,
  placement: React.PropTypes.string,
  maxBubbleRadius: React.PropTypes.number,
  minBubbleRadius: React.PropTypes.number,
};

export default injectIntl(BubbleChart);
<|endoftext|>


<commit_before>var MongoClient = require('mongodb').MongoClient,
    assert = require('assert'),
    ObjectID = require('mongodb').ObjectID
var config = require(".././util/config")
var crypto = require('crypto')

module.exports.insert = function(req, res) {
  var userRegister = {}

  if (req.body.user_email == null) {
    return jsonResponse(res, config.HttpResponseStatus.BadRequest, "email must be declared", null)
  }

  if (req.body.user_name == null) {
    return jsonResponse(res, config.HttpResponseStatus.BadRequest, "name must be declared", null)
  }

  if (req.body.password == null) {
    return jsonResponse(res, config.HttpResponseStatus.BadRequest, "password must be declared", null)
  }

  if (req.body.is_admin == null) {
    return jsonResponse(res, config.HttpResponseStatus.BadRequest, "Status admin must be declared", null)
  }

  var userSalt = crypto.randomBytes(16).toString('hex')

  userRegister["email"] = req.body.user_email
  userRegister["name"] = req.body.user_name
  userRegister["password"] = crypto.createHash('md5').update(req.body.password).digest("hex") + userSalt
  userRegister["salt"] = userSalt
  userRegister["is_admin"] = (req.body.is_admin == 'true')
  userRegister["app_identifier"] = crypto.randomBytes(48).toString('hex')
  userRegister["time_created"] = new Date()
  userRegister["last_updated"] = new Date()

  MongoClient.connect(config.db, function(err, db) {
    db.collection(config.user).findOne({"email" : req.body.user_email}, function(error, user) {
      if (error != null) {
        throw error
        db.close()
        return jsonResponse(res, config.HttpResponseStatus.InternalServerError, "an error occured", null)
      }

      if (user != null) {
        db.close()
        return jsonResponse(res, config.HttpResponseStatus.BadRequest, "Email is already registered", null)
      }

      db.collection(config.user).insertOne(userRegister, function(err, result) {
        if (err != null) {
          throw error
          db.close()
          return jsonResponse(res, config.HttpResponseStatus.InternalServerError, "an error occured", null)
        }

        db.close()
        var resultReturn = {}
        resultReturn["user_id"] = result.ops[0]._id
        resultReturn["email"] = userRegister["email"]
        resultReturn["name"] = userRegister["name"]
        resultReturn["app_identifier"] = userRegister["app_identifier"]
        resultReturn["time_created"] = userRegister["time_created"]
        resultReturn["last_updated"] = userRegister["last_updated"]

        return jsonResponse(res, config.HttpResponseStatus.Success, "Success registered", resultReturn)
      })
    })
  })
}

module.exports.login = function(req, res) {
  if (req.body.user_email == null || req.body.user_email == "") {
    return jsonResponse(res, config.HttpResponseStatus.BadRequest, "Email must be declared", null)
  }

  if (req.body.password == null || req.body.password == "") {
    return jsonResponse(res, config.HttpResponseStatus.BadRequest, "password must be declared", null)
  }

  MongoClient.connect(config.db, function(err, db) {
    db.collection(config.user).findOne({"email" : req.body.user_email}, function (error, user) {
      if (error != null) {
        throw error
        db.close()
        return jsonResponse(res, config.HttpResponseStatus.InternalServerError, "an error occured", null)
      }

      if (user == null) {
        db.close()
        return jsonResponse(res, config.HttpResponseStatus.BadRequest, "Wrong email or password", null)
      }

      var passwordValidation = crypto.createHash('md5').update(req.body.password).digest("hex") + user.salt

      if (passwordValidation == user.password) {
        var resultReturn = {}
        resultReturn["user_id"] = user._id
        resultReturn["email"] = user.email
        resultReturn["name"] = user.name
        resultReturn["app_identifier"] = user.app_identifier
        resultReturn["time_created"] = user.time_created
        resultReturn["last_updated"] = user.last_updated

        return jsonResponse(res, config.HttpResponseStatus.Success, "login Success", resultReturn)
      } else {
        return jsonResponse(res, config.HttpResponseStatus.BadRequest, "Wrong email or password", null)
      }
    })
  })
}

function jsonResponse(response, status, message, metadata) {
  return response.json({
    status: status,
    message: message,
    metadata: metadata
  })
}
<commit_msg>Change identifier to 8byte data<commit_after>var MongoClient = require('mongodb').MongoClient,
    assert = require('assert'),
    ObjectID = require('mongodb').ObjectID
var config = require(".././util/config")
var crypto = require('crypto')

module.exports.insert = function(req, res) {
  var userRegister = {}

  if (req.body.user_email == null) {
    return jsonResponse(res, config.HttpResponseStatus.BadRequest, "email must be declared", null)
  }

  if (req.body.user_name == null) {
    return jsonResponse(res, config.HttpResponseStatus.BadRequest, "name must be declared", null)
  }

  if (req.body.password == null) {
    return jsonResponse(res, config.HttpResponseStatus.BadRequest, "password must be declared", null)
  }

  if (req.body.is_admin == null) {
    return jsonResponse(res, config.HttpResponseStatus.BadRequest, "Status admin must be declared", null)
  }

  var userSalt = crypto.randomBytes(16).toString('hex')

  userRegister["email"] = req.body.user_email
  userRegister["name"] = req.body.user_name
  userRegister["password"] = crypto.createHash('md5').update(req.body.password).digest("hex") + userSalt
  userRegister["salt"] = userSalt
  userRegister["is_admin"] = (req.body.is_admin == 'true')
  userRegister["app_identifier"] = crypto.randomBytes(8).toString('hex')
  userRegister["time_created"] = new Date()
  userRegister["last_updated"] = new Date()

  MongoClient.connect(config.db, function(err, db) {
    db.collection(config.user).findOne({"email" : req.body.user_email}, function(error, user) {
      if (error != null) {
        throw error
        db.close()
        return jsonResponse(res, config.HttpResponseStatus.InternalServerError, "an error occured", null)
      }

      if (user != null) {
        db.close()
        return jsonResponse(res, config.HttpResponseStatus.BadRequest, "Email is already registered", null)
      }

      db.collection(config.user).insertOne(userRegister, function(err, result) {
        if (err != null) {
          throw error
          db.close()
          return jsonResponse(res, config.HttpResponseStatus.InternalServerError, "an error occured", null)
        }

        db.close()
        var resultReturn = {}
        resultReturn["user_id"] = result.ops[0]._id
        resultReturn["email"] = userRegister["email"]
        resultReturn["name"] = userRegister["name"]
        resultReturn["app_identifier"] = userRegister["app_identifier"]
        resultReturn["time_created"] = userRegister["time_created"]
        resultReturn["last_updated"] = userRegister["last_updated"]

        return jsonResponse(res, config.HttpResponseStatus.Success, "Success registered", resultReturn)
      })
    })
  })
}

module.exports.login = function(req, res) {
  if (req.body.user_email == null || req.body.user_email == "") {
    return jsonResponse(res, config.HttpResponseStatus.BadRequest, "Email must be declared", null)
  }

  if (req.body.password == null || req.body.password == "") {
    return jsonResponse(res, config.HttpResponseStatus.BadRequest, "password must be declared", null)
  }

  MongoClient.connect(config.db, function(err, db) {
    db.collection(config.user).findOne({"email" : req.body.user_email}, function (error, user) {
      if (error != null) {
        throw error
        db.close()
        return jsonResponse(res, config.HttpResponseStatus.InternalServerError, "an error occured", null)
      }

      if (user == null) {
        db.close()
        return jsonResponse(res, config.HttpResponseStatus.BadRequest, "Wrong email or password", null)
      }

      var passwordValidation = crypto.createHash('md5').update(req.body.password).digest("hex") + user.salt

      if (passwordValidation == user.password) {
        var resultReturn = {}
        resultReturn["user_id"] = user._id
        resultReturn["email"] = user.email
        resultReturn["name"] = user.name
        resultReturn["app_identifier"] = user.app_identifier
        resultReturn["time_created"] = user.time_created
        resultReturn["last_updated"] = user.last_updated

        return jsonResponse(res, config.HttpResponseStatus.Success, "login Success", resultReturn)
      } else {
        return jsonResponse(res, config.HttpResponseStatus.BadRequest, "Wrong email or password", null)
      }
    })
  })
}

function jsonResponse(response, status, message, metadata) {
  return response.json({
    status: status,
    message: message,
    metadata: metadata
  })
}
<|endoftext|>


<commit_before>AugmentedSzczecin.controller('MapController',['$scope', function($scope){

    var directionsDisplay;
    var directionsService = new google.maps.DirectionsService();
    var map;
    var handler = document.getElementById('map-canvas');
    /**
     * Inicjalizacja mapy, centrowanie jej, oraz wyswietlanie tras
     */
    function initialize(mapHandler) {
        directionsDisplay = new google.maps.DirectionsRenderer();
        var center = new google.maps.LatLng(53.425175, 14.550454);
        /**
         * Opcje mapy
         * @type {Object}
         */
        var mapOptions = {
            streetViewControl: true,
            mapTypeControl: true,
            panControl: false,
            zoom:15,
            center: center,
            scaleControl: true
        };
        /**
         * Wysiwietlanie mapy wraz z jej opcjami
         * @type {google}
         */
        map = new google.maps.Map(mapHandler, mapOptions);
        directionsDisplay.setMap(map);

        /**
         * Funkcja stawiajaca Pinezke na mapie
         * @param  {[object} event) {placeMarker(event.latLng);}  - ppm stawia na mapie Pinezke
         * @return {[type]}        - Pinezka pojawia sie w wyznaczonym przez nas miejscu
         */
        google.maps.event.addListener(map, 'rightclick', function(event) {
            placeMarker(event.latLng);
        });

        /**
         * @todo poiList - tablica z punktami poi
         * @type {Array}
         */
        var poiList= [];
        /**
         * punkty poi wyznaczone, do czasu uzyskania poiList
         * @type {Array}
         */
        var points= [
            ['katedra', 53.424736, 14.556168],
            ['kaskada', 53.428271, 14.551955],
            ['castorama', 53.386734, 14.659007],
            ['komisariat dąbie', 53.394111, 14.671734],
            ['outlet park', 53.381792, 14.669432],
            ['wneiz', 53.438839, 14.520724],
            ['wi zut', 53.448778, 14.491090],
            ['kordecki', 53.423487, 14.531787],
            ['szpital na unii', 53.448693, 14.504945],
            ['deptak', 53.429926, 14.544256]
        ]
       /**
        * Klastrowanie, zbieranie wiekszej ilosci punktow poi w jeden
        * @param  {google} entry){var coordinates  - cordy punktow poi
        */
        points.forEach(function(entry){
            var coordinates = new google.maps.LatLng(
                entry[1], entry[2]
            );
            poiMarker= new google.maps.Marker({
                position: coordinates,
                map: map
            });
            poiList.push(poiMarker);
        });
        /**
         * Tworzenie Punktu klastwoania, z wyswietlanie ilosci punktow poi w nim
         * @type {MarkerClusterer}
         */
        var markerCluster = new MarkerClusterer(map, poiList);
    }
    google.maps.event.addDomListener(window, 'load', initialize(handler));

    /**
     * Pinezka
     * @param  {object} location - okreslenie lokacji w ktorej postawiona bedzie pinezka
     * @return {google}          - wyswietlenie pinezkina mapie
     */
    function placeMarker(location) {
        var marker = new google.maps.Marker({
            position: location,
            map: map
        });
        /**
         * Okienko informacyjne z coordami
         * @type {google}
         */
        var infowindow = new google.maps.InfoWindow({
            content: 'Latitude: ' + location.lat() + '
Longitude: ' + location.lng()
        });
        infowindow.open(map,marker);
    }

    $scope.monuments = [
        {
        'name': 'Brama Portowa',
        'lat': 53.425060,
        'lng': 14.550462
        },
        {
        'name': 'Zamek Książąt Pomorskich',
        'lat': 53.426220,
        'lng': 14.560521
        },
        {
        'name': 'Wały Chrobrego',
        'lat': 53.428528,
        'lng': 14.563938
        },
        {
        'name': 'Jasne Błonia',
        'lat': 53.440721,
        'lng': 14.540001
        }
    ];
    /**
     * Wyznaczanie trasy
     * @param  {object} origin      - punkt poczatkowy naszej trasy
     * @param  {object} destination - punkt koncowy naszej trasy
     * @return {google}             - wyznacza najkrotsza trase pomiedzy punktami
     */
    $scope.calcRoute = function (origin, destination) {
        var request = {
            origin: new google.maps.LatLng(origin.lat, origin.lng),
            destination: new google.maps.LatLng(destination.lat, destination.lng),
            travelMode: google.maps.TravelMode.DRIVING
        };
        directionsService.route(request, function(response, status) {
            if (status === google.maps.DirectionsStatus.OK) {
                directionsDisplay.setDirections(response);
            }
        });
    };

    $scope.getValue = function(id){
        return document.getElementById(id).value;
    };
}]);
<commit_msg>Update map.controller.js<commit_after>AugmentedSzczecin.controller('MapController',['$scope', function($scope){

    var directionsDisplay;
    var directionsService = new google.maps.DirectionsService();
    var map;
    var handler = document.getElementById('map-canvas');
    /**
     * Inicjalizacja mapy, centrowanie jej, oraz wyswietlanie tras
     *
     */
    function initialize(mapHandler) {
        directionsDisplay = new google.maps.DirectionsRenderer();
        var center = new google.maps.LatLng(53.425175, 14.550454);
        /**
         * Opcje mapy
         * @type {Object}
         */
        var mapOptions = {
            streetViewControl: true,
            mapTypeControl: true,
            panControl: false,
            zoom:15,
            center: center,
            scaleControl: true
        };
        /**
         * Wysiwietlanie mapy wraz z jej opcjami
         * @type {google}
         */
        map = new google.maps.Map(mapHandler, mapOptions);
        directionsDisplay.setMap(map);

        /**
         * Funkcja stawiajaca Pinezke na mapie
         * @param  {[object} event) {placeMarker(event.latLng);}  - ppm stawia na mapie Pinezke
         * @return {[type]}        - Pinezka pojawia sie w wyznaczonym przez nas miejscu
         */
        google.maps.event.addListener(map, 'rightclick', function(event) {
            placeMarker(event.latLng);
        });

        /**
         * @todo poiList - tablica z punktami poi
         * @type {Array}
         */
        var poiList= [];
        /**
         * punkty poi wyznaczone, do czasu uzyskania poiList
         * @type {Array}
         */
        var points= [
            ['katedra', 53.424736, 14.556168],
            ['kaskada', 53.428271, 14.551955],
            ['castorama', 53.386734, 14.659007],
            ['komisariat dąbie', 53.394111, 14.671734],
            ['outlet park', 53.381792, 14.669432],
            ['wneiz', 53.438839, 14.520724],
            ['wi zut', 53.448778, 14.491090],
            ['kordecki', 53.423487, 14.531787],
            ['szpital na unii', 53.448693, 14.504945],
            ['deptak', 53.429926, 14.544256]
        ]
       /**
        * Klastrowanie, zbieranie wiekszej ilosci punktow poi w jeden
        * @param  {google} entry){var coordinates  - cordy punktow poi
        */
        points.forEach(function(entry){
            var coordinates = new google.maps.LatLng(
                entry[1], entry[2]
            );
            poiMarker= new google.maps.Marker({
                position: coordinates,
                map: map
            });
            poiList.push(poiMarker);
        });
        /**
         * Tworzenie Punktu klastwoania, z wyswietlanie ilosci punktow poi w nim
         * @type {MarkerClusterer}
         */
        var markerCluster = new MarkerClusterer(map, poiList);
    }
    google.maps.event.addDomListener(window, 'load', initialize(handler));

    /**
     * Pinezka
     * @param  {object} location - okreslenie lokacji w ktorej postawiona bedzie pinezka
     * @return {google}          - wyswietlenie pinezkina mapie
     */
    function placeMarker(location) {
        var marker = new google.maps.Marker({
            position: location,
            map: map
        });
        /**
         * Okienko informacyjne z coordami
         * @type {google}
         */
        var infowindow = new google.maps.InfoWindow({
            content: 'Latitude: ' + location.lat() + '
Longitude: ' + location.lng()
        });
        infowindow.open(map,marker);
    }

    $scope.monuments = [
        {
        'name': 'Brama Portowa',
        'lat': 53.425060,
        'lng': 14.550462
        },
        {
        'name': 'Zamek Książąt Pomorskich',
        'lat': 53.426220,
        'lng': 14.560521
        },
        {
        'name': 'Wały Chrobrego',
        'lat': 53.428528,
        'lng': 14.563938
        },
        {
        'name': 'Jasne Błonia',
        'lat': 53.440721,
        'lng': 14.540001
        }
    ];
    /**
     * Wyznaczanie trasy
     * @param  {object} origin      - punkt poczatkowy naszej trasy
     * @param  {object} destination - punkt koncowy naszej trasy
     * @return {google}             - wyznacza najkrotsza trase pomiedzy punktami
     */
    $scope.calcRoute = function (origin, destination) {
        var request = {
            origin: new google.maps.LatLng(origin.lat, origin.lng),
            destination: new google.maps.LatLng(destination.lat, destination.lng),
            travelMode: google.maps.TravelMode.DRIVING
        };
        directionsService.route(request, function(response, status) {
            if (status === google.maps.DirectionsStatus.OK) {
                directionsDisplay.setDirections(response);
            }
        });
    };

    $scope.getValue = function(id){
        return document.getElementById(id).value;
    };
}]);
<|endoftext|>


<commit_before>/**
 * Created by artem on 6/19/15.
 */
(function (angular) {
    'use strict';
    /*global google*/
    angular.module('LogicifyGMap')
        .controller('myCtrl', ['$scope', '$timeout', 'InfoWindow', function ($scope, $timeout, InfoWindow) {
            $scope.markers = [];
            $scope.controlEvents = {
                click: function (event) {
                    $scope.infoWindowName = 'hello you!';
                }
            };
            $scope.infoWindowName = 'hello native you!';
            $scope.cssOpts = {width: '50%', height: '50%', 'min-width': '400px', 'min-height': '200px'};
            $scope.gmOpts = {zoom: 10, center: new google.maps.LatLng(-1, 1)};
            $scope.position = google.maps.ControlPosition.BOTTOM_LEFT;
            $scope.index = 1;
            $scope.closeInfoWindow = function (infowindow) {
                infowindow.close(true);
            };
            $scope.ready = function (map) {
                var infowindow = new InfoWindow({templateUrl: 'template.html'});

                function attach(marker) {
                    google.maps.event.addListener(marker, 'click', function (markerObj) {
                        infowindow.$ready(function (wnd) {
                            wnd.open(map, marker);
                        });
                    });
                }

                for (var i = 10; i < 15; i++) {
                    var pos = new google.maps.LatLng(-1 + 1 / i, 1 + 1 / i);
                    var marker = new google.maps.Marker({
                        id: 'marker_' + i,
                        name: 'is_' + i,
                        position: pos,
                        map: map
                    });
                    $scope.markers.push(marker);
                    attach(marker);
                }
            };

        }])
})(angular);<commit_msg>remove test controller<commit_after><|endoftext|>