<commit_before>'use strict';

var fs                  = require ('fs');
var mongoose            = require ('mongoose');
var Project             = require ('../controllers/project.controller');
var Model               = mongoose.model ('Project');
var Phase               = mongoose.model ('Phase');
var Organization        = mongoose.model ('Organization');
var CSVParse            = require ('csv-parse');

// -------------------------------------------------------------------------
//
// This does a whole complicated mess of crap in loading up projects, should
// probably be in its own controller as it doesnt really follow the usual
// patterns, but it may also only be required for a short time, so its fine
// here for now.
//
// -------------------------------------------------------------------------
module.exports = function(file, req, res) {
	return new Promise (function (resolve, reject) {
		var params = req.url.split("/");
		var projectType = params[params.length-1]; // Last param is project type
		// console.log("projectType:",params[params.length-1]);
		// Now parse and go through this thing.
		fs.readFile(file.path, 'utf8', function(err, data) {
			if (err) {
				reject("err:"+err);
			}
			// console.log("FILE DATA:",data);
			var colArray = "";
			if (projectType === "eao") {
				colArray = ['id','Stream','ProjectName','Proponent','Region','description','locSpatial','locDescription','provincialED','federalED','investment','projectCreateDate','projectDescriptionLivingData','projectNotes','projectURL','investmentNotes','lat','long','constructionjobs','constructionjobsNotes','operatingjobs','operatingjobsNotes','projectType','sector','currentPhaseTypeActivity','eaActive','CEAAInvolvement','eaIssues','eaNotes','responsibleEPD','phoneEPD','emailEPD','projectLead','projectLeadPhone','projectLeadEmail','projectAnalyst','projectAssistant','administrativeAssistant','CELead','CELeadPhone','CELeadEmail','teamNotes'];
			} else {
				colArray = ['id','ProjectName','Proponent','Ownership','lat','long','Status','Commodity','Region','TailingsImpoundments','description'];
			}
			var parse = new CSVParse(data, {delimiter: ',', columns: colArray}, function(err, output){
				// Skip this many rows
				var length = Object.keys(output).length;
				var projectProcessed = 0;
				// console.log("length",length);
				Object.keys(output).forEach(function(key, index) {
					if (index > 0) {
						var row = output[key];
						projectProcessed++;
						// Hack for incoming table data
						var id = 0;
						if (!isNaN(row.id)) {
							id = parseInt(row.id);
						}
						var query = {epicProjectID: id};
						if (projectType === "mem") {
							query = {memPermitID: row.id};
						} else {
							query = {epicProjectID: parseInt(row.id)};
						}
						Model.findOne(query, function (err, doc) {
							var addOrChangeModel = function(model) {
								// Always do this
								model.name			= row.ProjectName;
								model.code 			= model.name.toLowerCase ().replace(/\//g,'-').replace (' ', '-').substr (0, model.name.length+1);
								var addOrChangeProp = function(prop) {
									// Sometimes mem Props are NULL
									// console.log(row.Proponent);
									if (row.Proponent === "") {
										row.Proponent = "N/A";
										prop.code = model.code;
									} else {
										prop.code = row.Proponent.toLowerCase().replace(/\//g,'-').match(/\b(\w)/g).join('');
									}
									prop.name 		= row.Proponent;
									prop.company	= row.Proponent;
									prop.address1 	= "";
									prop.city 		= "";
									prop.province 	= "";
									prop.postal 	= "";
									prop.save().then(function (org) {
										model.proponent = org;
										model.save();
											// console.log("saved",org);
											// console.log("model",model);
										});
								};
								Organization.findOne ({name:row.Proponent}, function (err, result) {
									if (result) {
										addOrChangeProp(result);
									} else {
										addOrChangeProp(new Organization());
									}
								});
								model.region 	  = row.Region.toLowerCase ().replace(' region','');
								// console.log("region:",model.region);
								model.description = row.description;

								if (row.lat) model.lat = parseFloat(row.lat);
								// Force negative because of import data
								if (row.long) model.lon = -Math.abs(parseFloat(row.long));

								// eao/mem specific
								if (projectType === "mem") {
									model.status = 'In Progress';
									// model.status = row.status;
									model.memPermitID = row.id; // We'll take what it is
									model.ownership = row.Ownership;
									model.commodity = row.Commodity;
									model.tailingsImpoundments = row.TailingsImpoundments;
									model.roles = ['mem', 'public'];
									model.read = ['public'];
									model.submit = ['mem'];
									model.type = "Mining";
									Phase.findOne ({name:row.Status}, function (err, result) {
										if (result) {
											model.phases = result._id;
											model.currentPhase = model.phases[0];
										}
									}).then(function (m) {
										model.save().then(function () {
											// Am I done processing?
											// console.log("INDEX:",index);
											if (index === length-1) {
												// console.log("processed: ",projectProcessed);
												resolve("{done: true, rowsProcessed: "+projectProcessed+"}");
											}
										});
									});
								} else { // eao
									// TODO: FIX
									model.status = 'In Progress';
									var pstatus = model.status;
									model.epicProjectID = id;

									if (row.locSpatial) model.locSpatial 	 = row.locSpatial;
									if (row.locDescription) model.location 	 = row.locDescription;
									if (row.provincialED) model.provElecDist = row.provincialED;
									if (row.federalED) model.fedElecDist 	 = row.federalED;

									//projectCreateDate
									if (row.projectNotes) model.projectNotes = row.projectNotes;

									model.intake.constructionjobs 		= row.constructionjobs;
									model.intake.constructionjobsNotes 	= row.constructionjobsNotes;
									model.intake.operatingjobs 			= row.operatingjobs;
									model.intake.operatingjobsNotes 	= row.operatingjobsNotes;
									model.intake.investment 			= row.investment;
									model.intake.investmentNotes 		= row.investmentNotes;

									model.type = row.projectType;
									model.sector = row.sector;
									if (row.eaActive) model.eaActive = row.eaActive;
									if (row.CEAAInvolvement) model.CEAAInvolvement = row.CEAAInvolvement;
									if (row.eaIssues) model.eaIssues = row.eaIssues;
									if (row.eaNotes) model.eaNotes = row.eaNotes;

									// The rest comes in as old data for now
									// model.stream 					= row.Stream;
									model.responsibleEPD 			= row.responsibleEPD;
									model.responsibleEPDPhone		= row.phoneEPD;
									model.responsibleEPDEmail 		= row.emailEPD;
									model.projectLead 				= row.projectLead;
									model.projectLeadPhone			= row.projectLeadPhone;
									model.projectLeadEmail 			= row.projectLeadEmail;
									model.projectAnalyst 			= row.projectAnalyst;
									model.projectAssistant 			= row.projectAssistant;
									model.administrativeAssistant 	= row.administrativeAssistant;
									model.CELead 					= row.CELead;
									model.CELeadPhone				= row.CELeadPhone;
									model.CELeadEmail				= row.CELeadEmail;
									model.teamNotes 				= row.teamNotes;
									model.phases = [];
									model.roles = ['eao', 'public'];
									model.read = ['public'];
									model.submit = ['eao'];
									var pname = ((row.currentPhaseTypeActivity === "") ? "not set":row.currentPhaseTypeActivity);
									var pdesc = ((row.currentPhaseTypeActivity === "") ? "not set":row.currentPhaseTypeActivity);
									var pcode = pname.toLowerCase ().replace(/\//g,'-').replace (' ', '-').substr (0, model.name.length+1);
									var phase = new Phase ({read: ['public'], submit: ['eao'], status : pstatus, code : pcode, name : pname, description : pdesc});
									model.phases.push (phase._id);
									phase.save().then(function() {
										model.currentPhase = model.phases[0];
										model.save().then(function () {
											// Am I done processing?
											// console.log("INDEX:",index);
											if (index === length-1) {
												// console.log("processed: ",projectProcessed);
												resolve("{done: true, rowsProcessed: "+projectProcessed+"}");
											}
										});
									});
								}
							};
							if (doc === null) {
								// Create new
								//var p = new Project (req.user);
								//p.new().then(addOrChangeModel);
								addOrChangeModel(new Model());
							} else {
								// Update:
								addOrChangeModel(doc);
							}
						});
					}
				}); // ObjectForKey
			}); // CSV Parse
		}); // Read File
	});
};

<commit_msg>ESM-98: Fix for importing, publish documents<commit_after>'use strict';

var fs                  = require ('fs');
var mongoose            = require ('mongoose');
var Project             = require ('../controllers/project.controller');
var Model               = mongoose.model ('Project');
var Phase               = mongoose.model ('Phase');
var Organization        = mongoose.model ('Organization');
var CSVParse            = require ('csv-parse');

// -------------------------------------------------------------------------
//
// This does a whole complicated mess of crap in loading up projects, should
// probably be in its own controller as it doesnt really follow the usual
// patterns, but it may also only be required for a short time, so its fine
// here for now.
//
// -------------------------------------------------------------------------
module.exports = function(file, req, res) {
	return new Promise (function (resolve, reject) {
		var params = req.url.split("/");
		var projectType = params[params.length-1]; // Last param is project type
		// console.log("projectType:",params[params.length-1]);
		// Now parse and go through this thing.
		fs.readFile(file.path, 'utf8', function(err, data) {
			if (err) {
				reject("err:"+err);
			}
			// console.log("FILE DATA:",data);
			var colArray = "";
			if (projectType === "eao") {
				colArray = ['id','Stream','ProjectName','Proponent','Region','description','locSpatial','locDescription','provincialED','federalED','investment','projectCreateDate','projectDescriptionLivingData','projectNotes','projectURL','investmentNotes','lat','long','constructionjobs','constructionjobsNotes','operatingjobs','operatingjobsNotes','projectType','sector','currentPhaseTypeActivity','eaActive','CEAAInvolvement','eaIssues','eaNotes','responsibleEPD','phoneEPD','emailEPD','projectLead','projectLeadPhone','projectLeadEmail','projectAnalyst','projectAssistant','administrativeAssistant','CELead','CELeadPhone','CELeadEmail','teamNotes'];
			} else {
				colArray = ['id','ProjectName','Proponent','Ownership','lat','long','Status','Commodity','Region','TailingsImpoundments','description'];
			}
			var parse = new CSVParse(data, {delimiter: ',', columns: colArray}, function(err, output){
				// Skip this many rows
				var length = Object.keys(output).length;
				var projectProcessed = 0;
				// console.log("length",length);
				Object.keys(output).forEach(function(key, index) {
					if (index > 0) {
						var row = output[key];
						projectProcessed++;
						// Hack for incoming table data
						var id = 0;
						if (!isNaN(row.id)) {
							id = parseInt(row.id);
						}
						var query = {epicProjectID: id};
						if (projectType === "mem") {
							query = {memPermitID: row.id};
						} else {
							query = {epicProjectID: parseInt(row.id)};
						}
						Model.findOne(query, function (err, doc) {
							var addOrChangeModel = function(model) {
								// Always do this
								model.name			= row.ProjectName;
								model.code 			= model.name.toLowerCase ().replace(/\//g,'-').replace (' ', '-').substr (0, model.name.length+1);
								var addOrChangeProp = function(prop) {
									// Sometimes mem Props are NULL
									// console.log(row.Proponent);
									if (row.Proponent === "") {
										row.Proponent = "N/A";
										prop.code = model.code;
									} else {
										prop.code = row.Proponent.toLowerCase().replace(/\//g,'-').match(/\b(\w)/g).join('');
									}
									prop.name 		= row.Proponent;
									prop.company	= row.Proponent;
									prop.address1 	= "";
									prop.city 		= "";
									prop.province 	= "";
									prop.postal 	= "";
									prop.save().then(function (org) {
										model.proponent = org;
										model.save();
											// console.log("saved",org);
											// console.log("model",model);
										});
								};
								Organization.findOne ({name:row.Proponent}, function (err, result) {
									if (result) {
										addOrChangeProp(result);
									} else {
										addOrChangeProp(new Organization());
									}
								});
								model.region 	  = row.Region.toLowerCase ().replace(' region','');
								// console.log("region:",model.region);
								model.description = row.description;

								if (row.lat) model.lat = parseFloat(row.lat);
								// Force negative because of import data
								if (row.long) model.lon = -Math.abs(parseFloat(row.long));

								// eao/mem specific
								if (projectType === "mem") {
									model.status = 'In Progress';
									// model.status = row.status;
									model.memPermitID = row.id; // We'll take what it is
									model.ownership = row.Ownership;
									model.commodity = row.Commodity;
									model.tailingsImpoundments = row.TailingsImpoundments;
									model.roles = ['mem', 'public'];
									model.read = ['public'];
									model.submit = ['mem'];
									model.type = "Mining";
									Phase.findOne ({name:row.Status}, function (err, result) {
										if (result) {
											model.phases = result._id;
											model.currentPhase = model.phases[0];
										}
									}).then(function (m) {
										model.save().then(function () {
											// Am I done processing?
											// console.log("INDEX:",index);
											if (index === length-1) {
												// console.log("processed: ",projectProcessed);
												resolve("{done: true, rowsProcessed: "+projectProcessed+"}");
											}
										});
									});
								} else { // eao
									// TODO: FIX
									model.status = 'In Progress';
									var pstatus = model.status;
									model.epicProjectID = id;

									if (row.locSpatial) model.locSpatial 	 = row.locSpatial;
									if (row.locDescription) model.location 	 = row.locDescription;
									if (row.provincialED) model.provElecDist = row.provincialED;
									if (row.federalED) model.fedElecDist 	 = row.federalED;

									//projectCreateDate
									if (row.projectNotes) model.projectNotes = row.projectNotes;

									model.intake.constructionjobs 		= row.constructionjobs;
									model.intake.constructionjobsNotes 	= row.constructionjobsNotes;
									model.intake.operatingjobs 			= row.operatingjobs;
									model.intake.operatingjobsNotes 	= row.operatingjobsNotes;
									model.intake.investment 			= row.investment;
									model.intake.investmentNotes 		= row.investmentNotes;

									model.type = row.projectType;
									model.sector = row.sector;
									if (row.eaActive) model.eaActive = row.eaActive;
									if (row.CEAAInvolvement) model.CEAAInvolvement = row.CEAAInvolvement;
									if (row.eaIssues) model.eaIssues = row.eaIssues;
									if (row.eaNotes) model.eaNotes = row.eaNotes;

									// The rest comes in as old data for now
									// model.stream 					= row.Stream;
									model.responsibleEPD 			= row.responsibleEPD;
									model.responsibleEPDPhone		= row.phoneEPD;
									model.responsibleEPDEmail 		= row.emailEPD;
									model.projectLead 				= row.projectLead;
									model.projectLeadPhone			= row.projectLeadPhone;
									model.projectLeadEmail 			= row.projectLeadEmail;
									model.projectAnalyst 			= row.projectAnalyst;
									model.projectAssistant 			= row.projectAssistant;
									model.administrativeAssistant 	= row.administrativeAssistant;
									model.CELead 					= row.CELead;
									model.CELeadPhone				= row.CELeadPhone;
									model.CELeadEmail				= row.CELeadEmail;
									model.teamNotes 				= row.teamNotes;
									model.phases = [];
									model.roles = ['eao', 'public'];
									model.read = ['public'];
									model.submit = ['eao'];
									model.publish();
									var pname = ((row.currentPhaseTypeActivity === "") ? "not set":row.currentPhaseTypeActivity);
									var pdesc = ((row.currentPhaseTypeActivity === "") ? "not set":row.currentPhaseTypeActivity);
									var pcode = pname.toLowerCase ().replace(/\//g,'-').replace (' ', '-').substr (0, model.name.length+1);
									var phase = new Phase ({read: ['public'], submit: ['eao'], status : pstatus, code : pcode, name : pname, description : pdesc});
									model.phases.push (phase._id);
									phase.save().then(function() {
										model.currentPhase = model.phases[0];
										model.save().then(function () {
											// Am I done processing?
											// console.log("INDEX:",index);
											if (index === length-1) {
												// console.log("processed: ",projectProcessed);
												resolve("{done: true, rowsProcessed: "+projectProcessed+"}");
											}
										});
									});
								}
							};
							if (doc === null) {
								// Create new
								//var p = new Project (req.user);
								//p.new().then(addOrChangeModel);
								addOrChangeModel(new Model());
							} else {
								// Update:
								addOrChangeModel(doc);
							}
						});
					}
				}); // ObjectForKey
			}); // CSV Parse
		}); // Read File
	});
};

<|endoftext|>


<commit_before>MainController.$inject = ['$scope', '$log', 'trace'];
function MainController($scope, $log, trace) {
  $log.log('MainCtrl', arguments);

  $scope.count = 0;

  function increment() {
    trace(arguments);
    // Increment counter
    ++$scope.count;
  }
  this.increment = increment;
}

ng.module('velocity.common');
  .controller('MainController', MainController);
<commit_msg>Correction d'une erreur de synthaxe<commit_after>MainController.$inject = ['$scope', '$log', 'trace'];
function MainController($scope, $log, trace) {
  $log.log('MainCtrl', arguments);

  $scope.count = 0;

  function increment() {
    trace(arguments);
    // Increment counter
    ++$scope.count;
  }
  this.increment = increment;
}

ng.module('velocity.common')
  .controller('MainController', MainController);
<|endoftext|>


<commit_before>$(document).ready(function() {
  $(".animsition").animsition({
    inClass: 'fade-in',
    outClass: 'fade-out',
    inDuration: 1500,
    outDuration: 800,
    linkElement: '.animsition-link',
    // e.g. linkElement: 'a:not([target="_blank"]):not([href^="#"])'
    loading: true,
    loadingParentElement: 'body', //animsition wrapper element
    loadingClass: 'animsition-loading',
    loadingInner: '', // e.g '<img src="loading.svg" />'
    timeout: false,
    timeoutCountdown: 5000,
    onLoadEvent: true,
    browser: [ 'animation-duration', '-webkit-animation-duration'],
    // "browser" option allows you to disable the "animsition" in case the css property in the array is not supported by your browser.
    // The default setting is to disable the "animsition" in a browser that does not support "animation-duration".
    overlay : false,
    overlayClass : 'animsition-overlay-slide',
    overlayParentElement : 'body',
    transition: function(url){ window.location.href = url; }
  });
});<commit_msg>deleted unecessary files<commit_after><|endoftext|>


<commit_before>'use strict';

angular.module('drupalService', ['ngResource'])

    .factory('Node', ['SERVER', '$resource', function (SERVER, $resource) {
        return $resource('/node/:nid', {nid: '@nid'}, {

            query: {
                method: 'GET',
                url: SERVER.URL + '/node',
                isArray: true,
                transformRequest: function (data, headersGetter) {
                    headersGetter().Accept = 'application/hal+json';
                    return angular.toJson(data);
                },
                transformResponse: function (data, headersGetter) {
                    var json = angular.fromJson(data);
                    angular.forEach(json, function (node, index) {
                        // TODO: DRY aka move 'internals' into function/factory
                        var internals = node._internals = {};

                        // Inject the nid (last element from href
                        var nid = node._links.self.href.split(/\//).pop();
                        internals.nid = [{value: nid, _drupal: 'https://www.drupal.org/node/2304849'}];

                        // Transform _links into node fields
                        angular.forEach(node._links, function (value, key) {
                            if (key === 'self') {
                              return;
                            }
                            if (key === 'type') {
                              return;
                            }
                            var id = key.split(/\//).pop();
                            internals[id] = [];
                            angular.forEach(value, function (val, index) {
                                internals[id].push({ target_id: val.href.split(/\//).pop()});
                            });
                        });
                    });
                    return json;
                }
            },
            fetch: {
                method: 'GET',
                url: SERVER.URL + '/node/:nid',
                transformRequest: function (data, headersGetter) {
                    headersGetter().Accept = 'application/hal+json';
                    return angular.toJson(data);
                },
                transformResponse: function (data, headersGetter) {
                    var node = angular.fromJson(data);
                    // TODO: DRY aka move 'internals' into function/factory
                    var internals = node._internals = {};

                    // Inject the nid (last element from href
                    var nid = node._links.self.href.split(/\//).pop();
                    internals.nid = [{value: nid, _drupal: 'https://www.drupal.org/node/2304849'}];

                    // Transform _links into node fields
                    angular.forEach(node._links, function (value, key) {
                        if (key === 'self') {
                          return;
                        }
                        if (key === 'type') {
                          return;
                        }
                        var id = key.split(/\//).pop();
                        internals[id] = [];
                        angular.forEach(value, function (val, index) {
                            internals[id].push({ target_id: val.href.split(/\//).pop()});
                        });
                    });

                    return node;
                }

            },

            patch: {
                method: 'PATCH',
                url: SERVER.URL + '/node/:nid',
                transformRequest: function (data, headersGetter) {
                    console.log('transformRequest', data);
                    delete data._internals;
                    headersGetter()['Content-Type'] = 'application/hal+json';
                    return angular.toJson(data);
                }
            },

            create: {
                method: 'POST',
                url: SERVER.URL + '/entity/node',
                transformRequest: function (data, headersGetter) {
                    delete data._internals;
                    headersGetter()['Content-Type'] = 'application/hal+json';
                    headersGetter()['Accept'] = 'application/json';
                    return angular.toJson(data);
                },
                transformResponse: function (data, headersGetter) {
                    console.log('transformResponse', data);
                }
            }
        });
    }])

    .factory('NodeByTerm', ['SERVER', '$resource', function (SERVER, $resource) {
        return $resource(SERVER.URL + '/taxonomy/term/:tid', {tid: '@tid'}, {});
    }])

    .factory('TaxonomyTerm', ['SERVER', '$resource', function (SERVER, $resource) {
        return $resource(SERVER.URL + '/taxonomy/list/:tid', {tid: '@tid'}, {});
    }])

    .factory('User', ['SERVER', '$resource', function (SERVER, $resource) {
        return $resource(SERVER.URL + '/user/:uid', {uid: '@uid'}, {});
    }])

    .factory('Comment', ['SERVER', '$resource', function (SERVER, $resource) {
        return $resource(SERVER.URL + '/node/:nid/comments', {nid: '@nid'}, {
            'post': {
                method: 'POST',
                url: '/entity/comment',
                transformRequest: function (data, headersGetter) {
                    headersGetter().Accept = 'application/hal+json';
                    headersGetter()['Content-Type'] = 'application/hal+json';
                }
            }
        });
    }]);
<commit_msg>Remove DRY _internals.<commit_after>'use strict';

var mod = angular.module('drupalService', ['ngResource']);

mod.hal = {
    fromServer: function (hal) {
        var internals = hal._internals = {};

        // Inject the nid (last element from href
        var nid = hal._links.self.href.split(/\//).pop();
        internals.nid = [{value: nid, _drupal: 'https://www.drupal.org/node/2304849'}];

        // Transform _links into node fields
        angular.forEach(hal._links, function (value, key) {
            if (key === 'self') {
                return;
            }
            if (key === 'type') {
                return;
            }
            var id = key.split(/\//).pop();
            internals[id] = [];
            angular.forEach(value, function (val, index) {
                internals[id].push({target_id: val.href.split(/\//).pop()});
            });
        });

    },
    toServer: function (hal) {
        delete hal._internals;
    }
};

mod
    .factory('Node', ['SERVER', '$resource', function (SERVER, $resource) {
        return $resource('/node/:nid', {nid: '@nid'}, {

            query: {
                method: 'GET',
                url: SERVER.URL + '/node',
                isArray: true,
                transformRequest: function (data, headersGetter) {
                    headersGetter().Accept = 'application/hal+json';
                    return angular.toJson(data);
                },
                transformResponse: function (data, headersGetter) {
                    var json = angular.fromJson(data);
                    angular.forEach(json, function (node, index) {
                        mod.hal.fromServer(node);
                    });
                    return json;
                }
            },
            fetch: {
                method: 'GET',
                url: SERVER.URL + '/node/:nid',
                transformRequest: function (data, headersGetter) {
                    headersGetter().Accept = 'application/hal+json';
                    return angular.toJson(data);
                },
                transformResponse: function (data, headersGetter) {
                    var node = angular.fromJson(data);
                    mod.hal.fromServer(node);
                    return node;
                }

            },

            patch: {
                method: 'PATCH',
                url: SERVER.URL + '/node/:nid',
                transformRequest: function (data, headersGetter) {
                    console.log('transformRequest', data);
                    mod.hal.toServer(data);
                    headersGetter()['Content-Type'] = 'application/hal+json';
                    return angular.toJson(data);
                }
            },

            create: {
                method: 'POST',
                url: SERVER.URL + '/entity/node',
                transformRequest: function (data, headersGetter) {
                    mod.hal.toServer(data);
                    headersGetter()['Content-Type'] = 'application/hal+json';
                    headersGetter()['Accept'] = 'application/json';
                    return angular.toJson(data);
                },
                transformResponse: function (data, headersGetter) {
                    console.log('transformResponse', data);
                }
            }
        });
    }])

    .factory('NodeByTerm', ['SERVER', '$resource', function (SERVER, $resource) {
        return $resource(SERVER.URL + '/taxonomy/term/:tid', {tid: '@tid'}, {});
    }])

    .factory('TaxonomyTerm', ['SERVER', '$resource', function (SERVER, $resource) {
        return $resource(SERVER.URL + '/taxonomy/list/:tid', {tid: '@tid'}, {});
    }])

    .factory('User', ['SERVER', '$resource', function (SERVER, $resource) {
        return $resource(SERVER.URL + '/user/:uid', {uid: '@uid'}, {});
    }])

    .factory('Comment', ['SERVER', '$resource', function (SERVER, $resource) {
        return $resource(SERVER.URL + '/node/:nid/comments', {nid: '@nid'}, {
            'post': {
                method: 'POST',
                url: '/entity/comment',
                transformRequest: function (data, headersGetter) {
                    headersGetter().Accept = 'application/hal+json';
                    headersGetter()['Content-Type'] = 'application/hal+json';
                }
            }
        });
    }]);
<|endoftext|>


<commit_before>
var formist = require('formist');

module.exports = function (attrs) {

    function checkboxesWidthAdditionWidget (name, field, value) {

        var o = {
                attributes : { autocomplete: 'off' },
                label: {
                    label: field.label,
                    attributes: {
                        'class': 'col-sm-2 control-label'
                    }
                }
            },
            elements = [];

        // add the helpText
        if (field.helpText) {
            o.helpText = {
                text: field.helpText,
                attributes: {
                    'class': 'col-sm-offset-2 col-sm-10 help-block'
                }
            };
        }

        // add the value if there is one
        if (value !== undefined && value !== null) {

            o.attributes.value = value;

            if (value.length > 0) {
                // overwrite the default list with value
                field.list = value;
            }

        }

        // is it required?
        if (field.required === true) {
            o.attributes.required = true;
        }

        // create each element
        (field.list || []).forEach(function (f) {

            if (typeof f === 'string') {
                f = {
                    label: f,
                    value: f
                };
            }

            var el = new formist.Field('input', {
                label: f.label,
                attributes: {
                    type: 'checkbox',
                    name: name,
                    value: f.value,
                    'data-linz-conflict-handler': 'checkboxesWithAdditionConflictHandler'
                },
                theme: {
                    field: function (label, content, helpText, field) {

                        // we want to append to the attributes, so default if it wasn't passed in
                        return '
' + content + ' ' + field.options.label.label + '
';

                    },
                    control: function (content) {
                        return content;
                    }
                }
            });

            if ((value || '').indexOf(f.value) >= 0) {
                el.attribute('checked', true);
            }

            if (field.disabled === true) {
                el.attribute('disabled', true);
            }

            if (field.required === true) {
                el.attribute('required', true);
                el.attribute('data-bv-notempty-message', 'Please choose one or more options');
            }

            // allow override on any attributes, through the attr argument
            for (attribute in attrs) {
                el.attribute(attribute, attrs[attribute]);
            }

            elements.push(el);

        });

        // Include button to add extra value to list
        var el = new formist.Field('input', {
            label: 'others',
            attributes: {
                type: 'checkbox',
                name: name,
                value: '',
                checked: true,
                disabled: true
            },
            theme: {
                field: function (label, content, helpText, field) {
                    var html = '

'
                                    + '<template>

' + content + ' ' + field.options.label.label + '

</template>'
                                    + '<input type="text" class="form-control input-sm" name="add-checkbox">'
                                    + '<button class="btn btn-default btn-sm" type="button" data-linz-control="add-checkbox"></button>'
                                + '

';
                    return html;

                },
                control: function (content) {
                    return content;
                }
            }
        });

        elements.push(el);

        return new formist.Fieldgroup(o, elements);

    };

    return checkboxesWidthAdditionWidget;

};
<commit_msg>fix checkbox with addition xss<commit_after>'use strict';

const formist = require('formist');
const linz = require('../../../');

module.exports = function (attrs) {

    function checkboxesWidthAdditionWidget (name, field, value) {

        var o = {
                attributes : { autocomplete: 'off' },
                label: {
                    label: field.label,
                    attributes: {
                        'class': 'col-sm-2 control-label'
                    }
                }
            },
            elements = [];

        // add the helpText
        if (field.helpText) {
            o.helpText = {
                text: field.helpText,
                attributes: {
                    'class': 'col-sm-offset-2 col-sm-10 help-block'
                }
            };
        }

        // add the value if there is one
        if (value !== undefined && value !== null) {

            o.attributes.value = value;

            if (value.length > 0) {
                // overwrite the default list with value
                field.list = value;
            }

        }

        // is it required?
        if (field.required === true) {
            o.attributes.required = true;
        }

        // create each element
        (field.list || []).forEach(function (f) {

            if (typeof f === 'string') {
                f = {
                    label: linz.api.util.escape(f),
                    value: f
                };
            }

            var el = new formist.Field('input', {
                label: f.label,
                attributes: {
                    type: 'checkbox',
                    name: name,
                    value: f.value,
                    'data-linz-conflict-handler': 'checkboxesWithAdditionConflictHandler'
                },
                theme: {
                    field: function (label, content, helpText, field) {

                        // we want to append to the attributes, so default if it wasn't passed in
                        return '
' + content + ' ' + field.options.label.label + '
';

                    },
                    control: function (content) {
                        return content;
                    }
                }
            });

            if ((value || '').indexOf(f.value) >= 0) {
                el.attribute('checked', true);
            }

            if (field.disabled === true) {
                el.attribute('disabled', true);
            }

            if (field.required === true) {
                el.attribute('required', true);
                el.attribute('data-bv-notempty-message', 'Please choose one or more options');
            }

            // allow override on any attributes, through the attr argument
            for (attribute in attrs) {
                el.attribute(attribute, attrs[attribute]);
            }

            elements.push(el);

        });

        // Include button to add extra value to list
        var el = new formist.Field('input', {
            label: 'others',
            attributes: {
                type: 'checkbox',
                name: name,
                value: '',
                checked: true,
                disabled: true
            },
            theme: {
                field: function (label, content, helpText, field) {
                    var html = '

'
                                    + '<template>

' + content + ' ' + field.options.label.label + '

</template>'
                                    + '<input type="text" class="form-control input-sm" name="add-checkbox">'
                                    + '<button class="btn btn-default btn-sm" type="button" data-linz-control="add-checkbox"></button>'
                                + '

';
                    return html;

                },
                control: function (content) {
                    return content;
                }
            }
        });

        elements.push(el);

        return new formist.Fieldgroup(o, elements);

    };

    return checkboxesWidthAdditionWidget;

};
<|endoftext|>


<commit_before>$(document).ready(init);

var page = 0;
function init() {
    getUsers(page);
    $('#prev').click(function() {
        page -= 1;
        getUsers(page)
    });
    $('#reload').click(function() {
        $('
').html('');
        getUsers(page);
    });
    $('#next').click(function() {
        page += 1;
        getUsers(page);
    });
}

function getUsers(page) {
    $.ajax({
        url: '/api/migrate_users/' + page,
        statusCode: {
            200: function(data) {
                $('#info').text(data.migrated_users + '/' + data.total_users + ' migrated users');
                if (data.users === undefined || data.users === null) {
                    alert('Could not find users');
                    return;
                }
                $.each(data.users, function(index, user) {
                    var $user = $('
'),
                        $title = $('
')
                            .text(user.id + ' - ' + user.displayName),
                        $migrate = $('<button>')
                            .text('Migrate playlists')
                            .click(function() {
                                $.ajax({
                                    url: '/api/migrate_users/' + user.id,
                                    type: 'POST',
                                    data: null,
                                    statusCode: {
                                        200: function(data) {
                                            $user.addClass('migrated');
                                            $migrate.attr('disabled', true);
                                        },
                                        404: function(data) {
                                            $user.addClass('error');
                                        },
                                        302: function(data) {
                                            alert('Log in as admin');
                                        }
                                    }
                                });
                            });
                    $title.appendTo($user);
                    $migrate.appendTo($user);
                    $user.appendTo('#users');
                });
            },
            302: function(data) {
                alert('Log in as admin');
            }
        }
    });
};
<commit_msg>Minor bug fix in migrate users<commit_after>$(document).ready(init);

var page = 0;
function init() {
    getUsers(page);
    $('#prev').click(function() {
        page -= 1;
        getUsers(page)
    });
    $('#reload').click(function() {
        $('
').html('');
        getUsers(page);
    });
    $('#next').click(function() {
        page += 1;
        getUsers(page);
    });
}

function getUsers(page) {
    $.ajax({
        url: '/api/migrate_users/' + page,
        statusCode: {
            200: function(data) {
                $('#info').text(data.migrated_users + '/' + data.total_users + ' migrated users');
                $('#users').html('');
                if (data.users === undefined || data.users === null) {
                    alert('Could not find users');
                    return;
                }
                $.each(data.users, function(index, user) {
                    var $user = $('
'),
                        $title = $('
')
                            .text(user.id + ' - ' + user.displayName),
                        $migrate = $('<button>')
                            .text('Migrate playlists')
                            .click(function() {
                                $.ajax({
                                    url: '/api/migrate_users/' + user.id,
                                    type: 'POST',
                                    data: null,
                                    statusCode: {
                                        200: function(data) {
                                            $user.addClass('migrated');
                                            $migrate.attr('disabled', true);
                                        },
                                        404: function(data) {
                                            $user.addClass('error');
                                        },
                                        302: function(data) {
                                            alert('Log in as admin');
                                        }
                                    }
                                });
                            });
                    $title.appendTo($user);
                    $migrate.appendTo($user);
                    $user.appendTo('#users');
                });
            },
            302: function(data) {
                alert('Log in as admin');
            }
        }
    });
};
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import { View, Text, StyleSheet, TouchableHighlight, ListView } from 'react-native';
import AbstractComponent from './AbstractComponent';
import Icon from './Icon';
import Button from './Button';
import { Colors } from './styles';

const styles = StyleSheet.create({
  container: {
    borderBottomWidth: 1,
    borderBottomColor: Colors.underlay,
    borderTopWidth: 1,
    borderTopColor: Colors.underlay
  },
  row: {
    flex: 1,
    flexDirection: 'row',
    height: 40,
    alignItems: 'center',
    marginLeft: 15,
    paddingRight: 15
  },
  header: {
    width: 30
  },
  body: {
    flex: 1
  },
  text: {
    color: '#000'
  },
  separator: {
    height: 0.5,
    marginLeft: 15
  }
});

/**
 * @author 田尘殇Sean(sean.snow@live.com)
 * @date 16/5/25
 */
class List extends AbstractComponent {

  static propTypes = {
    cellStyle: View.propTypes.style,
    items: PropTypes.array,
    separatorColor: PropTypes.string,
    onItemPress: PropTypes.func
  };

  static defaultProps = {
    alwaysBounceVertical: false,
    rowHasChanged: (r1, r2) => r1 !== r2,
    separatorColor: Colors.separator
  };

  state = {};

  constructor(props) {
    super(props);
    const {items, rowHasChanged} = props;
    const ds = new ListView.DataSource({rowHasChanged});
    this.state = {
      dataSource: ds.cloneWithRows(items)
    };
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.items !== nextProps.items) {
      this.setState({dataSource: this.state.dataSource.cloneWithRows(nextProps.items)});
    }
  }

  renderHeader(header) {
    return header || <View />;
  }

  renderBody(body) {
    if (!body || typeof body === 'string') {
      return (
        <Text style={styles.body}>{body || ''}</Text>
      );
    }
    return body;
  }

  renderFooter(footer) {
    if (footer) {
      if (typeof footer === 'string') {
        return (
          <Text>{footer}</Text>
        );
      }
      return footer;
    }
    return (
      <Icon color="#000"
            name="angle-right"
            size={18}
      />
    );
  }

  renderRow(row, sectionID, rowID, highlightRow) {
    const {header, body, footer} = row;
    const {onItemPress, cellStyle} = this.props;
    return (
      <Button Comp={TouchableHighlight}
              containerStyle={[styles.row, cellStyle]}
              key={rowID}
              onPress={() => onItemPress && onItemPress(row, sectionID, rowID)}
              type="link"
              underlayColor={Colors.underlay}
      >
        {this.renderHeader(header)}
        {this.renderBody(body)}
        {this.renderFooter(footer)}
      </Button>
    );
  }

  renderSeparator(sectionID, rowID, adjacentRowHighlighted) {
    const {separatorColor, items} = this.props;
    if (rowID === `${items.length - 1}`) {
      return null;
    }
    const style = {
      backgroundColor: adjacentRowHighlighted ? 'transparent' : separatorColor
    };
    return (
      <View key={`${sectionID}-${rowID}`}
            style={[styles.separator, style]}
      />
    );
  }

  render() {
    const {contentContainerStyle, ...other} = this.props;
    return (
      <ListView {...other}
        contentContainerStyle={[styles.container, contentContainerStyle]}
        dataSource={this.state.dataSource}
        renderRow={this.renderRow}
        renderSeparator={this.renderSeparator}
      />
    );
  }

}

export default List;
<commit_msg>增加容器View<commit_after>import React, { PropTypes } from 'react';
import { View, Text, StyleSheet, TouchableHighlight, ListView } from 'react-native';
import AbstractComponent from './AbstractComponent';
import Icon from './Icon';
import Button from './Button';
import { Colors } from './styles';

const styles = StyleSheet.create({
  container: {
    borderBottomWidth: 1,
    borderTopWidth: 1
  },
  row: {
    flex: 1,
    flexDirection: 'row',
    height: 45,
    alignItems: 'center',
    marginLeft: 15,
    paddingRight: 15
  },
  header: {
    width: 30
  },
  body: {
    flex: 1
  },
  text: {
    color: '#000'
  },
  separator: {
    height: 0.5,
    marginLeft: 15
  }
});

/**
 * @author 田尘殇Sean(sean.snow@live.com)
 * @date 16/5/25
 */
class List extends AbstractComponent {

  static propTypes = {
    bodyTextStyle: Text.propTypes.style,
    cellStyle: View.propTypes.style,
    items: PropTypes.array,
    separatorColor: PropTypes.string,
    onItemPress: PropTypes.func
  };

  static defaultProps = {
    alwaysBounceVertical: false,
    rowHasChanged: (r1, r2) => r1 !== r2,
    separatorColor: Colors.separator
  };

  state = {};

  constructor(props) {
    super(props);
    const {items, rowHasChanged} = props;
    const ds = new ListView.DataSource({rowHasChanged});
    this.state = {
      dataSource: ds.cloneWithRows(items)
    };
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.items !== nextProps.items) {
      this.setState({dataSource: this.state.dataSource.cloneWithRows(nextProps.items)});
    }
  }

  renderHeader(header) {
    return header || <View />;
  }

  renderBody(body) {
    const {bodyTextStyle} = this.props;
    if (!body || typeof body === 'string') {
      return (
        <Text style={[styles.body, bodyTextStyle]}>{body || ''}</Text>
      );
    }
    return body;
  }

  renderFooter(footer) {
    if (footer) {
      if (typeof footer === 'string') {
        return (
          <Text>{footer}</Text>
        );
      }
      return footer;
    }
    return (
      <Icon color="#000"
            name="angle-right"
            size={18}
      />
    );
  }

  renderRow(row, sectionID, rowID, highlightRow) {
    const {header, body, footer} = row;
    const {onItemPress, cellStyle} = this.props;
    return (
      <Button Comp={TouchableHighlight}
              containerStyle={[styles.row, cellStyle]}
              key={rowID}
              onPress={() => onItemPress && onItemPress(row, sectionID, rowID)}
              type="link"
              underlayColor={Colors.underlay}
      >
        {this.renderHeader(header)}
        {this.renderBody(body)}
        {this.renderFooter(footer)}
      </Button>
    );
  }

  renderSeparator(sectionID, rowID, adjacentRowHighlighted) {
    const {separatorColor, items} = this.props;
    if (rowID === `${items.length - 1}`) {
      return null;
    }
    const style = {
      backgroundColor: adjacentRowHighlighted ? 'transparent' : separatorColor
    };
    return (
      <View key={`${sectionID}-${rowID}`}
            style={[styles.separator, style]}
      />
    );
  }

  render() {
    const {style, separatorColor, ...other} = this.props;
    return (
      <View style={[styles.container, {borderColor: separatorColor}, style]}>
        <ListView {...other}
          dataSource={this.state.dataSource}
          renderRow={this.renderRow}
          renderSeparator={this.renderSeparator}
        />
      </View>
    );
  }

}

export default List;
<|endoftext|>


<commit_before>// $Revision$

Ensembl.Panel.Configurator = Ensembl.Panel.ModalContent.extend({
  constructor: function (id, params) {
    this.base(id, params);

    Ensembl.EventManager.register('updateConfiguration', this, this.updateConfiguration);
    Ensembl.EventManager.register('showConfiguration', this, this.show);
  },

  init: function () {
    var panel = this;

    this.base();

    this.elLk.form          = $('form.configuration', this.el);
    this.elLk.search        = $('.configuration_search_text', this.el);
    this.elLk.help          = $('.menu_help', this.elLk.form);
    this.elLk.menus         = $('.popup_menu', this.elLk.form);
    this.elLk.searchResults = $('a.search_results', this.elLk.links);

    this.initialConfig = {};
    this.lastQuery     = false;

    $.each(this.elLk.form.serializeArray(), function () {
      panel.initialConfig[this.name] = this.value;
    });

    if (this.params.hash) {
      this.elLk.links.removeClass('active').has('.' + this.params.hash).addClass('active');
      delete this.params.hash;
    }

    this.getContent();

    $('input.submit', this.elLk.form).hide();

    this.elLk.help.bind('click', function () { panel.toggleDescription(this); });

    // Popup menus - displaying
    $('.menu_option', this.elLk.form).bind('click', function () {
      var menu = $(this).siblings('.popup_menu');

      if (menu.children().length == 2 && !$(this).parent().hasClass('select_all')) {
        menu.children(':not(.' + $(this).siblings('input').val() + ')').trigger('click');
      } else {
        panel.elLk.menus.filter(':visible').not(menu).hide();
        menu.toggle();
      }

      menu = null;
    });

    // Popup menus - setting values
    $('li', this.elLk.menus).bind('click', function () {
      var li    = $(this);
      var img   = li.children('img');
      var menu  = li.parents('.popup_menu');
      var dt    = menu.parent();
      var val   = li.attr('className');
      var link  = panel.elLk.links.children('a.' + img.attr('className'));
      var label = link.html().split(/\b/);

      if (dt.hasClass('select_all')) {
        dt = dt.siblings('dt.internal');

        if (val == 'all_on') {
          // First li is off, so use the second (index 1) as default on setting.
          dt.find('li:eq(1)').each(function () {
            var text = $(this).text();

            $(this).parent().siblings('img.menu_option').attr({
              src:   '/i/render/' + this.className + '.gif',
              alt:   text,
              title: text
            }).siblings('input').attr('newVal', this.className);
          });
        }
      }

      dt.children('input').each(function () {
        var input = $(this);

        if (input.val() == 'off' ^ val == 'off') {
          label[1] = parseInt(label[1], 10) + (val == 'off' ? -1 : 1);
        }

        input.val(input.attr('newVal') || val).removeAttr('newVal');
        input = null;
      });

      if (val != 'all_on') {
        dt.children('img.menu_option').attr({
          src:   '/i/render/' + val + '.gif',
          alt:   li.text(),
          title: li.text()
        });
      }

      label = label.join('');
      link.attr('title', label).html(label);
      menu.hide();

      menu = null;
      dt   = null;
      link = null;
      img  = null;
      li   = null;
    });

    this.elLk.search.bind({
      keyup: function () {
        if (this.value.length < 3) {
          panel.lastQuery = this.value;
        }

        if (this.value != panel.lastQuery) {
          if (panel.searchTimer) {
            clearTimeout(panel.searchTimer);
          }

          panel.query = this.value;
          panel.regex = new RegExp(this.value, 'i');

          panel.searchTimer = setTimeout(function () {
            panel.elLk.links.removeClass('active');
            panel.elLk.searchResults.removeClass('disabled').parent().addClass('active');
            panel.search();
          }, 250);
        }
      },
      focus: function () {
        this.value = '';
      }
    });

    // Header on search results and active tracks sections will act like the links on the left
    $('div.config > h2', this.elLk.form).css('cursor', 'pointer').bind('click', function () {
      var link = $(this).parent().attr('className').replace(/\s*config\s*/, '');
      $('a.' + link, panel.elLk.links).trigger('click');
    });
  },

  show: function (active) {
    this.elLk.menus.hide();

    if (active) {
      this.elLk.links.removeClass('active').has('.' + active).addClass('active');
    }

    this.base();
    this.getContent();
  },

  updateConfiguration: function (delayReload) {
    if ($('input.invalid', this.elLk.form).length) {
      return;
    }

    var panel   = this;
    var d       = false;
    var diff    = { config: this.initialConfig.config };
    var checked = $.extend({}, this.initialConfig);

    $.each(this.elLk.form.serializeArray(), function () {
      if (this.value != panel.initialConfig[this.name]) {
        diff[this.name] = this.value;
        d = true;
      }

      delete checked[this.name];
    });

    // Add unchecked checkboxes to the diff
    for (var i in checked) {
      diff[i] = 'off';
      d = true;
    }

    if (d === true) {
      $.extend(this.initialConfig, diff);
      diff.submit = 1;

      this.updatePage(diff, delayReload);

      return true;
    }
  },

  updatePage: function (diff, delayReload) {
    $.ajax({
      url:  this.elLk.form.attr('action'),
      type: this.elLk.form.attr('method'),
      data: diff,
      dataType: 'html',
      success: function (html) {
        if (html == 'SUCCESS') {
          Ensembl.EventManager.trigger('queuePageReload', diff.config, !delayReload);
        } else {
          // TODO: show message on main page
        }
      },
      error: function (e) {
       // TODO: show message on main page
      }
    });
  },

  getContent: function () {
    var active = this.elLk.links.filter('.active').children('a').attr('className');

    if (typeof active == 'undefined') {
      active = this.elLk.links.first().addClass('active').children('a').attr('className');
    }

    if (active == 'search_results') {
      this.elLk.search.val(this.query);
      this.search();
    } else if (typeof active != 'undefined') {
      $('div:not(.' + active + '), dd', this.elLk.form).hide();
      this.elLk.help.html('Show info');

      if (active == 'active_tracks') {
        $('dl.config_menu input', this.elLk.form).each(function () {
          if (this.value == 'off') {
            $(this).parent().hide().next('dd').hide(); // Hide the dt and the dd corresponding to it
          } else {
            $(this).parents('dt, div.config').show();
          }
        });
      } else {
        $('div.' + active, this.elLk.form).show().find('dl.config_menu dt').show();
      }

      this.lastQuery = false;
      this.styleTracks(active == 'active_tracks');
    }
  },

  styleTracks: function (special) {
    var col    = { 1: 'col1', '-1': 'col2', f: 1 };
    var margin = 0;

    if (special === true) {
      $('.select_all, .external', this.elLk.form).hide();
      $('.submenu', this.elLk.form).css('marginTop', 0);
    } else {
      margin = 10;
      $('.submenu', this.elLk.form).removeAttr('style');
    }

    $('dl.config_menu:visible', this.elLk.form).each(function () {
      var internal = $('dt:visible', this).each(function () {
        if ($(this).hasClass('external')) {
          col.f = 1; // Force colour reset for the start of the external section
        } else {
          $(this).removeClass('col1 col2').addClass(col[col.f*=-1])
            .next('dd').removeClass('col1 col2').addClass(col[col.f]);
        }
      }).filter('.internal');

      if (internal.siblings('.select_all').length) {
        internal.each(function () {
          var level = this.className.match(/level(\d+)/);
          $(this).css('marginLeft', margin * (level ? parseInt(level[1], 10) : 1));
        });
      }

      col.f    = 1;
      internal = null;
    });
  },

  // Filtering from the search box
  search: function () {
    var panel = this;
    var dts    = [];

    $('dl.config_menu', this.elLk.form).each(function () {
      var menu = $(this);
      var div  = menu.parent();

      if (!div[0].show) {
        div[0].show = false;
      }

      menu.children('dt:not(.select_all, .external)').each(function () {
        var dt    = $(this);
        var match = dt.children('span:not(.menu_help)').html().match(panel.regex);

        if (match || dt.next('dd').text().match(panel.regex)) {
          dt.show();
          div[0].show = true;

          if (!match) {
            dts.push(dt[0]);
          }
        } else {
          dt.hide().next('dd').hide();
        }

        dt = null;
      });

      if (div[0].show === true) {
        div.show();
      } else {
        div.hide();
      }

      menu = null;
      div  = null;
    });

    this.lastQuery = this.query;
    this.styleTracks(true);
    this.toggleDescription(dts, 'show');

    dts = null;
  },

  toggleDescription: function (els, action) {
    var dd, span, i;

    if (typeof els.length == 'undefined') {
      els = [ els ];
    }

    i = els.length;

    while (i--) {
      switch (els[i].nodeName) {
        case 'DT'  : dd = $(els[i]).next('dd'); span = $('.menu_help', els[i]); break;
        case 'SPAN': dd = $(els[i]).parent().next('dd'); span = $(els[i]); break;
        default    : return;
      }

      switch (action) {
        case 'hide': dd.hide(); break;
        case 'show': dd.show(); break;
        default    : dd.toggle();
      }

      span.html(dd.is(':visible') ? 'Hide info': 'Show info');

      dd   = null;
      span = null;
    }
  }
});
<commit_msg>configuration now returns a json<commit_after>// $Revision$

Ensembl.Panel.Configurator = Ensembl.Panel.ModalContent.extend({
  constructor: function (id, params) {
    this.base(id, params);

    Ensembl.EventManager.register('updateConfiguration', this, this.updateConfiguration);
    Ensembl.EventManager.register('showConfiguration', this, this.show);
  },

  init: function () {
    var panel = this;

    this.base();

    this.elLk.form          = $('form.configuration', this.el);
    this.elLk.search        = $('.configuration_search_text', this.el);
    this.elLk.help          = $('.menu_help', this.elLk.form);
    this.elLk.menus         = $('.popup_menu', this.elLk.form);
    this.elLk.searchResults = $('a.search_results', this.elLk.links);

    this.initialConfig = {};
    this.lastQuery     = false;

    $.each(this.elLk.form.serializeArray(), function () {
      panel.initialConfig[this.name] = this.value;
    });

    if (this.params.hash) {
      this.elLk.links.removeClass('active').has('.' + this.params.hash).addClass('active');
      delete this.params.hash;
    }

    this.getContent();

    $('input.submit', this.elLk.form).hide();

    this.elLk.help.bind('click', function () { panel.toggleDescription(this); });

    // Popup menus - displaying
    $('.menu_option', this.elLk.form).bind('click', function () {
      var menu = $(this).siblings('.popup_menu');

      if (menu.children().length == 2 && !$(this).parent().hasClass('select_all')) {
        menu.children(':not(.' + $(this).siblings('input').val() + ')').trigger('click');
      } else {
        panel.elLk.menus.filter(':visible').not(menu).hide();
        menu.toggle();
      }

      menu = null;
    });

    // Popup menus - setting values
    $('li', this.elLk.menus).bind('click', function () {
      var li    = $(this);
      var img   = li.children('img');
      var menu  = li.parents('.popup_menu');
      var dt    = menu.parent();
      var val   = li.attr('className');
      var link  = panel.elLk.links.children('a.' + img.attr('className'));
      var label = link.html().split(/\b/);

      if (dt.hasClass('select_all')) {
        dt = dt.siblings('dt.internal');

        if (val == 'all_on') {
          // First li is off, so use the second (index 1) as default on setting.
          dt.find('li:eq(1)').each(function () {
            var text = $(this).text();

            $(this).parent().siblings('img.menu_option').attr({
              src:   '/i/render/' + this.className + '.gif',
              alt:   text,
              title: text
            }).siblings('input').attr('newVal', this.className);
          });
        }
      }

      dt.children('input').each(function () {
        var input = $(this);

        if (input.val() == 'off' ^ val == 'off') {
          label[1] = parseInt(label[1], 10) + (val == 'off' ? -1 : 1);
        }

        input.val(input.attr('newVal') || val).removeAttr('newVal');
        input = null;
      });

      if (val != 'all_on') {
        dt.children('img.menu_option').attr({
          src:   '/i/render/' + val + '.gif',
          alt:   li.text(),
          title: li.text()
        });
      }

      label = label.join('');
      link.attr('title', label).html(label);
      menu.hide();

      menu = null;
      dt   = null;
      link = null;
      img  = null;
      li   = null;
    });

    this.elLk.search.bind({
      keyup: function () {
        if (this.value.length < 3) {
          panel.lastQuery = this.value;
        }

        if (this.value != panel.lastQuery) {
          if (panel.searchTimer) {
            clearTimeout(panel.searchTimer);
          }

          panel.query = this.value;
          panel.regex = new RegExp(this.value, 'i');

          panel.searchTimer = setTimeout(function () {
            panel.elLk.links.removeClass('active');
            panel.elLk.searchResults.removeClass('disabled').parent().addClass('active');
            panel.search();
          }, 250);
        }
      },
      focus: function () {
        this.value = '';
      }
    });

    // Header on search results and active tracks sections will act like the links on the left
    $('div.config > h2', this.elLk.form).css('cursor', 'pointer').bind('click', function () {
      var link = $(this).parent().attr('className').replace(/\s*config\s*/, '');
      $('a.' + link, panel.elLk.links).trigger('click');
    });
  },

  show: function (active) {
    this.elLk.menus.hide();

    if (active) {
      this.elLk.links.removeClass('active').has('.' + active).addClass('active');
    }

    this.base();
    this.getContent();
  },

  updateConfiguration: function (delayReload) {
    if ($('input.invalid', this.elLk.form).length) {
      return;
    }

    var panel   = this;
    var d       = false;
    var diff    = { config: this.initialConfig.config };
    var checked = $.extend({}, this.initialConfig);

    $.each(this.elLk.form.serializeArray(), function () {
      if (this.value != panel.initialConfig[this.name]) {
        diff[this.name] = this.value;
        d = true;
      }

      delete checked[this.name];
    });

    // Add unchecked checkboxes to the diff
    for (var i in checked) {
      diff[i] = 'off';
      d = true;
    }

    if (d === true) {
      $.extend(this.initialConfig, diff);
      diff.submit = 1;

      this.updatePage(diff, delayReload);

      return true;
    }
  },

  updatePage: function (diff, delayReload) {
    $.ajax({
      url:  this.elLk.form.attr('action'),
      type: this.elLk.form.attr('method'),
      data: diff,
      dataType: 'json',
      success: function (json) {
        if (json.updated) {
          Ensembl.EventManager.trigger('queuePageReload', diff.config, !delayReload);
        } else if (json.redirect) {
          Ensembl.redirect(json.redirect);
        } else {
          // TODO: show message on main page
        }
      },
      error: function (e) {
       // TODO: show message on main page
      }
    });
  },

  getContent: function () {
    var active = this.elLk.links.filter('.active').children('a').attr('className');

    if (typeof active == 'undefined') {
      active = this.elLk.links.first().addClass('active').children('a').attr('className');
    }

    if (active == 'search_results') {
      this.elLk.search.val(this.query);
      this.search();
    } else if (typeof active != 'undefined') {
      $('div:not(.' + active + '), dd', this.elLk.form).hide();
      this.elLk.help.html('Show info');

      if (active == 'active_tracks') {
        $('dl.config_menu input', this.elLk.form).each(function () {
          if (this.value == 'off') {
            $(this).parent().hide().next('dd').hide(); // Hide the dt and the dd corresponding to it
          } else {
            $(this).parents('dt, div.config').show();
          }
        });
      } else {
        $('div.' + active, this.elLk.form).show().find('dl.config_menu dt').show();
      }

      this.lastQuery = false;
      this.styleTracks(active == 'active_tracks');
    }
  },

  styleTracks: function (special) {
    var col    = { 1: 'col1', '-1': 'col2', f: 1 };
    var margin = 0;

    if (special === true) {
      $('.select_all, .external', this.elLk.form).hide();
      $('.submenu', this.elLk.form).css('marginTop', 0);
    } else {
      margin = 10;
      $('.submenu', this.elLk.form).removeAttr('style');
    }

    $('dl.config_menu:visible', this.elLk.form).each(function () {
      var internal = $('dt:visible', this).each(function () {
        if ($(this).hasClass('external')) {
          col.f = 1; // Force colour reset for the start of the external section
        } else {
          $(this).removeClass('col1 col2').addClass(col[col.f*=-1])
            .next('dd').removeClass('col1 col2').addClass(col[col.f]);
        }
      }).filter('.internal');

      if (internal.siblings('.select_all').length) {
        internal.each(function () {
          var level = this.className.match(/level(\d+)/);
          $(this).css('marginLeft', margin * (level ? parseInt(level[1], 10) : 1));
        });
      }

      col.f    = 1;
      internal = null;
    });
  },

  // Filtering from the search box
  search: function () {
    var panel = this;
    var dts    = [];

    $('dl.config_menu', this.elLk.form).each(function () {
      var menu = $(this);
      var div  = menu.parent();

      if (!div[0].show) {
        div[0].show = false;
      }

      menu.children('dt:not(.select_all, .external)').each(function () {
        var dt    = $(this);
        var match = dt.children('span:not(.menu_help)').html().match(panel.regex);

        if (match || dt.next('dd').text().match(panel.regex)) {
          dt.show();
          div[0].show = true;

          if (!match) {
            dts.push(dt[0]);
          }
        } else {
          dt.hide().next('dd').hide();
        }

        dt = null;
      });

      if (div[0].show === true) {
        div.show();
      } else {
        div.hide();
      }

      menu = null;
      div  = null;
    });

    this.lastQuery = this.query;
    this.styleTracks(true);
    this.toggleDescription(dts, 'show');

    dts = null;
  },

  toggleDescription: function (els, action) {
    var dd, span, i;

    if (typeof els.length == 'undefined') {
      els = [ els ];
    }

    i = els.length;

    while (i--) {
      switch (els[i].nodeName) {
        case 'DT'  : dd = $(els[i]).next('dd'); span = $('.menu_help', els[i]); break;
        case 'SPAN': dd = $(els[i]).parent().next('dd'); span = $(els[i]); break;
        default    : return;
      }

      switch (action) {
        case 'hide': dd.hide(); break;
        case 'show': dd.show(); break;
        default    : dd.toggle();
      }

      span.html(dd.is(':visible') ? 'Hide info': 'Show info');

      dd   = null;
      span = null;
    }
  }
});
<|endoftext|>


<commit_before>"use strict";

/**
 * Small lib to go through the OneDrive authentication process and get back the token.
 *
 * Instructions:
 * - Host a copy of callback.html and odauth.js on your domain.
 * - Embed odauth.js in your app like this:
 *   <script src="odauth.js"></script>
 * - Create instance of OneDriveAuth and call auth() method to begin and whenever you
 *   need to make an API call. In first `callback` param you should provide handler of
 *   successful authorization. If you're making an api call in response to a user's click
 *   action, call auth(callback, true), otherwise just call auth(callback). The difference
 *   is that sometimes OneDriveAuth needs to pop up a window so the user can sign in,
 *   grant your app permission, etc. The pop up can only be launched in response
 *   to a user click, otherwise the browser's popup blocker will block it. When
 *   OneDriveAuth isn't called in click mode, it'll put a sign-in button at the top of
 *   your page for the user to click. When it's done, it'll remove that button.
 */

(function (global, factory) {
  if (typeof define === "function" && define.amd) {
    define("OneDriveAuth", ["module", "exports"], factory);
  } else if (typeof exports !== "undefined") {
    factory(module, exports);
  } else {
    var mod = {
      exports: {}
    };
    factory(mod, mod.exports);
    global.OneDriveAuth = mod.exports;
  }
})(this, function (module, exports) {
  Object.defineProperty(exports, "__esModule", {
    value: true
  });

  function _classCallCheck(instance, Constructor) {
    if (!(instance instanceof Constructor)) {
      throw new TypeError("Cannot call a class as a function");
    }
  }

  var _createClass = (function () {
    function defineProperties(target, props) {
      for (var i = 0; i < props.length; i++) {
        var descriptor = props[i];
        descriptor.enumerable = descriptor.enumerable || false;
        descriptor.configurable = true;
        if ("value" in descriptor) descriptor.writable = true;
        Object.defineProperty(target, descriptor.key, descriptor);
      }
    }

    return function (Constructor, protoProps, staticProps) {
      if (protoProps) defineProperties(Constructor.prototype, protoProps);
      if (staticProps) defineProperties(Constructor, staticProps);
      return Constructor;
    };
  })();

  var OneDriveAuth = (function () {
    function OneDriveAuth(appInfo) {
      _classCallCheck(this, OneDriveAuth);

      if (!appInfo.clientId) {
        throw "appInfo object should have `clientId` property set to your application id";
      }

      if (!appInfo.scopes) {
        throw "appInfo object should have `scopes` property set to the scopes your app needs";
      }

      if (!appInfo.redirectUri) {
        throw "appInfo object should have `redirectUri` property set to your redirect landing url";
      }

      if (!appInfo.redirectOrigin) {
        appInfo.redirectOrigin = appInfo.redirectUri.match(/^[\w:]+\/\/[^\/]+/)[0];
      }

      if (typeof appInfo.requireHttps === 'undefined') {
        appInfo.requireHttps = true;
      }

      this.appInfo = appInfo;
      var sep = this.appInfo.redirectUri.indexOf('?') < 0 ? '?' : '&';
      this.appInfo.redirectUri = this.appInfo.redirectUri.replace(/(#|$)/, sep + 'clientId=' + this.appInfo.clientId + '$1');
      this.callbacks = [];
      window.addEventListener('message', this.onAuthenticated.bind(this), false);
    }

    _createClass(OneDriveAuth, [{
      key: "auth",
      value: function auth(callback, wasClicked) {
        this.ensureHttps();
        var token = this.getTokenFromCookie();
        wasClicked = wasClicked || callback === true;
        callback = typeof callback === 'function' ? callback : false;

        if (token) {
          callback && callback(token);
          return true;
        }

        callback && this.callbacks.push(callback);

        if (wasClicked) {
          this.challengeForAuth();
        } else {
          this.showLoginButton();
        }

        return false;
      }
    }, {
      key: "ensureHttps",
      value: function ensureHttps() {
        if (this.appInfo.requireHttps && !this.isHttps()) {
          throw new Error("HTTPS is required to authorize this application for OneDrive");
        }
      }
    }, {
      key: "getTokenFromCookie",
      value: function getTokenFromCookie() {
        var cookies = document.cookie;
        var name = "odauth=";
        var start = cookies.indexOf(name);

        if (start >= 0) {
          start += name.length;
          var end = cookies.indexOf(';', start);

          if (end < 0) {
            end = cookies.length;
          }

          var value = cookies.substring(start, end);
          return value;
        }

        return "";
      }
    }, {
      key: "showLoginButton",
      value: function showLoginButton() {
        var callback = this.challengeForAuth.bind(this);
        var loginText = document.createElement('a');
        loginText.href = "#";
        loginText.id = "loginText";
        loginText.onclick = callback;
        loginText.innerText = "[sign in]";
        document.body.insertBefore(loginText, document.body.children[0]);
      }
    }, {
      key: "removeLoginButton",
      value: function removeLoginButton() {
        var loginText = document.getElementById("loginText");

        if (loginText) {
          document.body.removeChild(loginText);
        }
      }
    }, {
      key: "challengeForAuth",
      value: function challengeForAuth() {
        var appInfo = this.appInfo;
        var url = "https://login.live.com/oauth20_authorize.srf" + "?client_id=" + appInfo.clientId + "&scope=" + encodeURIComponent(appInfo.scopes) + "&response_type=token" + "&redirect_uri=" + encodeURIComponent(appInfo.redirectUri);
        this.popup(url);
      }
    }, {
      key: "popup",
      value: function popup(url) {
        var width = 525,
            height = 525,
            screenX = window.screenX,
            screenY = window.screenY,
            outerWidth = window.outerWidth,
            outerHeight = window.outerHeight;
        var left = screenX + Math.max(outerWidth - width, 0) / 2;
        var top = screenY + Math.max(outerHeight - height, 0) / 2;
        var features = ["width=" + width, "height=" + height, "top=" + top, "left=" + left, "status=no", "resizable=yes", "toolbar=no", "menubar=no", "scrollbars=yes"];
        var popup = window.open(url, "oauth", features.join(","));

        if (!popup) {
          console.error("failed to pop up auth window");
        }

        popup.focus();
      }
    }, {
      key: "onAuthenticated",
      value: function onAuthenticated(event) {
        var callback,
            token,
            data = event.data;
        if (this.appInfo.clientId !== data.clientId) return false;
        if (this.appInfo.redirectOrigin !== event.origin) return false;
        token = data.token;

        while (callback = this.callbacks.shift()) {
          callback(token);
        }
      }
    }], [{
      key: "isHttps",
      value: function isHttps() {
        return window.location.protocol.toLowerCase() === "https:";
      }
    }, {
      key: "onAuthCallback",
      value: function onAuthCallback() {
        var authInfo = this.getAuthInfoFromUrl();
        var token = authInfo["access_token"];
        var expiry = parseInt(authInfo["expires_in"]);
        var clientId = authInfo["clientId"];
        var origin = location.origin;
        this.setCookie(token, expiry);
        window.opener.postMessage({
          token: token,
          clientId: clientId
        }, origin);
        window.close();
      }
    }, {
      key: "getAuthInfoFromUrl",
      value: function getAuthInfoFromUrl() {
        if (window.location.hash) {
          var authResponse = (window.location.search + window.location.hash).substr(1);
          var authInfo = JSON.parse('{"' + authResponse.replace(/[&#]/g, '","').replace(/=/g, '":"') + '"}', function (key, value) {
            return key === "" ? value : decodeURIComponent(value);
          });
          return authInfo;
        } else {
          console.error("failed to receive auth token");
        }
      }
    }, {
      key: "setCookie",
      value: function setCookie(token, expiresInSeconds) {
        var expiration = new Date();
        expiration.setTime(expiration.getTime() + expiresInSeconds * 1000);
        var cookie = "odauth=" + token + "; path=/; expires=" + expiration.toUTCString();

        if (this.isHttps()) {
          cookie = cookie + ";secure";
        }

        document.cookie = cookie;
      }
    }]);

    return OneDriveAuth;
  })();

  exports.default = OneDriveAuth;
  module.exports = exports['default'];
});<commit_msg>v1.0.0 Promises<commit_after>"use strict";

/**
 * Small lib to go through the OneDrive authentication process and get back the token.
 *
 * Instructions:
 * - Host a copy of callback.html and odauth.js on your domain.
 * - Embed odauth.js in your app like this:
 *   <script src="odauth.js"></script>
 * - Create instance of OneDriveAuth and call auth() method to begin and whenever you
 *   need to make an API call. In first `callback` param you should provide handler of
 *   successful authorization. If you're making an api call in response to a user's click
 *   action, call auth(callback, true), otherwise just call auth(callback). The difference
 *   is that sometimes OneDriveAuth needs to pop up a window so the user can sign in,
 *   grant your app permission, etc. The pop up can only be launched in response
 *   to a user click, otherwise the browser's popup blocker will block it. When
 *   OneDriveAuth isn't called in click mode, it'll put a sign-in button at the top of
 *   your page for the user to click. When it's done, it'll remove that button.
 */

(function (global, factory) {
  if (typeof define === "function" && define.amd) {
    define("OneDriveAuth", ["module", "exports"], factory);
  } else if (typeof exports !== "undefined") {
    factory(module, exports);
  } else {
    var mod = {
      exports: {}
    };
    factory(mod, mod.exports);
    global.OneDriveAuth = mod.exports;
  }
})(this, function (module, exports) {
  Object.defineProperty(exports, "__esModule", {
    value: true
  });

  function _classCallCheck(instance, Constructor) {
    if (!(instance instanceof Constructor)) {
      throw new TypeError("Cannot call a class as a function");
    }
  }

  var _createClass = (function () {
    function defineProperties(target, props) {
      for (var i = 0; i < props.length; i++) {
        var descriptor = props[i];
        descriptor.enumerable = descriptor.enumerable || false;
        descriptor.configurable = true;
        if ("value" in descriptor) descriptor.writable = true;
        Object.defineProperty(target, descriptor.key, descriptor);
      }
    }

    return function (Constructor, protoProps, staticProps) {
      if (protoProps) defineProperties(Constructor.prototype, protoProps);
      if (staticProps) defineProperties(Constructor, staticProps);
      return Constructor;
    };
  })();

  var OneDriveAuth = (function () {
    function OneDriveAuth(appInfo) {
      _classCallCheck(this, OneDriveAuth);

      this.appInfo = Object.assign({}, appInfo);

      if (!appInfo.clientId) {
        throw "appInfo object should have `clientId` property set to your application id";
      }

      if (!appInfo.scopes) {
        throw "appInfo object should have `scopes` property set to the scopes your app needs";
      }

      if (!appInfo.redirectUri) {
        throw "appInfo object should have `redirectUri` property set to your redirect landing url";
      }

      if (!appInfo.redirectOrigin) {
        this.appInfo.redirectOrigin = appInfo.redirectUri.match(/^[\w:]+\/\/[^\/]+/)[0];
      }

      if (typeof appInfo.requireHttps === 'undefined') {
        this.appInfo.requireHttps = true;
      }

      var sep = this.appInfo.redirectUri.indexOf('?') < 0 ? '?' : '&';
      this.appInfo.redirectUri = this.appInfo.redirectUri.replace(/(#|$)/, sep + 'clientId=' + this.appInfo.clientId + '$1');
      this.callbacks = [];
    }

    _createClass(OneDriveAuth, [{
      key: "auth",
      value: function auth(callback, wasClicked) {
        var _this = this;

        if (!this.ensureHttps()) {
          var error = new Error("HTTPS is required to authorize this application for OneDrive");

          if (callback) {
            throw error;
          } else {
            return Promise.reject(error);
          }
        }

        wasClicked = wasClicked || callback === true;
        callback = typeof callback === 'function' ? callback : null;
        var token = this.getTokenFromCookie();

        if (token) {
          if (callback) {
            callback(token);
            return true;
          } else {
            return Promise.resolve(token);
          }
        }

        callback && this.callbacks.push(callback);
        if (this.state) return callback ? false : this.state;
        if (!wasClicked) return callback ? false : Promise.reject();
        this.state = new Promise(function (ok, no) {
          window.addEventListener('message', function (e) {
            var p = _this.onAuthenticated(e);

            p && p.then(ok, no);
          }, false);
        });
        this.challengeForAuth();
        return callback ? false : this.state;
      }
    }, {
      key: "ensureHttps",
      value: function ensureHttps() {
        return !this.appInfo.requireHttps || this.isHttps();
      }
    }, {
      key: "getTokenFromCookie",
      value: function getTokenFromCookie() {
        var cookies = document.cookie;
        var name = "odauth=";
        var start = cookies.indexOf(name);

        if (start >= 0) {
          start += name.length;
          var end = cookies.indexOf(';', start);

          if (end < 0) {
            end = cookies.length;
          }

          var value = cookies.substring(start, end);
          return value;
        }

        return "";
      }
    }, {
      key: "challengeForAuth",
      value: function challengeForAuth() {
        var appInfo = this.appInfo;
        var url = "https://login.live.com/oauth20_authorize.srf" + "?client_id=" + appInfo.clientId + "&scope=" + encodeURIComponent(appInfo.scopes) + "&response_type=token" + "&redirect_uri=" + encodeURIComponent(appInfo.redirectUri);
        this.popup(url);
      }
    }, {
      key: "popup",
      value: function popup(url) {
        var width = 525,
            height = 525,
            screenX = window.screenX,
            screenY = window.screenY,
            outerWidth = window.outerWidth,
            outerHeight = window.outerHeight;
        var left = screenX + Math.max(outerWidth - width, 0) / 2;
        var top = screenY + Math.max(outerHeight - height, 0) / 2;
        var features = ["width=" + width, "height=" + height, "top=" + top, "left=" + left, "status=no", "resizable=yes", "toolbar=no", "menubar=no", "scrollbars=yes"];
        var popup = window.open(url, "oauth", features.join(","));

        if (!popup) {
          console.error("failed to pop up auth window");
        }

        popup.focus();
      }
    }, {
      key: "onAuthenticated",
      value: function onAuthenticated(event) {
        var callback,
            data = event.data,
            token = data.access_token;
        if (this.appInfo.clientId !== data.clientId) return false;
        if (this.appInfo.redirectOrigin !== event.origin) return false;

        if (data.error) {
          var error = new Error();
          error.message = data.error_description;
          error.name = data.error;
          return Promise.reject(error);
        } else {
          while (callback = this.callbacks.shift()) {
            callback(token);
          }

          return Promise.resolve(token);
        }
      }
    }], [{
      key: "isHttps",
      value: function isHttps() {
        return window.location.protocol.toLowerCase() === "https:";
      }
    }, {
      key: "onAuthCallback",
      value: function onAuthCallback() {
        var authInfo = this.getAuthInfoFromUrl();
        var token = authInfo["access_token"];
        var expiry = parseInt(authInfo["expires_in"]);
        var origin = location.origin;

        if (authInfo.error_description) {
          authInfo.error_description = decodeURIComponent(authInfo.error_description).replace(/\+/g, ' ');
        }

        if (token) {
          this.setCookie(token, expiry);
        }

        window.opener.postMessage(authInfo, origin);
        window.close();
      }
    }, {
      key: "getAuthInfoFromUrl",
      value: function getAuthInfoFromUrl() {
        if (window.location.hash) {
          var authResponse = (window.location.search + window.location.hash).substr(1);
          var authInfo = JSON.parse('{"' + authResponse.replace(/[&#]/g, '","').replace(/=/g, '":"') + '"}', function (key, value) {
            return key === "" ? value : decodeURIComponent(value);
          });
          return authInfo;
        } else {
          console.error("failed to receive auth token");
        }
      }
    }, {
      key: "setCookie",
      value: function setCookie(token, expiresInSeconds) {
        var expiration = new Date();
        expiration.setTime(expiration.getTime() + expiresInSeconds * 1000);
        var cookie = "odauth=" + token + "; path=/; expires=" + expiration.toUTCString();

        if (this.isHttps()) {
          cookie = cookie + ";secure";
        }

        document.cookie = cookie;
      }
    }]);

    return OneDriveAuth;
  })();

  exports.default = OneDriveAuth;
  module.exports = exports['default'];
});

<|endoftext|>


<commit_before>//Copyright {2016} {NIIT Limited, Wipro Limited}
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
//
//   Name of Developers  Raghav Goel, Kshitij Jain, Lakshay Bansal, Ayush Jain, Saurabh Gupta, Akshay Meher
//

var express = require('express');
    router = express.Router(),
    Category = require("../models/category"),
    Topic = require("../models/topic"),
    Profile =require("../models/profile"),
    topicInst,
    topic1={},
    points = 0,
    level =1;

findPercentage = function(points,level)
{
  return ((points-levelScore(level))/(levelScore(level+1)-levelScore(level)))*100;
}

levelScore = function(n)
{
  return ((35 * (n * n)) +(95*n)-130);
}
findLevel = function(points){
  i=1;
  while(points>=levelScore(i))
  {
    i++;
  }
  return i-1;
}
 router.route('/categories')
  .get(function(req, res){
    Category.find()
      .populate("categoryTopics")
          .exec(function(err,categories){
            if(err){
                return res.send(err);
              }
            return res.json(categories);
          });
 	});
  router.route('/category/:id')
	.get(function(req, res){
		Category.findById(req.params.id)
      .populate("categoryTopics")
        .exec(function(err, category){
      			if(err)
      				return res.send(err);
      			return res.json(category);
		});
	});
  router.route('/topic/:id')
    .get(function(req,res){
      var usr = req.session.user.local.username;
      topicInst = req.params.id;
      req.session.tid = topicInst;
        Profile.findOne({userId: usr})
         .exec(function(err,data){

        topic1.topicWins=0;
        topic1.topicLosses=0;
        topic1["topicLevel"]=1;
        topic1["levelPercentage"]=0;
        topic1["isFollowed"]= false;
        topic1['points']=0;

        var topicsPlayed=data["topicsPlayed"];
         var l=topicsPlayed.length;
         for(var i=0;i<l;++i)
         {
           if(topicsPlayed[i].topicId === req.params.id)
            break;
         }
         if(i!=l)
         {
         var topic2=topicsPlayed[i];
         topic1["topicWins"]=topic2["gamesWon"];
         topic1["topicLosses"]=topic2["gamesPlayed"]-topic2["gamesWon"];
         points =topic2["points"];
         level= topic2["level"];
         topic1["topicLevel"]=topic2["level"];
         topic1["levelPercentage"]=findPercentage(points,level);
         topic1["isFollowed"]=topic2["isFollowed"];
         topic1["points"]=points;
       }
      Topic.findById(req.params.id)
       .exec(function(err,topic){
       if(err)
        return res.send(err);
        topic1.topicId=topic._id;
        topic1.topicName=topic.topicName;
        topic1.topicDescription=topic.topicDescription;
        topic1.topicIcon = topic.topicIcon;
        topic1.topicFollowers=topic.topicFollowers;
        console.log("######");
        console.log(topic1);
        res.json(topic1);
      });
      });
  })
  .put(function(req,res){
    var usr = req.session.user.local.username;
      Profile.findOne({userId: usr})
       .exec(function(err,data){
      var topicsPlayed=data["topicsPlayed"];
       var l=topicsPlayed.length;
       var tid=req.params.id;
       req.session.tid=tid;
       for(var i=0;i<l;++i)
       {
         if(topicsPlayed[i].topicId === req.params.id)
          break;
       }
       if(i==l)
       {
         var topic3={
             "topicId":req.params.id,
             "gamesPlayed":0,
             "gamesWon":0,
             "level":1,
              "isFollowed":false,
              "points":0
         }
         data.topicsPlayed.push(topic3);
       }
       data.topicsPlayed[i].isFollowed=!(data.topicsPlayed[i].isFollowed);
       data.save(function(err){
       if ( err ) console.log(err);
       var topic2=topicsPlayed[i];
       topic1["topicWins"]=topic2["gamesWon"];
       topic1["topicLosses"]=topic2["gamesPlayed"]-topic2["gamesWon"];
       topic1["topicLevel"]=topic2["level"];
       topic1["levelPercentage"]=0;
       topic1["points"]=topic2["points"];
       topic1["isFollowed"]=topic2["isFollowed"];

    Topic.findById(req.params.id)
     .exec(function(err,topic){
     if(err)
      return res.send(err);
      if(data.topicsPlayed[i].isFollowed==true)
      {
        topic.topicFollowers=topic.topicFollowers+1;
      }
      else {
        topic.topicFollowers=topic.topicFollowers-1;
      }
      topic.save(function(err){
      if ( err ) console.log(err);
    topic1.topicId=topic._id;
    topic1.topicName=topic.topicName;
    topic1.topicDescription=topic.topicDescription;
    topic1.topicIcon = topic.topicIcon;
    topic1.topicFollowers=topic.topicFollowers;
    res.json(topic1);

  });
    });
    });
});
})
.post(function(req,res){
  var usr = req.session.user.local.username;
    Profile.findOne({userId: usr})
     .exec(function(err,data){
    var topicsPlayed=data["topicsPlayed"];
     var l=topicsPlayed.length;
     var tid=req.params.id;
     req.session.tid=tid;
     for(var i=0;i<l;++i)
     {
       if(topicsPlayed[i].topicId === req.params.id)
        break;
     }
     if(i==l)
     {
       var topic3={
           "topicId":req.params.id,
           "gamesPlayed":0,
           "gamesWon":0,
           "level":1,
           "isFollowed":false,
           "points":0
       }
       data.topicsPlayed.push(topic3);
     }
     data.save(function(err){
     if ( err ) console.log(err)});

  });
});
module.exports= router;
<commit_msg>removed redundant var declarations<commit_after>//Copyright {2016} {NIIT Limited, Wipro Limited}
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
//
//   Name of Developers  Raghav Goel, Kshitij Jain, Lakshay Bansal, Ayush Jain, Saurabh Gupta, Akshay Meher
//

var express = require('express'),
    router = express.Router(),
    Category = require("../models/category"),
    Topic = require("../models/topic"),
    Profile =require("../models/profile"),
    topicInst,
    topic1={},
    points = 0,
    level =1;

findPercentage = function(points,level)
{
  return ((points-levelScore(level))/(levelScore(level+1)-levelScore(level)))*100;
}

levelScore = function(n)
{
  return ((35 * (n * n)) +(95*n)-130);
}
findLevel = function(points){
  i=1;
  while(points>=levelScore(i))
  {
    i++;
  }
  return i-1;
}
 router.route('/categories')
  .get(function(req, res){
    Category.find()
      .populate("categoryTopics")
          .exec(function(err,categories){
            if(err){
                return res.send(err);
              }
            return res.json(categories);
          });
 	});
  router.route('/category/:id')
	.get(function(req, res){
		Category.findById(req.params.id)
      .populate("categoryTopics")
        .exec(function(err, category){
      			if(err)
      				return res.send(err);
      			return res.json(category);
		});
	});
  router.route('/topic/:id')
    .get(function(req,res){
      var usr = req.session.user.local.username;
      topicInst = req.params.id;
      req.session.tid = topicInst;
        Profile.findOne({userId: usr})
         .exec(function(err,data){

        topic1.topicWins=0;
        topic1.topicLosses=0;
        topic1["topicLevel"]=1;
        topic1["levelPercentage"]=0;
        topic1["isFollowed"]= false;
        topic1['points']=0;

        var topicsPlayed=data["topicsPlayed"];
         var l=topicsPlayed.length;
         for(var i=0;i<l;++i)
         {
           if(topicsPlayed[i].topicId === req.params.id)
            break;
         }
         if(i!=l)
         {
         var topic2=topicsPlayed[i];
         topic1["topicWins"]=topic2["gamesWon"];
         topic1["topicLosses"]=topic2["gamesPlayed"]-topic2["gamesWon"];
         points =topic2["points"];
         level= topic2["level"];
         topic1["topicLevel"]=topic2["level"];
         topic1["levelPercentage"]=findPercentage(points,level);
         topic1["isFollowed"]=topic2["isFollowed"];
         topic1["points"]=points;
       }
      Topic.findById(req.params.id)
       .exec(function(err,topic){
       if(err)
        return res.send(err);
        topic1.topicId=topic._id;
        topic1.topicName=topic.topicName;
        topic1.topicDescription=topic.topicDescription;
        topic1.topicIcon = topic.topicIcon;
        topic1.topicFollowers=topic.topicFollowers;
        console.log("######");
        console.log(topic1);
        res.json(topic1);
      });
      });
  })
  .put(function(req,res){
    var usr = req.session.user.local.username;
      Profile.findOne({userId: usr})
       .exec(function(err,data){
      var topicsPlayed=data["topicsPlayed"];
       var l=topicsPlayed.length;
       var tid=req.params.id;
       req.session.tid=tid;
       for(var i=0;i<l;++i)
       {
         if(topicsPlayed[i].topicId === req.params.id)
          break;
       }
       if(i==l)
       {
         var topic3={
             "topicId":req.params.id,
             "gamesPlayed":0,
             "gamesWon":0,
             "level":1,
              "isFollowed":false,
              "points":0
         }
         data.topicsPlayed.push(topic3);
       }
       data.topicsPlayed[i].isFollowed=!(data.topicsPlayed[i].isFollowed);
       data.save(function(err){
       if ( err ) console.log(err);
       var topic2=topicsPlayed[i];
       topic1["topicWins"]=topic2["gamesWon"];
       topic1["topicLosses"]=topic2["gamesPlayed"]-topic2["gamesWon"];
       topic1["topicLevel"]=topic2["level"];
       topic1["levelPercentage"]=0;
       topic1["points"]=topic2["points"];
       topic1["isFollowed"]=topic2["isFollowed"];

    Topic.findById(req.params.id)
     .exec(function(err,topic){
     if(err)
      return res.send(err);
      if(data.topicsPlayed[i].isFollowed==true)
      {
        topic.topicFollowers=topic.topicFollowers+1;
      }
      else {
        topic.topicFollowers=topic.topicFollowers-1;
      }
      topic.save(function(err){
      if ( err ) console.log(err);
    topic1.topicId=topic._id;
    topic1.topicName=topic.topicName;
    topic1.topicDescription=topic.topicDescription;
    topic1.topicIcon = topic.topicIcon;
    topic1.topicFollowers=topic.topicFollowers;
    res.json(topic1);

  });
    });
    });
});
})
.post(function(req,res){
  var usr = req.session.user.local.username;
    Profile.findOne({userId: usr})
     .exec(function(err,data){
    var topicsPlayed=data["topicsPlayed"];
     var l=topicsPlayed.length;
     var tid=req.params.id;
     req.session.tid=tid;
     for(var i=0;i<l;++i)
     {
       if(topicsPlayed[i].topicId === req.params.id)
        break;
     }
     if(i==l)
     {
       var topic3={
           "topicId":req.params.id,
           "gamesPlayed":0,
           "gamesWon":0,
           "level":1,
           "isFollowed":false,
           "points":0
       }
       data.topicsPlayed.push(topic3);
     }
     data.save(function(err){
     if ( err ) console.log(err)});

  });
});
module.exports= router;
<|endoftext|>