<commit_before>var DataManagerUtils = function (schema) {

    this.schema = schema;
    this.widget = schema.widget;

};

DataManagerUtils.prototype = {
    /**
     *
     * @param {(OpenLayers.Feature | OpenLayers.Feature.Vector)} olFeature
     * @private
     */
    processCurrentFormItemsWithDataManager: function (olFeature) {
        var widget = this.widget;
        var schema = this.schema;

        // dataManager access function
        // TODO: maybe it would be better to create public methods on dataManager to do this
        function withSchema(dataManager, schemaName, callback) {
            var schema = dataManager.options.schemes[schemaName];
            // FIXME: following lines are a hack to get dataManager to open the correct popup
            // (it does open the popup for the scheme provided in currentSettings, not
            // the one passed to the _openEditPopup function)
            var prevSettings = dataManager.currentSettings;
            var prevActiveSchema = dataManager.activeSchema;
            dataManager.activeSchema = dataManager.currentSettings = schema;

            dataManager._getData(schema).then(function () {
                callback(schema);
                dataManager.currentSettings = prevSettings;
                dataManager.activeSchema = prevActiveSchema;
            });
        }

        DataUtil.eachItem(schema.formItems, function (item) {

            if (item.type === "resultTable" && item.editable && !item.isProcessed) {
                var onCreateClick;
                var onEditClick;

                if (!item.hasOwnProperty('dataManagerLink')) {
                    onCreateClick = function (e) {
                        e.preventDefault();
                        var item = $(this).next().data("item");
                        var popup = item.popupItems;
                        var table = $(this).siblings(".mapbender-element-result-table")
                        var uniqueIdKey = item.dataStore.uniqueId;

                        var feature = table.data('olFeature');
                        var data = {};

                        item.allowRemove = false;
                        data['linkId'] = feature.attributes[item.dataStoreLink.uniqueId];
                        data.item = item;
                        data[uniqueIdKey] = null;
                        widget._openEditDialog(data, popup, item, table);
                        return false;
                    };

                    onEditClick = function (rowData, ui, e) {
                        e.defaultPrevented && e.defaultPrevented();
                        e.preventDefault && e.preventDefault();

                        var table = ui.parents('.mapbender-element-result-table');
                        var item = table.data('item');
                        var popup = item.popupItems;
                        var feature = table.data('olFeature');

                        item.allowRemove = true;
                        rowData.externalId = feature.attributes[item.dataStoreLink.uniqueId];

                        widget._openEditDialog(rowData, popup, item, table);

                        return false;
                    };
                } else if (item.hasOwnProperty('dataManagerLink')) {
                    var schemaName = item.dataManagerLink.schema;
                    var fieldName = item.dataManagerLink.fieldName;
                    var schemaFieldName = item.dataManagerLink.schemaFieldName;

                    onCreateClick = function (e) {
                        e.preventDefault && e.preventDefault();

                        var dm = Mapbender.elementRegistry.listWidgets()['mapbenderMbDataManager'];
                        withSchema(dm, schemaName, function (schema) {
                            dm._openEditDialog(schema.create());
                        });

                        return false;
                    };

                    onEditClick = function (rowData, ui, e) {
                        e.defaultPrevented && e.defaultPrevented();
                        e.preventDefault && e.preventDefault();

                        var dm = Mapbender.elementRegistry.listWidgets()['mapbenderMbDataManager'];

                        withSchema(dm, schemaName, function (schema) {
                            var dataItem = _.find(schema.dataItems, function (d) {
                                return d[schemaFieldName] === rowData[fieldName];
                            });
                            dm._openEditDialog(dataItem);
                        });

                        return false;
                    };
                }

                var cloneItem = $.extend({}, item);
                cloneItem.isProcessed = true;
                item.type = "container";
                var button = {
                    type: "button",
                    title: "",
                    cssClass: "fa fa-plus",
                    click: onCreateClick
                };

                item.children = [button, cloneItem];

                var buttons = [];

                buttons.push({
                    title: Mapbender.DigitizerTranslator.translate('feature.edit'),
                    className: 'edit',
                    onClick: onEditClick
                });

                cloneItem.buttons = buttons;

            }

            if (item.type === "select" && !item.isProcessed && ((item.dataStore && item.dataStore.editable && item.dataStore.popupItems) || item.dataManagerLink)) {
                var onCreateClick;
                var onEditClick;

                if (item.dataManagerLink) {
                    var schemaName = item.dataManagerLink.schema;
                    var schemaFieldName = item.dataManagerLink.schemaFieldName;

                    onCreateClick = function (e) {
                        e.preventDefault && e.preventDefault();

                        var dm = Mapbender.elementRegistry.listWidgets()['mapbenderMbDataManager'];
                        withSchema(dm, schemaName, function (schema) {
                            dm._openEditDialog(schema.create());

                        });
                        $(dm.element).on('data.manager.item.saved', function (event, eventData) {
                            var uniqueIdKey = eventData.uniqueIdKey;
                            var text = item.itemPattern.replace('{id}', eventData.item[uniqueIdKey]).replace('{name}', eventData.item[item.itemName]);
                            var $option = $('<option />').val(eventData.item[uniqueIdKey]).text(text);
                            var $select = $('select[name=' + item.name + ']').append($option);
                            $select.val(eventData.item[uniqueIdKey]);
                        });
                        return false;
                    };

                    onEditClick = function (e) {
                        e.preventDefault && e.preventDefault();

                        var val = $(this).siblings().find('select').val();
                        var dm = Mapbender.elementRegistry.listWidgets()['mapbenderMbDataManager'];
                        withSchema(dm, schemaName, function (schema) {
                            var dataItem = _.find(schema.dataItems, function (d) {
                                return d[schemaFieldName].toString() === val;
                            });
                            var dialog = dm._openEditDialog(dataItem);

                        });

                        return false;
                    };
                } else {
                    onCreateClick = function () {
                        var dataItemId = $(this).siblings().find('select').val();
                        var selectRef = $(this).siblings().find('select');

                        var dataStoreId = item.dataStore.id;
                        QueryEngine.query("datastore/get", {
                            schema: schema.schemaName,
                            id: dataStoreId,
                            dataItemId: dataItemId
                        }).done(function (data) {
                            widget._openEditDialog(data, item.dataStore.popupItems, item, selectRef);

                        });

                        return false;
                    };

                    onEditClick = function () {
                        var selectRef = $(this).siblings().find('select');
                        widget._openEditDialog({}, item.dataStore.popupItems, item, selectRef);

                        return false;
                    };
                }

                var cloneItem = $.extend({}, item);
                cloneItem.isProcessed = true;
                item.type = "fieldSet";
                item.title = undefined;
                item.children = [
                    cloneItem,
                    {
                        type: "button",
                        title: Mapbender.DigitizerTranslator.translate('feature.edit'),
                        cssClass: 'edit',
                        click: onEditClick
                    },
                    {
                        type: "button",
                        title: "",
                        cssClass: "fa fa-plus",
                        click: onCreateClick
                    }
                ];
            }

            if (item.type === "file") {
                item.uploadHanderUrl = widget.elementUrl + "file/upload?schema=" + schema.schemaName + "&fid=" + olFeature.fid + "&field=" + item.name;
                if (item.hasOwnProperty("name") && olFeature.data.hasOwnProperty(item.name) && olFeature.data[item.name]) {
                    item.dbSrc = olFeature.data[item.name];
                    if (schema.featureType.files) {
                        $.each(schema.featureType.files, function (k, fileInfo) {
                            if (fileInfo.field && fileInfo.field == item.name) {
                                if (fileInfo.formats) {
                                    item.accept = fileInfo.formats;
                                }
                            }
                        });
                    }
                }

            }

            if (item.type === 'image') {

                if (!item.origSrc) {
                    item.origSrc = item.src;
                }

                if (item.hasOwnProperty("name") && olFeature.data.hasOwnProperty(item.name) && olFeature.data[item.name]) {
                    item.dbSrc = olFeature.data[item.name];
                    if (schema.featureType.files) {
                        $.each(schema.featureType.files, function (k, fileInfo) {
                            if (fileInfo.field && fileInfo.field == item.name) {

                                if (fileInfo.uri) {
                                    item.dbSrc = fileInfo.uri + "/" + item.dbSrc;
                                } else {
                                    item.dbSrc = widget.options.fileUri + "/" + schema.featureType.table + "/" + item.name + "/" + item.dbSrc;
                                }
                            }
                        });
                    }
                }

                var src = item.dbSrc || item.origSrc;
                if (!item.hasOwnProperty('relative') && !item.relative) {
                    item.src = src;
                } else {
                    item.src = Mapbender.configuration.application.urls.asset + src;
                }
            }
        });
    },

    /**
     *
     * @param dataItem
     * @param formItems
     * @param {Scheme} schema
     * @param ref
     * @returns {*|jQuery|HTMLElement}
     * @private
     */
    _openEditDialog: function (dataItem, formItems, schema, ref) {
        var widget = this.widget;
        var schema = this.schema;

        var schemaName = schema.schemaName;
        var uniqueKey = schema.dataStore.uniqueId;
        var textKey = schema.dataStore.text;
        var buttons = [];

        if (widget.currentPopup.currentPopup) {
            widget.currentPopup.currentPopup.popupDialog('close');
            widget.currentPopup.currentPopup = null;
        }

        var saveButton = {
            text: Mapbender.DigitizerTranslator.translate("feature.save", false),
            click: function () {
                widget.saveForeignDataStoreItem(dataItem);
            }
        };
        buttons.push(saveButton);

        buttons.push({

            text: Mapbender.DigitizerTranslator.translate("feature.remove.title", false),
            class: 'critical',
            click: function () {

                var uniqueIdKey = schema.dataStore.uniqueId;
                QueryEngine.query('datastore/remove', {
                    schema: dataItem.item.dataStoreLink.name,
                    dataItemId: dataItem[uniqueIdKey],
                    dataStoreLinkFieldName: schema.dataStoreLink.fieldName,
                    linkId: dataItem[dataItem.item.dataStoreLink.fieldName]

                }).done(function (response) {

                    if (response.processedItem.hasOwnProperty('errors')) {
                        $(dialog).enableForm();
                        $.each(response.errors, function (i, error) {
                            $.notify(error.message, {
                                title: 'API Error',
                                autoHide: false,
                                className: 'error'
                            });
                            console.error(error.message);
                        });
                        return;
                    }
                    var data = response.dataItems;
                    var tableApi = $(dialog).data('table').resultTable('getApi');
                    var item = $(dialog).data('table').data('item');
                    if (Object.prototype.toString.call(data) === '[object Array]') {
                        var a = [];
                        _.each(data, function (e, i) {
                            if (e.hasOwnProperty('attributes')) {
                                e.attributes.item = item;
                                a.push(e.attributes);
                            }
                        });

                        data = a;

                    } else {
                        if (data.hasOwnProperty('attributes')) {
                            data = [data.attributes];

                        }

                    }
                    tableApi.clear();
                    tableApi.rows.add(data);
                    tableApi.draw();
                    widget.currentPopup.currentPopup.popupDialog('close');
                    widget.currentPopup.currentPopup = null;
                    $.notify(Mapbender.DigitizerTranslator.translate("feature.remove.successfully", false), 'info');

                })
            }
        });

        buttons.push({
            text: Mapbender.DigitizerTranslator.translate("cancel"),
            click: function () {
                widget.currentPopup.currentPopup.popupDialog('close');
                widget.currentPopup.currentPopup = null;
            }
        });

        var dialog = $("<div/>");
        dialog.on("popupdialogopen", function (event, ui) {
            setTimeout(function () {
                dialog.formData(dataItem);

            }, 1);
        });

        DataUtil.eachItem(schema.formItems, function (item) {
            if (item.type === "file") {
                item.uploadHanderUrl = widget.elementUrl + "file-upload?schema=" + schema.schemaName + "&fid=" + dataItem.fid + "&field=" + item.name;
                if (item.hasOwnProperty("name") && dataItem.data.hasOwnProperty(item.name) && dataItem.data[item.name]) {
                    item.dbSrc = dataItem.data[item.name];
                    if (schema.featureType.files) {
                        $.each(schema.featureType.files, function (k, fileInfo) {
                            if (fileInfo.field && fileInfo.field == item.name) {
                                if (fileInfo.formats) {
                                    item.accept = fileInfo.formats;
                                }
                            }
                        });
                    }
                }

            }

            if (item.type === 'image') {

                if (!item.origSrc) {
                    item.origSrc = item.src;
                }

                if (item.hasOwnProperty("name") && dataItem.data.hasOwnProperty(item.name) && dataItem.data[item.name]) {
                    item.dbSrc = dataItem.data[item.name];
                    if (schema.featureType.files) {
                        $.each(schema.featureType.files, function (k, fileInfo) {
                            if (fileInfo.field && fileInfo.field === item.name) {

                                if (fileInfo.uri) {
                                    item.dbSrc = fileInfo.uri + "/" + item.dbSrc;
                                } else {
                                }
                            }
                        });
                    }
                }

                var src = item.dbSrc ? item.dbSrc : item.origSrc;
                if (item.relative) {
                    item.src = src.match(/^(http[s]?\:|\/{2})/) ? src : Mapbender.configuration.application.urls.asset + src;
                } else {
                    item.src = src;
                }
            }

        });
        /*  if(schema.popup.buttons) {
         buttons = _.union(schema.popup.buttons, buttons);
         } */
        var popupConfig = _.extend({

            title: Mapbender.DigitizerTranslator.translate("feature.attributes"),

            width: widget.featureEditDialogWidth,
        }, schema.popup);

        popupConfig.buttons = buttons;

        dialog.generateElements({children: formItems});
        dialog.popupDialog(popupConfig);
        dialog.addClass("data-store-edit-data");
        widget.currentPopup.currentPopup = dialog;
        dialog.parentDialog = widget.currentPopup;
        dialog.data('schema', schema);
        dialog.data('table', ref);

        return dialog;
    },

    /**
     *
     * @param dataItem
     * @returns {boolean}
     */

    saveForeignDataStoreItem: function (dataItem) {

        var widget = this.widget;
        var dialog = widget.currentPopup.currentPopup;
        var uniqueIdKey = dataItem.item.dataStore.uniqueId;
        var isNew = dataItem[uniqueIdKey] === null;
        var formData = dialog.formData();
        var schema = dialog.data('schema');
        debugger;
        if (!isNew) {

            formData[uniqueIdKey] = dataItem[uniqueIdKey];
            dataItem['linkId'] = dataItem[schema.dataStoreLink.fieldName];

        } else {
            delete formData[uniqueIdKey];

            formData[schema.dataStoreLink.fieldName] = dataItem.linkId;

        }
        var errorInputs = $(".has-error", dialog);
        var hasErrors = errorInputs.size() > 0;
        if (hasErrors) {
            return false;

        }

        $(dialog).disableForm();

        QueryEngine.query('datastore/save', {
            schema: dataItem.item.dataStoreLink.name,
            dataItem: formData,
            dataItemId: dataItem[uniqueIdKey],
            linkId: dataItem.linkId,
            dataStoreLinkFieldName: schema.dataStoreLink.fieldName
        }).done(function (response) {
            if (response.processedItem.hasOwnProperty('errors')) {
                $(dialog).enableForm();
                $.each(response.errors, function (i, error) {
                    $.notify(error.message, {
                        title: 'API Error',
                        autoHide: false,
                        className: 'error'
                    });
                    console.error(error.message);
                });
                return;
            }
            var data = response.dataItems;
            var tableApi = $(dialog).data('table').resultTable('getApi');
            var item = $(dialog).data('table').data('item');
            if (Object.prototype.toString.call(data) === '[object Array]') {
                var a = [];
                _.each(data, function (e, i) {
                    if (e.hasOwnProperty('attributes')) {
                        e.attributes.item = item;
                        a.push(e.attributes);
                    }
                });

                data = a;

            } else {
                if (data.hasOwnProperty('attributes')) {
                    data = [data.attributes];

                }

            }
            tableApi.clear();
            tableApi.rows.add(data);
            tableApi.draw();

            widget.currentPopup.currentPopup.popupDialog('close');
            widget.currentPopup.currentPopup = null;
            $(dialog).enableForm();
            $.notify(Mapbender.DigitizerTranslator.translate("feature.save.successfully", false), 'info');
        });

    }

};
<commit_msg>Transfer Method WithSchema to DataManager<commit_after>var DataManagerUtils = function (schema) {

    this.schema = schema;
    this.widget = schema.widget;

};

DataManagerUtils.prototype = {
    /**
     *
     * @param {(OpenLayers.Feature | OpenLayers.Feature.Vector)} olFeature
     * @private
     */
    processCurrentFormItemsWithDataManager: function (olFeature) {
        var widget = this.widget;
        var schema = this.schema;

        DataUtil.eachItem(schema.formItems, function (item) {

            if (item.type === "resultTable" && item.editable && !item.isProcessed) {
                var onCreateClick;
                var onEditClick;

                if (!item.hasOwnProperty('dataManagerLink')) {
                    onCreateClick = function (e) {
                        e.preventDefault();
                        var item = $(this).next().data("item");
                        var popup = item.popupItems;
                        var table = $(this).siblings(".mapbender-element-result-table")
                        var uniqueIdKey = item.dataStore.uniqueId;

                        var feature = table.data('olFeature');
                        var data = {};

                        item.allowRemove = false;
                        data['linkId'] = feature.attributes[item.dataStoreLink.uniqueId];
                        data.item = item;
                        data[uniqueIdKey] = null;
                        widget._openEditDialog(data, popup, item, table);
                        return false;
                    };

                    onEditClick = function (rowData, ui, e) {
                        e.defaultPrevented && e.defaultPrevented();
                        e.preventDefault && e.preventDefault();

                        var table = ui.parents('.mapbender-element-result-table');
                        var item = table.data('item');
                        var popup = item.popupItems;
                        var feature = table.data('olFeature');

                        item.allowRemove = true;
                        rowData.externalId = feature.attributes[item.dataStoreLink.uniqueId];

                        widget._openEditDialog(rowData, popup, item, table);

                        return false;
                    };
                } else if (item.hasOwnProperty('dataManagerLink')) {
                    var schemaName = item.dataManagerLink.schema;
                    var fieldName = item.dataManagerLink.fieldName;
                    var schemaFieldName = item.dataManagerLink.schemaFieldName;

                    onCreateClick = function (e) {
                        e.preventDefault && e.preventDefault();

                        var dm = Mapbender.elementRegistry.listWidgets()['mapbenderMbDataManager'];
                        dm.withSchema(schemaName, function (schema) {
                            dm._openEditDialog(schema.create());
                        });

                        return false;
                    };

                    onEditClick = function (rowData, ui, e) {
                        e.defaultPrevented && e.defaultPrevented();
                        e.preventDefault && e.preventDefault();

                        var dm = Mapbender.elementRegistry.listWidgets()['mapbenderMbDataManager'];

                        dm.withSchema(schemaName, function (schema) {
                            var dataItem = _.find(schema.dataItems, function (d) {
                                return d[schemaFieldName] === rowData[fieldName];
                            });
                            dm._openEditDialog(dataItem);
                        });

                        return false;
                    };
                }

                var cloneItem = $.extend({}, item);
                cloneItem.isProcessed = true;
                item.type = "container";
                var button = {
                    type: "button",
                    title: "",
                    cssClass: "fa fa-plus",
                    click: onCreateClick
                };

                item.children = [button, cloneItem];

                var buttons = [];

                buttons.push({
                    title: Mapbender.DigitizerTranslator.translate('feature.edit'),
                    className: 'edit',
                    onClick: onEditClick
                });

                cloneItem.buttons = buttons;

            }

            if (item.type === "select" && !item.isProcessed && ((item.dataStore && item.dataStore.editable && item.dataStore.popupItems) || item.dataManagerLink)) {
                var onCreateClick;
                var onEditClick;

                if (item.dataManagerLink) {
                    var schemaName = item.dataManagerLink.schema;
                    var schemaFieldName = item.dataManagerLink.schemaFieldName;

                    onCreateClick = function (e) {
                        e.preventDefault && e.preventDefault();

                        var dm = Mapbender.elementRegistry.listWidgets()['mapbenderMbDataManager'];
                        dm.withSchema(schemaName, function (schema) {
                            dm._openEditDialog(schema.create());

                        });
                        $(dm.element).on('data.manager.item.saved', function (event, eventData) {
                            var uniqueIdKey = eventData.uniqueIdKey;
                            var text = item.itemPattern.replace('{id}', eventData.item[uniqueIdKey]).replace('{name}', eventData.item[item.itemName]);
                            var $option = $('<option />').val(eventData.item[uniqueIdKey]).text(text);
                            var $select = $('select[name=' + item.name + ']').append($option);
                            $select.val(eventData.item[uniqueIdKey]);
                        });
                        return false;
                    };

                    onEditClick = function (e) {
                        e.preventDefault && e.preventDefault();

                        var val = $(this).siblings().find('select').val();
                        var dm = Mapbender.elementRegistry.listWidgets()['mapbenderMbDataManager'];
                        dm.withSchema(schemaName, function (schema) {
                            var dataItem = _.find(schema.dataItems, function (d) {
                                return d[schemaFieldName].toString() === val;
                            });
                            var dialog = dm._openEditDialog(dataItem);

                        });

                        return false;
                    };
                } else {
                    onCreateClick = function () {
                        var dataItemId = $(this).siblings().find('select').val();
                        var selectRef = $(this).siblings().find('select');

                        var dataStoreId = item.dataStore.id;
                        QueryEngine.query("datastore/get", {
                            schema: schema.schemaName,
                            id: dataStoreId,
                            dataItemId: dataItemId
                        }).done(function (data) {
                            widget._openEditDialog(data, item.dataStore.popupItems, item, selectRef);

                        });

                        return false;
                    };

                    onEditClick = function () {
                        var selectRef = $(this).siblings().find('select');
                        widget._openEditDialog({}, item.dataStore.popupItems, item, selectRef);

                        return false;
                    };
                }

                var cloneItem = $.extend({}, item);
                cloneItem.isProcessed = true;
                item.type = "fieldSet";
                item.title = undefined;
                item.children = [
                    cloneItem,
                    {
                        type: "button",
                        title: Mapbender.DigitizerTranslator.translate('feature.edit'),
                        cssClass: 'edit',
                        click: onEditClick
                    },
                    {
                        type: "button",
                        title: "",
                        cssClass: "fa fa-plus",
                        click: onCreateClick
                    }
                ];
            }

            if (item.type === "file") {
                item.uploadHanderUrl = widget.elementUrl + "file/upload?schema=" + schema.schemaName + "&fid=" + olFeature.fid + "&field=" + item.name;
                if (item.hasOwnProperty("name") && olFeature.data.hasOwnProperty(item.name) && olFeature.data[item.name]) {
                    item.dbSrc = olFeature.data[item.name];
                    if (schema.featureType.files) {
                        $.each(schema.featureType.files, function (k, fileInfo) {
                            if (fileInfo.field && fileInfo.field == item.name) {
                                if (fileInfo.formats) {
                                    item.accept = fileInfo.formats;
                                }
                            }
                        });
                    }
                }

            }

            if (item.type === 'image') {

                if (!item.origSrc) {
                    item.origSrc = item.src;
                }

                if (item.hasOwnProperty("name") && olFeature.data.hasOwnProperty(item.name) && olFeature.data[item.name]) {
                    item.dbSrc = olFeature.data[item.name];
                    if (schema.featureType.files) {
                        $.each(schema.featureType.files, function (k, fileInfo) {
                            if (fileInfo.field && fileInfo.field == item.name) {

                                if (fileInfo.uri) {
                                    item.dbSrc = fileInfo.uri + "/" + item.dbSrc;
                                } else {
                                    item.dbSrc = widget.options.fileUri + "/" + schema.featureType.table + "/" + item.name + "/" + item.dbSrc;
                                }
                            }
                        });
                    }
                }

                var src = item.dbSrc || item.origSrc;
                if (!item.hasOwnProperty('relative') && !item.relative) {
                    item.src = src;
                } else {
                    item.src = Mapbender.configuration.application.urls.asset + src;
                }
            }
        });
    },

    /**
     *
     * @param dataItem
     * @param formItems
     * @param {Scheme} schema
     * @param ref
     * @returns {*|jQuery|HTMLElement}
     * @private
     */
    _openEditDialog: function (dataItem, formItems, schema, ref) {
        var widget = this.widget;
        var schema = this.schema;

        var schemaName = schema.schemaName;
        var uniqueKey = schema.dataStore.uniqueId;
        var textKey = schema.dataStore.text;
        var buttons = [];

        if (widget.currentPopup.currentPopup) {
            widget.currentPopup.currentPopup.popupDialog('close');
            widget.currentPopup.currentPopup = null;
        }

        var saveButton = {
            text: Mapbender.DigitizerTranslator.translate("feature.save", false),
            click: function () {
                widget.saveForeignDataStoreItem(dataItem);
            }
        };
        buttons.push(saveButton);

        buttons.push({

            text: Mapbender.DigitizerTranslator.translate("feature.remove.title", false),
            class: 'critical',
            click: function () {

                var uniqueIdKey = schema.dataStore.uniqueId;
                QueryEngine.query('datastore/remove', {
                    schema: dataItem.item.dataStoreLink.name,
                    dataItemId: dataItem[uniqueIdKey],
                    dataStoreLinkFieldName: schema.dataStoreLink.fieldName,
                    linkId: dataItem[dataItem.item.dataStoreLink.fieldName]

                }).done(function (response) {

                    if (response.processedItem.hasOwnProperty('errors')) {
                        $(dialog).enableForm();
                        $.each(response.errors, function (i, error) {
                            $.notify(error.message, {
                                title: 'API Error',
                                autoHide: false,
                                className: 'error'
                            });
                            console.error(error.message);
                        });
                        return;
                    }
                    var data = response.dataItems;
                    var tableApi = $(dialog).data('table').resultTable('getApi');
                    var item = $(dialog).data('table').data('item');
                    if (Object.prototype.toString.call(data) === '[object Array]') {
                        var a = [];
                        _.each(data, function (e, i) {
                            if (e.hasOwnProperty('attributes')) {
                                e.attributes.item = item;
                                a.push(e.attributes);
                            }
                        });

                        data = a;

                    } else {
                        if (data.hasOwnProperty('attributes')) {
                            data = [data.attributes];

                        }

                    }
                    tableApi.clear();
                    tableApi.rows.add(data);
                    tableApi.draw();
                    widget.currentPopup.currentPopup.popupDialog('close');
                    widget.currentPopup.currentPopup = null;
                    $.notify(Mapbender.DigitizerTranslator.translate("feature.remove.successfully", false), 'info');

                })
            }
        });

        buttons.push({
            text: Mapbender.DigitizerTranslator.translate("cancel"),
            click: function () {
                widget.currentPopup.currentPopup.popupDialog('close');
                widget.currentPopup.currentPopup = null;
            }
        });

        var dialog = $("<div/>");
        dialog.on("popupdialogopen", function (event, ui) {
            setTimeout(function () {
                dialog.formData(dataItem);

            }, 1);
        });

        DataUtil.eachItem(schema.formItems, function (item) {
            if (item.type === "file") {
                item.uploadHanderUrl = widget.elementUrl + "file-upload?schema=" + schema.schemaName + "&fid=" + dataItem.fid + "&field=" + item.name;
                if (item.hasOwnProperty("name") && dataItem.data.hasOwnProperty(item.name) && dataItem.data[item.name]) {
                    item.dbSrc = dataItem.data[item.name];
                    if (schema.featureType.files) {
                        $.each(schema.featureType.files, function (k, fileInfo) {
                            if (fileInfo.field && fileInfo.field == item.name) {
                                if (fileInfo.formats) {
                                    item.accept = fileInfo.formats;
                                }
                            }
                        });
                    }
                }

            }

            if (item.type === 'image') {

                if (!item.origSrc) {
                    item.origSrc = item.src;
                }

                if (item.hasOwnProperty("name") && dataItem.data.hasOwnProperty(item.name) && dataItem.data[item.name]) {
                    item.dbSrc = dataItem.data[item.name];
                    if (schema.featureType.files) {
                        $.each(schema.featureType.files, function (k, fileInfo) {
                            if (fileInfo.field && fileInfo.field === item.name) {

                                if (fileInfo.uri) {
                                    item.dbSrc = fileInfo.uri + "/" + item.dbSrc;
                                } else {
                                }
                            }
                        });
                    }
                }

                var src = item.dbSrc ? item.dbSrc : item.origSrc;
                if (item.relative) {
                    item.src = src.match(/^(http[s]?\:|\/{2})/) ? src : Mapbender.configuration.application.urls.asset + src;
                } else {
                    item.src = src;
                }
            }

        });
        /*  if(schema.popup.buttons) {
         buttons = _.union(schema.popup.buttons, buttons);
         } */
        var popupConfig = _.extend({

            title: Mapbender.DigitizerTranslator.translate("feature.attributes"),

            width: widget.featureEditDialogWidth,
        }, schema.popup);

        popupConfig.buttons = buttons;

        dialog.generateElements({children: formItems});
        dialog.popupDialog(popupConfig);
        dialog.addClass("data-store-edit-data");
        widget.currentPopup.currentPopup = dialog;
        dialog.parentDialog = widget.currentPopup;
        dialog.data('schema', schema);
        dialog.data('table', ref);

        return dialog;
    },

    /**
     *
     * @param dataItem
     * @returns {boolean}
     */

    saveForeignDataStoreItem: function (dataItem) {

        var widget = this.widget;
        var dialog = widget.currentPopup.currentPopup;
        var uniqueIdKey = dataItem.item.dataStore.uniqueId;
        var isNew = dataItem[uniqueIdKey] === null;
        var formData = dialog.formData();
        var schema = dialog.data('schema');
        debugger;
        if (!isNew) {

            formData[uniqueIdKey] = dataItem[uniqueIdKey];
            dataItem['linkId'] = dataItem[schema.dataStoreLink.fieldName];

        } else {
            delete formData[uniqueIdKey];

            formData[schema.dataStoreLink.fieldName] = dataItem.linkId;

        }
        var errorInputs = $(".has-error", dialog);
        var hasErrors = errorInputs.size() > 0;
        if (hasErrors) {
            return false;

        }

        $(dialog).disableForm();

        QueryEngine.query('datastore/save', {
            schema: dataItem.item.dataStoreLink.name,
            dataItem: formData,
            dataItemId: dataItem[uniqueIdKey],
            linkId: dataItem.linkId,
            dataStoreLinkFieldName: schema.dataStoreLink.fieldName
        }).done(function (response) {
            if (response.processedItem.hasOwnProperty('errors')) {
                $(dialog).enableForm();
                $.each(response.errors, function (i, error) {
                    $.notify(error.message, {
                        title: 'API Error',
                        autoHide: false,
                        className: 'error'
                    });
                    console.error(error.message);
                });
                return;
            }
            var data = response.dataItems;
            var tableApi = $(dialog).data('table').resultTable('getApi');
            var item = $(dialog).data('table').data('item');
            if (Object.prototype.toString.call(data) === '[object Array]') {
                var a = [];
                _.each(data, function (e, i) {
                    if (e.hasOwnProperty('attributes')) {
                        e.attributes.item = item;
                        a.push(e.attributes);
                    }
                });

                data = a;

            } else {
                if (data.hasOwnProperty('attributes')) {
                    data = [data.attributes];

                }

            }
            tableApi.clear();
            tableApi.rows.add(data);
            tableApi.draw();

            widget.currentPopup.currentPopup.popupDialog('close');
            widget.currentPopup.currentPopup = null;
            $(dialog).enableForm();
            $.notify(Mapbender.DigitizerTranslator.translate("feature.save.successfully", false), 'info');
        });

    }

};
<|endoftext|>


<commit_before>/*
 * grunt-contrib-jshint
 * http://gruntjs.com/
 *
 * Copyright (c) 2013 "Cowboy" Ben Alman, contributors
 * Licensed under the MIT license.
 */

'use strict';

var path = require('path');
var jshint = require('jshint').JSHINT;
var jshintcli = require('jshint/src/cli');

exports.init = function(grunt) {
  var exports = {
    usingGruntReporter: false
  };

  // No idea why JSHint treats tabs as options.indent # characters wide, but it
  // does. See issue: https://github.com/jshint/jshint/issues/430
  var getTabStr = function(options) {
    // Do something that's going to error.
    jshint('\tx', options || {});
    // If an error occurred, figure out what character JSHint reported and
    // subtract one.
    var character = jshint.errors && jshint.errors[0] && jshint.errors[0].character - 1;
    // If character is actually a number, use it. Otherwise use 1.
    var tabsize = isNaN(character) ? 1 : character;
    // If tabsize > 1, return something that should be safe to use as a
    // placeholder. \uFFFF repeated 2+ times.
    return tabsize > 1 && grunt.util.repeat(tabsize, '\uFFFF');
  };

  var tabregex = /\t/g;

  // Select a reporter (if not using the default Grunt reporter)
  // Copied from jshint/src/cli/cli.js until that part is exposed
  exports.selectReporter = function(options) {
    switch (true) {
    // JSLint reporter
    case options.reporter === 'jslint':
    case options['jslint-reporter']:
      options.reporter = 'jshint/src/reporters/jslint_xml.js';
      break;

    // CheckStyle (XML) reporter
    case options.reporter === 'checkstyle':
    case options['checkstyle-reporter']:
      options.reporter = 'jshint/src/reporters/checkstyle.js';
      break;

    // Reporter that displays additional JSHint data
    case options['show-non-errors']:
      options.reporter = 'jshint/src/reporters/non_error.js';
      break;

    // Custom reporter
    case options.reporter !== undefined:
      options.reporter = path.resolve(process.cwd(), options.reporter);
    }

    var reporter;
    if (options.reporter) {
      try {
        reporter = require(options.reporter).reporter;
        exports.usingGruntReporter = false;
      } catch (err) {
        grunt.fatal(err);
      }
    }

    // Use the default Grunt reporter if none are found
    if (!reporter) {
      reporter = exports.reporter;
      exports.usingGruntReporter = true;
    }

    return reporter;
  };

  // Default Grunt JSHint reporter
  exports.reporter = function(results, data) {
    // Dont report empty data as its an ignored file
    if (data.length < 1) {
      grunt.log.error('0 files linted. Please check your ignored files.');
      return;
    }

    if (results.length === 0) {
      // Success!
      grunt.verbose.ok();
      return;
    }

    var options = data[0].options;

    // Tab size as reported by JSHint.
    var tabstr = getTabStr(options);
    var placeholderregex = new RegExp(tabstr, 'g');

    // Iterate over all errors.
    results.forEach(function(result) {
      // Display the defending file
      var msg = 'Linting' + (result.file ? ' ' + result.file : '') + ' ...';
      grunt.verbose.write(msg);

      // Something went wrong.
      grunt.verbose.or.write(msg);
      grunt.log.error();

      var e = result.error;
      // Sometimes there's no error object.
      if (!e) { return; }
      var pos;
      var code = '';
      var evidence = e.evidence;
      var character = e.character;
      if (evidence) {
        // Manually increment errorcount since we're not using grunt.log.error().
        grunt.fail.errorcount++;
        // Descriptive code error.
        pos = '['.red + ('L' + e.line).yellow + ':'.red + ('C' + character).yellow + ']'.red;
        if (e.code) {
          code = e.code.yellow + ':'.red + ' ';
        }
        grunt.log.writeln(pos + ' ' + code + e.reason.yellow);
        // If necessary, eplace each tab char with something that can be
        // swapped out later.
        if (tabstr) {
          evidence = evidence.replace(tabregex, tabstr);
        }
        if (character === 0) {
          // Beginning of line.
          evidence = '?'.inverse.red + evidence;
        } else if (character > evidence.length) {
          // End of line.
          evidence = evidence + ' '.inverse.red;
        } else {
          // Middle of line.
          evidence = evidence.slice(0, character - 1) + evidence[character - 1].inverse.red +
            evidence.slice(character);
        }
        // Replace tab placeholder (or tabs) but with a 2-space soft tab.
        evidence = evidence.replace(tabstr ? placeholderregex : tabregex, '  ');
        grunt.log.writeln(evidence);
      } else {
        // Generic "Whoops, too many errors" error.
        grunt.log.error(e.reason);
      }
    });
    grunt.log.writeln();
  };

  // Run JSHint on the given files with the given options
  exports.lint = function(files, options, done) {
    var cliOptions = {
      verbose: grunt.option('verbose'),
      extensions: '',
    };

    // A list of non-dot-js extensions to check
    if (options.extensions) {
      cliOptions.extensions = options.extensions;
      delete options.extensions;
    }

    // A list ignored files
    if (options.ignores) {
      if (typeof options.ignores === 'string') {
        options.ignores = [options.ignores];
      }
      cliOptions.ignores = options.ignores;
      delete options.ignores;
    }

    // Select a reporter to use
    var reporter = exports.selectReporter(options);

    // Remove bad options that may have came in from the cli
    ['reporter', 'jslint-reporter', 'checkstyle-reporter', 'show-non-errors'].forEach(function(opt) {
      if (options.hasOwnProperty(opt)) {
        delete options[opt];
      }
    });

    // Read JSHint options from a specified jshintrc file.
    if (options.jshintrc) {
      options = jshintcli.loadConfig(options.jshintrc);
      delete options.jshintrc;
    }

    // Enable/disable debugging if option explicitly set.
    if (grunt.option('debug') !== undefined) {
      options.devel = options.debug = grunt.option('debug');
      // Tweak a few things.
      if (grunt.option('debug')) {
        options.maxerr = Infinity;
      }
    }

    cliOptions.config = options;

    // Run JSHint on all file and collect results/data
    var allResults = [];
    var allData = [];
    var cliopts = grunt.util._.clone(cliOptions);
    cliopts.args = files;
    cliopts.reporter = function(results, data) {
      reporter(results, data);
      allResults = allResults.concat(results);
      allData = allData.concat(data);
    };
    jshintcli.run(cliopts);
    done(allResults, allData);
  };

  return exports;
};
<commit_msg>Fix output when maxerr is low. Fixes GH-105.<commit_after>/*
 * grunt-contrib-jshint
 * http://gruntjs.com/
 *
 * Copyright (c) 2013 "Cowboy" Ben Alman, contributors
 * Licensed under the MIT license.
 */

'use strict';

var path = require('path');
var jshint = require('jshint').JSHINT;
var jshintcli = require('jshint/src/cli');

exports.init = function(grunt) {
  var exports = {
    usingGruntReporter: false
  };

  // No idea why JSHint treats tabs as options.indent # characters wide, but it
  // does. See issue: https://github.com/jshint/jshint/issues/430
  var getTabStr = function(options) {
    options = options ? grunt.util._.clone(options) : {};
    options.maxerr = 50;
    // Do something that's going to error.
    jshint('\tx', options);
    // If an error occurred, figure out what character JSHint reported and
    // subtract one.
    var character = jshint.errors && jshint.errors[0] && jshint.errors[0].character - 1;
    // If character is actually a number, use it. Otherwise use 1.
    var tabsize = isNaN(character) ? 1 : character;
    // If tabsize > 1, return something that should be safe to use as a
    // placeholder. \uFFFF repeated 2+ times.
    return tabsize > 1 && grunt.util.repeat(tabsize, '\uFFFF');
  };

  var tabregex = /\t/g;

  // Select a reporter (if not using the default Grunt reporter)
  // Copied from jshint/src/cli/cli.js until that part is exposed
  exports.selectReporter = function(options) {
    switch (true) {
    // JSLint reporter
    case options.reporter === 'jslint':
    case options['jslint-reporter']:
      options.reporter = 'jshint/src/reporters/jslint_xml.js';
      break;

    // CheckStyle (XML) reporter
    case options.reporter === 'checkstyle':
    case options['checkstyle-reporter']:
      options.reporter = 'jshint/src/reporters/checkstyle.js';
      break;

    // Reporter that displays additional JSHint data
    case options['show-non-errors']:
      options.reporter = 'jshint/src/reporters/non_error.js';
      break;

    // Custom reporter
    case options.reporter !== undefined:
      options.reporter = path.resolve(process.cwd(), options.reporter);
    }

    var reporter;
    if (options.reporter) {
      try {
        reporter = require(options.reporter).reporter;
        exports.usingGruntReporter = false;
      } catch (err) {
        grunt.fatal(err);
      }
    }

    // Use the default Grunt reporter if none are found
    if (!reporter) {
      reporter = exports.reporter;
      exports.usingGruntReporter = true;
    }

    return reporter;
  };

  // Default Grunt JSHint reporter
  exports.reporter = function(results, data) {
    // Dont report empty data as its an ignored file
    if (data.length < 1) {
      grunt.log.error('0 files linted. Please check your ignored files.');
      return;
    }

    if (results.length === 0) {
      // Success!
      grunt.verbose.ok();
      return;
    }

    var options = data[0].options;

    // Tab size as reported by JSHint.
    var tabstr = getTabStr(options);
    var placeholderregex = new RegExp(tabstr, 'g');

    // Iterate over all errors.
    results.forEach(function(result) {
      // Display the defending file
      var msg = 'Linting' + (result.file ? ' ' + result.file : '') + ' ...';
      grunt.verbose.write(msg);

      // Something went wrong.
      grunt.verbose.or.write(msg);
      grunt.log.error();

      var e = result.error;
      // Sometimes there's no error object.
      if (!e) { return; }
      var pos;
      var code = '';
      var evidence = e.evidence;
      var character = e.character;
      if (evidence) {
        // Manually increment errorcount since we're not using grunt.log.error().
        grunt.fail.errorcount++;
        // Descriptive code error.
        pos = '['.red + ('L' + e.line).yellow + ':'.red + ('C' + character).yellow + ']'.red;
        if (e.code) {
          code = e.code.yellow + ':'.red + ' ';
        }
        grunt.log.writeln(pos + ' ' + code + e.reason.yellow);
        // If necessary, eplace each tab char with something that can be
        // swapped out later.
        if (tabstr) {
          evidence = evidence.replace(tabregex, tabstr);
        }
        if (character === 0) {
          // Beginning of line.
          evidence = '?'.inverse.red + evidence;
        } else if (character > evidence.length) {
          // End of line.
          evidence = evidence + ' '.inverse.red;
        } else {
          // Middle of line.
          evidence = evidence.slice(0, character - 1) + evidence[character - 1].inverse.red +
            evidence.slice(character);
        }
        // Replace tab placeholder (or tabs) but with a 2-space soft tab.
        evidence = evidence.replace(tabstr ? placeholderregex : tabregex, '  ');
        grunt.log.writeln(evidence);
      } else {
        // Generic "Whoops, too many errors" error.
        grunt.log.error(e.reason);
      }
    });
    grunt.log.writeln();
  };

  // Run JSHint on the given files with the given options
  exports.lint = function(files, options, done) {
    var cliOptions = {
      verbose: grunt.option('verbose'),
      extensions: '',
    };

    // A list of non-dot-js extensions to check
    if (options.extensions) {
      cliOptions.extensions = options.extensions;
      delete options.extensions;
    }

    // A list ignored files
    if (options.ignores) {
      if (typeof options.ignores === 'string') {
        options.ignores = [options.ignores];
      }
      cliOptions.ignores = options.ignores;
      delete options.ignores;
    }

    // Select a reporter to use
    var reporter = exports.selectReporter(options);

    // Remove bad options that may have came in from the cli
    ['reporter', 'jslint-reporter', 'checkstyle-reporter', 'show-non-errors'].forEach(function(opt) {
      if (options.hasOwnProperty(opt)) {
        delete options[opt];
      }
    });

    // Read JSHint options from a specified jshintrc file.
    if (options.jshintrc) {
      options = jshintcli.loadConfig(options.jshintrc);
      delete options.jshintrc;
    }

    // Enable/disable debugging if option explicitly set.
    if (grunt.option('debug') !== undefined) {
      options.devel = options.debug = grunt.option('debug');
      // Tweak a few things.
      if (grunt.option('debug')) {
        options.maxerr = Infinity;
      }
    }

    cliOptions.config = options;

    // Run JSHint on all file and collect results/data
    var allResults = [];
    var allData = [];
    var cliopts = grunt.util._.clone(cliOptions);
    cliopts.args = files;
    cliopts.reporter = function(results, data) {
      reporter(results, data);
      allResults = allResults.concat(results);
      allData = allData.concat(data);
    };
    jshintcli.run(cliopts);
    done(allResults, allData);
  };

  return exports;
};
<|endoftext|>


<commit_before>'use strict'

var flexProvider = require('flex-sdk-provider')
var Promise = require('es6-promise').Promise
var promisify = require('es6-promisify')
var os = require('os')
var path = require('path')

module.exports = function (grunt) {
  var isWindows = /^win/.test(os.platform())
  var mxmlc = 'mxmlc' + (isWindows ? '.exe' : '')

  var gSpawn = promisify(grunt.util.spawn)

  var spawn = function (opt) {
    return gSpawn(opt)
      .then(function (result, code) {
        if (code) {
          throw new Error('Exit status: ' + code)
        }
      })
  }

  var build = function (file, opt) {
    return flexProvider.get(opt.version)
      .then(function (sdkPath) {
        var cmd = path.join(sdkPath, 'bin', mxmlc)
        var args = ['-load-config+=' + file.src]
        grunt.verbose.writeln('Compiling ' + file.src + ' using ' + cmd)
        return spawn({cmd: cmd, args: args})
      })
  }

  grunt.registerMultiTask('mxmlc_lite', '', function () {
    var done = this.async()
    var options = this.options()
    var compiling = this.files.reduce(function (prev, curr) {
      return prev.then(function () {
        return build(curr, options)
      })
    }, Promise.resolve())
    compiling.then(done, grunt.fail.fatal)
  })
}
<commit_msg>Improving logic to find mxmlc; adding logging<commit_after>'use strict'

var flexProvider = require('flex-sdk-provider')
var Promise = require('es6-promise').Promise
var promisify = require('es6-promisify')
var fs = require('fs')
var path = require('path')
var os = require('os')

var stat = promisify(fs.stat)

module.exports = function (grunt) {
  var gSpawn = promisify(grunt.util.spawn)

  var mxmlc = null

  var spawn = function (opt) {
    grunt.verbose.debug('Spawning ' + opt.cmd + ' with args: ' + opt.args)
    return gSpawn(opt)
      .then(function (result, code) {
        if (code) {
          throw new Error('Exit status: ' + code)
        }
        grunt.verbose.ok('mxmlc exited cleanly')
      })
  }

  var findFile = function (dir, candidates) {
    if (candidates.length === 0) {
      throw new Error('Failed to locate mxmlc')
    }
    var candidate = candidates.shift()
    var candidatePath = path.join(dir, candidate)
    return stat(candidatePath)
      .then(function (stats) {
        return candidate
      })
      .catch(function () {
        return findFile(dir, candidates)
      })
  }

  var determineMxmlcCommand = function (sdkPath) {
    if (mxmlc !== null) {
      return
    }
    grunt.verbose.writeln('Locating mxmlc')
    var binDir = path.join(sdkPath, 'bin')
    var candidates = /^win/.test(os.platform()) ?
      ['mxmlc.bat', 'mxmlc.cmd', 'mxmlc.exe'] :
      ['mxmlc']
    return findFile(binDir, candidates)
      .then(function (res) {
        mxmlc = res
        grunt.verbose.ok('Using mxmlc at ' + path.join(sdkPath, mxmlc))
      })
  }

  var build = function (file, opt) {
    grunt.verbose.writeln('Starting build for ' + file.src +
      ' with Flex SDK version ' + opt.version)
    var sdkPath
    return flexProvider.get(opt.version)
      .then(function (_sdkPath) {
        sdkPath = _sdkPath
      })
      .then(function () {
        return determineMxmlcCommand(sdkPath)
      })
      .then(function () {
        var cmd = path.join(sdkPath, 'bin', mxmlc)
        var args = ['-load-config+=' + file.src]
        grunt.verbose.writeln('Compiling ' + file.src + ' using ' + cmd)
        return spawn({cmd: cmd, args: args})
      })
      .then(function () {
        grunt.log.ok('Build completed for ' + file.src)
      })
  }

  grunt.registerMultiTask('mxmlc_lite', '', function () {
    var done = this.async()
    var options = this.options()
    var compiling = this.files.reduce(function (prev, curr) {
      return prev.then(function () {
        return build(curr, options)
      })
    }, Promise.resolve())
    compiling.then(done, grunt.fail.fatal)
  })
}
<|endoftext|>


<commit_before>var $ = require('jquery');
var AD = require('AppDev');

require('ui/ChooseOptionWindow');
module.exports = AD.UI.ChooseOptionsWindow('AppDev.UI.ChooseContactsWindow', {}, {
    init: function(options) {
        // Build a dictionary of all the contacts that are initially chosen
        var contacts = this.options.contacts || [];
        var chosenContacts = $.indexArray(contacts, 'recordId');

        // Build a dictionary of the contacts already in the database
        var usedRecordIds = $.indexArray(AD.Models.Contact.cache.getArray(), 'contact_recordId');

        // Load all the contacts from the user's Address Book, remove contacts that already
        // have a NextSteps contact associated with them, then sort them by last name
        var options = Ti.Contacts.getAllPeople().filter(function(contact) {
            return typeof usedRecordIds[contact.recordId || contact.id] === 'undefined';
        }).map(function(contact) {
            return {
                title: contact.fullName,
                // Android does not allow access to the lastName property, so assume that it is the last word of the full name
                sortKey: (contact.lastName || (contact.fullName && contact.fullName.split(' ').pop()) || '').toUpperCase(),
                selected: typeof chosenContacts[contact.recordId || contact.id] !== 'undefined',
                recordId: contact.recordId || contact.id
            };
        }).sort(function(contact1, contact2) {
            return $.compare(contact1.sortKey, contact2.sortKey);
        });

        // Determine which options should be selected initially
        var selected = [];
        options.forEach(function(option, index) {
            if (option.selected) {
                selected.push(index);
            }
        });

        // Initialize the base AD.UI.ChooseContactsWindow object
        this._super({
            groupName: 'contact',
            initial: selected,
            options: options
        });
    }
});
<commit_msg>Request access to the system address book before attempting to populate ChooseContactsWindow with contacts<commit_after>var $ = require('jquery');
var AD = require('AppDev');

require('ui/ChooseOptionWindow');
module.exports = AD.UI.ChooseOptionsWindow('AppDev.UI.ChooseContactsWindow', {}, {
    init: function(options) {
        // Initialize the base AD.UI.ChooseOptionsWindow object
        this._super({
            groupName: 'contact',
            initial: [],
            options: []
        });

        var _this = this;
        AD.UI.requestContactsAuthorization().done(function() {
            // Build a dictionary of all the contacts that are initially chosen
            var contacts = _this.options.contacts || [];
            var chosenContacts = $.indexArray(contacts, 'recordId');

            // Build a dictionary of the contacts already in the database
            var usedRecordIds = $.indexArray(AD.Models.Contact.cache.getArray(), 'contact_recordId');

            // Load all the contacts from the user's Address Book, remove contacts that already
            // have a NextSteps contact associated with them, then sort them by last name
            var options = Ti.Contacts.getAllPeople().filter(function(contact) {
                return typeof usedRecordIds[contact.recordId || contact.id] === 'undefined';
            }).map(function(contact) {
                return {
                    title: contact.fullName,
                    // Android does not allow access to the lastName property, so assume that it is the last word of the full name
                    sortKey: (contact.lastName || (contact.fullName && contact.fullName.split(' ').pop()) || '').toUpperCase(),
                    selected: typeof chosenContacts[contact.recordId || contact.id] !== 'undefined',
                    recordId: contact.recordId || contact.id
                };
            }).sort(function(contact1, contact2) {
                return $.compare(contact1.sortKey, contact2.sortKey);
            });

            // Determine which options should be selected initially
            var selected = [];
            options.forEach(function(option, index) {
                if (option.selected) {
                    selected.push(index);
                }
            });

            // Initialize the ChooseOptionsWindow with the contacts data
            _this.options.initial = selected;
            _this.options.options = options;
            _this.initialize();
        });
    }
});
<|endoftext|>


<commit_before>module.exports = function(grunt) {
	var log = require('../node_modules/qunit/lib/log.js');
	var qunit = require("qunit");

	grunt.registerMultiTask("node-qunit", "Runs node-qunit ", function() {
		var done = this.async(),
			started = new Date(),
			callback = this.data.callback;
		// Setup Qunit
		qunit.setup(this.data.setup || {
			log: {
				summary: true,
				errors: true
			}
		});

		// Run tests
		var files = {};
		if(this.data.code) files.code = this.data.code;
		if(this.data.deps) files.deps = this.data.deps;
		if(this.data.moduleDeps) files.moduleDeps = this.data.moduleDeps;
		if(this.data.tests) files.tests = this.data.tests;
		qunit.run(files, function(err, result) {
			if(!result) {
				throw "Could not get results for Qunit test. Check previous exceptions";
			}
			result.started = started;
			result.completed = new Date();
			var waitForAsync = false;
			this.async = function() {
				waitForAsync = true;
				return function(status) {
					done(typeof status === "undefined" ? (result.failed === 0 && !err) : status);
					log.reset();
				};
			};
			var res;
			if(typeof callback === "function") {
				res = callback(err, result);
			}
			if(!waitForAsync) {
				done(typeof res === "undefined" ? (result.failed === 0 && !err) : res);
				log.reset();
			}
		});
	});
};<commit_msg>Enhancement: Added ignoreFailures support, to not let grunt task to fail when tests are not passing In that way, QUnit/code exceptions can actually be reported as errors by CI<commit_after>module.exports = function(grunt) {
	var log = require('../node_modules/qunit/lib/log.js');
	var qunit = require("qunit");

	grunt.registerMultiTask("node-qunit", "Runs node-qunit ", function() {
		var done = this.async(),
			started = new Date(),
			callback = this.data.callback;
		// Setup Qunit
		qunit.setup(this.data.setup || {
			log: {
				summary: true,
				errors: true
			}
		});

		// Run tests
		var files = {};
		var ignoreFailures = this.data && this.data.ignoreFailures;
		if(this.data.code) files.code = this.data.code;
		if(this.data.deps) files.deps = this.data.deps;
		if(this.data.moduleDeps) files.moduleDeps = this.data.moduleDeps;
		if(this.data.tests) files.tests = this.data.tests;
		qunit.run(files, function(err, result) {
			if(!result) {
				throw new Error("Could not get results for Qunit test. Check previous exceptions");
			}

			function check(res) {
				var hasErr = (result.failed > 0) && !ignoreFailures;
				done(typeof res === "undefined" ? (!hasErr && !err) : res);
				log.reset();
			}

			result.started = started;
			result.completed = new Date();
			var waitForAsync = false;
			this.async = function() {
				waitForAsync = true;
				return check;
			};
			var res;
			if(typeof callback === "function") {
				res = callback(err, result);
			}
			if(!waitForAsync) {
				check(res);
			}
		});
	});
};<|endoftext|>


<commit_before>'use strict';

var inquirer = require('inquirer');
var gitHelper = require('./lib/helpers/git');
var dependenciesHelper = require('./lib/helpers/dependencies');
var messages = require('./lib/messages');
var version = require('./lib/version');

module.exports = function (grunt) {

  grunt.task.loadNpmTasks('grunt-bump');

  // ---

  var releaseBranchName;

  grunt.registerTask('prepare_sg_release', function () {

    var done = this.async();
    var options = this.options({
      tempReleaseBranch: 'release'
    });

    function checkGit() {
      gitHelper.check(grunt);
      checkNpmInstall();
    }

    function checkNpmInstall() {
      dependenciesHelper.checkInstall(grunt, process.cwd(), 'npm', checkBowerInstall);
    }

    function checkBowerInstall() {
      dependenciesHelper.checkInstall(grunt, process.cwd(), 'bower', getReleaseVersion);
    }

    function getReleaseVersion() {
      version.getRelease(grunt, createTempReleaseBranch);
    }

    function createTempReleaseBranch() {
      releaseBranchName = options.tempReleaseBranch + '/v' + grunt.option('setversion');
      gitHelper.createBranch(grunt, process.cwd(), releaseBranchName, done);
    }

    (function start() {
      checkGit();
    })();

  });

  // ---

  grunt.registerTask('merge_sg_release', function () {

    var done = this.async();
    var options = this.options({
      developBranch: 'develop',
      masterBranch: 'master',
      mergeToDevelopMsg: messages.mergeToMasterMsg,
      mergeToMasterMsg: messages.mergeToDevelopMsg
    });

    function checkoutMaster() {
      gitHelper.checkout(grunt, process.cwd(), options.masterBranch, mergeFromTempReleaseBranch);
    }

    function mergeFromTempReleaseBranch() {
      gitHelper.merge(grunt, process.cwd(), releaseBranchName, options.mergeToMasterMsg, checkoutDevelop);
    }

    function checkoutDevelop() {
      gitHelper.checkout(grunt, process.cwd(), options.developBranch, mergeIntoDevelopBranch);
    }

    function mergeIntoDevelopBranch() {
      gitHelper.merge(grunt, process.cwd(), releaseBranchName, options.mergeToMasterMsg, deleteTempReleaseBranch);
    }

    function deleteTempReleaseBranch() {
      gitHelper.deleteBranch(grunt, process.cwd(), releaseBranchName, done);
    }

    (function start() {
      checkoutMaster();
    })();

  });

  // ---

  grunt.registerTask('finish_sg_release', function () {

    var done = this.async();
    var options = this.options({
      developVersionCommitMsg: messages.developVersionCommitMsg
    });

    function commitDevelopmentVersion() {
      gitHelper.commit(grunt, process.cwd(), options.developVersionCommitMsg, done);
    }

    (function start() {
      commitDevelopmentVersion();
    })();

  });

  // ---

  grunt.registerMultiTask('sg_release', 'The SunGard standard release script for HTML5 projects.', function () {

    grunt.task.run('prepare_sg_release');
    grunt.task.run('bump');
    grunt.task.run('merge_sg_release');
    grunt.task.run('bump-only');
    grunt.task.run('finish_sg_release');

  });

};

<commit_msg>Added push to develop branch step<commit_after>'use strict';

var inquirer = require('inquirer');
var gitHelper = require('./lib/helpers/git');
var dependenciesHelper = require('./lib/helpers/dependencies');
var messages = require('./lib/messages');
var version = require('./lib/version');

module.exports = function (grunt) {

  grunt.task.loadNpmTasks('grunt-bump');

  // ---

  var releaseBranchName;
  var defaultDevelopBranch = 'develop';
  var defaultMasterBranch = 'master';
  var defaultReleaseBranch = 'release';

  grunt.registerTask('prepare_sg_release', function () {

    var done = this.async();
    var options = this.options({
      tempReleaseBranch: defaultReleaseBranch
    });

    function checkGit() {
      gitHelper.check(grunt);
      checkNpmInstall();
    }

    function checkNpmInstall() {
      dependenciesHelper.checkInstall(grunt, process.cwd(), 'npm', checkBowerInstall);
    }

    function checkBowerInstall() {
      dependenciesHelper.checkInstall(grunt, process.cwd(), 'bower', getReleaseVersion);
    }

    function getReleaseVersion() {
      version.getRelease(grunt, createTempReleaseBranch);
    }

    function createTempReleaseBranch() {
      releaseBranchName = options.tempReleaseBranch + '/v' + grunt.option('setversion');
      gitHelper.createBranch(grunt, process.cwd(), releaseBranchName, done);
    }

    (function start() {
      checkGit();
    })();

  });

  // ---

  grunt.registerTask('merge_sg_release', function () {

    var done = this.async();
    var options = this.options({
      developBranch: defaultDevelopBranch,
      masterBranch: defaultMasterBranch,
      mergeToDevelopMsg: messages.mergeToMasterMsg,
      mergeToMasterMsg: messages.mergeToDevelopMsg
    });

    function checkoutMaster() {
      gitHelper.checkout(grunt, process.cwd(), options.masterBranch, mergeFromTempReleaseBranch);
    }

    function mergeFromTempReleaseBranch() {
      gitHelper.merge(grunt, process.cwd(), releaseBranchName, options.mergeToMasterMsg, checkoutDevelop);
    }

    function checkoutDevelop() {
      gitHelper.checkout(grunt, process.cwd(), options.developBranch, mergeIntoDevelopBranch);
    }

    function mergeIntoDevelopBranch() {
      gitHelper.merge(grunt, process.cwd(), releaseBranchName, options.mergeToMasterMsg, deleteTempReleaseBranch);
    }

    function deleteTempReleaseBranch() {
      gitHelper.deleteBranch(grunt, process.cwd(), releaseBranchName, done);
    }

    (function start() {
      checkoutMaster();
    })();

  });

  // ---

  grunt.registerTask('finish_sg_release', function () {

    var done = this.async();
    var options = this.options({
      developBranch: defaultDevelopBranch,
      masterBranch: defaultMasterBranch,
      developVersionCommitMsg: messages.developVersionCommitMsg,
      pushTo: 'origin'
    });

    function commitDevelopmentVersion() {
      gitHelper.commit(grunt, process.cwd(), options.developVersionCommitMsg, pushDevelopBranch);
    }

    function pushDevelopBranch() {
      gitHelper.push(grunt, process.cwd(), options.pushTo, options.developBranch, done);
    }

    (function start() {
      commitDevelopmentVersion();
    })();

  });

  // ---

  grunt.registerMultiTask('sg_release', 'The SunGard standard release script for HTML5 projects.', function () {

    grunt.task.run('prepare_sg_release');
    grunt.task.run('bump');
    grunt.task.run('merge_sg_release');
    grunt.task.run('bump-only');
    grunt.task.run('finish_sg_release');

  });

};

<|endoftext|>


<commit_before>/**   _     _   _         _____  __   _______  ______
*    | |___| |_| |__    /__  |  |  |     |  _  | * *
*    | / _ \  _|    |    __\    |  |  \  |  _  |  U _
*    |_\___/\__|_||_| _ |____/____ |__ \_|_  |_|_____|
*
*    @author LoTh / http://3dflashlo.wordpress.com/
*    @author SUNAG / http://www.sunag.com.br/
*    @author Ammo.lab / https://github.com/lo-th/Ammo.lab/
*/

'use strict';

SEA3D.AMMO = {

	world: null,

	rigidBodies: [],
	rigidBodiesTarget: [],
	rigidBodiesEnabled: [],

	constraints: [],

	vehicles: [],
	vehiclesWheels: [],

	ACTIVE: 1,
	ISLAND_SLEEPING: 2,
	WANTS_DEACTIVATION: 3,
	DISABLE_DEACTIVATION: 4,
	DISABLE_SIMULATION: 5,
	VERSION: 0.8,

	init: function ( gravity, worldScale, broadphase ) {

		gravity = gravity !== undefined ? gravity : - 90.8;

		this.worldScale = worldScale == undefined ? 1 : worldScale;
		this.broadphase = broadphase == undefined ? 'bvt' : broadphase;

		this.solver = new Ammo.btSequentialImpulseConstraintSolver();
		this.collisionConfig = new Ammo.btDefaultCollisionConfiguration();
		this.dispatcher = new Ammo.btCollisionDispatcher( this.collisionConfig );

		switch ( this.broadphase ) {

			case 'bvt':

				this.broadphase = new Ammo.btDbvtBroadphase();

				break;

			case 'sap':

				this.broadphase = new Ammo.btAxisSweep3(
					new Ammo.btVector3( - this.worldScale, - this.worldScale, - this.worldScale ),
					new Ammo.btVector3( this.worldScale, this.worldScale, this.worldScale ),
					4096
				);

				break;

			case 'simple':

				this.broadphase = new Ammo.btSimpleBroadphase();

				break;

		}

		this.world = new Ammo.btDiscreteDynamicsWorld( this.dispatcher, this.broadphase, this.solver, this.collisionConfig );

		this.setGravity( gravity );

		console.log( "THREE.AMMO " + this.VERSION );

	},

	setGravity: function ( gravity ) {

		this.gravity = gravity;

		this.world.setGravity( new Ammo.btVector3( 0, gravity, 0 ) );

		return this;

	},
	getGravity: function () {

		return this.gravity;

	},

	setEnabledRigidBody: function ( rb, enabled ) {

		if ( this.getEnabledRigidBody( rb ) == enabled ) return;

		if ( enabled ) this.world.addRigidBody( rb );
		else this.world.removeRigidBody( rb );

		return this;

	},
	getEnabledRigidBody: function ( rb ) {

		return this.rigidBodiesEnabled[ this.rigidBodies.indexOf( rb ) ] === true;

	},
	addRigidBody: function ( rb, target, enabled ) {

		enabled = enabled !== undefined ? enabled : true;

		this.rigidBodies.push( rb );
		this.rigidBodiesTarget.push( target );
		this.rigidBodiesEnabled.push( false );

		this.setEnabledRigidBody( rb, enabled );

		return this;

	},
	removeRigidBody: function ( rb, destroy ) {

		var index = this.rigidBodies.indexOf( rb );

		this.setEnabledRigidBody( rb, false );

		this.rigidBodies.splice( index, 1 );
		this.rigidBodiesTarget.splice( index, 1 );
		this.rigidBodiesEnabled.splice( index, 1 );

		if ( destroy ) Ammo.destroy( rb );

		return this;

	},
	containsRigidBody: function ( rb ) {

		return this.rigidBodies.indexOf( rb ) > - 1;

	},

	addConstraint: function ( ctrt, disableCollisionsBetweenBodies ) {

		disableCollisionsBetweenBodies = disableCollisionsBetweenBodies == undefined ? true : disableCollisionsBetweenBodies;

		this.constraints.push( ctrt );
		this.world.addConstraint( ctrt, disableCollisionsBetweenBodies );

		return this;

	},
	removeConstraint: function ( ctrt, destroy ) {

		this.constraints.splice( this.constraints.indexOf( ctrt ), 1 );
		this.world.removeConstraint( ctrt );

		if ( destroy ) Ammo.destroy( ctrt );

		return this;

	},
	containsConstraint: function ( ctrt ) {

		return this.constraints.indexOf( rb ) > - 1;

	},

	addVehicle: function ( vehicle, wheels ) {

		this.vehicles.push( vehicle );
		this.vehiclesWheels.push( wheels != undefined ? wheels : [] );

		this.world.addAction( vehicle );

		return this;

	},
	removeVehicle: function ( vehicle, destroy ) {

		var index = this.vehicles.indexOf( vehicle );

		this.vehicles.splice( index, 1 );
		this.vehiclesWheels.splice( index, 1 );

		this.world.removeAction( vehicle );

		if ( destroy ) Ammo.destroy( vehicle );

		return this;

	},
	containsVehicle: function ( vehicle ) {

		return this.vehicles.indexOf( vehicle ) > - 1;

	},

	createTriangleMesh: function ( geometry, index, removeDuplicateVertices ) {

		index = index == undefined ? - 1 : index;
		removeDuplicateVertices = removeDuplicateVertices == undefined ? false : removeDuplicateVertices;

		var mTriMesh = new Ammo.btTriangleMesh();

		var v0 = new Ammo.btVector3( 0, 0, 0 );
		var v1 = new Ammo.btVector3( 0, 0, 0 );
		var v2 = new Ammo.btVector3( 0, 0, 0 );

		var vertex = geometry.getAttribute( 'position' ).array;
		var indexes = geometry.getIndex().array;

		var group = index >= 0 ? geometry.groups[ index ] : undefined,
			start = group ? group.start : 0,
			count = group ? group.count : indexes.length;

		var scale = 1 / this.worldScale;

		for ( var idx = start; idx < count; idx += 3 ) {

			var vx1 = indexes[ idx ] * 3,
				vx2 = indexes[ idx + 1 ] * 3,
				vx3 = indexes[ idx + 2 ] * 3;

			v0.setValue( vertex[ vx1 ] * scale, vertex[ vx1 + 1 ] * scale, vertex[ vx1 + 2 ] * scale );
			v1.setValue( vertex[ vx2 ] * scale, vertex[ vx2 + 1 ] * scale, vertex[ vx2 + 2 ] * scale );
			v2.setValue( vertex[ vx3 ] * scale, vertex[ vx3 + 1 ] * scale, vertex[ vx3 + 2 ] * scale );

			mTriMesh.addTriangle( v0, v1, v2, removeDuplicateVertices );

		}

		return mTriMesh;

	},
	createConvexHull: function ( geometry, index ) {

		index = index == undefined ? - 1 : index;

		var mConvexHull = new Ammo.btConvexHullShape();

		var v0 = new Ammo.btVector3( 0, 0, 0 );

		var vertex = geometry.getAttribute( 'position' ).array;
		var indexes = geometry.getIndex().array;

		var group = index >= 0 ? geometry.groups[ index ] : undefined,
			start = group ? group.start : 0,
			count = group ? group.count : indexes.length;

		var scale = 1 / this.worldScale;

		for ( var idx = start; idx < count; idx += 3 ) {

			var vx1 = indexes[ idx ] * 3;

			var point = new Ammo.btVector3(
				vertex[ vx1 ] * scale, vertex[ vx1 + 1 ] * scale, vertex[ vx1 + 2 ] * scale
			);

			mConvexHull.addPoint( point );

		}

		return mConvexHull;

	},

	getTargetByRigidBody: function ( rb ) {

		return this.rigidBodiesTarget[ this.rigidBodies.indexOf( rb ) ];

	},
	getRigidBodyByTarget: function ( target ) {

		return this.rigidBodies[ this.rigidBodiesTarget.indexOf( target ) ];

	},
	getTransformFromMatrix: function ( mtx ) {

		var transform = new Ammo.btTransform();

		var pos = THREE.SEA3D.VECBUF.setFromMatrixPosition( mtx );
		transform.setOrigin( new Ammo.btVector3( pos.x, pos.y, pos.z ) );

		var scl = THREE.SEA3D.VECBUF.setFromMatrixScale( mtx );
		mtx.scale( scl.set( 1 / scl.x, 1 / scl.y, 1 / scl.z ) );

		var quat = new THREE.Quaternion().setFromRotationMatrix( mtx );

		var q = new Ammo.btQuaternion();
		q.setValue( quat.x, quat.y, quat.z, quat.w );
		transform.setRotation( q );

		Ammo.destroy( q );

		return transform;

	},
	getMatrixFromTransform: function ( transform ) {

		var position = new THREE.Vector3();
		var quaternion = new THREE.Quaternion();
		var scale = new THREE.Vector3( 1, 1, 1 );

		return function ( transform, matrix ) {

			matrix = matrix || new THREE.Matrix4();

			var pos = transform.getOrigin(),
				quat = transform.getRotation();

			position.set( pos.x(), pos.y(), pos.z() );
			quaternion.set( quat.x(), quat.y(), quat.z(), quat.w() );

			matrix.compose( position, quaternion, scale );

			return matrix;

		};

	}(),

	updateTargetTransform: function () {

		var matrix = new THREE.Matrix4();

		var position = new THREE.Vector3();
		var quaternion = new THREE.Quaternion();
		var scale = new THREE.Vector3( 1, 1, 1 );

		return function ( obj3d, transform, offset ) {

			var pos = transform.getOrigin(),
				quat = transform.getRotation();

			if ( offset ) {

				position.set( pos.x(), pos.y(), pos.z() );
				quaternion.set( quat.x(), quat.y(), quat.z(), quat.w() );

				matrix.compose( position, quaternion, scale );

				matrix.multiplyMatrices( matrix, offset );

				obj3d.position.setFromMatrixPosition( matrix );
				obj3d.quaternion.setFromRotationMatrix( matrix );

			} else {

				obj3d.position.set( pos.x(), pos.y(), pos.z() );
				obj3d.quaternion.set( quat.x(), quat.y(), quat.z(), quat.w() );

			}

			return this;

		};

	}(),
	update: function ( delta, iteration, fixedDelta ) {

		this.world.stepSimulation( delta, iteration || 0, fixedDelta || ( 60 / 1000 ) );

		var i, j;

		for ( i = 0; i < this.vehicles.length; i ++ ) {

			var vehicle = this.vehicles[ i ],
				numWheels = vehicle.getNumWheels(),
				wheels = this.vehiclesWheels[ i ];

			for ( j = 0; j < numWheels; j ++ ) {

				vehicle.updateWheelTransform( j, true );

				var wheelsTransform = vehicle.getWheelTransformWS( j ),
					wheelTarget = wheels[ j ];

				if ( wheelTarget ) {

					this.updateTargetTransform( wheelTarget, wheelsTransform, target.physics ? wheelTarget.physics.offset : null );

				}

			}

		}

		for ( i = 0; i < this.rigidBodies.length; i ++ ) {

			var rb = this.rigidBodies[ i ],
				target = this.rigidBodiesTarget[ i ];

			if ( target && rb.isActive() ) {

				this.updateTargetTransform( target, rb.getWorldTransform(), target.physics ? target.physics.offset : null );

			}

		}

		return this;

	}
};
<commit_msg>fix wheel offset<commit_after>/**   _     _   _         _____  __   _______  ______
*    | |___| |_| |__    /__  |  |  |     |  _  | * *
*    | / _ \  _|    |    __\    |  |  \  |  _  |  U _
*    |_\___/\__|_||_| _ |____/____ |__ \_|_  |_|_____|
*
*    @author LoTh / http://3dflashlo.wordpress.com/
*    @author SUNAG / http://www.sunag.com.br/
*    @author Ammo.lab / https://github.com/lo-th/Ammo.lab/
*/

'use strict';

SEA3D.AMMO = {

	world: null,

	rigidBodies: [],
	rigidBodiesTarget: [],
	rigidBodiesEnabled: [],

	constraints: [],

	vehicles: [],
	vehiclesWheels: [],

	ACTIVE: 1,
	ISLAND_SLEEPING: 2,
	WANTS_DEACTIVATION: 3,
	DISABLE_DEACTIVATION: 4,
	DISABLE_SIMULATION: 5,
	VERSION: 0.8,

	init: function ( gravity, worldScale, broadphase ) {

		gravity = gravity !== undefined ? gravity : - 90.8;

		this.worldScale = worldScale == undefined ? 1 : worldScale;
		this.broadphase = broadphase == undefined ? 'bvt' : broadphase;

		this.solver = new Ammo.btSequentialImpulseConstraintSolver();
		this.collisionConfig = new Ammo.btDefaultCollisionConfiguration();
		this.dispatcher = new Ammo.btCollisionDispatcher( this.collisionConfig );

		switch ( this.broadphase ) {

			case 'bvt':

				this.broadphase = new Ammo.btDbvtBroadphase();

				break;

			case 'sap':

				this.broadphase = new Ammo.btAxisSweep3(
					new Ammo.btVector3( - this.worldScale, - this.worldScale, - this.worldScale ),
					new Ammo.btVector3( this.worldScale, this.worldScale, this.worldScale ),
					4096
				);

				break;

			case 'simple':

				this.broadphase = new Ammo.btSimpleBroadphase();

				break;

		}

		this.world = new Ammo.btDiscreteDynamicsWorld( this.dispatcher, this.broadphase, this.solver, this.collisionConfig );

		this.setGravity( gravity );

		console.log( "THREE.AMMO " + this.VERSION );

	},

	setGravity: function ( gravity ) {

		this.gravity = gravity;

		this.world.setGravity( new Ammo.btVector3( 0, gravity, 0 ) );

		return this;

	},
	getGravity: function () {

		return this.gravity;

	},

	setEnabledRigidBody: function ( rb, enabled ) {

		if ( this.getEnabledRigidBody( rb ) == enabled ) return;

		if ( enabled ) this.world.addRigidBody( rb );
		else this.world.removeRigidBody( rb );

		return this;

	},
	getEnabledRigidBody: function ( rb ) {

		return this.rigidBodiesEnabled[ this.rigidBodies.indexOf( rb ) ] === true;

	},
	addRigidBody: function ( rb, target, enabled ) {

		enabled = enabled !== undefined ? enabled : true;

		this.rigidBodies.push( rb );
		this.rigidBodiesTarget.push( target );
		this.rigidBodiesEnabled.push( false );

		this.setEnabledRigidBody( rb, enabled );

		return this;

	},
	removeRigidBody: function ( rb, destroy ) {

		var index = this.rigidBodies.indexOf( rb );

		this.setEnabledRigidBody( rb, false );

		this.rigidBodies.splice( index, 1 );
		this.rigidBodiesTarget.splice( index, 1 );
		this.rigidBodiesEnabled.splice( index, 1 );

		if ( destroy ) Ammo.destroy( rb );

		return this;

	},
	containsRigidBody: function ( rb ) {

		return this.rigidBodies.indexOf( rb ) > - 1;

	},

	addConstraint: function ( ctrt, disableCollisionsBetweenBodies ) {

		disableCollisionsBetweenBodies = disableCollisionsBetweenBodies == undefined ? true : disableCollisionsBetweenBodies;

		this.constraints.push( ctrt );
		this.world.addConstraint( ctrt, disableCollisionsBetweenBodies );

		return this;

	},
	removeConstraint: function ( ctrt, destroy ) {

		this.constraints.splice( this.constraints.indexOf( ctrt ), 1 );
		this.world.removeConstraint( ctrt );

		if ( destroy ) Ammo.destroy( ctrt );

		return this;

	},
	containsConstraint: function ( ctrt ) {

		return this.constraints.indexOf( rb ) > - 1;

	},

	addVehicle: function ( vehicle, wheels ) {

		this.vehicles.push( vehicle );
		this.vehiclesWheels.push( wheels != undefined ? wheels : [] );

		this.world.addAction( vehicle );

		return this;

	},
	removeVehicle: function ( vehicle, destroy ) {

		var index = this.vehicles.indexOf( vehicle );

		this.vehicles.splice( index, 1 );
		this.vehiclesWheels.splice( index, 1 );

		this.world.removeAction( vehicle );

		if ( destroy ) Ammo.destroy( vehicle );

		return this;

	},
	containsVehicle: function ( vehicle ) {

		return this.vehicles.indexOf( vehicle ) > - 1;

	},

	createTriangleMesh: function ( geometry, index, removeDuplicateVertices ) {

		index = index == undefined ? - 1 : index;
		removeDuplicateVertices = removeDuplicateVertices == undefined ? false : removeDuplicateVertices;

		var mTriMesh = new Ammo.btTriangleMesh();

		var v0 = new Ammo.btVector3( 0, 0, 0 );
		var v1 = new Ammo.btVector3( 0, 0, 0 );
		var v2 = new Ammo.btVector3( 0, 0, 0 );

		var vertex = geometry.getAttribute( 'position' ).array;
		var indexes = geometry.getIndex().array;

		var group = index >= 0 ? geometry.groups[ index ] : undefined,
			start = group ? group.start : 0,
			count = group ? group.count : indexes.length;

		var scale = 1 / this.worldScale;

		for ( var idx = start; idx < count; idx += 3 ) {

			var vx1 = indexes[ idx ] * 3,
				vx2 = indexes[ idx + 1 ] * 3,
				vx3 = indexes[ idx + 2 ] * 3;

			v0.setValue( vertex[ vx1 ] * scale, vertex[ vx1 + 1 ] * scale, vertex[ vx1 + 2 ] * scale );
			v1.setValue( vertex[ vx2 ] * scale, vertex[ vx2 + 1 ] * scale, vertex[ vx2 + 2 ] * scale );
			v2.setValue( vertex[ vx3 ] * scale, vertex[ vx3 + 1 ] * scale, vertex[ vx3 + 2 ] * scale );

			mTriMesh.addTriangle( v0, v1, v2, removeDuplicateVertices );

		}

		return mTriMesh;

	},
	createConvexHull: function ( geometry, index ) {

		index = index == undefined ? - 1 : index;

		var mConvexHull = new Ammo.btConvexHullShape();

		var v0 = new Ammo.btVector3( 0, 0, 0 );

		var vertex = geometry.getAttribute( 'position' ).array;
		var indexes = geometry.getIndex().array;

		var group = index >= 0 ? geometry.groups[ index ] : undefined,
			start = group ? group.start : 0,
			count = group ? group.count : indexes.length;

		var scale = 1 / this.worldScale;

		for ( var idx = start; idx < count; idx += 3 ) {

			var vx1 = indexes[ idx ] * 3;

			var point = new Ammo.btVector3(
				vertex[ vx1 ] * scale, vertex[ vx1 + 1 ] * scale, vertex[ vx1 + 2 ] * scale
			);

			mConvexHull.addPoint( point );

		}

		return mConvexHull;

	},

	getTargetByRigidBody: function ( rb ) {

		return this.rigidBodiesTarget[ this.rigidBodies.indexOf( rb ) ];

	},
	getRigidBodyByTarget: function ( target ) {

		return this.rigidBodies[ this.rigidBodiesTarget.indexOf( target ) ];

	},
	getTransformFromMatrix: function ( mtx ) {

		var transform = new Ammo.btTransform();

		var pos = THREE.SEA3D.VECBUF.setFromMatrixPosition( mtx );
		transform.setOrigin( new Ammo.btVector3( pos.x, pos.y, pos.z ) );

		var scl = THREE.SEA3D.VECBUF.setFromMatrixScale( mtx );
		mtx.scale( scl.set( 1 / scl.x, 1 / scl.y, 1 / scl.z ) );

		var quat = new THREE.Quaternion().setFromRotationMatrix( mtx );

		var q = new Ammo.btQuaternion();
		q.setValue( quat.x, quat.y, quat.z, quat.w );
		transform.setRotation( q );

		Ammo.destroy( q );

		return transform;

	},
	getMatrixFromTransform: function ( transform ) {

		var position = new THREE.Vector3();
		var quaternion = new THREE.Quaternion();
		var scale = new THREE.Vector3( 1, 1, 1 );

		return function ( transform, matrix ) {

			matrix = matrix || new THREE.Matrix4();

			var pos = transform.getOrigin(),
				quat = transform.getRotation();

			position.set( pos.x(), pos.y(), pos.z() );
			quaternion.set( quat.x(), quat.y(), quat.z(), quat.w() );

			matrix.compose( position, quaternion, scale );

			return matrix;

		};

	}(),

	updateTargetTransform: function () {

		var matrix = new THREE.Matrix4();

		var position = new THREE.Vector3();
		var quaternion = new THREE.Quaternion();
		var scale = new THREE.Vector3( 1, 1, 1 );

		return function ( obj3d, transform, offset ) {

			var pos = transform.getOrigin(),
				quat = transform.getRotation();

			if ( offset ) {

				position.set( pos.x(), pos.y(), pos.z() );
				quaternion.set( quat.x(), quat.y(), quat.z(), quat.w() );

				matrix.compose( position, quaternion, scale );

				matrix.multiplyMatrices( matrix, offset );

				obj3d.position.setFromMatrixPosition( matrix );
				obj3d.quaternion.setFromRotationMatrix( matrix );

			} else {

				obj3d.position.set( pos.x(), pos.y(), pos.z() );
				obj3d.quaternion.set( quat.x(), quat.y(), quat.z(), quat.w() );

			}

			return this;

		};

	}(),
	update: function ( delta, iteration, fixedDelta ) {

		this.world.stepSimulation( delta, iteration || 0, fixedDelta || ( 60 / 1000 ) );

		var i, j;

		for ( i = 0; i < this.vehicles.length; i ++ ) {

			var vehicle = this.vehicles[ i ],
				numWheels = vehicle.getNumWheels(),
				wheels = this.vehiclesWheels[ i ];

			for ( j = 0; j < numWheels; j ++ ) {

				vehicle.updateWheelTransform( j, true );

				var wheelsTransform = vehicle.getWheelTransformWS( j ),
					wheelTarget = wheels[ j ];

				if ( wheelTarget ) {

					this.updateTargetTransform( wheelTarget, wheelsTransform, wheelTarget.physics ? wheelTarget.physics.offset : null );

				}

			}

		}

		for ( i = 0; i < this.rigidBodies.length; i ++ ) {

			var rb = this.rigidBodies[ i ],
				target = this.rigidBodiesTarget[ i ];

			if ( target && rb.isActive() ) {

				this.updateTargetTransform( target, rb.getWorldTransform(), target.physics ? target.physics.offset : null );

			}

		}

		return this;

	}
};
<|endoftext|>


<commit_before>/*global defineSuite*/
defineSuite([
        'Scene/Cesium3DTileStyle',
        'Scene/Expression'
    ], function(
        Cesium3DTileStyle,
        Expression) {
    'use strict';

    function MockStyleEngine() {
    }

    MockStyleEngine.prototype.makeDirty = function() {
    };

    function MockTileset(styleEngine) {
        this.styleEngine = styleEngine;
    }

    it ('sets show value to default expression', function() {
        var styleEngine = new MockStyleEngine();
        var tileset = new MockTileset(styleEngine);

        var style = new Cesium3DTileStyle(tileset, {

        });
        expect(style.show).toEqual(new Expression(styleEngine, 'true'));

        style = new Cesium3DTileStyle(tileset);
        expect(style.show).toEqual(new Expression(styleEngine, 'true'));
    });

    it ('sets show value to expression', function() {
        var styleEngine = new MockStyleEngine();
        var tileset = new MockTileset(styleEngine);

        var style = new Cesium3DTileStyle(tileset, {
            show : 'true'
        });
        expect(style.show).toEqual(new Expression(styleEngine, 'true'));

        style = new Cesium3DTileStyle(tileset, {
            show : 'false'
        });
        expect(style.show).toEqual(new Expression(styleEngine, 'false'));

        style = new Cesium3DTileStyle(tileset, {
            show : '${height} * 10 >= 1000'
        });
        expect(style.show).toEqual(new Expression(styleEngine, '${height} * 10 >= 1000'));

        style = new Cesium3DTileStyle(new MockTileset(new MockStyleEngine()), {
            show : true
        });
        expect(style.show).toEqual(new Expression(styleEngine, 'true'));

        style = new Cesium3DTileStyle(new MockTileset(new MockStyleEngine()), {
            show : false
        });
        expect(style.show).toEqual(new Expression(styleEngine, 'false'));
    });

    it ('sets show to undefined if not a string or a boolean', function() {
        var styleEngine = new MockStyleEngine();
        var tileset = new MockTileset(styleEngine);

        var style = new Cesium3DTileStyle(tileset, {
            show : 1
        });
        expect(style.show).toEqual(undefined);
    });
});<commit_msg>Add test for applying style to a tileset<commit_after>/*global defineSuite*/
defineSuite([
        'Scene/Cesium3DTileStyle',
        'Core/Cartesian3',
        'Core/Color',
        'Core/HeadingPitchRange',
        'Renderer/ContextLimits',
        'Scene/Expression',
        'Specs/Cesium3DTilesTester',
        'Specs/createScene'
    ], function(
        Cesium3DTileStyle,
        Cartesian3,
        Color,
        HeadingPitchRange,
        ContextLimits,
        Expression,
        Cesium3DTilesTester,
        createScene) {
    'use strict';

    function MockStyleEngine() {
    }

    MockStyleEngine.prototype.makeDirty = function() {
    };

    function MockTileset(styleEngine) {
        this.styleEngine = styleEngine;
    }

    var scene;
    var centerLongitude = -1.31968;
    var centerLatitude = 0.698874;

    var withoutBatchTableUrl = './Data/Cesium3DTiles/Batched/BatchedWithoutBatchTable/';

    it ('sets show value to default expression', function() {
        var styleEngine = new MockStyleEngine();
        var tileset = new MockTileset(styleEngine);

        var style = new Cesium3DTileStyle(tileset, {

        });
        expect(style.show).toEqual(new Expression(styleEngine, 'true'));

        style = new Cesium3DTileStyle(tileset);
        expect(style.show).toEqual(new Expression(styleEngine, 'true'));
    });

    it ('sets show value to expression', function() {
        var styleEngine = new MockStyleEngine();
        var tileset = new MockTileset(styleEngine);

        var style = new Cesium3DTileStyle(tileset, {
            show : 'true'
        });
        expect(style.show).toEqual(new Expression(styleEngine, 'true'));

        style = new Cesium3DTileStyle(tileset, {
            show : 'false'
        });
        expect(style.show).toEqual(new Expression(styleEngine, 'false'));

        style = new Cesium3DTileStyle(tileset, {
            show : '${height} * 10 >= 1000'
        });
        expect(style.show).toEqual(new Expression(styleEngine, '${height} * 10 >= 1000'));

        style = new Cesium3DTileStyle(new MockTileset(new MockStyleEngine()), {
            show : true
        });
        expect(style.show).toEqual(new Expression(styleEngine, 'true'));

        style = new Cesium3DTileStyle(new MockTileset(new MockStyleEngine()), {
            show : false
        });
        expect(style.show).toEqual(new Expression(styleEngine, 'false'));
    });

    it ('sets show to undefined if not a string or a boolean', function() {
        var styleEngine = new MockStyleEngine();
        var tileset = new MockTileset(styleEngine);

        var style = new Cesium3DTileStyle(tileset, {
            show : 1
        });
        expect(style.show).toEqual(undefined);
    });

    it('renders translucent style when vertex texture fetch is not supported', function() {
        scene = createScene();

        // One building in each data set is always located in the center, so point the camera there
        var center = Cartesian3.fromRadians(centerLongitude, centerLatitude, 5.0);
        scene.camera.lookAt(center, new HeadingPitchRange(0.0, -1.57, 10.0));

        // Disable VTF
        var maximumVertexTextureImageUnits = ContextLimits.maximumVertexTextureImageUnits;
        ContextLimits._maximumVertexTextureImageUnits = 0;

        return Cesium3DTilesTester.loadTileset(scene, withoutBatchTableUrl).then(function(tileset) {
            var showColor = scene.renderForSpecs();

            tileset.style = new Cesium3DTileStyle(tileset, {show : 'false'});
            var hideColor = scene.renderForSpecs();
            expect(hideColor).not.toEqual(showColor);
            expect(hideColor).toEqual([0, 0, 0, 255]);

            tileset.style = new Cesium3DTileStyle(tileset, {show : 'true'});
            var restoredShow = scene.renderForSpecs();
            expect(restoredShow).toEqual(showColor);

            // Re-enable VTF
            ContextLimits._maximumVertexTextureImageUnits = maximumVertexTextureImageUnits;

            scene.primitives.removeAll();

            scene.destroyForSpecs();
        });
    });
}, 'WebGL');<|endoftext|>


<commit_before>/*
* @Author: Manraj Singh
* @Date:   2016-08-13 20:55:37
* @Last Modified by:   Manraj Singh
* @Last Modified time: 2016-08-13 20:57:52
*/

'use strict';

const Music = ["MP3", "WAV", "WMA", "MKA", "AAC", "MID", "RA", "RAM", "RM", "OGG"];
const Codes = ["CPP", "RB", "PY", "HTML", "CSS", "JS"];
const Compressed = ["RAR", "JAR", "ZIP", "TAR", "MAR", "ISO", "LZ", "7ZIP", "TGZ", "GZ", "BZ2"];
const Documents = ["DOC", "DOCX", "PPT", "PPTX", "PAGES", "PDF", "ODT", "ODP", "XLSX", "XLS", "ODS", "TXT", "IN", "OUT", "MD"];
const Images = ["JPG", "JPEG", "GIF", "PNG", "SVG"];
const sys_files = ["DEB", "EXE", "SH", "BUNDLE"];
const Video = ["FLV", "WMV", "MOV", "MP4", "MPEG", "3GP", "MKV"];

module.exports = {
  Music,
  Codes,
  Compressed,
  Documents,
  Images,
  Video,
  "System Files" : sys_files,
};
<commit_msg>fix #11<commit_after>/*
* @Author: Manraj Singh
* @Date:   2016-08-13 20:55:37
* @Last Modified by:   Manraj Singh
* @Last Modified time: 2016-08-13 20:57:52
*/

'use strict';

const Music = ["MP3", "WAV", "WMA", "MKA", "AAC", "MID", "RA", "RAM", "RM", "OGG"];
const Codes = ["CPP", "RB", "PY", "HTML", "CSS", "JS"];
const Compressed = ["RAR", "JAR", "ZIP", "TAR", "MAR", "ISO", "LZ", "7ZIP", "TGZ", "GZ", "BZ2"];
const Documents = ["DOC", "DOCX", "PPT", "PPTX", "PAGES", "PDF", "ODT", "ODP", "XLSX", "XLS", "ODS", "TXT", "IN", "OUT", "MD"];
const Images = ["JPG", "JPEG", "GIF", "PNG", "SVG"];
const Executables = ["DEB", "EXE", "SH", "BUNDLE"];
const Video = ["FLV", "WMV", "MOV", "MP4", "MPEG", "3GP", "MKV"];

module.exports = {
  Music,
  Codes,
  Compressed,
  Documents,
  Images,
  Video,
  Executables,
};
<|endoftext|>