<commit_before>var MapproxyBaseService = function(_section, _model, _dependencies) {
    var _this = this;
    this._items = {};
    this._item;
    this._last;
    this._section = _section;
    this._action;
    this._dependencies = _dependencies;
    this._model = _model;
    this._rootScope;
    this._resource;
    this._messageService;
    this.error;

    this._errorMessageHandler = function(error) {
        _this._rootScope.$broadcast(_this._section + '.' + _this._action + '_error');
        _this._messageService.message(_this._section, _this._action + '_error', error.data.error);
    };
    this._successMessageHandler = function(msg) {
        _this._messageService.message(_this._section, _this._action + '_success', msg);
    };
    this._addDependencies = function(item) {
        item._dependencies = {};
        angular.forEach(_this._dependencies, function(dependency) {
            item._dependencies[dependency._section] = []
            angular.forEach(dependency._items, function(dependencyItem) {
                var useSection = _this._section;
                //layers only have sources for cache- and source-items
                if(item._section == 'caches' && dependencyItem._section == 'layers') {
                    useSection = 'sources';
                }
                if($.inArray(item._id, dependencyItem.data[useSection]) != -1) {
                    item._dependencies[dependency._section].push(dependencyItem);
                }
            });
        });
    };
    this._waitForLoadComplete = function(event) {
        var name = event.name.split('.')[0];
        var loadComplete = _this._loaded;
        angular.forEach(_this.dependencies, function(dependency) {
            if(!dependency._loaded) {
                loadComplete = false;
            }
        });
        if(loadComplete) {
            angular.forEach(_this._items, _this._addDependencies);
            _this._successMessageHandler(_this._localize.getLocalizedString('Load complete'));
        }
    };
    this._removeNonModelProperties = function(data) {
        var cleanup = function(cleanData, data) {
            var _data = {};
            angular.forEach(cleanData, function(value, key) {
                if(angular.isObject(cleanData[key]) && !angular.isArray(cleanData[key])) {
                    _data[key] = cleanup(cleanData[key], data[key]);
                } else {
                    if(angular.isDefined(data)) {
                        _data[key] = data[key]
                    }
                }
            });
            return _data;
        };
        return cleanup(_this._model, data);;
    };
    this.load = function() {
        _this._items = {};
        _this._loaded = false;
        _this._action = 'load';
        _this._loadingInProgress = true;
        _this._resource.query({action: _this._section}, function(result) {
            if(result) {
                angular.forEach(result, function(item) {
                    item._section = _this._section;
                    _this._items[item._id] = item;
                });
                _this._loaded = true;
                _this._loadingInProgress = false;
                if(angular.isDefined(_this._rootScope))
                    _this._rootScope.$broadcast(_this._section + '.load_finished');
            }
        }, _this._errorMessageHandler);
    };
    this.add = function(_item) {
        if(_this._model && !_item._manual) {
            _item.data = _this._removeNonModelProperties(_item.data);
        }
        var item = new _this._resource(_item);
        delete item._dependencies;
        delete item._section;
        if(angular.isUndefined(item._id)) {
            _this._action = 'add';
            item.$save({action: _this._section},
                function(result) {
                    result._section = _this._section;
                    _this._addDependencies(result);
                    _this._items[result._id] = result;
                    _this._successMessageHandler(_this._localize.getLocalizedString('Successful added'));
                    if(angular.isDefined(_this._rootScope)) {
                        _this._last = result;
                        _this.current(result);
                    }
                }, _this._errorMessageHandler);
        } else {
            _this._action = 'update';
            item.$update({action: _this._section, id: item._id}, function(result) {
                result._section = _this._section;
                _this._addDependencies(result);
                _this._items[result._id] = result;
                _this._successMessageHandler(_this._localize.getLocalizedString('Successful updated'));
                if(angular.isDefined(_this._rootScope)) {
                    _this._last = result;
                    _this.current(result);
                }
            }, _this._errorMessageHandler);
        }
    };
    this.remove = function(_item) {
        var item = new _this._resource(_item)
        _this._action = 'delete';
        item.$delete({action: _this._section, id: item._id}, function(result) {
            delete(_this._items[result._id]);
            _this._successMessageHandler(_this._localize.getLocalizedString('Successful deleted'));
        }, _this._errorMessageHandler);
    };
    this.list = function() {
        var result = [];
        for(var key in _this._items) {
            result.push(_this._items[key]);
        }
        return result;
    };
    this.byId = function(_id) {
        return angular.isDefined(_this._items[_id]) ? _this._items[_id] : false;
    };
    this.byName = function(_name) {
        for(var id in _this._items) {
            if(_this._items[id].data.name == _name) {
                return _this._items[id];
            }
        }
        return false;
    };
    this.idByName = function(_name) {
        var item = _this.byName(_name);
        return item ? item._id : false;

    };
    this.nameById = function(_id) {
        var item = _this.byId(_id);
        return item ? item.data.name : false;
    };
    this.current = function(_item) {
        if(_item) {
            _this._item = _item;
            if(angular.isDefined(_this._rootScope))
                _this._rootScope.$broadcast(_this._section + '.current');
        } else {
            return $.extend({}, {'data': _this._model}, _this._item);
        }
    };
    this.last = function() {
        return _this._last;
    };
    this.error = function() {
        return _this._error_msg;
    }
    this.return_func = function($rootScope, MapproxyResource, MessageService, localize) {
        _this._rootScope = $rootScope;
        _this._resource = MapproxyResource;
        _this._messageService = MessageService;
        _this._localize = localize;
        _this._rootScope.$on(_this._section + '.load_finished', _this._waitForLoadComplete);
        angular.forEach(_this._dependencies, function(dependency) {
            _this._rootScope.$on(dependency._section + '.load_finished', _this._waitForLoadComplete)
            dependency.return_func(_this._rootScope, _this._resource, _this._messageService, _this._localize);
        });
        if(!_this._loadingInProgress && !_this._loaded) {
            _this.load();
        }
        return _this.return_dict;
    };

    this.return_dict = {
        refresh: _this.load,
        add: _this.add,
        remove: _this.remove,
        list: _this.list,
        byId: _this.byId,
        byName: _this.byName,
        idByName: _this.idByName,
        nameById: _this.nameById,
        current: _this.current,
        last: _this.last,
        error: _this.error,
        section: _this._section,
        model: _this._model
    }
};

var MapproxyLayerService = function(_section, _model, _dependencies) {
    MapproxyBaseService.call(this, _section, _model, _dependencies);
    var _this = this;

    this.prepareLayer = function(store, layer, idx, parent_id) {
        if(angular.isDefined(layer._layers)) {
            angular.forEach(layer._layers, function(child_layer, _idx) {
                _this.prepareLayer(store, child_layer, _idx, layer._id);
            });
        }
        store.push({_id: layer._id, _rank: idx, _parent: parent_id})
    };

    this.tree = function(parent_id) {
        var treeStructure = [];
        var items = angular.copy(_this._items);
        angular.forEach(items, function(item) {
            if(item._parent == null) {
                if($.inArray(item, treeStructure) == -1) {
                    treeStructure.push(item);
                }
            } else {
                if(angular.isArray(items[item._parent]._layers)) {
                    if($.inArray(item, items[item._parent]) == -1) {
                        items[item._parent]._layers.push(item)
                    }
                } else {
                    items[item._parent]._layers = [item]
                }
            }
        });
        return treeStructure;
    };

    this.updateStructure = function(tree) {
        var to_update = [];
        _this._action = 'updateStructure';
        angular.forEach(tree, function(layer, idx) {
            _this.prepareLayer(to_update, layer, idx);
        });
        to_update = new _this._resource({'tree': to_update});
        to_update.$update({action: _this._section}, function(result) {
            _this._successMessageHandler(_this._localize.getLocalizedString('Structure successful updated'));
        }, _this._errorMessageHandler);
    };

    this.return_dict['tree'] = _this.tree;
    this.return_dict['updateStructure'] = _this.updateStructure;
};

WMSSourceService = function(_section) {
    MapproxyBaseService.call(this, _section);
    var _this = this;

    this._addSourceURL = function(layer, sourceURL) {
        layer.sourceURL = sourceURL;
        if(angular.isDefined(layer.layers)) {
            angular.forEach(layer.layers, function(layer) {
                _this._addSourceURL(layer, sourceURL);
            });
        }
    };
    this.list = function() {
        var result = [];
        angular.forEach(_this._items, function(item) {
            var sourceURL = item.data.url;
            angular.forEach(item.data.layer.layers, function(layer) {
                _this._addSourceURL(layer, sourceURL)
            });
        });
        for(var key in _this._items) {
            result.push(_this._items[key]);
        }
        return result;
    };
    this._identifySource = function(url) {
        var source = false;
        angular.forEach(_this._items, function(_source) {
            if(_source.data.url == url) {
                source = _source;
            }
        });
        return source;
    };
    this._identifyLayer = function(layers, layerName) {
        var layer = false;
        angular.forEach(layers, function(_layer) {
            if(!layer) {
                if(_layer.name == layerName) {
                    layer = _layer;
                } else if(angular.isDefined(_layer.layers)) {
                    layer = _this._identifyLayer(_layer.layers, layerName);
                }
            }
        });
        return layer;
    };

    this.layerTitle = function(url, layerName) {
        var source = _this._identifySource(url);
        if(source) {
            var layer = _this._identifyLayer(source.data.layer.layers, layerName);
            if(layer) {
                return layer.title;
            }
        }
        return false;
    };

    this.coverage = function(url) {
        var source = _this._identifySource(url);
        if(source) {
            return source.data.layer.llbbox;
        }
        return false;
    };

    this.srs = function(url) {
        var source = _this._identifySource(url);
        if(source) {
            return source.data.layer.srs;
        }
        return false;
    };

    this.refresh = function(_item) {
        var item = new _this._resource(_item);
        _this._action = 'update';
        item.$update({action: _this._section, id: item._id}, function(result) {
            _this._items[result._id] = result;
            _this._last = result;
            _this._successMessageHandler(_this._localize.getLocalizedString('Successful updated'));
        }, _this._errorMessageHandler);
    };

    this.allURLs = function() {
        var result = [];
        angular.forEach(_this._items, function(wms) {
            result.push(wms.url);
        });
        return result;
    };

    this.return_dict['list'] = _this.list;
    this.return_dict['layerTitle'] = _this.layerTitle;
    this.return_dict['refresh'] = _this.refresh;
    this.return_dict['allURLs'] = _this.allURLs;
    this.return_dict['coverage'] = _this.coverage;
    this.return_dict['srs'] = _this.srs;
};

var layerModel = {
    'name': undefined,
    'title': undefined,
    'sources': [],
    'min_res': undefined,
    'max_res': undefined,
    'min_res_scale': undefined,
    'max_res_scale': undefined
};
var globalsModel = {
    'cache': {
        'meta_size': [],
        'meta_buffer': undefined
    },
    'image': {
        'resampling_method': undefined,
        'paletted': undefined
    }
};
var cacheModel = {
    'name': undefined,
    'sources': [],
    'grids': [],
    'format': undefined,
    'request_format': undefined
};
var gridModel = {
    'name': undefined,
    'srs': undefined,
    'bbox': [],
    'bbox_srs': undefined,
    'origin': undefined,
    'res': [],
    'scales': []
};
var sourceModel = {
    'name': undefined,
    'req': {
        'url': undefined,
        'layers': [],
        'transparent': undefined
    },
    'coverage': {
        'bbox': undefined,
        'srs': undefined
    },
    'supported_formats': []
};
var defaultsModel = {
    'dpi': undefined,
    'srs': []
};

var layerService = new MapproxyLayerService('layers', layerModel);
var globalsService = new MapproxyBaseService('globals', globalsModel);
var servicesService = new MapproxyBaseService('services');
var cacheService = new MapproxyBaseService('caches', cacheModel, [layerService]);
var gridService = new MapproxyBaseService('grids', gridModel, [cacheService]);
var sourceService = new MapproxyBaseService('sources', sourceModel, [cacheService, layerService]);
var wmsService = new WMSSourceService('wms_capabilities');
var defaultsService = new MapproxyBaseService('defaults', defaultsModel);

angular.module('mapproxy_gui.services', ['mapproxy_gui.resources']).

service('WMSSources', wmsService.return_func).
service('MapproxySources', sourceService.return_func).
service('MapproxyCaches', cacheService.return_func).
service('MapproxyGrids', gridService.return_func).
service('MapproxyLayers', layerService.return_func).
service('MapproxyGlobals', globalsService.return_func).
service('MapproxyServices', servicesService.return_func).
service('ProjectDefaults', defaultsService.return_func).

service('DataShareService', function($rootScope) {
    var _this = this;
    this._data = {};

    return {
        data: function(key, value) {
            if(angular.isDefined(value)) {
                _this._data[key] = value;
                $rootScope.$broadcast('dss.' + key);
            } else {
                if(angular.isDefined(_this._data[key])) {
                    return _this._data[key];
                } else {
                    return undefined;
                }
            }
        }
    }
});
<commit_msg>Add min_/max_res_scale to source model<commit_after>var MapproxyBaseService = function(_section, _model, _dependencies) {
    var _this = this;
    this._items = {};
    this._item;
    this._last;
    this._section = _section;
    this._action;
    this._dependencies = _dependencies;
    this._model = _model;
    this._rootScope;
    this._resource;
    this._messageService;
    this.error;

    this._errorMessageHandler = function(error) {
        _this._rootScope.$broadcast(_this._section + '.' + _this._action + '_error');
        _this._messageService.message(_this._section, _this._action + '_error', error.data.error);
    };
    this._successMessageHandler = function(msg) {
        _this._messageService.message(_this._section, _this._action + '_success', msg);
    };
    this._addDependencies = function(item) {
        item._dependencies = {};
        angular.forEach(_this._dependencies, function(dependency) {
            item._dependencies[dependency._section] = []
            angular.forEach(dependency._items, function(dependencyItem) {
                var useSection = _this._section;
                //layers only have sources for cache- and source-items
                if(item._section == 'caches' && dependencyItem._section == 'layers') {
                    useSection = 'sources';
                }
                if($.inArray(item._id, dependencyItem.data[useSection]) != -1) {
                    item._dependencies[dependency._section].push(dependencyItem);
                }
            });
        });
    };
    this._waitForLoadComplete = function(event) {
        var name = event.name.split('.')[0];
        var loadComplete = _this._loaded;
        angular.forEach(_this.dependencies, function(dependency) {
            if(!dependency._loaded) {
                loadComplete = false;
            }
        });
        if(loadComplete) {
            angular.forEach(_this._items, _this._addDependencies);
            _this._successMessageHandler(_this._localize.getLocalizedString('Load complete'));
        }
    };
    this._removeNonModelProperties = function(data) {
        var cleanup = function(cleanData, data) {
            var _data = {};
            angular.forEach(cleanData, function(value, key) {
                if(angular.isObject(cleanData[key]) && !angular.isArray(cleanData[key])) {
                    _data[key] = cleanup(cleanData[key], data[key]);
                } else {
                    if(angular.isDefined(data)) {
                        _data[key] = data[key]
                    }
                }
            });
            return _data;
        };
        return cleanup(_this._model, data);;
    };
    this.load = function() {
        _this._items = {};
        _this._loaded = false;
        _this._action = 'load';
        _this._loadingInProgress = true;
        _this._resource.query({action: _this._section}, function(result) {
            if(result) {
                angular.forEach(result, function(item) {
                    item._section = _this._section;
                    _this._items[item._id] = item;
                });
                _this._loaded = true;
                _this._loadingInProgress = false;
                if(angular.isDefined(_this._rootScope))
                    _this._rootScope.$broadcast(_this._section + '.load_finished');
            }
        }, _this._errorMessageHandler);
    };
    this.add = function(_item) {
        if(_this._model && !_item._manual) {
            _item.data = _this._removeNonModelProperties(_item.data);
        }
        var item = new _this._resource(_item);
        delete item._dependencies;
        delete item._section;
        if(angular.isUndefined(item._id)) {
            _this._action = 'add';
            item.$save({action: _this._section},
                function(result) {
                    result._section = _this._section;
                    _this._addDependencies(result);
                    _this._items[result._id] = result;
                    _this._successMessageHandler(_this._localize.getLocalizedString('Successful added'));
                    if(angular.isDefined(_this._rootScope)) {
                        _this._last = result;
                        _this.current(result);
                    }
                }, _this._errorMessageHandler);
        } else {
            _this._action = 'update';
            item.$update({action: _this._section, id: item._id}, function(result) {
                result._section = _this._section;
                _this._addDependencies(result);
                _this._items[result._id] = result;
                _this._successMessageHandler(_this._localize.getLocalizedString('Successful updated'));
                if(angular.isDefined(_this._rootScope)) {
                    _this._last = result;
                    _this.current(result);
                }
            }, _this._errorMessageHandler);
        }
    };
    this.remove = function(_item) {
        var item = new _this._resource(_item)
        _this._action = 'delete';
        item.$delete({action: _this._section, id: item._id}, function(result) {
            delete(_this._items[result._id]);
            _this._successMessageHandler(_this._localize.getLocalizedString('Successful deleted'));
        }, _this._errorMessageHandler);
    };
    this.list = function() {
        var result = [];
        for(var key in _this._items) {
            result.push(_this._items[key]);
        }
        return result;
    };
    this.byId = function(_id) {
        return angular.isDefined(_this._items[_id]) ? _this._items[_id] : false;
    };
    this.byName = function(_name) {
        for(var id in _this._items) {
            if(_this._items[id].data.name == _name) {
                return _this._items[id];
            }
        }
        return false;
    };
    this.idByName = function(_name) {
        var item = _this.byName(_name);
        return item ? item._id : false;

    };
    this.nameById = function(_id) {
        var item = _this.byId(_id);
        return item ? item.data.name : false;
    };
    this.current = function(_item) {
        if(_item) {
            _this._item = _item;
            if(angular.isDefined(_this._rootScope))
                _this._rootScope.$broadcast(_this._section + '.current');
        } else {
            return $.extend({}, {'data': _this._model}, _this._item);
        }
    };
    this.last = function() {
        return _this._last;
    };
    this.error = function() {
        return _this._error_msg;
    }
    this.return_func = function($rootScope, MapproxyResource, MessageService, localize) {
        _this._rootScope = $rootScope;
        _this._resource = MapproxyResource;
        _this._messageService = MessageService;
        _this._localize = localize;
        _this._rootScope.$on(_this._section + '.load_finished', _this._waitForLoadComplete);
        angular.forEach(_this._dependencies, function(dependency) {
            _this._rootScope.$on(dependency._section + '.load_finished', _this._waitForLoadComplete)
            dependency.return_func(_this._rootScope, _this._resource, _this._messageService, _this._localize);
        });
        if(!_this._loadingInProgress && !_this._loaded) {
            _this.load();
        }
        return _this.return_dict;
    };

    this.return_dict = {
        refresh: _this.load,
        add: _this.add,
        remove: _this.remove,
        list: _this.list,
        byId: _this.byId,
        byName: _this.byName,
        idByName: _this.idByName,
        nameById: _this.nameById,
        current: _this.current,
        last: _this.last,
        error: _this.error,
        section: _this._section,
        model: _this._model
    }
};

var MapproxyLayerService = function(_section, _model, _dependencies) {
    MapproxyBaseService.call(this, _section, _model, _dependencies);
    var _this = this;

    this.prepareLayer = function(store, layer, idx, parent_id) {
        if(angular.isDefined(layer._layers)) {
            angular.forEach(layer._layers, function(child_layer, _idx) {
                _this.prepareLayer(store, child_layer, _idx, layer._id);
            });
        }
        store.push({_id: layer._id, _rank: idx, _parent: parent_id})
    };

    this.tree = function(parent_id) {
        var treeStructure = [];
        var items = angular.copy(_this._items);
        angular.forEach(items, function(item) {
            if(item._parent == null) {
                if($.inArray(item, treeStructure) == -1) {
                    treeStructure.push(item);
                }
            } else {
                if(angular.isArray(items[item._parent]._layers)) {
                    if($.inArray(item, items[item._parent]) == -1) {
                        items[item._parent]._layers.push(item)
                    }
                } else {
                    items[item._parent]._layers = [item]
                }
            }
        });
        return treeStructure;
    };

    this.updateStructure = function(tree) {
        var to_update = [];
        _this._action = 'updateStructure';
        angular.forEach(tree, function(layer, idx) {
            _this.prepareLayer(to_update, layer, idx);
        });
        to_update = new _this._resource({'tree': to_update});
        to_update.$update({action: _this._section}, function(result) {
            _this._successMessageHandler(_this._localize.getLocalizedString('Structure successful updated'));
        }, _this._errorMessageHandler);
    };

    this.return_dict['tree'] = _this.tree;
    this.return_dict['updateStructure'] = _this.updateStructure;
};

WMSSourceService = function(_section) {
    MapproxyBaseService.call(this, _section);
    var _this = this;

    this._addSourceURL = function(layer, sourceURL) {
        layer.sourceURL = sourceURL;
        if(angular.isDefined(layer.layers)) {
            angular.forEach(layer.layers, function(layer) {
                _this._addSourceURL(layer, sourceURL);
            });
        }
    };
    this.list = function() {
        var result = [];
        angular.forEach(_this._items, function(item) {
            var sourceURL = item.data.url;
            angular.forEach(item.data.layer.layers, function(layer) {
                _this._addSourceURL(layer, sourceURL)
            });
        });
        for(var key in _this._items) {
            result.push(_this._items[key]);
        }
        return result;
    };
    this._identifySource = function(url) {
        var source = false;
        angular.forEach(_this._items, function(_source) {
            if(_source.data.url == url) {
                source = _source;
            }
        });
        return source;
    };
    this._identifyLayer = function(layers, layerName) {
        var layer = false;
        angular.forEach(layers, function(_layer) {
            if(!layer) {
                if(_layer.name == layerName) {
                    layer = _layer;
                } else if(angular.isDefined(_layer.layers)) {
                    layer = _this._identifyLayer(_layer.layers, layerName);
                }
            }
        });
        return layer;
    };

    this.layerTitle = function(url, layerName) {
        var source = _this._identifySource(url);
        if(source) {
            var layer = _this._identifyLayer(source.data.layer.layers, layerName);
            if(layer) {
                return layer.title;
            }
        }
        return false;
    };

    this.coverage = function(url) {
        var source = _this._identifySource(url);
        if(source) {
            return source.data.layer.llbbox;
        }
        return false;
    };

    this.srs = function(url) {
        var source = _this._identifySource(url);
        if(source) {
            return source.data.layer.srs;
        }
        return false;
    };

    this.refresh = function(_item) {
        var item = new _this._resource(_item);
        _this._action = 'update';
        item.$update({action: _this._section, id: item._id}, function(result) {
            _this._items[result._id] = result;
            _this._last = result;
            _this._successMessageHandler(_this._localize.getLocalizedString('Successful updated'));
        }, _this._errorMessageHandler);
    };

    this.allURLs = function() {
        var result = [];
        angular.forEach(_this._items, function(wms) {
            result.push(wms.url);
        });
        return result;
    };

    this.return_dict['list'] = _this.list;
    this.return_dict['layerTitle'] = _this.layerTitle;
    this.return_dict['refresh'] = _this.refresh;
    this.return_dict['allURLs'] = _this.allURLs;
    this.return_dict['coverage'] = _this.coverage;
    this.return_dict['srs'] = _this.srs;
};

var layerModel = {
    'name': undefined,
    'title': undefined,
    'sources': [],
    'min_res': undefined,
    'max_res': undefined,
    'min_res_scale': undefined,
    'max_res_scale': undefined
};
var globalsModel = {
    'cache': {
        'meta_size': [],
        'meta_buffer': undefined
    },
    'image': {
        'resampling_method': undefined,
        'paletted': undefined
    }
};
var cacheModel = {
    'name': undefined,
    'sources': [],
    'grids': [],
    'format': undefined,
    'request_format': undefined
};
var gridModel = {
    'name': undefined,
    'srs': undefined,
    'bbox': [],
    'bbox_srs': undefined,
    'origin': undefined,
    'res': [],
    'scales': []
};
var sourceModel = {
    'name': undefined,
    'req': {
        'url': undefined,
        'layers': [],
        'transparent': undefined
    },
    'coverage': {
        'bbox': undefined,
        'srs': undefined
    },
    'supported_formats': [],
    'min_res_scale': undefined,
    'max_res_scale': undefined
};
var defaultsModel = {
    'dpi': undefined,
    'srs': []
};

var layerService = new MapproxyLayerService('layers', layerModel);
var globalsService = new MapproxyBaseService('globals', globalsModel);
var servicesService = new MapproxyBaseService('services');
var cacheService = new MapproxyBaseService('caches', cacheModel, [layerService]);
var gridService = new MapproxyBaseService('grids', gridModel, [cacheService]);
var sourceService = new MapproxyBaseService('sources', sourceModel, [cacheService, layerService]);
var wmsService = new WMSSourceService('wms_capabilities');
var defaultsService = new MapproxyBaseService('defaults', defaultsModel);

angular.module('mapproxy_gui.services', ['mapproxy_gui.resources']).

service('WMSSources', wmsService.return_func).
service('MapproxySources', sourceService.return_func).
service('MapproxyCaches', cacheService.return_func).
service('MapproxyGrids', gridService.return_func).
service('MapproxyLayers', layerService.return_func).
service('MapproxyGlobals', globalsService.return_func).
service('MapproxyServices', servicesService.return_func).
service('ProjectDefaults', defaultsService.return_func).

service('DataShareService', function($rootScope) {
    var _this = this;
    this._data = {};

    return {
        data: function(key, value) {
            if(angular.isDefined(value)) {
                _this._data[key] = value;
                $rootScope.$broadcast('dss.' + key);
            } else {
                if(angular.isDefined(_this._data[key])) {
                    return _this._data[key];
                } else {
                    return undefined;
                }
            }
        }
    }
});
<|endoftext|>


<commit_before>(function($) {
	$.fn.map_user_input = function(baseInput) {
		var $self = $(this);
		var onInput = function() {
			$self.val($(this).val().toLowerCase()
						.replace(/ä/g, 'ae')
						.replace(/ö/g, 'oe')
						.replace(/ü/g, 'ue')
						.replace(/ß/g, 'ss')
						.replace(/[^a-z0-9]/g, ''));
		};
		baseInput.on('input', onInput);
		$self.on('input', function() { baseInput.off('input', onInput); });
	};
})(jQuery);
<commit_msg>Revert wrong merge<commit_after>(function($) {
	$.fn.mapUserName = function(baseInput) {
		var $self = $(this);
		function onInput() {
			$self.val($(this).val().toLowerCase()
						.replace(/ä/g, 'ae')
						.replace(/ö/g, 'oe')
						.replace(/ü/g, 'ue')
						.replace(/ß/g, 'ss')
						.replace(/[^a-z0-9]/g, ''));
		};
		function offInput() {
			baseInput.off('input', onInput);
			$self.off('input', offInput);
		};
		baseInput = $(baseInput);
		baseInput.on('input', onInput);
		$self.on('input', offInput);
	};
})(jQuery);
<|endoftext|>


<commit_before>import Users from 'meteor/vulcan:users';
import { addCallback } from 'meteor/vulcan:core';
import { createNotification } from './notifications.js';

// note: leverage weak dependencies on packages
const Comments = Package['vulcan:comments'] ? Package['vulcan:comments'].default : null;
const Posts = Package['vulcan:posts'] ? Package['vulcan:posts'].default : null;

if (!!Posts) {
  /**
   * @summary Add notification callback when a post is approved
   */
  const PostsApprovedNotification = (post) => {
    const notificationData = {
      post: _.pick(post, '_id', 'userId', 'title', 'url')
    };

    createNotification(post.userId, 'postApproved', notificationData);
  }
  addCallback("posts.approve.async", PostsApprovedNotification);

  /**
   * @summary Add new post notification callback on post submit
   */
  const PostsNewNotifications = (post) => {

    let adminIds = _.pluck(Users.adminUsers({fields: {_id:1}}), '_id');
    let notifiedUserIds = _.pluck(Users.find({'notifications_posts': true}, {fields: {_id:1}}).fetch(), '_id');

    const notificationData = {
      post: _.pick(post, '_id', 'userId', 'title', 'url', 'slug')
    };

    // remove post author ID from arrays
    adminIds = _.without(adminIds, post.userId);
    notifiedUserIds = _.without(notifiedUserIds, post.userId);

    if (post.status === Posts.config.STATUS_PENDING && !!adminIds.length) {
      // if post is pending, only notify admins
      createNotification(adminIds, 'newPendingPost', notificationData);
    } else if (!!notifiedUserIds.length) {
      // if post is approved, notify everybody
      createNotification(notifiedUserIds, 'newPost', notificationData);
    }

  }
  addCallback("posts.new.async", PostsNewNotifications);
}

if (!!Comments) {
  // add new comment notification callback on comment submit
  const CommentsNewNotifications = (comment) => {

    // note: dummy content has disableNotifications set to true
    if(Meteor.isServer && !comment.disableNotifications) {

      const post = Posts.findOne(comment.postId);
      const postAuthor = Users.findOne(post.userId);
      const notificationData = {
        comment: _.pick(comment, '_id', 'userId', 'author', 'htmlBody', 'postId'),
        post: _.pick(post, '_id', 'userId', 'title', 'url')
      };

      let userIdsNotified = [];

      // 1. Notify author of post (if they have new comment notifications turned on)
      //    but do not notify author of post if they're the ones posting the comment
      if (Users.getSetting(postAuthor, "notifications_comments", true) && comment.userId !== postAuthor._id) {
        createNotification(post.userId, 'newComment', notificationData);
        userIdsNotified.push(post.userId);
      }

      // 2. Notify author of comment being replied to
      if (!!comment.parentCommentId) {

        const parentComment = Comments.findOne(comment.parentCommentId);

        // do not notify author of parent comment if they're also post author or comment author
        // (someone could be replying to their own comment)
        if (parentComment.userId !== post.userId && parentComment.userId !== comment.userId) {

          const parentCommentAuthor = Users.findOne(parentComment.userId);

          // do not notify parent comment author if they have reply notifications turned off
          if (Users.getSetting(parentCommentAuthor, "notifications_replies", true)) {

            // add parent comment to notification data
            notificationData.parentComment = _.pick(parentComment, '_id', 'userId', 'author', 'htmlBody');

            createNotification(parentComment.userId, 'newReply', notificationData);
            userIdsNotified.push(parentComment.userId);
          }
        }

      }

    }
  }

  addCallback("comments.new.async", CommentsNewNotifications);
}
<commit_msg>Workaround for Issue #1580<commit_after>import Users from 'meteor/vulcan:users';
import { addCallback } from 'meteor/vulcan:core';
import { createNotification } from './notifications.js';

// note: leverage weak dependencies on packages
const Comments = Package['vulcan:comments'] ? Package['vulcan:comments'].default : null;
const Posts = Package['vulcan:posts'] ? Package['vulcan:posts'].default : null;

if (!!Posts) {
  /**
   * @summary Add notification callback when a post is approved
   */
  const PostsApprovedNotification = (post) => {
    const notificationData = {
      post: _.pick(post, '_id', 'userId', 'title', 'url')
    };

    createNotification(post.userId, 'postApproved', notificationData);
  }
  addCallback("posts.approve.async", PostsApprovedNotification);

  /**
   * @summary Add new post notification callback on post submit
   */
  const PostsNewNotifications = (post) => {

    let adminIds = _.pluck(Users.adminUsers({fields: {_id:1}}), '_id');
    let notifiedUserIds = _.pluck(Users.find({'notifications_posts': true}, {fields: {_id:1}}).fetch(), '_id');

    const notificationData = {
      post: _.pick(post, '_id', 'userId', 'title', 'url', 'slug')
    };

    // remove post author ID from arrays
    adminIds = _.without(adminIds, post.userId);
    notifiedUserIds = _.without(notifiedUserIds, post.userId);

    if (post.status === Posts.config.STATUS_PENDING && !!adminIds.length) {
      // if post is pending, only notify admins
      createNotification(adminIds, 'newPendingPost', notificationData);
    } else if (!!notifiedUserIds.length) {
      // if post is approved, notify everybody
      createNotification(notifiedUserIds, 'newPost', notificationData);
    }

  }
  addCallback("posts.new.async", PostsNewNotifications);
}

if (!!Comments) {
  // add new comment notification callback on comment submit
  const CommentsNewNotifications = (comment) => {

    // note: dummy content has disableNotifications set to true
    if(Meteor.isServer && !comment.disableNotifications) {

      const post = Posts.findOne(comment.postId);
      const postAuthor = Users.findOne(post.userId);
      const notificationData = {
        comment: _.pick(comment, '_id', 'userId', 'author', 'htmlBody', 'postId'),
        post: _.pick(post, '_id', 'userId', 'title', 'url')
      };

      let userIdsNotified = [];

      // 1. Notify author of post (if they have new comment notifications turned on)
      //    but do not notify author of post if they're the ones posting the comment
      if (Users.getSetting(postAuthor, "notifications_comments", false) && comment.userId !== postAuthor._id) {
        createNotification(post.userId, 'newComment', notificationData);
        userIdsNotified.push(post.userId);
      }

      // 2. Notify author of comment being replied to
      if (!!comment.parentCommentId) {

        const parentComment = Comments.findOne(comment.parentCommentId);

        // do not notify author of parent comment if they're also post author or comment author
        // (someone could be replying to their own comment)
        if (parentComment.userId !== post.userId && parentComment.userId !== comment.userId) {

          const parentCommentAuthor = Users.findOne(parentComment.userId);

          // do not notify parent comment author if they have reply notifications turned off
          if (Users.getSetting(parentCommentAuthor, "notifications_replies", false)) {

            // add parent comment to notification data
            notificationData.parentComment = _.pick(parentComment, '_id', 'userId', 'author', 'htmlBody');

            createNotification(parentComment.userId, 'newReply', notificationData);
            userIdsNotified.push(parentComment.userId);
          }
        }

      }

    }
  }

  addCallback("comments.new.async", CommentsNewNotifications);
}
<|endoftext|>


<commit_before>/*
 * Laconica - a distributed open-source microblogging tool
 * Copyright (C) 2008, Controlez-Vous, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

$(document).ready(function(){
	// count character on keyup
	function counter(event){
		var maxLength = 140;
		var currentLength = $("#notice_data-text").val().length;
		var remaining = maxLength - currentLength;
		var counter = $("#notice_text-count");
		counter.text(remaining);

		if (remaining <= 0) {
			$("#form_notice").addClass("warning");
		} else {
			$("#form_notice").removeClass("warning");
		}
	}

	function submitonreturn(event) {
		if (event.keyCode == 13) {
			$("#form_notice").submit();
			event.preventDefault();
			event.stopPropagation();
			return false;
		}
		return true;
	}

	if ($("#notice_data-text").length) {
		$("#notice_data-text").bind("keyup", counter);
		$("#notice_data-text").bind("keydown", submitonreturn);

		// run once in case there's something in there
		counter();

		// set the focus
		$("#notice_data-text").focus();
	}

	// XXX: refactor this code

	var favoptions = { dataType: 'xml',
					   success: function(xml) { var new_form = document._importNode($('form', xml).get(0), true);
												var dis = new_form.id;
												var fav = dis.replace('disfavor', 'favor');
												$('form#'+fav).replaceWith(new_form);
												$('form#'+dis).ajaxForm(disoptions).each(addAjaxHidden);
											  }
					 };

	var disoptions = { dataType: 'xml',
					   success: function(xml) { var new_form = document._importNode($('form', xml).get(0), true);
												var fav = new_form.id;
												var dis = fav.replace('favor', 'disfavor');
												$('form#'+dis).replaceWith(new_form);
												$('form#'+fav).ajaxForm(favoptions).each(addAjaxHidden);
											  }
					 };

	var joinoptions = { dataType: 'xml',
					   success: function(xml) { var new_form = document._importNode($('form', xml).get(0), true);
												var leave = new_form.id;
												var join = leave.replace('leave', 'join');
												$('form#'+join).replaceWith(new_form);
												$('form#'+leave).ajaxForm(leaveoptions).each(addAjaxHidden);
											  }
					 };

	var leaveoptions = { dataType: 'xml',
					   success: function(xml) { var new_form = document._importNode($('form', xml).get(0), true);
												var join = new_form.id;
												var leave = join.replace('join', 'leave');
												$('form#'+leave).replaceWith(new_form);
												$('form#'+join).ajaxForm(joinoptions).each(addAjaxHidden);
											  }
					 };

	function addAjaxHidden() {
		var ajax = document.createElement('input');
		ajax.setAttribute('type', 'hidden');
		ajax.setAttribute('name', 'ajax');
		ajax.setAttribute('value', 1);
		this.appendChild(ajax);
	}

	$("form.form_favor").ajaxForm(favoptions);
	$("form.form_disfavor").ajaxForm(disoptions);
	$("form.form_group_join").ajaxForm(joinoptions);
	$("form.form_group_leave").ajaxForm(leaveoptions);
	$("form.form_favor").each(addAjaxHidden);
	$("form.form_disfavor").each(addAjaxHidden);
	$("form.form_group_join").each(addAjaxHidden);
	$("form.form_group_leave").each(addAjaxHidden);

	$("#form_user_nudge").ajaxForm ({ dataType: 'xml',
		beforeSubmit: function(xml) { $("#form_user_nudge input[type=submit]").attr("disabled", "disabled");
									  $("#form_user_nudge input[type=submit]").addClass("disabled");
									},
		success: function(xml) { $("#form_user_nudge").replaceWith(document._importNode($("#nudge_response", xml).get(0),true));
							     $("#form_user_nudge input[type=submit]").removeAttr("disabled");
							     $("#form_user_nudge input[type=submit]").removeClass("disabled");
							   }
	 });
	$("#form_user_nudge").each(addAjaxHidden);

	var Subscribe = { dataType: 'xml',
					  beforeSubmit: function(formData, jqForm, options) { $(".form_user_subscribe input[type=submit]").attr("disabled", "disabled");
																	      $(".form_user_subscribe input[type=submit]").addClass("disabled");
																	    },
					  success: function(xml) { var form_unsubscribe = document._importNode($('form', xml).get(0), true);
										  	   var form_unsubscribe_id = form_unsubscribe.id;
											   var form_subscribe_id = form_unsubscribe_id.replace('unsubscribe', 'subscribe');
											   $("form#"+form_subscribe_id).replaceWith(form_unsubscribe);
											   $("form#"+form_unsubscribe_id).ajaxForm(UnSubscribe).each(addAjaxHidden);
											   $("dd.subscribers").text(parseInt($("dd.subscribers").text())+1);
											   $(".form_user_subscribe input[type=submit]").removeAttr("disabled");
											   $(".form_user_subscribe input[type=submit]").removeClass("disabled");
										     }
					};

	var UnSubscribe = { dataType: 'xml',
						beforeSubmit: function(formData, jqForm, options) { $(".form_user_unsubscribe input[type=submit]").attr("disabled", "disabled");
																		    $(".form_user_unsubscribe input[type=submit]").addClass("disabled");
																		  },
					    success: function(xml) { var form_subscribe = document._importNode($('form', xml).get(0), true);
										  		 var form_subscribe_id = form_subscribe.id;
												 var form_unsubscribe_id = form_subscribe_id.replace('subscribe', 'unsubscribe');
												 $("form#"+form_unsubscribe_id).replaceWith(form_subscribe);
												 $("form#"+form_subscribe_id).ajaxForm(Subscribe).each(addAjaxHidden);
												 $("#profile_send_a_new_message").remove();
												 $("#profile_nudge").remove();
											     $("dd.subscribers").text(parseInt($("dd.subscribers").text())-1);
												 $(".form_user_unsubscribe input[type=submit]").removeAttr("disabled");
												 $(".form_user_unsubscribe input[type=submit]").removeClass("disabled");
											   }
					  };

	$(".form_user_subscribe").ajaxForm(Subscribe);
	$(".form_user_unsubscribe").ajaxForm(UnSubscribe);
	$(".form_user_subscribe").each(addAjaxHidden);
	$(".form_user_unsubscribe").each(addAjaxHidden);

	var PostNotice = { dataType: 'xml',
					   beforeSubmit: function(formData, jqForm, options) { if ($("#notice_data-text").get(0).value.length == 0) {
																				$("#form_notice").addClass("warning");
																				return false;
																		   }
																		   $("#notice_action-submit").attr("disabled", "disabled");
																		   $("#notice_action-submit").addClass("disabled");
																		   return true;
												 						 },
					   success: function(xml) {	if ($("#error", xml).length > 0 || $("#command_result", xml).length > 0) {
													var result = document._importNode($("p", xml).get(0), true);
													result = result.textContent || result.innerHTML;
													alert(result);
												}
												else {
													$("#notices_primary .notices").prepend(document._importNode($("li", xml).get(0), true));
													$("#notice_data-text").val("");
													counter();
													$("#notices_primary .notice:first").css({display:"none"});
													$("#notices_primary .notice:first").fadeIn(2500);
													NoticeHover();
													NoticeReply();
												}
												$("#notice_action-submit").removeAttr("disabled");
												$("#notice_action-submit").removeClass("disabled");
											 }
					   };
	$("#form_notice").ajaxForm(PostNotice);
	$("#form_notice").each(addAjaxHidden);

    NoticeHover();
    NoticeReply();
});

function NoticeHover() {
    $("#content .notice").hover(
        function () {
            $(this).addClass('hover');
        },
        function () {
            $(this).removeClass('hover');
        }
    );
}

function NoticeReply() {
    $('#content .notice').each(function() {
        var notice = $(this);
        $('.notice_reply', $(this)).click(function() {
            var nickname = ($('.author .nickname', notice).length > 0) ? $('.author .nickname', notice) : $('.author .nickname');
            NoticeReplySet(nickname.text(), $('.notice_id', notice).text());
            return false;
        });
    });
}

function NoticeReplySet(nick,id) {
	rgx_username = /^[0-9a-zA-Z\-_.]*$/;
	if (nick.match(rgx_username)) {
		replyto = "@" + nick + " ";
		if ($("#notice_data-text").length) {
			$("#notice_data-text").val(replyto);
			$("#form_notice input#notice_in-reply-to").val(id);
			$("#notice_data-text").focus();
			return false;
		}
	}
	return true;
}
<commit_msg>Uses regular HTTP GET to new notice replyto page instead of JS when notice_data-text is available.<commit_after>/*
 * Laconica - a distributed open-source microblogging tool
 * Copyright (C) 2008, Controlez-Vous, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

$(document).ready(function(){
	// count character on keyup
	function counter(event){
		var maxLength = 140;
		var currentLength = $("#notice_data-text").val().length;
		var remaining = maxLength - currentLength;
		var counter = $("#notice_text-count");
		counter.text(remaining);

		if (remaining <= 0) {
			$("#form_notice").addClass("warning");
		} else {
			$("#form_notice").removeClass("warning");
		}
	}

	function submitonreturn(event) {
		if (event.keyCode == 13) {
			$("#form_notice").submit();
			event.preventDefault();
			event.stopPropagation();
			return false;
		}
		return true;
	}

	if ($("#notice_data-text").length) {
		$("#notice_data-text").bind("keyup", counter);
		$("#notice_data-text").bind("keydown", submitonreturn);

		// run once in case there's something in there
		counter();

		// set the focus
		$("#notice_data-text").focus();
	}

	// XXX: refactor this code

	var favoptions = { dataType: 'xml',
					   success: function(xml) { var new_form = document._importNode($('form', xml).get(0), true);
												var dis = new_form.id;
												var fav = dis.replace('disfavor', 'favor');
												$('form#'+fav).replaceWith(new_form);
												$('form#'+dis).ajaxForm(disoptions).each(addAjaxHidden);
											  }
					 };

	var disoptions = { dataType: 'xml',
					   success: function(xml) { var new_form = document._importNode($('form', xml).get(0), true);
												var fav = new_form.id;
												var dis = fav.replace('favor', 'disfavor');
												$('form#'+dis).replaceWith(new_form);
												$('form#'+fav).ajaxForm(favoptions).each(addAjaxHidden);
											  }
					 };

	var joinoptions = { dataType: 'xml',
					   success: function(xml) { var new_form = document._importNode($('form', xml).get(0), true);
												var leave = new_form.id;
												var join = leave.replace('leave', 'join');
												$('form#'+join).replaceWith(new_form);
												$('form#'+leave).ajaxForm(leaveoptions).each(addAjaxHidden);
											  }
					 };

	var leaveoptions = { dataType: 'xml',
					   success: function(xml) { var new_form = document._importNode($('form', xml).get(0), true);
												var join = new_form.id;
												var leave = join.replace('join', 'leave');
												$('form#'+leave).replaceWith(new_form);
												$('form#'+join).ajaxForm(joinoptions).each(addAjaxHidden);
											  }
					 };

	function addAjaxHidden() {
		var ajax = document.createElement('input');
		ajax.setAttribute('type', 'hidden');
		ajax.setAttribute('name', 'ajax');
		ajax.setAttribute('value', 1);
		this.appendChild(ajax);
	}

	$("form.form_favor").ajaxForm(favoptions);
	$("form.form_disfavor").ajaxForm(disoptions);
	$("form.form_group_join").ajaxForm(joinoptions);
	$("form.form_group_leave").ajaxForm(leaveoptions);
	$("form.form_favor").each(addAjaxHidden);
	$("form.form_disfavor").each(addAjaxHidden);
	$("form.form_group_join").each(addAjaxHidden);
	$("form.form_group_leave").each(addAjaxHidden);

	$("#form_user_nudge").ajaxForm ({ dataType: 'xml',
		beforeSubmit: function(xml) { $("#form_user_nudge input[type=submit]").attr("disabled", "disabled");
									  $("#form_user_nudge input[type=submit]").addClass("disabled");
									},
		success: function(xml) { $("#form_user_nudge").replaceWith(document._importNode($("#nudge_response", xml).get(0),true));
							     $("#form_user_nudge input[type=submit]").removeAttr("disabled");
							     $("#form_user_nudge input[type=submit]").removeClass("disabled");
							   }
	 });
	$("#form_user_nudge").each(addAjaxHidden);

	var Subscribe = { dataType: 'xml',
					  beforeSubmit: function(formData, jqForm, options) { $(".form_user_subscribe input[type=submit]").attr("disabled", "disabled");
																	      $(".form_user_subscribe input[type=submit]").addClass("disabled");
																	    },
					  success: function(xml) { var form_unsubscribe = document._importNode($('form', xml).get(0), true);
										  	   var form_unsubscribe_id = form_unsubscribe.id;
											   var form_subscribe_id = form_unsubscribe_id.replace('unsubscribe', 'subscribe');
											   $("form#"+form_subscribe_id).replaceWith(form_unsubscribe);
											   $("form#"+form_unsubscribe_id).ajaxForm(UnSubscribe).each(addAjaxHidden);
											   $("dd.subscribers").text(parseInt($("dd.subscribers").text())+1);
											   $(".form_user_subscribe input[type=submit]").removeAttr("disabled");
											   $(".form_user_subscribe input[type=submit]").removeClass("disabled");
										     }
					};

	var UnSubscribe = { dataType: 'xml',
						beforeSubmit: function(formData, jqForm, options) { $(".form_user_unsubscribe input[type=submit]").attr("disabled", "disabled");
																		    $(".form_user_unsubscribe input[type=submit]").addClass("disabled");
																		  },
					    success: function(xml) { var form_subscribe = document._importNode($('form', xml).get(0), true);
										  		 var form_subscribe_id = form_subscribe.id;
												 var form_unsubscribe_id = form_subscribe_id.replace('subscribe', 'unsubscribe');
												 $("form#"+form_unsubscribe_id).replaceWith(form_subscribe);
												 $("form#"+form_subscribe_id).ajaxForm(Subscribe).each(addAjaxHidden);
												 $("#profile_send_a_new_message").remove();
												 $("#profile_nudge").remove();
											     $("dd.subscribers").text(parseInt($("dd.subscribers").text())-1);
												 $(".form_user_unsubscribe input[type=submit]").removeAttr("disabled");
												 $(".form_user_unsubscribe input[type=submit]").removeClass("disabled");
											   }
					  };

	$(".form_user_subscribe").ajaxForm(Subscribe);
	$(".form_user_unsubscribe").ajaxForm(UnSubscribe);
	$(".form_user_subscribe").each(addAjaxHidden);
	$(".form_user_unsubscribe").each(addAjaxHidden);

	var PostNotice = { dataType: 'xml',
					   beforeSubmit: function(formData, jqForm, options) { if ($("#notice_data-text").get(0).value.length == 0) {
																				$("#form_notice").addClass("warning");
																				return false;
																		   }
																		   $("#notice_action-submit").attr("disabled", "disabled");
																		   $("#notice_action-submit").addClass("disabled");
																		   return true;
												 						 },
					   success: function(xml) {	if ($("#error", xml).length > 0 || $("#command_result", xml).length > 0) {
													var result = document._importNode($("p", xml).get(0), true);
													result = result.textContent || result.innerHTML;
													alert(result);
												}
												else {
													$("#notices_primary .notices").prepend(document._importNode($("li", xml).get(0), true));
													$("#notice_data-text").val("");
													counter();
													$("#notices_primary .notice:first").css({display:"none"});
													$("#notices_primary .notice:first").fadeIn(2500);
													NoticeHover();
													NoticeReply();
												}
												$("#notice_action-submit").removeAttr("disabled");
												$("#notice_action-submit").removeClass("disabled");
											 }
					   };
	$("#form_notice").ajaxForm(PostNotice);
	$("#form_notice").each(addAjaxHidden);

    NoticeHover();
    NoticeReply();
});

function NoticeHover() {
    $("#content .notice").hover(
        function () {
            $(this).addClass('hover');
        },
        function () {
            $(this).removeClass('hover');
        }
    );
}

function NoticeReply() {
    if ($('#notice_data-text').length > 0) {
        $('#content .notice').each(function() {
            var notice = $(this);
            $('.notice_reply', $(this)).click(function() {
                var nickname = ($('.author .nickname', notice).length > 0) ? $('.author .nickname', notice) : $('.author .nickname');
                NoticeReplySet(nickname.text(), $('.notice_id', notice).text());
                return false;
            });
        });
    }
}

function NoticeReplySet(nick,id) {
	rgx_username = /^[0-9a-zA-Z\-_.]*$/;
	if (nick.match(rgx_username)) {
		replyto = "@" + nick + " ";
		if ($("#notice_data-text").length) {
			$("#notice_data-text").val(replyto);
			$("#form_notice input#notice_in-reply-to").val(id);
			$("#notice_data-text").focus();
			return false;
		}
	}
	return true;
}
<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const rollup = require('rollup');
const uglify = require('rollup-plugin-uglify');
const resolve = require('rollup-plugin-node-resolve');
const commonjs = require('rollup-plugin-commonjs');
const del = require('del');
const pkg = require('./package.json');

let resolvePlugin = resolve({
    // use "module" field for ES6 module if possible
    module: true, // Default: true

    // use "jsnext:main" if possible – see
    // https://github.com/rollup/rollup/wiki/jsnext:main
    jsnext: true, // Default: false

    // use "main" field or index.js, even if it's not an ES6 module (needs to be
    // converted from CommonJS to ES6 – see
    // https://github.com/rollup/rollup-plugin-commonjs
    main: true, // Default: true

    // some package.json files have a `browser` field which specifies alternative
    // files to load for people bundling for the browser. If that's you, use this
    // option, otherwise pkg.browser will be ignored
    browser: true, // Default: false

    // not all files you want to resolve are .js files
    extensions: [
        '.js', '.json'
    ], // Default: ['.js']

    // whether to prefer built-in modules (e.g. `fs`, `path`) or local ones with the
    // same names
    preferBuiltins: false, // Default: true

    // Lock the module search in this path (like a chroot). Module defined outside
    // this path will be mark has external
    jail: '/', // Default: '/'

    // If true, inspect resolved files to check that they are ES2015 modules
    modulesOnly: false, // Default: false
});

const bundles = [
    {
        format: 'es',
        ext: '.mjs',
        plugins: []
    }, {
        format: 'cjs',
        ext: '.browser.js',
        plugins: []
    }, {
        format: 'umd',
        ext: '.js',
        plugins: [],
        moduleName: 'ratings'
    }, {
        format: 'umd',
        ext: '.min.js',
        plugins: [uglify()],
        moduleName: 'ratings',
        minify: true
    }
];

let promise = Promise.resolve();

promise = promise.then(() => del(['dist/*']));

for (const config of bundles) {
    promise = promise.then(() => rollup.rollup({
        entry: 'src/main.js',
        plugins: [resolvePlugin, commonjs()].concat(config.plugins)
    }).then(bundle => bundle.write({
        dest: `dist/${config.moduleName || 'ratings'}${config.ext}`,
        format: config.format,
        sourceMap: !config.minify,
        moduleName: config.moduleName
    })));
}

promise = promise.then(() => {
  delete pkg.devDependencies;
  delete pkg.scripts;
  delete pkg.eslintConfig;
  fs.writeFileSync('dist/package.json', JSON.stringify(pkg, null, '  '), 'utf-8');
  fs.writeFileSync('dist/LICENSE.md', fs.readFileSync('LICENSE.md', 'utf-8'), 'utf-8');
});

promise.catch(err => console.error(err.stack)); // eslint-disable-line no-console<commit_msg>Cleaned up build script<commit_after>'use strict';

const fs = require('fs');
const rollup = require('rollup');
const uglify = require('rollup-plugin-uglify');
const resolve = require('rollup-plugin-node-resolve');
const commonjs = require('rollup-plugin-commonjs');
const del = require('del');
const pkg = require('./package.json');

let resolvePlugin = resolve({
    // use "jsnext:main" if possible – see
    // https://github.com/rollup/rollup/wiki/jsnext:main
    jsnext: true, // Default: false

    // some package.json files have a `browser` field which specifies alternative
    // files to load for people bundling for the browser. If that's you, use this
    // option, otherwise pkg.browser will be ignored
    browser: true, // Default: false

    // not all files you want to resolve are .js files
    extensions: [
        '.js', '.json'
    ], // Default: ['.js']

    // whether to prefer built-in modules (e.g. `fs`, `path`) or local ones with the
    // same names
    preferBuiltins: false, // Default: true
});

const bundles = [
    {
        format: 'es',
        ext: '.mjs',
        plugins: []
    }, {
        format: 'cjs',
        ext: '.browser.js',
        plugins: []
    }, {
        format: 'umd',
        ext: '.js',
        plugins: [],
        moduleName: 'ratings'
    }, {
        format: 'umd',
        ext: '.min.js',
        plugins: [uglify()],
        moduleName: 'ratings',
        minify: true
    }
];

let promise = Promise.resolve();

promise = promise.then(() => del(['dist/*']));

for (const config of bundles) {
    promise = promise.then(() => rollup.rollup({
        entry: 'src/main.js',
        plugins: [resolvePlugin, commonjs()].concat(config.plugins)
    }).then(bundle => bundle.write({
        dest: `dist/${config.moduleName || 'ratings'}${config.ext}`,
        format: config.format,
        sourceMap: !config.minify,
        moduleName: config.moduleName
    })));
}

promise = promise.then(() => {
    delete pkg.devDependencies;
    delete pkg.scripts;
    delete pkg.eslintConfig;

    fs.writeFileSync('dist/package.json', JSON.stringify(pkg, null, '  '), 'utf-8');
    fs.writeFileSync('dist/LICENSE.md', fs.readFileSync('LICENSE.md', 'utf-8'), 'utf-8');
});

promise.catch(err => console.error(err.stack)); // eslint-disable-line no-console<|endoftext|>


<commit_before>(function(app) {
  'use strict';
  var util = {};

  util.inherits = function(ctor, superCtor) {
    ctor.super_ = superCtor;
    ctor.prototype = Object.create(superCtor.prototype, {
      constructor: {
        value: ctor,
        enumerable: false,
        writable: true,
        configurable: true
      }
    });
    return ctor;
  };

  util.invoke = function(array, methodName) {
    var args = Array.prototype.slice.call(arguments, 2);
    return array.map(function(value) {
      return value[methodName].apply(value, args);
    });
  };

  util.sortBy = function(array, key) {
    return array.concat().sort(function(a, b) {
      return a[key] - b[key];
    });
  };

  util.camelCase = function(s) {
    return s.replace(/-(.)/g, function(_, g) {
      return g.toUpperCase();
    });
  };

  util.startOfDay = function() {
    var now = new Date();
    return new Date(now.getFullYear(), now.getMonth(), now.getDate());
  };

  util.addDays = function(date, n) {
    return new Date(date.getTime() + n * 86400000);
  };

  util.diffDays = function(date0, date1) {
    return (date0.getTime() - date1.getTime()) / 86400000;
  };

  util.supportsTouch = function() {
    return 'createTouch' in document;
  };

  util.rootElement = function() {
    return document.documentElement;
  };

  util.windowWidth = function() {
    return window.innerWidth;
  };

  util.windowHeight = function() {
    return window.innerHeight;
  };

  util.openWindow = function(url) {
    window.open(url, '_blank');
  };

  util.addResizeEvent = function(listener) {
    window.addEventListener('resize', listener);
  };

  util.el = function(selector) {
    return document.querySelector(selector);
  };

  util.closest = function(el, selector) {
    var indexOf = Array.prototype.indexOf;
    while (el) {
      var parentNode = el.parentNode;
      if (!parentNode)
        return null;
      if (indexOf.call(parentNode.querySelectorAll(selector), el) !== -1)
        return el;
      el = parentNode;
    }
  };

  util.translateX = function(el, x) {
    var value = 'translateX(' + x + 'px)';
    el.style.transform =  value;
    el.style.webkitTransform = value;
    el.style.MozTransform = value;
    el.style.msTransform = value;
    el.style.OTransform = value;
  };

  util.getJSON = function(url) {
    return jQuery.getJSON(url);
  };

  util.sortable = function(el, option) {
    return jQuery(el).sortable(option);
  };

  util.storageKey = function(key) {
    return 'org.ionstage.timeline.' + key;
  };

  util.loadData = function(key, defaultValue) {
    var value = localStorage.getItem(util.storageKey(key));
    if (value === null && typeof defaultValue !== 'undefined')
      return defaultValue;
    return JSON.parse(value);
  };

  util.saveData = function(key, data) {
    localStorage.setItem(util.storageKey(key), JSON.stringify(data));
  };

  if (typeof module !== 'undefined' && module.exports)
    module.exports = util;
  else
    app.util = util;
})(this.app || (this.app = {}));<commit_msg>Make storage-key function private<commit_after>(function(app) {
  'use strict';
  var util = {};

  util.inherits = function(ctor, superCtor) {
    ctor.super_ = superCtor;
    ctor.prototype = Object.create(superCtor.prototype, {
      constructor: {
        value: ctor,
        enumerable: false,
        writable: true,
        configurable: true
      }
    });
    return ctor;
  };

  util.invoke = function(array, methodName) {
    var args = Array.prototype.slice.call(arguments, 2);
    return array.map(function(value) {
      return value[methodName].apply(value, args);
    });
  };

  util.sortBy = function(array, key) {
    return array.concat().sort(function(a, b) {
      return a[key] - b[key];
    });
  };

  util.camelCase = function(s) {
    return s.replace(/-(.)/g, function(_, g) {
      return g.toUpperCase();
    });
  };

  util.startOfDay = function() {
    var now = new Date();
    return new Date(now.getFullYear(), now.getMonth(), now.getDate());
  };

  util.addDays = function(date, n) {
    return new Date(date.getTime() + n * 86400000);
  };

  util.diffDays = function(date0, date1) {
    return (date0.getTime() - date1.getTime()) / 86400000;
  };

  util.supportsTouch = function() {
    return 'createTouch' in document;
  };

  util.rootElement = function() {
    return document.documentElement;
  };

  util.windowWidth = function() {
    return window.innerWidth;
  };

  util.windowHeight = function() {
    return window.innerHeight;
  };

  util.openWindow = function(url) {
    window.open(url, '_blank');
  };

  util.addResizeEvent = function(listener) {
    window.addEventListener('resize', listener);
  };

  util.el = function(selector) {
    return document.querySelector(selector);
  };

  util.closest = function(el, selector) {
    var indexOf = Array.prototype.indexOf;
    while (el) {
      var parentNode = el.parentNode;
      if (!parentNode)
        return null;
      if (indexOf.call(parentNode.querySelectorAll(selector), el) !== -1)
        return el;
      el = parentNode;
    }
  };

  util.translateX = function(el, x) {
    var value = 'translateX(' + x + 'px)';
    el.style.transform =  value;
    el.style.webkitTransform = value;
    el.style.MozTransform = value;
    el.style.msTransform = value;
    el.style.OTransform = value;
  };

  util.getJSON = function(url) {
    return jQuery.getJSON(url);
  };

  util.sortable = function(el, option) {
    return jQuery(el).sortable(option);
  };

  util.loadData = function(key, defaultValue) {
    var value = localStorage.getItem(storageKey(key));
    if (value === null && typeof defaultValue !== 'undefined')
      return defaultValue;
    return JSON.parse(value);
  };

  util.saveData = function(key, data) {
    localStorage.setItem(storageKey(key), JSON.stringify(data));
  };

  var storageKey = function(key) {
    return 'org.ionstage.timeline.' + key;
  };

  if (typeof module !== 'undefined' && module.exports)
    module.exports = util;
  else
    app.util = util;
})(this.app || (this.app = {}));<|endoftext|>


<commit_before>/**
 * This function contains the code necessary for subclassing and should be called
 * immediately following the creation of a class constructor for a class that wants
 * to be a subclass of another and inherit its properties and methods
 *
 * e.g.
 * ANewSubClass = function() {}
 * ANewSubClass.inheritsFrom(ExistingClass)
 *
 * @param the superclass this class wants to inherit from
 * @return the subclass
 */
Function.prototype.inheritsFrom = function( parentClassOrObject ){
	if ( parentClassOrObject.constructor == Function )
	{
		//Normal Inheritance
		this.prototype = new parentClassOrObject;
		this.prototype.constructor = this;
		this.prototype.parent = parentClassOrObject.prototype;
	}
	else
	{
		//Pure Virtual Inheritance
		this.prototype = parentClassOrObject;
		this.prototype.constructor = this;
		this.prototype.parent = parentClassOrObject;
	}
	return this;
}

<commit_msg>Added reference link for code snippet of inheritsFrom method.<commit_after>/**
 * This function contains the code necessary for subclassing and should be called
 * immediately following the creation of a class constructor for a class that wants
 * to be a subclass of another and inherit its properties and methods
 *
 * Reference: This code snippet was taken from http://phrogz.net/js/classes/OOPinJS2.html
 *
 * e.g.
 * ANewSubClass = function() {}
 * ANewSubClass.inheritsFrom(ExistingClass)
 *
 * @param the superclass this class wants to inherit from
 * @return the subclass
 */
Function.prototype.inheritsFrom = function( parentClassOrObject ){
	if ( parentClassOrObject.constructor == Function )
	{
		//Normal Inheritance
		this.prototype = new parentClassOrObject;
		this.prototype.constructor = this;
		this.prototype.parent = parentClassOrObject.prototype;
	}
	else
	{
		//Pure Virtual Inheritance
		this.prototype = parentClassOrObject;
		this.prototype.constructor = this;
		this.prototype.parent = parentClassOrObject;
	}
	return this;
}

<|endoftext|>