<commit_before>"use strict";

// Define our default color generator controller!
mcgApp.controller('ColorGeneratorCtrl',
function ($scope, $mdDialog, ColourLovers, $rootScope, $mdColorPalette )
{
	// Init function.
	// This is placed into a function
	// for ease-of-use in the future.
	// Often times an app needs to be
	// "Restarted" without a reload.
	$scope.init = function ()
	{
		// Reset palette to default color
		$scope.setDefaultPalette();

		// Define palettes
		$scope.palettes = [];
		$scope.colourlovers = [];

		// Toolbar is hidden by default.
		$scope.initSpeedDial();

		// Add a default palette
		$scope.addPaletteFromObject( $mdColorPalette.indigo );

		// Define theme defaults
		$scope.theme = {
			name: '',
            palettes: $scope.palettes
		};
	};

	$scope.initSpeedDial = function(){
		$scope.dialOpen = false;
	};

	// Function to replace all current palettes with an array of hex values.
	$rootScope.setPalettesByColors = function(colors){
		$scope.palettes = [];
		angular.forEach(colors, function( value ){
			$scope.palette.base = '#'+ value;
			$scope.addBasePalette();
		});
		$scope.setDefaultPalette();
	};

	// Function to add a palette from import code
	$scope.addPaletteFromJSON = function ( code )
	{
		// Break code into chunks to find JSON
		var chunks = code.split( /[{}]/ );
		var colorsObj = JSON.parse( '{' + chunks[ 1 ] + '}' );

		// Add this palette!
		$scope.addPaletteFromObject(colorsObj);
	};

	// Function to add a palette from
	// a JSON object (angularjs material
	// design format)
	$scope.addPaletteFromObject = function ( objectRef )
	{
		// First, clone object to clean it.
		var paletteObj = angular.copy( objectRef );

		// Init our customized palette values.
		var colors = [];
		var base = $scope.palette.base;

		// Build palette color json format
		angular.forEach( paletteObj, function ( value, key )
		{
			// If this is an object with RGB/Contrast values (Default angularjs palettes)
			if(typeof value == "object")
			{
				// Format it for tinycolor
				value = "rgb(" + value.value[ 0 ] + ", " + value.value[ 1 ] + ", " + value.value[ 2 ] + ")";
			}

			// Regardless, push this color to the colors using tinycolor!
			colors.push( { hex: tinycolor( value ).toHexString(), name: key } );

			// If this key is the base (500), set as base
			if ( key == 500 || key == "500" ) {
				base = value;
			}
		} );

		// Copy the base palette & add our customizations
		var palette = angular.copy( $scope.palette );
		palette.colors = colors;
		palette.base = base;

		// Push to the palette repository.
		$scope.palettes.push( palette );
	};

	// Function to add a palette to palettes.
	$scope.addBasePalette = function()
	{
		// Push on the default and then calculate it's values from it's base.
		$scope.palettes.push(angular.copy($scope.palette));
		$scope.calcPalette($scope.palettes.length-1);

		// Google Analytics Event Track
		ga('send', 'event', 'mcg', 'add_palette');
	};

	// Function to reset palette back to default.
	$scope.setDefaultPalette = function () {
		// Define base palette
		$scope.palette = {
			colors: [],
			orig:   [],
			base:   '#26a69a',
			json:   '',
			name:   ''
		};
	};

	// Function to calculate all colors for all palettes
	$scope.calcPalettes = function(){
		for(var i = 0; i < $scope.palettes.length; i++){
			$scope.calcPalette(i);
		}
	};

	// Function to delete a palette when passed it's key.
	$scope.deletePalette = function(key){
		$scope.palettes.remove(key);
		// Google Analytics Event Track
		ga('send', 'event', 'mcg', 'remove_palette');
	};

	// Function to assign watchers to all bases
	$scope.calcPalette = function(key){
		$scope.palettes[key].orig = $scope.computeColors($scope.palettes[key].base);
		$scope.palettes[key].colors = $scope.palettes[key].orig;
	};

	// Function to make the definePalette code for a palette.
	$scope.createDefinePalette = function(palette){
		return '$mdThemingProvider.definePalette(\'' + palette.name + '\', ' + $scope.makeColorsJson(palette.colors) + ');';
	};

	// Function to make an exportable json array for themes.
	$scope.makeColorsJson = function(colors){
		var exportable = {};
		angular.forEach(colors, function(value, key){
			exportable[value.name] = value.hex;
		});
		return angular.toJson(exportable, null, 4);
	};

	// Function to calculate all colors from base
	$scope.computeColors = function(hex)
	{
		// Return array of color objects.
		return [
			{ hex : tinycolor( hex ).lighten( 52 ).toHexString(), name : '50' },
			{ hex : tinycolor( hex ).lighten( 37 ).toHexString(), name : '100' },
			{ hex : tinycolor( hex ).lighten( 26 ).toHexString(), name : '200' },
			{ hex : tinycolor( hex ).lighten( 12 ).toHexString(), name : '300' },
			{ hex : tinycolor( hex ).lighten( 6 ).toHexString(), name : '400' },
			{ hex : hex, name : '500' },
			{ hex : tinycolor( hex ).darken( 6 ).toHexString(), name: '600' },
			{ hex : tinycolor( hex ).darken( 12 ).toHexString(), name: '700' },
			{ hex : tinycolor( hex ).darken( 18 ).toHexString(), name: '800' },
			{ hex : tinycolor( hex ).darken( 24 ).toHexString(), name: '900' },
			{ hex : tinycolor( hex ).lighten( 52 ).toHexString(), name: 'A100' },
			{ hex : tinycolor( hex ).lighten( 37 ).toHexString(), name: 'A200' },
			{ hex : tinycolor( hex ).lighten( 6 ).toHexString(), name: 'A400' },
			{ hex : tinycolor( hex ).darken( 12 ).toHexString(), name: 'A700' }
		];
	};

    // Function to show theme's full code
    $scope.showThemeCode = function()
    {
	    // Check to see that a theme name and palette names are set.
	    if(
		    typeof $scope.theme.name === 'undefined' || $scope.theme.name.length < 1 ||
		    typeof $scope.palettes[0] === 'undefined' || typeof $scope.palettes[0].name === 'undefined' || $scope.palettes[0].name.length < 1 ||
		    typeof $scope.palettes[1] === 'undefined' || typeof $scope.palettes[1].name === 'undefined' || $scope.palettes[1].name.length < 1
	    ){
		    alert('To generate the code for a theme you must provide a theme name and at least two palettes with names.');
		    return false;
	    }

        // Init return string
        var themeCodeString = '';

        // For each palette, add it's declaration
        for(var i = 0; i < $scope.palettes.length; i++){
            themeCodeString = themeCodeString+$scope.createDefinePalette($scope.palettes[i])+'\n\r';
        }

        // Add theme configuration
        themeCodeString = themeCodeString +
        '$mdThemingProvider.theme(\'' + $scope.theme.name + '\')\n\r\t'+
        '.primaryPalette(\''+$scope.palettes[0].name+'\')\n\r\t'+
        '.accentPalette(\''+$scope.palettes[1].name+'\');'
        +'\n\r';

        // Show clipboard with theme code
        $scope.showClipboard(themeCodeString);

	    // Google Analytics Event Track
	    ga('send', 'event', 'mcg', 'copy_code_theme');
    };

	// Function to regenerate json and show dialog for palette.
	$scope.showPaletteCode = function(palette)
	{
		// Check to see that this palette has a name
		if (
			typeof palette === 'undefined' ||
			typeof palette.name === 'undefined' ||
			palette.name.length < 1
		) {
			alert('To generate the code for a palette the palette must have a name.');
			return false;
		}

		// Generate palette's code
		palette.json = $scope.createDefinePalette(palette);

		// Show code
		$scope.showClipboard(palette.json);

		// Google Analytics Event Track
		ga('send', 'event', 'mcg', 'copy_code_palette');
	};

    // Function to show export json for loading carts later
    $scope.showImport = function()
	{
		$mdDialog
			// Show the dialog to allow import
			.show( {
				templateUrl: 'templates/dialogs/import.html',
				controller: DialogImportCtrl
			} )
			// Once the user clicks import...
			.then( function ( code )
			{
				// ...add the palette!
				if ( typeof code == "object" ) {
					$scope.addPaletteFromObject( code );
				}else{
					$scope.addPaletteFromJSON( code );
				}
			}, function () { } );

		// Google Analytics Event Track
		ga( 'send', 'event', 'mcg', 'import_code' );
    };

	// Function to show generic clipboard alert dialog
	$scope.showClipboard = function(code)
	{
		// TODO: Move these controllers and templates to their own files.
		$mdDialog.show({
			template   : '<md-dialog aria-label="Clipboard dialog">' +
			'  <md-content>' +
			'
{{code}}
' +
			'  </md-content>' +
			'
' +
			'    <md-button ng-click="closeDialog()">' +
			'      Close' +
			'    </md-button>' +
			'
' +
			'</md-dialog>',
			locals     : {
				code: code
			},
			controller : ClipboardDialogController
		});

		// Google Analytics Event Track
		ga('send', 'event', 'mcg', 'copy_code');

		// TODO: Move these controllers and templates to their own files.
		function ClipboardDialogController($scope, $mdDialog, code)
		{
			$scope.code = code;
			$scope.closeDialog = function () {
				$mdDialog.hide();
			};

			// Configure Zero Clipboard
			var client = new ZeroClipboard(document.getElementById('copy-to-clipboard'));
			client.on('ready', function (event) {
				client.on('copy', function (event) {
					$scope.closeDialog();
				});
			});
		}
	};

	// Function to show generic clipboard alert dialog
	$scope.showColourLovers = function () {
		$mdDialog.show( {
			templateUrl: '/templates/dialogs/colourlovers.html',
			controller: ColourLoversDialogController
		} );

		// Google Analytics Event Track
		ga( 'send', 'event', 'mcg', 'view_colourlovers' );

		function ColourLoversDialogController( $scope, $mdDialog, ColourLovers )
		{
			$scope.init = function(){
				$scope.colourlovers = [];
				$scope.setColors = $rootScope.setPalettesByColors;
				$scope.getTop();
			};

			// Get top colourlover palettes.
			$scope.getTop = function(){
				ColourLovers.getTop().success( function ( data ) {
					$scope.colourlovers = data;
				} );
			};

			// Get new colourlover palettes.
			$scope.getNew = function () {
				ColourLovers.getNew().success( function ( data ) {
					$scope.colourlovers = data;
				} );
			};

			// Get random colourlover palettes.
			$scope.getRandom = function () {
				ColourLovers.getRandom().success( function ( data ) {
					$scope.colourlovers = data;
				} );
			};

			// Function to close dialog
			$scope.closeDialog = function () {
				$mdDialog.hide();
			};

			$scope.init();
		}
	};

    // Function to darken a palette's color.
    $scope.darkenPaletteItem = function(color){
        color.hex = shadeColor(color.hex, -0.1);
    };

    // Function to lighten a palette's color.
    $scope.lightenPaletteItem = function(color){
        color.hex = shadeColor(color.hex, 0.1);
    };

	// Init controller
	$scope.init();
});
<commit_msg>Fixed issue that caused many of the lightest colors to by white when selecting a darker color as the base. This happened particularly a lot with colourlovers themes.<commit_after>"use strict";

// Define our default color generator controller!
mcgApp.controller('ColorGeneratorCtrl',
function ($scope, $mdDialog, ColourLovers, $rootScope, $mdColorPalette )
{
	// Init function.
	// This is placed into a function
	// for ease-of-use in the future.
	// Often times an app needs to be
	// "Restarted" without a reload.
	$scope.init = function ()
	{
		// Reset palette to default color
		$scope.setDefaultPalette();

		// Define palettes
		$scope.palettes = [];
		$scope.colourlovers = [];

		// Toolbar is hidden by default.
		$scope.initSpeedDial();

		// Add a default palette
		$scope.addPaletteFromObject( $mdColorPalette.indigo );

		// Define theme defaults
		$scope.theme = {
			name: '',
            palettes: $scope.palettes
		};
	};

	$scope.initSpeedDial = function(){
		$scope.dialOpen = false;
	};

	// Function to replace all current palettes with an array of hex values.
	$rootScope.setPalettesByColors = function(colors){
		$scope.palettes = [];
		angular.forEach(colors, function( value ){
			$scope.palette.base = $scope.getLightestBase( '#' + value );
			$scope.addBasePalette();
		});
		$scope.setDefaultPalette();
	};

	// Function to add a palette from import code
	$scope.addPaletteFromJSON = function ( code )
	{
		// Break code into chunks to find JSON
		var chunks = code.split( /[{}]/ );
		var colorsObj = JSON.parse( '{' + chunks[ 1 ] + '}' );

		// Add this palette!
		$scope.addPaletteFromObject(colorsObj);
	};

	// Function to add a palette from
	// a JSON object (angularjs material
	// design format)
	$scope.addPaletteFromObject = function ( objectRef )
	{
		// First, clone object to clean it.
		var paletteObj = angular.copy( objectRef );

		// Init our customized palette values.
		var colors = [];
		var base = $scope.palette.base;

		// Build palette color json format
		angular.forEach( paletteObj, function ( value, key )
		{
			// If this is an object with RGB/Contrast values (Default angularjs palettes)
			if(typeof value == "object")
			{
				// Format it for tinycolor
				value = "rgb(" + value.value[ 0 ] + ", " + value.value[ 1 ] + ", " + value.value[ 2 ] + ")";
			}

			// Regardless, push this color to the colors using tinycolor!
			colors.push( { hex: tinycolor( value ).toHexString(), name: key } );

			// If this key is the base (500), set as base
			if ( key == 500 || key == "500" ) {
				base = value;
			}
		} );

		// Copy the base palette & add our customizations
		var palette = angular.copy( $scope.palette );
		palette.colors = colors;
		palette.base = base;

		// Push to the palette repository.
		$scope.palettes.push( palette );
	};

	// Function to add a palette to palettes.
	$scope.addBasePalette = function()
	{
		// Push on the default and then calculate it's values from it's base.
		$scope.palettes.push(angular.copy($scope.palette));
		$scope.calcPalette($scope.palettes.length-1);

		// Google Analytics Event Track
		ga('send', 'event', 'mcg', 'add_palette');
	};

	// Function to reset palette back to default.
	$scope.setDefaultPalette = function () {
		// Define base palette
		$scope.palette = {
			colors: [],
			orig:   [],
			base:   '#26a69a',
			json:   '',
			name:   ''
		};
	};

	// Function to calculate all colors for all palettes
	$scope.calcPalettes = function(){
		for(var i = 0; i < $scope.palettes.length; i++){
			$scope.calcPalette(i);
		}
	};

	// Function to delete a palette when passed it's key.
	$scope.deletePalette = function(key){
		$scope.palettes.remove(key);
		// Google Analytics Event Track
		ga('send', 'event', 'mcg', 'remove_palette');
	};

	// Function to assign watchers to all bases
	$scope.calcPalette = function(key){
		$scope.palettes[key].orig = $scope.computeColors($scope.palettes[key].base);
		$scope.palettes[key].colors = $scope.palettes[key].orig;
	};

	// Function to make the definePalette code for a palette.
	$scope.createDefinePalette = function(palette){
		return '$mdThemingProvider.definePalette(\'' + palette.name + '\', ' + $scope.makeColorsJson(palette.colors) + ');';
	};

	// Function to make an exportable json array for themes.
	$scope.makeColorsJson = function(colors){
		var exportable = {};
		angular.forEach(colors, function(value, key){
			exportable[value.name] = value.hex;
		});
		return angular.toJson(exportable, null, 4);
	};

	// Function to calculate all colors from base
	$scope.computeColors = function(hex)
	{
		// Return array of color objects.
		return [
			{ hex : tinycolor( hex ).lighten( 52 ).toHexString(), name : '50' },
			{ hex : tinycolor( hex ).lighten( 37 ).toHexString(), name : '100' },
			{ hex : tinycolor( hex ).lighten( 26 ).toHexString(), name : '200' },
			{ hex : tinycolor( hex ).lighten( 12 ).toHexString(), name : '300' },
			{ hex : tinycolor( hex ).lighten( 6 ).toHexString(), name : '400' },
			{ hex : hex, name : '500' },
			{ hex : tinycolor( hex ).darken( 6 ).toHexString(), name: '600' },
			{ hex : tinycolor( hex ).darken( 12 ).toHexString(), name: '700' },
			{ hex : tinycolor( hex ).darken( 18 ).toHexString(), name: '800' },
			{ hex : tinycolor( hex ).darken( 24 ).toHexString(), name: '900' },
			{ hex : tinycolor( hex ).lighten( 52 ).toHexString(), name: 'A100' },
			{ hex : tinycolor( hex ).lighten( 37 ).toHexString(), name: 'A200' },
			{ hex : tinycolor( hex ).lighten( 6 ).toHexString(), name: 'A400' },
			{ hex : tinycolor( hex ).darken( 12 ).toHexString(), name: 'A700' }
		];
	};

	// Function to prevent lightest
	// colors from turning into white.
	// Done by darkening base until the
	// brightest color is no longer #fff.
	$scope.getLightestBase = function(base)
	{
		console.log( "Get lighter base called." );
		console.log( base );
		console.log( tinycolor( base ).lighten( 37 ).toHexString() );
		if( tinycolor( base ).lighten( 52 ).toHexString().toLowerCase() == "#ffffff" ){
			return $scope.getLightestBase( tinycolor( base ).darken( 5 ).toHexString() );
		}else{
			console.log(base);
			console.log("Color determined! Selecting!");
			return base;
		}
	};

    // Function to show theme's full code
    $scope.showThemeCode = function()
    {
	    // Check to see that a theme name and palette names are set.
	    if(
		    typeof $scope.theme.name === 'undefined' || $scope.theme.name.length < 1 ||
		    typeof $scope.palettes[0] === 'undefined' || typeof $scope.palettes[0].name === 'undefined' || $scope.palettes[0].name.length < 1 ||
		    typeof $scope.palettes[1] === 'undefined' || typeof $scope.palettes[1].name === 'undefined' || $scope.palettes[1].name.length < 1
	    ){
		    alert('To generate the code for a theme you must provide a theme name and at least two palettes with names.');
		    return false;
	    }

        // Init return string
        var themeCodeString = '';

        // For each palette, add it's declaration
        for(var i = 0; i < $scope.palettes.length; i++){
            themeCodeString = themeCodeString+$scope.createDefinePalette($scope.palettes[i])+'\n\r';
        }

        // Add theme configuration
        themeCodeString = themeCodeString +
        '$mdThemingProvider.theme(\'' + $scope.theme.name + '\')\n\r\t'+
        '.primaryPalette(\''+$scope.palettes[0].name+'\')\n\r\t'+
        '.accentPalette(\''+$scope.palettes[1].name+'\');'
        +'\n\r';

        // Show clipboard with theme code
        $scope.showClipboard(themeCodeString);

	    // Google Analytics Event Track
	    ga('send', 'event', 'mcg', 'copy_code_theme');
    };

	// Function to regenerate json and show dialog for palette.
	$scope.showPaletteCode = function(palette)
	{
		// Check to see that this palette has a name
		if (
			typeof palette === 'undefined' ||
			typeof palette.name === 'undefined' ||
			palette.name.length < 1
		) {
			alert('To generate the code for a palette the palette must have a name.');
			return false;
		}

		// Generate palette's code
		palette.json = $scope.createDefinePalette(palette);

		// Show code
		$scope.showClipboard(palette.json);

		// Google Analytics Event Track
		ga('send', 'event', 'mcg', 'copy_code_palette');
	};

    // Function to show export json for loading carts later
    $scope.showImport = function()
	{
		$mdDialog
			// Show the dialog to allow import
			.show( {
				templateUrl: 'templates/dialogs/import.html',
				controller: DialogImportCtrl
			} )
			// Once the user clicks import...
			.then( function ( code )
			{
				// ...add the palette!
				if ( typeof code == "object" ) {
					$scope.addPaletteFromObject( code );
				}else{
					$scope.addPaletteFromJSON( code );
				}
			}, function () { } );

		// Google Analytics Event Track
		ga( 'send', 'event', 'mcg', 'import_code' );
    };

	// Function to show generic clipboard alert dialog
	$scope.showClipboard = function(code)
	{
		// TODO: Move these controllers and templates to their own files.
		$mdDialog.show({
			template   : '<md-dialog aria-label="Clipboard dialog">' +
			'  <md-content>' +
			'
{{code}}
' +
			'  </md-content>' +
			'
' +
			'    <md-button ng-click="closeDialog()">' +
			'      Close' +
			'    </md-button>' +
			'
' +
			'</md-dialog>',
			locals     : {
				code: code
			},
			controller : ClipboardDialogController
		});

		// Google Analytics Event Track
		ga('send', 'event', 'mcg', 'copy_code');

		// TODO: Move these controllers and templates to their own files.
		function ClipboardDialogController($scope, $mdDialog, code)
		{
			$scope.code = code;
			$scope.closeDialog = function () {
				$mdDialog.hide();
			};

			// Configure Zero Clipboard
			var client = new ZeroClipboard(document.getElementById('copy-to-clipboard'));
			client.on('ready', function (event) {
				client.on('copy', function (event) {
					$scope.closeDialog();
				});
			});
		}
	};

	// Function to show generic clipboard alert dialog
	$scope.showColourLovers = function () {
		$mdDialog.show( {
			templateUrl: '/templates/dialogs/colourlovers.html',
			controller: ColourLoversDialogController
		} );

		// Google Analytics Event Track
		ga( 'send', 'event', 'mcg', 'view_colourlovers' );

		function ColourLoversDialogController( $scope, $mdDialog, ColourLovers )
		{
			$scope.init = function(){
				$scope.colourlovers = [];
				$scope.setColors = $rootScope.setPalettesByColors;
				$scope.getTop();
			};

			// Get top colourlover palettes.
			$scope.getTop = function(){
				ColourLovers.getTop().success( function ( data ) {
					$scope.colourlovers = data;
				} );
			};

			// Get new colourlover palettes.
			$scope.getNew = function () {
				ColourLovers.getNew().success( function ( data ) {
					$scope.colourlovers = data;
				} );
			};

			// Get random colourlover palettes.
			$scope.getRandom = function () {
				ColourLovers.getRandom().success( function ( data ) {
					$scope.colourlovers = data;
				} );
			};

			// Function to close dialog
			$scope.closeDialog = function () {
				$mdDialog.hide();
			};

			$scope.init();
		}
	};

    // Function to darken a palette's color.
    $scope.darkenPaletteItem = function(color){
        color.hex = shadeColor(color.hex, -0.1);
    };

    // Function to lighten a palette's color.
    $scope.lightenPaletteItem = function(color){
        color.hex = shadeColor(color.hex, 0.1);
    };

	// Init controller
	$scope.init();
});
<|endoftext|>


<commit_before>// a key map of allowed keys
var allowedKeys = {
  37: 'left',
  38: 'up',
  39: 'right',
  40: 'down',
  65: 'a',
  66: 'b'
};

// the 'official' Konami Code sequence
var konamiCode = ['up', 'up', 'down', 'down', 'left', 'right', 'left', 'right', 'b', 'a'];

// a variable to remember the 'position' the user has reached so far.
var konamiCodePosition = 0;

// add keydown event listener
document.addEventListener('keydown', function(e) {
  // get the value of the key code from the key map
  var key = allowedKeys[e.keyCode];
  // get the value of the required key from the konami code
  var requiredKey = konamiCode[konamiCodePosition];

  // compare the key with the required key
  if (key == requiredKey) {

    // move to the next key in the konami code sequence
    konamiCodePosition++;

    // if the last key is reached, activate cheats
    if (konamiCodePosition == konamiCode.length)
      activateCheats();
  } else
    konamiCodePosition = 0;
});

function activateCheats() {
  var chiliDiv = document.createElement("div");
  chiliDiv.id = "chili";
  document.body.appendChild(chiliDiv);

  var x = chiliDiv.clientHeight;
  setTimeout(function() {
    chiliDiv.className = "electricBugaloo";
  }, 100);

  var audio = new Audio('audio/pling.mp3');
  audio.play();

  //alert("cheats activated");
}
<commit_msg>Update konami.js<commit_after>// a key map of allowed keys
var allowedKeys = {
  37: 'left',
  38: 'up',
  39: 'right',
  40: 'down',
  65: 'a',
  66: 'b'
};

// the 'official' Konami Code sequence
var konamiCode = ['up', 'up', 'down', 'down', 'left', 'right', 'left', 'right', 'b', 'a'];

// a variable to remember the 'position' the user has reached so far.
var konamiCodePosition = 0;

// add keydown event listener
document.addEventListener('keydown', function(e) {
  // get the value of the key code from the key map
  var key = allowedKeys[e.keyCode];
  // get the value of the required key from the konami code
  var requiredKey = konamiCode[konamiCodePosition];

  // compare the key with the required key
  if (key == requiredKey) {

    // move to the next key in the konami code sequence
    konamiCodePosition++;

    // if the last key is reached, activate cheats
    if (konamiCodePosition == konamiCode.length)
      activateCheats();
  } else
    konamiCodePosition = 0;
});

function activateCheats() {
  var chiliDiv = document.createElement("div");
  chiliDiv.id = "chili";
  document.body.appendChild(chiliDiv);

  var x = chiliDiv.clientHeight;
  setTimeout(function() {
    chiliDiv.className = "electricBugaloo";
  }, 300);

  var audio = new Audio('audio/pling.mp3');
  audio.play();

  //alert("cheats activated");
}
<|endoftext|>


<commit_before>Components.utils.import('chrome://greasemonkey-modules/content/util.js'); // ref'd in XUL

var gScriptId = decodeURIComponent(location.hash.substring(1));
var gScript = GM_util.getService().config.getMatchingScripts(function(script) {
  return script && (script.id == gScriptId);
})[0];

var gScriptExcludesEl;
var gScriptMatchesEl;
var gScriptIncludesEl;
var gTabboxEl;
var gUserExcludesEl;
var gUserMatchesEl;
var gUserIncludesEl;
var gUserTabEl;

window.addEventListener('load', function() {
  // I wanted "%s" but % is reserved in a DTD and I don't know the literal.
  document.title = document.title.replace('!!', gScript.localized.name);

  var gTabboxEl = document.getElementsByTagName('tabbox')[0];
  gUserTabEl = gTabboxEl.tabs.getItemAtIndex(0);

  gUserIncludesEl = document.getElementById('user-includes');
  gUserMatchesEl = document.getElementById('user-matches');
  gUserExcludesEl = document.getElementById('user-excludes');
  gScriptIncludesEl = document.getElementById('script-includes');
  gScriptMatchesEl = document.getElementById('script-matches');
  gScriptExcludesEl = document.getElementById('script-excludes');

  gScriptIncludesEl.pages = gScript.includes;
  gScriptIncludesEl.onAddUserExclude = function(url) {
    gUserExcludesEl.addPage(url);
    gTabboxEl.selectedTab = gUserTabEl;
  };
  gUserIncludesEl.pages = gScript.userIncludes;

  for (var i = 0; i < gScript.matches.length; i++) {
    gScriptMatchesEl.addPage(gScript.matches[i].pattern);
  }
  for (var i = 0; i < gScript.userMatches.length; i++) {
    gUserMatchesEl.addPage(gScript.userMatches[i].pattern);
  }

  gScriptExcludesEl.pages = gScript.excludes;
  gScriptExcludesEl.onAddUserInclude = function(url) {
    gUserIncludesEl.addPage(url);
    gTabboxEl.selectedTab = gUserTabEl;
  };
  gUserExcludesEl.pages = gScript.userExcludes;
}, false);

function onDialogAccept() {
  gScript.userIncludes = gUserIncludesEl.pages;
  gScript.userMatches = gUserMatchesEl.pages;
  gScript.userExcludes = gUserExcludesEl.pages;
  GM_util.getService().config._changed(gScript, "cludes");
}
<commit_msg>Script preferences - script terminated by timeout (very many matches)<commit_after>Components.utils.import('chrome://greasemonkey-modules/content/util.js'); // ref'd in XUL

var gScriptId = decodeURIComponent(location.hash.substring(1));
var gScript = GM_util.getService().config.getMatchingScripts(function(script) {
  return script && (script.id == gScriptId);
})[0];

var gScriptExcludesEl;
var gScriptMatchesEl;
var gScriptIncludesEl;
var gTabboxEl;
var gUserExcludesEl;
var gUserMatchesEl;
var gUserIncludesEl;
var gUserTabEl;

window.addEventListener('load', function() {
  // I wanted "%s" but % is reserved in a DTD and I don't know the literal.
  document.title = document.title.replace('!!', gScript.localized.name);

  var gTabboxEl = document.getElementsByTagName('tabbox')[0];
  gUserTabEl = gTabboxEl.tabs.getItemAtIndex(0);

  gUserIncludesEl = document.getElementById('user-includes');
  gUserMatchesEl = document.getElementById('user-matches');
  gUserExcludesEl = document.getElementById('user-excludes');
  gScriptIncludesEl = document.getElementById('script-includes');
  gScriptMatchesEl = document.getElementById('script-matches');
  gScriptExcludesEl = document.getElementById('script-excludes');

  gScriptIncludesEl.pages = gScript.includes;
  gScriptIncludesEl.onAddUserExclude = function(url) {
    gUserExcludesEl.addPage(url);
    gTabboxEl.selectedTab = gUserTabEl;
  };
  gUserIncludesEl.pages = gScript.userIncludes;

  var matchesPattern = [];
  for (var i = 0, count = gScript.matches.length; i < count; i++) {
    matchesPattern.push(gScript.matches[i].pattern);
  }
  gScriptMatchesEl.pages = matchesPattern;
  var userMatchesPattern = [];
  for (var i = 0, count = gScript.userMatches.length; i < count; i++) {
    userMatchesPattern.push(gScript.userMatches[i].pattern);
  }
  gUserMatchesEl.pages = userMatchesPattern;

  gScriptExcludesEl.pages = gScript.excludes;
  gScriptExcludesEl.onAddUserInclude = function(url) {
    gUserIncludesEl.addPage(url);
    gTabboxEl.selectedTab = gUserTabEl;
  };
  gUserExcludesEl.pages = gScript.userExcludes;
}, false);

function onDialogAccept() {
  gScript.userIncludes = gUserIncludesEl.pages;
  gScript.userMatches = gUserMatchesEl.pages;
  gScript.userExcludes = gUserExcludesEl.pages;
  GM_util.getService().config._changed(gScript, "cludes");
}
<|endoftext|>


<commit_before>---
---

(function($) {
  "use strict";
  // From https://paste.ee/p/y1RvZ and https://justgetflux.com/
  // Modified by le717

  // TODO Testing
  window.similarproducts = {};

  function checkLenovo() {
    if (window.similarproducts) { // this variable is defined as soon as the malicious payload from Superfish is injected into the DOM
      // display a warning to your visitor that they've been hacked by Lenovo
      $(".page-wrapper").prepend({% include lenovo.html %});
    }
  }

  $(".lenovo .btn.close").on("click", function() {
    $(".lenovo").remove();
  });

  window.setTimeout(checkLenovo, 5000);
})(jQuery);
<commit_msg>. [ci skip]<commit_after>---
---

(function($) {
  "use strict";
  // From https://paste.ee/p/y1RvZ and https://justgetflux.com/
  // Modified by le717

  // TODO Testing
  window.similarproducts = {};

  function checkLenovo() {
    if (window.similarproducts) { // this variable is defined as soon as the malicious payload from Superfish is injected into the DOM
      // display a warning to your visitor that they've been hacked by Lenovo
      $(".page-wrapper").prepend("{% include lenovo.html %}".replace(/\n/g, "\n\\"));
    }
  }

  $(".lenovo .btn.close").on("click", function() {
    $(".lenovo").remove();
  });

  window.setTimeout(checkLenovo, 5000);
})(jQuery);
<|endoftext|>


<commit_before>// Retrive data for all steps of all files
// (map db data into meta objects for our needs)

'use strict';

var aFrom                         = require('es5-ext/array/from')
  , forEach                       = require('es5-ext/object/for-each')
  , capitalize                    = require('es5-ext/string/#/capitalize')
  , includes                      = require('es5-ext/string/#/contains')
  , Set                           = require('es6-set')
  , Map                           = require('es6-map')
  , deferred                      = require('deferred')
  , memoize                       = require('memoizee')
  , unserializeValue              = require('dbjs/_setup/unserialize/value')
  , resolveKeyPath                = require('dbjs/_setup/utils/resolve-key-path')
  , resolveEventKeys              = require('dbjs-persistence/lib/resolve-event-keys')
  , debugLoad                     = require('debug-ext')('load', 6)
  , humanize                      = require('debug-ext').humanize
  , resolveProcessingStepFullPath = require('../../utils/resolve-processing-step-full-path')
  , toDateInTz                    = require('../../utils/to-date-in-time-zone')
  , timeZone                      = require('../../db').timeZone;

var re = new RegExp('^processingSteps\\/map\\/([a-zA-Z0-9]+' +
	'(?:\\/steps\\/map\\/[a-zA-Z0-9]+)*)\\/([a-z0-9A-Z\\/]+)$');

module.exports = exports = memoize(function (driver, processingStepsMeta) {
	var storageStepsMap = new Map(), stepShortPathMap = new Map()
	  , serviceFullShortNameMap = new Map()
	  , startTime = Date.now();

	var result = { steps: Object.create(null), businessProcesses: Object.create(null) };

	forEach(processingStepsMeta, function (meta, stepShortPath) {
		var stepPath = resolveProcessingStepFullPath(stepShortPath);
		stepShortPathMap.set(stepPath, stepShortPath);
		meta._services.forEach(function (serviceName) {
			var serviceFullName = 'businessProcess' + capitalize.call(serviceName)
			  , storage = driver.getStorage(serviceFullName);
			serviceFullShortNameMap.set(serviceFullName, serviceName);
			if (!storageStepsMap.has(storage)) storageStepsMap.set(storage, new Set());
			storageStepsMap.get(storage).add(stepPath);
		});

		result.steps[stepShortPath] = Object.create(null);
	});

	return deferred.map(aFrom(storageStepsMap), function (data) {
		var storage = data[0], stepPaths = data[1]
		  , serviceName = serviceFullShortNameMap.get(storage.name);

		var initStepDataset = function (stepPath, businessProcessId) {
			var stepShortPath = stepShortPathMap.get(stepPath);
			if (!result.steps[stepShortPath][businessProcessId]) {
				result.steps[stepShortPath][businessProcessId] = {
					stepFullPath: 'processingSteps/map/' + stepPath
				};
			}
			return result.steps[stepShortPath][businessProcessId];
		};
		var initBpDataset = function (businessProcessId) {
			if (!result.businessProcesses[businessProcessId]) {
				result.businessProcesses[businessProcessId] = { serviceName: serviceName };
			}
			return result.businessProcesses[businessProcessId];
		};

		// Listen for new records
		stepPaths.forEach(function (stepPath) {
			// Status
			forEach(exports.stepMetaMap, function (meta, stepKeyPath) {
				storage.on('key:processingSteps/map/' + stepPath + '/' + stepKeyPath, function (event) {
					if (event.type !== (meta.type || 'direct')) return;
					if (!meta.validate(event.data)) meta.delete(initStepDataset(stepPath, event.ownerId));
					else meta.set(initStepDataset(stepPath, event.ownerId), event.data);
				});
			});
		});
		forEach(exports.businessProcessMetaMap, function (meta, keyPath) {
			storage.on('key:' + keyPath, function (event) {
				if (event.type !== (meta.type || 'direct')) return;
				if (!meta.validate(event.data)) meta.delete(initBpDataset(event.ownerId));
				else meta.set(initBpDataset(event.ownerId), event.data);
			});
		});

		// Get current records
		return deferred(
			storage.search(function (id, record) {
				var bpId = id.split('/', 1)[0], stepPath, stepKeyPath, meta, keyPath, multiItemValue, path;
				if (bpId === id) return;
				if (includes.call(id, '*')) {
					keyPath = resolveKeyPath(id);
					path = bpId + '/' + keyPath;
					if (path !== id) multiItemValue = id.slice(path.length + 1);
				} else {
					keyPath = id.slice(bpId.length + 1);
				}
				meta = exports.businessProcessMetaMap[keyPath];
				if (meta) {
					if (meta.type && (meta.type !== 'direct')) return;
					if (multiItemValue && !meta.multiple) return;
					if (!meta.validate(record, multiItemValue)) return;
					meta.set(initBpDataset(bpId), record, multiItemValue);
				}
				var match = keyPath.match(re);
				if (!match) return;
				stepPath = match[2];
				if (!stepPaths.has(stepPath)) return;
				stepKeyPath = match[3];
				meta = exports.stepMetaMap[stepKeyPath];
				if (!meta) return;
				if (meta.type && (meta.type !== 'direct')) return;
				if (multiItemValue && !meta.multiple) return;
				if (!meta.validate(record, multiItemValue)) return;
				meta.set(initStepDataset(stepPath, bpId), record, multiItemValue);
			}),
			deferred.map(Object.keys(exports.businessProcessMetaMap), function (keyPath) {
				var meta = exports.businessProcessMetaMap[keyPath];
				if (meta.type !== 'computed') return;
				return storage.searchComputed({ keyPath: keyPath }, function (id, record) {
					if (!meta.validate(record)) return;
					meta.set(initBpDataset(id.split('/', 1)[0]), record);
				});
			}),
			deferred.map(aFrom(stepPaths), function (stepPath) {
				return deferred.map(Object.keys(exports.stepMetaMap), function (stepPropKeyPath) {
					var meta = exports.stepMetaMap[stepPropKeyPath];
					if (meta.type !== 'computed') return;
					var keyPath = 'processingSteps/map/' + stepPath + '/' + stepPropKeyPath;
					return storage.searchComputed({ keyPath: keyPath }, function (id, record) {
						if (!meta.validate(record)) return;
						meta.set(initStepDataset(stepPath, id.split('/', 1)[0]), record);
					});
				});
			})
		);
	})(result).aside(function () {
		debugLoad('business process db data (in %s)', humanize(Date.now() - startTime));
	});

}, { length: 0 });

// Map of all properties to be mapped to result with corresponding instructions
exports.stepMetaMap = {
	correctionTime: {
		validate: function (record) { return (record.value[0] === '2'); },
		set: function (data, record) { data.correctionTime = unserializeValue(record.value); },
		delete: function (data) { delete data.correctionTime; }
	},
	isReady: {
		type: 'computed',
		validate: function (record) { return (record.value === '11'); },
		set: function (data, record) {
			data.pendingDate = toDateInTz(new Date(record.stamp / 1000), timeZone);
			data.pendingDateTime = new Date(record.stamp / 1000);
		},
		delete: function (data) {
			delete data.pendingDate;
			delete data.pendingDateTime;
		}
	},
	processingHolidaysTime: {
		validate: function (record) { return (record.value[0] === '2'); },
		set: function (data, record) { data.processingHolidaysTime = unserializeValue(record.value); },
		delete: function (data) { delete data.processingHolidaysTime; }
	},
	processor: {
		validate: function (record) { return (record.value[0] === '7'); },
		set: function (data, record) { data.processor = record.value.slice(1); },
		delete: function (data) { delete data.processor; }
	},
	status: {
		validate: function (record) {
			return ((record.value === '3approved') || (record.value === '3rejected'));
		},
		set: function (data, record) {
			data.processingDate = toDateInTz(new Date(record.stamp / 1000), timeZone);
			data.processingDateTime = new Date(record.stamp / 1000);
		},
		delete: function (data) {
			delete data.processingDate;
			delete data.processingDateTime;
		}
	}
};

exports.businessProcessMetaMap = {
	isApproved: {
		validate: function (record) { return (record.value === '11'); },
		set: function (data, record) {
			data.approvedDateTime = new Date(record.stamp / 1000);
			data.approvedDate = toDateInTz(data.approvedDateTime, timeZone);
		},
		delete: function (data) {
			delete data.approvedDateTime;
			delete data.approvedDate;
		}
	},
	isDemo: {
		validate: function (record) { return (record.value === '11'); },
		set: function (data, record) { data.isDemo = true; },
		delete: function (data) { delete data.isDemo; }
	},
	isSubmitted: {
		validate: function (record) { return (record.value === '11'); },
		set: function (data, record) {
			data.submissionDateTime = new Date(record.stamp / 1000);
		},
		delete: function (data) { delete data.submissionDateTime; }
	},
	'registrations/requested': {
		type: 'computed',
		validate: function (record) { return record.value[0] === '['; },
		set: function (data, record) {
			data.registrations = new Set(resolveEventKeys(JSON.parse(record.value)).map(function (value) {
				return value.slice(value.lastIndexOf('/') + 1);
			}));
		},
		delete: function (data) { delete data.registrations; }
	},
	searchString: {
		type: 'computed',
		validate: function (record) { return record.value[0] === '3'; },
		set: function (data, record) { data.searchString = unserializeValue(record.value); },
		delete: function (data) { delete data.searchString; }
	},
	status: {
		validate: function (record) { return (record.value[0] === '3'); },
		set: function (data, record) { data.status = record.value.slice(1); },
		delete: function (data) { delete data.status; }
	}
};
<commit_msg>Fix match handling<commit_after>// Retrive data for all steps of all files
// (map db data into meta objects for our needs)

'use strict';

var aFrom                         = require('es5-ext/array/from')
  , forEach                       = require('es5-ext/object/for-each')
  , capitalize                    = require('es5-ext/string/#/capitalize')
  , includes                      = require('es5-ext/string/#/contains')
  , Set                           = require('es6-set')
  , Map                           = require('es6-map')
  , deferred                      = require('deferred')
  , memoize                       = require('memoizee')
  , unserializeValue              = require('dbjs/_setup/unserialize/value')
  , resolveKeyPath                = require('dbjs/_setup/utils/resolve-key-path')
  , resolveEventKeys              = require('dbjs-persistence/lib/resolve-event-keys')
  , debugLoad                     = require('debug-ext')('load', 6)
  , humanize                      = require('debug-ext').humanize
  , resolveProcessingStepFullPath = require('../../utils/resolve-processing-step-full-path')
  , toDateInTz                    = require('../../utils/to-date-in-time-zone')
  , timeZone                      = require('../../db').timeZone;

var re = new RegExp('^processingSteps\\/map\\/([a-zA-Z0-9]+' +
	'(?:\\/steps\\/map\\/[a-zA-Z0-9]+)*)\\/([a-z0-9A-Z\\/]+)$');

module.exports = exports = memoize(function (driver, processingStepsMeta) {
	var storageStepsMap = new Map(), stepShortPathMap = new Map()
	  , serviceFullShortNameMap = new Map()
	  , startTime = Date.now();

	var result = { steps: Object.create(null), businessProcesses: Object.create(null) };

	forEach(processingStepsMeta, function (meta, stepShortPath) {
		var stepPath = resolveProcessingStepFullPath(stepShortPath);
		stepShortPathMap.set(stepPath, stepShortPath);
		meta._services.forEach(function (serviceName) {
			var serviceFullName = 'businessProcess' + capitalize.call(serviceName)
			  , storage = driver.getStorage(serviceFullName);
			serviceFullShortNameMap.set(serviceFullName, serviceName);
			if (!storageStepsMap.has(storage)) storageStepsMap.set(storage, new Set());
			storageStepsMap.get(storage).add(stepPath);
		});

		result.steps[stepShortPath] = Object.create(null);
	});

	return deferred.map(aFrom(storageStepsMap), function (data) {
		var storage = data[0], stepPaths = data[1]
		  , serviceName = serviceFullShortNameMap.get(storage.name);

		var initStepDataset = function (stepPath, businessProcessId) {
			var stepShortPath = stepShortPathMap.get(stepPath);
			if (!result.steps[stepShortPath][businessProcessId]) {
				result.steps[stepShortPath][businessProcessId] = {
					stepFullPath: 'processingSteps/map/' + stepPath
				};
			}
			return result.steps[stepShortPath][businessProcessId];
		};
		var initBpDataset = function (businessProcessId) {
			if (!result.businessProcesses[businessProcessId]) {
				result.businessProcesses[businessProcessId] = { serviceName: serviceName };
			}
			return result.businessProcesses[businessProcessId];
		};

		// Listen for new records
		stepPaths.forEach(function (stepPath) {
			// Status
			forEach(exports.stepMetaMap, function (meta, stepKeyPath) {
				storage.on('key:processingSteps/map/' + stepPath + '/' + stepKeyPath, function (event) {
					if (event.type !== (meta.type || 'direct')) return;
					if (!meta.validate(event.data)) meta.delete(initStepDataset(stepPath, event.ownerId));
					else meta.set(initStepDataset(stepPath, event.ownerId), event.data);
				});
			});
		});
		forEach(exports.businessProcessMetaMap, function (meta, keyPath) {
			storage.on('key:' + keyPath, function (event) {
				if (event.type !== (meta.type || 'direct')) return;
				if (!meta.validate(event.data)) meta.delete(initBpDataset(event.ownerId));
				else meta.set(initBpDataset(event.ownerId), event.data);
			});
		});

		// Get current records
		return deferred(
			storage.search(function (id, record) {
				var bpId = id.split('/', 1)[0], stepPath, stepKeyPath, meta, keyPath, multiItemValue, path;
				if (bpId === id) return;
				if (includes.call(id, '*')) {
					keyPath = resolveKeyPath(id);
					path = bpId + '/' + keyPath;
					if (path !== id) multiItemValue = id.slice(path.length + 1);
				} else {
					keyPath = id.slice(bpId.length + 1);
				}
				meta = exports.businessProcessMetaMap[keyPath];
				if (meta) {
					if (meta.type && (meta.type !== 'direct')) return;
					if (multiItemValue && !meta.multiple) return;
					if (!meta.validate(record, multiItemValue)) return;
					meta.set(initBpDataset(bpId), record, multiItemValue);
				}
				var match = keyPath.match(re);
				if (!match) return;
				stepPath = match[1];
				if (!stepPaths.has(stepPath)) return;
				stepKeyPath = match[2];
				meta = exports.stepMetaMap[stepKeyPath];
				if (!meta) return;
				if (meta.type && (meta.type !== 'direct')) return;
				if (multiItemValue && !meta.multiple) return;
				if (!meta.validate(record, multiItemValue)) return;
				meta.set(initStepDataset(stepPath, bpId), record, multiItemValue);
			}),
			deferred.map(Object.keys(exports.businessProcessMetaMap), function (keyPath) {
				var meta = exports.businessProcessMetaMap[keyPath];
				if (meta.type !== 'computed') return;
				return storage.searchComputed({ keyPath: keyPath }, function (id, record) {
					if (!meta.validate(record)) return;
					meta.set(initBpDataset(id.split('/', 1)[0]), record);
				});
			}),
			deferred.map(aFrom(stepPaths), function (stepPath) {
				return deferred.map(Object.keys(exports.stepMetaMap), function (stepPropKeyPath) {
					var meta = exports.stepMetaMap[stepPropKeyPath];
					if (meta.type !== 'computed') return;
					var keyPath = 'processingSteps/map/' + stepPath + '/' + stepPropKeyPath;
					return storage.searchComputed({ keyPath: keyPath }, function (id, record) {
						if (!meta.validate(record)) return;
						meta.set(initStepDataset(stepPath, id.split('/', 1)[0]), record);
					});
				});
			})
		);
	})(result).aside(function () {
		debugLoad('business process db data (in %s)', humanize(Date.now() - startTime));
	});

}, { length: 0 });

// Map of all properties to be mapped to result with corresponding instructions
exports.stepMetaMap = {
	correctionTime: {
		validate: function (record) { return (record.value[0] === '2'); },
		set: function (data, record) { data.correctionTime = unserializeValue(record.value); },
		delete: function (data) { delete data.correctionTime; }
	},
	isReady: {
		type: 'computed',
		validate: function (record) { return (record.value === '11'); },
		set: function (data, record) {
			data.pendingDate = toDateInTz(new Date(record.stamp / 1000), timeZone);
			data.pendingDateTime = new Date(record.stamp / 1000);
		},
		delete: function (data) {
			delete data.pendingDate;
			delete data.pendingDateTime;
		}
	},
	processingHolidaysTime: {
		validate: function (record) { return (record.value[0] === '2'); },
		set: function (data, record) { data.processingHolidaysTime = unserializeValue(record.value); },
		delete: function (data) { delete data.processingHolidaysTime; }
	},
	processor: {
		validate: function (record) { return (record.value[0] === '7'); },
		set: function (data, record) { data.processor = record.value.slice(1); },
		delete: function (data) { delete data.processor; }
	},
	status: {
		validate: function (record) {
			return ((record.value === '3approved') || (record.value === '3rejected'));
		},
		set: function (data, record) {
			data.processingDate = toDateInTz(new Date(record.stamp / 1000), timeZone);
			data.processingDateTime = new Date(record.stamp / 1000);
		},
		delete: function (data) {
			delete data.processingDate;
			delete data.processingDateTime;
		}
	}
};

exports.businessProcessMetaMap = {
	isApproved: {
		validate: function (record) { return (record.value === '11'); },
		set: function (data, record) {
			data.approvedDateTime = new Date(record.stamp / 1000);
			data.approvedDate = toDateInTz(data.approvedDateTime, timeZone);
		},
		delete: function (data) {
			delete data.approvedDateTime;
			delete data.approvedDate;
		}
	},
	isDemo: {
		validate: function (record) { return (record.value === '11'); },
		set: function (data, record) { data.isDemo = true; },
		delete: function (data) { delete data.isDemo; }
	},
	isSubmitted: {
		validate: function (record) { return (record.value === '11'); },
		set: function (data, record) {
			data.submissionDateTime = new Date(record.stamp / 1000);
		},
		delete: function (data) { delete data.submissionDateTime; }
	},
	'registrations/requested': {
		type: 'computed',
		validate: function (record) { return record.value[0] === '['; },
		set: function (data, record) {
			data.registrations = new Set(resolveEventKeys(JSON.parse(record.value)).map(function (value) {
				return value.slice(value.lastIndexOf('/') + 1);
			}));
		},
		delete: function (data) { delete data.registrations; }
	},
	searchString: {
		type: 'computed',
		validate: function (record) { return record.value[0] === '3'; },
		set: function (data, record) { data.searchString = unserializeValue(record.value); },
		delete: function (data) { delete data.searchString; }
	},
	status: {
		validate: function (record) { return (record.value[0] === '3'); },
		set: function (data, record) { data.status = record.value.slice(1); },
		delete: function (data) { delete data.status; }
	}
};
<|endoftext|>


<commit_before>/* Originally written by Christian Rasmussen */

var Q = require("q");
var request = require("request");
var xml2js = require("xml2js");
var mapper = require("object-mapper");
var jsdom = require("jsdom");
var serverSync = require("../server_sync");

var parser = new xml2js.Parser();

var externalURL = "http://samfundet.no/rss";

exports.insertEvents = function getEventsFromExternalSource () {
    request({
        method: "GET",
        uri: externalURL,
        encoding: "utf8"
    }, function (error, response, body) {
        if (!error && response.statusCode === 200) {
            xml2js.parseString(body);
        }
    });
}

parser.on("end", function(result) {
    var data = mapper.getKeyValue(result, "rss.channel.0.item");
    var events = parseEvents(data);

    updateEventsWithPrices(events, function () {
        serverSync.sync(events);
    });
});

function parseEvents (externalEvents) {
    var outputEvents = [];
    for (var i = 0; i < externalEvents.length; i++) {
        var externalEvent = externalEvents[i];
        var event = mapper.merge(externalEvent, {
            venue: {
                name: "Studentersamfundet",
                address: "Elgeseter gate 1",
                latitude: 63.422634,
                longitude: 10.394697
            },
            isPublished: true
        }, mapping);

        outputEvents.push(event);
    }

    return outputEvents;
}

function updateEventsWithPrices (events, callback) {
    var promise_chain = Q.fcall(function(){});

    events.forEach(function (event) {
        var promise_link = function () {
            var deferred = Q.defer();

            console.log("Finding price for event: " + event.title);
            jsdom.env({
                url: event.eventUrl,
                scripts: ['http://code.jquery.com/jquery.js'],
                done: function (err, window) {
                    event.price = findPrice(window.$);
                    console.log("Found price: " + event.price);

                    deferred.resolve();
                }
            });

            return deferred.promise;
        };

        promise_chain = promise_chain.then(promise_link);
    });

    promise_chain.done(function () {
        callback();
    });
}

function findPrice($) {
    return parseInt($("td:contains('Billett') + td").text()) || 0;
}

var mapping = {
    "title.0": {
        key: "title",
        transform: function (value) {
            return value.replace(/^.*?-/, "").trim();
        }
    },
    "pubDate.0": {
        key: "startAt",
        transform: function (value) {
            var date = new Date(Date.parse(value));
            return date.toISOString();
        }
    },
    "agelimit.0": {

        key: "ageLimit",
        transform: function (value) {
            var ageLimit = parseInt(value, 10);
            return (!isNaN(ageLimit)) ? ageLimit : 0;
        }
    },
    "category.0": {
        key: "category",
        transform: function (value) {
            return categoryMapping[value];
        }
    },
    "description.0": {
        key: "description"
    },
    "link.0": {
        key: "eventUrl"
    },
    "link.1.$.href": {
        key: "imageUrl",
        transform: function(value) {
            return value.replace("/large/", "/medium/");
        }
    }
};

var categoryMapping = {
    "Konsert": "MUSIC",
    "Film": "PRESENTATIONS",
    "Møte": "DEBATE",
    "Happening": "NIGHTLIFE",
    "Samfundsmøte": "DEBATE",
    "Excenteraften": "DEBATE",
    "Temafest": "NIGHTLIFE",
    "Bokstavelig talt": "DEBATE",
    "Quiz": "OTHER",
    "Kurs": "OTHER",
    "Show": "PERFORMANCES",
    "Fotballkamp": "SPORT",
    "DJ": "MUSIC",
    "Teater": "PERFORMANCES"
};
<commit_msg>Remove unnecessary regex<commit_after>/* Originally written by Christian Rasmussen */

var Q = require("q");
var request = require("request");
var xml2js = require("xml2js");
var mapper = require("object-mapper");
var jsdom = require("jsdom");
var serverSync = require("../server_sync");

var parser = new xml2js.Parser();

var externalURL = "http://samfundet.no/rss";

exports.insertEvents = function getEventsFromExternalSource () {
    request({
        method: "GET",
        uri: externalURL,
        encoding: "utf8"
    }, function (error, response, body) {
        if (!error && response.statusCode === 200) {
            xml2js.parseString(body);
        }
    });
}

parser.on("end", function(result) {
    var data = mapper.getKeyValue(result, "rss.channel.0.item");
    var events = parseEvents(data);

    updateEventsWithPrices(events, function () {
        serverSync.sync(events);
    });
});

function parseEvents (externalEvents) {
    var outputEvents = [];
    for (var i = 0; i < externalEvents.length; i++) {
        var externalEvent = externalEvents[i];
        var event = mapper.merge(externalEvent, {
            venue: {
                name: "Studentersamfundet",
                address: "Elgeseter gate 1",
                latitude: 63.422634,
                longitude: 10.394697
            },
            isPublished: true
        }, mapping);

        outputEvents.push(event);
    }

    return outputEvents;
}

function updateEventsWithPrices (events, callback) {
    var promise_chain = Q.fcall(function(){});

    events.forEach(function (event) {
        var promise_link = function () {
            var deferred = Q.defer();

            console.log("Finding price for event: " + event.title);
            jsdom.env({
                url: event.eventUrl,
                scripts: ['http://code.jquery.com/jquery.js'],
                done: function (err, window) {
                    event.price = findPrice(window.$);
                    console.log("Found price: " + event.price);

                    deferred.resolve();
                }
            });

            return deferred.promise;
        };

        promise_chain = promise_chain.then(promise_link);
    });

    promise_chain.done(function () {
        callback();
    });
}

function findPrice($) {
    return parseInt($("td:contains('Billett') + td").text()) || 0;
}

var mapping = {
    "title.0": {
        key: "title",
        transform: function (value) {
            return value.trim();
        }
    },
    "pubDate.0": {
        key: "startAt",
        transform: function (value) {
            var date = new Date(Date.parse(value));
            return date.toISOString();
        }
    },
    "agelimit.0": {

        key: "ageLimit",
        transform: function (value) {
            var ageLimit = parseInt(value, 10);
            return (!isNaN(ageLimit)) ? ageLimit : 0;
        }
    },
    "category.0": {
        key: "category",
        transform: function (value) {
            return categoryMapping[value];
        }
    },
    "description.0": {
        key: "description"
    },
    "link.0": {
        key: "eventUrl"
    },
    "link.1.$.href": {
        key: "imageUrl",
        transform: function(value) {
            return value.replace("/large/", "/medium/");
        }
    }
};

var categoryMapping = {
    "Konsert": "MUSIC",
    "Film": "PRESENTATIONS",
    "Møte": "DEBATE",
    "Happening": "NIGHTLIFE",
    "Samfundsmøte": "DEBATE",
    "Excenteraften": "DEBATE",
    "Temafest": "NIGHTLIFE",
    "Bokstavelig talt": "DEBATE",
    "Quiz": "OTHER",
    "Kurs": "OTHER",
    "Show": "PERFORMANCES",
    "Fotballkamp": "SPORT",
    "DJ": "MUSIC",
    "Teater": "PERFORMANCES"
};
<|endoftext|>


<commit_before>"use strict";

function cacheThenNetworkRequest(url, query, callback)
{
	query = typeof query !== 'undefined' ? query : {};
	var networkDataReceived = false;
	var cacheDataReceived = false;
	request(url, query, undefined).addCallback(function(response)
		{
			networkDataReceived = true;
			callback(response, cacheDataReceived);
		});
	request(url, query, {"Accept": "x-cache/only"}).addCallback(function(response)
		{
			if(!networkDataReceived)
			{
				cacheDataReceived = true;
				callback(response, false);
			}
		});
}
<commit_msg>Fixed wrong frontend default value<commit_after>"use strict";

function cacheThenNetworkRequest(url, query, callback)
{
	query = typeof query !== 'undefined' ? query : "";
	var networkDataReceived = false;
	var cacheDataReceived = false;
	request(url, query, undefined).addCallback(function(response)
		{
			networkDataReceived = true;
			callback(response, cacheDataReceived);
		});
	request(url, query, {"Accept": "x-cache/only"}).addCallback(function(response)
		{
			if(!networkDataReceived)
			{
				cacheDataReceived = true;
				callback(response, false);
			}
		});
}
<|endoftext|>


<commit_before>/*
 * Fuel UX Loader
 * https://github.com/ExactTarget/fuelux
 *
 * Copyright (c) 2014 ExactTarget
 * Licensed under the MIT license.
 */

// -- BEGIN UMD WRAPPER PREFACE --

// For more information on UMD visit:
// https://github.com/umdjs/umd/blob/master/jqueryPlugin.js

(function (factory) {
	if (typeof define === 'function' && define.amd) {
		// if AMD loader is available, register as an anonymous module.
		define(['jquery'], factory);
	} else {
		// OR use browser globals if AMD is not present
		factory(jQuery);
	}
}(function ($) {
// -- END UMD WRAPPER PREFACE --

// -- BEGIN MODULE CODE HERE --

	var old = $.fn.loader;

	// LOADER CONSTRUCTOR AND PROTOTYPE

	var Loader = function (element, options) {
		this.$element = $(element);
		this.options = $.extend({}, $.fn.loader.defaults, options);

		this.begin = (this.$element.is('[data-begin]')) ? parseFloat(this.$element.attr('data-begin')) : 1;
		this.delay = (this.$element.is('[data-delay]')) ? parseFloat(this.$element.attr('data-delay')) : 150;
		this.end = (this.$element.is('[data-end]')) ? parseInt(this.$element.attr('data-end'), 10) : 8;
		this.frame = (this.$element.is('[data-frame]')) ? parseInt(this.$element.attr('data-frame'), 10) : 1;
		this.playing = false;
		this.timeout = {};

		var ieVer = this.msieVersion();
		if(ieVer!==false && ieVer<9){
			this.$element.className += ' iefix';
		}

		this.$element.attr('data-frame', this.frame + '');
		this.play();
	};

	Loader.prototype = {

		constructor: Loader,

		msieVersion: function(){
			var ua = window.navigator.userAgent;
			var msie = ua.indexOf('MSIE ');
			if(msie>0){
				return parseInt(ua.substring(msie+5, ua.indexOf(".", msie )), 10);
			}else{
				return false;
			}
		},

		next: function(){
			this.frame++;
			if(this.frame>this.end){
				this.frame = this.begin;
			}
			this.$element.attr('data-frame', this.frame + '');
		},

		pause: function(){
			clearTimeout(this.timeout);
			this.playing = false;
		},

		play: function(){
			var self = this;
			if(!this.playing){
				this.timeout = setTimeout(function(){
					self.next();
					self.play();
				}, this.delay);
				this.playing = true;
			}
		},

		prev: function(){
			this.frame--;
			if(this.frame<this.begin){
				this.frame = this.end;
			}
			this.$element.attr('data-frame', this.frame + '');
		},

		reset: function(){
			this.frame = this.begin;
			this.$element.attr('data-frame', this.frame + '');
		}

	};

	// LOADER PLUGIN DEFINITION

	$.fn.loader = function (option) {
		var args = Array.prototype.slice.call( arguments, 1 );
		var methodReturn;

		var $set = this.each(function () {
			var $this = $( this );
			var data = $this.data( 'loader' );
			var options = typeof option === 'object' && option;

			if (!data) $this.data('loader', (data = new Loader(this, options)));
			if (typeof option === 'string') methodReturn = data[ option ].apply( data, args );
		});

		return ( methodReturn === undefined ) ? $set : methodReturn;
	};

	$.fn.loader.defaults = {};

	$.fn.loader.Constructor = Loader;

	$.fn.loader.noConflict = function () {
		$.fn.loader = old;
		return this;
	};

	// INIT LOADER ON DOMCONTENTLOADED

	$(function () {
		$('.loader').each(function () {
			var $this = $(this);
			if (!$this.data('loader')) {
				$this.loader($this.data());
			}
		});
	});

// -- BEGIN UMD WRAPPER AFTERWORD --
}));
// -- END UMD WRAPPER AFTERWORD --<commit_msg>dumb loader bug I can't believe I didn't catch O.o<commit_after>/*
 * Fuel UX Loader
 * https://github.com/ExactTarget/fuelux
 *
 * Copyright (c) 2014 ExactTarget
 * Licensed under the MIT license.
 */

// -- BEGIN UMD WRAPPER PREFACE --

// For more information on UMD visit:
// https://github.com/umdjs/umd/blob/master/jqueryPlugin.js

(function (factory) {
	if (typeof define === 'function' && define.amd) {
		// if AMD loader is available, register as an anonymous module.
		define(['jquery'], factory);
	} else {
		// OR use browser globals if AMD is not present
		factory(jQuery);
	}
}(function ($) {
// -- END UMD WRAPPER PREFACE --

// -- BEGIN MODULE CODE HERE --

	var old = $.fn.loader;

	// LOADER CONSTRUCTOR AND PROTOTYPE

	var Loader = function (element, options) {
		this.$element = $(element);
		this.options = $.extend({}, $.fn.loader.defaults, options);

		this.begin = (this.$element.is('[data-begin]')) ? parseFloat(this.$element.attr('data-begin')) : 1;
		this.delay = (this.$element.is('[data-delay]')) ? parseFloat(this.$element.attr('data-delay')) : 150;
		this.end = (this.$element.is('[data-end]')) ? parseInt(this.$element.attr('data-end'), 10) : 8;
		this.frame = (this.$element.is('[data-frame]')) ? parseInt(this.$element.attr('data-frame'), 10) : 1;
		this.timeout = {};

		var ieVer = this.msieVersion();
		if(ieVer!==false && ieVer<9){
			this.$element.className += ' iefix';
		}

		this.$element.attr('data-frame', this.frame + '');
		this.play();
	};

	Loader.prototype = {

		constructor: Loader,

		msieVersion: function(){
			var ua = window.navigator.userAgent;
			var msie = ua.indexOf('MSIE ');
			if(msie>0){
				return parseInt(ua.substring(msie+5, ua.indexOf(".", msie )), 10);
			}else{
				return false;
			}
		},

		next: function(){
			this.frame++;
			if(this.frame>this.end){
				this.frame = this.begin;
			}
			this.$element.attr('data-frame', this.frame + '');
		},

		pause: function(){
			clearTimeout(this.timeout);
		},

		play: function(){
			var self = this;
			clearTimeout(this.timeout);
			this.timeout = setTimeout(function(){
				self.next();
				self.play();
			}, this.delay);
		},

		prev: function(){
			this.frame--;
			if(this.frame<this.begin){
				this.frame = this.end;
			}
			this.$element.attr('data-frame', this.frame + '');
		},

		reset: function(){
			this.frame = this.begin;
			this.$element.attr('data-frame', this.frame + '');
		}

	};

	// LOADER PLUGIN DEFINITION

	$.fn.loader = function (option) {
		var args = Array.prototype.slice.call( arguments, 1 );
		var methodReturn;

		var $set = this.each(function () {
			var $this = $( this );
			var data = $this.data( 'loader' );
			var options = typeof option === 'object' && option;

			if (!data) $this.data('loader', (data = new Loader(this, options)));
			if (typeof option === 'string') methodReturn = data[ option ].apply( data, args );
		});

		return ( methodReturn === undefined ) ? $set : methodReturn;
	};

	$.fn.loader.defaults = {};

	$.fn.loader.Constructor = Loader;

	$.fn.loader.noConflict = function () {
		$.fn.loader = old;
		return this;
	};

	// INIT LOADER ON DOMCONTENTLOADED

	$(function () {
		$('.loader').each(function () {
			var $this = $(this);
			if (!$this.data('loader')) {
				$this.loader($this.data());
			}
		});
	});

// -- BEGIN UMD WRAPPER AFTERWORD --
}));
// -- END UMD WRAPPER AFTERWORD --<|endoftext|>


<commit_before>/* jshint indent: false */ // TODO: ENYO-3311

/* global Phonegap */

/**
 * UI: Phonegap pane in the ProjectProperties popup
 * @name Phonegap.BuildStatusUI
 */
enyo.kind({
	name: "Phonegap.ProjectProperties.PlatformBuildStatus",
	kind: "onyx.IconButton",
	ontap: "showStatusMessage",
	published: {
		platform: undefined,
		buildStatusData: undefined,
	},
	/**
	 * Update the image for the platform IconButton depending on the status of the related platform
	 * described in buildStatusData.
	 *
	 * @private
	 */
	buildStatusDataChanged: function() {
		if (this.buildStatusData && this.buildStatusData.status[this.platform] === "complete") {
			//Build status: complete
			this.setSrc("$services/assets/images/platforms/" + this.platform + "-logo-complete-32x32.png");

		} else {
			if (this.buildStatusData && this.buildStatusData.status[this.platform] === "error" ||
			    this.buildStatusData && this.buildStatusData.status[this.platform] === null){

				//Build status: error
				this.setSrc("$services/assets/images/platforms/" + this.platform + "-logo-error-32x32.png");

			} else {
				if(this.buildStatusData === null) {

					//Build status: application not built
					this.setSrc("$services/assets/images/platforms/" + this.platform + "-logo-not-available-32x32.png");

				} else {
					//Build status: pending
					this.setSrc("$services/assets/images/platforms/" + this.platform + "-logo-not-available-32x32.png");
					this.bubble("appIdChanged");
				}
			}
		}
	}
});

/**
 * The widget "Build status", show the building state of the application
 * for each platform.
 */
enyo.kind({
	name: "Phonegap.ProjectProperties.BuildStatus",
	kind: "FittableRows",
	published: {
		appId: "",
		buildStatusData: undefined,
		phongapUrl: "https://build.phonegap.com",
		provider: undefined,
		selectedPlatform: undefined
	},
	handlers: {
		onUpdateStatusMessage: "updateDownloadMessageContent"
	},
	components: [
		{
			name: "buildStatusContainer", kind: "FittableRows", classes: "ares-project-properties-build-status-container",
			components: [
				{
					name: "platformIconContainer",
					classes:"ares-project-properties-platform-icon-container",
					kind: "FittableColumns",
				},

				{ name: "downloadStatus", kind: "Phonegap.ProjectProperties.DownloadStatus" },
				{
					name: "messageContainer",
					classes: "ares-project-properties-status-message-container",
					showing: false,
					components: [
						{
							name: "hideStatusContainer",
							kind: "onyx.IconButton",
							src: "$project-view/assets/images/close-button-16x16.png",
							classes: "ares-project-properties-hide-status-button",
							ontap:"hideMessageContainer"
						},
						{
							name: "statusMessage",
							classes: "ares-project-properties-status-message"
						}
					]
				},
				{
					kind: "FittableColumns",
					style: "height: 32px; position: relative; top:-6em;",
					components: [
						{
							name:"separatorForDownloadButton"
						},
						{
							name: "downloadButton",
							kind: "onyx.IconButton",
							src: "$services/assets/images/download-icon.png",
							showing: false,
							ontap: "downloadPackage"
						}
					]
				}

			]
		}
	],
	/**@private*/
	create: function() {
		this.inherited(arguments);
		this.createIconButtons();
		this.appIdChanged();
		this.setProvider(Phonegap.ProjectProperties.getProvider());
	},

	/**
	 * Create the IconButtons displaying the build state of the application
	 * for all platforms defined in the object {Phonegap.ProjectProperties.downloadStatus}
	 *
	 * @private
	 */
	createIconButtons: function() {
		for (var key in Phonegap.ProjectProperties.downloadStatus) {
			this.$.platformIconContainer.createComponent(
				{
					name: key + "Decorator",
					classes: "ares-project-properties-build-status-icon",
					components: [
						{
							name: key + "Button",
							kind: "Phonegap.ProjectProperties.PlatformBuildStatus",
							platform: key
						}
					]
				},
				{owner: this}
			);

		}
	},

	/**
	 * Charge the icon showing the build status of the application of a a given platform depending on
	 * its status. the status is checked from the "buildStatusData" object.
	 * By clicking on the icon, the status message is displayed.
	 *
	 * @private
	 */
	buildStatusDataChanged: function(){
		var pendingApplication = false;

		//Check if there is a pending build.
		for(var key1 in this.buildStatusData && this.buildStatusData.status) {
			if (this.buildStatusData.status[key1] === "pending") {
				pendingApplication = true;
			}
		}

		//If there is a pending build, another buildStatus Request is sent after 600 ms timeout.
		if (pendingApplication) {
			setTimeout(this.sendBuildStatusRequest(), 2000);
		}

		// Get only the Enyo control that have the "platform" attribute
		// => {Phonegap.ProjectProperties.PlatformBuildStatus} instance
		for(var key2 in this.$){
			if(this.$[key2].platform !== undefined) {
				this.$[key2].setBuildStatusData(this.buildStatusData);
			}
		}

		//Update to Status container if a platform is selected.
		if(this.selectedPlatform !== undefined) {
			this.showStatusMessage({platform: this.selectedPlatform});
		}

		this.$.buildStatusContainer.render();

	},

	/**
	 * Use the phonegap service to request a {buildStatus} object from Phonegap build
	 * @private
	 */
	sendBuildStatusRequest: function() {

		if(this.appId === "" || this.appId === undefined){
			this.setBuildStatusData(null);
		} else {
			this.provider.getAppData(this.appId, enyo.bind(this, this.getBuildStatusData));
		}
	},

	/**
	 * Update the content of the statusMessage row.
	 * @protected
	 */
	updateDownloadMessageContent: function() {

		this.$.statusMessage.setContent(this.$.downloadStatus.getDownloadStatus(this.selectedPlatform));
		this.$.statusMessage.show();
		this.updateDownloadMessageDisplay(this.selectedPlatform);

		//stop the propagation of the bubble event
		return true;
	},

	/**
	 * Highlight the selected platform button by appling a css style on its decorator.
	 * @param {enyo.component} inIconButtonDecorator decorator of the button
	 * @private
	 */
	addHightlightIconButton: function(inIconButtonDecorator) {
		this.removeHightlightIconButton();
		inIconButtonDecorator.addClass("ares-project-properties-buildStatus-icon-highlight");

	},

	/**
	 * Remove the highlignt effect from all platform buttons.
	 * @private
	 */
	removeHightlightIconButton: function() {
		for(var key in Phonegap.ProjectProperties.downloadStatus) {
			this.$[key + "Decorator"].removeClass("ares-project-properties-buildStatus-icon-highlight");
		}
	},

	/**
	 *
	 * @param  {String} inPlatform Mobile platform supported by Phonegap.
	 * @private
	 */
	updateDownloadMessageDisplay: function(inPlatform) {
		var classAttribute = "ares-project-properties-buildStatus-download-button-" + inPlatform;
		this.$.separatorForDownloadButton.setClassAttribute(classAttribute);

		this.$.downloadButton.show();
	},

	/**@private*/
	showStatusMessage: function(inSender){

		this.setSelectedPlatform(inSender.platform);
		this.$.messageContainer.show();
		this.addHightlightIconButton(this.$[inSender.platform+ "Decorator"]);

		//Build status: complete
		if (this.buildStatusData && this.buildStatusData.status[inSender.platform] === "complete") {

				this.updateDownloadMessageContent();
				this.updateDownloadMessageDisplay(inSender.platform);

		} else {
			this.$.downloadButton.hide();

			if (this.buildStatusData && this.buildStatusData.status[inSender.platform] === "error" ||
				this.buildStatusData && this.buildStatusData.status[inSender.platform] === null){

				//Build status: error
				this.$.statusMessage.setContent("Error: " + this.buildStatusData.error[inSender.platform]);

			} else {

				if(this.buildStatusData === null) {

					//Build status: application not built
					this.$.statusMessage.setContent("Build the application first");

				} else {

					//Build status: pending
					this.$.statusMessage.setContent("Build in progress");
				}
			}
		}

		//stop the propagation of the bubble event
		return true;
	},

	/**
	 * Listener to launch the download request form the Phonegap Build service manager.
	 * @param  {Object} inSender
	 * @param  {Object} inEvent
	 * @private
	 */
	downloadPackage: function(inSender, inEvent) {

		var projectConfig = this.owner.getProject();
		this.provider.downloadPackage(projectConfig, this.selectedPlatform, this.buildStatusData, enyo.bind(this, this.getPackage));

		//set the download status to "Download on progress"
		this.$.downloadStatus.setDownloadStatus(this.selectedPlatform, 2);
	},

	/**
	 * Callback used in the function "downloadPackage()"" in "Build.js"
	 * Update the status message to show the current status of the download request.
	 *
	 * @param  {Object} err       error object
	 * @private
	 */
	getPackage: function(err) {
		if(err) {
			//set the download status to "Download failed"
			this.$.downloadStatus.setDownloadStatus(this.selectedPlatform, 0);
		} else {
			//set the download status to "Download complete"
			this.$.downloadStatus.setDownloadStatus(this.selectedPlatform, 1);
		}
	},

	/**@private*/
	hideMessageContainer: function() {
		//Unselect the focused platform
		this.setSelectedPlatform(undefined);
		this.removeHightlightIconButton();

		this.$.messageContainer.hide();
		this.$.downloadButton.hide();
	},

	/**@private*/
	hideMessageContent: function() {
		this.$.downloadButton.hide();
	},

	/**@private*/
	appIdChanged: function(){
		this.sendBuildStatusRequest();
	},

	/**
	 * Callback function to initialize the "buildStatusData" object.
	 *
	 * @param  {Object} err               error object
	 * @param  {Object} inBuildStatusData Object returned by Phonegap build, it contains several informations
	 *                                    about the built application.
	 * @private
	 */
	getBuildStatusData: function (err, inBuildStatusData) {
		if (err) {
			this.error("err:", err);
		} else {
			this.setBuildStatusData(inBuildStatusData.user);
		}
	}
});

/**
 * Model kind to keep track on the download status for each
 * mobile platform supported by Phonegap Build.
 *
 * Used only by the widget {Phonegap.ProjectProperties.BuildStatus}
 */
enyo.kind({
	name: "Phonegap.ProjectProperties.DownloadStatus",

	/**
	 * Set the download status for a platform defined in {this.downloadStatus}.
	 *
	 * @param {String} inPlatform       platform defined in {this.downloadStatus}
	 * @param {integer} inDownloadStatus code status: 0 => failed, 1 => complete, other => on progress
	 * @public
	 */
	setDownloadStatus: function(inPlatform, inDownloadStatus) {
		if(inDownloadStatus === 1){
			Phonegap.ProjectProperties.downloadStatus[inPlatform] = "Download complete";
		} else {
			if (inDownloadStatus === 0) {
				Phonegap.ProjectProperties.downloadStatus[inPlatform] = "Download failed";
			} else {
				Phonegap.ProjectProperties.downloadStatus[inPlatform] = "Download on progress";
			}
		}

		this.bubble("onUpdateStatusMessage");
	},

	/**
	 * Get the download status value by platform.
	 *
	 * @param  {String} inPlatform [description]
	 * @return {String} status message
	 * @public
	 */
	getDownloadStatus: function(inPlatform) {
		return Phonegap.ProjectProperties.downloadStatus[inPlatform];
	}

});<commit_msg>ENYO-2788: create a published variable for the userData request timeout.<commit_after>/* jshint indent: false */ // TODO: ENYO-3311

/* global Phonegap */

/**
 * UI: Phonegap pane in the ProjectProperties popup
 * @name Phonegap.BuildStatusUI
 */
enyo.kind({
	name: "Phonegap.ProjectProperties.PlatformBuildStatus",
	kind: "onyx.IconButton",
	ontap: "showStatusMessage",
	published: {
		platform: undefined,
		buildStatusData: undefined,
		userDataRequestTimeout: 2500
	},

	/**
	 * Update the image for the platform IconButton depending on the status of the related platform
	 * described in buildStatusData.
	 *
	 * @private
	 */
	buildStatusDataChanged: function() {
		if (this.buildStatusData && this.buildStatusData.status[this.platform] === "complete") {
			//Build status: complete
			this.setSrc("$services/assets/images/platforms/" + this.platform + "-logo-complete-32x32.png");

		} else {
			if (this.buildStatusData && this.buildStatusData.status[this.platform] === "error" ||
			    this.buildStatusData && this.buildStatusData.status[this.platform] === null){

				//Build status: error
				this.setSrc("$services/assets/images/platforms/" + this.platform + "-logo-error-32x32.png");

			} else {
				if(this.buildStatusData === null) {

					//Build status: application not built
					this.setSrc("$services/assets/images/platforms/" + this.platform + "-logo-not-available-32x32.png");

				} else {
					//Build status: pending
					this.setSrc("$services/assets/images/platforms/" + this.platform + "-logo-not-available-32x32.png");
					this.bubble("appIdChanged");
				}
			}
		}
	}
});

/**
 * The widget "Build status", show the building state of the application
 * for each platform.
 */
enyo.kind({
	name: "Phonegap.ProjectProperties.BuildStatus",
	kind: "FittableRows",
	published: {
		appId: "",
		buildStatusData: undefined,
		phongapUrl: "https://build.phonegap.com",
		provider: undefined,
		selectedPlatform: undefined
	},
	handlers: {
		onUpdateStatusMessage: "updateDownloadMessageContent"
	},
	components: [
		{
			name: "buildStatusContainer", kind: "FittableRows", classes: "ares-project-properties-build-status-container",
			components: [
				{
					name: "platformIconContainer",
					classes:"ares-project-properties-platform-icon-container",
					kind: "FittableColumns",
				},

				{ name: "downloadStatus", kind: "Phonegap.ProjectProperties.DownloadStatus" },
				{
					name: "messageContainer",
					classes: "ares-project-properties-status-message-container",
					showing: false,
					components: [
						{
							name: "hideStatusContainer",
							kind: "onyx.IconButton",
							src: "$project-view/assets/images/close-button-16x16.png",
							classes: "ares-project-properties-hide-status-button",
							ontap:"hideMessageContainer"
						},
						{
							name: "statusMessage",
							classes: "ares-project-properties-status-message"
						}
					]
				},
				{
					kind: "FittableColumns",
					style: "height: 32px; position: relative; top:-6em;",
					components: [
						{
							name:"separatorForDownloadButton"
						},
						{
							name: "downloadButton",
							kind: "onyx.IconButton",
							src: "$services/assets/images/download-icon.png",
							showing: false,
							ontap: "downloadPackage"
						}
					]
				}

			]
		}
	],
	/**@private*/
	create: function() {
		this.inherited(arguments);
		this.createIconButtons();
		this.appIdChanged();
		this.setProvider(Phonegap.ProjectProperties.getProvider());
	},

	/**
	 * Create the IconButtons displaying the build state of the application
	 * for all platforms defined in the object {Phonegap.ProjectProperties.downloadStatus}
	 *
	 * @private
	 */
	createIconButtons: function() {
		for (var key in Phonegap.ProjectProperties.downloadStatus) {
			this.$.platformIconContainer.createComponent(
				{
					name: key + "Decorator",
					classes: "ares-project-properties-build-status-icon",
					components: [
						{
							name: key + "Button",
							kind: "Phonegap.ProjectProperties.PlatformBuildStatus",
							platform: key
						}
					]
				},
				{owner: this}
			);

		}
	},

	/**
	 * Charge the icon showing the build status of the application of a a given platform depending on
	 * its status. the status is checked from the "buildStatusData" object.
	 * By clicking on the icon, the status message is displayed.
	 *
	 * @private
	 */
	buildStatusDataChanged: function(){
		var pendingApplication = false;

		//Check if there is a pending build.
		for(var key1 in this.buildStatusData && this.buildStatusData.status) {
			if (this.buildStatusData.status[key1] === "pending") {
				pendingApplication = true;
			}
		}

		//If there is a pending build, another buildStatus Request is sent after 600 ms timeout.
		if (pendingApplication) {
			setTimeout(this.sendBuildStatusRequest(), this.userDataRequestTimeout);
		}

		// Get only the Enyo control that have the "platform" attribute
		// => {Phonegap.ProjectProperties.PlatformBuildStatus} instance
		for(var key2 in this.$){
			if(this.$[key2].platform !== undefined) {
				this.$[key2].setBuildStatusData(this.buildStatusData);
			}
		}

		//Update to Status container if a platform is selected.
		if(this.selectedPlatform !== undefined) {
			this.showStatusMessage({platform: this.selectedPlatform});
		}

		this.$.buildStatusContainer.render();

	},

	/**
	 * Use the phonegap service to request a {buildStatus} object from Phonegap build
	 * @private
	 */
	sendBuildStatusRequest: function() {

		if(this.appId === "" || this.appId === undefined){
			this.setBuildStatusData(null);
		} else {
			this.provider.getAppData(this.appId, enyo.bind(this, this.getBuildStatusData));
		}
	},

	/**
	 * Update the content of the statusMessage row.
	 * @protected
	 */
	updateDownloadMessageContent: function() {

		this.$.statusMessage.setContent(this.$.downloadStatus.getDownloadStatus(this.selectedPlatform));
		this.$.statusMessage.show();
		this.updateDownloadMessageDisplay(this.selectedPlatform);

		//stop the propagation of the bubble event
		return true;
	},

	/**
	 * Highlight the selected platform button by appling a css style on its decorator.
	 * @param {enyo.component} inIconButtonDecorator decorator of the button
	 * @private
	 */
	addHightlightIconButton: function(inIconButtonDecorator) {
		this.removeHightlightIconButton();
		inIconButtonDecorator.addClass("ares-project-properties-buildStatus-icon-highlight");

	},

	/**
	 * Remove the highlignt effect from all platform buttons.
	 * @private
	 */
	removeHightlightIconButton: function() {
		for(var key in Phonegap.ProjectProperties.downloadStatus) {
			this.$[key + "Decorator"].removeClass("ares-project-properties-buildStatus-icon-highlight");
		}
	},

	/**
	 *
	 * @param  {String} inPlatform Mobile platform supported by Phonegap.
	 * @private
	 */
	updateDownloadMessageDisplay: function(inPlatform) {
		var classAttribute = "ares-project-properties-buildStatus-download-button-" + inPlatform;
		this.$.separatorForDownloadButton.setClassAttribute(classAttribute);

		this.$.downloadButton.show();
	},

	/**@private*/
	showStatusMessage: function(inSender){

		this.setSelectedPlatform(inSender.platform);
		this.$.messageContainer.show();
		this.addHightlightIconButton(this.$[inSender.platform+ "Decorator"]);

		//Build status: complete
		if (this.buildStatusData && this.buildStatusData.status[inSender.platform] === "complete") {

				this.updateDownloadMessageContent();
				this.updateDownloadMessageDisplay(inSender.platform);

		} else {
			this.$.downloadButton.hide();

			if (this.buildStatusData && this.buildStatusData.status[inSender.platform] === "error" ||
				this.buildStatusData && this.buildStatusData.status[inSender.platform] === null){

				//Build status: error
				this.$.statusMessage.setContent("Error: " + this.buildStatusData.error[inSender.platform]);

			} else {

				if(this.buildStatusData === null) {

					//Build status: application not built
					this.$.statusMessage.setContent("Build the application first");

				} else {

					//Build status: pending
					this.$.statusMessage.setContent("Build in progress");
				}
			}
		}

		//stop the propagation of the bubble event
		return true;
	},

	/**
	 * Listener to launch the download request form the Phonegap Build service manager.
	 * @param  {Object} inSender
	 * @param  {Object} inEvent
	 * @private
	 */
	downloadPackage: function(inSender, inEvent) {

		var projectConfig = this.owner.getProject();
		this.provider.downloadPackage(projectConfig, this.selectedPlatform, this.buildStatusData, enyo.bind(this, this.getPackage));

		//set the download status to "Download on progress"
		this.$.downloadStatus.setDownloadStatus(this.selectedPlatform, 2);
	},

	/**
	 * Callback used in the function "downloadPackage()"" in "Build.js"
	 * Update the status message to show the current status of the download request.
	 *
	 * @param  {Object} err       error object
	 * @private
	 */
	getPackage: function(err) {
		if(err) {
			//set the download status to "Download failed"
			this.$.downloadStatus.setDownloadStatus(this.selectedPlatform, 0);
		} else {
			//set the download status to "Download complete"
			this.$.downloadStatus.setDownloadStatus(this.selectedPlatform, 1);
		}
	},

	/**@private*/
	hideMessageContainer: function() {
		//Unselect the focused platform
		this.setSelectedPlatform(undefined);
		this.removeHightlightIconButton();

		this.$.messageContainer.hide();
		this.$.downloadButton.hide();
	},

	/**@private*/
	hideMessageContent: function() {
		this.$.downloadButton.hide();
	},

	/**@private*/
	appIdChanged: function(){
		this.sendBuildStatusRequest();
	},

	/**
	 * Callback function to initialize the "buildStatusData" object.
	 *
	 * @param  {Object} err               error object
	 * @param  {Object} inBuildStatusData Object returned by Phonegap build, it contains several informations
	 *                                    about the built application.
	 * @private
	 */
	getBuildStatusData: function (err, inBuildStatusData) {
		if (err) {
			this.error("err:", err);
		} else {
			this.setBuildStatusData(inBuildStatusData.user);
		}
	}
});

/**
 * Model kind to keep track on the download status for each
 * mobile platform supported by Phonegap Build.
 *
 * Used only by the widget {Phonegap.ProjectProperties.BuildStatus}
 */
enyo.kind({
	name: "Phonegap.ProjectProperties.DownloadStatus",

	/**
	 * Set the download status for a platform defined in {this.downloadStatus}.
	 *
	 * @param {String} inPlatform       platform defined in {this.downloadStatus}
	 * @param {integer} inDownloadStatus code status: 0 => failed, 1 => complete, other => on progress
	 * @public
	 */
	setDownloadStatus: function(inPlatform, inDownloadStatus) {
		if(inDownloadStatus === 1){
			Phonegap.ProjectProperties.downloadStatus[inPlatform] = "Download complete";
		} else {
			if (inDownloadStatus === 0) {
				Phonegap.ProjectProperties.downloadStatus[inPlatform] = "Download failed";
			} else {
				Phonegap.ProjectProperties.downloadStatus[inPlatform] = "Download on progress";
			}
		}

		this.bubble("onUpdateStatusMessage");
	},

	/**
	 * Get the download status value by platform.
	 *
	 * @param  {String} inPlatform [description]
	 * @return {String} status message
	 * @public
	 */
	getDownloadStatus: function(inPlatform) {
		return Phonegap.ProjectProperties.downloadStatus[inPlatform];
	}

});<|endoftext|>


<commit_before>var manage = (function () {
	$(function () {
		$(".site-section").on("click", ".delete_video", function () {
			// $.post("/ajax/users/delete/" + this.getAttribute("data-userId"), function (data) {
			// 	var resp = JSON.parse(data);
			// 	if (resp["success"] == true) {
			// 		// remove the item from the dom
			// 		 $(this).parent().parent().remove();
			// 	}
			// });
			$(this).parent().parent().remove();
		});

		$("#user_enable_submit").click(function () {
			$.post("/wmutube/ajax/user/enable" + $("#username").val(), function (data) {
				var resp = JSON.parse(data);
				if (resp["success"] == true) {
					$("#username").val("");
				}
			});
		});

		$("#user_disable_submit").click(function () {
			$.post("/wmutube/ajax/user/disable" + $("#username").val(), function (data) {
				var resp = JSON.parse(data);
				if (resp["success"] == true) {
					$("#username").val("");
				}
			});
		});

		$("#course_delete_submit").click(function () {
			var $del = $($("#course_delete_select").find(":selected").first());
			var id = $del.attr("data-course_id");
			if (id !== undefined) {
				$.post("/wmutube/ajax/course/delete", "id=" + id, function (data) {
					var resp = JSON.parse(data);
					if (resp["success"] == true) {
						$del.remove();
					}
				});
			}
		});

		$("#course_add_submit").click(function (data) {

			var num = $("#course_add_number")[0];
			var title = $("#course_add_title")[0];
			var subject = $("#course_add_subject")[0];

			// validate the form
			if (!(num.checkValidity() && title.checkValidity() && subject.checkValidity())) {
				return;
			}

			theObj = {
				"number": parseInt($(num).val()),
				"title": $(title).val(),
				"subject": $(subject).val()
			};

			console.log(JSON.stringify(theObj));

			$.post("/wmutube/ajax/course/create", "courseInfo=" + JSON.stringify(theObj), function (data) {
				var resp = JSON.parse(data);
				if (resp["success"] == true) {
					$(num).val("");
					$(title).val("");
					$(subject).val("");
				}
			});
		});
	});
})();
<commit_msg>- Really really for real fixed enable/disable this time<commit_after>var manage = (function () {
	$(function () {
		$(".site-section").on("click", ".delete_video", function () {
			// $.post("/ajax/users/delete/" + this.getAttribute("data-userId"), function (data) {
			// 	var resp = JSON.parse(data);
			// 	if (resp["success"] == true) {
			// 		// remove the item from the dom
			// 		 $(this).parent().parent().remove();
			// 	}
			// });
			$(this).parent().parent().remove();
		});

		$("#user_enable_submit").click(function () {
			$.post("/wmutube/ajax/user/enable", "username=" + $("#username").val(), function (data) {
				var resp = JSON.parse(data);
				if (resp["success"] == true) {
					$("#username").val("");
				}
			});
		});

		$("#user_disable_submit").click(function () {
			$.post("/wmutube/ajax/user/disable", "username=" + $("#username").val(), function (data) {
				var resp = JSON.parse(data);
				if (resp["success"] == true) {
					$("#username").val("");
				}
			});
		});

		$("#course_delete_submit").click(function () {
			var $del = $($("#course_delete_select").find(":selected").first());
			var id = $del.attr("data-course_id");
			if (id !== undefined) {
				$.post("/wmutube/ajax/course/delete", "id=" + id, function (data) {
					var resp = JSON.parse(data);
					if (resp["success"] == true) {
						$del.remove();
					}
				});
			}
		});

		$("#course_add_submit").click(function (data) {

			var num = $("#course_add_number")[0];
			var title = $("#course_add_title")[0];
			var subject = $("#course_add_subject")[0];

			// validate the form
			if (!(num.checkValidity() && title.checkValidity() && subject.checkValidity())) {
				return;
			}

			theObj = {
				"number": parseInt($(num).val()),
				"title": $(title).val(),
				"subject": $(subject).val()
			};

			console.log(JSON.stringify(theObj));

			$.post("/wmutube/ajax/course/create", "courseInfo=" + JSON.stringify(theObj), function (data) {
				var resp = JSON.parse(data);
				if (resp["success"] == true) {
					$(num).val("");
					$(title).val("");
					$(subject).val("");
				}
			});
		});
	});
})();
<|endoftext|>