<commit_before>let React = require('react-native');
let pages = require('./pagesContent');
let RecordPage = require('./RecordPage');
let {
  StyleSheet,
  Text,
  View,
  Image,
  TouchableHighlight,
} = React;

let styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#084265',
  },
  welcome: {
    color: '#F5FCFF',
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#F5FCFF',
    marginBottom: 5,
    paddingLeft: 15,
    paddingRight: 15,
  },
  actionButton: {
    marginTop: 30,
    paddingLeft: 15,
    paddingRight: 15,
    paddingTop: 10,
    paddingBottom: 10,
    backgroundColor: '#5B99FA',
    borderRadius: 4,
  },
  actionLabel: {
    color: '#fff',
    fontSize: 18,
  },
  pageImage: {
    width: 256,
    height: 256,
  },
});

class FreshSetup extends React.Component {
  _onPressButton() {
    let page, title, props;

    if (pages[this.props.pageId].next) {
      title = pages[pages[this.props.pageId].next].title;
      page = FreshSetup;
      props = {
        pageId: pages[this.props.pageId].next,
      };
    } else {
      title = 'Meowth';
      page = RecordPage;
    }

    this.props.navigator.push({
      component: page,
      backButtonTitle: 'Back',
      title: title,
      passProps: props,
      rightButtonTitle: 'Skip',
      onRightButtonPress: function () {
        this.props.navigator.push({
          component: RecordPage,
          backButtonTitle: 'Back',
          title: 'Meowth',
        });
      }.bind(this)
    });
  }

  render() {
    const actionText = pages[this.props.pageId].next ? 'Next slide' : 'Let\'s play!';

    return (
      <View style={styles.container}>
        <Image
          style={styles.pageImage}
          source={pages[this.props.pageId].source}
        />
        <Text style={styles.instructions}>
          {pages[this.props.pageId].subTitle}
        </Text>

        <TouchableHighlight
          underlayColor="#3969B4"
          style={styles.actionButton}
          onPress={this._onPressButton.bind(this)}
        >
          <Text style={styles.actionLabel}>
            {actionText}
          </Text>
        </TouchableHighlight>
      </View>
    );
  }
}

module.exports = FreshSetup;
<commit_msg>Fix navigation right button on Record Page<commit_after>let React = require('react-native');
let pages = require('./pagesContent');
let RecordPage = require('./RecordPage');
let {
  StyleSheet,
  Text,
  View,
  Image,
  TouchableHighlight,
} = React;

let styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#084265',
  },
  welcome: {
    color: '#F5FCFF',
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#F5FCFF',
    marginBottom: 5,
    paddingLeft: 15,
    paddingRight: 15,
  },
  actionButton: {
    marginTop: 30,
    paddingLeft: 15,
    paddingRight: 15,
    paddingTop: 10,
    paddingBottom: 10,
    backgroundColor: '#5B99FA',
    borderRadius: 4,
  },
  actionLabel: {
    color: '#fff',
    fontSize: 18,
  },
  pageImage: {
    width: 256,
    height: 256,
  },
});

class FreshSetup extends React.Component {
  _onPressButton() {
    let page, title, props;

    if (pages[this.props.pageId].next) {
      this.props.navigator.push({
        component: FreshSetup,
        backButtonTitle: 'Back',
        title: pages[pages[this.props.pageId].next].title,
        passProps: {
          pageId: pages[this.props.pageId].next,
        },
        rightButtonTitle: 'Skip',
        onRightButtonPress: function () {
          this.props.navigator.push({
            component: RecordPage,
            backButtonTitle: 'Back',
            title: 'Meowth',
          });
        }.bind(this)
      });
    } else {
      this.props.navigator.push({
        component: RecordPage,
        backButtonTitle: 'Back',
        title: 'Meowth',
      });
    }
  }

  render() {
    const actionText = pages[this.props.pageId].next ? 'Next slide' : 'Let\'s play!';

    return (
      <View style={styles.container}>
        <Image
          style={styles.pageImage}
          source={pages[this.props.pageId].source}
        />
        <Text style={styles.instructions}>
          {pages[this.props.pageId].subTitle}
        </Text>

        <TouchableHighlight
          underlayColor="#3969B4"
          style={styles.actionButton}
          onPress={this._onPressButton.bind(this)}
        >
          <Text style={styles.actionLabel}>
            {actionText}
          </Text>
        </TouchableHighlight>
      </View>
    );
  }
}

module.exports = FreshSetup;
<|endoftext|>


<commit_before>
var express = require('express'),
	app = express(),
	_ = require('underscore-x'),
	url = require('url'),
	fs = require('fs'),
	//ejs =  require('ejs'),
	ejsEngine = require('ejs-locals'),
	qs = require("querystring"),
	async = require('async'),
	parse = require('url').parse,
	adminSecurity = require('../lib/adminSecurity'),
	actionManager = require('../lib/actionManager');

app.engine('ejs', ejsEngine);
app.set('view engine', 'ejs');
app.set('views', rootPath + '/views');

app.use(express.favicon());
app.use(express.logger());
app.use(express.cookieParser());
app.use(express.json());
app.use(express.urlencoded());
//server.use(express.multipart());
app.use(express.static(rootPath+'/public'));
app.use(app.router);

app.get('/test', function(req, res){
	var temp = "Subdomain: " + req.subdomains[0] + "
";
	temp += "Url: " + JSON.stringify(req.url) + "
";
	temp += "UserAgent: " + req.headers['user-agent'] + "
";
	res.send('
Output '+temp+'
');
});

app.get('/login', function(req, res){
	if (req.session.adminUser) {
		// already login
		res.redirect('/home');
	} else {
		console.log("not login");

		res.render('login', {layout:false, error:'', csrftoken:res.locals.csrftoken, cfg:cfg});
	}
});

app.post('/login', adminSecurity.login);

app.get('/logout', adminSecurity.logout);

app.post('/logout', adminSecurity.logout);

app.post('/build', adminSecurity.restrict, function (req, res) {
	var passback = { status:false};
	async.waterfall([
		function(callback) {
			console.log("STEP 1");
			updateBuildProcess[1];
			actionManager.scriptExec(null, callback);
		},
		function(data, callback) {
			console.log("STEP 2 data: " + JSON.stringify(data));
			updateBuildProcess[2];
			passback.build_process = build_process;
			passback.status = true;
			res.json(passback);
		}

	], function(err, result){
		console.log("STEP ERROR");
		updateBuildProcess[4];
		passback.build_process = build_process;
		passback.err = err;
		res.json(passback);
	});
});

app.get('/', adminSecurity.restrict, function (req, res) {
	res.render('dashboard', { error:'', csrftoken:res.locals.csrftoken, cfg:cfg, data:{} });
});

app.get('/*', adminSecurity.restrict, function (req, res) {
	var reqUrl = (req.url.length >0)?req.url:'/home';
	var urlObject = url.parse(reqUrl);
	var page = urlObject.pathname.substring(1);
	console.log("req url: " + reqUrl + " Page: "  + page);

	var passback = { error:'', csrftoken:res.locals.csrftoken, cfg:cfg, data:{} };

	if (page == 'build') {
		passback.build_process = build_process;
	}

	if (page == 'view_config') {
		passback.data.script_content = fs.readFileSync(cfg.build_file_root_path + cfg.build_file_name);
	}

	res.render(page, passback);
});

// standard output
var output = function(req, res, data) {

	if (req.query.callback) {
		req.query.format = 'jsonp';
		req.body.format = 'jsonp';
	}

	if (req.query.format == 'json' || req.body.format == 'json') {
		res.json(data);
	} else if (req.query.format == 'jsonp' || req.body.format == 'jsonp') {
		res.jsonp(data);
	} else if (req.query.format == 'text' || req.body.format == 'text') {
		res.send(data);
	} else {
		res.send('
'+data+'
');
	}
}

module.exports.app = app;
<commit_msg>fix stupid bug<commit_after>
var express = require('express'),
	app = express(),
	_ = require('underscore-x'),
	url = require('url'),
	fs = require('fs'),
	//ejs =  require('ejs'),
	ejsEngine = require('ejs-locals'),
	qs = require("querystring"),
	async = require('async'),
	parse = require('url').parse,
	adminSecurity = require('../lib/adminSecurity'),
	actionManager = require('../lib/actionManager');

app.engine('ejs', ejsEngine);
app.set('view engine', 'ejs');
app.set('views', rootPath + '/views');

app.use(express.favicon());
app.use(express.logger());
app.use(express.cookieParser());
app.use(express.json());
app.use(express.urlencoded());
//server.use(express.multipart());
app.use(express.static(rootPath+'/public'));
app.use(app.router);

app.get('/test', function(req, res){
	var temp = "Subdomain: " + req.subdomains[0] + "
";
	temp += "Url: " + JSON.stringify(req.url) + "
";
	temp += "UserAgent: " + req.headers['user-agent'] + "
";
	res.send('
Output '+temp+'
');
});

app.get('/login', function(req, res){
	if (req.session.adminUser) {
		// already login
		res.redirect('/home');
	} else {
		console.log("not login");

		res.render('login', {layout:false, error:'', csrftoken:res.locals.csrftoken, cfg:cfg});
	}
});

app.post('/login', adminSecurity.login);

app.get('/logout', adminSecurity.logout);

app.post('/logout', adminSecurity.logout);

app.post('/build', adminSecurity.restrict, function (req, res) {
	var passback = { status:false};
	async.waterfall([
		function(callback) {
			console.log("STEP 1");
			updateBuildProcess(1);
			actionManager.scriptExec(null, callback);
		},
		function(data, callback) {
			console.log("STEP 2 data: " + JSON.stringify(data));
			updateBuildProcess(2);
			passback.build_process = build_process;
			passback.status = true;
			res.json(passback);
		}

	], function(err, result){
		console.log("STEP ERROR");
		updateBuildProcess(4);
		passback.build_process = build_process;
		passback.err = err;
		res.json(passback);
	});
});

app.get('/', adminSecurity.restrict, function (req, res) {
	res.render('dashboard', { error:'', csrftoken:res.locals.csrftoken, cfg:cfg, data:{} });
});

app.get('/*', adminSecurity.restrict, function (req, res) {
	var reqUrl = (req.url.length >0)?req.url:'/home';
	var urlObject = url.parse(reqUrl);
	var page = urlObject.pathname.substring(1);
	console.log("req url: " + reqUrl + " Page: "  + page);

	var passback = { error:'', csrftoken:res.locals.csrftoken, cfg:cfg, data:{} };

	if (page == 'build') {
		passback.build_process = build_process;
	}

	if (page == 'view_config') {
		passback.data.script_content = fs.readFileSync(cfg.build_file_root_path + cfg.build_file_name);
	}

	res.render(page, passback);
});

// standard output
var output = function(req, res, data) {

	if (req.query.callback) {
		req.query.format = 'jsonp';
		req.body.format = 'jsonp';
	}

	if (req.query.format == 'json' || req.body.format == 'json') {
		res.json(data);
	} else if (req.query.format == 'jsonp' || req.body.format == 'jsonp') {
		res.jsonp(data);
	} else if (req.query.format == 'text' || req.body.format == 'text') {
		res.send(data);
	} else {
		res.send('
'+data+'
');
	}
}

module.exports.app = app;
<|endoftext|>


<commit_before>/**
 * Shopware 5
 * Copyright (c) shopware AG
 *
 * According to our dual licensing model, this program can be used either
 * under the terms of the GNU Affero General Public License, version 3,
 * or under a proprietary license.
 *
 * The texts of the GNU Affero General Public License with an additional
 * permission and of our proprietary license can be found at and
 * in the LICENSE file you have received along with this program.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * "Shopware" is a registered trademark of shopware AG.
 * The licensing of the program under the AGPLv3 does not imply a
 * trademark license. Therefore any rights, title and interest in
 * our trademarks remain entirely with us.
 *
 * @category   Shopware
 * @package    Article
 * @subpackage Detail
 * @version    $Id$
 * @author shopware AG
 */

/**
 * Shopware UI - Article detail page - Image
 * The image list component contains a custom listing of the assigned article images.
 * The component contains also a toolbar to define the preview image, remove selected images
 * and change the displayed image size over a slider. All events of the component handled in the media controller.
 */
//{namespace name=backend/article/view/main}
//{block name="backend/article/view/image/list"}
Ext.define('Shopware.apps.Article.view.image.List', {

    /**
     * Defines that the article image listing is an extension of the Ext.panel.Panel
     */
    extend: 'Ext.panel.Panel',

    /**
     * Defines an alias for this component to get access over xtype
     */
    alias: 'widget.article-image-list',

    /**
     * Individually css class
     */
    cls: Ext.baseCSSPrefix + 'article-image-list',

    /**
     * Sets the background color for the listing
     */
    style: 'background: #fff',

    /**
     * Enables automatically scrolling
     */
    autoScroll: true,

    /**
     * Contains all snippets for this component
     * @object
     */
    snippets: {
        title: '{s name=image/list/title}Assigned images{/s}',
        comboBox: '{s name=image/list/combo_box}Images per page{/s}',
        previewButton: '{s name=image/list/preview_button}Mark as preview image{/s}',
        removeButton: '{s name=image/list/remove_button}Remove image(s)image/list/remove_button{/s}',
        configButton: '{s name=image/list/config_button}Open configuration{/s}',
        attributeButton: '{s name=image/list/attribute_button}Edit attributes{/s}',
        downloadButton: '{s name=image/list/download_button}Download image{/s}',
        mainImage:'{s name=image/list/main_image}Preview{/s}'
    },

    dragOverCls: 'drag-over',

    /**
     * Indicates if there are attributes for article images
     * @boolean
     */
    hasActiveAttributes: false,

    layout: 'fit',

    /**
     * Initializes the component and sets the neccessary
     * toolbars and items.
     *
     * @return void
     */
    initComponent: function() {
        var me = this;

        me.mediaStore = me.article.getMedia();

        me.title = me.snippets.title;
        me.tbar = me.createActionToolbar();
        me.dropZone = Ext.create('Shopware.apps.Article.view.image.DropZone', {
            padding: 20,
            dropZoneConfig: { hideOnLegacy: true, focusable: false },
            height: 100,
            style: {
                borderBottom: '1px solid',
                borderColor: '#a4b5c0'
            }
        });

        me.items = [{
            xtype: 'container',
            style: 'background: #fff',
            autoScroll: true,
            layout: {
                type: 'vbox',
                align: 'stretch'
            },
            items: [
                me.dropZone,
                me.createMediaView()
            ]
        }];
        me.registerEvents();
        me.callParent(arguments);

        me.on('afterrender', function() {
            if (me.mediaStore.getCount() && me.dataView.getSelectionModel().getSelection().length === 0) {
                window.setTimeout(function() {
                    me.dataView.getSelectionModel().select(0);
                }, 1);
            }
        });
    },

    /**
     * Registers additional component events.
     */
    registerEvents: function() {
        this.addEvents(
            /**
             * Event will be fired when the user select an article image in the listing.
             *
             * @event
             * @param [Ext.selection.DataViewModel] The selection data view model of the Ext.view.View
             * @param [Shopware.apps.Article.model.Media] The selected media
             */
            'mediaSelect',

            /**
             * Event will be fired when the user de select an article image in the listing.
             *
             * @event
             * @param [Ext.selection.DataViewModel] The selection data view model of the Ext.view.View
             * @param [Shopware.apps.Article.model.Media] The selected media
             */
            'mediaDeselect',

            /**
             * Event will be fired when the user move an image.
             *
             * @event
             * @param [Ext.data.Store] The media store
             * @param [Shopware.apps.Article.model.Media] The dragged record
             * @param [Shopware.apps.Article.model.Media] The target record, on which the dragged record dropped
             */
            'mediaMoved',

            /**
             * Event will be fired when the user clicks the "mark selected image as preview image".
             *
             * @event
             */
            'markPreviewImage',

            /**
             * Event will be fired when the user clicks the "remove selected image".
             *
             * @event
             */
            'removeImage',

            /**
             * Event will be fired when the user clicks the "open configuration" button.
             *
             * @event
             */
            'openImageMapping',

            /**
             * Event will be fired when the user clicks the "download" button
             */
            'download'

        );
    },

    /**
     * Creates the template for the media view panel
     *
     * @return [object] generated Ext.XTemplate
     */
    createMediaViewTemplate: function() {
        var me = this;
        return new Ext.XTemplate(
            '{literal}<tpl for=".">',
                '
',
                    // If the type is image, then show the image
                    '
',
                        '

',
                        '<tpl if="main===1">',
                            '
' + me.snippets.mainImage  + '
',
                        '</tpl>',
                        '<tpl if="hasConfig">',
                            '

',
                        '</tpl>',
                    '
',
                '
',
            '</tpl>',
            '

{/literal}'
        );
    },

    /**
     * Creates the media listing based on an Ext.view.View (know as DataView)
     * and binds the "Media"-store to it
     *
     * @return [object] this.dataView - created Ext.view.View
     */
    createMediaView: function() {
        var me = this;

        me.dataView = Ext.create('Ext.view.View', {
            itemSelector: '.article-thumb-wrap',
            name: 'image-listing',
            emptyText: 'No Media found',
            multiSelect: true,
            padding: '10 10 20',
            store: me.mediaStore,
            flex: 1,
            tpl: me.createMediaViewTemplate(),
            plugins: [ Ext.create('Ext.ux.DataView.DragSelector', {}) ]
        });

        me.dataView.getSelectionModel().on('select', function (dataViewModel, media) {
            me.fireEvent('mediaSelect', dataViewModel, media, me.previewButton, me.removeButton, me.configButton, me.downloadButton);
        });

        me.dataView.getSelectionModel().on('deselect', function (dataViewModel, media) {
            me.fireEvent('mediaDeselect', dataViewModel, media, me.previewButton, me.removeButton, me.configButton, me.downloadButton);
        });
        me.initDragAndDrop();

        return me.dataView;
    },

    /**
     * Creates the drag and drop zone for the Ext.view.View to allow
     */
    initDragAndDrop: function() {
        var me = this;

        me.dataView.on('afterrender', function(v) {
            me.dataView.dragZone = new Ext.dd.DragZone(v.getEl(), {
                getDragData: function(e) {
                    //Use the DataView's own itemSelector to
                    //test if the mousedown is within one of the DataView's nodes.
                    var sourceEl = e.getTarget(v.itemSelector, 10);

                    //If the mousedown is within a DataView node, clone the node to produce
                    //a ddel element for use by the drag proxy. Also add application data
                    //to the returned data object.
                    if (sourceEl) {
                        var d = sourceEl.cloneNode(true);
                        d.id = Ext.id();

                        var result = {
                            ddel: d,
                            sourceEl: sourceEl,
                            repairXY: Ext.fly(sourceEl).getXY(),
                            sourceStore: v.store,
                            draggedRecord: v.getRecord(sourceEl)
                        };
                        return result;
                    }
                },
                getRepairXY: function() {
                    return this.dragData.repairXY;
                }
            });

            me.dataView.dropZone = new Ext.dd.DropZone(me.dataView.getEl(), {
                //If the mouse is over a grid row, return that node. This is
                //provided as the "target" parameter in all "onNodeXXXX" node event handling functions
                getTargetFromEvent: function(e) {
                    return e.getTarget(me.dataView.itemSelector);
                },

                //On entry into a target node, highlight that node.
                onNodeEnter : function(target, dd, e, data){
                    var record = me.dataView.getRecord(target);
                    if (record !== data.draggedRecord) {
                        Ext.fly(target).addCls(me.dragOverCls);
                    }
                },

                //On exit from a target node, unhighlight that node.
                onNodeOut : function(target, dd, e, data){
                    Ext.fly(target).removeCls(me.dragOverCls);
                },

                //While over a target node, return the default drop allowed class which
                //places a "tick" icon into the drag proxy.
                onNodeOver : function(target, dd, e, data){
                    return (data.draggedRecord instanceof Ext.data.Model);
                },

                //On node drop we can interrogate the target to find the underlying
                //application object that is the real target of the dragged data.
                //In this case, it is a Record in the GridPanel's Store.
                //We can use the data set up by the DragZone's getDragData method to read
                //any data we decided to attach in the DragZone's getDragData method.
                onNodeDrop : function(target, dd, e, data){
                    var record = me.dataView.getRecord(target);
                    me.fireEvent('mediaMoved', me.mediaStore, data.draggedRecord, record)
                }
            });

        });
    },

    /**
     * Creates the action toolbar for the image listing.
     *
     * @return [object] created Ext.toolbar.Toolbar
     */
    createActionToolbar: function() {
        var me = this;

        me.addButton = Ext.create('Ext.button.Button', {
            text: '{s name="image_list_add_button"}{/s}',
            iconCls: 'sprite-plus-circle-frame',
            handler: function() {
                me.openMediaManager();
            }
        });

        //the preview button, marks the selected image in the listing as preview.
        //the event will be handled in the media controller
        me.previewButton = Ext.create('Ext.button.Button', {
            text: me.snippets.previewButton,
            action: 'previewImage',
            disabled: true,
            iconCls: 'sprite-camera-lens',
            handler: function() {
                me.fireEvent('markPreviewImage');
            }
        });

        //the remove button, removes the selected item from the image listing.
        me.removeButton = Ext.create('Ext.button.Button', {
            text: me.snippets.removeButton,
            action: 'removeImage',
            disabled: true,
            iconCls:'sprite-minus-circle-frame',
            handler: function() {
                me.fireEvent('removeImage');
            }
        });

        //the config button, opens the config window for the image mapping
        me.configButton = Ext.create('Ext.button.Button', {
            text: me.snippets.configButton,
            disabled: true,
            iconCls:'sprite-gear',
            handler: function() {
                me.fireEvent('openImageMapping');
            }
        });

        //the download button, opens a popup with the original image
        me.downloadButton = Ext.create('Ext.button.Button', {
            text: me.snippets.downloadButton,
            disabled: true,
            iconCls:'sprite-drive-download',
            handler: function() {
                if (me.dataView.getSelectionModel().selected && me.dataView.getSelectionModel().selected.first()) {
                    me.fireEvent('download', me.dataView.getSelectionModel().selected.first());
                }
            }
        });

        return Ext.create('Ext.toolbar.Toolbar', {
            items: [
                me.addButton,
                me.previewButton,
                me.removeButton,
                me.configButton,
                me.downloadButton
            ]
        });
    },

    openMediaManager: function() {
        var me = this;

        Shopware.app.Application.addSubApplication({
            name: 'Shopware.apps.MediaManager',
            layout: 'small',
            eventScope: me,
            selectionMode: true,
            params: { albumId: -1 },
            mediaSelectionCallback: me.onSelectMedia
        });
    },

    onSelectMedia: function(button, window, selection) {
        var me = this;

        Ext.each(selection, function(item) {
            var media = Ext.create('Shopware.apps.Article.model.Media', item.data);
            media.set('path', item.get('name'));
            media.set('main', 2);
            media.set('mediaId', item.get('id'));

            if (me.mediaStore.getCount() === 0) {
                media.set('main', 1);
            }
            media.set('id', 0);
            me.mediaStore.add(media);
        });
        window.close();
    }
});
//{/block}
<commit_msg>SW-14863 - Fix scrolling for images in product module<commit_after>/**
 * Shopware 5
 * Copyright (c) shopware AG
 *
 * According to our dual licensing model, this program can be used either
 * under the terms of the GNU Affero General Public License, version 3,
 * or under a proprietary license.
 *
 * The texts of the GNU Affero General Public License with an additional
 * permission and of our proprietary license can be found at and
 * in the LICENSE file you have received along with this program.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * "Shopware" is a registered trademark of shopware AG.
 * The licensing of the program under the AGPLv3 does not imply a
 * trademark license. Therefore any rights, title and interest in
 * our trademarks remain entirely with us.
 *
 * @category   Shopware
 * @package    Article
 * @subpackage Detail
 * @version    $Id$
 * @author shopware AG
 */

/**
 * Shopware UI - Article detail page - Image
 * The image list component contains a custom listing of the assigned article images.
 * The component contains also a toolbar to define the preview image, remove selected images
 * and change the displayed image size over a slider. All events of the component handled in the media controller.
 */
//{namespace name=backend/article/view/main}
//{block name="backend/article/view/image/list"}
Ext.define('Shopware.apps.Article.view.image.List', {

    /**
     * Defines that the article image listing is an extension of the Ext.panel.Panel
     */
    extend: 'Ext.panel.Panel',

    /**
     * Defines an alias for this component to get access over xtype
     */
    alias: 'widget.article-image-list',

    /**
     * Individually css class
     */
    cls: Ext.baseCSSPrefix + 'article-image-list',

    /**
     * Sets the background color for the listing
     */
    style: 'background: #fff',

    /**
     * Enables automatically scrolling
     */
    autoScroll: true,

    /**
     * Contains all snippets for this component
     * @object
     */
    snippets: {
        title: '{s name=image/list/title}Assigned images{/s}',
        comboBox: '{s name=image/list/combo_box}Images per page{/s}',
        previewButton: '{s name=image/list/preview_button}Mark as preview image{/s}',
        removeButton: '{s name=image/list/remove_button}Remove image(s)image/list/remove_button{/s}',
        configButton: '{s name=image/list/config_button}Open configuration{/s}',
        attributeButton: '{s name=image/list/attribute_button}Edit attributes{/s}',
        downloadButton: '{s name=image/list/download_button}Download image{/s}',
        mainImage:'{s name=image/list/main_image}Preview{/s}'
    },

    dragOverCls: 'drag-over',

    /**
     * Indicates if there are attributes for article images
     * @boolean
     */
    hasActiveAttributes: false,

    layout: 'fit',

    /**
     * Initializes the component and sets the neccessary
     * toolbars and items.
     *
     * @return void
     */
    initComponent: function() {
        var me = this;

        me.mediaStore = me.article.getMedia();

        me.title = me.snippets.title;
        me.tbar = me.createActionToolbar();
        me.dropZone = Ext.create('Shopware.apps.Article.view.image.DropZone', {
            padding: 20,
            dropZoneConfig: { hideOnLegacy: true, focusable: false },
            height: 100,
            style: {
                borderBottom: '1px solid',
                borderColor: '#a4b5c0'
            }
        });

        me.items = [{
            xtype: 'container',
            style: 'background: #fff',
            autoScroll: true,
            layout: {
                type: 'vbox',
                align: 'stretch'
            },
            items: [
                me.dropZone,
                me.createMediaView()
            ]
        }];
        me.registerEvents();
        me.callParent(arguments);

        me.on('afterrender', function() {
            if (me.mediaStore.getCount() && me.dataView.getSelectionModel().getSelection().length === 0) {
                window.setTimeout(function() {
                    me.dataView.getSelectionModel().select(0);
                }, 1);
            }
        });
    },

    /**
     * Registers additional component events.
     */
    registerEvents: function() {
        this.addEvents(
            /**
             * Event will be fired when the user select an article image in the listing.
             *
             * @event
             * @param [Ext.selection.DataViewModel] The selection data view model of the Ext.view.View
             * @param [Shopware.apps.Article.model.Media] The selected media
             */
            'mediaSelect',

            /**
             * Event will be fired when the user de select an article image in the listing.
             *
             * @event
             * @param [Ext.selection.DataViewModel] The selection data view model of the Ext.view.View
             * @param [Shopware.apps.Article.model.Media] The selected media
             */
            'mediaDeselect',

            /**
             * Event will be fired when the user move an image.
             *
             * @event
             * @param [Ext.data.Store] The media store
             * @param [Shopware.apps.Article.model.Media] The dragged record
             * @param [Shopware.apps.Article.model.Media] The target record, on which the dragged record dropped
             */
            'mediaMoved',

            /**
             * Event will be fired when the user clicks the "mark selected image as preview image".
             *
             * @event
             */
            'markPreviewImage',

            /**
             * Event will be fired when the user clicks the "remove selected image".
             *
             * @event
             */
            'removeImage',

            /**
             * Event will be fired when the user clicks the "open configuration" button.
             *
             * @event
             */
            'openImageMapping',

            /**
             * Event will be fired when the user clicks the "download" button
             */
            'download'

        );
    },

    /**
     * Creates the template for the media view panel
     *
     * @return [object] generated Ext.XTemplate
     */
    createMediaViewTemplate: function() {
        var me = this;
        return new Ext.XTemplate(
            '{literal}<tpl for=".">',
                '
',
                    // If the type is image, then show the image
                    '
',
                        '

',
                        '<tpl if="main===1">',
                            '
' + me.snippets.mainImage  + '
',
                        '</tpl>',
                        '<tpl if="hasConfig">',
                            '

',
                        '</tpl>',
                    '
',
                '
',
            '</tpl>',
            '

{/literal}'
        );
    },

    /**
     * Creates the media listing based on an Ext.view.View (know as DataView)
     * and binds the "Media"-store to it
     *
     * @return [object] this.dataView - created Ext.view.View
     */
    createMediaView: function() {
        var me = this;

        me.dataView = Ext.create('Ext.view.View', {
            itemSelector: '.article-thumb-wrap',
            name: 'image-listing',
            emptyText: 'No Media found',
            multiSelect: true,
            padding: '10 10 20',
            store: me.mediaStore,
            flex: 1,
            tpl: me.createMediaViewTemplate(),
            autoScroll: true,
            plugins: [ Ext.create('Ext.ux.DataView.DragSelector', {}) ]
        });

        me.dataView.getSelectionModel().on('select', function (dataViewModel, media) {
            me.fireEvent('mediaSelect', dataViewModel, media, me.previewButton, me.removeButton, me.configButton, me.downloadButton);
        });

        me.dataView.getSelectionModel().on('deselect', function (dataViewModel, media) {
            me.fireEvent('mediaDeselect', dataViewModel, media, me.previewButton, me.removeButton, me.configButton, me.downloadButton);
        });
        me.initDragAndDrop();

        return me.dataView;
    },

    /**
     * Creates the drag and drop zone for the Ext.view.View to allow
     */
    initDragAndDrop: function() {
        var me = this;

        me.dataView.on('afterrender', function(v) {
            me.dataView.dragZone = new Ext.dd.DragZone(v.getEl(), {
                getDragData: function(e) {
                    //Use the DataView's own itemSelector to
                    //test if the mousedown is within one of the DataView's nodes.
                    var sourceEl = e.getTarget(v.itemSelector, 10);

                    //If the mousedown is within a DataView node, clone the node to produce
                    //a ddel element for use by the drag proxy. Also add application data
                    //to the returned data object.
                    if (sourceEl) {
                        var d = sourceEl.cloneNode(true);
                        d.id = Ext.id();

                        var result = {
                            ddel: d,
                            sourceEl: sourceEl,
                            repairXY: Ext.fly(sourceEl).getXY(),
                            sourceStore: v.store,
                            draggedRecord: v.getRecord(sourceEl)
                        };
                        return result;
                    }
                },
                getRepairXY: function() {
                    return this.dragData.repairXY;
                }
            });

            me.dataView.dropZone = new Ext.dd.DropZone(me.dataView.getEl(), {
                //If the mouse is over a grid row, return that node. This is
                //provided as the "target" parameter in all "onNodeXXXX" node event handling functions
                getTargetFromEvent: function(e) {
                    return e.getTarget(me.dataView.itemSelector);
                },

                //On entry into a target node, highlight that node.
                onNodeEnter : function(target, dd, e, data){
                    var record = me.dataView.getRecord(target);
                    if (record !== data.draggedRecord) {
                        Ext.fly(target).addCls(me.dragOverCls);
                    }
                },

                //On exit from a target node, unhighlight that node.
                onNodeOut : function(target, dd, e, data){
                    Ext.fly(target).removeCls(me.dragOverCls);
                },

                //While over a target node, return the default drop allowed class which
                //places a "tick" icon into the drag proxy.
                onNodeOver : function(target, dd, e, data){
                    return (data.draggedRecord instanceof Ext.data.Model);
                },

                //On node drop we can interrogate the target to find the underlying
                //application object that is the real target of the dragged data.
                //In this case, it is a Record in the GridPanel's Store.
                //We can use the data set up by the DragZone's getDragData method to read
                //any data we decided to attach in the DragZone's getDragData method.
                onNodeDrop : function(target, dd, e, data){
                    var record = me.dataView.getRecord(target);
                    me.fireEvent('mediaMoved', me.mediaStore, data.draggedRecord, record)
                }
            });

        });
    },

    /**
     * Creates the action toolbar for the image listing.
     *
     * @return [object] created Ext.toolbar.Toolbar
     */
    createActionToolbar: function() {
        var me = this;

        me.addButton = Ext.create('Ext.button.Button', {
            text: '{s name="image_list_add_button"}{/s}',
            iconCls: 'sprite-plus-circle-frame',
            handler: function() {
                me.openMediaManager();
            }
        });

        //the preview button, marks the selected image in the listing as preview.
        //the event will be handled in the media controller
        me.previewButton = Ext.create('Ext.button.Button', {
            text: me.snippets.previewButton,
            action: 'previewImage',
            disabled: true,
            iconCls: 'sprite-camera-lens',
            handler: function() {
                me.fireEvent('markPreviewImage');
            }
        });

        //the remove button, removes the selected item from the image listing.
        me.removeButton = Ext.create('Ext.button.Button', {
            text: me.snippets.removeButton,
            action: 'removeImage',
            disabled: true,
            iconCls:'sprite-minus-circle-frame',
            handler: function() {
                me.fireEvent('removeImage');
            }
        });

        //the config button, opens the config window for the image mapping
        me.configButton = Ext.create('Ext.button.Button', {
            text: me.snippets.configButton,
            disabled: true,
            iconCls:'sprite-gear',
            handler: function() {
                me.fireEvent('openImageMapping');
            }
        });

        //the download button, opens a popup with the original image
        me.downloadButton = Ext.create('Ext.button.Button', {
            text: me.snippets.downloadButton,
            disabled: true,
            iconCls:'sprite-drive-download',
            handler: function() {
                if (me.dataView.getSelectionModel().selected && me.dataView.getSelectionModel().selected.first()) {
                    me.fireEvent('download', me.dataView.getSelectionModel().selected.first());
                }
            }
        });

        return Ext.create('Ext.toolbar.Toolbar', {
            items: [
                me.addButton,
                me.previewButton,
                me.removeButton,
                me.configButton,
                me.downloadButton
            ]
        });
    },

    openMediaManager: function() {
        var me = this;

        Shopware.app.Application.addSubApplication({
            name: 'Shopware.apps.MediaManager',
            layout: 'small',
            eventScope: me,
            selectionMode: true,
            params: { albumId: -1 },
            mediaSelectionCallback: me.onSelectMedia
        });
    },

    onSelectMedia: function(button, window, selection) {
        var me = this;

        Ext.each(selection, function(item) {
            var media = Ext.create('Shopware.apps.Article.model.Media', item.data);
            media.set('path', item.get('name'));
            media.set('main', 2);
            media.set('mediaId', item.get('id'));

            if (me.mediaStore.getCount() === 0) {
                media.set('main', 1);
            }
            media.set('id', 0);
            me.mediaStore.add(media);
        });
        window.close();
    }
});
//{/block}
<|endoftext|>


<commit_before>L.Map.mergeOptions({
	zoomAnimation: L.DomUtil.TRANSITION && !L.Browser.android23 && !L.Browser.mobileOpera
});

L.Map.include(!L.DomUtil.TRANSITION ? {} : {

	_zoomToIfClose: function (center, zoom) {

		if (this._animatingZoom) { return true; }

		if (!this.options.zoomAnimation) { return false; }

		var scale = this.getZoomScale(zoom),
			offset = this._getCenterOffset(center).divideBy(1 - 1 / scale);

		// if offset does not exceed half of the view
		if (!this._offsetIsWithinView(offset, 1)) { return false; }

		L.DomUtil.addClass(this._mapPane, 'leaflet-zoom-anim');

		this
			.fire('movestart')
			.fire('zoomstart');

		this._prepareTileBg();

		this.fire('zoomanim', {
			center: center,
			zoom: zoom
		});

		var origin = this._getCenterLayerPoint().add(offset);

		this._runAnimation(center, zoom, scale, origin);

		return true;
	},

	_runAnimation: function (center, zoom, scale, origin, backwardsTransform) {
		this._animatingZoom = true;

		this._animateToCenter = center;
		this._animateToZoom = zoom;

		var transform = L.DomUtil.TRANSFORM,
			tileBg = this._tileBg;

		clearTimeout(this._clearTileBgTimer);

		//dumb FireFox hack, I have no idea why this magic zero translate fixes the scale transition problem
		if (L.Browser.gecko || window.opera) {
			tileBg.style[transform] += ' translate(0,0)';
		}

		var scaleStr = L.DomUtil.getScaleString(scale, origin);

		L.Util.falseFn(tileBg.offsetWidth); //hack to make sure transform is updated before running animation

		var options = {};
		if (backwardsTransform) {
			options[transform] = tileBg.style[transform] + ' ' + scaleStr;
		} else {
			options[transform] = scaleStr + ' ' + tileBg.style[transform];
		}

		tileBg.transition.run(options);
	},

	_prepareTileBg: function () {
		var tilePane = this._tilePane,
			tileBg = this._tileBg;

		// If foreground layer doesn't have many tiles but bg layer does, keep the existing bg layer and just zoom it some more
		if (tileBg &&
				this._getLoadedTilesPercentage(tileBg) > 0.5 &&
				this._getLoadedTilesPercentage(tilePane) < 0.5) {

			tilePane.style.visibility = 'hidden';
			tilePane.empty = true;
			this._stopLoadingImages(tilePane);
			return;
		}

		if (!tileBg) {
			tileBg = this._tileBg = this._createPane('leaflet-tile-pane', this._mapPane);
			tileBg.style.zIndex = 1;
		}

		// prepare the background pane to become the main tile pane
		tileBg.style[L.DomUtil.TRANSFORM] = '';
		tileBg.style.visibility = 'hidden';

		// tells tile layers to reinitialize their containers
		tileBg.empty = true; //new FG
		tilePane.empty = false; //new BG

		//Switch out the current layer to be the new bg layer (And vice-versa)
		this._tilePane = this._panes.tilePane = tileBg;
		var newTileBg = this._tileBg = tilePane;

		if (!newTileBg.transition) {
			// TODO move to Map options
			newTileBg.transition = new L.Transition(newTileBg, {
				duration: 0.25,
				easing: 'cubic-bezier(0.25,0.1,0.25,0.75)'
			});
			newTileBg.transition.on('end', this._onZoomTransitionEnd, this);
		}

		this._stopLoadingImages(newTileBg);
	},

	_getLoadedTilesPercentage: function (container) {
		var tiles = container.getElementsByTagName('img'),
			i, len, count = 0;

		for (i = 0, len = tiles.length; i < len; i++) {
			if (tiles[i].complete) {
				count++;
			}
		}
		return count / len;
	},

	// stops loading all tiles in the background layer
	_stopLoadingImages: function (container) {
		var tiles = Array.prototype.slice.call(container.getElementsByTagName('img')),
			i, len, tile;

		for (i = 0, len = tiles.length; i < len; i++) {
			tile = tiles[i];

			if (!tile.complete) {
				tile.onload = L.Util.falseFn;
				tile.onerror = L.Util.falseFn;
				tile.src = L.Util.emptyImageUrl;

				tile.parentNode.removeChild(tile);
			}
		}
	},

	_onZoomTransitionEnd: function () {
		this._restoreTileFront();

		L.Util.falseFn(this._tileBg.offsetWidth); // force reflow
		this._resetView(this._animateToCenter, this._animateToZoom, true, true);

		L.DomUtil.removeClass(this._mapPane, 'leaflet-zoom-anim');
		this._animatingZoom = false;
	},

	_restoreTileFront: function () {
		this._tilePane.innerHTML = '';
		this._tilePane.style.visibility = '';
		this._tilePane.style.zIndex = 2;
		this._tileBg.style.zIndex = 1;
	},

	_clearTileBg: function () {
		if (!this._animatingZoom && !this.touchZoom._zooming) {
			this._tileBg.innerHTML = '';
		}
	}
});
<commit_msg>Move tile layer transition to CSS, detect zoom transion end globally<commit_after>L.Map.mergeOptions({
	zoomAnimation: L.DomUtil.TRANSITION && !L.Browser.android23 && !L.Browser.mobileOpera
});

L.Map.addInitHook(function () {
	L.DomEvent.on(this._mapPane, L.Transition.END, this._catchTransitionEnd, this);
});

L.Map.include(!L.DomUtil.TRANSITION ? {} : {

	_zoomToIfClose: function (center, zoom) {

		if (this._animatingZoom) { return true; }

		if (!this.options.zoomAnimation) { return false; }

		var scale = this.getZoomScale(zoom),
			offset = this._getCenterOffset(center).divideBy(1 - 1 / scale);

		// if offset does not exceed half of the view
		if (!this._offsetIsWithinView(offset, 1)) { return false; }

		L.DomUtil.addClass(this._mapPane, 'leaflet-zoom-anim');

		this
			.fire('movestart')
			.fire('zoomstart');

		this._prepareTileBg();

		this.fire('zoomanim', {
			center: center,
			zoom: zoom
		});

		var origin = this._getCenterLayerPoint().add(offset);

		this._runAnimation(center, zoom, scale, origin);

		return true;
	},

	_catchTransitionEnd: function (e) {
		if (this._animatingZoom) {
			this._onZoomTransitionEnd();
		}
	},

	_runAnimation: function (center, zoom, scale, origin, backwardsTransform) {
		this._animatingZoom = true;

		this._animateToCenter = center;
		this._animateToZoom = zoom;

		var transform = L.DomUtil.TRANSFORM,
			tileBg = this._tileBg;

		clearTimeout(this._clearTileBgTimer);

		//dumb FireFox hack, I have no idea why this magic zero translate fixes the scale transition problem
		if (L.Browser.gecko || window.opera) {
			tileBg.style[transform] += ' translate(0,0)';
		}

		var scaleStr = L.DomUtil.getScaleString(scale, origin);

		L.Util.falseFn(tileBg.offsetWidth); //hack to make sure transform is updated before running animation

		tileBg.style[transform] = backwardsTransform ?
			tileBg.style[transform] + ' ' + scaleStr :
			scaleStr + ' ' + tileBg.style[transform];
	},

	_prepareTileBg: function () {
		var tilePane = this._tilePane,
			tileBg = this._tileBg;

		// If foreground layer doesn't have many tiles but bg layer does, keep the existing bg layer and just zoom it some more
		if (tileBg &&
				this._getLoadedTilesPercentage(tileBg) > 0.5 &&
				this._getLoadedTilesPercentage(tilePane) < 0.5) {

			tilePane.style.visibility = 'hidden';
			tilePane.empty = true;
			this._stopLoadingImages(tilePane);
			return;
		}

		if (!tileBg) {
			tileBg = this._tileBg = this._createPane('leaflet-tile-pane', this._mapPane);
			tileBg.style.zIndex = 1;
		}

		// prepare the background pane to become the main tile pane
		tileBg.style[L.DomUtil.TRANSFORM] = '';
		tileBg.style.visibility = 'hidden';

		// tells tile layers to reinitialize their containers
		tileBg.empty = true; //new FG
		tilePane.empty = false; //new BG

		//Switch out the current layer to be the new bg layer (And vice-versa)
		this._tilePane = this._panes.tilePane = tileBg;
		var newTileBg = this._tileBg = tilePane;

		L.DomUtil.addClass(newTileBg, 'leaflet-zoom-animated');

		this._stopLoadingImages(newTileBg);
	},

	_getLoadedTilesPercentage: function (container) {
		var tiles = container.getElementsByTagName('img'),
			i, len, count = 0;

		for (i = 0, len = tiles.length; i < len; i++) {
			if (tiles[i].complete) {
				count++;
			}
		}
		return count / len;
	},

	// stops loading all tiles in the background layer
	_stopLoadingImages: function (container) {
		var tiles = Array.prototype.slice.call(container.getElementsByTagName('img')),
			i, len, tile;

		for (i = 0, len = tiles.length; i < len; i++) {
			tile = tiles[i];

			if (!tile.complete) {
				tile.onload = L.Util.falseFn;
				tile.onerror = L.Util.falseFn;
				tile.src = L.Util.emptyImageUrl;

				tile.parentNode.removeChild(tile);
			}
		}
	},

	_onZoomTransitionEnd: function () {
		this._restoreTileFront();
		L.Util.falseFn(this._tileBg.offsetWidth); // force reflow
		this._resetView(this._animateToCenter, this._animateToZoom, true, true);

		L.DomUtil.removeClass(this._mapPane, 'leaflet-zoom-anim');
		this._animatingZoom = false;
	},

	_restoreTileFront: function () {
		this._tilePane.innerHTML = '';
		this._tilePane.style.visibility = '';
		this._tilePane.style.zIndex = 2;
		this._tileBg.style.zIndex = 1;
	},

	_clearTileBg: function () {
		if (!this._animatingZoom && !this.touchZoom._zooming) {
			this._tileBg.innerHTML = '';
		}
	}
});
<|endoftext|>


<commit_before>var id;
var database = Alloy.Globals.db;
/**
 * Screen Initialization
 * */
function initialize() {
	$.topBar.imageContainer.addEventListener('click', closeWindow);
	$.topBar.setTitle(L('localDB'));
	$.add.setTitle(L('insert'));
	initializeDB();
}

/**
 * DB Initialization
 * */
function initializeDB() {
	var db = Ti.Database.open(database);
	db.execute('CREATE TABLE IF NOT EXISTS Employee (id INTEGER PRIMARY KEY AUTOINCREMENT , firstName TEXT, lastName TEXT);');
	fetchData();
	db.close();
}

/**
 * Selects data from table
 * */
function fetchData() {
	var db = Ti.Database.open(database);
	var tableData = [];
	var resultSet = db.execute('SELECT * from Employee;');
	while (resultSet.isValidRow()) {
		var row = createRow(resultSet);
		tableData.push(row);
		resultSet.next();
	}
	$.namesTable.setData(tableData);
	resultSet.close();
	db.close();
}

/**
 * Creates table rows
 * */
function createRow(rs) {
	var row = Alloy.createController("partials/dbRow", {
		first_name : rs.fieldByName('firstName'),
		last_name : rs.fieldByName('lastName'),
		id : rs.fieldByName('id'),
		editCallback : updateRow,
		delCallback : deleteRow
	}).getView();

	return row;
}

/**
 * Edits the record selected
 * */
function updateRow(fname, lname, recordId) {
	$.add.title = L('update');
	id = recordId;
	$.firstNameVal.value = fname;
	$.lastNameVal.value = lname;
}

/**
 * resets the first name last name and insert button
 */
function reset() {
	id = "";
	$.firstNameVal.value = "";
	$.lastNameVal.value = "";
	$.add.title = L('insert');
}

/**
 * Deletes the record selected
 * */
function deleteRow(id) {
	var dialog = Ti.UI.createAlertDialog({
		message : L('delRecord'),
		ok : L("ok"),
		buttonNames : [L("ok"), L('cancel')],
		cancel : 1
	});
	dialog.show();

	dialog.addEventListener("click", function(e) {
		if (e.index === 0) {
			var db = Ti.Database.open(database);
			db.execute('DELETE FROM Employee WHERE id = ?', id);
			Ti.UI.createAlertDialog({
				message : L('record_deleted'),
				ok : L("ok")
			}).show();
			fetchData();

			//Incase the Update option is selected and then the user clicks delete
			reset();

			db.close();
		}
	});
}

/**
 *EVENT LISTENERS
 */

/**
 * Insert and Update data into table
 * */
function addData(e) {
	$.firstNameVal.blur();
	$.lastNameVal.blur();
	if ($.firstNameVal.value !== "" && $.firstNameVal.value !== undefined) {
		var db = Ti.Database.open(database);
		if (id) {
			db.execute('UPDATE Employee SET firstName = ? , lastName = ? WHERE id = ?', $.firstNameVal.value, $.lastNameVal.value, id);
			Ti.UI.createAlertDialog({
				message : L('record_updated'),
				ok : L("ok")
			}).show();
			id = "";
		} else {
			$.lastNameVal.value = ($.lastNameVal.value === undefined) ? "" : $.lastNameVal.value;
			db.execute('INSERT INTO Employee (firstName, lastName) VALUES (?, ?)', $.firstNameVal.value, $.lastNameVal.value);

		}
		db.close();
		fetchData();
		$.firstNameVal.value = "";
		$.lastNameVal.value = "";
		$.add.title = L('insert');
	}

}

/**
 * perform edit and delete actions
 * */
function performOperations(e) {
	var action = e.source.id;
	var fname = e.row.fname;
	var lname = e.row.lname;
	var index = e.row.index;
	switch(action) {
		case "edit":
			if (id) {
				reset();
			} else {
				updateRow(fname, lname, index);
			}
			break;
		case "del":
			deleteRow(index);
			break;
		default:
			break;
	}

}

/**
 * Closes the window
 * */
function closeWindow() {
	$.localDbWin.close();
}

//Initialization Logic
initialize();
<commit_msg>fixing update functionality<commit_after>var id;
var database = Alloy.Globals.db;
/**
 * Screen Initialization
 * */
function initialize() {
	$.topBar.imageContainer.addEventListener('click', closeWindow);
	$.topBar.setTitle(L('localDB'));
	$.add.setTitle(L('insert'));
	initializeDB();
}

/**
 * DB Initialization
 * */
function initializeDB() {
	var db = Ti.Database.open(database);
	db.execute('CREATE TABLE IF NOT EXISTS Employee (id INTEGER PRIMARY KEY AUTOINCREMENT , firstName TEXT, lastName TEXT);');
	fetchData();
	db.close();
}

/**
 * Selects data from table
 * */
function fetchData() {
	var db = Ti.Database.open(database);
	var tableData = [];
	var resultSet = db.execute('SELECT * from Employee;');
	while (resultSet.isValidRow()) {
		var row = createRow(resultSet);
		tableData.push(row);
		resultSet.next();
	}
	$.namesTable.setData(tableData);
	resultSet.close();
	db.close();
}

/**
 * Creates table rows
 * */
function createRow(rs) {
	var row = Alloy.createController("partials/dbRow", {
		first_name : rs.fieldByName('firstName'),
		last_name : rs.fieldByName('lastName'),
		id : rs.fieldByName('id'),
		editCallback : updateRow,
		delCallback : deleteRow
	}).getView();

	return row;
}

/**
 * Edits the record selected
 * */
function updateRow(fname, lname, recordId) {
	$.add.title = L('update');
	id = recordId;
	$.firstNameVal.value = fname;
	$.lastNameVal.value = lname;
}

/**
 * resets the first name last name and insert button
 */
function reset() {
	id = "";
	$.firstNameVal.value = "";
	$.lastNameVal.value = "";
	$.add.title = L('insert');
}

/**
 * Deletes the record selected
 * */
function deleteRow(id) {
	var dialog = Ti.UI.createAlertDialog({
		message : L('delRecord'),
		ok : L("ok"),
		buttonNames : [L("ok"), L('cancel')],
		cancel : 1
	});
	dialog.show();

	dialog.addEventListener("click", function(e) {
		if (e.index === 0) {
			var db = Ti.Database.open(database);
			db.execute('DELETE FROM Employee WHERE id = ?', id);
			Ti.UI.createAlertDialog({
				message : L('record_deleted'),
				ok : L("ok")
			}).show();
			fetchData();

			//Incase the Update option is selected and then the user clicks delete
			reset();

			db.close();
		}
	});
}

/**
 *EVENT LISTENERS
 */

/**
 * Insert and Update data into table
 * */
function addData(e) {
	$.firstNameVal.blur();
	$.lastNameVal.blur();
	if ($.firstNameVal.value !== "" && $.firstNameVal.value !== undefined) {
		var db = Ti.Database.open(database);
		if (id) {
			db.execute('UPDATE Employee SET firstName = ? , lastName = ? WHERE id = ?', $.firstNameVal.value, $.lastNameVal.value, id);
			Ti.UI.createAlertDialog({
				message : L('record_updated'),
				ok : L("ok")
			}).show();
			id = "";
		} else {
			$.lastNameVal.value = ($.lastNameVal.value === undefined) ? "" : $.lastNameVal.value;
			db.execute('INSERT INTO Employee (firstName, lastName) VALUES (?, ?)', $.firstNameVal.value, $.lastNameVal.value);

		}
		db.close();
		fetchData();
		$.firstNameVal.value = "";
		$.lastNameVal.value = "";
		$.add.title = L('insert');
	}

}

/**
 * perform edit and delete actions
 * */
function performOperations(e) {
	var action = e.source.id;
	var fname = e.row.fname;
	var lname = e.row.lname;
	var index = e.row.index;
	switch(action) {
		case "edit":
			updateRow(fname, lname, index);
			break;
		case "del":
			deleteRow(index);
			break;
		default:
			break;
	}

}

/**
 * Closes the window
 * */
function closeWindow() {
	$.localDbWin.close();
}

//Initialization Logic
initialize();
<|endoftext|>


<commit_before>'use strict';

function ObjectPrimitives() {
    Primitives.call(this);
    var _this = this;

    function _equals(frame, args) {
        var op1 = args[1];
        var op2 = args[0];
        if (op1 === op2) {
            return som.trueObject;
        } else {
            return som.falseObject;
        }
    }

    function _hashcode(frame, args) {
        var rcvr = args[0];
        var hash = rcvr.hash;
        if (hash === undefined) {
            hash = Math.round(Math.random() * 2147483647);
            rcvr.hash = hash;
        }
        return hash;
    }

    function _objectSize(frame, args) {
        var size = 0;
        var rcvr = args[0];
        if (rcvr instanceof SObject) {
            size = rcvr.getNumberOfFields();
        } else if (rcvr instanceof SArray) {
            size = rcvr.getNumberOfIndexableFields();
        }
        return universe.newInteger(size);
    }

    function _perform(frame, args) {
        var selector = args[1];
        var rcvr     = args[0];
        var invokable = rcvr.getClass().lookupInvokable(selector);
        return invokable.invoke([rcvr]);
    }

    function _performInSuperclass(frame, args) {
        var clazz    = args[2];
        var selector = args[1];
        var rcvr     = args[0];

        var invokable = clazz.lookupInvokable(selector);
        return invokable.invoke([rcvr]);
    }

    function _performWithArguments(frame, args) {
        // TODO: need to create a proper SArray, but don't have SArray yet.
        notYetImplemented();
        var argArr   = args[2].get_indexable_fields();
        var selector = args[1];
        var rcvr     = args[0];

        var invokable = rcvr.getClass().lookupInvokable(selector)
        return invokable.invoke(rcvr, argArr)
    }

    function _instVarAt(frame, args) {
        var idx = args[1];
        return args[0].getField(idx.getEmbeddedInteger() - 1);
    }

    function _instVarAtPut(frame, args) {
        var val = args[2];
        var idx = args[1];
        args[0].setField(idx.getEmbeddedInteger() - 1, val);
        return val;
    }

    function _instVarNamed(frame, args) {
        var rcvr = args[0];
        var i = rcvr.getFieldIndex(args[1]);
        return rcvr.getField(i);
    }

    function _halt(frame, args) {
        universe.println("BREAKPOINT");
        debugger;
        return args[0];
    }

    function _class(frame, args) {
        return args[0].getClass();
    }

    this.installPrimitives = function () {
        _this.installInstancePrimitive("==",                     _equals);
        _this.installInstancePrimitive("hashcode",               _hashcode);
        _this.installInstancePrimitive("objectSize",             _objectSize);
        _this.installInstancePrimitive("perform:",               _perform);
        _this.installInstancePrimitive("perform:inSuperclass:",  _performInSuperclass);
        _this.installInstancePrimitive("perform:withArguments:", _performWithArguments);
        _this.installInstancePrimitive("perform:withArguments:inSuperclass:", null);  // TODO: primitive implementation missing, also in RTruffleSOM...
        _this.installInstancePrimitive("instVarAt:",             _instVarAt);
        _this.installInstancePrimitive("instVarAt:put:",         _instVarAtPut);
        _this.installInstancePrimitive("instVarNamed:",          _instVarNamed);
        _this.installInstancePrimitive("halt",                   _halt);
        _this.installInstancePrimitive("class",                  _class);
    }
}
ObjectPrimitives.prototype = Object.create(Primitives.prototype);
som.primitives["Object"] = ObjectPrimitives;
<commit_msg>Fix method name<commit_after>'use strict';

function ObjectPrimitives() {
    Primitives.call(this);
    var _this = this;

    function _equals(frame, args) {
        var op1 = args[1];
        var op2 = args[0];
        if (op1 === op2) {
            return som.trueObject;
        } else {
            return som.falseObject;
        }
    }

    function _hashcode(frame, args) {
        var rcvr = args[0];
        var hash = rcvr.hash;
        if (hash === undefined) {
            hash = Math.round(Math.random() * 2147483647);
            rcvr.hash = hash;
        }
        return hash;
    }

    function _objectSize(frame, args) {
        var size = 0;
        var rcvr = args[0];
        if (rcvr instanceof SObject) {
            size = rcvr.getNumberOfFields();
        } else if (rcvr instanceof SArray) {
            size = rcvr.getNumberOfIndexableFields();
        }
        return universe.newInteger(size);
    }

    function _perform(frame, args) {
        var selector = args[1];
        var rcvr     = args[0];
        var invokable = rcvr.getClass().lookupInvokable(selector);
        return invokable.invoke([rcvr]);
    }

    function _performInSuperclass(frame, args) {
        var clazz    = args[2];
        var selector = args[1];
        var rcvr     = args[0];

        var invokable = clazz.lookupInvokable(selector);
        return invokable.invoke([rcvr]);
    }

    function _performWithArguments(frame, args) {
        // TODO: need to create a proper SArray, but don't have SArray yet.
        notYetImplemented();
        var argArr   = args[2].getIndexableFields();
        var selector = args[1];
        var rcvr     = args[0];

        var invokable = rcvr.getClass().lookupInvokable(selector)
        return invokable.invoke(rcvr, argArr)
    }

    function _instVarAt(frame, args) {
        var idx = args[1];
        return args[0].getField(idx.getEmbeddedInteger() - 1);
    }

    function _instVarAtPut(frame, args) {
        var val = args[2];
        var idx = args[1];
        args[0].setField(idx.getEmbeddedInteger() - 1, val);
        return val;
    }

    function _instVarNamed(frame, args) {
        var rcvr = args[0];
        var i = rcvr.getFieldIndex(args[1]);
        return rcvr.getField(i);
    }

    function _halt(frame, args) {
        universe.println("BREAKPOINT");
        debugger;
        return args[0];
    }

    function _class(frame, args) {
        return args[0].getClass();
    }

    this.installPrimitives = function () {
        _this.installInstancePrimitive("==",                     _equals);
        _this.installInstancePrimitive("hashcode",               _hashcode);
        _this.installInstancePrimitive("objectSize",             _objectSize);
        _this.installInstancePrimitive("perform:",               _perform);
        _this.installInstancePrimitive("perform:inSuperclass:",  _performInSuperclass);
        _this.installInstancePrimitive("perform:withArguments:", _performWithArguments);
        _this.installInstancePrimitive("perform:withArguments:inSuperclass:", null);  // TODO: primitive implementation missing, also in RTruffleSOM...
        _this.installInstancePrimitive("instVarAt:",             _instVarAt);
        _this.installInstancePrimitive("instVarAt:put:",         _instVarAtPut);
        _this.installInstancePrimitive("instVarNamed:",          _instVarNamed);
        _this.installInstancePrimitive("halt",                   _halt);
        _this.installInstancePrimitive("class",                  _class);
    }
}
ObjectPrimitives.prototype = Object.create(Primitives.prototype);
som.primitives["Object"] = ObjectPrimitives;
<|endoftext|>


<commit_before>$(document).ready(function() {

	var newCourseModal = $('#create-new-course-modal');

	var codeField = $('#course-code');
	var nameField = $('#course-name');
	var templateField = $('#template-url');
	var provisionNewCourseButton = $('#provision-new-course');
	var templateBox = $('#base-on-template');
	var templatePanel = $('#template-url-panel');

	var timers = [];

	$("#create-new-course").click(function(e) {
		e.preventDefault();
		newCourseModal.modal("show");
	});

	function getFullCourseName() {
		return codeField.val() + " " + nameField.val();
	}

	setInterval(function() {
		if (templateBox.is(":checked")) {
			templatePanel.show();
		}
		else {
			templatePanel.hide();
		}
	}, 100);

	newCourseModal.on("show", function() {
		nameField.val("");
		codeField.val("");
		templateBox.attr("checked", false);
		templateField.val("");
		enableVerification();
	});

	newCourseModal.on("hide", function() {
		stopTimers(timers);
		nameField.val("");
		codeField.val("");
		templateBox.attr("checked", false);
		templateField.val("");
	});

	provisionNewCourseButton.click(function(e) {
		e.preventDefault();
		var name = nameField.val();
		var code = codeField.val();
		var courseName = code.trim() + " " + name.trim();
		var template = templateField.val();

		stopTimers(timers);
		setButtonState(provisionNewCourseButton, false);

		displayProcessor();

		$.ajax({
			type: "post",
			dataType: "text",
			contentType: "application/json",
			url: "/api/courses/create",
			data: JSON.stringify({ "name": courseName , "templateUrl": template }),
			success: function() {
				window.location.replace("/admin");
			},
			error: function(jqXHR, textStatus, errorThrown) {
				removeProcessor();
				var result = jqXHR.responseText;
				if (result == "already-taken") {
					showAlert("alert-error", "There's already a course with this code and name!");
				}
				else if (result == "invalid-name") {
					showAlert("alert-error", "This is not a valid course code and/or name!");
				}
				else if (result == "could-not-clone-repo") {
					showAlert("alert-error", "Could not clone from the template Git repository!", "Either the Git service hosting the repository is inaccessible or the repository is not public");
				}
				else {
					showAlert("alert-error", result);
				}

				provisionNewCourseButton.attr("disabled", "disabled");
				enableVerification();
			}
		});
	});

	function enableVerification() {
		timers.push(
			verify(codeField, "^[a-zA-Z0-9]{6,}$", function(value, callback) {
				var value = nameField.val();
				if (value != undefined && value.match("^.{6,}$")) {
					callback.call(this, true);
				}
				else {
					callback.call(this, false);
				}
			}),
			verifyCheckbox(templateBox, templateField, "^.{1,}$"),
			synchronize(provisionNewCourseButton, [ codeField, nameField, templateField ])
		);
	}

});<commit_msg>Minor improvement.<commit_after>$(document).ready(function() {

	var newCourseModal = $('#create-new-course-modal');

	var codeField = $('#course-code');
	var nameField = $('#course-name');
	var templateField = $('#template-url');
	var provisionNewCourseButton = $('#provision-new-course');
	var templateBox = $('#base-on-template');
	var templatePanel = $('#template-url-panel');

	var timers = [];

	$("#create-new-course").click(function(e) {
		e.preventDefault();
		newCourseModal.modal("show");
	});

	function getFullCourseName() {
		return codeField.val() + " " + nameField.val();
	}

	setInterval(function() {
		if (templateBox.is(":checked")) {
			templatePanel.show();
		}
		else {
			templatePanel.hide();
		}
	}, 100);

	newCourseModal.on("show", function() {
		nameField.val("");
		codeField.val("");
		templateBox.attr("checked", false);
		templateField.val("");
		enableVerification();
	});

	newCourseModal.on("hide", function() {
		stopTimers(timers);
		nameField.val("");
		codeField.val("");
		templateBox.attr("checked", false);
		templateField.val("");
	});

	provisionNewCourseButton.click(function(e) {
		e.preventDefault();
		var name = nameField.val();
		var code = codeField.val();
		var courseName = code.trim() + " " + name.trim();
		var template = templateField.val();

		stopTimers(timers);
		setButtonState(provisionNewCourseButton, false);

		displayProcessor();

		$.ajax({
			type: "post",
			dataType: "text",
			contentType: "application/json",
			url: "/api/courses/create",
			data: JSON.stringify({ "name": courseName , "templateUrl": template }),
			success: function() {
				window.location.replace("/admin");
			},
			error: function(jqXHR, textStatus, errorThrown) {
				removeProcessor();
				var result = jqXHR.responseText;
				if (result == "already-taken") {
					showAlert("alert-error", "There's already a course with this code and name!");
				}
				else if (result == "invalid-name") {
					showAlert("alert-error", "This is not a valid course code and/or name!");
				}
				else if (result == "could-not-clone-repo") {
					showAlert("alert-error", "Could not clone from the template Git repository!", "Either the Git service hosting the repository is down or the repository is not public");
				}
				else {
					showAlert("alert-error", result);
				}

				provisionNewCourseButton.attr("disabled", "disabled");
				enableVerification();
			}
		});
	});

	function enableVerification() {
		timers.push(
			verify(codeField, "^[a-zA-Z0-9]{6,}$", function(value, callback) {
				var value = nameField.val();
				if (value != undefined && value.match("^.{6,}$")) {
					callback.call(this, true);
				}
				else {
					callback.call(this, false);
				}
			}),
			verifyCheckbox(templateBox, templateField, "^.{1,}$"),
			synchronize(provisionNewCourseButton, [ codeField, nameField, templateField ])
		);
	}

});<|endoftext|>


<commit_before>import React from 'react';
import cx from 'classnames';
import idgen from './idgen';
import constants from './constants';

class Input extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: this.props.defaultValue};
    this._onChange = this._onChange.bind(this);
    this.isSelect = this.isSelect.bind(this);
  }

  componentDidMount() {
    if (this.isMaterialSelect()) {
      $(this.refs.inputEl).material_select();
      $(this.refs.inputEl).on('change', this._onChange);
    }
  }

  componentDidUpdate(prevProps, prevState) {
    if (this.isMaterialSelect()) {
      $(this.refs.inputEl).material_select();
    }
  }

  componentWillReceiveProps(nextProps) {
    if (this.isMaterialSelect()) {
      this.setState({
        value: nextProps.defaultValue
      }, () => $(this.refs.inputEl).material_select());
    }
  }

  componentWillUnmount() {
    if (this.isMaterialSelect()) {
      $(this.refs.inputEl).off('change', this._onChange);
    }
  }

  _onChange(e) {
    this.setState({
      value: e.target.value
    });
    if (this.props.onChange) {
      this.props.onChange(e);
    }
  }

  render() {
    let { defaultValue, placeholder, id, type, label, children, validate, onChange, ...props} = this.props;
    let classes = {
      col: true,
      'input-field': type !== 'checkbox' && type !== 'radio'
    };
    constants.SIZES.forEach(size => {
      if (this.props[size]) {
        classes[size + this.props[size]] = true;
      }
    });
    if (!id) {
      id = `input_${idgen()}`;
    }
    let inputClasses = {
      validate
    };
    let C, inputType;
    switch (type) {
      case 'textarea':
        C = 'textarea';
        inputClasses['materialize-textarea'] = true;
        break;
      case 'switch':
        C = 'input';
        inputType = 'checkbox';
        break;
      default:
        C = 'input';
        inputType = type || 'text';
    }
    let labelClasses = {
      active: this.state.value || this.isSelect()
    };

    let htmlLabel = label ? {label} : null;

    if (this.isSelect()) {
      let options = placeholder && !defaultValue ? [<option disabled key={idgen()}>{placeholder}</option>] : [];
      options = options.concat(React.Children.map(children, (child) => {
        return React.cloneElement(child, {'key': child.props.value});
      }));
      return (

          {htmlLabel}
          <select
            id={id}
            className={cx(inputClasses)}
            ref='inputEl'
            value={this.state.value}
            {...props}
          >
            { options }
          </select>

      );
    } else if (type === 'switch') {
      return (

            Off
            <input type="checkbox" name={this.props.name} {...props} />

            On

      );
    }
    else {
      let icon = null;
      if (React.Children.count(children) == 1) {
        icon = React.Children.only(children);
      }
      return (

            {icon === null ? null : React.cloneElement(icon, {className: 'prefix'})}
            <C
                id={id}
                className={cx(inputClasses)}
                onChange={this._onChange}
                placeholder={placeholder}
                ref='inputEl'
                type={inputType}
                value={this.state.value}
                {...props}
            />
            {htmlLabel}

      );
    }
  }

  isSelect() {
    return this.props.type === 'select';
  }

  isMaterialSelect() {
    return this.props.type === 'select' && !this.props.browserDefault && typeof $ !== 'undefined';
  }
}

Input.propTypes = {
  s: React.PropTypes.number,
  m: React.PropTypes.number,
  l: React.PropTypes.number,
  label: React.PropTypes.node,
  /**
   * Input field type, e.g. select, checkbox, radio, text, tel, email
   * @default 'text'
   */
  type: React.PropTypes.string,
  defaultValue: React.PropTypes.string,
  placeholder: React.PropTypes.string,
  id: React.PropTypes.string,
  name: React.PropTypes.string,
  validate: React.PropTypes.bool,
  browserDefault: React.PropTypes.bool,
  onChange: React.PropTypes.func
};

Input.defaultProps = {type: 'text'};

export default Input;
<commit_msg>Add onChange listener to switch inputs<commit_after>import React from 'react';
import cx from 'classnames';
import idgen from './idgen';
import constants from './constants';

class Input extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: this.props.defaultValue};
    this._onChange = this._onChange.bind(this);
    this.isSelect = this.isSelect.bind(this);
  }

  componentDidMount() {
    if (this.isMaterialSelect()) {
      $(this.refs.inputEl).material_select();
      $(this.refs.inputEl).on('change', this._onChange);
    }
  }

  componentDidUpdate(prevProps, prevState) {
    if (this.isMaterialSelect()) {
      $(this.refs.inputEl).material_select();
    }
  }

  componentWillReceiveProps(nextProps) {
    if (this.isMaterialSelect()) {
      this.setState({
        value: nextProps.defaultValue
      }, () => $(this.refs.inputEl).material_select());
    }
  }

  componentWillUnmount() {
    if (this.isMaterialSelect()) {
      $(this.refs.inputEl).off('change', this._onChange);
    }
  }

  _onChange(e) {
    this.setState({
      value: e.target.value
    });
    if (this.props.onChange) {
      this.props.onChange(e);
    }
  }

  render() {
    let { defaultValue, placeholder, id, type, label, children, validate, onChange, ...props} = this.props;
    let classes = {
      col: true,
      'input-field': type !== 'checkbox' && type !== 'radio'
    };
    constants.SIZES.forEach(size => {
      if (this.props[size]) {
        classes[size + this.props[size]] = true;
      }
    });
    if (!id) {
      id = `input_${idgen()}`;
    }
    let inputClasses = {
      validate
    };
    let C, inputType;
    switch (type) {
      case 'textarea':
        C = 'textarea';
        inputClasses['materialize-textarea'] = true;
        break;
      case 'switch':
        C = 'input';
        inputType = 'checkbox';
        break;
      default:
        C = 'input';
        inputType = type || 'text';
    }
    let labelClasses = {
      active: this.state.value || this.isSelect()
    };

    let htmlLabel = label ? {label} : null;

    if (this.isSelect()) {
      let options = placeholder && !defaultValue ? [<option disabled key={idgen()}>{placeholder}</option>] : [];
      options = options.concat(React.Children.map(children, (child) => {
        return React.cloneElement(child, {'key': child.props.value});
      }));
      return (

          {htmlLabel}
          <select
            id={id}
            className={cx(inputClasses)}
            ref='inputEl'
            value={this.state.value}
            {...props}
          >
            { options }
          </select>

      );
    } else if (type === 'switch') {
      return (

            Off
            <input
              name={this.props.name}
              onChange={this._onChange}
              type="checkbox"
              {...props}
            />

            On

      );
    }
    else {
      let icon = null;
      if (React.Children.count(children) == 1) {
        icon = React.Children.only(children);
      }
      return (

            {icon === null ? null : React.cloneElement(icon, {className: 'prefix'})}
            <C
                id={id}
                className={cx(inputClasses)}
                onChange={this._onChange}
                placeholder={placeholder}
                ref='inputEl'
                type={inputType}
                value={this.state.value}
                {...props}
            />
            {htmlLabel}

      );
    }
  }

  isSelect() {
    return this.props.type === 'select';
  }

  isMaterialSelect() {
    return this.props.type === 'select' && !this.props.browserDefault && typeof $ !== 'undefined';
  }
}

Input.propTypes = {
  s: React.PropTypes.number,
  m: React.PropTypes.number,
  l: React.PropTypes.number,
  label: React.PropTypes.node,
  /**
   * Input field type, e.g. select, checkbox, radio, text, tel, email
   * @default 'text'
   */
  type: React.PropTypes.string,
  defaultValue: React.PropTypes.string,
  placeholder: React.PropTypes.string,
  id: React.PropTypes.string,
  name: React.PropTypes.string,
  validate: React.PropTypes.bool,
  browserDefault: React.PropTypes.bool,
  onChange: React.PropTypes.func
};

Input.defaultProps = {type: 'text'};

export default Input;
<|endoftext|>


<commit_before>function addNeo(graph, data) {
	console.log("addNeo",graph,data)
    function addNode(id) {
        if (!id || typeof id == "undefined") return null;
		var node = graph.getNode(id);
		if (node) return node;
		node = new Node(id);
//	  	node.position.x = Math.random()*1000;
//	  	node.position.y = Math.random()*500;
	  	node.data.title = id;
        graph.addNode(node);
        return node;
    }
    for (n in data.edges) {
        if (data.edges[n].source) {
            addNode(data.edges[n].source);
        }
        if (data.edges[n].target) {
            addNode(data.edges[n].target);
        }
    }

	var added = 0;
    for (n in data.edges) {
        var edge=data.edges[n];
		if (!edge.source || !edge.target) continue;
        var n1 = graph.getNode(edge.source);
        var n2 = graph.getNode(edge.target);
        if (n1.connectedTo(n2) || n2.connectedTo(n1)) continue;
		graph.addEdge(n1,n2);
		added ++;
    }
    if (added > 0) {
		graph.createLayout();
	}
}

function loadGraph(graph,cb) {
    $.ajax("/edges", {
        type:"GET",
        dataType:"json",
        success:function (res) {
            addNeo(graph, {edges:res});
            cb();
        }
    })
}

function isTag(id) {
	return /^::/.test(id);
}
function loadData(graph,id) {
	console.log("loadData",graph,id)
	var url = "/edges/"+id;
	console.log(url)
    $.ajax(url, {
        type:"GET",
        dataType:"json",
        success:function (res) {
            addNeo(graph, {edges:res});
        }
    })
}

var timeout;
function showSelection(graph,obj) {
	if (obj==null) clearTimeout(timeout);
	else {
		timeout = setTimeout(function () {
            showBox(obj.node);
        }, 250);
	}
//	console.log("selection",obj)

}

var last;
function showClick(graph,obj) {
	console.log("click",graph,obj)
	if (obj!=last) {
	    loadData(graph,obj.node.id);
		showBox(obj.node)
		obj.scale.x=2;
		obj.scale.y=2;
		if (last) {
			last.scale.x=1;
			last.scale.y=1;
		}
		last=obj;
	}
}

var showBox = function (node) {
    var t = $("#hoveredName").empty();
    if (!node) return;
    var id = node['id'];
    if (id.match(/^::/)) {
        id = "#" + id.substring(2);
        t.text(id).append(n).show();
    } else {
        var n = '
';
        t.empty().text("@" + id).append(n).show()
    }
    $.ajax("/tweets/" + node['id'], {
        type:"GET",
        dataType:"json",
        success:function (res) {
            console.log("tweets", res);
            for (var n=0;n<res.length;n++) {
                $("
" + res[n].text + "
").appendTo(t)
            }
        }});
};

<commit_msg>initial set, and adding recent tweets<commit_after>function addNeo(graph, data) {
	console.log("addNeo",graph,data)
    function addNode(id) {
        if (!id || typeof id == "undefined") return null;
		var node = graph.getNode(id);
		if (node) return node;
		node = new Node(id);
//	  	node.position.x = Math.random()*1000;
//	  	node.position.y = Math.random()*500;
	  	node.data.title = id;
        graph.addNode(node);
        return node;
    }
    for (n in data.edges) {
        if (data.edges[n].source) {
            addNode(data.edges[n].source);
        }
        if (data.edges[n].target) {
            addNode(data.edges[n].target);
        }
    }

	var added = 0;
    for (n in data.edges) {
        var edge=data.edges[n];
		if (!edge.source || !edge.target) continue;
        var n1 = graph.getNode(edge.source);
        var n2 = graph.getNode(edge.target);
        if (n1.connectedTo(n2) || n2.connectedTo(n1)) continue;
		graph.addEdge(n1,n2);
		added ++;
    }
    if (added > 0) {
		graph.createLayout();
	}
}

function addRecent(graph) {
    $.ajax("/recent", {
        type:"GET",
        dataType:"json",
        success:function (res) {
            addNeo(graph, {edges:res});
        }
    })
}

function loadGraph(graph,cb) {
    $.ajax("/edges/::waza", {
        type:"GET",
        dataType:"json",
        success:function (res) {
            addNeo(graph, {edges:res});
            cb();
        }
    })
	setInterval(function() {addRecent(graph)},10000);
}

function isTag(id) {
	return /^::/.test(id);
}
function loadData(graph,id) {
	console.log("loadData",graph,id)
	var url = "/edges/"+id;
	console.log(url)
    $.ajax(url, {
        type:"GET",
        dataType:"json",
        success:function (res) {
            addNeo(graph, {edges:res});
        }
    })
}

var timeout;
function showSelection(graph,obj) {
	if (obj==null) clearTimeout(timeout);
	else {
		timeout = setTimeout(function () {
            showBox(obj.node);
        }, 250);
	}
//	console.log("selection",obj)

}

var last;
function showClick(graph,obj) {
	console.log("click",graph,obj)
	if (obj!=last) {
	    loadData(graph,obj.node.id);
		showBox(obj.node)
		obj.scale.x=2;
		obj.scale.y=2;
		if (last) {
			last.scale.x=1;
			last.scale.y=1;
		}
		last=obj;
	}
}

var showBox = function (node) {
    var t = $("#hoveredName").empty();
    if (!node) return;
    var id = node['id'];
    if (id.match(/^::/)) {
        id = "#" + id.substring(2);
        t.text(id).append(n).show();
    } else {
        var n = '
';
        t.empty().text("@" + id).append(n).show()
    }
    $.ajax("/tweets/" + node['id'], {
        type:"GET",
        dataType:"json",
        success:function (res) {
            console.log("tweets", res);
            for (var n=0;n<res.length;n++) {
                $("
" + res[n].text + "
").appendTo(t)
            }
        }});
};
<|endoftext|>


<commit_before>module.exports = function() {
	return {
		start: function() {
			start();
		}
	};

	function start() {
		var schedule = require('node-schedule');
		var fs = require('fs');
		var i = 0;
		var job = schedule.scheduleJob('42 * * * * *', function() {
			fs.readdir(__rootDir + '/static/uploads', function(err, files) {
				files.map(function(file) {
					fs.stat(__rootDir + '/static/uploads/' + file, function(err, stats) {
						if ((Date.now() - stats.mtime) / 1000 / 60 / 60 / 24 > 30) {
							fs.unlink(__rootDir + '/static/uploads/' + file, function(err) {
								if(err) {
									console.error('unable to delete image ' + file);
								}
							});
						}
					});
				});
			});
		});
	}
};
<commit_msg>fix scheduler crash<commit_after>module.exports = function() {
	return {
		start: function() {
			start();
		}
	};

	function start() {
		var schedule = require('node-schedule');
		var fs = require('fs');
		var path = __rootDir + '/static/uploads';
		var job = schedule.scheduleJob('42 * * * * *', function() {
			fs.readdir(path, function(err, files) {
				if (!err) {
					files.map(function(file) {
						fs.stat(path + file, function(err, stats) {
							if ((Date.now() - stats.mtime) / 1000 / 60 / 60 / 24 > 30) {
								fs.unlink(path + file, function(err) {
									if (err) {
										console.error('unable to delete image ' + file);
									}
								});
							}
						});
					});
				}
			});
		});
	}
};
<|endoftext|>