<commit_before>var request = require('request-promise');
var async = require("async");

var metadataTemplate = '<DIDL-Lite xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:upnp="urn:schemas-upnp-org:metadata-1-0/upnp/" ' +
        'xmlns:r="urn:schemas-rinconnetworks-com:metadata-1-0/" xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/">' +
        '<item id="{metadataID}" parentID="{parentURI}" restricted="true"><upnp:class>object.item.audioItem.{clazz}</upnp:class>' +
        '<desc id="cdudn" nameSpace="urn:schemas-rinconnetworks-com:metadata-1-0/">SA_RINCON52231_X_#Svc52231-0-Token</desc></item></DIDL-Lite>';

var uriTemplates = {
  song: 'x-sonos-http:{id}.mp4?sid=204&flags=8224&sn=4',
  album: 'x-rincon-cpcontainer:0004206c{id}',
  name: 'x-sonos-http:{id}.mp4?sid=204&flags=8224&sn=4'
};

var CLASSES = {
  song: 'musicTrack',
  album: 'musicAlbum',
  name: 'musicTrack'
}

var METADATA_URI_STARTERS = {
  song: '00032020',
  album: '0004206c',
  name: '00032020'
};

var PARENTS = {
  song: '0004206calbum%3a',
  album: '00020000album%3a',
  name: '0004206calbum%3a'
};

function appleMusic(player, values) {
  var action = values[0];
  var trackID = values[1];
  var type = trackID.split(':')[0];
  var metadataID = METADATA_URI_STARTERS[type] + encodeURIComponent(trackID);
  var trkNum = 0;

  var metadata = metadataTemplate.format({
    metadataID: metadataID,
    parentURI: PARENTS[type],
    clazz: CLASSES[type]
  });

  var uri = uriTemplates[type].format({id: encodeURIComponent(trackID)});

  if (action == 'queue') {
    if (type == 'name') {
      request({url: "https://itunes.apple.com/search?media=music&limit=50&entity=song&term=" + trackID.split(':')[1],
               json: true})
        .then(function(tracksJson) {
          while ((trkNum < tracksJson.resultCount) && !tracksJson.results[trkNum].isStreamable) {
            trkNum++;
          }

          // There is at least one streamable track
          if (trkNum < tracksJson.resultCount) {
            var prevArtist = tracksJson.results[trkNum].artistName;
            var prevTrack = tracksJson.results[trkNum].trackName;
            var artistCount = 1;
            var trackCount = 1;
            var artists = tracksJson.results.map(function(track) {
              return track.artistName.toLowerCase();
            });
            var tracks = tracksJson.results.map(function(track) {
              return track.trackName.toLowerCase();
            });

            artists.sort();
            tracks.sort();

            // Determine if the search results are many tracks for an artist OR a specific song title.
            var prevArtist=artists[0];
            var prevTrack=tracks[0];
            for (var i=1; i < tracksJson.resultCount;i++) {

              if (artists[i] != prevArtist) {
                artistCount++;
                prevArtist = artists[i];
              }
              if (tracks[i] != prevTrack) {
                trackCount++;
                prevTrack = tracks[i];
              }
            }

            // If there are at least twice as many track differences that artist differences, then load all of the artist's tracks into the queue, ELSE play just the first track now (iTunes returns the most popular track first)
            if (trackCount/artistCount > 2) {
              var first = true;
              player.coordinator.removeAllTracksFromQueue(function() {
                trkNum = 0;
                // Add each of the remaining tracks after a delay interval to keep from pounding Sonos
                async.eachSeries(tracksJson.results,
                  function(track,callback) {
                    // Check see if this track is a duplicate of a track that has already been queued and skip it if so
                    if (track.isStreamable) {
                      var found = false;

                      for (var j=0; (j < trkNum) && !found ; j++) {
                        dupe_check = tracksJson.results[j];
                        found = (track.trackName == dupe_check.trackName);
                      }

                      if (!found) {
                        var metadataID = METADATA_URI_STARTERS[type] + encodeURIComponent('song:' + track.trackId);
                        var metadata = metadataTemplate.format({
                          metadataID: metadataID,
                          parentURI: PARENTS[type],
                          clazz: CLASSES[type]
                        });
                        var uri = uriTemplates[type].format({id: encodeURIComponent('song:' + track.trackId)});

                        if (first) {
                          player.coordinator.addURIToQueue(uri, metadata, true, 1, function (error, res) {
                            if (!error) {
                              //need this to tell sonos to use queue (it may be playing from line in, etc)
                              var queueURI = 'x-rincon-queue:' + player.uuid + '#0';
                              player.setAVTransportURI(queueURI, '', function () {
                                player.coordinator.play(callback);
                              });
                            } else {
                              callback(error);
                            }
                          });
                          first = false;
                        } else {
                          var nextTrackNo = player.coordinator.state.trackNo + 1;
                          player.coordinator.addURIToQueue(uri, metadata, function (error, res) {
                            callback();
                          });
                        }
                      } else {
                        callback();
                      }
                    } else {
                      callback();
                    }
                  },
                  function(err) {
                  });

              });
            } else {
              var track = tracksJson.results[trkNum];
              var metadataID = METADATA_URI_STARTERS[type] + encodeURIComponent('song:' + track.trackId);
              var metadata = metadataTemplate.format({
                metadataID: metadataID,
                parentURI: PARENTS[type],
                clazz: CLASSES[type]
              });
              var uri = uriTemplates[type].format({id: encodeURIComponent('song:' + track.trackId)});
              var nextTrackNo = player.coordinator.state.trackNo + 1;

              player.coordinator.addURIToQueue(uri, metadata, true, nextTrackNo, function (error, res) {
                if (!error) {
                  player.coordinator.nextTrack(function (error) {
                    if (!error) {
                      //need this to tell sonos to use queue (it may be playing from line in, etc)
                      var queueURI = 'x-rincon-queue:' + player.uuid + '#' + nextTrackNo;
                      player.setAVTransportURI(queueURI, '', function () {
                        player.coordinator.play();
                      });
                    }
                  });
                }
              });
            }
          }
        });
    } else {
      player.coordinator.addURIToQueue(uri, metadata);
    }
  } else if(action == 'now') {

    var nextTrackNo = player.coordinator.state.trackNo + 1;
    player.coordinator.addURIToQueue(uri, metadata, true, nextTrackNo, function (error, res) {
      if (!error) {
        player.coordinator.nextTrack(function (error) {
          if (!error) {
            player.coordinator.play();
          }
        });
      }
    });
  } else if (action == 'next') {
    var nextTrackNo = player.coordinator.state.trackNo + 1;
    player.coordinator.addURIToQueue(uri, metadata, true, nextTrackNo);
  }
}

module.exports = function (api) {
  api.registerAction('applemusic', appleMusic);
}<commit_msg>Update appleMusic.js<commit_after>var request = require('request-promise');
var async = require("async");

var metadataTemplate = '<DIDL-Lite xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:upnp="urn:schemas-upnp-org:metadata-1-0/upnp/" ' +
        'xmlns:r="urn:schemas-rinconnetworks-com:metadata-1-0/" xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/">' +
        '<item id="{metadataID}" parentID="{parentURI}" restricted="true"><upnp:class>object.item.audioItem.{clazz}</upnp:class>' +
        '<desc id="cdudn" nameSpace="urn:schemas-rinconnetworks-com:metadata-1-0/">SA_RINCON52231_X_#Svc52231-0-Token</desc></item></DIDL-Lite>';

var uriTemplates = {
  song: 'x-sonos-http:{id}.mp4?sid=204&flags=8224&sn=4',
  album: 'x-rincon-cpcontainer:0004206c{id}',
  name: 'x-sonos-http:{id}.mp4?sid=204&flags=8224&sn=4'
};

var CLASSES = {
  song: 'musicTrack',
  album: 'musicAlbum',
  name: 'musicTrack'
}

var METADATA_URI_STARTERS = {
  song: '00032020',
  album: '0004206c',
  name: '00032020'
};

var PARENTS = {
  song: '0004206calbum%3a',
  album: '00020000album%3a',
  name: '0004206calbum%3a'
};

function appleMusic(player, values) {
  var action = values[0];
  var trackID = values[1];
  var type = trackID.split(':')[0];
  var metadataID = METADATA_URI_STARTERS[type] + encodeURIComponent(trackID);
  var trkNum = 0;

  var metadata = metadataTemplate.format({
    metadataID: metadataID,
    parentURI: PARENTS[type],
    clazz: CLASSES[type]
  });

  var uri = uriTemplates[type].format({id: encodeURIComponent(trackID)});

  if (action == 'queue') {
    if (type == 'name') {
      request({url: "https://itunes.apple.com/search?media=music&limit=50&entity=song&term=" + trackID.split(':')[1],
               json: true})
        .then(function(tracksJson) {
          while ((trkNum < tracksJson.resultCount) && !tracksJson.results[trkNum].isStreamable) {
            trkNum++;
          }

          // There is at least one streamable track
          if (trkNum < tracksJson.resultCount) {
            var prevArtist = tracksJson.results[trkNum].artistName;
            var prevTrack = tracksJson.results[trkNum].trackName;
            var artistCount = 1;
            var trackCount = 1;
            var artists = tracksJson.results.map(function(track) {
              return track.artistName.toLowerCase();
            });
            var tracks = tracksJson.results.map(function(track) {
              return track.trackName.toLowerCase();
            });

            artists.sort();
            tracks.sort();

            // Determine if the search results are many tracks for an artist OR a specific song title.
            var prevArtist=artists[0];
            var prevTrack=tracks[0];
            for (var i=1; i < tracksJson.resultCount;i++) {

              if (artists[i] != prevArtist) {
                artistCount++;
                prevArtist = artists[i];
              }
              if (tracks[i] != prevTrack) {
                trackCount++;
                prevTrack = tracks[i];
              }
            }

            // If there are at least twice as many track differences that artist differences, then load all of the artist's tracks into the queue, ELSE play just the first track now (iTunes returns the most popular track first)
            if (trackCount/artistCount > 2) {
              var first = true;
              player.coordinator.removeAllTracksFromQueue(function() {
                trkNum = 0;
                // Add each of the remaining tracks after a delay interval to keep from pounding Sonos
                async.eachSeries(tracksJson.results,
                  function(track,callback) {
                    // Check see if this track is a duplicate of a track that has already been queued and skip it if so
                    if (track.isStreamable) {
                      var found = false;

                      for (var j=0; (j < trkNum) && !found ; j++) {
                        dupe_check = tracksJson.results[j];
                        found = (track.trackName == dupe_check.trackName);
                      }

                      if (!found) {
                        var metadataID = METADATA_URI_STARTERS[type] + encodeURIComponent('song:' + track.trackId);
                        var metadata = metadataTemplate.format({
                          metadataID: metadataID,
                          parentURI: PARENTS[type],
                          clazz: CLASSES[type]
                        });
                        var uri = uriTemplates[type].format({id: encodeURIComponent('song:' + track.trackId)});

                        if (first) {
                          player.coordinator.addURIToQueue(uri, metadata, true, 1, function (error, res) {
                            if (!error) {
                              //need this to tell sonos to use queue (it may be playing from line in, etc)
                              var queueURI = 'x-rincon-queue:' + player.uuid + '#0';
                              player.setAVTransportURI(queueURI, '', function () {
                                player.coordinator.play(callback);
                              });
                            } else {
                              callback(error);
                            }
                          });
                          first = false;
                        } else {
                          var nextTrackNo = player.coordinator.state.trackNo + 1;
                          player.coordinator.addURIToQueue(uri, metadata, function (error, res) {
                            callback();
                          });
                        }
                      } else {
                        callback();
                      }
                    } else {
                      callback();
                    }
                  },
                  function(err) {
                  });

              });
            } else {
              var track = tracksJson.results[trkNum];
              var metadataID = METADATA_URI_STARTERS[type] + encodeURIComponent('song:' + track.trackId);
              var metadata = metadataTemplate.format({
                metadataID: metadataID,
                parentURI: PARENTS[type],
                clazz: CLASSES[type]
              });
              var uri = uriTemplates[type].format({id: encodeURIComponent('song:' + track.trackId)});
              var nextTrackNo = player.coordinator.state.trackNo + 1;

              player.coordinator.addURIToQueue(uri, metadata, true, nextTrackNo, function (error, res) {
                if (!error) {
                  //need this to tell sonos to use queue (it may be playing from line in, etc)
                  var queueURI = 'x-rincon-queue:' + player.uuid + '#0';
                  player.setAVTransportURI(queueURI, '', function () {
                    player.coordinator.nextTrack(function (error) {
                      player.coordinator.play();
                    });
                  });
                }
              });
            }
          }
        });
    } else {
      player.coordinator.addURIToQueue(uri, metadata);
    }
  } else if(action == 'now') {

    var nextTrackNo = player.coordinator.state.trackNo + 1;
    player.coordinator.addURIToQueue(uri, metadata, true, nextTrackNo, function (error, res) {
      if (!error) {
        player.coordinator.nextTrack(function (error) {
          if (!error) {
            player.coordinator.play();
          }
        });
      }
    });
  } else if (action == 'next') {
    var nextTrackNo = player.coordinator.state.trackNo + 1;
    player.coordinator.addURIToQueue(uri, metadata, true, nextTrackNo);
  }
}

module.exports = function (api) {
  api.registerAction('applemusic', appleMusic);
}
<|endoftext|>


<commit_before>( function( window, atom, require, module, undefined ) {
	'use strict';

	// Imports
	var atomUtils = require( 'atom' );
	var spawn = require( 'win-spawn' );

	// Instance
	var commands = {
		subscriptions: new atomUtils.CompositeDisposable(),
		panel: null,
		config: require( './config' )
	}

	commands.activate = function( state ) {

		// Define and update a command list from the user config
		var registeredAtomCommands = [];

		atom.config.observe( 'atom-user-commands', {}, function( value ) {

			// Dispose old commands
			registeredAtomCommands.forEach( function( disposable ) {

				// Remove it from subscriptions and...
				commands.subscriptions.remove( disposable );

				// ... dispose it manually
				disposable.dispose();
			} );

			registeredAtomCommands = [];

			// Register new commands
			value.commands.forEach( function( command ) {

				// Create an atom command for each entry
				var commandName = 'atom-user-commands:' + command.name;
				var atomCommand = atom.commands.add( command.selector, commandName, function() {

					execute( command.command, command.arguments, command.options );
				} )

				// Create a menu entry for each command
				var menuEntry = atom.menu.add( [ {
					label : 'Packages',
					submenu: [ {
						label: 'Atom User Commands',
						submenu: [
							{
								label: command.name,
								command: commandName
							}
						]
					} ]
				} ] );

				// Register it in the subscriptions;
				registeredAtomCommands.push( atomCommand );
				registeredAtomCommands.push( menuEntry );

				commands.subscriptions.add( atomCommand );
				commands.subscriptions.add( menuEntry );
			} );
		} );
	}

	commands.deactivate = function() {
		commands.panel.destroy();
		commands.subscriptions.dispose();
	}

	commands.serialize = function() {
		return {};
	}

	// Create a bottom panel for the output
	function showConsole() {

		if ( !commands.panel ) {

			commands.panel = atom.workspace.addBottomPanel( {
				item: buildPanel(),
				visible: true,
				priority: 100
			} )
		};
	}

	// Destroy de bottom panel
	function hideConsole() {

		if ( commands.panel ) {
			commands.panel.destroy();
			commands.panel = null;
		}
	}

	// Execute an OS command
	function execute( command, args, options ) {

		// Open the panel if it is not
		if ( !commands.panel ) {
			showConsole();
		}

		// Cancel the close console listener
		if (commands.closeConsoleDisposable) {
			commands.closeConsoleDisposable.dispose();
			commands.subscriptions.remove(commands.closeConsoleDisposable);
		}

		var env = getEnv();

		command = replace( command || '', env );
		args = replace( args || [], env );
		options = replace( options || {}, env );

		// Announcing launch
		commands.panel.item.appendChild( window.document.createElement( 'br' ) );
		var span = window.document.createElement( 'span' );
		span.classList.add( 'echo' );
		span.textContent = "> " + command + ' ' + JSON.stringify( args ) + ' ' + JSON.stringify( options );
		commands.panel.item.appendChild( span );
		commands.panel.item.appendChild( window.document.createElement( 'br' ) );
		commands.panel.item.appendChild( window.document.createElement( 'br' ) );

		// Run the spawn, we pass args.slice() to make a shallow copy of the array because spawn will modify it.
		var proc = spawn( command, args.slice(), options );

		// Update console panel on data
		proc.stdout.on( 'data', function( data ) {

			var div = commands.panel.item;
			var line = window.document.createElement( 'div' );
			line.classList.add( 'stdout' );
			line.textContent = data.toString();
			div.appendChild( line );
			div.scrollTop = div.scrollHeight;

		} );

		// Update console panel on error data
		proc.stderr.on( 'data', function( data ) {

			var div = commands.panel.item;
			var line = window.document.createElement( 'div' );
			line.classList.add( 'stderr' );
			line.textContent = data.toString();
			div.appendChild( line );
			div.scrollTop = div.scrollHeight;
		} );

		proc.stdout.on( 'close', function( code, signal ) {
			// console.info('command closed', code, signal);
		} );

		// Register code for termination
		proc.stderr.on( 'close', function( code, signal ) {

			// Register an action for panel destruction
			commands.closeConsoleDisposable = atom.commands.add( 'atom-workspace', 'core:cancel', function() {
				hideConsole()
				commands.closeConsoleDisposable.dispose();
				commands.subscriptions.remove( commands.closeConsoleDisposable );
			} )

			commands.subscriptions.add( commands.closeConsoleDisposable );
		} );
	}

	// Set up the HTML element
	function buildPanel() {

		var mainDiv = window.document.createElement( 'div' );
		mainDiv.classList.add( 'atom-user-commands-console' );

		var input = window.document.createElement( 'textarea' );
		input.classList.add( 'console-input' );
		mainDiv.appendChild(input);

		return mainDiv;

	}

	// Generate Environment variables
	function getEnv() {

		var paths = atom.project.relativizePath( atom.workspace.getActiveTextEditor().getPath() );
		var env = {
			project: paths[ 0 ],
			path: paths[ 1 ],
			absPath: atom.workspace.getActiveTextEditor().getPath()
		};

		return env;
	}

	// Replace members with env variables.
	function replace( input, vars ) {

		// Dispatch input type
		if ( !input ) {
			return;
		} else if ( typeof input == 'string' ) {
			return replaceString( input, vars );
		} else if ( Array.isArray( input ) ) {
			return replaceArray( input, vars );
		} else if ( typeof input == 'object' ) {
			return replaceObject( input, vars );
		} else {
			return input;
		}
	}

	// replace a string with vars.
	function replaceString( input, vars ) {

		var rgx = /{({?)(\w+)(}?)}/g

		var match = null;
		while ( match = rgx.exec( input ) ) {

			// {? + variable + }? so {{arg}} -> {arg}
			var key = match[ 1 ] + match[ 2 ] + match[ 3 ];
			var replacement = vars[ key ] || key;

			// Replace the result only on the remaining string
			input = input.substring( 0, match.index ) + input.substring( match.index ).replace( match[ 0 ], replacement );
			rgx.lastIndex = match.index + replacement.length;

			//console.info('replace', match[0], 'for', replacement, 'at', match.index, 'in', match.input, 'next on', rgx.lastIndex );
		}

		return input;
	}

	// Replace array string elements with variables
	function replaceArray( input, vars ) {

		for ( var i = 0; i < input.length; i++ ) {
			input[ i ] = replace( input[ i ], vars );
		}

		return input;

	}

	// Replaces oboject string members with variables
	function replaceObject( input, vars ) {

		var keys = Object.keys( input );
		keys.forEach( function( key ) {
			input[ key ] = replace( input[ key ], vars );
		} );

		return input;
	}

	// TODO: Register active processes for killing;

	// Publishing a reference
	module.exports = commands;

} )( window, atom, require, module );
<commit_msg>Reverted experimental and incomplete changes.<commit_after>( function( window, atom, require, module, undefined ) {
	'use strict';

	// Imports
	var atomUtils = require( 'atom' );
	var spawn = require( 'win-spawn' );

	// Instance
	var commands = {
		subscriptions: new atomUtils.CompositeDisposable(),
		panel: null,
		config: require( './config' )
	}

	commands.activate = function( state ) {

		// Define and update a command list from the user config
		var registeredAtomCommands = [];

		atom.config.observe( 'atom-user-commands', {}, function( value ) {

			// Dispose old commands
			registeredAtomCommands.forEach( function( disposable ) {

				// Remove it from subscriptions and...
				commands.subscriptions.remove( disposable );

				// ... dispose it manually
				disposable.dispose();
			} );

			registeredAtomCommands = [];

			// Register new commands
			value.commands.forEach( function( command ) {

				// Create an atom command for each entry
				var commandName = 'atom-user-commands:' + command.name;
				var atomCommand = atom.commands.add( command.selector, commandName, function() {

					execute( command.command, command.arguments, command.options );
				} )

				// Create a menu entry for each command
				var menuEntry = atom.menu.add( [ {
					label : 'Packages',
					submenu: [ {
						label: 'Atom User Commands',
						submenu: [
							{
								label: command.name,
								command: commandName
							}
						]
					} ]
				} ] );

				// Register it in the subscriptions;
				registeredAtomCommands.push( atomCommand );
				registeredAtomCommands.push( menuEntry );

				commands.subscriptions.add( atomCommand );
				commands.subscriptions.add( menuEntry );
			} );
		} );
	}

	commands.deactivate = function() {
		commands.panel.destroy();
		commands.subscriptions.dispose();
	}

	commands.serialize = function() {
		return {};
	}

	// Create a bottom panel for the output
	function showConsole() {

		if ( !commands.panel ) {

			commands.panel = atom.workspace.addBottomPanel( {
				item: buildPanel(),
				visible: true,
				priority: 100
			} )
		};
	}

	// Destroy de bottom panel
	function hideConsole() {

		if ( commands.panel ) {
			commands.panel.destroy();
			commands.panel = null;
		}
	}

	// Execute an OS command
	function execute( command, args, options ) {

		// Open the panel if it is not
		if ( !commands.panel ) {
			showConsole();
		}

		// Cancel the close console listener
		if (commands.closeConsoleDisposable) {
			commands.closeConsoleDisposable.dispose();
			commands.subscriptions.remove(commands.closeConsoleDisposable);
		}

		var env = getEnv();

		command = replace( command || '', env );
		args = replace( args || [], env );
		options = replace( options || {}, env );

		// Announcing launch
		commands.panel.item.appendChild( window.document.createElement( 'br' ) );
		var span = window.document.createElement( 'span' );
		span.classList.add( 'echo' );
		span.textContent = "> " + command + ' ' + JSON.stringify( args ) + ' ' + JSON.stringify( options );
		commands.panel.item.appendChild( span );
		commands.panel.item.appendChild( window.document.createElement( 'br' ) );
		commands.panel.item.appendChild( window.document.createElement( 'br' ) );

		// Run the spawn, we pass args.slice() to make a shallow copy of the array because spawn will modify it.
		var proc = spawn( command, args.slice(), options );

		// Update console panel on data
		proc.stdout.on( 'data', function( data ) {

			var div = commands.panel.item;
			var line = window.document.createElement( 'div' );
			line.classList.add( 'stdout' );
			line.textContent = data.toString();
			div.appendChild( line );
			div.scrollTop = div.scrollHeight;

		} );

		// Update console panel on error data
		proc.stderr.on( 'data', function( data ) {

			var div = commands.panel.item;
			var line = window.document.createElement( 'div' );
			line.classList.add( 'stderr' );
			line.textContent = data.toString();
			div.appendChild( line );
			div.scrollTop = div.scrollHeight;
		} );

		proc.stdout.on( 'close', function( code, signal ) {
			// console.info('command closed', code, signal);
		} );

		// Register code for termination
		proc.stderr.on( 'close', function( code, signal ) {

			// Register an action for panel destruction
			commands.closeConsoleDisposable = atom.commands.add( 'atom-workspace', 'core:cancel', function() {
				hideConsole()
				commands.closeConsoleDisposable.dispose();
				commands.subscriptions.remove( commands.closeConsoleDisposable );
			} )

			commands.subscriptions.add( commands.closeConsoleDisposable );
		} );
	}

	// Set up the HTML element
	function buildPanel() {

		var mainDiv = window.document.createElement( 'div' );
		mainDiv.classList.add( 'atom-user-commands-console' );

		//var input = window.document.createElement( 'textarea' );
		//input.classList.add( 'console-input' );
		//mainDiv.appendChild(input);

		return mainDiv;

	}

	// Generate Environment variables
	function getEnv() {

		var paths = atom.project.relativizePath( atom.workspace.getActiveTextEditor().getPath() );
		var env = {
			project: paths[ 0 ],
			path: paths[ 1 ],
			absPath: atom.workspace.getActiveTextEditor().getPath()
		};

		return env;
	}

	// Replace members with env variables.
	function replace( input, vars ) {

		// Dispatch input type
		if ( !input ) {
			return;
		} else if ( typeof input == 'string' ) {
			return replaceString( input, vars );
		} else if ( Array.isArray( input ) ) {
			return replaceArray( input, vars );
		} else if ( typeof input == 'object' ) {
			return replaceObject( input, vars );
		} else {
			return input;
		}
	}

	// replace a string with vars.
	function replaceString( input, vars ) {

		var rgx = /{({?)(\w+)(}?)}/g

		var match = null;
		while ( match = rgx.exec( input ) ) {

			// {? + variable + }? so {{arg}} -> {arg}
			var key = match[ 1 ] + match[ 2 ] + match[ 3 ];
			var replacement = vars[ key ] || key;

			// Replace the result only on the remaining string
			input = input.substring( 0, match.index ) + input.substring( match.index ).replace( match[ 0 ], replacement );
			rgx.lastIndex = match.index + replacement.length;

			//console.info('replace', match[0], 'for', replacement, 'at', match.index, 'in', match.input, 'next on', rgx.lastIndex );
		}

		return input;
	}

	// Replace array string elements with variables
	function replaceArray( input, vars ) {

		for ( var i = 0; i < input.length; i++ ) {
			input[ i ] = replace( input[ i ], vars );
		}

		return input;

	}

	// Replaces oboject string members with variables
	function replaceObject( input, vars ) {

		var keys = Object.keys( input );
		keys.forEach( function( key ) {
			input[ key ] = replace( input[ key ], vars );
		} );

		return input;
	}

	// TODO: Register active processes for killing;

	// Publishing a reference
	module.exports = commands;

} )( window, atom, require, module );
<|endoftext|>


<commit_before>var _           = require('lodash');
var AssetLoader	= require('./assetLoader');

/**
 * SceneParser class
 * @param {object} param
 * @constructor
 */
function SceneParser() {
  if (SceneParser._instance === null) {
    SceneParser.prototype.init.apply(this, arguments);
    SceneParser.type = 'babylon';
    SceneParser._instance = this;
  } else {
    return SceneParser._instance;
  }
}

var proto = SceneParser.prototype;

proto.init = function(param) {
  param = param || {};
  this.sceneUrl = param.url;
  if (!this.sceneUrl) {
  	throw new Error('Scene should have an Url');
  }
  this.assetLoader = new AssetLoader();
  this.assetLoader.getFile(this.sceneUrl).then(function success() {

  }, function failure() {

  });
  /*
  this.assetLoader.push(this.sceneUrl);
  this.assetLoader.once(this.sceneUrl, this.parseScene.bind(this));
  this.assetLoader.start();
  */
};

proto.parseScene = function() {
	this.scene = this.assetLoader.resources[this.sceneUrl];

};

proto.parseMesh = function(mesh) {

};

//static
SceneParser._instance = null;
SceneParser.getInstance = function() {
  return SceneParser._instance;
};

module.exports = SceneParser;
<commit_msg>Fix scene parser handlers<commit_after>var _           = require('lodash');
var AssetLoader	= require('./assetLoader');

/**
 * SceneParser class
 * @param {object} param
 * @constructor
 */
function SceneParser() {
  if (SceneParser._instance === null) {
    SceneParser.prototype.init.apply(this, arguments);
    SceneParser.type = 'babylon';
    SceneParser._instance = this;
  } else {
    return SceneParser._instance;
  }
}

var proto = SceneParser.prototype;

proto.init = function(param) {
  param = param || {};
  this.sceneUrl = param.url;
  if (!this.sceneUrl) {
  	throw new Error('Scene should have an Url');
  }
  this.assetLoader = new AssetLoader();
  this.assetLoader.getFile(this.sceneUrl)
  	.then(this.parseScene.bind(this), function failure() {

  	});
};

proto.parseScene = function(scene) {
	this.scene = scene;

};

proto.parseMesh = function(mesh) {

};

//static
SceneParser._instance = null;
SceneParser.getInstance = function() {
  return SceneParser._instance;
};

module.exports = SceneParser;
<|endoftext|>


<commit_before>'use strict'
var Base = require('../')
var define = Object.defineProperty

/**
 * @function createContextGetter
 * @memberOf Base#
 * @param  {string} key - Key to create the context getter for
 */
exports.createContextGetter = function (key) {
  // if (!this['_' + key]) {
    let cont = this._context
    let level = this._contextLevel
    let value = this.contextCandidate(key)
    if (!value) {
      // if(key !== '_parent' && )
      key = '_' + key
      value = this[key]
      if (
        value &&
        this.hasOwnProperty(key) &&
        // make it smart here
        !value.hasOwnProperty('_Constructor') &&
        value._Constructor
      ) {
        // console.log('ROUND 2', key)
        for (let val_key in value) {
          // console.log('level 2 lets make!', val_key)
          value.createContextGetter(val_key)
        }
      }
    } else if (value) {
      // console.log('ok ok', key)
      let privateKey = '_' + key
      this[privateKey] = value
      for (let val_key in value) {
        // console.log('2 -- ok ok', val_key)
        value.createContextGetter(val_key)
      }
      define(this, key, {
        get () {
          var value = this[privateKey]
          if (value instanceof Base) {
            if (!this.hasOwnProperty(privateKey)) {
              value._context = this
              value._contextLevel = 1
            } else if (this._context) {
              value._contextLevel = this._contextLevel + 1
              value._context = this._context
            } else {
              value.clearContext()
            }
          }
          return value
        },
        set (val) {
          this[privateKey] = val
        },
        // enumerable: false,
        configurable: true
      })
    }
    if (!cont) {
      this.clearContext()
    } else if (cont !== this._context) {
      this._context = cont
      this._contextLevel = level
    }
  // }
}

/**
 * @function resolveContext
 * resolves context sets
 * @memberOf Base#
 * @param {*} val set value to be resolved
 * @param {event} event current event
 * @param {base} context resolve this context
 * @param {boolean} alwaysreturn when set to true always returns resolved base
 * @type {base|undefined}
 */
exports.resolveContext = function (val, event, context, target, path) {
  context = context || this._context
  var i = this._contextLevel
  var path
  var prevContext
  var level = i

  if (!target) {
    target = this
  }

  var iterator = target

  if (!path) {
    path = pathMaker(path, iterator, i)
  }

  if (context._context) {
    let cpath = pathMaker(false, context, context._contextLevel)

    // so we need the whole chain stored and applied for this probably...

    context = context.resolveContext(val, event, context._context, target, cpath.concat(path))
    return
  }

  var pathLength = path.length
  var pathLengthCompare = pathLength - 1

  for (i = 0; i < pathLength; i++) {
    if (context) {
      prevContext = context
      let segment = path[i]
      let key = typeof segment === 'string' ? segment : segment.key
      let prop = context[key] || segment.__contextTarget__
      let set
      let property

      if (i === pathLengthCompare) {
        set = val
      } else {
        set = {}
      }

      context = context.setKeyInternal(key, set, prop, event, true)
      if (!context) {
        context = prevContext[key]
      }
    }
  }
  this.clearContextUp(level)
  return context
}

function pathMaker (path, iterator, i) {
  path = path || []
  while (i) {
    let key = iterator.key
    if (iterator._contextKey) {
      path.unshift({ key: key, __contextTarget__: iterator })
    } else {
      path.unshift(key)
    }
    // lp = iterator
    iterator = iterator._parent
    i--
  }
  return path
}<commit_msg>removed logs<commit_after>'use strict'
var Base = require('../')
var define = Object.defineProperty

/**
 * @function createContextGetter
 * @memberOf Base#
 * @param  {string} key - Key to create the context getter for
 */
exports.createContextGetter = function (key) {
  // if (!this['_' + key]) {
    let cont = this._context
    let level = this._contextLevel
    let value = this.contextCandidate(key)
    if (!value) {
      // if(key !== '_parent' && )
      key = '_' + key
      value = this[key]
      if (
        value &&
        this.hasOwnProperty(key) &&
        // make it smart here
        !value.hasOwnProperty('_Constructor') &&
        value._Constructor
      ) {
        // console.log('ROUND 2', key)
        for (let val_key in value) {
          // console.log('level 2 lets make!', val_key)
          value.createContextGetter(val_key)
        }
      }
    } else if (value) {
      // console.log('ok ok', key)
      let privateKey = '_' + key
      this[privateKey] = value
      for (let val_key in value) {
        // console.log('2 -- ok ok', val_key)
        value.createContextGetter(val_key)
      }
      define(this, key, {
        get () {
          var value = this[privateKey]
          if (value instanceof Base) {
            if (!this.hasOwnProperty(privateKey)) {
              value._context = this
              value._contextLevel = 1
            } else if (this._context) {
              value._contextLevel = this._contextLevel + 1
              value._context = this._context
            } else {
              value.clearContext()
            }
          }
          return value
        },
        set (val) {
          this[privateKey] = val
        },
        // enumerable: false,
        configurable: true
      })
    }
    if (!cont) {
      this.clearContext()
    } else if (cont !== this._context) {
      this._context = cont
      this._contextLevel = level
    }
  // }
}

/**
 * @function resolveContext
 * resolves context sets
 * @memberOf Base#
 * @param {*} val set value to be resolved
 * @param {event} event current event
 * @param {base} context resolve this context
 * @param {boolean} alwaysreturn when set to true always returns resolved base
 * @type {base|undefined}
 */
exports.resolveContext = function (val, event, context, target, path) {
  context = context || this._context
  var i = this._contextLevel
  var path
  var prevContext
  var level = i

  if (!target) {
    target = this
  }

  var iterator = target

  if (!path) {
    path = pathMaker(path, iterator, i)
  }

  if (context._context) {
    let cpath = pathMaker(false, context, context._contextLevel)
    // so we need the whole chain stored and applied for this probably...
    context = context.resolveContext(val, event, context._context, target, cpath.concat(path))
    return
  }

  var pathLength = path.length
  var pathLengthCompare = pathLength - 1

  for (i = 0; i < pathLength; i++) {
    if (context) {
      prevContext = context
      let segment = path[i]
      let key = typeof segment === 'string' ? segment : segment.key
      let prop = context[key] || segment.__contextTarget__
      let set
      let property

      if (i === pathLengthCompare) {
        set = val
      } else {
        set = {}
      }

      context = context.setKeyInternal(key, set, prop, event, true)
      if (!context) {
        context = prevContext[key]
      }
    }
  }
  this.clearContextUp(level)
  return context
}

function pathMaker (path, iterator, i) {
  path = path || []
  while (i) {
    let key = iterator.key
    if (iterator._contextKey) {
      path.unshift({ key: key, __contextTarget__: iterator })
    } else {
      path.unshift(key)
    }
    // lp = iterator
    iterator = iterator._parent
    i--
  }
  return path
}<|endoftext|>


<commit_before>angular.module('WorkView').controller('navBarController', ['$scope', '$filter', '$cookieStore', '$location', '$modal', 'ProjectsFactory', 'FullscreenFactory', function($scope, $filter, $cookieStore, $location, $modal, projectsFactory, fullscreenFactory) {
    //all projects sorted in alpabetical order
    $scope.projects = [];
    //a subset of projects after being filtered by the current search term
    $scope.filteredProjects = [];

    //keeps track of all project not being displayed in the wall board
    $scope.uncheckedProjectIds = [];

    //the current search term
    $scope.query = '';

    $scope.firstChar = true;

    /*----- Project Filtering -----*/

    $scope.search = function(item) {
        var query = $scope.query.toLowerCase();
        var group = item.group.toLowerCase();
        var name = item.name.toLowerCase();
        return name.indexOf(query) !== -1 || group.indexOf(query) !== -1;
    };

    //listens for newProject events
    $scope.$on('newProject', function(event, project) {
        //set the included field on the project
        project.included = !$scope.contains($scope.uncheckedProjectIds, project.id);

        //then add the project to the search/filter and sort by the name
        $scope.projects.push(project);
        $scope.projects = $filter('orderBy')($scope.projects, 'name');
    });

    //listens for deleteProject events
    $scope.$on('deleteProject', function(event, project) {
        //if scope.projects contains the project being deleted remove it
        var index = $scope.projects.indexOf(project);
        if(index > -1) {
            $scope.projects.splice(index, 1);
        }
    });

    // returns whether the given object is contained in the given list
    $scope.contains = function(a, obj) {
        for(var i = a.length - 1; i >= 0; i--) {
            if (a[i] === obj) {
                return true;
            }
        }
        return false;
    };

    //clears the checkbox for all checkboxes in the current filter list
    $scope.clearCheckboxes = function() {
        angular.forEach($scope.filteredProjects, function(project) {
            if(project.included) {
                project.included = false;
                $scope.checkProject(project);
            }
        });
    };

    //checks the checkbox for all checkboxes in the current filter list
    $scope.checkCheckboxes = function() {
        angular.forEach($scope.filteredProjects, function(project) {
            if(!project.included) {
                project.included = true;
                $scope.checkProject(project);
            }
        });
    };

    //on checkbox change
    $scope.checkProject = function(project) {
        //if included is set remove the project from the unchecked list
        if(project.included) {
            var index = $scope.uncheckedProjectIds.indexOf(project.id);
            if(index > -1) {
                $scope.uncheckedProjectIds.splice(index, 1);
            }
        }
        //else push the id onto the unchecked list
        else {
            $scope.uncheckedProjectIds.push(project.id);
        }

        //finally update variables and cookies relying on the unchecked list
        $scope.cookieState();
    };

    // updates the cookie, embedded url, and location url
    $scope.cookieState = function() {
        $cookieStore.remove('projectIds');
        $cookieStore.put('projectIds', $scope.uncheckedProjectIds);

        var idString = '';
        if ($scope.uncheckedProjectIds) {
        	idString = $scope.uncheckedProjectIds.join();
        }
        $location.search('ids', idString);
    };

    $scope.initialClear = function() {
        if($scope.firstChar) {
            $scope.firstChar = false;
            $scope.clearCheckboxes();
        }
    };

    /*----- Time Filtering -----*/
    $scope.filterDays = projectsFactory.getFilterDays();

    $scope.changeFilterDays = function(number) {
        if(number !== $scope.filterDays) {
            $scope.filterDays = number;
            $scope.$emit('hideEpics', null);
            projectsFactory.setFilterDays(number);
        }
    };

    /*----- Fullscreen Toggle -----*/
    $scope.isFullscreen = fullscreenFactory.getFullscreen();

    $scope.toggleFullscreen = function() {
        //tell the factory to toggle the fullscreen variable
        fullscreenFactory.toggleFullscreen();
        //update our copy
        $scope.isFullscreen = fullscreenFactory.getFullscreen();

        //lastly toggle the header and footer elements in the page
        jQuery('header').animate({opacity: 'toggle', height: 'toggle'});
        jQuery('footer').animate({opacity: 'toggle', height: 'toggle'});
    };

    /*----- Info Modal -----*/
    $scope.open = function() {
        var modal = $modal.open({
            templateUrl: 'info.html'
        });

        var unregister = $scope.$parent.$on('hideModal', function() {
            modal.dismiss('');
            unregister();
        });
    };

    /*----- controller initialization code -----*/

    $scope.init = function() {
        //initialize the filtered project ids to what is stored in the cookie
        $scope.uncheckedProjectIds = $cookieStore.get('projectIds');
        // sometimes gets set to '' instead of undefined, not sure why
        if($scope.uncheckedProjectIds === undefined || $scope.uncheckedProjectIds === '') {
            $scope.uncheckedProjectIds = [];
            $cookieStore.put('projectIds', $scope.uncheckedProjectIds);
        }

        //will reinitialize the filtered projects to the given ids
        var urlFilterIds = $location.search().ids;
        if(urlFilterIds !== undefined && urlFilterIds.length > 0) {
            var ids = urlFilterIds.split(',');
            $scope.uncheckedProjectIds = [];

            angular.forEach(ids, function(id) {
                $scope.uncheckedProjectIds.push(parseInt(id));
            });
        }

        $scope.cookieState();
    };

    $scope.init();
}]);<commit_msg>added a comment<commit_after>angular.module('WorkView').controller('navBarController', ['$scope', '$filter', '$cookieStore', '$location', '$modal', 'ProjectsFactory', 'FullscreenFactory', function($scope, $filter, $cookieStore, $location, $modal, projectsFactory, fullscreenFactory) {
    //all projects sorted in alpabetical order
    $scope.projects = [];
    //a subset of projects after being filtered by the current search term
    $scope.filteredProjects = [];

    //keeps track of all project not being displayed in the wall board
    $scope.uncheckedProjectIds = [];

    //the current search term
    $scope.query = '';

    $scope.firstChar = true;

    /*----- Project Filtering -----*/

    // return whether the given item should be included for this query
    $scope.search = function(item) {
        var query = $scope.query.toLowerCase();
        var group = item.group.toLowerCase();
        var name = item.name.toLowerCase();
        return name.indexOf(query) !== -1 || group.indexOf(query) !== -1;
    };

    //listens for newProject events
    $scope.$on('newProject', function(event, project) {
        //set the included field on the project
        project.included = !$scope.contains($scope.uncheckedProjectIds, project.id);

        //then add the project to the search/filter and sort by the name
        $scope.projects.push(project);
        $scope.projects = $filter('orderBy')($scope.projects, 'name');
    });

    //listens for deleteProject events
    $scope.$on('deleteProject', function(event, project) {
        //if scope.projects contains the project being deleted remove it
        var index = $scope.projects.indexOf(project);
        if(index > -1) {
            $scope.projects.splice(index, 1);
        }
    });

    // returns whether the given object is contained in the given list
    $scope.contains = function(a, obj) {
        for(var i = a.length - 1; i >= 0; i--) {
            if (a[i] === obj) {
                return true;
            }
        }
        return false;
    };

    //clears the checkbox for all checkboxes in the current filter list
    $scope.clearCheckboxes = function() {
        angular.forEach($scope.filteredProjects, function(project) {
            if(project.included) {
                project.included = false;
                $scope.checkProject(project);
            }
        });
    };

    //checks the checkbox for all checkboxes in the current filter list
    $scope.checkCheckboxes = function() {
        angular.forEach($scope.filteredProjects, function(project) {
            if(!project.included) {
                project.included = true;
                $scope.checkProject(project);
            }
        });
    };

    //on checkbox change
    $scope.checkProject = function(project) {
        //if included is set remove the project from the unchecked list
        if(project.included) {
            var index = $scope.uncheckedProjectIds.indexOf(project.id);
            if(index > -1) {
                $scope.uncheckedProjectIds.splice(index, 1);
            }
        }
        //else push the id onto the unchecked list
        else {
            $scope.uncheckedProjectIds.push(project.id);
        }

        //finally update variables and cookies relying on the unchecked list
        $scope.cookieState();
    };

    // updates the cookie, embedded url, and location url
    $scope.cookieState = function() {
        $cookieStore.remove('projectIds');
        $cookieStore.put('projectIds', $scope.uncheckedProjectIds);

        var idString = '';
        if ($scope.uncheckedProjectIds) {
        	idString = $scope.uncheckedProjectIds.join();
        }
        $location.search('ids', idString);
    };

    $scope.initialClear = function() {
        if($scope.firstChar) {
            $scope.firstChar = false;
            $scope.clearCheckboxes();
        }
    };

    /*----- Time Filtering -----*/
    $scope.filterDays = projectsFactory.getFilterDays();

    $scope.changeFilterDays = function(number) {
        if(number !== $scope.filterDays) {
            $scope.filterDays = number;
            $scope.$emit('hideEpics', null);
            projectsFactory.setFilterDays(number);
        }
    };

    /*----- Fullscreen Toggle -----*/
    $scope.isFullscreen = fullscreenFactory.getFullscreen();

    $scope.toggleFullscreen = function() {
        //tell the factory to toggle the fullscreen variable
        fullscreenFactory.toggleFullscreen();
        //update our copy
        $scope.isFullscreen = fullscreenFactory.getFullscreen();

        //lastly toggle the header and footer elements in the page
        jQuery('header').animate({opacity: 'toggle', height: 'toggle'});
        jQuery('footer').animate({opacity: 'toggle', height: 'toggle'});
    };

    /*----- Info Modal -----*/
    $scope.open = function() {
        var modal = $modal.open({
            templateUrl: 'info.html'
        });

        var unregister = $scope.$parent.$on('hideModal', function() {
            modal.dismiss('');
            unregister();
        });
    };

    /*----- controller initialization code -----*/

    $scope.init = function() {
        //initialize the filtered project ids to what is stored in the cookie
        $scope.uncheckedProjectIds = $cookieStore.get('projectIds');
        // sometimes gets set to '' instead of undefined, not sure why
        if($scope.uncheckedProjectIds === undefined || $scope.uncheckedProjectIds === '') {
            $scope.uncheckedProjectIds = [];
            $cookieStore.put('projectIds', $scope.uncheckedProjectIds);
        }

        //will reinitialize the filtered projects to the given ids
        var urlFilterIds = $location.search().ids;
        if(urlFilterIds !== undefined && urlFilterIds.length > 0) {
            var ids = urlFilterIds.split(',');
            $scope.uncheckedProjectIds = [];

            angular.forEach(ids, function(id) {
                $scope.uncheckedProjectIds.push(parseInt(id));
            });
        }

        $scope.cookieState();
    };

    $scope.init();
}]);<|endoftext|>


<commit_before>/*
 * Copyright 2016 Studentmediene i Trondheim AS
 *
 * 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.
 */

'use strict';

angular.module('momusApp.controllers')
    .controller('DispositionCtrl', function ($scope, $routeParams, ArticleService, PublicationService, MessageModal, $location, $modal, $templateRequest, $window) {
        $scope.pubId = $routeParams.id;
        $scope.loading = 5;
        $scope.newPageAt = 0;
        $scope.numNewPages = 1;
        $scope.editPhotoStatus = false;

        if($scope.pubId){
            PublicationService.getById($scope.pubId).success(function(data) {
                if(!data){
                    $location.path("/");
                    return;
                }
                $scope.publication = data;
                $scope.getPages();
            });
        } else{
            PublicationService.getAll().success(function(data){
                $scope.publication = PublicationService.getActive(data);
                $scope.getPages();
            });
        }

        $scope.getPages = function(){
            var pubId = $scope.publication.id;
            ArticleService.search({publication: pubId}).success(function (data) {
                $scope.publication.articles = data;
                $scope.loading--;
                PublicationService.getPages(pubId).success(function (data){
                    $scope.publication.pages = data;
                    PublicationService.linkPagesToArticles($scope.publication.pages, $scope.publication.articles);
                    $scope.loading--;
                });
            });

            ArticleService.getReviews().success(function(data){
                $scope.reviewOptions = data;
                $scope.loading--;
            });

            ArticleService.getStatuses().success(function(data){
                $scope.statusOptions = data;
                $scope.loading--;
            });

            PublicationService.getLayoutStatuses().success(function(data){
                $scope.layoutStatuses = data;
                $scope.loading--;
            });
        };

        $scope.showHelp = function(){
            MessageModal.info("
Genererer en disposisjon etter beste evne. Bruker artiklene i den gjeldende utgaven til å " +
                "generere en standarddisposisjon");
        };

        $scope.generateDispBtn = function(){
            if($scope.publication.pages.length == 0){
                $scope.generateDisp();
            } else if(confirm("Dette vil overskrive den nåværende disposisjonen")){
                $scope.generateDisp();
            }
        };

        /*
        *   Not used at the moment, left here in case it's wanted later
        */
        $scope.generateDisp = function(){
            PublicationService.generateDisp($scope.publication.id).success(function(data){
                $scope.publication.pages = data;
            })
        };

        $scope.savePublication = function() {
            PublicationService.updateMetadata($scope.publication).success(function(data){
                $scope.getPages();
            });
        };

        $scope.deletePage = function(page) {
            if(confirm("Er du sikker på at du vil slette denne siden?")){
                PublicationService.deletePage(page.id).success(function(){
                    PublicationService.getPages($scope.publication.id).success(function(data){
                        $scope.publication.pages = data;
                        sortPages();
                        $scope.savePublication();
                    });
                });
            }
        };

        $scope.newPage = function(){
            var insertPageAt = $scope.newPageAt;
            var numNewPages = $scope.numNewPages;
            if(numNewPages>100){
                numNewPages = 100;
            }else if(numNewPages <= 0){
                numNewPages = 1;
            }
            for(var i = 0; i < numNewPages; i++) {
                var temp_page = {
                    page_nr: $scope.publication.pages.length + 1,
                    note: null,
                    advertisement: false,
                    articles: [],
                    publication: $scope.publication.id,
                    layout_status: $scope.getLayoutStatusByName("Ukjent")
                };
                    if (0 <= insertPageAt && insertPageAt <= $scope.publication.pages.length) {
                        $scope.publication.pages.splice(insertPageAt, 0, temp_page);
                    } else {
                        $scope.publication.pages.push(data);
                    }
                    sortPages();
            }
            $scope.savePublication();
        };

        function sortPages(){
            for ( var i = 0; i < $scope.publication.pages.length; i++ ) {
                $scope.publication.pages[i].page_nr = i+1;
            }
        }

        $scope.savePage = function() {
            PublicationService.updateMetadata($scope.publication);
        };

        $scope.getLayoutStatusByName = function(name){
            for(var i = 0; i < $scope.layoutStatuses.length; i++){
                if($scope.layoutStatuses[i].name == name){
                    return $scope.layoutStatuses[i];
                }
            }
            return null;
        };

        $scope.createArticle = function(page){
            var modal = $modal.open({
                templateUrl: 'partials/article/createArticleModal.html',
                controller: 'CreateArticleModalCtrl',
                resolve: {
                    pubId: function(){
                        return $scope.publication.id;
                    }
                }
            });
            modal.result.then(function(id){
                ArticleService.getArticle(id).success(function(data){
                    page.articles.push(data);
                    $scope.publication.articles.push(data);
                    $scope.savePage();
                })
            })

        };

        $scope.saveArticle = function(article){
            ArticleService.updateMetadata(article);
        };

        $scope.sortableOptions = {
            helper: function(e, ui) {
                var c = ui.clone();
                c.addClass("disp-helper");
                return c;
            },
            axis: 'y',
            handle: '.handle',
            stop: function(e, ui){
                $scope.selectedPage = $scope.publication.pages[ui.item.index()];
                sortPages();
                PublicationService.updateMetadata($scope.publication);
            },
            placeholder: "disp-placeholder"
        };

        $scope.showHelp = function(){
            $templateRequest('partials/templates/help/dispHelp.html').then(function(template){
                MessageModal.info(template);
            });
        };

        $scope.responsiveCSS = {
            comment: {minWidth: '100px'},
            name: {minWidth: '100px'},
            journalist: {minWidth: '60px'},
            photographer: {minWidth: '60px'},
            pstatus: {minWidth: '90px'}
        };

        $scope.updateDispSize = function(){
            var constantArticleSize = 320;
            var constantDispSize = constantArticleSize + 190;
            var dispWidth = angular.element(document.getElementById("disposition")).context.clientWidth;

            //Don't resize if disp is too small
            if(dispWidth < 990){
                return;
            }

            //Must divide rest of width between journalists, photographers, photostatus and comment. leaving some wiggle room
            var widthLeft = dispWidth - constantDispSize - 10;
            var shareParts = {
                name: 0.25,
                journalist: 0.2,
                photographer: 0.2,
                pstatus: 0.15,
                comment: 0.2
            };
            for(var k in shareParts){
                var width = Math.floor(shareParts[k]*widthLeft);
                $scope.responsiveCSS[k] = {minWidth: width + 'px', maxWidth: width + 'px', width: width + 'px'}
            }
        };

        angular.element($window).bind('resize', function(){
            $scope.updateDispSize();
            $scope.$apply();
        });

        $scope.updateDispSize();
    });
<commit_msg>Fixed an overflow bug on small screens<commit_after>/*
 * Copyright 2016 Studentmediene i Trondheim AS
 *
 * 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.
 */

'use strict';

angular.module('momusApp.controllers')
    .controller('DispositionCtrl', function ($scope, $routeParams, ArticleService, PublicationService, MessageModal, $location, $modal, $templateRequest, $window) {
        $scope.pubId = $routeParams.id;
        $scope.loading = 5;
        $scope.newPageAt = 0;
        $scope.numNewPages = 1;
        $scope.editPhotoStatus = false;

        if($scope.pubId){
            PublicationService.getById($scope.pubId).success(function(data) {
                if(!data){
                    $location.path("/");
                    return;
                }
                $scope.publication = data;
                $scope.getPages();
            });
        } else{
            PublicationService.getAll().success(function(data){
                $scope.publication = PublicationService.getActive(data);
                $scope.getPages();
            });
        }

        $scope.getPages = function(){
            var pubId = $scope.publication.id;
            ArticleService.search({publication: pubId}).success(function (data) {
                $scope.publication.articles = data;
                $scope.loading--;
                PublicationService.getPages(pubId).success(function (data){
                    $scope.publication.pages = data;
                    PublicationService.linkPagesToArticles($scope.publication.pages, $scope.publication.articles);
                    $scope.loading--;
                });
            });

            ArticleService.getReviews().success(function(data){
                $scope.reviewOptions = data;
                $scope.loading--;
            });

            ArticleService.getStatuses().success(function(data){
                $scope.statusOptions = data;
                $scope.loading--;
            });

            PublicationService.getLayoutStatuses().success(function(data){
                $scope.layoutStatuses = data;
                $scope.loading--;
            });
        };

        $scope.showHelp = function(){
            MessageModal.info("
Genererer en disposisjon etter beste evne. Bruker artiklene i den gjeldende utgaven til å " +
                "generere en standarddisposisjon");
        };

        $scope.generateDispBtn = function(){
            if($scope.publication.pages.length == 0){
                $scope.generateDisp();
            } else if(confirm("Dette vil overskrive den nåværende disposisjonen")){
                $scope.generateDisp();
            }
        };

        /*
        *   Not used at the moment, left here in case it's wanted later
        */
        $scope.generateDisp = function(){
            PublicationService.generateDisp($scope.publication.id).success(function(data){
                $scope.publication.pages = data;
            })
        };

        $scope.savePublication = function() {
            PublicationService.updateMetadata($scope.publication).success(function(data){
                $scope.getPages();
            });
        };

        $scope.deletePage = function(page) {
            if(confirm("Er du sikker på at du vil slette denne siden?")){
                PublicationService.deletePage(page.id).success(function(){
                    PublicationService.getPages($scope.publication.id).success(function(data){
                        $scope.publication.pages = data;
                        sortPages();
                        $scope.savePublication();
                    });
                });
            }
        };

        $scope.newPage = function(){
            var insertPageAt = $scope.newPageAt;
            var numNewPages = $scope.numNewPages;
            if(numNewPages>100){
                numNewPages = 100;
            }else if(numNewPages <= 0){
                numNewPages = 1;
            }
            for(var i = 0; i < numNewPages; i++) {
                var temp_page = {
                    page_nr: $scope.publication.pages.length + 1,
                    note: null,
                    advertisement: false,
                    articles: [],
                    publication: $scope.publication.id,
                    layout_status: $scope.getLayoutStatusByName("Ukjent")
                };
                    if (0 <= insertPageAt && insertPageAt <= $scope.publication.pages.length) {
                        $scope.publication.pages.splice(insertPageAt, 0, temp_page);
                    } else {
                        $scope.publication.pages.push(data);
                    }
                    sortPages();
            }
            $scope.savePublication();
        };

        function sortPages(){
            for ( var i = 0; i < $scope.publication.pages.length; i++ ) {
                $scope.publication.pages[i].page_nr = i+1;
            }
        }

        $scope.savePage = function() {
            PublicationService.updateMetadata($scope.publication);
        };

        $scope.getLayoutStatusByName = function(name){
            for(var i = 0; i < $scope.layoutStatuses.length; i++){
                if($scope.layoutStatuses[i].name == name){
                    return $scope.layoutStatuses[i];
                }
            }
            return null;
        };

        $scope.createArticle = function(page){
            var modal = $modal.open({
                templateUrl: 'partials/article/createArticleModal.html',
                controller: 'CreateArticleModalCtrl',
                resolve: {
                    pubId: function(){
                        return $scope.publication.id;
                    }
                }
            });
            modal.result.then(function(id){
                ArticleService.getArticle(id).success(function(data){
                    page.articles.push(data);
                    $scope.publication.articles.push(data);
                    $scope.savePage();
                })
            })

        };

        $scope.saveArticle = function(article){
            ArticleService.updateMetadata(article);
        };

        $scope.sortableOptions = {
            helper: function(e, ui) {
                var c = ui.clone();
                c.addClass("disp-helper");
                return c;
            },
            axis: 'y',
            handle: '.handle',
            stop: function(e, ui){
                $scope.selectedPage = $scope.publication.pages[ui.item.index()];
                sortPages();
                PublicationService.updateMetadata($scope.publication);
            },
            placeholder: "disp-placeholder"
        };

        $scope.showHelp = function(){
            $templateRequest('partials/templates/help/dispHelp.html').then(function(template){
                MessageModal.info(template);
            });
        };

        $scope.responsiveCSS = {
            comment: {minWidth: '100px'},
            name: {minWidth: '100px'},
            journalist: {minWidth: '60px'},
            photographer: {minWidth: '60px'},
            pstatus: {minWidth: '90px'}
        };

        $scope.updateDispSize = function(){
            var constantArticleSize = 320;
            var constantDispSize = constantArticleSize + 190;
            var dispWidth = angular.element(document.getElementById("disposition")).context.clientWidth;

            //Don't resize if disp is too small
            if(dispWidth < 750){
                return;
            }

            //Must divide rest of width between journalists, photographers, photostatus and comment. leaving some wiggle room
            var widthLeft = dispWidth - constantDispSize - 10;
            var shareParts = {
                name: 0.25,
                journalist: 0.2,
                photographer: 0.2,
                pstatus: 0.15,
                comment: 0.2
            };
            for(var k in shareParts){
                var width = Math.floor(shareParts[k]*widthLeft);
                $scope.responsiveCSS[k] = {minWidth: width + 'px', maxWidth: width + 'px', width: width + 'px'}
            }
        };

        angular.element($window).bind('resize', function(){
            $scope.updateDispSize();
            $scope.$apply();
        });

        $scope.updateDispSize();
    });
<|endoftext|>


<commit_before>
/** @class IdP Selector UI */
function IdPSelectUIParms() {
    //
    // Adjust the following to fit into your local configuration
    //
    this.alwaysShow = true;          // If true, this will show results as soon as you start typing
    this.dataSource = window.location.hostname === 'localhost' ? '/resources/dev/sample-shib-identities.json' : '/Shibboleth.sso/DiscoFeed'; // where to get the data from (dev vs. prod)
    this.defaultLanguage = 'en';     // Language to use if the browser local doesnt have a bundle
    this.defaultLogo = 'resources/images/shib_no_logo.png';
    this.defaultLogoWidth = 1;
    this.defaultLogoHeight = 1;
//    this.defaultReturn = null;       // If non null, then the default place to send users who are not
    // Approaching via the Discovery Protocol for example
    //this.defaultReturn = "https://example.org/Shibboleth.sso/DS?SAMLDS=1&target=https://example.org/secure";

    if (window.location.href.search("redirectPage") > 0){
        redirectStr = urlParam('redirectPage');
        shibRedirectPage = encodeURIComponent("?redirectPage=" + redirectStr);
    }

    this.defaultReturn = window.location.protocol + "//" + window.location.hostname + "/Shibboleth.sso/Login?SAMLDS=1&target=" + window.location.protocol + "//" + window.location.hostname + "/shib.xhtml" + shibRedirectPage;
    this.defaultReturnIDParam = null;
    this.helpURL = 'http://guides.dataverse.org/en/latest/user/account.html';
    this.ie6Hack = null;             // An array of structures to disable when drawing the pull down (needed to
    // handle the ie6 z axis problem
    this.insertAtDiv = 'idpSelect';  // The div where we will insert the data
    this.maxResults = 10;            // How many results to show at once or the number at which to
    // start showing if alwaysShow is false
    this.myEntityID = null;          // If non null then this string must match the string provided in the DS parms
    this.preferredIdP = null;        // Array of entityIds to always show
    this.hiddenIdPs = null;          // Array of entityIds to delete
    this.ignoreKeywords = false;     // Do we ignore the <mdui:Keywords/> when looking for candidates
    this.showListFirst = true;      // Do we start with a list of IdPs or just the dropdown
    this.samlIdPCookieTTL = 730;     // in days
    this.setFocusTextBox = true;     // Set to false to supress focus
    this.testGUI = false;

    //
    // Globalization stuff
    //
    this.langBundles = {
        'en': {
            'fatal.divMissing': '<div> specified  as "insertAtDiv" could not be located in the HTML',
            'fatal.noXMLHttpRequest': 'Browser does not support XMLHttpRequest, unable to load IdP selection data',
            'fatal.wrongProtocol': 'Policy supplied to DS was not "urn:oasis:names:tc:SAML:profiles:SSO:idpdiscovery-protocol:single"',
            'fatal.wrongEntityId': 'entityId supplied by SP did not match configuration',
            'fatal.noData': 'Metadata download returned no data',
            'fatal.loadFailed': 'Failed to download metadata from ',
            'fatal.noparms': 'No parameters to discovery session and no defaultReturn parameter configured',
            'fatal.noReturnURL': "No URL return parameter provided",
            'fatal.badProtocol': "Return request must start with https:// or http://",
            'idpPreferred.label': 'Use a previous selection:',
            'idpEntry.label': 'Or enter your institution\'s name.',
            'idpEntry.NoPreferred.label': 'Enter your institution\'s name and click "Continue" to log in via your institution\'s authentication system.',
            'idpList.label': 'Or select your institution from the list below.',
            'idpList.NoPreferred.label': 'Select your institution and click "Continue" to log in via your institution\'s authentication system.',
            'idpList.defaultOptionLabel': 'Please select...',
            'idpList.showList': 'Allow me to pick from a list',
            'idpList.showSearch': 'Allow me to type the name of my institution',
            'submitButton.label': 'Continue',
            'helpText': 'Help',
            'defaultLogoAlt': ' '
        },
        'de': {
            'fatal.divMissing': 'Das notwendige Div Element fehlt',
            'fatal.noXMLHttpRequest': 'Ihr Webbrowser unterst\u00fctzt keine XMLHttpRequests, IdP-Auswahl kann nicht geladen werden',
            'fatal.wrongProtocol': 'DS bekam eine andere Policy als "urn:oasis:names:tc:SAML:profiles:SSO:idpdiscovery-protocol:single"',
            'fatal.wrongEntityId': 'Die entityId ist nicht korrekt',
            'fatal.loadFailed': 'Metadaten konnten nicht heruntergeladen werden: ',
            'fatal.noparms': 'Parameter f\u00fcr das Discovery Service oder \'defaultReturn\' fehlen',
            'fatal.noReturnURL': "URL return Parmeter fehlt",
            'fatal.badProtocol': "return Request muss mit https:// oder http:// beginnen",
            'idpPreferred.label': 'Vorherige Auswahl:',
            'idpEntry.label': 'Oder geben Sie den Namen (oder Teile davon) an:',
            'idpEntry.NoPreferred.label': 'Namen (oder Teile davon) der Institution angeben:',
            'idpList.label': 'Oder w\u00e4hlen Sie Ihre Institution aus einer Liste:',
            'idpList.NoPreferred.label': 'Institution aus folgender Liste w\u00e4hlen:',
            'idpList.defaultOptionLabel': 'W\u00e4hlen Sie Ihre Institution aus...',
            'idpList.showList': 'Institution aus einer Liste w\u00e4hlen',
            'idpList.showSearch': 'Institution selbst angeben',
            'submitButton.label': 'OK',
            'helpText': 'Hilfe',
            'defaultLogoAlt': 'Standard logo'
        },
        'ja': {
            'fatal.divMissing': '"insertAtDiv" の ID を持つ <div> が HTML 中に存在しません',
            'fatal.noXMLHttpRequest': 'ブラウザが XMLHttpRequest をサポートしていないので IdP 情報を取得できません',
            'fatal.wrongProtocol': 'DSへ渡された Policy パラメータが "urn:oasis:names:tc:SAML:profiles:SSO:idpdiscovery-protocol:single" ではありません',
            'fatal.wrongEntityId': 'SP から渡された entityId が設定値と異なります',
            'fatal.noData': 'メタデータが空です',
            'fatal.loadFailed': '次の URL からメタデータをダウンロードできませんでした: ',
            'fatal.noparms': 'DSにパラメータが渡されておらず defaultReturn も設定されていません',
            'fatal.noReturnURL': "戻り URL が指定されていません",
            'fatal.badProtocol': "戻り URL は https:// か http:// で始まらなければなりません",
            'idpPreferred.label': '選択候補の IdP:',
            'idpEntry.label': 'もしくはあなたの所属機関名を入力してください',
            'idpEntry.NoPreferred.label': 'あなたの所属機関名を入力してください',
            'idpList.label': 'もしくはあなたの所属機関を選択してください',
            'idpList.NoPreferred.label': 'あなたの所属機関を一覧から選択してください',
            'idpList.defaultOptionLabel': '所属機関を選択してください...',
            'idpList.showList': '一覧から選択する',
            'idpList.showSearch': '機関名を入力する',
            'submitButton.label': '選択',
            'helpText': 'Help',
            'defaultLogoAlt': 'DefaultLogo'
        },
        'pt-br': {
            'fatal.divMissing': 'A tag <div> com "insertAtDiv" não foi encontrada no arquivo HTML',
            'fatal.noXMLHttpRequest': 'Seu navegador não suporta "XMLHttpRequest", impossível de carregador os dados do IdP selecionado',
            'fatal.wrongProtocol': 'A política "Policy" fornecida para o DS não foi "urn:oasis:names:tc:SAML:profiles:SSO:idpdiscovery-protocol:single"',
            'fatal.wrongEntityId': 'entityId oferecido pelo SP não confere com o da configuração',
            'fatal.noData': 'O arquivo de metadados não retornou nada;',
            'fatal.loadFailed': 'Falhou ao realizar download do metadado de ',
            'fatal.noparms': 'Sem parâmetros para sessão de descoberta e sem parâmetro "defaultReturn" configurado',
            'fatal.noReturnURL': "Não foi definida um endereço (URL) de retorno no parâmetro",
            'fatal.badProtocol': "Retorno do endereço requisitado deve começar com https:// ou http://",
            'idpPreferred.label': 'Use estas Instituições sugeridas: ',
            'idpEntry.label': 'Ou informe o nome da sua Instituição',
            'idpEntry.NoPreferred.label': 'Informe o nome da sua Instituição',
            'idpList.label': 'Ou selecione sua Instituição através da lista abaixo',
            'idpList.NoPreferred.label': 'Selecione sua Instituição através da lista abaixo',
            'idpList.defaultOptionLabel': 'Por favor, selecione sua Instituição: ',
            'idpList.showList': 'Permitir que eu escolha um IdP através de uma lista',
            'idpList.showSearch': 'Permitir que eu especifique o IdP',
            'submitButton.label': 'Continuar ',
            'helpText': 'Ajuda',
            'defaultLogoAlt': 'Logo padrão'
        }
    };

    //
    // The following should not be changed without changes to the css.  Consider them as mandatory defaults
    //
    this.maxPreferredIdPs = 3;
    this.maxIdPCharsButton = 33;
    this.maxIdPCharsDropDown = 58;
    this.maxIdPCharsAltTxt = 60;

    this.minWidth = 20;
    this.minHeight = 20;
    this.maxWidth = 115;
    this.maxHeight = 69;
    this.bestRatio = Math.log(80 / 60);
}

function urlParam(name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    return results[1] || 0;
}
<commit_msg>Comment explaining stuff<commit_after>
/** @class IdP Selector UI */
function IdPSelectUIParms() {
    //
    // Adjust the following to fit into your local configuration
    //
    this.alwaysShow = true;          // If true, this will show results as soon as you start typing
    this.dataSource = window.location.hostname === 'localhost' ? '/resources/dev/sample-shib-identities.json' : '/Shibboleth.sso/DiscoFeed'; // where to get the data from (dev vs. prod)
    this.defaultLanguage = 'en';     // Language to use if the browser local doesnt have a bundle
    this.defaultLogo = 'resources/images/shib_no_logo.png';
    this.defaultLogoWidth = 1;
    this.defaultLogoHeight = 1;
//    this.defaultReturn = null;       // If non null, then the default place to send users who are not
    // Approaching via the Discovery Protocol for example
    //this.defaultReturn = "https://example.org/Shibboleth.sso/DS?SAMLDS=1&target=https://example.org/secure";

    if (window.location.href.search("redirectPage") > 0){
        redirectStr = urlParam('redirectPage');
        shibRedirectPage = encodeURIComponent("?redirectPage=" + redirectStr);
    }

    this.defaultReturn = window.location.protocol + "//" + window.location.hostname + "/Shibboleth.sso/Login?SAMLDS=1&target=" + window.location.protocol + "//" + window.location.hostname + "/shib.xhtml" + shibRedirectPage;
    this.defaultReturnIDParam = null;
    this.helpURL = 'http://guides.dataverse.org/en/latest/user/account.html';
    this.ie6Hack = null;             // An array of structures to disable when drawing the pull down (needed to
    // handle the ie6 z axis problem
    this.insertAtDiv = 'idpSelect';  // The div where we will insert the data
    this.maxResults = 10;            // How many results to show at once or the number at which to
    // start showing if alwaysShow is false
    this.myEntityID = null;          // If non null then this string must match the string provided in the DS parms
    this.preferredIdP = null;        // Array of entityIds to always show
    this.hiddenIdPs = null;          // Array of entityIds to delete
    this.ignoreKeywords = false;     // Do we ignore the <mdui:Keywords/> when looking for candidates
    this.showListFirst = true;      // Do we start with a list of IdPs or just the dropdown
    this.samlIdPCookieTTL = 730;     // in days
    this.setFocusTextBox = true;     // Set to false to supress focus
    this.testGUI = false;

    //
    // Globalization stuff
    //
    this.langBundles = {
        'en': {
            'fatal.divMissing': '<div> specified  as "insertAtDiv" could not be located in the HTML',
            'fatal.noXMLHttpRequest': 'Browser does not support XMLHttpRequest, unable to load IdP selection data',
            'fatal.wrongProtocol': 'Policy supplied to DS was not "urn:oasis:names:tc:SAML:profiles:SSO:idpdiscovery-protocol:single"',
            'fatal.wrongEntityId': 'entityId supplied by SP did not match configuration',
            'fatal.noData': 'Metadata download returned no data',
            'fatal.loadFailed': 'Failed to download metadata from ',
            'fatal.noparms': 'No parameters to discovery session and no defaultReturn parameter configured',
            'fatal.noReturnURL': "No URL return parameter provided",
            'fatal.badProtocol': "Return request must start with https:// or http://",
            'idpPreferred.label': 'Use a previous selection:',
            'idpEntry.label': 'Or enter your institution\'s name.',
            'idpEntry.NoPreferred.label': 'Enter your institution\'s name and click "Continue" to log in via your institution\'s authentication system.',
            'idpList.label': 'Or select your institution from the list below.',
            'idpList.NoPreferred.label': 'Select your institution and click "Continue" to log in via your institution\'s authentication system.',
            'idpList.defaultOptionLabel': 'Please select...',
            'idpList.showList': 'Allow me to pick from a list',
            'idpList.showSearch': 'Allow me to type the name of my institution',
            'submitButton.label': 'Continue',
            'helpText': 'Help',
            'defaultLogoAlt': ' '
        },
        'de': {
            'fatal.divMissing': 'Das notwendige Div Element fehlt',
            'fatal.noXMLHttpRequest': 'Ihr Webbrowser unterst\u00fctzt keine XMLHttpRequests, IdP-Auswahl kann nicht geladen werden',
            'fatal.wrongProtocol': 'DS bekam eine andere Policy als "urn:oasis:names:tc:SAML:profiles:SSO:idpdiscovery-protocol:single"',
            'fatal.wrongEntityId': 'Die entityId ist nicht korrekt',
            'fatal.loadFailed': 'Metadaten konnten nicht heruntergeladen werden: ',
            'fatal.noparms': 'Parameter f\u00fcr das Discovery Service oder \'defaultReturn\' fehlen',
            'fatal.noReturnURL': "URL return Parmeter fehlt",
            'fatal.badProtocol': "return Request muss mit https:// oder http:// beginnen",
            'idpPreferred.label': 'Vorherige Auswahl:',
            'idpEntry.label': 'Oder geben Sie den Namen (oder Teile davon) an:',
            'idpEntry.NoPreferred.label': 'Namen (oder Teile davon) der Institution angeben:',
            'idpList.label': 'Oder w\u00e4hlen Sie Ihre Institution aus einer Liste:',
            'idpList.NoPreferred.label': 'Institution aus folgender Liste w\u00e4hlen:',
            'idpList.defaultOptionLabel': 'W\u00e4hlen Sie Ihre Institution aus...',
            'idpList.showList': 'Institution aus einer Liste w\u00e4hlen',
            'idpList.showSearch': 'Institution selbst angeben',
            'submitButton.label': 'OK',
            'helpText': 'Hilfe',
            'defaultLogoAlt': 'Standard logo'
        },
        'ja': {
            'fatal.divMissing': '"insertAtDiv" の ID を持つ <div> が HTML 中に存在しません',
            'fatal.noXMLHttpRequest': 'ブラウザが XMLHttpRequest をサポートしていないので IdP 情報を取得できません',
            'fatal.wrongProtocol': 'DSへ渡された Policy パラメータが "urn:oasis:names:tc:SAML:profiles:SSO:idpdiscovery-protocol:single" ではありません',
            'fatal.wrongEntityId': 'SP から渡された entityId が設定値と異なります',
            'fatal.noData': 'メタデータが空です',
            'fatal.loadFailed': '次の URL からメタデータをダウンロードできませんでした: ',
            'fatal.noparms': 'DSにパラメータが渡されておらず defaultReturn も設定されていません',
            'fatal.noReturnURL': "戻り URL が指定されていません",
            'fatal.badProtocol': "戻り URL は https:// か http:// で始まらなければなりません",
            'idpPreferred.label': '選択候補の IdP:',
            'idpEntry.label': 'もしくはあなたの所属機関名を入力してください',
            'idpEntry.NoPreferred.label': 'あなたの所属機関名を入力してください',
            'idpList.label': 'もしくはあなたの所属機関を選択してください',
            'idpList.NoPreferred.label': 'あなたの所属機関を一覧から選択してください',
            'idpList.defaultOptionLabel': '所属機関を選択してください...',
            'idpList.showList': '一覧から選択する',
            'idpList.showSearch': '機関名を入力する',
            'submitButton.label': '選択',
            'helpText': 'Help',
            'defaultLogoAlt': 'DefaultLogo'
        },
        'pt-br': {
            'fatal.divMissing': 'A tag <div> com "insertAtDiv" não foi encontrada no arquivo HTML',
            'fatal.noXMLHttpRequest': 'Seu navegador não suporta "XMLHttpRequest", impossível de carregador os dados do IdP selecionado',
            'fatal.wrongProtocol': 'A política "Policy" fornecida para o DS não foi "urn:oasis:names:tc:SAML:profiles:SSO:idpdiscovery-protocol:single"',
            'fatal.wrongEntityId': 'entityId oferecido pelo SP não confere com o da configuração',
            'fatal.noData': 'O arquivo de metadados não retornou nada;',
            'fatal.loadFailed': 'Falhou ao realizar download do metadado de ',
            'fatal.noparms': 'Sem parâmetros para sessão de descoberta e sem parâmetro "defaultReturn" configurado',
            'fatal.noReturnURL': "Não foi definida um endereço (URL) de retorno no parâmetro",
            'fatal.badProtocol': "Retorno do endereço requisitado deve começar com https:// ou http://",
            'idpPreferred.label': 'Use estas Instituições sugeridas: ',
            'idpEntry.label': 'Ou informe o nome da sua Instituição',
            'idpEntry.NoPreferred.label': 'Informe o nome da sua Instituição',
            'idpList.label': 'Ou selecione sua Instituição através da lista abaixo',
            'idpList.NoPreferred.label': 'Selecione sua Instituição através da lista abaixo',
            'idpList.defaultOptionLabel': 'Por favor, selecione sua Instituição: ',
            'idpList.showList': 'Permitir que eu escolha um IdP através de uma lista',
            'idpList.showSearch': 'Permitir que eu especifique o IdP',
            'submitButton.label': 'Continuar ',
            'helpText': 'Ajuda',
            'defaultLogoAlt': 'Logo padrão'
        }
    };

    //
    // The following should not be changed without changes to the css.  Consider them as mandatory defaults
    //
    this.maxPreferredIdPs = 3;
    this.maxIdPCharsButton = 33;
    this.maxIdPCharsDropDown = 58;
    this.maxIdPCharsAltTxt = 60;

    this.minWidth = 20;
    this.minHeight = 20;
    this.maxWidth = 115;
    this.maxHeight = 69;
    this.bestRatio = Math.log(80 / 60);
}

function urlParam(name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    //Returns the value for the specified parameter, or 0 if the parameter is not found in the url string
    return results[1] || 0;
}
<|endoftext|>


<commit_before>var jQuery = require("jquery");
var noty = require("noty");
var notify = function(filename) {
  var n = noty({
    type: 'success',
    layout:'topRight',
    theme:'relax',
    timeout: 1300,
    text: "Web page conventered to PDF
Output: '"+filename+"'"
  });
};

var opts = XXX_opts_XXX;

jQuery.download = function(url, data, method) {
  //url and data options required
  if (url && data) {
    //data can be string of parameters or array/object
    data = typeof data == 'string' ? data : decodeURIComponent(jQuery.param(data));
    //split params into form inputs
    var inputs = '';
    jQuery.each(data.split('&'), function() {
      var pair = this.split('=');
      inputs += '<input type="hidden" name="' + pair[0] +
        '" value="' + pair[1] + '" />';
    });
    //send request
    jQuery('<form action="' + url +
      '" method="' + (method || 'post') + '">' + inputs + '</form>')
      .appendTo('body').submit().remove();
  };
};

var requestParams = {
  url:encodeURIComponent(window.location),
  title:document.title,
  opts:opts
};

console.log("opts", opts);

if (!opts.onFinish.open || !Boolean(opts.onFinish.open)) {
  console.log("opts.onFinish.open is not set, performing convertation in background...");
  jQuery.ajax({
    url: "XXX_absoluteURL_XXXconvertPage",

    // The name of the callback parameter, as specified by the YQL service
    jsonp: "callback",

    // Tell jQuery we're expecting JSONP
    dataType: "jsonp",

    // Tell YQL what we want and that we want JSON
    data: requestParams,

    // Work with the response
    success: function( response ) {
      notify(response.filename);
    }
  });
} else {
  console.log("opts.onFinish.open is set, open pdf!");

  jQuery.download(
    "XXX_absoluteURL_XXXconvertPage",
    requestParams, "GET"
  );

}<commit_msg>snipped fixed<commit_after>var jQuery = require("jquery");
var noty = require("noty");
var notify = function(filename) {
  var n = noty({
    type: 'success',
    layout:'topRight',
    theme:'relax',
    timeout: 1300,
    text: "Web page conventered to PDF
Output: '"+filename+"'"
  });
};

var opts = XXX_opts_XXX;

jQuery.download = function(url, data, method) {
  //url and data options required
  if (url && data) {
    //data can be string of parameters or array/object
    data = typeof data == 'string' ? data : decodeURIComponent(jQuery.param(data));
    //split params into form inputs
    var inputs = '';
    jQuery.each(data.split('&'), function() {
      var pair = this.split('=');
      inputs += '<input type="hidden" name="' + pair[0] +
        '" value="' + pair[1] + '" />';
    });
    //send request
    jQuery('<form action="' + url +
      '" method="' + (method || 'post') + '">' + inputs + '</form>')
      .appendTo('body').submit().remove();
  };
};

var requestParams = {
  url:encodeURIComponent(window.location),
  title:document.title,
  opts:opts
};

if (!opts.onFinish.open || opts.onFinish.open=="false") {
  jQuery.ajax({
    url: "XXX_absoluteURL_XXXconvertPage",

    // The name of the callback parameter, as specified by the YQL service
    jsonp: "callback",

    // Tell jQuery we're expecting JSONP
    dataType: "jsonp",

    // Tell YQL what we want and that we want JSON
    data: requestParams,

    // Work with the response
    success: function( response ) {
      notify(response.filename);
    }
  });
} else {
  jQuery.download(
    "XXX_absoluteURL_XXXconvertPage",
    requestParams, "GET"
  );

}<|endoftext|>


<commit_before>import {getElementById} from '../../common/getElement';

export function interceptMouseEvents() {
  getElementById('actionList').addEventListener('mouseover', function(evt) {
    var self = evt.target;
    if (self.classList.contains('verb') &&
        self.classList.contains('view') &&
        self.classList.contains('tip-static') &&
        !self.classList.contains('fshTip')) {
      self.classList.add('fshTip');
      $(self).qtip({
        overwrite: true,
        show: {
          event: evt.type,
          ready: true
        },
        style: {classes: 'qtip-tipsy qtip-custom'},
        position: {
          my: 'center right',
          at: 'center left',
          effect: false,
          viewport: $(window)
        },
        content: 'This is a test',
        hide: {effect: false}
      });
    }
  });
}
<commit_msg>reduce complexity (updated eslint rule 4.14.0)<commit_after>import {getElementById} from '../../common/getElement';

var creatureViewTests = ['verb', 'view', 'tip-static', 'fshTip'];

function isCreatureView(self) {
  return creatureViewTests.every(function(e) {
    return self.classList.contains(e);
  });
}

function moEvt(evt) {
  var self = evt.target;
  if (isCreatureView(self)) {
    self.classList.add('fshTip');
    $(self).qtip({
      overwrite: true,
      show: {
        event: evt.type,
        ready: true
      },
      style: {classes: 'qtip-tipsy qtip-custom'},
      position: {
        my: 'center right',
        at: 'center left',
        effect: false,
        viewport: $(window)
      },
      content: 'This is a test',
      hide: {effect: false}
    });
  }
}

export function interceptMouseEvents() {
  getElementById('actionList').addEventListener('mouseover', moEvt);
}
<|endoftext|>


<commit_before>/**
 * Check if user is logged in
 */
var checkUserLoggedIn = function() {
    if(Meteor.user()) {
        Router.go(Router.current().route.path(this));
    } else {
        this.render('loginRequired');
    }
    this.next();
};
Router.onBeforeAction(checkUserLoggedIn, {except: WSL.publicRoutes });
<commit_msg>this.next moved to top in checkUserLoggedIn<commit_after>/**
 * Check if user is logged in
 */
var checkUserLoggedIn = function() {
    this.next();
    if(Meteor.user()) {
        Router.go(Router.current().route.path(this));
    } else {
        this.render('loginRequired');
    }
};
Router.onBeforeAction(checkUserLoggedIn, {except: WSL.publicRoutes });
<|endoftext|>