<commit_before>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow strict-local
 * @format
 */

import * as React from 'react';
import {
  Animated,
  PanResponder,
  View,
  StyleSheet,
  FlatList,
  useWindowDimensions,
} from 'react-native';

module.exports = {
  displayName: 'SwipeableCardExample',
  framework: 'React',
  title: 'SwipeableCard',
  category: 'Basic',
  description:
    'Example of a swipeable card with scrollable content to test PanResponder and JSResponderHandler interaction.',
  examples: [
    {
      title: 'SwipeableCardExample',
      description: ('This example creates a swipeable card using PanResponder. ' +
        'Under the hood, JSResponderHandler should prevent scroll when the card is being swiped.': string),
      render: function(): React.Node {
        return <SwipeableCard />;
      },
    },
  ],
};

function SwipeableCard() {
  const movementX = React.useRef(new Animated.Value(0)).current;

  const panResponder = React.useRef(
    PanResponder.create({
      onMoveShouldSetPanResponderCapture: (e, gestureState) => {
        const {dx} = gestureState;
        return Math.abs(dx) > 5;
      },
      onPanResponderMove: (e, gestureState) => {
        Animated.event([null, {dx: movementX}], {
          useNativeDriver: false,
        })(e, gestureState);
      },
      onPanResponderEnd: (e, gestureState) => {
        Animated.timing(movementX, {
          toValue: 0,
          useNativeDriver: true,
        }).start();
      },
    }),
  ).current;

  const {width} = useWindowDimensions();
  const rotation = movementX.interpolate({
    inputRange: [-width / 2, 0, width / 2],
    outputRange: (['-5deg', '0deg', '5deg']: $ReadOnlyArray<string>),
    extrapolate: 'clamp',
  });

  return (
    <View style={styles.container}>
      <Animated.View
        {...panResponder.panHandlers}
        style={{
          transform: [{translateX: movementX}, {rotateZ: rotation}],
          flex: 1,
        }}>
        <Card />
      </Animated.View>
    </View>
  );
}

const cardData = Array(5);

function Card(props) {
  const renderItem = ({item, index}) => (
    <View style={index % 2 === 0 ? styles.cardSectionA : styles.cardSectionB} />
  );
  return (
    <View style={styles.card}>
      <FlatList style={{flex: 1}} data={cardData} renderItem={renderItem} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 10,
    paddingTop: 30,
  },
  card: {
    flex: 1,
    margin: 5,
  },
  cardSectionA: {
    height: 200,
    backgroundColor: 'aquamarine',
  },
  cardSectionB: {
    height: 200,
    backgroundColor: 'pink',
  },
});
<commit_msg>Multiple swipeable cards<commit_after>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow strict-local
 * @format
 */

import * as React from 'react';
import {
  Animated,
  PanResponder,
  View,
  StyleSheet,
  FlatList,
  Text,
  useWindowDimensions,
} from 'react-native';

module.exports = {
  displayName: 'SwipeableCardExample',
  framework: 'React',
  title: 'SwipeableCard',
  category: 'Basic',
  description:
    'Example of a swipeable card with scrollable content to test PanResponder and JSResponderHandler interaction.',
  examples: [
    {
      title: 'SwipeableCardExample',
      description: ('This example creates a swipeable card using PanResponder. ' +
        'Under the hood, JSResponderHandler should prevent scroll when the card is being swiped.': string),
      render: function(): React.Node {
        return <SwipeableCardExample />;
      },
    },
  ],
};

function SwipeableCardExample() {
  const cardColors = ['red', 'blue', 'pink', 'aquamarine'];
  const [currentIndex, setCurrentIndex] = React.useState(0);

  const nextIndex = currentIndex + 1;

  const isFirstCardOnTop = currentIndex % 2 !== 0;

  const incrementCurrent = () => setCurrentIndex(currentIndex + 1);

  const getCardColor = index => cardColors[index % cardColors.length];

  /*
   * The cards try to reuse the views. Instead of always rebuilding the current card on top
   * the order is configured by zIndex. This way, the native side reuses the same views for bottom
   * and top after swiping out.
   */
  return (
    <>
      <SwipeableCard
        zIndex={isFirstCardOnTop ? 2 : 1}
        color={
          isFirstCardOnTop
            ? getCardColor(currentIndex)
            : getCardColor(nextIndex)
        }
        onSwipedOut={incrementCurrent}
      />
      <SwipeableCard
        zIndex={isFirstCardOnTop ? 1 : 2}
        color={
          isFirstCardOnTop
            ? getCardColor(nextIndex)
            : getCardColor(currentIndex)
        }
        onSwipedOut={incrementCurrent}
      />
    </>
  );
}

function SwipeableCard(props: {
  zIndex: number,
  color: string,
  onSwipedOut: () => void,
}) {
  // eslint-disable-next-line react-hooks/exhaustive-deps
  const movementX = React.useMemo(() => new Animated.Value(0), [props.color]);

  const panResponder = React.useMemo(
    () =>
      PanResponder.create({
        onMoveShouldSetPanResponderCapture: (e, gestureState) => {
          const {dx} = gestureState;
          return Math.abs(dx) > 5;
        },
        onPanResponderMove: Animated.event([null, {dx: movementX}], {
          useNativeDriver: false,
        }),
        onPanResponderEnd: (e, gestureState) => {
          const {dx} = gestureState;
          if (Math.abs(dx) > 120) {
            Animated.timing(movementX, {
              toValue: dx > 0 ? 1000 : -1000,
              useNativeDriver: true,
            }).start(props.onSwipedOut);
          } else {
            Animated.timing(movementX, {
              toValue: 0,
              useNativeDriver: true,
            }).start();
          }
        },
      }),
    [movementX, props.onSwipedOut],
  );

  const {width} = useWindowDimensions();
  const rotation = movementX.interpolate({
    inputRange: [-width / 2, 0, width / 2],
    outputRange: (['-5deg', '0deg', '5deg']: $ReadOnlyArray<string>),
    extrapolate: 'clamp',
  });

  return (
    <View style={StyleSheet.compose(styles.container, {zIndex: props.zIndex})}>
      <Animated.View
        {...panResponder.panHandlers}
        style={{
          transform: [{translateX: movementX}, {rotateZ: rotation}],
          flex: 1,
        }}>
        <Card color={props.color} />
      </Animated.View>
    </View>
  );
}

const cardData = Array(5);

function Card(props: {color: string}) {
  const renderItem = ({item, index}) => (
    <CardSection color={props.color} index={index} />
  );

  const separatorComponent = () => <View style={styles.separator} />;

  const listRef = React.useRef<?React.ElementRef<typeof FlatList>>();

  React.useEffect(() => {
    listRef.current?.scrollToOffset({offset: 0, animated: false});
  }, [props.color]);

  return (
    <View style={styles.card}>
      <FlatList
        style={{flex: 1}}
        data={cardData}
        renderItem={renderItem}
        ItemSeparatorComponent={separatorComponent}
        ref={listRef}
      />
    </View>
  );
}

function CardSection(props: {index: number, color: string}) {
  return (
    <View
      style={StyleSheet.compose(styles.sectionBg, {
        backgroundColor: props.color,
      })}>
      <Text style={styles.sectionText}>Section #{props.index}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    position: 'absolute',
    height: '100%',
    width: '100%',
    padding: 10,
    paddingTop: 30,
  },
  card: {
    flex: 1,
    margin: 5,
    backgroundColor: 'white',
    borderWidth: 1,
    borderColor: 'lightgray',
  },
  separator: {
    width: '100%',
    height: 2,
    backgroundColor: 'white',
  },
  sectionBg: {
    height: 200,
    alignItems: 'center',
    justifyContent: 'center',
  },
  sectionText: {
    color: 'white',
    fontWeight: 'bold',
  },
});
<|endoftext|>


<commit_before>/**
 * @ngdoc service
 * @name belajarOauth2ImplicitClientApp.BarangFactory
 * @description
 * # BarangFactory
 * Factory in the belajarOauth2ImplicitClientApp.
 */

(function() {
  'use strict';
  angular.module('belajarOauth2ImplicitClientApp')
    .factory('BarangFactory', BarangFactory);

  BarangFactory.$inject = ['$resource'];

  function BarangFactory($resource) {
    var barangFactory = this;

    barangFactory.getAllBarang = function() {
      return $resource('/api/barang');
    };

    return barangFactory;
  }
})();
<commit_msg>Update Barang Factory with token<commit_after>/**
 * @ngdoc service
 * @name belajarOauth2ImplicitClientApp.BarangFactory
 * @description
 * # BarangFactory
 * Factory in the belajarOauth2ImplicitClientApp.
 */

(function() {
  'use strict';
  angular.module('belajarOauth2ImplicitClientApp')
    .factory('BarangFactory', BarangFactory);

  BarangFactory.$inject = ['$resource', 'BarangService'];

  function BarangFactory($resource, BarangService) {
    var barangFactory = this;

    barangFactory.getAllBarang = function(token) {
      console.log(BarangService.getBarangAll);
      return $resource(BarangService.getBarangAll + token);
    };

    return barangFactory;
  }
})();
<|endoftext|>


<commit_before>import { createSelector } from 'reselect';
import { deburrUpper } from 'app/utils';
import sortBy from 'lodash/sortBy';

const getCountries = state => state.countries;
const getAllIndicators = state => (state.data ? state.data.indicators : {});
const getCategories = state => (state.data ? state.data.categories : {});
const getSectors = state => (state.data ? state.data.sectors : {});
const getSearch = state => deburrUpper(state.search);

export const parseIndicatorsDefs = createSelector(
  [getAllIndicators, getCategories, getCountries],
  (indicators, categories, countries) => {
    if (!indicators || !categories || !countries) return null;
    const parsedIndicators = {};
    Object.keys(categories).forEach(category => {
      const categoryIndicators = indicators.filter(
        indicator => indicator.category_ids.indexOf(parseInt(category, 10)) > -1
      );
      const parsedDefinitions = categoryIndicators.map(def => {
        const descriptions = countries.map(country => ({
          iso: country,
          value: def.locations[country] ? def.locations[country][0].value : null
        }));
        return {
          title: def.name,
          slug: def.slug,
          descriptions
        };
      });
      if (parsedDefinitions && parsedDefinitions.length) {
        parsedIndicators[category] = sortBy(parsedDefinitions, 'title');
      }
    });
    return parsedIndicators;
  }
);

export const parseIndicatorsDefsWithSectors = createSelector(
  [getAllIndicators, getCategories, getCountries, getSectors],
  (indicators, categories, countries, sectors) => {
    if (!indicators || !categories || !countries || !sectors) return null;
    const parsedIndicators = [];
    Object.keys(categories).forEach(category => {
      const indicatorsWithCategory = indicators.filter(
        indicator => indicator.category_ids.indexOf(parseInt(category, 10)) > -1
      );
      const parsedDefinitions = indicatorsWithCategory.map(indicator => {
        const sectorIds = [];
        let descriptions = [];
        Object.keys(indicator.locations).forEach(location => {
          indicator.locations[location].forEach(def =>
            sectorIds.push(def.sector_id)
          );
        });
        if (sectorIds && sectorIds.length && sectorIds[0]) {
          sectorIds.forEach(sector => {
            const descriptionsBySector = countries.map(country => {
              const value = indicator.locations[country]
                ? indicator.locations[country].find(
                  indicValue => indicValue.sector_id === sector
                )
                : '';
              return {
                iso: country,
                value: value ? value.value : null
              };
            });
            descriptions.push({
              title: sectors[sector].name,
              slug: sector,
              descriptions: descriptionsBySector
            });
          });
        } else {
          descriptions = countries.map(country => ({
            iso: country,
            values: indicator.locations[country]
              ? indicator.locations[country]
              : null
          }));
        }
        return {
          title: indicator.name,
          slug: indicator.slug,
          descriptions: sortBy(descriptions, 'title')
        };
      });
      if (parsedDefinitions) {
        parsedIndicators[category] = sortBy(parsedDefinitions, 'title');
      }
    });
    return parsedIndicators;
  }
);

export const getNDCs = createSelector(
  [getCategories, parseIndicatorsDefs],
  (categories, indicators) => {
    if (!categories) return null;
    const ndcs = Object.keys(categories).map(category => ({
      title: categories[category].name,
      slug: categories[category].slug,
      definitions: indicators[category] ? indicators[category] : []
    }));
    return ndcs;
  }
);

export const getSectoralNDCs = createSelector(
  [getCategories, parseIndicatorsDefsWithSectors],
  (categories, indicators) => {
    if (!categories || !indicators) return null;
    const ndcs = Object.keys(categories).map(category => ({
      title: categories[category].name,
      slug: categories[category].slug,
      indicators: indicators[category] ? indicators[category] : []
    }));
    return ndcs;
  }
);

export const filterNDCs = createSelector(
  [getNDCs, getSearch],
  (ndcs, search) => {
    if (!ndcs) return null;
    const filteredNDCs = ndcs.map(ndc => {
      const defs = ndc.definitions.filter(
        def =>
          deburrUpper(def.title).indexOf(search) > -1 ||
          deburrUpper(def.descriptions[0].value).indexOf(search) > -1
      );

      return {
        ...ndc,
        definitions: defs
      };
    });
    const reducedNDCs = filteredNDCs.filter(ndc => ndc.definitions.length > 0);
    return sortBy(reducedNDCs, 'title');
  }
);

export const filterSectoralNDCs = createSelector(
  [getSectoralNDCs, getSearch],
  (ndcs, search) => {
    if (!ndcs) return null;
    const reducedNDCs = ndcs.filter(
      ndc => ndc.indicators && ndc.indicators.length
    );
    const filteredNDCs = reducedNDCs.map(ndc => {
      const defs = [];
      ndc.indicators.forEach(def => {
        const descs = def.descriptions.filter(
          desc =>
            deburrUpper(desc.title).indexOf(search) > -1 ||
            deburrUpper(desc.descriptions[0].value).indexOf(search) > -1
        );
        if (descs && descs.length) {
          defs.push({
            ...def,
            descriptions: descs
          });
        }
      });

      return {
        ...ndc,
        indicators: defs
      };
    });
    return sortBy(filteredNDCs, 'title');
  }
);

export default {
  filterNDCs,
  filterSectoralNDCs
};
<commit_msg>New selectors for parsing sectors and indicators<commit_after>import { createSelector } from 'reselect';
import { deburrUpper } from 'app/utils';
import sortBy from 'lodash/sortBy';
import uniq from 'lodash/uniq';
import snakeCase from 'lodash/snakeCase';

const getCountries = state => state.countries;
const getAllIndicators = state => (state.data ? state.data.indicators : {});
const getCategories = state => (state.data ? state.data.categories : {});
const getSectors = state => (state.data ? state.data.sectors : {});
const getSearch = state => deburrUpper(state.search);

export const parseIndicatorsDefs = createSelector(
  [getAllIndicators, getCategories, getCountries],
  (indicators, categories, countries) => {
    if (!indicators || !categories || !countries) return null;
    const parsedIndicators = {};
    Object.keys(categories).forEach(category => {
      const categoryIndicators = indicators.filter(
        indicator => indicator.category_ids.indexOf(parseInt(category, 10)) > -1
      );
      const parsedDefinitions = categoryIndicators.map(def => {
        const descriptions = countries.map(country => ({
          iso: country,
          value: def.locations[country] ? def.locations[country][0].value : null
        }));
        return {
          title: def.name,
          slug: def.slug,
          descriptions
        };
      });
      if (parsedDefinitions && parsedDefinitions.length) {
        parsedIndicators[category] = sortBy(parsedDefinitions, 'title');
      }
    });
    return parsedIndicators;
  }
);

export const groupIndicatorsByCategory = createSelector(
  [getAllIndicators, getCategories],
  (indicators, categories) => {
    if (!indicators || !categories) return null;
    return Object.keys(categories)
      .map(cat => ({
        ...categories[cat],
        indicators: indicators.filter(
          ind => ind.category_ids.indexOf(parseInt(cat, 10)) > -1
        )
      }))
      .filter(cat => cat.indicators.length);
  }
);

export const getCategoriesWithSectors = createSelector(
  [groupIndicatorsByCategory],
  categories => {
    if (!categories) return null;
    return categories.map(cat => {
      const sectorIds = [];
      cat.indicators.forEach(ind => {
        Object.keys(ind.locations).forEach(location => {
          ind.locations[location].forEach(
            value => value.sector_id && sectorIds.push(value.sector_id)
          );
        });
      });
      return {
        ...cat,
        sectors: sectorIds.length ? uniq(sectorIds) : null
      };
    });
  }
);

export const parsedCategoriesWithSectors = createSelector(
  [getCategoriesWithSectors, getSectors],
  (categories, sectors) => {
    if (!categories) return null;
    return sortBy(
      categories.map(cat => {
        const sectorsParsed = sortBy(
          cat.sectors &&
            cat.sectors.length &&
            cat.sectors.map(sec => {
              const definitions = sortBy(
                cat.indicators.map(ind => {
                  const descriptions = Object.keys(ind.locations).map(loc => {
                    const value = ind.locations[loc].find(
                      v => v.sector_id === sec
                    );
                    return {
                      iso: loc,
                      value: value ? value.value : null
                    };
                  });
                  return {
                    title: ind.name,
                    slug: ind.slug,
                    descriptions
                  };
                }),
                'title'
              );
              return {
                title: sectors[sec].name,
                slug: snakeCase(sectors[sec].name),
                definitions
              };
            }),
          'title'
        );
        return {
          title: cat.name,
          slug: cat.slug,
          sectors: sectorsParsed
        };
      }),
      'title'
    );
  }
);

export const getNDCs = createSelector(
  [getCategories, parseIndicatorsDefs],
  (categories, indicators) => {
    if (!categories) return null;
    const ndcs = Object.keys(categories).map(category => ({
      title: categories[category].name,
      slug: categories[category].slug,
      definitions: indicators[category] ? indicators[category] : []
    }));
    return ndcs;
  }
);

export const filterNDCs = createSelector(
  [getNDCs, getSearch],
  (ndcs, search) => {
    if (!ndcs) return null;
    const filteredNDCs = ndcs.map(ndc => {
      const defs = ndc.definitions.filter(
        def =>
          deburrUpper(def.title).indexOf(search) > -1 ||
          deburrUpper(def.descriptions[0].value).indexOf(search) > -1
      );

      return {
        ...ndc,
        definitions: defs
      };
    });
    const reducedNDCs = filteredNDCs.filter(ndc => ndc.definitions.length > 0);
    return sortBy(reducedNDCs, 'title');
  }
);

export const filterSectoralNDCs = createSelector(
  [parsedCategoriesWithSectors, getSearch],
  (ndcs, search) => {
    if (!ndcs) return null;
    if (!search) return ndcs;
    const filteredNDCs = [];
    ndcs.forEach(ndc => {
      const sectors = [];
      ndc.sectors.forEach(sec => {
        const definitions = sec.definitions.filter(
          def =>
            deburrUpper(def.title).indexOf(search) > -1 ||
            deburrUpper(def.descriptions[0].value).indexOf(search) > -1
        );
        if (definitions.length) {
          sectors.push({
            ...sec,
            definitions
          });
        }
      });
      if (sectors.length) {
        filteredNDCs.push({
          ...ndc,
          sectors
        });
      }
    });
    return filteredNDCs;
  }
);

export default {
  filterNDCs,
  filterSectoralNDCs
};
<|endoftext|>


<commit_before>/*========================================================================

   This file is part of the GOsa project -  http://gosa-project.org

   Copyright:
      (C) 2010-2012 GONICUS GmbH, Germany, http://www.gonicus.de

   License:
      LGPL-2.1: http://www.gnu.org/licenses/lgpl-2.1.html

   See the LICENSE file in the project's top-level directory for details.

======================================================================== */

qx.Class.define("gosa.ui.widgets.QPushButtonWidget",
{
  extend : gosa.ui.widgets.Widget,

  properties: {

    // The buttons text
    text : {
      init : "",
      check : "String",
      apply : "_setText",
      nullable: true
    }
  },

  construct : function()
  {
    this.base(arguments);

    // Call super class
    this.contents.setLayout(new qx.ui.layout.Canvas());
    this._widget = new qx.ui.form.Button();
    this._widget.addListener("execute", function(){
        if(this._dialog){
          var d = this.getParent()._dialogs[this._dialog];
          if(d){
            d.open();
          }else{
            this.error("no such dialog named '" + this._dialog + "'!");
          }
        }
      }, this);
    this.contents.add(this._widget, {top:0, bottom:0, left:0, right: 0});
  },

  members :
  {
    _widget: null,
    _dialog: null,

    _setText : function(value)
    {
      this._widget.setLabel(this['tr'](value));
    },

    /* Apply collected gui properties to this widet
     * */
    _applyGuiProperties: function(props){

      // This happens when this widgets gets destroyed - all properties will be set to null.
      if(!props){
        return;
      }

      // Check if we have to open a dialog.
      if(props["dialog"] && props["dialog"]["string"]){
        this._dialog = props["dialog"]["string"];
      }

      if(props["text"] && props["text"]["string"]){
        this._setText(props["text"]["string"]);
      }
    }
  }
});

// vim:tabstop=2:expandtab:shiftwidth=2
<commit_msg>Added property 'dialog' to QPushButton that opens on button execution<commit_after>/*========================================================================

   This file is part of the GOsa project -  http://gosa-project.org

   Copyright:
      (C) 2010-2012 GONICUS GmbH, Germany, http://www.gonicus.de

   License:
      LGPL-2.1: http://www.gnu.org/licenses/lgpl-2.1.html

   See the LICENSE file in the project's top-level directory for details.

======================================================================== */

qx.Class.define("gosa.ui.widgets.QPushButtonWidget", {

  extend : gosa.ui.widgets.Widget,

  construct : function() {
    this.base(arguments);

    this.contents.setLayout(new qx.ui.layout.Canvas());
    this._widget = new qx.ui.form.Button();
    this._widget.addListener("execute", function() {
        if (this._dialog) {
          var d = this.getParent()._dialogs[this._dialog];
          if (d) {
            d.open();
          } else {
            this.error("no such dialog named '" + this._dialog + "'!");
          }
        }
      }, this);

    this.contents.add(this._widget, {
      top : 0,
      bottom : 0,
      left : 0,
      right : 0
    });
  },

  properties: {
    /**
     * The button label.
     */
    text : {
      init : "",
      check : "String",
      apply : "_setText",
      nullable: true
    },

    /**
     * Base name of a dialog class. On click on the button, this class is searched for in the namespace of
     * "gosa.ui.dialogs" and then a new such dialog will be created. Example: "ChangePasswordDialog" opens a new
     * "gosa.ui.dialogs.ChangePasswordDialog" dialog.
     */
    dialog : {
      init : null,
      nullable : true,
      check : "String",
      apply : "_applyDialog"
    }
  },

  members : {

    _widget : null,
    _dialog : null,
    _dialogExecutionListener : null,

    _setText : function(value) {
      this._widget.setLabel(this.tr(value));
    },

    _applyGuiProperties : function(props) {
      // properties are null when widget gets destroyed
      if (!props) {
        return;
      }

      if (props.dialog && props.dialog.string) {
        this._dialog = props.dialog.string;
      }
      if (props.text && props.text.string) {
        this._setText(props.text.string);
      }
    },

    _applyDialog : function(value) {
      if (value) {
        this._createDialogExecutionListener();
      }
      else {
        this._removeDialogExecutionListener();
      }
    },

    _createDialogExecutionListener : function() {
      if (!this._dialogExecutionListener) {
        this._dialogExecutionListener = this._widget.addListener("execute", function() {
          var clazz = qx.Class.getByName("gosa.ui.dialogs." + this.getDialog());
          if (!clazz) {
            qx.core.Assert.fail("Unkown dialog class: '" + this.getDialog() + "'");
          }
          var dialog = new clazz();
          dialog.setAutoDispose();
          dialog.open();
        }, this);
      }
    },

    _removeDialogExecutionListener : function() {
      if (this._dialogExecutionListener) {
        this._widget.removeListenerById(this._dialogExecutionListener);
        this._dialogExecutionListener = null;
      }
    }
  },

  destruct : function() {
    this._removeDialogExecutionListener();
  }
});
<|endoftext|>


<commit_before>function createLayout() {
	var Page = $Page, property = Page.getPageProperties(), hash = property.hash;

	// Ext.create('Ext.panel.Panel', {
	Ext.create('Ext.container.Container', {
		id : 'tabLayout',
		border : true,
		autoScroll : false,
		width : $(window).width() - 250,
		items : [{
			region : 'north',
			border : false,
			height : 22,
			xtype : 'tabpanel',
			id : 'tabPanel',
			items : [{
				title : "Specialty Genes",
				id : "0"
			}],
			ClickFromTab : true,
			listeners : {
				'tabchange' : function(tabPanel, tab) {
					if (tab.getId() == 0) {
						hash.cwG = false, hash.gId = "", hash.gName = "";
					} else {
						hash.cwG = (hash.cwG || hash.cwG == "true"), hash.gId = !hash.cwG ? "" : hash.gId, hash.gName = !hash.cwG ? "" : hash.gName;
					}

					if (!this.ClickFromTab) {
						loadGrid();
						this.ClickFromTab = true;
					} else {
						hash.aT = parseInt(tab.getId());
						hash.aP[tab.getId()] = 1, createURL();
					}
				}
			}
		}, {
			region : 'center',
			xtype: 'container',
			id : 'centerPanel',
			contentEl : 'information',
			border : false,
			split : false
		}, {
			region : 'south',
			xtype: 'container',
			id : 'southPanel',
			html : '

',
			height : 570,
			border : false,
			autoScroll : true
		}],
		renderTo : 'sample-layout'
	});

	Ext.create('Ext.panel.Panel', {
		title : 'Filter By',
		renderTo : 'tree-panel',
		width : 239,
		height : 620,
		border : true,
		resizable : true,
		autoScroll : false,
		collapsible : true,
		collapseDirection : 'left',
		id : 'treePanel',
		items : [{
			id : 'westPanel',
			region : 'west',
			html : '

',
			width : 239,
			height : 340,
			border: 0,
			split : true,
			tbar : [{
				xtype : 'textfield',
				itemId : 'keyword',
				width : 150,
				hideLabel : true,
				allowBlank : true,
				value : hash.kW,
				emptyText : 'keyword',
				listeners : {
					specialKey : function(field, e) {
						if (e.getKey() == e.ENTER) {
							hash.kW = field.value.trim();
							Ext.getDom("keyword").value = getOriginalKeyword(hash);
							refresh();
						}
					}
				}
			}, '->', {
				text : 'Clear All',
				handler : function() {
					hash.kW = "";
					Ext.getDom("keyword").value = getOriginalKeyword(hash);
					this.ownerCt.getComponent("keyword").setRawValue("");
					// clear filter panel
					var fP = Ext.getCmp("filterPanel");
					fP.getComponent('sbjCoverage').setRawValue(0);
					fP.getComponent('qryCoverage').setRawValue(0);
					fP.getComponent('identity').setRawValue(0);
					fP.getComponent("organism_filter").setValue({scope:"All"});

					refresh("clear_all");
				}
			}]
		}, {
			id: 'filterPanel',
			xtype: 'container',
			region: 'south',
			height: 250,
			border: 0,
			margin: '0 0 0 10px',
			items: [{
				xtype: 'displayfield',
				fieldLabel: 'Filter BLAST Hits by:',
				labelStyle: 'color: #CC6600; font-weight: bold',
				labelWidth: 200
			}, {
				xtype: 'radiogroup',
				itemId: 'organism_filter',
				fieldLabel: 'Source organism',
				labelSeparator: '',
				labelAlign: 'top',
				margin: '5 0 5 16',
				columns: 1,
				items: [{
					boxLabel: 'Same Genome',
					name: 'scope',
					inputValue: 'Genome',
					margin: '0 0 0 16'
				}, {
					boxLabel: 'Same Species',
					name: 'scope',
					inputValue: 'Species',
					margin: '0 0 0 16'
				}, {
					boxLabel: 'Same Genus',
					name: 'scope',
					inputValue: 'Genus',
					margin: '0 0 0 16'
				}, {
					boxLabel: 'All',
					name: 'scope',
					inputValue: 'All',
					checked: true,
					margin: '0 0 0 16'
				}]
			}, {
				xtype: 'numberfield',
				itemId: 'qryCoverage',
				fieldLabel: '% Query Coverage',
				labelSeparator: ' >= ',
				labelAlign: 'left',
				value: 0,
				minValue: 0,
				maxValue: 100,
				step: 10,
				labelWidth: 140,
				width: 200,
				margin: '0 0 3 16'
			},{
				xtype: 'numberfield',
				itemId: 'sbjCoverage',
				fieldLabel: '% Subject Coverage',
				labelSeparator: ' >= ',
				labelAlign: 'left',
				value: 0,
				minValue: 0,
				maxValue: 100,
				step: 10,
				labelWidth: 140,
				width: 200,
				margin: '0 0 3 16'
			},{
				xtype: 'numberfield',
				itemId: 'identity',
				fieldLabel: '% Identity',
				labelSeparator: ' >= ',
				labelAlign: 'left',
				value: 0,
				minValue: 0,
				maxValue: 100,
				step: 10,
				labelWidth: 140,
				width: 200,
				margin: '0 0 3 16'
			},{
				xtype: 'button',
				text: 'Filter',
				cls: 'button',
				margin: '5 0 0 160',
				handler: function() {
					hash.sbjCoverage = this.ownerCt.getComponent('sbjCoverage').getValue();
					hash.qryCoverage = this.ownerCt.getComponent('qryCoverage').getValue();
					hash.identity = this.ownerCt.getComponent('identity').getValue();
					hash.scope = this.ownerCt.getComponent("organism_filter").getValue().scope;
					Ext.getDom("keyword").value = getOriginalKeyword(hash);
					refresh();
				}
			}]
		}],
		listeners : {
			resize : function(cmp, width, height, oldWidth, oldHeight, eOpts) {
				var Page = $Page;
				if (Page.getGrid()) {
					Ext.getCmp("westPanel").setWidth(width);
					Ext.getCmp("GenericSelectorTree").setWidth(width - 7);
					Page.doTabLayout();
				}
			}
		}
	});
}

function loadFBCD() {
	var tabs = Ext.getCmp("tabPanel"), id = tabs.getActiveTab().getId(), hash = $Page.getPageProperties().hash;

	SetLoadParameters();

	Ext.getCmp('westPanel').getDockedItems()[0].getComponent("keyword").setRawValue(hash.kW);

	if (hash.aT == parseInt(id)) {
		loadGrid();
	} else {
		tabs.ClickFromTab = false;
		tabs.setActiveTab(hash.aT);
	}
}

function getExtraParams() {
	var Page = $Page, property = Page.getPageProperties(), hash = property.hash, which = hash.aT, name = property.name, tree = property.tree;

	return {
		pk : hash.key,
		need : which,
		taxonId : hash.tId,
		keyword : constructKeyword((tree) ? tree.getSelectedTerms() : {}, name),
		facet : JSON.stringify({
			"facet" : configuration[name].display_facets.join(","),
			"facet_text" : configuration[name].display_facets_texts.join(","),
			'field_facets': configuration[name].field_facets.join(',')
		})
	};
}

function CallBack() {
	var Page = $Page, property = Page.getPageProperties(), hash = property.hash, totalcount = Page.getStore(hash.aT).totalCount, tree = property.tree, treeDS = property.treeDS, name = property.name;

	Ext.getDom('grid_result_summary').innerHTML = "" + totalcount + " records found
";

	if (tree) {
		treeDS.proxy.extraParams = {
			need : "tree",
			pk : hash.key,
			keyword : constructKeyword((tree != null) ? tree.getSelectedTerms() : {}, name),
			facet : JSON.stringify({
				"facet" : configuration[name].display_facets.join(","),
				"facet_text" : configuration[name].display_facets_texts.join(","),
				'field_facets': configuration[name].field_facets.join(',')
			}),
			state : JSON.stringify(tree.getState())
		};
		treeDS.load();
	} else {
		createTree();
	}
	if (Page.getGrid().sortchangeOption) {
		Page.getGrid().setSortDirectionColumnHeader();
	}
}

function getSelectedFeatures() {"use strict";

	var Page = $Page, property = Page.getPageProperties(), sl = Page.getCheckBox().getSelections(), i, fids = property.fids;

	for ( i = 0; i < sl.length; i++) {
		fids.push(sl[i].data.feature_id);
	}
}

function renderSource(value, metadata, record, rowIndex, colIndex, store) {
	metadata.tdAttr = 'data-qtip="' + value + '" data-qclass="x-tip"';
	switch (record.data.source) {
		case "ARDB":
			return Ext.String.format('{0}', value);
			break;
		case "CARD":
			return Ext.String.format('{0}', value);
			break;
		case "DrugBank":
			return Ext.String.format('{0}', value);
			break;
		case "TDD":
			return Ext.String.format('{0}', value);
			break;
		case "Human":
			return Ext.String.format('{0}', value);
			break;
		case "PATRIC_VF":
			return Ext.String.format('{0}', value);
			break;
		case "VFDB":
			return Ext.String.format('{0}', value);
			break;
		case "Victors":
			return Ext.String.format('{0}', value);
			break;
		default:
			return value;
	}
}
function renderSourceId(value, metadata, record, rowIndex, colIndex, store) {
	metadata.tdAttr = 'data-qtip="' + value + '" data-qclass="x-tip"';
	switch (record.data.source) {
		case "ARDB":
			return Ext.String.format('{0}', value);
			break;
		case "DrugBank":
			return Ext.String.format('{0}', value);
			break;
		case "TDD":
			return Ext.String.format('{0}', value);
			break;
		case "Human":
			return Ext.String.format('{0}', value);
			break;
		case "PATRIC_VF":
			return Ext.String.format('{0}', value);
			break;
		case "VFDB":
			return Ext.String.format('{0}', value);
			break;
		case "Victors":
			return Ext.String.format('{0}', value);
			break;
		default:
			return value;
	}
}

//Download File
//BEGIN

function DownloadFile(type) {"use strict";

	var Page = $Page, property = Page.getPageProperties(), hash = property.hash, form = Ext.getDom("fTableForm"), name = property.name, tree = property.tree;

	if (isOverDownloadLimit()) {
		return false;
	}
	if (tree.getSelectedTerms()["Keyword"] == null) {
		tree.selectedTerm["Keyword"] = Ext.getDom("keyword").value;
	}

	// form.action = "/patric-searches-and-tools/jsp/grid_download_handler.jsp";
	form.action = "/portal/portal/patric/SpecialtyGeneSearch/SpecialtyGeneSearchWindow?action=b&cacheability=PAGE&need=download";
	//form.download_keyword.value = constructKeyword(tree.getSelectedTerms(), name);
	form.pk.value = hash.key;
	form.fileformat.value = arguments[0];
	form.target = "";
	getHashFieldsToDownload(form);

	var grid = Page.getGrid();
	var sort = [];
	sort.push(getSortersInText(grid.store));
	form.sort.value = JSON.stringify(sort);
	form.submit();
}
<commit_msg>fix bug: link outs for specialty_gene<commit_after>function createLayout() {
	var Page = $Page, property = Page.getPageProperties(), hash = property.hash;

	// Ext.create('Ext.panel.Panel', {
	Ext.create('Ext.container.Container', {
		id : 'tabLayout',
		border : true,
		autoScroll : false,
		width : $(window).width() - 250,
		items : [{
			region : 'north',
			border : false,
			height : 22,
			xtype : 'tabpanel',
			id : 'tabPanel',
			items : [{
				title : "Specialty Genes",
				id : "0"
			}],
			ClickFromTab : true,
			listeners : {
				'tabchange' : function(tabPanel, tab) {
					if (tab.getId() == 0) {
						hash.cwG = false, hash.gId = "", hash.gName = "";
					} else {
						hash.cwG = (hash.cwG || hash.cwG == "true"), hash.gId = !hash.cwG ? "" : hash.gId, hash.gName = !hash.cwG ? "" : hash.gName;
					}

					if (!this.ClickFromTab) {
						loadGrid();
						this.ClickFromTab = true;
					} else {
						hash.aT = parseInt(tab.getId());
						hash.aP[tab.getId()] = 1, createURL();
					}
				}
			}
		}, {
			region : 'center',
			xtype: 'container',
			id : 'centerPanel',
			contentEl : 'information',
			border : false,
			split : false
		}, {
			region : 'south',
			xtype: 'container',
			id : 'southPanel',
			html : '

',
			height : 570,
			border : false,
			autoScroll : true
		}],
		renderTo : 'sample-layout'
	});

	Ext.create('Ext.panel.Panel', {
		title : 'Filter By',
		renderTo : 'tree-panel',
		width : 239,
		height : 620,
		border : true,
		resizable : true,
		autoScroll : false,
		collapsible : true,
		collapseDirection : 'left',
		id : 'treePanel',
		items : [{
			id : 'westPanel',
			region : 'west',
			html : '

',
			width : 239,
			height : 340,
			border: 0,
			split : true,
			tbar : [{
				xtype : 'textfield',
				itemId : 'keyword',
				width : 150,
				hideLabel : true,
				allowBlank : true,
				value : hash.kW,
				emptyText : 'keyword',
				listeners : {
					specialKey : function(field, e) {
						if (e.getKey() == e.ENTER) {
							hash.kW = field.value.trim();
							Ext.getDom("keyword").value = getOriginalKeyword(hash);
							refresh();
						}
					}
				}
			}, '->', {
				text : 'Clear All',
				handler : function() {
					hash.kW = "";
					Ext.getDom("keyword").value = getOriginalKeyword(hash);
					this.ownerCt.getComponent("keyword").setRawValue("");
					// clear filter panel
					var fP = Ext.getCmp("filterPanel");
					fP.getComponent('sbjCoverage').setRawValue(0);
					fP.getComponent('qryCoverage').setRawValue(0);
					fP.getComponent('identity').setRawValue(0);
					fP.getComponent("organism_filter").setValue({scope:"All"});

					refresh("clear_all");
				}
			}]
		}, {
			id: 'filterPanel',
			xtype: 'container',
			region: 'south',
			height: 250,
			border: 0,
			margin: '0 0 0 10px',
			items: [{
				xtype: 'displayfield',
				fieldLabel: 'Filter BLAST Hits by:',
				labelStyle: 'color: #CC6600; font-weight: bold',
				labelWidth: 200
			}, {
				xtype: 'radiogroup',
				itemId: 'organism_filter',
				fieldLabel: 'Source organism',
				labelSeparator: '',
				labelAlign: 'top',
				margin: '5 0 5 16',
				columns: 1,
				items: [{
					boxLabel: 'Same Genome',
					name: 'scope',
					inputValue: 'Genome',
					margin: '0 0 0 16'
				}, {
					boxLabel: 'Same Species',
					name: 'scope',
					inputValue: 'Species',
					margin: '0 0 0 16'
				}, {
					boxLabel: 'Same Genus',
					name: 'scope',
					inputValue: 'Genus',
					margin: '0 0 0 16'
				}, {
					boxLabel: 'All',
					name: 'scope',
					inputValue: 'All',
					checked: true,
					margin: '0 0 0 16'
				}]
			}, {
				xtype: 'numberfield',
				itemId: 'qryCoverage',
				fieldLabel: '% Query Coverage',
				labelSeparator: ' >= ',
				labelAlign: 'left',
				value: 0,
				minValue: 0,
				maxValue: 100,
				step: 10,
				labelWidth: 140,
				width: 200,
				margin: '0 0 3 16'
			},{
				xtype: 'numberfield',
				itemId: 'sbjCoverage',
				fieldLabel: '% Subject Coverage',
				labelSeparator: ' >= ',
				labelAlign: 'left',
				value: 0,
				minValue: 0,
				maxValue: 100,
				step: 10,
				labelWidth: 140,
				width: 200,
				margin: '0 0 3 16'
			},{
				xtype: 'numberfield',
				itemId: 'identity',
				fieldLabel: '% Identity',
				labelSeparator: ' >= ',
				labelAlign: 'left',
				value: 0,
				minValue: 0,
				maxValue: 100,
				step: 10,
				labelWidth: 140,
				width: 200,
				margin: '0 0 3 16'
			},{
				xtype: 'button',
				text: 'Filter',
				cls: 'button',
				margin: '5 0 0 160',
				handler: function() {
					hash.sbjCoverage = this.ownerCt.getComponent('sbjCoverage').getValue();
					hash.qryCoverage = this.ownerCt.getComponent('qryCoverage').getValue();
					hash.identity = this.ownerCt.getComponent('identity').getValue();
					hash.scope = this.ownerCt.getComponent("organism_filter").getValue().scope;
					Ext.getDom("keyword").value = getOriginalKeyword(hash);
					refresh();
				}
			}]
		}],
		listeners : {
			resize : function(cmp, width, height, oldWidth, oldHeight, eOpts) {
				var Page = $Page;
				if (Page.getGrid()) {
					Ext.getCmp("westPanel").setWidth(width);
					Ext.getCmp("GenericSelectorTree").setWidth(width - 7);
					Page.doTabLayout();
				}
			}
		}
	});
}

function loadFBCD() {
	var tabs = Ext.getCmp("tabPanel"), id = tabs.getActiveTab().getId(), hash = $Page.getPageProperties().hash;

	SetLoadParameters();

	Ext.getCmp('westPanel').getDockedItems()[0].getComponent("keyword").setRawValue(hash.kW);

	if (hash.aT == parseInt(id)) {
		loadGrid();
	} else {
		tabs.ClickFromTab = false;
		tabs.setActiveTab(hash.aT);
	}
}

function getExtraParams() {
	var Page = $Page, property = Page.getPageProperties(), hash = property.hash, which = hash.aT, name = property.name, tree = property.tree;

	return {
		pk : hash.key,
		need : which,
		taxonId : hash.tId,
		keyword : constructKeyword((tree) ? tree.getSelectedTerms() : {}, name),
		facet : JSON.stringify({
			"facet" : configuration[name].display_facets.join(","),
			"facet_text" : configuration[name].display_facets_texts.join(","),
			'field_facets': configuration[name].field_facets.join(',')
		})
	};
}

function CallBack() {
	var Page = $Page, property = Page.getPageProperties(), hash = property.hash, totalcount = Page.getStore(hash.aT).totalCount, tree = property.tree, treeDS = property.treeDS, name = property.name;

	Ext.getDom('grid_result_summary').innerHTML = "" + totalcount + " records found
";

	if (tree) {
		treeDS.proxy.extraParams = {
			need : "tree",
			pk : hash.key,
			keyword : constructKeyword((tree != null) ? tree.getSelectedTerms() : {}, name),
			facet : JSON.stringify({
				"facet" : configuration[name].display_facets.join(","),
				"facet_text" : configuration[name].display_facets_texts.join(","),
				'field_facets': configuration[name].field_facets.join(',')
			}),
			state : JSON.stringify(tree.getState())
		};
		treeDS.load();
	} else {
		createTree();
	}
	if (Page.getGrid().sortchangeOption) {
		Page.getGrid().setSortDirectionColumnHeader();
	}
}

function getSelectedFeatures() {"use strict";

	var Page = $Page, property = Page.getPageProperties(), sl = Page.getCheckBox().getSelections(), i, fids = property.fids;

	for ( i = 0; i < sl.length; i++) {
		fids.push(sl[i].data.feature_id);
	}
}

function renderSource(value, metadata, record, rowIndex, colIndex, store) {
	metadata.tdAttr = 'data-qtip="' + value + '" data-qclass="x-tip"';
	switch (record.data.source) {
		case "ARDB":
			return Ext.String.format('{0}', value);
			break;
		case "CARD":
			return Ext.String.format('{0}', value);
			break;
		case "DrugBank":
			return Ext.String.format('{0}', value);
			break;
		case "TDD":
			return Ext.String.format('{0}', value);
			break;
		case "Human":
			return Ext.String.format('{0}', value);
			break;
		case "PATRIC_VF":
			return Ext.String.format('{0}', value);
			break;
		case "VFDB":
			return Ext.String.format('{0}', value);
			break;
		case "Victors":
			return Ext.String.format('{0}', value);
			break;
		default:
			return value;
	}
}
function renderSourceId(value, metadata, record, rowIndex, colIndex, store) {
	metadata.tdAttr = 'data-qtip="' + value + '" data-qclass="x-tip"';
	switch (record.data.source) {
		case "ARDB":
			return Ext.String.format('{0}', value);
			break;
		case "DrugBank":
			return Ext.String.format('{0}', value);
			break;
		case "TDD":
			return Ext.String.format('{0}', value);
			break;
		case "Human":
			return Ext.String.format('{0}', value);
			break;
		case "PATRIC_VF":
			return Ext.String.format('{0}', value);
			break;
		case "VFDB":
			return Ext.String.format('{0}', value);
			break;
		case "Victors":
			return Ext.String.format('{0}', value);
			break;
		default:
			return value;
	}
}

//Download File
//BEGIN

function DownloadFile(type) {"use strict";

	var Page = $Page, property = Page.getPageProperties(), hash = property.hash, form = Ext.getDom("fTableForm"), name = property.name, tree = property.tree;

	if (isOverDownloadLimit()) {
		return false;
	}
	if (tree.getSelectedTerms()["Keyword"] == null) {
		tree.selectedTerm["Keyword"] = Ext.getDom("keyword").value;
	}

	// form.action = "/patric-searches-and-tools/jsp/grid_download_handler.jsp";
	form.action = "/portal/portal/patric/SpecialtyGeneSearch/SpecialtyGeneSearchWindow?action=b&cacheability=PAGE&need=download";
	//form.download_keyword.value = constructKeyword(tree.getSelectedTerms(), name);
	form.pk.value = hash.key;
	form.fileformat.value = arguments[0];
	form.target = "";
	getHashFieldsToDownload(form);

	var grid = Page.getGrid();
	var sort = [];
	sort.push(getSortersInText(grid.store));
	form.sort.value = JSON.stringify(sort);
	form.submit();
}
<|endoftext|>


<commit_before>'use strict';

// Organizations controller
angular.module('organizations').controller('OrganizationsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Organizations', 'PlantQuery', 'FormlyForms', 'Permissions', 'Plants', 'FoundationApi',
	function($scope, $stateParams, $location, Authentication, Organizations, PlantQuery, FormlyForms, Permissions, Plants, FoundationApi) {
		$scope.authentication = Authentication;

    // ensure user has an organization
    // var user = $scope.authentication.user;
    // if (!user.organization) {
    //   $location.path('/organizations/create')
    // };

    // set dates in increments of 2 weeks
    var date = new Date();
    var dates = {
      now: date.setDate(date.getDate() + 0),
      twoWeeks: date.setDate(date.getDate() + 14),
      fourWeeks: date.setDate(date.getDate() + 14),
      sixWeeks: date.setDate(date.getDate() + 14),
      eightWeeks: date.setDate(date.getDate() + 14),
    }

    $scope.dates = dates;

    // set current user permissions
    Permissions.userPermissions($scope.authentication.user, $stateParams.organizationId, function(permission){
      $scope.userPermission = permission;
    });

    // set organization plants
    PlantQuery.findPlants($stateParams.organizationId, function(orgPlants){
      $scope.plantsGrid = {};
      var plants = orgPlants;
      $scope.plantsGrid.data = plants;
    });

    $scope.newAvailability = {
        date: '',
        quantity: '',
    };

    $scope.formUpdateAvailability = FormlyForms.updateAvailability();

    // register orgData model
		$scope.orgObj = {
			type: '',
			name: '',
			description: '',
      owner: '',
      members: [],
      mailingList: '',
      contact: {
      	phone: 0,
      	email: '',
      	website: '',
      	address: {
      		street: '',
      		city: '',
      		state: '',
      		zip: 0
      	}
      }
		}

    // organization form from formly service
		$scope.formCreateOrg = FormlyForms.createOrganization($scope.orgObj);

    // Create new Organization
    $scope.create = function() {
      // Get user object
      var user = $scope.authentication.user;
      // Create new Organization object
      var organization = new Organizations($scope.orgObj);

      // set org type to user role
      if (user.role !== 'admin') {
        organization.type === user.role;
      } else {
        $scope.error = "admin can't make an organization"
      }
      // set org members array
      organization.members = [];
      // set owner to creating user
      organization.owner = user._id;
      // add user as member
      organization.members.push({
        memberId: user._id,
        memberPermission: 'admin'
      });
      // Redirect after save
      organization.$save(function(response) {
        // redirect to organization home page
        $location.path('organizations/' + response._id);
        // Clear form fields
        $scope.name = '';
      }, function(errorResponse) {
        $scope.error = errorResponse.data.message;
      });
    };

		// Remove existing Organization
		$scope.remove = function(organization) {
			if ( organization ) {
				organization.$remove();

				for (var i in $scope.organizations) {
					if ($scope.organizations [i] === organization) {
						$scope.organizations.splice(i, 1);
					}
				}
			} else {
				$scope.organization.$remove(function() {
					$location.path('organizations');
				});
			}
		};

		// Update existing Organization
		$scope.update = function() {
			var organization = $scope.organization;

			organization.$update(function() {
				$location.path('organizations/' + organization._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of Organizations
		$scope.find = function() {
      $scope.organizations = Organizations.query();
		};

		// Find existing Organization
		$scope.findOne = function() {
			$scope.organization = Organizations.get({
				organizationId: $stateParams.organizationId
			});
		};

   // invoke functions for setup
   // $scope.userOrganization();

    $scope.updateAvailability = function(plant) {
      $scope.plant = plant;
    }

    $scope.addAvailability = function(plant) {
      var availability = {
        date: $scope.newAvailability.date,
        quantity: $scope.newAvailability.quantity
      }
      $scope.plant.unitAvailability.push(availability);
      Plants.update({
        plantId: plant._id
      }, plant, function (res) {
          $scope.plant = res;
          $scope.message = plant.commonName + ', successfully updated'
          $scope.newAvailability = {
            date: '',
            quantity: ''
          };
        }
      );
    }

    $scope.removeAvailability = function(availability, plant) {
      $scope.plant.unitAvailability.splice(availability.$index, 1);
      Plants.update({
        plantId: plant._id
      }, plant, function (res) {
          $scope.plant = res;
          $scope.message = plant.commonName + ', successfully updated'
        }
      );
    }

    // Update existing Plant
    $scope.update = function(plant) {
      // close modal
      FoundationApi.closeActiveElements();
      Plants.update({
        plantId: plant._id
      }, plant, function () {
          $scope.message = plant.commonName + ', successfully updated'
        }
      );
    };

    $scope.remove = function(plant) {
      Plants.delete({
        plantId: plant._id
      }, plant, function(){
        // remove object from $scope data
        $scope.message = plant.commonName + ', successfully deleted'
      })
    }
  }
]);<commit_msg>availability functions<commit_after>'use strict';

// Organizations controller
angular.module('organizations').controller('OrganizationsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Organizations', 'PlantQuery', 'FormlyForms', 'Permissions', 'Plants', 'FoundationApi',
	function($scope, $stateParams, $location, Authentication, Organizations, PlantQuery, FormlyForms, Permissions, Plants, FoundationApi) {
		$scope.authentication = Authentication;

    // set current user permissions
    Permissions.userPermissions($scope.authentication.user, $stateParams.organizationId, function(permission){
      $scope.userPermission = permission;
    });

    // set organization plants
    PlantQuery.findPlants($stateParams.organizationId, function(orgPlants){
      $scope.plantsGrid = {};
      var plants = orgPlants;
      $scope.plantsGrid.data = plants;
    });

    $scope.newAvailability = {
        date: '',
        quantity: '',
    };

    $scope.formUpdateAvailability = FormlyForms.updateAvailability();

    // register orgData model
		$scope.orgObj = {
			type: '',
			name: '',
			description: '',
      owner: '',
      members: [],
      mailingList: '',
      contact: {
      	phone: 0,
      	email: '',
      	website: '',
      	address: {
      		street: '',
      		city: '',
      		state: '',
      		zip: 0
      	}
      }
		}

    // organization form from formly service
		$scope.formCreateOrg = FormlyForms.createOrganization($scope.orgObj);

    // Create new Organization
    $scope.create = function() {
      // Get user object
      var user = $scope.authentication.user;
      // Create new Organization object
      var organization = new Organizations($scope.orgObj);

      // set org type to user role
      if (user.role !== 'admin') {
        organization.type === user.role;
      } else {
        $scope.error = "admin can't make an organization"
      }
      // set org members array
      organization.members = [];
      // set owner to creating user
      organization.owner = user._id;
      // add user as member
      organization.members.push({
        memberId: user._id,
        memberPermission: 'admin'
      });
      // Redirect after save
      organization.$save(function(response) {
        // redirect to organization home page
        $location.path('organizations/' + response._id);
        // Clear form fields
        $scope.name = '';
      }, function(errorResponse) {
        $scope.error = errorResponse.data.message;
      });
    };

		// Remove existing Organization
		$scope.remove = function(organization) {
			if ( organization ) {
				organization.$remove();

				for (var i in $scope.organizations) {
					if ($scope.organizations [i] === organization) {
						$scope.organizations.splice(i, 1);
					}
				}
			} else {
				$scope.organization.$remove(function() {
					$location.path('organizations');
				});
			}
		};

		// Update existing Organization
		$scope.update = function() {
			var organization = $scope.organization;

			organization.$update(function() {
				$location.path('organizations/' + organization._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of Organizations
		$scope.find = function() {
      $scope.organizations = Organizations.query();
		};

		// Find existing Organization
		$scope.findOne = function() {
			$scope.organization = Organizations.get({
				organizationId: $stateParams.organizationId
			});
		};

    // Update existing Plant
    $scope.update = function(plant) {
      // close modal
      FoundationApi.closeActiveElements();
      Plants.update({
        plantId: plant._id
      }, plant, function () {
          $scope.message = plant.commonName + ', successfully updated'
        }
      );
    };

    $scope.remove = function(plant) {
      $scope.plantsGrid.data.splice(plant.$index, 1);
      Plants.delete({
        plantId: plant._id
      }, plant, function(){
        // remove object from $scope data
        $scope.message = plant.commonName + ', successfully deleted'
      })
    }

    // Availability Functions

    $scope.updateAvailability = function(plant) {
      $scope.plant = plant;
    }

    $scope.addAvailability = function(plant) {
      var availability = {
        date: $scope.newAvailability.date,
        quantity: $scope.newAvailability.quantity
      }
      $scope.plant.unitAvailability.push(availability);
      Plants.update({
        plantId: plant._id
      }, plant, function (res) {
          $scope.plant = res;
          $scope.message = plant.commonName + ', successfully updated'
          $scope.newAvailability = {
            date: '',
            quantity: ''
          };
        }
      );
    }

    $scope.removeAvailability = function(availability, plant) {
      $scope.plant.unitAvailability.splice(availability.$index, 1);
      Plants.update({
        plantId: plant._id
      }, plant, function (res) {
          $scope.plant = res;
          $scope.message = plant.commonName + ', successfully updated'
        }
      );
    }

  }
]);<|endoftext|>


<commit_before>'use strict';

// Schoolclasses controller
angular.module('schoolclasses').controller('SchoolclassesController', ['$scope', '$state', '$modal', '$stateParams', '$location', 'Authentication', 'Schoolclasses', 'Schools', 'Courses', 'CoursesService',
    function ($scope, $state, $modal, $stateParams, $location, Authentication, Schoolclasses, Schools, Courses, CoursesService) {

        $scope.authentication = Authentication;

        $scope.addCourseForStudent = function (studentId, courseId) {
            Courses.query({
                userId: studentId
            }).$promise.then(function (studentCourses) {
                    var setVisible = false;
                    studentCourses.forEach(function (studentCourse) {

                        // if the course existed, then just set it visible
                        if (studentCourse.supervised && studentCourse.master.toString() === courseId) {
                            studentCourse.visible = true;
                            studentCourse.$update();
                            setVisible = true;
                        }
                    });
                    if (!setVisible) {
                        var res = CoursesService.copyCourseFor(studentId);
                        res.get({courseId: courseId});

                    }
                });
        };

        $scope.addCourseToClass = function (course) {

            if ($scope.schoolclass.courses.indexOf(course._id) === -1) {
                $scope.schoolclass.courses.push(course._id);
                $scope.schoolclass.$update();

                $scope.schoolclass.students.forEach(function (studentId) {

                    $scope.addCourseForStudent(studentId, course._id);

                });
            }
        };

        $scope.removeCourseFromClass = function (course) {
            for (var i in $scope.schoolclass.courses) {
                if ($scope.schoolclass.courses[i] === course) {
                    $scope.schoolclass.courses.splice(i, 1);
                }
            }

            $scope.schoolclass.$update();

            $scope.schoolclass.students.forEach(function (studentId) {

                Courses.query({
                    userId: studentId
                }).$promise.then(function (studentCourses) {
                        studentCourses.forEach(function (studentCourse) {
                            if (studentCourse.supervised && studentCourse.master.toString() === course.toString()) {
                                studentCourse.visible = false;
                                studentCourse.$update();
                            }
                        });
                    });
            }, this);

        };

        $scope.areYouSureToDeleteClass = function (schoolclass) {

            $scope.schoolclass = schoolclass;
            $modal.open({
                templateUrl: 'areYouSureToDeleteClass.html',
                controller: 'DeleteClassModalController',
                resolve: {

                    schoolclass: function () {
                        return $scope.schoolclass;
                    }
                }
            });

        };

        // Create new Schoolclass
        $scope.create = function () {
            // Create new Schoolclass object
            var schoolclass = new Schoolclasses({
                name: this.name
            });

            // Redirect after save
            schoolclass.$save(function (response) {
                $location.path('schoolclasses/' + response._id);
            }, function (errorResponse) {
                $scope.error = errorResponse.data.message;
            });

            // Clear form fields
            this.name = '';
        };

        // Remove existing Schoolclass
        $scope.remove = function (schoolclass) {
            if (schoolclass) {
                schoolclass.$remove();

                for (var i in $scope.schoolclasses) {
                    if ($scope.schoolclasses [i] === schoolclass) {
                        $scope.schoolclasses.splice(i, 1);
                    }
                }
            } else {
                $scope.schoolclass.$remove(function () {
                    $location.path('schoolclasses');
                });
            }
        };

        // Update existing Schoolclass
        $scope.update = function () {
            var schoolclass = $scope.schoolclass;

            schoolclass.$update(function () {
                $location.path('schoolclasses/' + schoolclass._id);
            }, function (errorResponse) {
                $scope.error = errorResponse.data.message;
            });
        };

        // Find a list of Schoolclasses
        $scope.find = function () {
            $scope.schoolclasses = Schoolclasses.query();
        };

        // Find existing Schoolclass
        $scope.findOne = function () {

            Schoolclasses.get({
                schoolclassId: $stateParams.schoolclassId
            }, function (schoolclass) {
                $scope.schoolclass = schoolclass;
                $scope.school = Schools.get({
                    schoolId: $scope.schoolclass.school
                });
                // remove missing courses
                // this shouldn't happen, but while I am developing
                // I like it to be self-fixing.
                schoolclass.courses.forEach(function (courseId) {
                    Courses.query({
                        _id: courseId
                    }).$promise.then(function (courses) {
                            if (courses.length === 0) {
                                console.log('Course doesnt exist. Removing from schoolclass');
                                for (var i in schoolclass.courses) {
                                    if (schoolclass.courses[i] === courseId) {
                                        schoolclass.courses.splice(i, 1);
                                    }
                                }
                                schoolclass.$update();
                            }

                        });
                });

            });
        };

        $scope.findById = function (id) {

            $scope.schoolclass = Schoolclasses.get({
                schoolclassId: id
            });
        };

        $scope.findForUser = function () {

            Schoolclasses.query({
                teachers: Authentication.user._id

            }, function (schoolclasses) {
                $scope.schoolclasses = schoolclasses;
            });
        };

        $scope.findForCourse = function (courseId) {

            $scope.schoolclass = Schoolclasses.get({
                courseId: courseId
            });
        };

        // Find list for current user
        $scope.findForTeacher = function (teacherId) {
            $scope.schoolclasses = Schoolclasses.query({
                teacher: teacherId
            }, function (schoolclasses) {
//                    console.log(schoolclasses);
//                    if (schoolclasses.length === 1) {
//                        $location.path('schools/'+schools[0]._id+'/edit');
//                    }
            });
        };

        $scope.editClassPopup = function (size) {
            $modal.open({
                templateUrl: 'editClass.html',
                controller: 'EditClassController',
                size: size,
                resolve: {
                    schoolclass: function () {
                        return $scope.schoolclass;
                    }
                }
            });

        };

        $scope.removeStudentFromClass = function (student) {
            for (var i in $scope.schoolclass.students) {
                if ($scope.schoolclass.students[i] === student) {
                    $scope.schoolclass.students.splice(i, 1);
                }
            }

            console.log($scope.schoolclass.courses);
            Courses.query({
                userId: student
            }, function(courses) {
                courses.forEach(function(course) {
                    console.log(course);
                }, this);

            });

//            $scope.schoolclass.$update(function (res) {
//
//            }, function (err) {
////                console.log(err);
//            });
        };

        $scope.addStudentToClass = function (student) {

            if ($scope.schoolclass.students.indexOf(student._id) === -1) {
                $scope.schoolclass.students.push(student._id);
            }

            $scope.schoolclass.$update(function () {

                $scope.schoolclass.courses.forEach(function(courseId) {
                    $scope.addCourseForStudent(student._id, courseId);
                });

                //$location.path('schoolclasses/' + schoolclass._id);
            }, function (errorResponse) {
                $scope.error = errorResponse.data.message;
            });
//            $scope.schoolclass.$update();
        };

        $scope.addTeacherToClass = function (teacher) {
            if ($scope.schoolclass.teachers.indexOf(teacher._id) === -1) {
                $scope.schoolclass.teachers.push(teacher._id);
            }

            $scope.schoolclass.$update(function () {
                if (teacher.schoolclasses.indexOf($scope.schoolclass._id) === -1) {
                    teacher.schoolclasses.push($scope.schoolclass._id);
                    teacher.$update(function () {
                        $state.go($state.$current, null, {reload: true});
                    });
                }
            }, function (errorResponse) {
                $scope.error = errorResponse.data.message;
            });
        };

        $scope.removeTeacherFromClass = function (teacher) {
            for (var i in $scope.schoolclass.teachers) {
                if ($scope.schoolclass.teachers[i] === teacher._id) {
                    $scope.schoolclass.teachers.splice(i, 1);
                }
            }

            $scope.schoolclass.$update(function (res) {
                for (var i in teacher.schoolclasses) {
                    if (teacher.schoolclasses[i] === $scope.schoolclass._id) {
                        teacher.schoolclasses.splice(i, 1);
                    }
                }
                teacher.$update(function (t) {
                    console.log(t.schoolclasses);
                });
            }, function (err) {
//                console.log(err);
            });
        };

    }
]);<commit_msg>removing student from class frees up all the courses he had in class.<commit_after>'use strict';

// Schoolclasses controller
angular.module('schoolclasses').controller('SchoolclassesController', ['$scope', '$state', '$modal', '$stateParams', '$location', 'Authentication', 'Schoolclasses', 'Schools', 'Courses', 'CoursesService',
    function ($scope, $state, $modal, $stateParams, $location, Authentication, Schoolclasses, Schools, Courses, CoursesService) {

        $scope.authentication = Authentication;

        $scope.addCourseForStudent = function (studentId, courseId) {
            Courses.query({
                userId: studentId
            }).$promise.then(function (studentCourses) {
                    var setVisible = false;
                    studentCourses.forEach(function (studentCourse) {

                        // if the course existed, then just set it visible
                        if (studentCourse.supervised && studentCourse.master.toString() === courseId) {
                            studentCourse.visible = true;
                            studentCourse.$update();
                            setVisible = true;
                        }
                    });
                    if (!setVisible) {
                        var res = CoursesService.copyCourseFor(studentId);
                        res.get({courseId: courseId});

                    }
                });
        };

        $scope.addCourseToClass = function (course) {

            if ($scope.schoolclass.courses.indexOf(course._id) === -1) {
                $scope.schoolclass.courses.push(course._id);
                $scope.schoolclass.$update();

                $scope.schoolclass.students.forEach(function (studentId) {

                    $scope.addCourseForStudent(studentId, course._id);

                });
            }
        };

        $scope.removeCourseFromClass = function (course) {
            for (var i in $scope.schoolclass.courses) {
                if ($scope.schoolclass.courses[i] === course) {
                    $scope.schoolclass.courses.splice(i, 1);
                }
            }

            $scope.schoolclass.$update();

            $scope.schoolclass.students.forEach(function (studentId) {

                Courses.query({
                    userId: studentId
                }).$promise.then(function (studentCourses) {
                        studentCourses.forEach(function (studentCourse) {
                            if (studentCourse.supervised && studentCourse.master.toString() === course.toString()) {
                                studentCourse.visible = false;
                                studentCourse.$update();
                            }
                        });
                    });
            }, this);

        };

        $scope.areYouSureToDeleteClass = function (schoolclass) {

            $scope.schoolclass = schoolclass;
            $modal.open({
                templateUrl: 'areYouSureToDeleteClass.html',
                controller: 'DeleteClassModalController',
                resolve: {

                    schoolclass: function () {
                        return $scope.schoolclass;
                    }
                }
            });

        };

        // Create new Schoolclass
        $scope.create = function () {
            // Create new Schoolclass object
            var schoolclass = new Schoolclasses({
                name: this.name
            });

            // Redirect after save
            schoolclass.$save(function (response) {
                $location.path('schoolclasses/' + response._id);
            }, function (errorResponse) {
                $scope.error = errorResponse.data.message;
            });

            // Clear form fields
            this.name = '';
        };

        // Remove existing Schoolclass
        $scope.remove = function (schoolclass) {
            if (schoolclass) {
                schoolclass.$remove();

                for (var i in $scope.schoolclasses) {
                    if ($scope.schoolclasses [i] === schoolclass) {
                        $scope.schoolclasses.splice(i, 1);
                    }
                }
            } else {
                $scope.schoolclass.$remove(function () {
                    $location.path('schoolclasses');
                });
            }
        };

        // Update existing Schoolclass
        $scope.update = function () {
            var schoolclass = $scope.schoolclass;

            schoolclass.$update(function () {
                $location.path('schoolclasses/' + schoolclass._id);
            }, function (errorResponse) {
                $scope.error = errorResponse.data.message;
            });
        };

        // Find a list of Schoolclasses
        $scope.find = function () {
            $scope.schoolclasses = Schoolclasses.query();
        };

        // Find existing Schoolclass
        $scope.findOne = function () {

            Schoolclasses.get({
                schoolclassId: $stateParams.schoolclassId
            }, function (schoolclass) {
                $scope.schoolclass = schoolclass;
                $scope.school = Schools.get({
                    schoolId: $scope.schoolclass.school
                });
                // remove missing courses
                // this shouldn't happen, but while I am developing
                // I like it to be self-fixing.
                schoolclass.courses.forEach(function (courseId) {
                    Courses.query({
                        _id: courseId
                    }).$promise.then(function (courses) {
                            if (courses.length === 0) {
                                console.log('Course doesnt exist. Removing from schoolclass');
                                for (var i in schoolclass.courses) {
                                    if (schoolclass.courses[i] === courseId) {
                                        schoolclass.courses.splice(i, 1);
                                    }
                                }
                                schoolclass.$update();
                            }

                        });
                });

            });
        };

        $scope.findById = function (id) {

            $scope.schoolclass = Schoolclasses.get({
                schoolclassId: id
            });
        };

        $scope.findForUser = function () {

            Schoolclasses.query({
                teachers: Authentication.user._id

            }, function (schoolclasses) {
                $scope.schoolclasses = schoolclasses;
            });
        };

        $scope.findForCourse = function (courseId) {

            $scope.schoolclass = Schoolclasses.get({
                courseId: courseId
            });
        };

        // Find list for current user
        $scope.findForTeacher = function (teacherId) {
            $scope.schoolclasses = Schoolclasses.query({
                teacher: teacherId
            }, function (schoolclasses) {
//                    console.log(schoolclasses);
//                    if (schoolclasses.length === 1) {
//                        $location.path('schools/'+schools[0]._id+'/edit');
//                    }
            });
        };

        $scope.editClassPopup = function (size) {
            $modal.open({
                templateUrl: 'editClass.html',
                controller: 'EditClassController',
                size: size,
                resolve: {
                    schoolclass: function () {
                        return $scope.schoolclass;
                    }
                }
            });

        };

        $scope.removeStudentFromClass = function (student) {
            for (var i in $scope.schoolclass.students) {
                if ($scope.schoolclass.students[i] === student) {
                    $scope.schoolclass.students.splice(i, 1);
                }
            }

            console.log($scope.schoolclass.courses);
            Courses.query({
                userId: student
            }, function(courses) {
                courses.forEach(function(course) {
                    if ($scope.schoolclass.courses.indexOf(course.master) > -1) {
                        course.visble = true;
                        course.supervised = false;
                        course.$update();
                    }
                }, this);

            });

            $scope.schoolclass.$update();
        };

        $scope.addStudentToClass = function (student) {

            if ($scope.schoolclass.students.indexOf(student._id) === -1) {
                $scope.schoolclass.students.push(student._id);
            }

            $scope.schoolclass.$update(function () {

                $scope.schoolclass.courses.forEach(function(courseId) {
                    $scope.addCourseForStudent(student._id, courseId);
                });

                //$location.path('schoolclasses/' + schoolclass._id);
            }, function (errorResponse) {
                $scope.error = errorResponse.data.message;
            });
//            $scope.schoolclass.$update();
        };

        $scope.addTeacherToClass = function (teacher) {
            if ($scope.schoolclass.teachers.indexOf(teacher._id) === -1) {
                $scope.schoolclass.teachers.push(teacher._id);
            }

            $scope.schoolclass.$update(function () {
                if (teacher.schoolclasses.indexOf($scope.schoolclass._id) === -1) {
                    teacher.schoolclasses.push($scope.schoolclass._id);
                    teacher.$update(function () {
                        $state.go($state.$current, null, {reload: true});
                    });
                }
            }, function (errorResponse) {
                $scope.error = errorResponse.data.message;
            });
        };

        $scope.removeTeacherFromClass = function (teacher) {
            for (var i in $scope.schoolclass.teachers) {
                if ($scope.schoolclass.teachers[i] === teacher._id) {
                    $scope.schoolclass.teachers.splice(i, 1);
                }
            }

            $scope.schoolclass.$update(function (res) {
                for (var i in teacher.schoolclasses) {
                    if (teacher.schoolclasses[i] === $scope.schoolclass._id) {
                        teacher.schoolclasses.splice(i, 1);
                    }
                }
                teacher.$update(function (t) {
                    console.log(t.schoolclasses);
                });
            }, function (err) {
//                console.log(err);
            });
        };

    }
]);<|endoftext|>


<commit_before>/**
 * This <server-gardu-reporter> project created by :
 * Name         : syafiq
 * Date / Time  : 28 June 2017, 11:03 PM.
 * Email        : syafiq.rezpector@gmail.com
 * Github       : syafiqq
 */

(function ($)
{
    $(function ()
    {
        $('input').iCheck({
            checkboxClass: 'icheckbox_square-blue',
            radioClass: 'iradio_square-blue',
            increaseArea: '20%' // optional
        });
    });
    /*
     * Run right away
     * */
})(jQuery);
<commit_msg>Fix login member script<commit_after>/**
 * This <server-gardu-reporter> project created by :
 * Name         : syafiq
 * Date / Time  : 28 June 2017, 11:03 PM.
 * Email        : syafiq.rezpector@gmail.com
 * Github       : syafiqq
 */

(function ($) {
    $(function () {
        NProgress.configure({
            showSpinner: false,
            template: '

'
        });

        $('form#login').on('submit', function (event) {
            event.preventDefault();
            var form = $(this);

            var input = form.serializeObject();

            input['remember_me'] = $(form).find('input:checkbox[name=remember_me]').prop('checked');
            if ((input['remember_me'] === undefined) || (input['remember_me'] === null))
            {
                input['remember_me'] = 0;
            }
            else
            {
                input['remember_me'] = input['remember_me'] ? 1 : 0;
            }

            NProgress.start();
            $.post(
                form.attr('action'),
                input,
                null,
                'json')
                .done(function (response) {
                    var status = ['danger', 'info', 'warning', 'success'];
                    var type   = ['login', 'validation'];
                    if (response['data'] !== undefined)
                    {
                        if (response['data']['message'] !== undefined)
                        {
                            for (var i = -1, is = type.length; ++i < is;)
                            {
                                if (response['data']['message'][type[i]] !== undefined)
                                {
                                    for (var j = -1, js = status.length; ++j < js;)
                                    {
                                        if (response['data']['message'][type[i]][status[j]] !== undefined)
                                        {
                                            var template = '
'
                                                + '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>'
                                                + '
';
                                            for (var k = -1, ks = response['data']['message'][type[i]][status[j]].length; ++k < ks;)
                                            {
                                                template += '
' + response['data']['message'][type[i]][status[j]][k] + '
'
                                            }
                                            template += '
'
                                                + '
';
                                            $("div#form-message-container").empty().append(template);
                                        }
                                    }
                                }
                            }
                        }

                        if (response['data']['redirect'] !== undefined)
                        {
                            location.href = response['data']['redirect'];
                        }

                        if (response['data']['csrf'] !== undefined)
                        {
                            $(form).find('input:hidden[name=' + response['data']['csrf']['name'] + ']').val(response['data']['csrf']['hash']);
                        }
                    }
                })
                .fail(function () {
                })
                .always(function () {
                    NProgress.done();
                });
        });

        $('input').iCheck({
            checkboxClass: 'icheckbox_square-blue',
            radioClass: 'iradio_square-blue',
            increaseArea: '20%' // optional
        });

        if ((sessionFlashdata !== undefined) && (sessionFlashdata !== null))
        {
            for (var i = -1, is = sessionFlashdata.length; ++i < is;)
            {
                $.notify({
                    message: sessionFlashdata[i]
                }, {
                    type: 'info'
                });
            }
        }
    });
    /*
     * Run right away
     * */
})(jQuery);
<|endoftext|>


<commit_before>define([
    'jquery',
    'oroui/js/app/views/base/view'
], function($, BaseView) {
    'use strict';

    var CalendarEventAllDayView;
    CalendarEventAllDayView = BaseView.extend({

        /**
         * Options
         */
        options: {},

        autoRender: true,

        events: {
            'change input[name$="[allDay]"]': 'onAllDayChange'
        },

        startAtTimeElement: null,
        oldStartAtValue: null,

        endAtTimeElement: null,
        oldEndAtValue: null,

        render: function() {
            var self = this;
            var renderDeferred = this.renderDeferred = $.Deferred();
            this.initLayout().done(function() {
                self.handleLayoutInit();
                renderDeferred.resolve();
            });
        },

        handleLayoutInit: function() {
            this.handleAllDayEventFlag($('input[name$="[allDay]"]'), 0);
        },

        onAllDayChange: function(event) {
            this.handleAllDayEventFlag($(event.target), 200);
        },

        handleAllDayEventFlag: function(allDayEventElement, animationDuration) {
            if (!this.startAtTimeElement) {
                var startAtElements = this.$('input[name$="[start]"]').closest('.control-group-datetime');
                this.startAtTimeElement = startAtElements.find('.timepicker-input');
            }
            if (!this.endAtTimeElement) {
                var endAtElements = this.$('input[name$="[end]"]').closest('.control-group-datetime');
                this.endAtTimeElement = endAtElements.find('.timepicker-input');
            }
            if (allDayEventElement.prop('checked')) {
                this.oldStartAtValue = this.startAtTimeElement.timepicker('getTime');
                this.oldEndAtValue = this.endAtTimeElement.timepicker('getTime');

                var resetTimeDelegate = function() {
                    $(this).timepicker('setTime', 0).trigger('change');
                };
                this.startAtTimeElement.hide(animationDuration, resetTimeDelegate);
                this.endAtTimeElement.hide(animationDuration, resetTimeDelegate);
            } else {
                if (this.oldStartAtValue) {
                    this.startAtTimeElement.timepicker('setTime', this.oldStartAtValue);
                }
                if (this.oldEndAtValue) {
                    this.endAtTimeElement.timepicker('setTime', this.oldEndAtValue);
                }

                this.startAtTimeElement.show(animationDuration);
                this.endAtTimeElement.show(animationDuration);
            }
        }
    });

    return CalendarEventAllDayView;
});
<commit_msg>BAP-11099: Incorrect sync all day events between OroCRM and MS Outlook - fix review notes<commit_after>define([
    'jquery',
    'oroui/js/app/views/base/view'
], function($, BaseView) {
    'use strict';

    var CalendarEventAllDayView;
    CalendarEventAllDayView = BaseView.extend({

        /**
         * Options
         */
        options: {},

        autoRender: true,

        events: {
            'change input[name$="[allDay]"]': 'onAllDayChange'
        },

        startAtTimeElement: null,
        oldStartAtValue: null,

        endAtTimeElement: null,
        oldEndAtValue: null,

        render: function() {
            var self = this;
            var renderDeferred = this.renderDeferred = $.Deferred();
            this.initLayout().done(function() {
                self.handleLayoutInit();
                renderDeferred.resolve();
            });
        },

        handleLayoutInit: function() {
            this.handleAllDayEventFlag(this.$('input[name$="[allDay]"]'), 0);
        },

        onAllDayChange: function(event) {
            this.handleAllDayEventFlag($(event.target), 200);
        },

        handleAllDayEventFlag: function(allDayEventElement, animationDuration) {
            if (!this.startAtTimeElement) {
                var startAtElements = this.$('input[name$="[start]"]').closest('.control-group-datetime');
                this.startAtTimeElement = startAtElements.find('.timepicker-input');
            }
            if (!this.endAtTimeElement) {
                var endAtElements = this.$('input[name$="[end]"]').closest('.control-group-datetime');
                this.endAtTimeElement = endAtElements.find('.timepicker-input');
            }
            if (allDayEventElement.prop('checked')) {
                this.oldStartAtValue = this.startAtTimeElement.timepicker('getTime');
                this.oldEndAtValue = this.endAtTimeElement.timepicker('getTime');

                var resetTimeDelegate = function() {
                    $(this).timepicker('setTime', 0).trigger('change');
                };
                this.startAtTimeElement.hide(animationDuration, resetTimeDelegate);
                this.endAtTimeElement.hide(animationDuration, resetTimeDelegate);
            } else {
                if (this.oldStartAtValue) {
                    this.startAtTimeElement.timepicker('setTime', this.oldStartAtValue);
                }
                if (this.oldEndAtValue) {
                    this.endAtTimeElement.timepicker('setTime', this.oldEndAtValue);
                }

                this.startAtTimeElement.show(animationDuration);
                this.endAtTimeElement.show(animationDuration);
            }
        }
    });

    return CalendarEventAllDayView;
});
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { autobind } from 'core-decorators';
import { compose, graphql, gql } from 'react-apollo';
import { Button, Intent, Spinner, EditableText } from '@blueprintjs/core';
import { saveState } from '../../../actions/stateActions';
import MarkdownEditor from '../../../../../lib/react/components/MarkdownEditor';
import NotificationToaster from '../NotificationToaster';

const QueryGetArticle = gql`
query GetArticle($category:String!, $articleId:ID!){
	getArticle(category:$category, articleId:$articleId){
		title
		content
		modified
		modifiedBy{
			username
		}
	}
}`;

const QueryGetArticleOptions = {
	name: 'QueryGetArticle',
	options: (props) => {
		return {
			variables: {
				category: 'instructions',
				articleId: props.article._id
			}
		}
	}
}

const MutationSetArticleTitle = gql`
mutation SetArticleTitle($articleId:ID!,$category:String!, $newTitle:String!){
	setArticleTitle(articleId:$articleId, category:$category, newTitle:$newTitle){
		ok
	}
}`;

@compose(
	graphql(QueryGetArticle, QueryGetArticleOptions),
	graphql(MutationSetArticleTitle, { name: 'MutationSetArticleTitle' })
)
@connect()
@autobind
class InstructionArticleProfile extends React.Component {
	static propTypes = {
		article: PropTypes.shape({
			_id: PropTypes.string.isRequired,
			title: PropTypes.string.isRequired
		}).isRequired,
		closeProfile: PropTypes.func.isRequired
	}

	state = {
		saving: false,
		titleText: this.props.article.title,
		content: null
	}

	componentDidMount() {
		this._mounted = true;
	}

	componentWillUnmount() {
		this._mounted = false;
	}

	closeProfile() {
		this.props.closeProfile();
	}

	editTitle(value) {
		this.setState({ titleText: value });
	}

	confirmTitle(value) {
		if (value.length < 1) {
			this.setState({ titleText: this.props.article.title });
			NotificationToaster.show({
				intent: Intent.DANGER,
				message: 'Title cannot be empty.'
			});
		}
		else {
			this._saveTitle();
		}
	}

	componentDidUpdate() {
		if (!this.state.content && this.props.QueryGetArticle.getArticle) {
			this.setState({content: this.props.QueryGetArticle.getArticle.content});
		}
	}

	editContent(event) {
		this.setState({content: event.target.value});
	}

	async _saveTitle() {
		try {
			this.setState({ saving: true });
			await this.props.MutationSetArticleTitle({
				variables: {
					articleId: this.props.article._id,
					category: 'instructions',
					newTitle: this.state.titleText
				}
			});

			await this.props.QueryGetArticle.refetch();
			this.props.dispatch(saveState());
			if (this._mounted) this.setState({saving: false});
		}
		catch (err) {
			NotificationToaster.show({
				intent: Intent.DANGER,
				message: err.toString()
			});
			if (this._mounted) this.setState({saving: false});
		}
	}

	render() {
		let { loading, getArticle } = this.props.QueryGetArticle;

		return (

				<Button className='pt-minimal' intent={Intent.DANGER} text='Close' onClick={this.closeProfile} style={{float:'right'}}/>
				{loading || this.state.saving ?

						<Spinner className='pt-small'/>

				: null }

					<EditableText value={this.state.titleText} onChange={this.editTitle} onConfirm={this.confirmTitle}/>

				{ loading ? null:
					<MarkdownEditor content={this.state.content || this.props.QueryGetArticle.getArticle.content} onChange={this.editContent}/>
				}

		);
	}
}

export default InstructionArticleProfile;
<commit_msg>[ADD] Add save functionality to InstructionArticleProfile<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { autobind } from 'core-decorators';
import { compose, graphql, gql } from 'react-apollo';
import { Button, Intent, Spinner, EditableText } from '@blueprintjs/core';
import { saveState } from '../../../actions/stateActions';
import MarkdownEditor from '../../../../../lib/react/components/MarkdownEditor';
import NotificationToaster from '../NotificationToaster';

const QueryGetArticle = gql`
query GetArticle($category:String!, $articleId:ID!){
	getArticle(category:$category, articleId:$articleId){
		title
		content
		modified
		modifiedBy{
			username
		}
	}
}`;

const QueryGetArticleOptions = {
	name: 'QueryGetArticle',
	options: (props) => {
		return {
			variables: {
				category: 'instructions',
				articleId: props.article._id
			}
		}
	}
}

const MutationSetArticleTitle = gql`
mutation SetArticleTitle($articleId:ID!,$category:String!, $newTitle:String!){
	setArticleTitle(articleId:$articleId, category:$category, newTitle:$newTitle){
		ok
	}
}`;

const MutationEditArticle = gql`
mutation EditArticle($articleId:ID!,$category:String!, $content:String!){
	editArticle(articleId:$articleId, category:$category, content:$content){
		ok
	}
}`;

@compose(
	graphql(QueryGetArticle, QueryGetArticleOptions),
	graphql(MutationSetArticleTitle, { name: 'MutationSetArticleTitle' }),
	graphql(MutationEditArticle, { name: 'MutationEditArticle' })
)
@connect()
@autobind
class InstructionArticleProfile extends React.Component {
	static propTypes = {
		article: PropTypes.shape({
			_id: PropTypes.string.isRequired,
			title: PropTypes.string.isRequired
		}).isRequired,
		closeProfile: PropTypes.func.isRequired
	}

	state = {
		saving: false,
		modified: false,
		titleText: this.props.article.title,
		content: null
	}

	componentDidMount() {
		this._mounted = true;
	}

	componentWillUnmount() {
		this._mounted = false;
	}

	closeProfile() {
		this.props.closeProfile();
	}

	editTitle(value) {
		this.setState({ titleText: value });
	}

	confirmTitle(value) {
		if (value.length < 1) {
			this.setState({ titleText: this.props.article.title });
			NotificationToaster.show({
				intent: Intent.DANGER,
				message: 'Title cannot be empty.'
			});
		}
		else {
			const options = {
				variables: {
					articleId: this.props.article._id,
					category: 'instructions',
					newTitle: this.state.titleText
				}
			};
			this._save(this.props.MutationSetArticleTitle, options);
		}
	}

	componentDidUpdate() {
		if (!this.state.content && this.props.QueryGetArticle.getArticle) {
			this.setState({content: this.props.QueryGetArticle.getArticle.content});
		}
	}

	editContent(event) {
		this.setState({content: event.target.value, modified: true});
	}

	saveContent() {
		this.setState({modified: false});
		const options = {
			variables: {
				articleId: this.props.article._id,
				category: 'instructions',
				content: this.state.content
			}
		};
		this._save(this.props.MutationEditArticle, options);
	}

	async _save(mutation, mutationOptions) {
		try {
			this.setState({saving: true});
			await mutation(mutationOptions);

			await this.props.QueryGetArticle.refetch();
			this.props.dispatch(saveState());
			if (this._mounted) this.setState({saving: false});
		}
		catch (e) {
			NotificationToaster.show({
				intent: Intent.DANGER,
				message: err.toString()
			});
			if (this._mounted) this.setState({saving: false});
		}
	}

	render() {
		let { loading, getArticle } = this.props.QueryGetArticle;

		return (

				<Button className='pt-minimal' intent={Intent.PRIMARY} text='Save' onClick={this.saveContent} style={{float:'right'}} disabled={!this.state.modified}/>
				<Button className='pt-minimal' intent={Intent.DANGER} text='Close' onClick={this.closeProfile} style={{float:'right'}}/>
				{loading || this.state.saving ?

						<Spinner className='pt-small'/>

				: null }

					<EditableText value={this.state.titleText} onChange={this.editTitle} onConfirm={this.confirmTitle}/>

				{ loading ? null:
					<MarkdownEditor content={this.state.content || this.props.QueryGetArticle.getArticle.content} onChange={this.editContent}/>
				}

		);
	}
}

export default InstructionArticleProfile;
<|endoftext|>