<commit_before>window.iD = function () {
    window.locale.en = iD.data.en;
    window.locale.current('en');

    var context = {},
        storage;

    // https://github.com/openstreetmap/iD/issues/772
    // http://mathiasbynens.be/notes/localstorage-pattern#comment-9
    try { storage = localStorage; } catch (e) {}  // eslint-disable-line no-empty
    storage = storage || (function() {
        var s = {};
        return {
            getItem: function(k) { return s[k]; },
            setItem: function(k, v) { s[k] = v; },
            removeItem: function(k) { delete s[k]; }
        };
    })();

    context.storage = function(k, v) {
        try {
            if (arguments.length === 1) return storage.getItem(k);
            else if (v === null) storage.removeItem(k);
            else storage.setItem(k, v);
        } catch(e) {
            // localstorage quota exceeded
            /* eslint-disable no-console */
            if (typeof console !== 'undefined') console.error('localStorage quota exceeded');
            /* eslint-enable no-console */
        }
    };

    /* Accessor for setting minimum zoom for editing features. */

    var minEditableZoom = 16;
    context.minEditableZoom = function(_) {
        if (!arguments.length) return minEditableZoom;
        minEditableZoom = _;
        connection.tileZoom(_);
        return context;
    };

    var history = iD.History(context),
        dispatch = d3.dispatch('enter', 'exit'),
        mode,
        container,
        ui = iD.ui(context),
        connection = iD.Connection(),
        locale = iD.detect().locale,
        localePath;

    if (locale && iD.data.locales.indexOf(locale) === -1) {
        locale = locale.split('-')[0];
    }

    context.preauth = function(options) {
        connection.switch(options);
        return context;
    };

    context.locale = function(loc, path) {
        locale = loc;
        localePath = path;

        // Also set iD.detect().locale (unless we detected 'en-us' and openstreetmap wants 'en')..
        if (!(loc.toLowerCase() === 'en' && iD.detect().locale.toLowerCase() === 'en-us')) {
            iD.detect().locale = loc;
        }

        return context;
    };

    context.loadLocale = function(cb) {
        if (locale && locale !== 'en' && iD.data.locales.indexOf(locale) !== -1) {
            localePath = localePath || context.assetPath() + 'locales/' + locale + '.json';
            d3.json(localePath, function(err, result) {
                window.locale[locale] = result;
                window.locale.current(locale);
                cb();
            });
        } else {
            cb();
        }
    };

    /* Straight accessors. Avoid using these if you can. */
    context.ui = function() { return ui; };
    context.connection = function() { return connection; };
    context.history = function() { return history; };

    /* Connection */
    function entitiesLoaded(err, result) {
        if (!err) history.merge(result.data, result.extent);
    }

    context.loadTiles = function(projection, dimensions, callback) {
        function done(err, result) {
            entitiesLoaded(err, result);
            if (callback) callback(err, result);
        }
        connection.loadTiles(projection, dimensions, done);
    };

    context.loadEntity = function(id, callback) {
        function done(err, result) {
            entitiesLoaded(err, result);
            if (callback) callback(err, result);
        }
        connection.loadEntity(id, done);
    };

    context.zoomToEntity = function(id, zoomTo) {
        if (zoomTo !== false) {
            this.loadEntity(id, function(err, result) {
                if (err) return;
                var entity = _.find(result.data, function(e) { return e.id === id; });
                if (entity) { map.zoomTo(entity); }
            });
        }

        map.on('drawn.zoomToEntity', function() {
            if (!context.hasEntity(id)) return;
            map.on('drawn.zoomToEntity', null);
            context.on('enter.zoomToEntity', null);
            context.enter(iD.modes.Select(context, [id]));
        });

        context.on('enter.zoomToEntity', function() {
            if (mode.id !== 'browse') {
                map.on('drawn.zoomToEntity', null);
                context.on('enter.zoomToEntity', null);
            }
        });
    };

    /* History */
    context.graph = history.graph;
    context.changes = history.changes;
    context.intersects = history.intersects;

    var inIntro = false;

    context.inIntro = function(_) {
        if (!arguments.length) return inIntro;
        inIntro = _;
        return context;
    };

    context.save = function() {
        if (inIntro || (mode && mode.id === 'save')) return;
        history.save();
        if (history.hasChanges()) return t('save.unsaved_changes');
    };

    context.flush = function() {
        connection.flush();
        features.reset();
        history.reset();
        return context;
    };

    // Debounce save, since it's a synchronous localStorage write,
    // and history changes can happen frequently (e.g. when dragging).
    var debouncedSave = _.debounce(context.save, 350);
    function withDebouncedSave(fn) {
        return function() {
            var result = fn.apply(history, arguments);
            debouncedSave();
            return result;
        };
    }

    context.perform = withDebouncedSave(history.perform);
    context.replace = withDebouncedSave(history.replace);
    context.pop = withDebouncedSave(history.pop);
    context.overwrite = withDebouncedSave(history.overwrite);
    context.undo = withDebouncedSave(history.undo);
    context.redo = withDebouncedSave(history.redo);

    /* Graph */
    context.hasEntity = function(id) {
        return history.graph().hasEntity(id);
    };

    context.entity = function(id) {
        return history.graph().entity(id);
    };

    context.childNodes = function(way) {
        return history.graph().childNodes(way);
    };

    context.geometry = function(id) {
        return context.entity(id).geometry(history.graph());
    };

    /* Modes */
    context.enter = function(newMode) {
        if (mode) {
            mode.exit();
            dispatch.exit(mode);
        }

        mode = newMode;
        mode.enter();
        dispatch.enter(mode);
    };

    context.mode = function() {
        return mode;
    };

    context.selectedIDs = function() {
        if (mode && mode.selectedIDs) {
            return mode.selectedIDs();
        } else {
            return [];
        }
    };

    /* Behaviors */
    context.install = function(behavior) {
        context.surface().call(behavior);
    };

    context.uninstall = function(behavior) {
        context.surface().call(behavior.off);
    };

    /* Copy/Paste */
    var copyIDs = [], copyGraph;
    context.copyGraph = function() { return copyGraph; };
    context.copyIDs = function(_) {
        if (!arguments.length) return copyIDs;
        copyIDs = _;
        copyGraph = history.graph();
        return context;
    };

    /* Projection */
    context.projection = iD.geo.RawMercator();

    /* Background */
    var background = iD.Background(context);
    context.background = function() { return background; };

    /* Features */
    var features = iD.Features(context);
    context.features = function() { return features; };
    context.hasHiddenConnections = function(id) {
        var graph = history.graph(),
            entity = graph.entity(id);
        return features.hasHiddenConnections(entity, graph);
    };

    /* Map */
    var map = iD.Map(context);
    context.map = function() { return map; };
    context.layers = function() { return map.layers; };
    context.surface = function() { return map.surface; };
    context.editable = function() { return map.editable(); };
    context.mouse = map.mouse;
    context.extent = map.extent;
    context.pan = map.pan;
    context.zoomIn = map.zoomIn;
    context.zoomOut = map.zoomOut;
    context.zoomInFurther = map.zoomInFurther;
    context.zoomOutFurther = map.zoomOutFurther;

    context.surfaceRect = function() {
        // Work around a bug in Firefox.
        //   http://stackoverflow.com/questions/18153989/
        //   https://bugzilla.mozilla.org/show_bug.cgi?id=530985
        return context.surface().node().parentNode.getBoundingClientRect();
    };

    /* Presets */
    var presets = iD.presets();

    context.presets = function(_) {
        if (!arguments.length) return presets;
        presets.load(_);
        iD.areaKeys = presets.areaKeys();
        return context;
    };

    context.imagery = function(_) {
        background.load(_);
        return context;
    };

    context.container = function(_) {
        if (!arguments.length) return container;
        container = _;
        container.classed('id-container', true);
        return context;
    };

    /* Taginfo */
    var taginfo;
    context.taginfo = function(_) {
        if (!arguments.length) return taginfo;
        taginfo = _;
        return context;
    };

    var embed = false;
    context.embed = function(_) {
        if (!arguments.length) return embed;
        embed = _;
        return context;
    };

    var assetPath = '';
    context.assetPath = function(_) {
        if (!arguments.length) return assetPath;
        assetPath = _;
        return context;
    };

    var assetMap = {};
    context.assetMap = function(_) {
        if (!arguments.length) return assetMap;
        assetMap = _;
        return context;
    };

    context.imagePath = function(_) {
        var asset = 'img/' + _;
        return assetMap[asset] || assetPath + asset;
    };

    return d3.rebind(context, dispatch, 'on');
};

iD.version = '1.8.0';

(function() {
    var detected = {};

    var ua = navigator.userAgent,
        m = null;

    m = ua.match(/Trident\/.*rv:([0-9]{1,}[\.0-9]{0,})/i);   // IE11+
    if (m !== null) {
        detected.browser = 'msie';
        detected.version = m[1];
    }
    if (!detected.browser) {
        m = ua.match(/(opr)\/?\s*(\.?\d+(\.\d+)*)/i);   // Opera 15+
        if (m !== null) {
            detected.browser = 'Opera';
            detected.version = m[2];
        }
    }
    if (!detected.browser) {
        m = ua.match(/(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\.\d+)*)/i);
        if (m !== null) {
            detected.browser = m[1];
            detected.version = m[2];
            m = ua.match(/version\/([\.\d]+)/i);
            if (m !== null) detected.version = m[1];
        }
    }
    if (!detected.browser) {
        detected.browser = navigator.appName;
        detected.version = navigator.appVersion;
    }

    // keep major.minor version only..
    detected.version = detected.version.split(/\W/).slice(0,2).join('.');

    if (detected.browser.toLowerCase() === 'msie') {
        detected.ie = true;
        detected.browser = 'Internet Explorer';
        detected.support = parseFloat(detected.version) > 9;
    } else {
        detected.ie = false
        detected.support = true;
    }

    // Added due to incomplete svg style support. See #715
    detected.opera = (detected.browser.toLowerCase() === 'opera' && parseFloat(detected.version) < 15 );

    detected.locale = (navigator.languages && navigator.languages.length)
        ? navigator.languages[0] : (navigator.language || navigator.userLanguage || 'en-US');

    detected.filedrop = (window.FileReader && 'ondrop' in window);

    function nav(x) {
        return navigator.userAgent.indexOf(x) !== -1;
    }

    if (nav('Win')) {
        detected.os = 'win';
        detected.platform = 'Windows';
    }
    else if (nav('Mac')) {
        detected.os = 'mac';
        detected.platform = 'Macintosh';
    }
    else if (nav('X11') || nav('Linux')) {
        detected.os = 'linux';
        detected.platform = 'Linux';
    }
    else {
        detected.os = 'win';
        detected.platform = 'Unknown';
    }

    iD.detect = function() { return detected; };
})();
<commit_msg>Detect Edge useragent<commit_after>window.iD = function () {
    window.locale.en = iD.data.en;
    window.locale.current('en');

    var context = {},
        storage;

    // https://github.com/openstreetmap/iD/issues/772
    // http://mathiasbynens.be/notes/localstorage-pattern#comment-9
    try { storage = localStorage; } catch (e) {}  // eslint-disable-line no-empty
    storage = storage || (function() {
        var s = {};
        return {
            getItem: function(k) { return s[k]; },
            setItem: function(k, v) { s[k] = v; },
            removeItem: function(k) { delete s[k]; }
        };
    })();

    context.storage = function(k, v) {
        try {
            if (arguments.length === 1) return storage.getItem(k);
            else if (v === null) storage.removeItem(k);
            else storage.setItem(k, v);
        } catch(e) {
            // localstorage quota exceeded
            /* eslint-disable no-console */
            if (typeof console !== 'undefined') console.error('localStorage quota exceeded');
            /* eslint-enable no-console */
        }
    };

    /* Accessor for setting minimum zoom for editing features. */

    var minEditableZoom = 16;
    context.minEditableZoom = function(_) {
        if (!arguments.length) return minEditableZoom;
        minEditableZoom = _;
        connection.tileZoom(_);
        return context;
    };

    var history = iD.History(context),
        dispatch = d3.dispatch('enter', 'exit'),
        mode,
        container,
        ui = iD.ui(context),
        connection = iD.Connection(),
        locale = iD.detect().locale,
        localePath;

    if (locale && iD.data.locales.indexOf(locale) === -1) {
        locale = locale.split('-')[0];
    }

    context.preauth = function(options) {
        connection.switch(options);
        return context;
    };

    context.locale = function(loc, path) {
        locale = loc;
        localePath = path;

        // Also set iD.detect().locale (unless we detected 'en-us' and openstreetmap wants 'en')..
        if (!(loc.toLowerCase() === 'en' && iD.detect().locale.toLowerCase() === 'en-us')) {
            iD.detect().locale = loc;
        }

        return context;
    };

    context.loadLocale = function(cb) {
        if (locale && locale !== 'en' && iD.data.locales.indexOf(locale) !== -1) {
            localePath = localePath || context.assetPath() + 'locales/' + locale + '.json';
            d3.json(localePath, function(err, result) {
                window.locale[locale] = result;
                window.locale.current(locale);
                cb();
            });
        } else {
            cb();
        }
    };

    /* Straight accessors. Avoid using these if you can. */
    context.ui = function() { return ui; };
    context.connection = function() { return connection; };
    context.history = function() { return history; };

    /* Connection */
    function entitiesLoaded(err, result) {
        if (!err) history.merge(result.data, result.extent);
    }

    context.loadTiles = function(projection, dimensions, callback) {
        function done(err, result) {
            entitiesLoaded(err, result);
            if (callback) callback(err, result);
        }
        connection.loadTiles(projection, dimensions, done);
    };

    context.loadEntity = function(id, callback) {
        function done(err, result) {
            entitiesLoaded(err, result);
            if (callback) callback(err, result);
        }
        connection.loadEntity(id, done);
    };

    context.zoomToEntity = function(id, zoomTo) {
        if (zoomTo !== false) {
            this.loadEntity(id, function(err, result) {
                if (err) return;
                var entity = _.find(result.data, function(e) { return e.id === id; });
                if (entity) { map.zoomTo(entity); }
            });
        }

        map.on('drawn.zoomToEntity', function() {
            if (!context.hasEntity(id)) return;
            map.on('drawn.zoomToEntity', null);
            context.on('enter.zoomToEntity', null);
            context.enter(iD.modes.Select(context, [id]));
        });

        context.on('enter.zoomToEntity', function() {
            if (mode.id !== 'browse') {
                map.on('drawn.zoomToEntity', null);
                context.on('enter.zoomToEntity', null);
            }
        });
    };

    /* History */
    context.graph = history.graph;
    context.changes = history.changes;
    context.intersects = history.intersects;

    var inIntro = false;

    context.inIntro = function(_) {
        if (!arguments.length) return inIntro;
        inIntro = _;
        return context;
    };

    context.save = function() {
        if (inIntro || (mode && mode.id === 'save')) return;
        history.save();
        if (history.hasChanges()) return t('save.unsaved_changes');
    };

    context.flush = function() {
        connection.flush();
        features.reset();
        history.reset();
        return context;
    };

    // Debounce save, since it's a synchronous localStorage write,
    // and history changes can happen frequently (e.g. when dragging).
    var debouncedSave = _.debounce(context.save, 350);
    function withDebouncedSave(fn) {
        return function() {
            var result = fn.apply(history, arguments);
            debouncedSave();
            return result;
        };
    }

    context.perform = withDebouncedSave(history.perform);
    context.replace = withDebouncedSave(history.replace);
    context.pop = withDebouncedSave(history.pop);
    context.overwrite = withDebouncedSave(history.overwrite);
    context.undo = withDebouncedSave(history.undo);
    context.redo = withDebouncedSave(history.redo);

    /* Graph */
    context.hasEntity = function(id) {
        return history.graph().hasEntity(id);
    };

    context.entity = function(id) {
        return history.graph().entity(id);
    };

    context.childNodes = function(way) {
        return history.graph().childNodes(way);
    };

    context.geometry = function(id) {
        return context.entity(id).geometry(history.graph());
    };

    /* Modes */
    context.enter = function(newMode) {
        if (mode) {
            mode.exit();
            dispatch.exit(mode);
        }

        mode = newMode;
        mode.enter();
        dispatch.enter(mode);
    };

    context.mode = function() {
        return mode;
    };

    context.selectedIDs = function() {
        if (mode && mode.selectedIDs) {
            return mode.selectedIDs();
        } else {
            return [];
        }
    };

    /* Behaviors */
    context.install = function(behavior) {
        context.surface().call(behavior);
    };

    context.uninstall = function(behavior) {
        context.surface().call(behavior.off);
    };

    /* Copy/Paste */
    var copyIDs = [], copyGraph;
    context.copyGraph = function() { return copyGraph; };
    context.copyIDs = function(_) {
        if (!arguments.length) return copyIDs;
        copyIDs = _;
        copyGraph = history.graph();
        return context;
    };

    /* Projection */
    context.projection = iD.geo.RawMercator();

    /* Background */
    var background = iD.Background(context);
    context.background = function() { return background; };

    /* Features */
    var features = iD.Features(context);
    context.features = function() { return features; };
    context.hasHiddenConnections = function(id) {
        var graph = history.graph(),
            entity = graph.entity(id);
        return features.hasHiddenConnections(entity, graph);
    };

    /* Map */
    var map = iD.Map(context);
    context.map = function() { return map; };
    context.layers = function() { return map.layers; };
    context.surface = function() { return map.surface; };
    context.editable = function() { return map.editable(); };
    context.mouse = map.mouse;
    context.extent = map.extent;
    context.pan = map.pan;
    context.zoomIn = map.zoomIn;
    context.zoomOut = map.zoomOut;
    context.zoomInFurther = map.zoomInFurther;
    context.zoomOutFurther = map.zoomOutFurther;

    context.surfaceRect = function() {
        // Work around a bug in Firefox.
        //   http://stackoverflow.com/questions/18153989/
        //   https://bugzilla.mozilla.org/show_bug.cgi?id=530985
        return context.surface().node().parentNode.getBoundingClientRect();
    };

    /* Presets */
    var presets = iD.presets();

    context.presets = function(_) {
        if (!arguments.length) return presets;
        presets.load(_);
        iD.areaKeys = presets.areaKeys();
        return context;
    };

    context.imagery = function(_) {
        background.load(_);
        return context;
    };

    context.container = function(_) {
        if (!arguments.length) return container;
        container = _;
        container.classed('id-container', true);
        return context;
    };

    /* Taginfo */
    var taginfo;
    context.taginfo = function(_) {
        if (!arguments.length) return taginfo;
        taginfo = _;
        return context;
    };

    var embed = false;
    context.embed = function(_) {
        if (!arguments.length) return embed;
        embed = _;
        return context;
    };

    var assetPath = '';
    context.assetPath = function(_) {
        if (!arguments.length) return assetPath;
        assetPath = _;
        return context;
    };

    var assetMap = {};
    context.assetMap = function(_) {
        if (!arguments.length) return assetMap;
        assetMap = _;
        return context;
    };

    context.imagePath = function(_) {
        var asset = 'img/' + _;
        return assetMap[asset] || assetPath + asset;
    };

    return d3.rebind(context, dispatch, 'on');
};

iD.version = '1.8.0';

(function() {
    var detected = {};

    var ua = navigator.userAgent,
        m = null;

    m = ua.match(/(edge)\/?\s*(\.?\d+(\.\d+)*)/i);   // Edge
    if (m !== null) {
        detected.browser = m[1];
        detected.version = m[2];
    }
    if (!detected.browser) {
        m = ua.match(/Trident\/.*rv:([0-9]{1,}[\.0-9]{0,})/i);   // IE11
        if (m !== null) {
            detected.browser = 'msie';
            detected.version = m[1];
        }
    }
    if (!detected.browser) {
        m = ua.match(/(opr)\/?\s*(\.?\d+(\.\d+)*)/i);   // Opera 15+
        if (m !== null) {
            detected.browser = 'Opera';
            detected.version = m[2];
        }
    }
    if (!detected.browser) {
        m = ua.match(/(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\.\d+)*)/i);
        if (m !== null) {
            detected.browser = m[1];
            detected.version = m[2];
            m = ua.match(/version\/([\.\d]+)/i);
            if (m !== null) detected.version = m[1];
        }
    }
    if (!detected.browser) {
        detected.browser = navigator.appName;
        detected.version = navigator.appVersion;
    }

    // keep major.minor version only..
    detected.version = detected.version.split(/\W/).slice(0,2).join('.');

    if (detected.browser.toLowerCase() === 'msie') {
        detected.ie = true;
        detected.browser = 'Internet Explorer';
        detected.support = parseFloat(detected.version) >= 11;
    } else {
        detected.ie = false;
        detected.support = true;
    }

    // Added due to incomplete svg style support. See #715
    detected.opera = (detected.browser.toLowerCase() === 'opera' && parseFloat(detected.version) < 15 );

    detected.locale = (navigator.languages && navigator.languages.length)
        ? navigator.languages[0] : (navigator.language || navigator.userLanguage || 'en-US');

    detected.filedrop = (window.FileReader && 'ondrop' in window);

    function nav(x) {
        return navigator.userAgent.indexOf(x) !== -1;
    }

    if (nav('Win')) {
        detected.os = 'win';
        detected.platform = 'Windows';
    }
    else if (nav('Mac')) {
        detected.os = 'mac';
        detected.platform = 'Macintosh';
    }
    else if (nav('X11') || nav('Linux')) {
        detected.os = 'linux';
        detected.platform = 'Linux';
    }
    else {
        detected.os = 'win';
        detected.platform = 'Unknown';
    }

    iD.detect = function() { return detected; };
})();
<|endoftext|>


<commit_before>// Radius of layers according to course level
var radius = new Array,
		ln,
		li = [];

for (var i = 0; i < 10; i++) {
	radius[i] = 15 + 10 * i;
	li[i] = 0;
}

sigma.classes.graph.addIndex('layerCount',{
	constructor: function(){ this.layerCount = []; },
	addNode: function(n){
		if (!this.layerCount[n.layer])
			this.layerCount[n.layer] = 0;
		this.layerCount[n.layer]++;
		console.log(this.layerCount);
	},
	dropNode: function(nid){
		this.layerCount[this.nodeIndex[nid].layer]--;
	}
});

sigma.classes.graph.attach('addNode', 'refreshCoordinates', function(){
	var _self = this;
	_self.nodesArray.forEach(function(n,i,a){
		n.x = radius[n.layer] * Math.sin(
			n.layerIndex*2*Math.PI/_self.layerCount[n.layer]
		);
		n.y = radius[n.layer] * Math.cos(
			n.layerIndex*2*Math.PI/_self.layerCount[n.layer]
		);
	});
});

var s = new sigma('container');

oboe('/data/csci_spring_2015.json')
  .node({
		// Process each course as it arrives
		'result[*]': function(course){
			ln = Math.floor(course.number / 1000) - 1;
			console.log('CSCI-' + course.number + ' ' + ln);
			// Add the current node
			s.graph.addNode({
				id: 'n'+course.id,
				x: Math.random(),
				y: Math.random(),
				size: 2,
				color: '#666',
				label: 'CSCI-'+course.number,
				layer: ln,
				layerIndex: li[ln]++
			});
			// Refresh the graph
			s.refresh();
		}
	});
<commit_msg>Use relative path to data<commit_after>// Radius of layers according to course level
var radius = new Array,
		ln,
		li = [];

for (var i = 0; i < 10; i++) {
	radius[i] = 15 + 10 * i;
	li[i] = 0;
}

sigma.classes.graph.addIndex('layerCount',{
	constructor: function(){ this.layerCount = []; },
	addNode: function(n){
		if (!this.layerCount[n.layer])
			this.layerCount[n.layer] = 0;
		this.layerCount[n.layer]++;
		console.log(this.layerCount);
	},
	dropNode: function(nid){
		this.layerCount[this.nodeIndex[nid].layer]--;
	}
});

sigma.classes.graph.attach('addNode', 'refreshCoordinates', function(){
	var _self = this;
	_self.nodesArray.forEach(function(n,i,a){
		n.x = radius[n.layer] * Math.sin(
			n.layerIndex*2*Math.PI/_self.layerCount[n.layer]
		);
		n.y = radius[n.layer] * Math.cos(
			n.layerIndex*2*Math.PI/_self.layerCount[n.layer]
		);
	});
});

var s = new sigma('container');

oboe('../data/csci_spring_2015.json')
  .node({
		// Process each course as it arrives
		'result[*]': function(course){
			ln = Math.floor(course.number / 1000) - 1;
			console.log('CSCI-' + course.number + ' ' + ln);
			// Add the current node
			s.graph.addNode({
				id: 'n'+course.id,
				x: Math.random(),
				y: Math.random(),
				size: 2,
				color: '#666',
				label: 'CSCI-'+course.number,
				layer: ln,
				layerIndex: li[ln]++
			});
			// Refresh the graph
			s.refresh();
		}
	});
<|endoftext|>


<commit_before><commit_msg>Update JS file<commit_after>
// Begin google authentication code

var profile; //profile variable available at the global scope

function onSignIn(googleUser) {
	profile = googleUser.getBasicProfile();
  	console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
  	console.log('Name: ' + profile.getName());
  	console.log('Image URL: ' + profile.getImageUrl());
  	console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.
}

function signOut() {
	var auth2 = gapi.auth2.getAuthInstance();
	auth2.signOut().then(function () {
		console.log('User signed out.');
	  });
}

// end google authentication code
<|endoftext|>


<commit_before>"use strict";

var similarArtists = {
  results: [{ "name": undefined }],
};

var currentPlayerInfo = {
  artist: function () {
    if (similarArtists.results.length > 0) {
      return similarArtists.results[similarArtists.artistPosition].name;
    }
  }
};

var listenHistory = {
  getCurrentPlayerInfo: function () {
    this.previousVideos.push({
      artist: currentPlayerInfo.artist(),
      videoTitle: currentPlayerInfo.videoTitle,
      videoID: currentPlayerInfo.videoID,
      videoDescription: currentPlayerInfo.videoDescription
    });
    var videoTitleEdited = currentPlayerInfo.videoTitle.replace(currentPlayerInfo.artist(), "");
    this.titlesOnly.push(videoTitleEdited.replace(/[^0-9a-z]/gi, ""));
  },
  previousVideos: [],
  titlesOnly: [],
  mixtape: []
};

$("#initialSearchInput").click(function () {
  initialSearchInput.value = "";
  $(".searchBtn").removeClass("disabled");
});

$(".searchBtn").click(function () {
  runSearch();
});

$("#initialSearchInput").keydown(function (key) {
  if (key.keyCode === 13) {
    runSearch();
    this.blur();
  }
});

function runSearch() {
  var searchInput = $("#initialSearchInput").val().toLowerCase();
  if (searchInput !== similarArtists.results[0].name && searchInput !== "") {
    similarArtists.artistPosition = 0;
    similarArtists.results = [{ "name": searchInput, "frequency": 100, "artistImage": undefined }];
    runSpotifySearch(searchInput); // Located in spotifyMethod.js
    $(".subheading").hide();
    $(".nowPlayingSection").show();
    $(".customPlayerUI").css("visibility", "visible");
    $(".relevanceColorScale").show();
  }
}

function displayResults() {
  $(".allSearchResults").html("");
  var forEachCount = 0;
  similarArtists.results.forEach(function (result) {
    forEachCount++;
    var relevance = assignRelevanceClassForColorScale(result.frequency);
    var individualResultBtnHTMLSuffix = relevance + "'>" + result.name.replace(/"/g, "") + "<button class='deleteArtistResultBtn btn btn-sm btn-default'>✖</button>
";
    var individualResultBtnHTML = "<li class='individualResult " + individualResultBtnHTMLSuffix;

    if (forEachCount <= similarArtists.artistPosition) {
      individualResultBtnHTML = "<li class='individualResult previousResults " + individualResultBtnHTMLSuffix;
    } else if (forEachCount === similarArtists.artistPosition + 1) {
      individualResultBtnHTML = "
 similarArtists.artistPosition + 10) {
      individualResultBtnHTML = "
= 5) {
    return "relevance5of5";
  } else if (frequency === 4) {
    return "relevance4of5";
  } else if (frequency === 3) {
    return "relevance3of5";
  } else if (frequency === 2) {
    return "relevance2of5";
  } else {
    return "relevance1of5";
  }
}

function adjustPreviousAndAdditionalResultsBtnState() {
  if ($(".previousResults").length > 0) {
    $(".showPreviousResultsBtn").html("Show previous results").show();
  } else {
    $(".showPreviousResultsBtn").hide();
  }
  if ($(".additionalResults").length > 0) {
    $(".showAdditionalResultsBtn").html("Show more results").show();
  } else {
    $(".showAdditionalResultsBtn").hide();
  }
}

$(".showPreviousResultsBtn").click(function () {
  if ($(".previousResults").css("display") === "none") {
    $(".previousResults").slideDown("slow", function () {
      $(".showPreviousResultsBtn").html("Hide previous results");
    });
  } else {
    $(".previousResults").slideUp("slow", function () {
      $(".showPreviousResultsBtn").html("Show previous results");
    });
  }
});

$(".showAdditionalResultsBtn").click(function () {
  if ($(".additionalResults").css("display") === "none") {
    $(".additionalResults").slideDown("slow");
    $(".showAdditionalResultsBtn").html("Show less results");
  } else {
    $(".additionalResults").slideUp("slow");
    $(".showAdditionalResultsBtn").html("Show more results");
  }
});

(function skipToThisArtist() {
  $("ol").on("click", "li:not(.mixtapeTitle)", function (event) {
    event.stopPropagation();
    if ($(this).html().indexOf("") !== -1) {
      similarArtists.artistPosition = $(this).index();
      findAndPlayVideo(); // Located in search.js
    }
  });
})();

(function deleteThisArtistFromSimilarArtists() {
  $(".allSearchResults").on("click", "button", function (event) {
    event.stopPropagation(event);
    if ($(this).html() === "✖") {
      var locationOfArtistClicked = $(this).parent().index();
      similarArtists.results.splice(locationOfArtistClicked, 1);
      $(this).parent().fadeOut("slow", function () {
        if (locationOfArtistClicked === similarArtists.artistPosition) {
          similarArtists.artistPosition--;
          cueNextVideo();
        } else {
          displayResults();
        }
      });
    }
  });
})();

function cueNextVideo() {
  if ($(".lockArtistBtn").hasClass("btn-default")) { // "Lock artist" is disabled
    $(".allSearchResults li").eq(similarArtists.artistPosition).slideUp("fast");
    similarArtists.artistPosition++;
  }
  findAndPlayVideo();
  clearInterval(currentPlayerInfo.playbackTimer);
  currentPlayerInfo.playbackTimer = null;
  $(".currentTime").html("0:00");
  $(".trackLength").html(" / 0:00");
  $(".addToMixtapeBtn").removeClass("disabled");
}

(function setupDragAndDropForOrderedLists() {
  $("ol").sortable({
    placeholder: {
      element: function () {
        return $("

");
      },
      update: function () {
        return;
      }
    }
  });
  $("ol").disableSelection();

  $("ol").on("mousedown", "li", function () {
    var elementClicked = $(this);
    var ignoreQuickClicksTimer;
    elementClicked.mouseup(() => clearTimeout(ignoreQuickClicksTimer));
    ignoreQuickClicksTimer = setTimeout(function () {
      elementClicked.off("mouseup");
      elementClicked.addClass("itemBeingDragged", 100); // jQuery UI feature, animates CSS class style differences
      var originalPosition = elementClicked.index();
      var newPosition;
      $("ol").on("mousemove", "li", function () {
        newPosition = $(".placeholderForDrag").index();
      });

      $("ol").on("mouseup", "li", function () {
        $("ol").off("mousemove");
        $("ol").off("mouseup");
        if (newPosition === undefined) {
          newPosition = originalPosition;
        }
        // similarArtists

        if (elementClicked.hasClass("individualResult")) {
          var artistObjectBeingMoved = similarArtists.results.splice(originalPosition, 1)[0];
          similarArtists.results.splice(newPosition, 0, artistObjectBeingMoved);
          if (originalPosition === similarArtists.artistPosition) {
            similarArtists.artistPosition = newPosition;
          }
        }
        // mixtape

        if (!elementClicked.hasClass("individualResult")) {
          var mixtapeTitleBeingMoved = listenHistory.mixtape.splice(originalPosition, 1)[0];
          listenHistory.mixtape.splice(newPosition, 0, mixtapeTitleBeingMoved);
        }
        elementClicked.removeClass("itemBeingDragged", 75, function () {
          displayResults();
        });
      });
    }, 200);
  });
})();

function displayMixtapeSection() {

  if (listenHistory.mixtape.length > 0) {
    $(".mixtapeViewableList").html("");
    listenHistory.mixtape.forEach(function (track) {
      var mixtapeTrackHTML = "
" + track.replace(/"/g, "") + "<button class='deleteVideoFromHistoryBtn btn btn-sm btn-info'>✖</button>
";
      $(".mixtapeViewableList").append(mixtapeTrackHTML);
    });
    $(".createMixtapeBtn").show();
    $(".clearMixtapeBtn").show();
    if (!currentPlayerInfo.userLoggedIn) {
      $(".pre-auth").show();
    }
  } else {
    $(".mixtapePlaceholder").show();
    $(".createMixtapeBtn").hide();
    $(".clearMixtapeBtn").hide();
  }
}

(function assignDeleteVideoFromHistoryBtnFunctionality() {
  $(".mixtapeViewableList").on("click", "button", function () {
    listenHistory.mixtape.splice($(this).parent("li").index(), 1);
    $(this).parent("li").fadeOut("fast", function () {
      displayMixtapeSection();
      $(".addToMixtapeBtn").removeClass("disabled");
    });
  });
})();

$(".addToMixtapeBtn").click(function () {
  if (!$(this).hasClass("disabled") && currentPlayerInfo.videoTitle !== undefined) {
    $(".addToMixtapeBtn").addClass("disabled");
    listenHistory.mixtape.push(currentPlayerInfo.videoTitle);
    displayMixtapeSection();
  }
});

$(".createMixtapeBtn").click(function () {
  if (currentPlayerInfo.userLoggedIn) {
    autoCreatePlaylist();
    $(this).addClass("disabled");
    $(this).html("Now creating your Mixtape");
  }
});

$(".clearMixtapeBtn").click(function () {
  listenHistory.mixtape = [];
  $(".mixtapeViewableList").slideUp("slow", function () {
    $(".createMixtapeBtn").fadeOut("slow");
    $(".viewMixtape").fadeOut("slow");
    $(".pre-auth").fadeOut("slow");
    $(".clearMixtapeBtn").fadeOut("slow", function () {
      $(".addToMixtapeBtn").removeClass("disabled");
      $(".mixtapeViewableList").html("").show();
      displayMixtapeSection();
    });
  });
});

// Player Controls
$(".pauseVideoBtn").click(function () {
  if ($(".pauseVideoBtn span").hasClass("glyphicon-pause")) {
    $(".pauseVideoBtn span").removeClass("glyphicon-pause").addClass("glyphicon-play");
    currentPlayerInfo.player.pauseVideo();
  } else {
    $(".pauseVideoBtn span").removeClass("glyphicon-play").addClass("glyphicon-pause");
    currentPlayerInfo.player.playVideo();
  }
});

$(".nextVideoBtn").click(function () {
  cueNextVideo();
});

$(".lockArtistBtn").click(function () {
  if ($(this).hasClass("btn-default")) {
    $(this).removeClass("btn-default").addClass("btn-warning"); // Enable
  } else {
    $(this).removeClass("btn-warning").addClass("btn-default"); // Disable
  }
});

$(".showPlayerBtn").click(function () {
  if ($(".videoWrapper").css("display") === "none") {
    $(".videoWrapper").slideDown("slow", function () {
      $(".showPlayerBtn").html(" Hide player");
    });
  } else {
    $(".videoWrapper").slideUp("slow", function () {
      $(".showPlayerBtn").html(" Show player");
    });
  }
});

$("button").click(function () {
  $(this).blur();
});<commit_msg>"UI Feedback when dragging current playing artist"<commit_after>"use strict";

var similarArtists = {
  results: [{ "name": undefined }],
};

var currentPlayerInfo = {
  artist: function () {
    if (similarArtists.results.length > 0) {
      return similarArtists.results[similarArtists.artistPosition].name;
    }
  }
};

var listenHistory = {
  getCurrentPlayerInfo: function () {
    this.previousVideos.push({
      artist: currentPlayerInfo.artist(),
      videoTitle: currentPlayerInfo.videoTitle,
      videoID: currentPlayerInfo.videoID,
      videoDescription: currentPlayerInfo.videoDescription
    });
    var videoTitleEdited = currentPlayerInfo.videoTitle.replace(currentPlayerInfo.artist(), "");
    this.titlesOnly.push(videoTitleEdited.replace(/[^0-9a-z]/gi, ""));
  },
  previousVideos: [],
  titlesOnly: [],
  mixtape: []
};

$("#initialSearchInput").click(function () {
  initialSearchInput.value = "";
  $(".searchBtn").removeClass("disabled");
});

$(".searchBtn").click(function () {
  runSearch();
});

$("#initialSearchInput").keydown(function (key) {
  if (key.keyCode === 13) {
    runSearch();
    this.blur();
  }
});

function runSearch() {
  var searchInput = $("#initialSearchInput").val().toLowerCase();
  if (searchInput !== similarArtists.results[0].name && searchInput !== "") {
    similarArtists.artistPosition = 0;
    similarArtists.results = [{ "name": searchInput, "frequency": 100, "artistImage": undefined }];
    runSpotifySearch(searchInput); // Located in spotifyMethod.js
    $(".subheading").hide();
    $(".nowPlayingSection").show();
    $(".customPlayerUI").css("visibility", "visible");
    $(".relevanceColorScale").show();
  }
}

function displayResults() {
  $(".allSearchResults").html("");
  var forEachCount = 0;
  similarArtists.results.forEach(function (result) {
    forEachCount++;
    var relevance = assignRelevanceClassForColorScale(result.frequency);
    var individualResultBtnHTMLSuffix = relevance + "'>" + result.name.replace(/"/g, "") + "<button class='deleteArtistResultBtn btn btn-sm btn-default'>✖</button>
";
    var individualResultBtnHTML = "<li class='individualResult " + individualResultBtnHTMLSuffix;

    if (forEachCount <= similarArtists.artistPosition) {
      individualResultBtnHTML = "<li class='individualResult previousResults " + individualResultBtnHTMLSuffix;
    } else if (forEachCount === similarArtists.artistPosition + 1) {
      individualResultBtnHTML = "
 similarArtists.artistPosition + 10) {
      individualResultBtnHTML = "
= 5) {
    return "relevance5of5";
  } else if (frequency === 4) {
    return "relevance4of5";
  } else if (frequency === 3) {
    return "relevance3of5";
  } else if (frequency === 2) {
    return "relevance2of5";
  } else {
    return "relevance1of5";
  }
}

function adjustPreviousAndAdditionalResultsBtnState() {
  if ($(".previousResults").length > 0) {
    $(".showPreviousResultsBtn").html("Show previous results").show();
  } else {
    $(".showPreviousResultsBtn").hide();
  }
  if ($(".additionalResults").length > 0) {
    $(".showAdditionalResultsBtn").html("Show more results").show();
  } else {
    $(".showAdditionalResultsBtn").hide();
  }
}

$(".showPreviousResultsBtn").click(function () {
  if ($(".previousResults").css("display") === "none") {
    $(".previousResults").slideDown("slow", function () {
      $(".showPreviousResultsBtn").html("Hide previous results");
    });
  } else {
    $(".previousResults").slideUp("slow", function () {
      $(".showPreviousResultsBtn").html("Show previous results");
    });
  }
});

$(".showAdditionalResultsBtn").click(function () {
  if ($(".additionalResults").css("display") === "none") {
    $(".additionalResults").slideDown("slow");
    $(".showAdditionalResultsBtn").html("Show less results");
  } else {
    $(".additionalResults").slideUp("slow");
    $(".showAdditionalResultsBtn").html("Show more results");
  }
});

(function skipToThisArtist() {
  $("ol").on("click", "li:not(.mixtapeTitle)", function (event) {
    event.stopPropagation();
    if ($(this).html().indexOf("") !== -1) {
      similarArtists.artistPosition = $(this).index();
      findAndPlayVideo(); // Located in search.js
    }
  });
})();

(function deleteThisArtistFromSimilarArtists() {
  $(".allSearchResults").on("click", "button", function (event) {
    event.stopPropagation(event);
    if ($(this).html() === "✖") {
      var locationOfArtistClicked = $(this).parent().index();
      similarArtists.results.splice(locationOfArtistClicked, 1);
      $(this).parent().fadeOut("slow", function () {
        if (locationOfArtistClicked === similarArtists.artistPosition) {
          similarArtists.artistPosition--;
          cueNextVideo();
        } else {
          displayResults();
        }
      });
    }
  });
})();

function cueNextVideo() {
  if ($(".lockArtistBtn").hasClass("btn-default")) { // "Lock artist" is disabled
    $(".allSearchResults li").eq(similarArtists.artistPosition).slideUp("fast");
    similarArtists.artistPosition++;
  }
  findAndPlayVideo();
  clearInterval(currentPlayerInfo.playbackTimer);
  currentPlayerInfo.playbackTimer = null;
  $(".currentTime").html("0:00");
  $(".trackLength").html(" / 0:00");
  $(".addToMixtapeBtn").removeClass("disabled");
}

(function setupDragAndDropForOrderedLists() {
  $("ol").sortable({
    placeholder: {
      element: function () {
        return $("

");
      },
      update: function () {
        return;
      }
    }
  });
  $("ol").disableSelection();

  $("ol").on("mousedown", "li", function () {
    var elementClicked = $(this);
    var ignoreQuickClicksTimer;
    elementClicked.mouseup(() => clearTimeout(ignoreQuickClicksTimer));
    ignoreQuickClicksTimer = setTimeout(function () {
      elementClicked.off("mouseup");
      elementClicked.addClass("itemBeingDragged", 100); // jQuery UI feature, animates CSS class style differences
      var originalPosition = elementClicked.index();
      var newPosition;
      $("ol").on("mousemove", "li", function () {
        newPosition = $(".placeholderForDrag").index();
        if (originalPosition === similarArtists.artistPosition) {
          $(".individualResult").each(function () {
            if ($(this).index() < newPosition) {
              $(this).css("opacity", "0.7");
            } else {
              $(this).css("opacity", "1");
            }
          });
        }
      });

      $("ol").on("mouseup", "li", function () {
        $("ol").off("mousemove");
        $("ol").off("mouseup");
        if (newPosition === undefined) {
          newPosition = originalPosition;
        }
        // similarArtists

        if (elementClicked.hasClass("individualResult")) {
          var artistObjectBeingMoved = similarArtists.results.splice(originalPosition, 1)[0];
          similarArtists.results.splice(newPosition, 0, artistObjectBeingMoved);
          if (originalPosition === similarArtists.artistPosition) {
            similarArtists.artistPosition = newPosition;
          }
        }
        // mixtape

        if (!elementClicked.hasClass("individualResult")) {
          var mixtapeTitleBeingMoved = listenHistory.mixtape.splice(originalPosition, 1)[0];
          listenHistory.mixtape.splice(newPosition, 0, mixtapeTitleBeingMoved);
        }
        elementClicked.removeClass("itemBeingDragged", 75, function () {
          displayResults();
        });
      });
    }, 200);
  });
})();

function displayMixtapeSection() {

  if (listenHistory.mixtape.length > 0) {
    $(".mixtapeViewableList").html("");
    listenHistory.mixtape.forEach(function (track) {
      var mixtapeTrackHTML = "
" + track.replace(/"/g, "") + "<button class='deleteVideoFromHistoryBtn btn btn-sm btn-info'>✖</button>
";
      $(".mixtapeViewableList").append(mixtapeTrackHTML);
    });
    $(".createMixtapeBtn").show();
    $(".clearMixtapeBtn").show();
    if (!currentPlayerInfo.userLoggedIn) {
      $(".pre-auth").show();
    }
  } else {
    $(".mixtapePlaceholder").show();
    $(".createMixtapeBtn").hide();
    $(".clearMixtapeBtn").hide();
  }
}

(function assignDeleteVideoFromHistoryBtnFunctionality() {
  $(".mixtapeViewableList").on("click", "button", function () {
    listenHistory.mixtape.splice($(this).parent("li").index(), 1);
    $(this).parent("li").fadeOut("fast", function () {
      displayMixtapeSection();
      $(".addToMixtapeBtn").removeClass("disabled");
    });
  });
})();

$(".addToMixtapeBtn").click(function () {
  if (!$(this).hasClass("disabled") && currentPlayerInfo.videoTitle !== undefined) {
    $(".addToMixtapeBtn").addClass("disabled");
    listenHistory.mixtape.push(currentPlayerInfo.videoTitle);
    displayMixtapeSection();
  }
});

$(".createMixtapeBtn").click(function () {
  if (currentPlayerInfo.userLoggedIn) {
    autoCreatePlaylist();
    $(this).addClass("disabled");
    $(this).html("Now creating your Mixtape");
  }
});

$(".clearMixtapeBtn").click(function () {
  listenHistory.mixtape = [];
  $(".mixtapeViewableList").slideUp("slow", function () {
    $(".createMixtapeBtn").fadeOut("slow");
    $(".viewMixtape").fadeOut("slow");
    $(".pre-auth").fadeOut("slow");
    $(".clearMixtapeBtn").fadeOut("slow", function () {
      $(".addToMixtapeBtn").removeClass("disabled");
      $(".mixtapeViewableList").html("").show();
      displayMixtapeSection();
    });
  });
});

// Player Controls
$(".pauseVideoBtn").click(function () {
  if ($(".pauseVideoBtn span").hasClass("glyphicon-pause")) {
    $(".pauseVideoBtn span").removeClass("glyphicon-pause").addClass("glyphicon-play");
    currentPlayerInfo.player.pauseVideo();
  } else {
    $(".pauseVideoBtn span").removeClass("glyphicon-play").addClass("glyphicon-pause");
    currentPlayerInfo.player.playVideo();
  }
});

$(".nextVideoBtn").click(function () {
  cueNextVideo();
});

$(".lockArtistBtn").click(function () {
  if ($(this).hasClass("btn-default")) {
    $(this).removeClass("btn-default").addClass("btn-warning"); // Enable
  } else {
    $(this).removeClass("btn-warning").addClass("btn-default"); // Disable
  }
});

$(".showPlayerBtn").click(function () {
  if ($(".videoWrapper").css("display") === "none") {
    $(".videoWrapper").slideDown("slow", function () {
      $(".showPlayerBtn").html(" Hide player");
    });
  } else {
    $(".videoWrapper").slideUp("slow", function () {
      $(".showPlayerBtn").html(" Show player");
    });
  }
});

$("button").click(function () {
  $(this).blur();
});<|endoftext|>


<commit_before>"use strict";

$(function() {

    // handle log in event
    $('#sign-in').submit(function(event) {

        event.preventDefault();
        var user = $('#username').val();
        var discogsUsersEndpoint = 'https://api.discogs.com/users/' + user;

        // check username entered is a valid Discogs username
        var discogsPayLoad = checkDiscogsIsValid(user, discogsUsersEndpoint);

    });
});

// initialize error message, invoked upon click in input field[text]
function initializeError() {

    $('label').attr('data-error', ' ');
}

function loadUserLocation(discogsPayLoad) {

    // function to get location of user to use for jambase event lookup
    $.get('https:freegeoip.net/json/', function() {

    }).done(function(data) {

        var userLocation = {};
        userLocation.city = data.city;
        userLocation.country = data.country_name;
        renderInfoBox(userLocation, discogsPayLoad);

    }).fail(function(data) {

    }).always(function() {

    });
}

function checkDiscogsIsValid(user, discogsUsersEndpoint) {

    $.getJSON(discogsUsersEndpoint, function() {
        // set visibility of log-in box elements to none
        $('.sign-in-page').css('display', 'none');

    }).done(function(data) {

        var discogsPayLoad = new Object();
        discogsPayLoad.recordCount = data.num_collection;
        discogsPayLoad.forSaleCount = data.num_for_sale;
        discogsPayLoad.wantListCount = data.num_wantlist;
        discogsPayLoad.registered = data.registered;
        discogsPayLoad.username = data.username;
        discogsPayLoad.artists = [];

        if (discogsPayLoad.recordCount > 0) {
            // load Discogs collection of the user, page 1, limit 50, ascending sort by artist
            loadDiscogsReleases(discogsPayLoad, user, 1, 20, 'asc');

        } else {

            renderEmptyCollectionView();
        }

        return discogsPayLoad;

    }).fail(function(data) {

        if (data.responseJSON === undefined) {

            $('Label').attr('data-error', data.responseJSON.message);

        } else {

            $('Label').attr('data-error', data.responseJSON.message);

        }
        return false;

    }).always(function() {

    });
}

function loadDiscogsReleases(discogsPayLoad, user, page, limit, order) {

    var discogsCollectionEndpoint = 'https://api.discogs.com/users/' + user + '/collection/folders/0/releases?' + 'page=' + page + '&per_page=' + limit + '&sort=artist' + '&sort_order=' + order;

    // call Discogs collection/releases API
    $.getJSON(discogsCollectionEndpoint, function(data) {

    }).done(function(data) {

        var artistId = '';

        for (var i = data.releases.length - 1; i >= 0; i--) {

            for (var j = data.releases[i].basic_information.artists.length - 1; j >= 0; j--) {

                if (artistId != data.releases[i].basic_information.artists[j].id) {
                    artistId = data.releases[i].basic_information.artists[j].id;

                    if (artistObj != undefined) {

                        discogsPayLoad.artists.push(artistObj);
                        albumObj = {};
                    }

                    var artistObj = {};
                    artistObj.albums = [];
                    artistObj.members = [];

                    artistId = data.releases[i].basic_information.artists[j].id;
                    artistObj.artistid = data.releases[i].basic_information.artists[j].id;
                    artistObj.name = data.releases[i].basic_information.artists[j].name.replace(/\(\d\)/, ""); // remove parenthesis + number
                    artistObj.name = artistObj.name.replace(/\s+$/, ''); // remove trailing space
                    artistObj.url = data.releases[i].basic_information.artists[j].resource_url;
                }
            }

            var albumObj = {};
            albumObj.artistId = artistId;
            albumObj.title = data.releases[i].basic_information.title;
            albumObj.year = data.releases[i].basic_information.year;
            albumObj.format = data.releases[i].basic_information.formats[0].name;
            artistObj.albums.push(albumObj);

        }

        discogsPayLoad.artists.push(artistObj);

        enrichDiscogsArtists(discogsPayLoad);

    }).fail(function(data, success) {

        renderLoadingErrorView('Discogs', data);

    }).always(function() {

    });
}

function enrichDiscogsArtists(discogsPayLoad) {

    $.each(discogsPayLoad.artists, function(i, data) {

        $.getJSON(discogsPayLoad.artists[i].url, function(data) {

        }).done(function(data) {

            var artistObj = {};
            artistObj.members = [];

            discogsPayLoad.artists[i].profile = data.profile;

            var activeMembersCount = 0;
            for (var j = data.members.length - 1; j >= 0; j--) {

                if (data.members[j].active === true) {

                    var membersObj = {};
                    membersObj.name = data.members[j].name;
                    membersObj.active = data.members[j].active;
                    artistObj.members.push(membersObj);

                    activeMembersCount++;
                }

                if (activeMembersCount >= 6) {
                    break; // only want to show 6 active members
                }

            }

            discogsPayLoad.artists[i].members = artistObj.members;

            loadLastFMImages(discogsPayLoad);

        }).fail(function(data, success) {

            renderLoadingErrorView('Discogs', data);

        }).always(function() {

        });

    });
}

function loadLastFMImages(discogsPayLoad) {

    $.each(discogsPayLoad.artists, function(i, data) {

        var lastFMScrobber = 'https://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=' + discogsPayLoad.artists[i].name + '&api_key=a9ec7949488cffd19b50fc457a7731d1&format=json';
        debugger;
        $.getJSON(lastFMScrobber, function(data) {

        }).done(function(data) {

            var keys = Object.keys(data.artist.image);
            var result = {};

            for (var j = data.artist.image.length - 1; j >= 0; j--) {

                if (data.artist.image[j].size === 'large') {

                    var str = JSON.stringify(data.artist.image[j]);
                    str = str.replace('#text', 'text');
                    data.artist.image[j] = JSON.parse(str);
                    discogsPayLoad.artists[i].image = data.artist.image[j].text;
                }
            }

            renderArtistCards(discogsPayLoad);
            loadUserLocation(discogsPayLoad);

        }).fail(function(data, success) {

            renderLoadingErrorView('LastFM', data);

        }).always(function() {

        });

    });
}

function renderInfoBox(userLocation, discogsPayLoad) {

    var infoBoxHTML = '';

    infoBoxHTML += '

Location Information:

';
    infoBoxHTML += '
City: ' + userLocation.city + '
';
    infoBoxHTML += '
Country: ' + userLocation.country + '
';

    if (discogsPayLoad != undefined) {

        infoBoxHTML += '

Discogs Information:

';
        infoBoxHTML += '
Discogs user name: ' + discogsPayLoad.username + '
';
        infoBoxHTML += '
Registered On: ' + discogsPayLoad.registered + '
';
        infoBoxHTML += '
Collection count: ' + discogsPayLoad.recordCount + '
';
        infoBoxHTML += '
Want List count: ' + discogsPayLoad.wantListCount + '
';
        infoBoxHTML += '
For Sale count: ' + discogsPayLoad.forSaleCount + '
';
    }

    // render info box
    $('.js-info-box').html(infoBoxHTML).fadeIn();
}

function renderEmptyCollectionView() {

    var messageHTML = '

';

    messageHTML += '

Empty Collection
';
    messageHTML += '
No records are maintained in your Discogs collection
';
    messageHTML += '
and therefore nothing to show.

';

    // set visibility of main page element to none
    $('.js-main-page').css('display', 'none');
    // render empty collection message box
    $('.js-message-box').html(messageHTML).fadeIn();
    $('.js-message-box').css('visibility', 'visible');

}

function renderLoadingErrorView(api, data) {

    var messageHTML = '

';

    messageHTML += '

Load Error
';
    messageHTML += '
Unable to load all information since ' + api + ' API returned following error:
';

    if (data.status != 0) {
        messageHTML += '
HTTP code ' + data.status + ' - ' + data.statusText + '

';
    } else {
        messageHTML += '
HTTP code 429 (Too Many Requests) No Access-Control-Allow-Origin present

';
    }

    // set visibility of main page element to none
    $('.js-main-page').css('display', 'none');
    // render empty collection message box
    $('.js-message-box').html(messageHTML).fadeIn();
    $('.js-message-box').css('visibility', 'visible');

}

jQuery(function($) {
    var target = $('#target');

    $('.toggle-loading').click(function() {
        if (target.hasClass('loading')) {
            target.loadingOverlay('remove');
        } else {
            target.loadingOverlay();
        };
    });
});

function renderArtistCards(discogsPayLoad) {

    var artistHTML = '';
    var counter = 0;
    var noOfColumns = 4;

    // loop over Discogs data load and render page
    for (var i = discogsPayLoad.artists.length - 1; i >= 0; i--) {

        if (counter === 0) {

            artistHTML += '
';
        }

        counter++;
        artistHTML += '
';
        //artistHTML += '

' + discogsPayLoad.artists[i].name + '

';
        artistHTML += '
';
        artistHTML += '
';
        artistHTML += '

' + discogsPayLoad.artists[i].name + '

';

        if (discogsPayLoad.artists[i].image === '') {

            artistHTML += '';

        } else {

            artistHTML += '';
        }

        artistHTML += '
'; //  closing tag card image
        artistHTML += '
';
        artistHTML += '' + 'Members' + '' + 'more_vert' + '';

        if (discogsPayLoad.artists[i].members === undefined) {

            artistHTML += '
No active members found
';

        } else {

            artistHTML += '

';

            var memberCount = 0;
            for (var j = discogsPayLoad.artists[i].members.length - 1; j >= 0; j--) {

                if (memberCount === 0) { artistHTML += '
'; }
                memberCount++;
                artistHTML += '' + discogsPayLoad.artists[i].members[j].name + '	';
                if (memberCount === 2) {
                    artistHTML += '
';
                    memberCount = 0;
                }
            }

            var emptyMembers = 6 - discogsPayLoad.artists[i].members.length
            if (discogsPayLoad.artists[i].members.length === 0) {
                artistHTML += '

';
                artistHTML += '

';
                artistHTML += '

';
            } else if (discogsPayLoad.artists[i].members.length === 1 || discogsPayLoad.artists[i].members.length === 2) {
                artistHTML += '

';
                artistHTML += '

';
            } else if (discogsPayLoad.artists[i].members.length === 3 || discogsPayLoad.artists[i].members.length === 4) {
                artistHTML += '

';
            }

            artistHTML += '

';
        }

        artistHTML += '
'; //  closing tag card content
        artistHTML += '
';
        artistHTML += '' + 'Artist Profile' + 'close';
        artistHTML += '
' + discogsPayLoad.artists[i].profile + '
';
        artistHTML += '
'; //  closing tag card reveal
        artistHTML += '
';
        artistHTML += '
';
        artistHTML += '' + 'Live Events' + '';
        artistHTML += '
'; //  closing tag card action
        artistHTML += '
'; //  closing tag card stacked
        artistHTML += '
'; //  closing tag card type
        artistHTML += '
'; //  closing tag column

        if (counter === noOfColumns) {

            counter = 0;
            artistHTML += '
'; // closing tag row
        }
    }

    // render artist cards
    $('.js-main-view').html(artistHTML).fadeIn();
}

function renderAlbumView(response, noOfColumns) {

    var counter = 0;
    $.each(response, function(index, value) {

        if (counter === 0) {

            musicState.albumHTML += '
';
        }

        counter++;
        musicState.albumHTML += '
';
        musicState.albumHTML += '
';
        musicState.albumHTML += '<div class="card-image
';
        musicState.albumHTML += '
';
        musicState.albumHTML += '
';
        musicState.albumHTML += '' + value.basic_information.title + 'more_vert';
        musicState.albumHTML += '
' + 'Year' + '
';
        musicState.albumHTML += '

' + value.basic_information.year + '

';
        musicState.albumHTML += '
' + 'Format' + '
';
        musicState.albumHTML += '

' + value.basic_information.formats[0].name + '

';
        musicState.albumHTML += '
';
        musicState.albumHTML += 'Card Titleclose'
        musicState.albumHTML += '
Here is some more information about this product that is only revealed once clicked on.
'
        musicState.albumHTML += '
';
        musicState.albumHTML += '
'; //  closing tag card type

        if (counter === noOfColumns) {

            counter = 0;
            musicState.albumHTML += '
'; // closing tag row
        }
    });

    // render album page
    $('.js-album-view').html(musicState.albumHTML).fadeIn();
}

$(document).ready(function() {

    loadUserLocation();

});
<commit_msg>Correction of insecure call to freegeoip API<commit_after>"use strict";

$(function() {

    // handle log in event
    $('#sign-in').submit(function(event) {

        event.preventDefault();
        var user = $('#username').val();
        var discogsUsersEndpoint = 'https://api.discogs.com/users/' + user;

        // check username entered is a valid Discogs username
        var discogsPayLoad = checkDiscogsIsValid(user, discogsUsersEndpoint);

    });
});

// initialize error message, invoked upon click in input field[text]
function initializeError() {

    $('label').attr('data-error', ' ');
}

function loadUserLocation(discogsPayLoad) {

    // function to get location of user to use for jambase event lookup
    $.get('https://freegeoip.net/json/', function() {

    }).done(function(data) {

        var userLocation = {};
        userLocation.city = data.city;
        userLocation.country = data.country_name;
        renderInfoBox(userLocation, discogsPayLoad);

    }).fail(function(data) {

    }).always(function() {

    });
}

function checkDiscogsIsValid(user, discogsUsersEndpoint) {

    $.getJSON(discogsUsersEndpoint, function() {
        // set visibility of log-in box elements to none
        $('.sign-in-page').css('display', 'none');

    }).done(function(data) {

        var discogsPayLoad = new Object();
        discogsPayLoad.recordCount = data.num_collection;
        discogsPayLoad.forSaleCount = data.num_for_sale;
        discogsPayLoad.wantListCount = data.num_wantlist;
        discogsPayLoad.registered = data.registered;
        discogsPayLoad.username = data.username;
        discogsPayLoad.artists = [];

        if (discogsPayLoad.recordCount > 0) {
            // load Discogs collection of the user, page 1, limit 50, ascending sort by artist
            loadDiscogsReleases(discogsPayLoad, user, 1, 20, 'asc');

        } else {

            renderEmptyCollectionView();
        }

        return discogsPayLoad;

    }).fail(function(data) {

        if (data.responseJSON === undefined) {

            $('Label').attr('data-error', data.responseJSON.message);

        } else {

            $('Label').attr('data-error', data.responseJSON.message);

        }
        return false;

    }).always(function() {

    });
}

function loadDiscogsReleases(discogsPayLoad, user, page, limit, order) {

    var discogsCollectionEndpoint = 'https://api.discogs.com/users/' + user + '/collection/folders/0/releases?' + 'page=' + page + '&per_page=' + limit + '&sort=artist' + '&sort_order=' + order;

    // call Discogs collection/releases API
    $.getJSON(discogsCollectionEndpoint, function(data) {

    }).done(function(data) {

        var artistId = '';

        for (var i = data.releases.length - 1; i >= 0; i--) {

            for (var j = data.releases[i].basic_information.artists.length - 1; j >= 0; j--) {

                if (artistId != data.releases[i].basic_information.artists[j].id) {
                    artistId = data.releases[i].basic_information.artists[j].id;

                    if (artistObj != undefined) {

                        discogsPayLoad.artists.push(artistObj);
                        albumObj = {};
                    }

                    var artistObj = {};
                    artistObj.albums = [];
                    artistObj.members = [];

                    artistId = data.releases[i].basic_information.artists[j].id;
                    artistObj.artistid = data.releases[i].basic_information.artists[j].id;
                    artistObj.name = data.releases[i].basic_information.artists[j].name.replace(/\(\d\)/, ""); // remove parenthesis + number
                    artistObj.name = artistObj.name.replace(/\s+$/, ''); // remove trailing space
                    artistObj.url = data.releases[i].basic_information.artists[j].resource_url;
                }
            }

            var albumObj = {};
            albumObj.artistId = artistId;
            albumObj.title = data.releases[i].basic_information.title;
            albumObj.year = data.releases[i].basic_information.year;
            albumObj.format = data.releases[i].basic_information.formats[0].name;
            artistObj.albums.push(albumObj);

        }

        discogsPayLoad.artists.push(artistObj);

        enrichDiscogsArtists(discogsPayLoad);

    }).fail(function(data, success) {

        renderLoadingErrorView('Discogs', data);

    }).always(function() {

    });
}

function enrichDiscogsArtists(discogsPayLoad) {

    $.each(discogsPayLoad.artists, function(i, data) {

        $.getJSON(discogsPayLoad.artists[i].url, function(data) {

        }).done(function(data) {

            var artistObj = {};
            artistObj.members = [];

            discogsPayLoad.artists[i].profile = data.profile;

            var activeMembersCount = 0;
            for (var j = data.members.length - 1; j >= 0; j--) {

                if (data.members[j].active === true) {

                    var membersObj = {};
                    membersObj.name = data.members[j].name;
                    membersObj.active = data.members[j].active;
                    artistObj.members.push(membersObj);

                    activeMembersCount++;
                }

                if (activeMembersCount >= 6) {
                    break; // only want to show 6 active members
                }

            }

            discogsPayLoad.artists[i].members = artistObj.members;

            loadLastFMImages(discogsPayLoad);

        }).fail(function(data, success) {

            renderLoadingErrorView('Discogs', data);

        }).always(function() {

        });

    });
}

function loadLastFMImages(discogsPayLoad) {

    $.each(discogsPayLoad.artists, function(i, data) {

        var lastFMScrobber = 'https://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=' + discogsPayLoad.artists[i].name + '&api_key=a9ec7949488cffd19b50fc457a7731d1&format=json';
        debugger;
        $.getJSON(lastFMScrobber, function(data) {

        }).done(function(data) {

            var keys = Object.keys(data.artist.image);
            var result = {};

            for (var j = data.artist.image.length - 1; j >= 0; j--) {

                if (data.artist.image[j].size === 'large') {

                    var str = JSON.stringify(data.artist.image[j]);
                    str = str.replace('#text', 'text');
                    data.artist.image[j] = JSON.parse(str);
                    discogsPayLoad.artists[i].image = data.artist.image[j].text;
                }
            }

            renderArtistCards(discogsPayLoad);
            loadUserLocation(discogsPayLoad);

        }).fail(function(data, success) {

            renderLoadingErrorView('LastFM', data);

        }).always(function() {

        });

    });
}

function renderInfoBox(userLocation, discogsPayLoad) {

    var infoBoxHTML = '';

    infoBoxHTML += '

Location Information:

';
    infoBoxHTML += '
City: ' + userLocation.city + '
';
    infoBoxHTML += '
Country: ' + userLocation.country + '
';

    if (discogsPayLoad != undefined) {

        infoBoxHTML += '

Discogs Information:

';
        infoBoxHTML += '
Discogs user name: ' + discogsPayLoad.username + '
';
        infoBoxHTML += '
Registered On: ' + discogsPayLoad.registered + '
';
        infoBoxHTML += '
Collection count: ' + discogsPayLoad.recordCount + '
';
        infoBoxHTML += '
Want List count: ' + discogsPayLoad.wantListCount + '
';
        infoBoxHTML += '
For Sale count: ' + discogsPayLoad.forSaleCount + '
';
    }

    // render info box
    $('.js-info-box').html(infoBoxHTML).fadeIn();
}

function renderEmptyCollectionView() {

    var messageHTML = '

';

    messageHTML += '

Empty Collection
';
    messageHTML += '
No records are maintained in your Discogs collection
';
    messageHTML += '
and therefore nothing to show.

';

    // set visibility of main page element to none
    $('.js-main-page').css('display', 'none');
    // render empty collection message box
    $('.js-message-box').html(messageHTML).fadeIn();
    $('.js-message-box').css('visibility', 'visible');

}

function renderLoadingErrorView(api, data) {

    var messageHTML = '

';

    messageHTML += '

Load Error
';
    messageHTML += '
Unable to load all information since ' + api + ' API returned following error:
';

    if (data.status != 0) {
        messageHTML += '
HTTP code ' + data.status + ' - ' + data.statusText + '

';
    } else {
        messageHTML += '
HTTP code 429 (Too Many Requests) No Access-Control-Allow-Origin present

';
    }

    // set visibility of main page element to none
    $('.js-main-page').css('display', 'none');
    // render empty collection message box
    $('.js-message-box').html(messageHTML).fadeIn();
    $('.js-message-box').css('visibility', 'visible');

}

jQuery(function($) {
    var target = $('#target');

    $('.toggle-loading').click(function() {
        if (target.hasClass('loading')) {
            target.loadingOverlay('remove');
        } else {
            target.loadingOverlay();
        };
    });
});

function renderArtistCards(discogsPayLoad) {

    var artistHTML = '';
    var counter = 0;
    var noOfColumns = 4;

    // loop over Discogs data load and render page
    for (var i = discogsPayLoad.artists.length - 1; i >= 0; i--) {

        if (counter === 0) {

            artistHTML += '
';
        }

        counter++;
        artistHTML += '
';
        //artistHTML += '

' + discogsPayLoad.artists[i].name + '

';
        artistHTML += '
';
        artistHTML += '
';
        artistHTML += '

' + discogsPayLoad.artists[i].name + '

';

        if (discogsPayLoad.artists[i].image === '') {

            artistHTML += '';

        } else {

            artistHTML += '';
        }

        artistHTML += '
'; //  closing tag card image
        artistHTML += '
';
        artistHTML += '' + 'Members' + '' + 'more_vert' + '';

        if (discogsPayLoad.artists[i].members === undefined) {

            artistHTML += '
No active members found
';

        } else {

            artistHTML += '

';

            var memberCount = 0;
            for (var j = discogsPayLoad.artists[i].members.length - 1; j >= 0; j--) {

                if (memberCount === 0) { artistHTML += '
'; }
                memberCount++;
                artistHTML += '' + discogsPayLoad.artists[i].members[j].name + '	';
                if (memberCount === 2) {
                    artistHTML += '
';
                    memberCount = 0;
                }
            }

            var emptyMembers = 6 - discogsPayLoad.artists[i].members.length
            if (discogsPayLoad.artists[i].members.length === 0) {
                artistHTML += '

';
                artistHTML += '

';
                artistHTML += '

';
            } else if (discogsPayLoad.artists[i].members.length === 1 || discogsPayLoad.artists[i].members.length === 2) {
                artistHTML += '

';
                artistHTML += '

';
            } else if (discogsPayLoad.artists[i].members.length === 3 || discogsPayLoad.artists[i].members.length === 4) {
                artistHTML += '

';
            }

            artistHTML += '

';
        }

        artistHTML += '
'; //  closing tag card content
        artistHTML += '
';
        artistHTML += '' + 'Artist Profile' + 'close';
        artistHTML += '
' + discogsPayLoad.artists[i].profile + '
';
        artistHTML += '
'; //  closing tag card reveal
        artistHTML += '
';
        artistHTML += '
';
        artistHTML += '' + 'Live Events' + '';
        artistHTML += '
'; //  closing tag card action
        artistHTML += '
'; //  closing tag card stacked
        artistHTML += '
'; //  closing tag card type
        artistHTML += '
'; //  closing tag column

        if (counter === noOfColumns) {

            counter = 0;
            artistHTML += '
'; // closing tag row
        }
    }

    // render artist cards
    $('.js-main-view').html(artistHTML).fadeIn();
}

function renderAlbumView(response, noOfColumns) {

    var counter = 0;
    $.each(response, function(index, value) {

        if (counter === 0) {

            musicState.albumHTML += '
';
        }

        counter++;
        musicState.albumHTML += '
';
        musicState.albumHTML += '
';
        musicState.albumHTML += '<div class="card-image
';
        musicState.albumHTML += '
';
        musicState.albumHTML += '
';
        musicState.albumHTML += '' + value.basic_information.title + 'more_vert';
        musicState.albumHTML += '
' + 'Year' + '
';
        musicState.albumHTML += '

' + value.basic_information.year + '

';
        musicState.albumHTML += '
' + 'Format' + '
';
        musicState.albumHTML += '

' + value.basic_information.formats[0].name + '

';
        musicState.albumHTML += '
';
        musicState.albumHTML += 'Card Titleclose'
        musicState.albumHTML += '
Here is some more information about this product that is only revealed once clicked on.
'
        musicState.albumHTML += '
';
        musicState.albumHTML += '
'; //  closing tag card type

        if (counter === noOfColumns) {

            counter = 0;
            musicState.albumHTML += '
'; // closing tag row
        }
    });

    // render album page
    $('.js-album-view').html(musicState.albumHTML).fadeIn();
}

$(document).ready(function() {

    loadUserLocation();

});
<|endoftext|>


<commit_before>var folded = new OriDomi('.paper', {
  speed:           2000,
  ripple:          4,     // backwards ripple effect when animating
  perspective:     4000,   // smaller values exaggerate 3D distortion
  maxAngle:        180,    //fold range
  vPanels:         12,
  hPanels:         1,
  shading:         'soft',
  touchEnabled:    true,
  touchSensitivity: .10

});

//weird effects - comment/uncomment/switch orders/change values for MAXIMUM FUN

folded.stairs(43);

<commit_msg>com mudanca de lado na animacao<commit_after>var folded = new OriDomi('.paper', {
  speed:           3000,
  ripple:          4,     // backwards ripple effect when animating
  perspective:     4000,   // smaller values exaggerate 3D distortion
  maxAngle:        180,    //fold range
  vPanels:         12,
  hPanels:         1,
  shading:         'soft',
  touchEnabled:    true,
  touchSensitivity: .10

});

//weird effects - comment/uncomment/switch orders/change values for MAXIMUM FUN

folded.stairs(43).wait(2000).stairs(44, 'right');

<|endoftext|>