<commit_before>Polymer('three-viewer', {
			open: false,
			width:320,
			height:240,
			bg: "#ffffff",
			showStats: false,
			ready: function() {
				this.clock = new THREE.Clock();
				this.init();
				this.animate();
				console.log("pouet");
			},
			init: function()
			{
				var container, scene, camera, renderer, controls, stats;

				scene = new THREE.Scene();
				var SCREEN_WIDTH = this.width;//window.innerWidth,
				SCREEN_HEIGHT = this.height;//window.innerHeight;
				// camera attributes
				var VIEW_ANGLE = 45, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 0.1, FAR = 20000;
				// set up camera
				camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR);
				// add the camera to the scene
				scene.add(camera);
				// the camera defaults to position (0,0,0)
				// 	so pull it back (z = 400) and up (y = 100) and set the angle towards the scene origin
				camera.position.set(0,150,400);
				camera.lookAt(scene.position);

				/*if ( Detector.webgl )
					renderer = new THREE.WebGLRenderer( {antialias:true} );
				else
				*/
				renderer = new THREE.WebGLRenderer( {antialias:true} );
				//renderer = new THREE.CanvasRenderer();
				renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
				renderer.setClearColor( this.convertColor(this.bg), 1 );
				this.$.viewer.appendChild( renderer.domElement );

				// automatically resize renderer
				//THREEx.WindowResize(renderer, camera);
				// toggle full-screen on given key press
				//THREEx.FullScreen.bindKey({ charCode : 'm'.charCodeAt(0) });

				controls = new THREE.OrbitControls( camera, renderer.domElement );
				// create a light
				var light = new THREE.PointLight(0xffffff);
				light.position.set(0,250,0);
				scene.add(light);
				var ambientLight = new THREE.AmbientLight(0x111111);
				scene.add(ambientLight);

				// Sphere parameters: radius, segments along width, segments along height
				var sphereGeometry = new THREE.SphereGeometry( 50, 32, 16 );
				var sphereMaterial = new THREE.MeshLambertMaterial( {color: 0x8888ff} );
				var sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
				sphere.position.set(100, 50, -50);
				scene.add(sphere);

				this.scene = scene;
				this.camera = camera;
				this.renderer = renderer;
				this.controls = controls;

				this.controls.autoRotate = true;

				// displays current and past frames per second attained by scene
				//TODO: move this to another web component
				/*if(this.showStats == true)
				{
					stats = new Stats();
					stats.domElement.style.position = 'absolute';
					stats.domElement.style.bottom = '0px';
					stats.domElement.style.zIndex = 100;
					this.$.stats.appendChild( stats.domElement );
					this.stats = stats;
				}*/

			},
			animate: function()
			{
				this.render();
				this.update();
				requestAnimationFrame(this.animate.bind(this))
			},
			update: function()
			{
				// delta = change in time since last call (in seconds)
				var delta = this.clock.getDelta();
				this.controls.update();
				if(this.showStats == true)
				{
					//this.stats.update();
				}
			},
			render: function()
			{
				this.renderer.render( this.scene, this.camera );
			},
			convertColor: function(hex)
			{
		        hex = parseInt("0x"+hex.split('#').pop(),16)
		        return  hex
			},
			bgChanged: function() {
				console.log("bg changed");
		        //this.$.status.style.backgroundColor = 'hsl(' + h + ', 100%, 50%)';
      		}
		  });<commit_msg> some slight cleanup to three-viewer<commit_after>Polymer('three-viewer', {
		open: false,
		width:320,
		height:240,
		bg: "#ffffff",
		showStats: false,
		ready: function() {
			this.clock = new THREE.Clock();
			this.init();
			this.animate();
			console.log("pouet");
		},
		init: function()
		{
			var container, scene, camera, renderer, controls, stats;

			scene = new THREE.Scene();
			var SCREEN_WIDTH = this.width;//window.innerWidth,
			SCREEN_HEIGHT = this.height;//window.innerHeight;
			// camera attributes
			var VIEW_ANGLE = 45, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 0.1, FAR = 20000;
			// set up camera
			camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR);
			// add the camera to the scene
			scene.add(camera);
			// the camera defaults to position (0,0,0)
			// 	so pull it back (z = 400) and up (y = 100) and set the angle towards the scene origin
			camera.position.set(0,150,400);
			camera.lookAt(scene.position);

			/*if ( Detector.webgl )
				renderer = new THREE.WebGLRenderer( {antialias:true} );
			else
			*/
			renderer = new THREE.WebGLRenderer( {antialias:true} );
			//renderer = new THREE.CanvasRenderer();
			renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
			renderer.setClearColor( this.convertColor(this.bg), 1 );
			this.$.viewer.appendChild( renderer.domElement );

			// automatically resize renderer
			//THREEx.WindowResize(renderer, camera);
			// toggle full-screen on given key press
			//THREEx.FullScreen.bindKey({ charCode : 'm'.charCodeAt(0) });

			controls = new THREE.OrbitControls( camera, renderer.domElement );
			// create a light
			var light = new THREE.PointLight(0xffffff);
			light.position.set(0,250,0);
			scene.add(light);
			var ambientLight = new THREE.AmbientLight(0x111111);
			scene.add(ambientLight);

			// Sphere parameters: radius, segments along width, segments along height
			var sphereGeometry = new THREE.SphereGeometry( 50, 32, 16 );
			var sphereMaterial = new THREE.MeshLambertMaterial( {color: 0x8888ff} );
			var sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
			sphere.position.set(100, 50, -50);
			scene.add(sphere);

			this.scene = scene;
			this.camera = camera;
			this.renderer = renderer;
			this.controls = controls;

			this.controls.autoRotate = true;

			// displays current and past frames per second attained by scene
			//TODO: move this to another web component
			/*if(this.showStats == true)
			{
				stats = new Stats();
				stats.domElement.style.position = 'absolute';
				stats.domElement.style.bottom = '0px';
				stats.domElement.style.zIndex = 100;
				this.$.stats.appendChild( stats.domElement );
				this.stats = stats;
			}*/

		},
		animate: function()
		{
			this.render();
			this.update();
			requestAnimationFrame(this.animate.bind(this))
		},
		update: function()
		{
			// delta = change in time since last call (in seconds)
			var delta = this.clock.getDelta();
			this.controls.update();
			if(this.showStats == true)
			{
				//this.stats.update();
			}
		},
		render: function()
		{
			this.renderer.render( this.scene, this.camera );
		},
		convertColor: function(hex)
		{
	        hex = parseInt("0x"+hex.split('#').pop(),16)
	        return  hex
		},
		bgChanged: function() {
			console.log("bg changed");
	        //this.$.status.style.backgroundColor = 'hsl(' + h + ', 100%, 50%)';
  		}
  });<|endoftext|>


<commit_before>/**
 * Created by zuk38 & przemoli on 9/11/15.
 */
(function () {
  angular.module('ui.grid').config(['$provide', function($provide) {
    $provide.decorator('i18nService', ['$delegate', function($delegate) {
      $delegate.add('pl', {
        headerCell: {
          aria: {
            defaultFilterLabel: 'Filtr dla kolumny',
            removeFilter: 'Usuń filtr',
            columnMenuButtonLabel: 'Menu kolumny'
          },
          priority: 'Prioritet:',
          filterLabel: "Filtr dla kolumny: "
        },
        aggregate: {
          label: 'pozycji'
        },
        groupPanel: {
          description: 'Przeciągnij nagłówek kolumny tutaj, aby pogrupować według niej.'
        },
        search: {
          placeholder: 'Szukaj...',
          showingItems: 'Widoczne pozycje:',
          selectedItems: 'Zaznaczone pozycje:',
          totalItems: 'Wszystkich pozycji:',
          size: 'Rozmiar strony:',
          first: 'Pierwsza strona',
          next: 'Następna strona',
          previous: 'Poprzednia strona',
          last: 'Ostatnia strona'
        },
        menu: {
          text: 'Wybierz kolumny:'
        },
        sort: {
          ascending: 'Sortuj rosnąco',
          descending: 'Sortuj malejąco',
          none: 'Brak sortowania',
          remove: 'Wyłącz sortowanie'
        },
        column: {
          hide: 'Ukryj kolumne'
        },
        aggregation: {
          count: 'Razem pozycji: ',
            sum: 'Razem: ',
            avg: 'Średnia: ',
            min: 'Min: ',
            max: 'Max: '
        },
        pinning: {
          pinLeft: 'Przypnij do lewej',
          pinRight: 'Przypnij do prawej',
          unpin: 'Odepnij'
        },
        columnMenu: {
          close: 'Zamknij'
        },
        gridMenu: {
          aria: {
            buttonLabel: 'Menu Grida'
          },
          columns: 'Kolumny:',
          importerTitle: 'Importuj plik',
          exporterAllAsCsv: 'Eksportuj wszystkie dane do csv',
          exporterVisibleAsCsv: 'Eksportuj widoczne dane do csv',
          exporterSelectedAsCsv: 'Eksportuj zaznaczone dane do csv',
          exporterAllAsPdf: 'Eksportuj wszystkie dane do pdf',
          exporterVisibleAsPdf: 'Eksportuj widoczne dane do pdf',
          exporterSelectedAsPdf: 'Eksportuj zaznaczone dane do pdf',
          clearAllFilters: 'Wyczyść filtry'
        },
        importer: {
          noHeaders: 'Nie udało się wczytać nazw kolumn. Czy plik posiada nagłówek?',
          noObjects: 'Nie udalo się wczytać pozycji. Czy plik zawiera dane??',
          invalidCsv: 'Nie udało się przetworzyć pliku, jest to prawidlowy plik CSV??',
          invalidJson: 'Nie udało się przetworzyć pliku, jest to prawidlowy plik Json?',
          jsonNotArray: 'Importowany plik json musi zawierać tablicę, importowanie przerwane.'
        },
        pagination: {
          aria: {
            pageToFirst: 'Pierwsza strona',
            pageBack: 'Poprzednia strona',
            pageSelected: 'Wybrana strona',
            pageForward: 'Następna strona',
            pageToLast: 'Ostatnia strona'
          },
          sizes: 'pozycji na stronę',
          totalItems: 'pozycji',
          through: 'do',
          of: 'z'
        },
        grouping: {
          group: 'Grupuj',
          ungroup: 'Rozgrupuj',
          aggregate_count: 'Zbiorczo: Razem',
          aggregate_sum: 'Zbiorczo: Suma',
          aggregate_max: 'Zbiorczo: Max',
          aggregate_min: 'Zbiorczo: Min',
          aggregate_avg: 'Zbiorczo: Średnia',
          aggregate_remove: 'Zbiorczo: Usuń'
        },
        validate: {
          error: 'Błąd:',
          minLength: 'Wartość powinna składać się z co najmniej THRESHOLD znaków.',
          maxLength: 'Wartość powinna składać się z przynajmniej THRESHOLD znaków.',
          required: 'Wartość jest wymagana.'
        }
      });
      return $delegate;
    }]);
  }]);
})();
<commit_msg>chore(update pl translations): Update pl.js<commit_after>/**
 * Created by zuk38 & przemoli on 9/11/15.
 */
(function () {
  angular.module('ui.grid').config(['$provide', function($provide) {
    $provide.decorator('i18nService', ['$delegate', function($delegate) {
      $delegate.add('pl', {
        headerCell: {
          aria: {
            defaultFilterLabel: 'Filtr dla kolumny',
            removeFilter: 'Usuń filtr',
            columnMenuButtonLabel: 'Menu kolumny'
          },
          priority: 'Prioritet:',
          filterLabel: "Filtr dla kolumny: "
        },
        aggregate: {
          label: 'pozycji'
        },
        groupPanel: {
          description: 'Przeciągnij nagłówek kolumny tutaj, aby pogrupować według niej.'
        },
        search: {
          placeholder: 'Szukaj...',
          showingItems: 'Widoczne pozycje:',
          selectedItems: 'Zaznaczone pozycje:',
          totalItems: 'Wszystkich pozycji:',
          size: 'Rozmiar strony:',
          first: 'Pierwsza strona',
          next: 'Następna strona',
          previous: 'Poprzednia strona',
          last: 'Ostatnia strona'
        },
        menu: {
          text: 'Wybierz kolumny:'
        },
        sort: {
          ascending: 'Sortuj rosnąco',
          descending: 'Sortuj malejąco',
          none: 'Brak sortowania',
          remove: 'Wyłącz sortowanie'
        },
        column: {
          hide: 'Ukryj kolumnę'
        },
        aggregation: {
          count: 'Razem pozycji: ',
            sum: 'Razem: ',
            avg: 'Średnia: ',
            min: 'Min: ',
            max: 'Max: '
        },
        pinning: {
          pinLeft: 'Przypnij do lewej',
          pinRight: 'Przypnij do prawej',
          unpin: 'Odepnij'
        },
        columnMenu: {
          close: 'Zamknij'
        },
        gridMenu: {
          aria: {
            buttonLabel: 'Opcje tabeli'
          },
          columns: 'Kolumny:',
          importerTitle: 'Importuj plik',
          exporterAllAsCsv: 'Eksportuj wszystkie dane do csv',
          exporterVisibleAsCsv: 'Eksportuj widoczne dane do csv',
          exporterSelectedAsCsv: 'Eksportuj zaznaczone dane do csv',
          exporterAllAsPdf: 'Eksportuj wszystkie dane do pdf',
          exporterVisibleAsPdf: 'Eksportuj widoczne dane do pdf',
          exporterSelectedAsPdf: 'Eksportuj zaznaczone dane do pdf',
          clearAllFilters: 'Wyczyść filtry'
        },
        importer: {
          noHeaders: 'Nie udało się wczytać nazw kolumn. Czy plik posiada nagłówek?',
          noObjects: 'Nie udalo się wczytać pozycji. Czy plik zawiera dane??',
          invalidCsv: 'Nie udało się przetworzyć pliku, jest to prawidlowy plik CSV??',
          invalidJson: 'Nie udało się przetworzyć pliku, jest to prawidlowy plik Json?',
          jsonNotArray: 'Importowany plik json musi zawierać tablicę, importowanie przerwane.'
        },
        pagination: {
          aria: {
            pageToFirst: 'Pierwsza strona',
            pageBack: 'Poprzednia strona',
            pageSelected: 'Wybrana strona',
            pageForward: 'Następna strona',
            pageToLast: 'Ostatnia strona'
          },
          sizes: 'pozycji na stronę',
          totalItems: 'pozycji',
          through: 'do',
          of: 'z'
        },
        grouping: {
          group: 'Grupuj',
          ungroup: 'Rozgrupuj',
          aggregate_count: 'Zbiorczo: Razem',
          aggregate_sum: 'Zbiorczo: Suma',
          aggregate_max: 'Zbiorczo: Max',
          aggregate_min: 'Zbiorczo: Min',
          aggregate_avg: 'Zbiorczo: Średnia',
          aggregate_remove: 'Zbiorczo: Usuń'
        },
        validate: {
          error: 'Błąd:',
          minLength: 'Wartość powinna składać się z co najmniej THRESHOLD znaków.',
          maxLength: 'Wartość powinna składać się z przynajmniej THRESHOLD znaków.',
          required: 'Wartość jest wymagana.'
        }
      });
      return $delegate;
    }]);
  }]);
})();
<|endoftext|>


<commit_before>var Remix = {
    init: function(apiKey) {
        if (apiKey) {
            localStorage.echoNestApiKey = apiKey;
        }
        swfobject.embedSWF('remix.swf', 'swf', '0', '0', '9.0.0', null, {apiKey: localStorage.echoNestApiKey}, {wmode: 'transparent'});

        this._tracks = [];
        this._trackMap = {};

        this._searchMap = {};

        // add selection and sorting functions to global scope
        extend(window, selection);
        extend(window, sorting);
    },

    apiKeyRequired: function () {
        return !localStorage.echoNestApiKey;
    },

    onError: function(message) {},

    log: function () {},

    __init: function() {
        this._swf = document.getElementById('swf');
    },

    getTrack: function(trackId) {
        var track = this._trackMap[trackId];
        if (!track) {
            track = {id: trackId};
            this._trackMap[trackId] = track;
            this._tracks.push(track);
            this.onTrackAdded(track);
        }
        return track;
    },

    removeTrack: function (track) {
        var i = this._tracks.indexOf(track);
        this._tracks.splice(i, 1);
        delete this._trackMap[track.id];
        this._swf.unloadTrack(track.id);
    },

    __setTrackState: function (trackId, state, arg) {
        Remix.log('state: ', trackId, state, arg);
        var track = this.getTrack(trackId);
        track.state = state;
        if (state == 'sound_loading') {
            track.file = arg;
            this.onTrackSoundLoading(track);
        }
        else if (state == 'sound_loaded') {
            track.sound = arg;
            track.soundLoaded = true;
            this.onTrackSoundLoaded(track);
        }
        else if (state == 'md5_calculated') {
            track.md5 = arg;
            track.key = arg;
            this._loadAnalysis(track);
        }
        else if (state == 'analysis_loading') {
            this.onTrackAnalysisLoading(track);
        }
        else if (state == 'analysis_loaded') {
            track.rawAnalysis = arg;
            track.analysis = new AudioAnalysis(track.rawAnalysis);
            track.analysis.track = track;
            localStorage['analysis_' + track.key] = JSON.stringify(track.rawAnalysis);
            track.analysisLoaded = true;
            this.onTrackAnalysisLoaded(track);
        }
    },

    _loadAnalysis: function (track) {
        var analysisString = localStorage['analysis_' + track.key];
        if (analysisString) {
            track.rawAnalysis = JSON.parse(analysisString);
            track.analysis = new AudioAnalysis(track.rawAnalysis);
            track.analysis.track = track;
            track.analysisLoaded = true;
            this.onTrackAnalysisLoaded(track);
        }
        else {
            this._swf.loadAnalysis(track.id);
        }
    },

    onTrackAdded: function (track) {},

    onTrackSoundLoading: function (track) {},

    onTrackSoundLoaded: function (track) {},

    onTrackAnalysisLoading: function (track) {},

    onTrackAnalysisLoaded: function (track) {},

    togglePlayPause: function () {
        this._swf.togglePlayPause();
    },

    __setProgress: function (progress, sourceIndex, sourcePosition) {
        this.onPlayerProgress(progress, sourceIndex, sourcePosition);
    },

    onPlayerProgress: function (progress, sourceIndex, sourcePosition) {},

    __setPlayerState: function (state) {
        this['onPlayer' + state[0].toUpperCase() + state.substring(1)]();
    },

    onPlayerReady: function () {},

    onPlayerEmpty: function () {},

    onPlayerPlaying: function () {},

    onPlayerPaused: function () {},

    onPlayerComplete: function () {},

    search: function (params) {
        var search = {params: params};
        var searchId = this._swf.search(params);
        search.id = searchId;
        this._searchMap[searchId] = search;
        return search;
    },

    __setSearchState: function (searchId, state, arg) {
        Remix.log('search state: ', searchId, state, arg);
        var search = this._searchMap[searchId];
        if (state == 'echo_nest_error') {
            if (arg.description == 'no results') {
                this.onSearchNoResults(search);
            }
            else {
                search.error = arg;
                this.onSearchError(search);
            }
        }
        else if (state == 'error') {
            search.error = arg;
            this.onSearchError(search);
        }
        else if (state == 'complete') {
            search.results = arg;
            this.onSearchResults(search);
        }
    },

    onSearchResults: function (search) {},

    onSearchNoResults: function (search) {},

    remix: function(aqs) {
        try {
            if (!aqs) {
                Remix.onError('remix must return an array of audio quanta');
                return;
            }

            this.mixSpec = [];
            for (var i = 0; i < aqs.length; i++) {
                var aq = aqs[i];
                if (aq.end < aq.start) {
                    Remix.onError('end position ' + i + ' is before start position');
                    return;
                }
                var track = aq.track || aq.container.analysis.track;
                var spec = [track.id, aq.start, aq.end];
                if (aq.filters) {
                    spec.push({filters: aq.filters});
                }
                this.mixSpec.push(spec);
            }

            if (this.onRemix) {
                //this.onRemix();
            }
            this._swf.setRemixString(JSON.stringify(this.mixSpec));
        }
        catch (e) {
            Remix.onError(e);
        }
    },

    load: function (url, enTrackId) {
        var trackId = this._swf.load(url, enTrackId);
        var track = this.getTrack(trackId);
        track.key = enTrackId;
        this._loadAnalysis(track);
        return track;
    }
};

Remix.__log = Remix.log;

if (!window.localStorage) {
    window.localStorage = {};
}

if (''.toJSON) {
    JSON.stringify = Object.toJSON;
    JSON.parse = JSON.parse || function(s) { return s.evalJSON(true); };
}

FilteredAudioQuantum.addFilter('touch');
<commit_msg>flatten sample list<commit_after>var Remix = {
    init: function(apiKey) {
        if (apiKey) {
            localStorage.echoNestApiKey = apiKey;
        }
        swfobject.embedSWF('remix.swf', 'swf', '0', '0', '9.0.0', null, {apiKey: localStorage.echoNestApiKey}, {wmode: 'transparent'});

        this._tracks = [];
        this._trackMap = {};

        this._searchMap = {};

        // add selection and sorting functions to global scope
        extend(window, selection);
        extend(window, sorting);
    },

    apiKeyRequired: function () {
        return !localStorage.echoNestApiKey;
    },

    onError: function(message) {},

    log: function () {},

    __init: function() {
        this._swf = document.getElementById('swf');
    },

    getTrack: function(trackId) {
        var track = this._trackMap[trackId];
        if (!track) {
            track = {id: trackId};
            this._trackMap[trackId] = track;
            this._tracks.push(track);
            this.onTrackAdded(track);
        }
        return track;
    },

    removeTrack: function (track) {
        var i = this._tracks.indexOf(track);
        this._tracks.splice(i, 1);
        delete this._trackMap[track.id];
        this._swf.unloadTrack(track.id);
    },

    __setTrackState: function (trackId, state, arg) {
        Remix.log('track state: ', trackId, state, arg);
        var track = this.getTrack(trackId);
        track.state = state;
        if (state == 'sound_loading') {
            track.file = arg;
            this.onTrackSoundLoading(track);
        }
        else if (state == 'sound_loaded') {
            track.sound = arg;
            track.soundLoaded = true;
            this.onTrackSoundLoaded(track);
        }
        else if (state == 'md5_calculated') {
            track.md5 = arg;
            track.key = arg;
            this._loadAnalysis(track);
        }
        else if (state == 'analysis_loading') {
            this.onTrackAnalysisLoading(track);
        }
        else if (state == 'analysis_loaded') {
            track.rawAnalysis = arg;
            track.analysis = new AudioAnalysis(track.rawAnalysis);
            track.analysis.track = track;
            localStorage['analysis_' + track.key] = JSON.stringify(track.rawAnalysis);
            track.analysisLoaded = true;
            this.onTrackAnalysisLoaded(track);
        }
    },

    _loadAnalysis: function (track) {
        var analysisString = localStorage['analysis_' + track.key];
        if (analysisString) {
            track.rawAnalysis = JSON.parse(analysisString);
            track.analysis = new AudioAnalysis(track.rawAnalysis);
            track.analysis.track = track;
            track.analysisLoaded = true;
            this.onTrackAnalysisLoaded(track);
        }
        else {
            this._swf.loadAnalysis(track.id);
        }
    },

    onTrackAdded: function (track) {},

    onTrackSoundLoading: function (track) {},

    onTrackSoundLoaded: function (track) {},

    onTrackAnalysisLoading: function (track) {},

    onTrackAnalysisLoaded: function (track) {},

    togglePlayPause: function () {
        this._swf.togglePlayPause();
    },

    __setProgress: function (progress, sourceIndex, sourcePosition) {
        this.onPlayerProgress(progress, sourceIndex, sourcePosition);
    },

    onPlayerProgress: function (progress, sourceIndex, sourcePosition) {},

    __setPlayerState: function (state) {
        this['onPlayer' + state[0].toUpperCase() + state.substring(1)]();
    },

    onPlayerReady: function () {},

    onPlayerEmpty: function () {},

    onPlayerPlaying: function () {},

    onPlayerPaused: function () {},

    onPlayerComplete: function () {},

    search: function (params) {
        var search = {params: params};
        var searchId = this._swf.search(params);
        search.id = searchId;
        this._searchMap[searchId] = search;
        return search;
    },

    __setSearchState: function (searchId, state, arg) {
        Remix.log('search state: ', searchId, state, arg);
        var search = this._searchMap[searchId];
        if (state == 'echo_nest_error') {
            if (arg.description == 'no results') {
                this.onSearchNoResults(search);
            }
            else {
                search.error = arg;
                this.onSearchError(search);
            }
        }
        else if (state == 'error') {
            search.error = arg;
            this.onSearchError(search);
        }
        else if (state == 'complete') {
            search.results = arg;
            this.onSearchResults(search);
        }
    },

    onSearchResults: function (search) {},

    onSearchNoResults: function (search) {},

    remix: function(aqs) {
        try {
            if (!aqs) {
                Remix.onError('remix must return an array of audio quanta');
                return;
            }

            aqs = aqs.flatten();

            this.mixSpec = [];
            for (var i = 0; i < aqs.length; i++) {
                var aq = aqs[i];
                if (aq.end < aq.start) {
                    Remix.onError('end position ' + i + ' is before start position');
                    return;
                }
                var track = aq.track || aq.container.analysis.track;
                var spec = [track.id, aq.start, aq.end];
                if (aq.filters) {
                    spec.push({filters: aq.filters});
                }
                this.mixSpec.push(spec);
            }

            if (this.onRemix) {
                //this.onRemix();
            }
            this._swf.setRemixString(JSON.stringify(this.mixSpec));
        }
        catch (e) {
            Remix.onError(e);
        }
    },

    load: function (url, enTrackId) {
        var trackId = this._swf.load(url, enTrackId);
        var track = this.getTrack(trackId);
        track.key = enTrackId;
        this._loadAnalysis(track);
        return track;
    }
};

Remix.__log = Remix.log;

if (!window.localStorage) {
    window.localStorage = {};
}

if (''.toJSON) {
    JSON.stringify = Object.toJSON;
    JSON.parse = JSON.parse || function(s) { return s.evalJSON(true); };
}

FilteredAudioQuantum.addFilter('touch');
<|endoftext|>


<commit_before>  $.extend(prototype, {
    initPreview: function () {
      var crossOrigin = getCrossOrigin(this.crossOrigin);
      var url = this.url;

      this.$preview = $(this.options.preview);
      this.$viewBox.html('<img' + crossOrigin + ' src="' + url + '">');
      this.$preview.each(function () {
        var $this = $(this);

        // Save the original size for recover
        $this.data(DATA_PREVIEW, {
          width: $this.width(),
          height: $this.height(),
          original: $this.html()
        });

        /**
         * Override img element styles
         * Add `display:block` to avoid margin top issue
         * (Occur only when margin-top <= -height)
         */
        $this.css('overflow', 'hidden').html(
          '<img' + crossOrigin + ' src="' + url + '" style="' +
          'display:block;width:100%;height:auto;' +
          'min-width:0!important;min-height:0!important;' +
          'max-width:none!important;max-height:none!important;' +
          'image-orientation:0deg!important">'
        );
      });
    },

    resetPreview: function () {
      this.$preview.each(function () {
        var $this = $(this);
        var data = $this.data(DATA_PREVIEW);

        $this.css({
          width: data.width,
          height: data.height,
          overflow: 'visible'
        }).html(data.original).removeData(DATA_PREVIEW);
      });
    },

    preview: function () {
      var image = this.image;
      var canvas = this.canvas;
      var cropBox = this.cropBox;
      var cropBoxWidth = cropBox.width;
      var cropBoxHeight = cropBox.height;
      var width = image.width;
      var height = image.height;
      var left = cropBox.left - canvas.left - image.left;
      var top = cropBox.top - canvas.top - image.top;

      if (!this.isCropped || this.isDisabled) {
        return;
      }

      this.$viewBox.find('img').css({
        width: width,
        height: height,
        marginLeft: -left,
        marginTop: -top,
        transform: getTransform(image)
      });

      this.$preview.each(function () {
        var $this = $(this);
        var data = $this.data(DATA_PREVIEW);
        var originalWidth = data.width;
        var originalHeight = data.height;
        var newWidth = originalWidth;
        var newHeight = originalHeight;
        var ratio = 1;

        if (cropBoxWidth) {
          ratio = originalWidth / cropBoxWidth;
          newHeight = cropBoxHeight * ratio;
        }

        if (cropBoxHeight && newHeight > originalHeight) {
          ratio = originalHeight / cropBoxHeight;
          newWidth = cropBoxWidth * ratio;
          newHeight = originalHeight;
        }

        $this.css({
          width: newWidth,
          height: newHeight
        }).find('img').css({
          width: width * ratio,
          height: height * ratio,
          marginLeft: -left * ratio,
          marginTop: -top * ratio,
          transform: getTransform(image)
        });
      });
    }
  });
<commit_msg>Add end semicolon to style<commit_after>  $.extend(prototype, {
    initPreview: function () {
      var crossOrigin = getCrossOrigin(this.crossOrigin);
      var url = this.url;

      this.$preview = $(this.options.preview);
      this.$viewBox.html('<img' + crossOrigin + ' src="' + url + '">');
      this.$preview.each(function () {
        var $this = $(this);

        // Save the original size for recover
        $this.data(DATA_PREVIEW, {
          width: $this.width(),
          height: $this.height(),
          original: $this.html()
        });

        /**
         * Override img element styles
         * Add `display:block` to avoid margin top issue
         * (Occur only when margin-top <= -height)
         */
        $this.css('overflow', 'hidden').html(
          '<img' + crossOrigin + ' src="' + url + '" style="' +
          'display:block;width:100%;height:auto;' +
          'min-width:0!important;min-height:0!important;' +
          'max-width:none!important;max-height:none!important;' +
          'image-orientation:0deg!important;">'
        );
      });
    },

    resetPreview: function () {
      this.$preview.each(function () {
        var $this = $(this);
        var data = $this.data(DATA_PREVIEW);

        $this.css({
          width: data.width,
          height: data.height,
          overflow: 'visible'
        }).html(data.original).removeData(DATA_PREVIEW);
      });
    },

    preview: function () {
      var image = this.image;
      var canvas = this.canvas;
      var cropBox = this.cropBox;
      var cropBoxWidth = cropBox.width;
      var cropBoxHeight = cropBox.height;
      var width = image.width;
      var height = image.height;
      var left = cropBox.left - canvas.left - image.left;
      var top = cropBox.top - canvas.top - image.top;

      if (!this.isCropped || this.isDisabled) {
        return;
      }

      this.$viewBox.find('img').css({
        width: width,
        height: height,
        marginLeft: -left,
        marginTop: -top,
        transform: getTransform(image)
      });

      this.$preview.each(function () {
        var $this = $(this);
        var data = $this.data(DATA_PREVIEW);
        var originalWidth = data.width;
        var originalHeight = data.height;
        var newWidth = originalWidth;
        var newHeight = originalHeight;
        var ratio = 1;

        if (cropBoxWidth) {
          ratio = originalWidth / cropBoxWidth;
          newHeight = cropBoxHeight * ratio;
        }

        if (cropBoxHeight && newHeight > originalHeight) {
          ratio = originalHeight / cropBoxHeight;
          newWidth = cropBoxWidth * ratio;
          newHeight = originalHeight;
        }

        $this.css({
          width: newWidth,
          height: newHeight
        }).find('img').css({
          width: width * ratio,
          height: height * ratio,
          marginLeft: -left * ratio,
          marginTop: -top * ratio,
          transform: getTransform(image)
        });
      });
    }
  });
<|endoftext|>


<commit_before>import React from "react";
import ReactDOM from "react-dom";
import {NavigationBar} from "./components/PageComponents";
import SvgIcon from "./components/svg/SvgIcon";

function Support() {
    return (

New Features

                            <SvgIcon icon="file" size="1.2rem"/>
                            {" Public Planet Imagery"}

Collect Earth Online Manuals

                            <SvgIcon icon="file" size="1.2rem"/>
                            {" Data Collection Manual (English)"}

                            <SvgIcon icon="file" size="1.2rem"/>
                            {" Manual de Recolección de Datos (Español)"}

                            <SvgIcon icon="file" size="1.2rem"/>
                            {" Manuel pour la collecte de données (Français)"}

                            <SvgIcon icon="file" size="1.2rem"/>
                            {" Manual de Coleta de Dados (Português)"}

                            <SvgIcon icon="file" size="1.2rem"/>
                            {" Institution & Project Creation Manual (For Admin)"}

                            <SvgIcon icon="file" size="1.2rem"/>
                            {" Manual de Creación de Instituciones y Proyectos (para el Administrador)"}

                            <SvgIcon icon="file" size="1.2rem"/>
                            {" Manuel de création de projets et de profils d’institution (pour l’administrateur)"}

                            <SvgIcon icon="file" size="1.2rem"/>
                            {" Manual de Criação de Instituições e Projetos (para Administrador)"}

                            <SvgIcon icon="file" size="1.2rem"/>
                            {" Project Development Theory"}

Code and Bug Support

Note that Chrome is the only officially supported browser.

                            <SvgIcon icon="link" size="1.2rem"/>
                            {" Github Issue Tracker"}

                            <SvgIcon icon="link" size="1.2rem"/>
                            {" OpenForis Website"}

Collect Earth Online Tutorials

                        This content is currently under development. Please check
                        back later for updates.

Collect Earth Online Demo

                        This content is currently under development. Please check
                        back later for updates.

Geo-Dash Help Center

                        Please access the Geo-Dash Help Center
                        for details on configuring the Geo-Dash for your project.

Terms of Service

                        Please view our Terms of Service here.

    );
}

export function pageInit(args) {
    ReactDOM.render(
        <NavigationBar
            userId={args.userId}
            userName={args.userName}
            version={args.version}
        >
            <Support/>
        </NavigationBar>,
        document.getElementById("app")
    );
}
<commit_msg>Update link reference to manual pdf<commit_after>import React from "react";
import ReactDOM from "react-dom";
import {NavigationBar} from "./components/PageComponents";
import SvgIcon from "./components/svg/SvgIcon";

function Support() {
    return (

New Features

                            <SvgIcon icon="file" size="1.2rem"/>
                            {" Public Planet Imagery"}

Collect Earth Online Manuals

                            <SvgIcon icon="file" size="1.2rem"/>
                            {" Data Collection Manual (English)"}

                            <SvgIcon icon="file" size="1.2rem"/>
                            {" Manual de Recolección de Datos (Español)"}

                            <SvgIcon icon="file" size="1.2rem"/>
                            {" Manuel pour la collecte de données (Français)"}

                            <SvgIcon icon="file" size="1.2rem"/>
                            {" Manual de Coleta de Dados (Português)"}

                            <SvgIcon icon="file" size="1.2rem"/>
                            {" Institution & Project Creation Manual (For Admin)"}

                            <SvgIcon icon="file" size="1.2rem"/>
                            {" Manual de Creación de Instituciones y Proyectos (para el Administrador)"}

                            <SvgIcon icon="file" size="1.2rem"/>
                            {" Manuel de création de projets et de profils d’institution (pour l’administrateur)"}

                            <SvgIcon icon="file" size="1.2rem"/>
                            {" Manual de Criação de Instituições e Projetos (para Administrador)"}

                            <SvgIcon icon="file" size="1.2rem"/>
                            {" Project Development Theory"}

Code and Bug Support

Note that Chrome is the only officially supported browser.

                            <SvgIcon icon="link" size="1.2rem"/>
                            {" Github Issue Tracker"}

                            <SvgIcon icon="link" size="1.2rem"/>
                            {" OpenForis Website"}

Collect Earth Online Tutorials

                        This content is currently under development. Please check
                        back later for updates.

Collect Earth Online Demo

                        This content is currently under development. Please check
                        back later for updates.

Geo-Dash Help Center

                        Please access the Geo-Dash Help Center
                        for details on configuring the Geo-Dash for your project.

Terms of Service

                        Please view our Terms of Service here.

    );
}

export function pageInit(args) {
    ReactDOM.render(
        <NavigationBar
            userId={args.userId}
            userName={args.userName}
            version={args.version}
        >
            <Support/>
        </NavigationBar>,
        document.getElementById("app")
    );
}
<|endoftext|>


<commit_before>/**
 * UI for the PlugPro Menu
 * @module settings/AutoWootToggle
 */

/**
 * Menu UI constructor
 * @constructor
 * @param {object} JST - Javascript HTML templates
 * @param {object} toggleSettings - List of settings and their corresponding togglers
 */
function Menu( JST, toggleSettings ){
	this.$parent = $('#app-menu');
	this.visible = false;

	// Load menu template
	var menuHTML = JST['src/html_templates/menu.html']({
		chromeDir: 'chrome-extension://' + $('#plug_pro_chrome_extension_id').val()
	});
	this.$parent.append( menuHTML );

	// Add toggle settings
	var toggleSettingsUL = this.$parent.find('#pro-toggle-settings');
	var setting;
	for( setting in toggleSettings ){
		var toggleSettingHTML = JST['src/html_templates/toggle_setting.html']({
			title: setting
		});

		toggleSettingsUL.append( toggleSettingHTML );
	}

	// Detect Plug.DJ menu animations to trigger Pro menu open/close
	this.$parent.find('.list')[0].addEventListener(
		this.getTransitionEvent(),
		this.toggle.bind(this),
		false
	);

	// Prevent menu from closing when clicking in the Pro Menu
	document.addEventListener("mousedown", function(event){
		var target = $(event.target);
		if(
			event.target.id === "plugpro-menu" ||
			target.parents('#plugpro-menu').length > 0
		){
			event.stopPropagation();
		}
	}, true);

}

/**
 * Toggle Pro menu visibility
 */
Menu.prototype.toggle = function(){
	var left = this.$parent.find('.list').css("left");
	if( left === "0px" ){
		this.show();
	}else{
		this.hide();
	}
};

/**
 * Make Pro menu visible
 */
Menu.prototype.show = function(){
	$('#plugpro-menu').addClass("expanded");
	this.visible = true;
};

/**
 * Make Pro menu hidden
 */
Menu.prototype.hide = function(){
	$('#plugpro-menu').removeClass("expanded");
	this.visible = false;
};

/**
 * Determine correct transition event name
 * @returns {string} The name of the transition event used by the user's browser
 */
Menu.prototype.getTransitionEvent = function( el ){
	var el = el || document.createElement('div');
	var animations = {
		'animation':'transitionend',
		'OAnimation':'oTransitionEnd',
		'MozAnimation':'transitionend',
		'WebkitAnimation':'webkitTransitionEnd'
	};

	for(var t in animations){
		if( el.style[t] !== undefined ){
			return animations[t];
		}
	}
};

module.exports = Menu;<commit_msg>Move event initialization to its own method<commit_after>/**
 * UI for the PlugPro Menu
 * @module settings/AutoWootToggle
 */

/**
 * Menu UI constructor
 * @constructor
 * @param {object} JST - Javascript HTML templates
 * @param {object} toggleSettings - List of settings and their corresponding togglers
 */
function Menu( JST, toggleSettings ){
	this.$parent = $('#app-menu');
	this.visible = false;

	// Load menu template
	var menuHTML = JST['src/html_templates/menu.html']({
		chromeDir: 'chrome-extension://' + $('#plug_pro_chrome_extension_id').val()
	});
	this.$parent.append( menuHTML );

	// Add toggle settings
	var toggleSettingsUL = this.$parent.find('#pro-toggle-settings');
	var setting;
	for( setting in toggleSettings ){
		var toggleSettingHTML = JST['src/html_templates/toggle_setting.html']({
			title: setting
		});

		toggleSettingsUL.append( toggleSettingHTML );
	}

	this.initializeEvents();

}

/**
 * Adds change events to menu items
 */
Menu.prototype.initializeEvents = function(){
	// Detect Plug.DJ menu animations to trigger Pro menu open/close
	this.$parent.find('.list')[0].addEventListener(
		this.getTransitionEvent(),
		this.toggle.bind(this),
		false
	);

	// Prevent menu from closing when clicking in the Pro Menu
	document.addEventListener("mousedown", function(event){
		var target = $(event.target);
		if(
			event.target.id === "plugpro-menu" ||
			target.parents('#plugpro-menu').length > 0
		){
			event.stopPropagation();
		}
	}, true);
};

/**
 * Toggle Pro menu visibility
 */
Menu.prototype.toggle = function(){
	var left = this.$parent.find('.list').css("left");
	if( left === "0px" ){
		this.show();
	}else{
		this.hide();
	}
};

/**
 * Make Pro menu visible
 */
Menu.prototype.show = function(){
	$('#plugpro-menu').addClass("expanded");
	this.visible = true;
};

/**
 * Make Pro menu hidden
 */
Menu.prototype.hide = function(){
	$('#plugpro-menu').removeClass("expanded");
	this.visible = false;
};

/**
 * Determine correct transition event name
 * @returns {string} The name of the transition event used by the user's browser
 */
Menu.prototype.getTransitionEvent = function( el ){
	var el = el || document.createElement('div');
	var animations = {
		'animation':'transitionend',
		'OAnimation':'oTransitionEnd',
		'MozAnimation':'transitionend',
		'WebkitAnimation':'webkitTransitionEnd'
	};

	for(var t in animations){
		if( el.style[t] !== undefined ){
			return animations[t];
		}
	}
};

module.exports = Menu;<|endoftext|>


<commit_before>
function Page ( id, x18nPrefix, onTop, onLeave ) {

	const tab  = document.createElement( 'div' );
	const page = document.createElement( 'div' );

	page.classList.add( 'page' );

	tab.classList.add( id );
	tab.classList.add( 'tab' );

	this.page = page;
	this.tab = tab;
	this.onTop = onTop;
	this.frame = null;
	this.onLeave = onLeave;
	this.slide = undefined;
	this.x18nPrefix = x18nPrefix + '.';
	this.onChange = null;
	this.id = id;

}

Page.prototype.constructor = Page;

Page.prototype.i18n = function ( text ) {

	const cfg = this.frame.ctx.cfg;
	const tr = cfg.i18n( this.x18nPrefix + text );

	return ( tr === undefined ) ? text : tr;

};

Page.prototype.addListener = function ( obj, name, handler ) {

	this.frame.addListener( obj, name, handler );
	// redirect to frame method - allows later rework to page specific destruction

};

Page.prototype.tabHandleClick = function ( event ) {

	event.preventDefault();
	event.stopPropagation();

	this.open();

};

Page.prototype.open = function () {

	const tab = this.tab;
	const pages = this.frame.pages;

	tab.classList.add( 'toptab' );

	this.frame.onScreen( this.i18n( 'title' ) );
	this.frame.openPageId = this.id;

	pages.forEach( function ( page ) {

		const otherPage = page.page;
		const otherTab = page.tab;
		const owner = page.owner;

		if ( otherTab === tab ) {

			otherPage.style.display = 'block';

		} else {

			otherPage.style.display = 'none';

			if ( otherTab.classList.contains( 'toptab' ) ) {

				otherTab.classList.remove( 'toptab' );

				if ( owner.onLeave !== undefined ) owner.onLeave();

			}

		}

	} );

};

Page.prototype.appendChild = function ( domElement ) {

	this.page.appendChild( domElement );

	return domElement;

};

Page.prototype.addHeader = function ( text ) {

	const div = document.createElement( 'div' );

	div.classList.add( 'header' );
	div.textContent = this.i18n( text );

	this.page.appendChild( div );

	return div;

};

Page.prototype.addCollapsingHeader = function ( text ) {

	const div = document.createElement( 'div' );

	div.classList.add( 'header' );
	div.textContent = this.i18n( text );
	div.classList.add( 'header_full' );

	this.page.appendChild( div );

	const container = document.createElement( 'div' );

	container.classList.add( 'container_full' );

	this.page.appendChild( container );

	div.addEventListener( 'click', function () {

		var redraw; // eslint-disable-line no-unused-vars

		if ( div.classList.contains( 'header_collapsed' ) ) {

			container.style.display = 'block';

			container.addEventListener( 'transitionend', _onReveal );

			redraw = container.clientHeight; // lgtm
			container.classList.remove( 'container_collapsed' );

		} else {

			container.addEventListener( 'transitionend', _onCollapse );

			container.classList.add( 'container_collapsed' );

		}

		function _onReveal () {

			container.removeEventListener( 'transitionend', _onReveal );

			div.classList.remove( 'header_collapsed' );

		}

		function _onCollapse () {

			container.removeEventListener( 'transitionend', _onCollapse );

			div.classList.add( 'header_collapsed' );
			container.style.display = 'none';

		}

	} );

	return container;

};

Page.prototype.addText = function ( text ) {

	const p = this.addLine( text );

	p.classList.add( 'spaced' );

	return p;

};

Page.prototype.addLine = function ( text ) {

	const p = document.createElement( 'p' );

	p.textContent = text;

	this.page.appendChild( p );

	return p;

};

Page.prototype.addLink = function ( url, text ) {

	const a = document.createElement( 'a' );

	a.href = url;
	a.textContent = text;
	a.target = '_blank';

	this.page.appendChild( a );

	return a;

};

Page.prototype.addSelect = function ( title, obj, trgObj, property, replace ) {

	const div    = document.createElement( 'div' );
	const label  = document.createElement( 'label' );
	const select = document.createElement( 'select' );

	div.classList.add( 'control' );

	if ( obj instanceof Array ) {

		obj.forEach( function ( element ) {

			const opt = document.createElement( 'option' );

			opt.value = element;
			opt.text = element;

			if ( opt.text === trgObj[ property ] ) opt.selected = true;

			select.add( opt, null );

		} );

	} else {

		for ( var p in obj ) {

			const opt = document.createElement( 'option' );
			const self = this;

			// translate each space delimited substring of ui text
			opt.text = p.split( ' ' ).reduce( function ( res, val) { return res + ' ' + self.i18n( val ); }, '' ).trim();
			opt.value = obj[ p ];

			if ( opt.value == trgObj[ property ] ) opt.selected = true;

			select.add( opt, null );

		}

	}

	const frame = this.frame;

	this.addListener( select, 'change', function onChange ( event ) { frame.inHandler = true; trgObj[ property ] = event.target.value; frame.inHandler = false; } );

	label.textContent = this.i18n( title );
	label.classList.add( 'cv-select' );

	frame.controls[ property ] = select;

	div.appendChild( label );
	div.appendChild( select );

	if ( replace === undefined ) {

		this.page.appendChild( div );

	} else {

		this.page.replaceChild( div, replace );

	}

	return div;

};

Page.prototype.addFileSelect = function ( title, obj, trgObj, property ) {

	const frame = this.frame;
	const div = this.addSelect( title, obj, trgObj, property );

	const label = div.firstChild;
	const id = 'cv-' + frame.getSeq();

	label.for = id;
	label.classList.add( 'cv-file-label' );

	const input = document.createElement( 'input' );

	input.id = id;
	input.classList.add( 'cv-file' );
	input.type = 'file';
	input.accept = '.svx,.lox,.plt';
	input.multiple = true;

	this.addListener( input, 'change', function _handleFileChange () {

		const count = input.files.length;
		const files = [];

		if ( count > 0 ) {

			for ( var i = 0; i < count; i++ ) files.push( input.files[ i ] );

			trgObj[ property ] = files;

		}

	} );

	label.appendChild( input );

	return div;

};

Page.prototype.addCheckbox = function ( title, obj, property ) {

	const frame = this.frame;
	const label = document.createElement( 'label' );
	const cb    = document.createElement( 'input' );
	const div   = document.createElement( 'div' );

	const id = 'cv-' + frame.getSeq();

	div.classList.add( 'control' );

	cb.type = 'checkbox';
	cb.checked = obj[ property ];
	cb.id = id;

	label.textContent = this.i18n( title );
	label.htmlFor = id;
	label.classList.add( 'check' );

	this.addListener( cb, 'change', _checkboxChanged );

	frame.controls[ property ] = cb;

	div.appendChild( cb );
	div.appendChild( label );

	this.page.appendChild( div );

	return div;

	function _checkboxChanged ( event ) {

		frame.inHandler = true;

		obj[ property ] = event.target.checked;

		frame.inHandler = false;

	}

};

Page.prototype.addRange = function ( title, obj, property ) {

	const frame = this.frame;
	const div = document.createElement( 'div' );
	const label = document.createElement( 'label' );
	const range = document.createElement( 'input' );

	div.classList.add( 'control' );

	range.type = 'range';

	range.min = 0;
	range.max = 1;

	range.step = 0.05;
	range.value = obj[ property ];

	this.addListener( range, 'input', _rangeChanged );
	this.addListener( range, 'change', _rangeChanged ); // for IE11 support

	label.textContent = this.i18n( title );
	label.classList.add( 'cv-range' );

	frame.controls[ property ] = range;

	div.appendChild( label );
	div.appendChild( range );

	this.page.appendChild( div );

	return div;

	function _rangeChanged ( event ) {

		frame.inHandler = true;

		obj[ property ] = event.target.value;

		frame.inHandler = false;

	}

};

Page.prototype.addSlide = function ( domElement, depth ) {

	const slide = document.createElement( 'div' );

	slide.classList.add( 'slide' );
	slide.style.zIndex = 200 - depth;

	slide.appendChild( domElement );

	this.page.appendChild( slide );

	this.slide = slide;
	this.slideDepth = depth;

	return slide;

};

Page.prototype.replaceSlide = function ( domElement, depth ) {

	const newSlide = document.createElement( 'div' );
	const page = this.page;

	var oldSlide = this.slide;

	var redraw; // eslint-disable-line no-unused-vars

	newSlide.classList.add( 'slide' );
	newSlide.style.zIndex = 200 - depth;

	if ( depth < this.slideDepth ) {

		newSlide.classList.add( 'slide-out' );

	}

	newSlide.appendChild( domElement );

	page.appendChild( newSlide );

	if ( depth > this.slideDepth ) {

		oldSlide.addEventListener( 'transitionend', afterSlideOut );
		oldSlide.classList.add( 'slide-out' );

		redraw = oldSlide.clientHeight; // lgtm

	} else if ( depth < this.slideDepth ) {

		newSlide.addEventListener( 'transitionend', afterSlideIn );

		redraw = newSlide.clientHeight; // lgtm

		newSlide.classList.remove( 'slide-out' );

	} else {

		page.removeChild( oldSlide );

	}

	this.slide = newSlide;
	this.slideDepth = depth;

	return newSlide;

	function afterSlideOut () {

		oldSlide.removeEventListener( 'transitionend', afterSlideOut );
		page.removeChild( oldSlide );

		oldSlide = null;

	}

	function afterSlideIn () {

		page.removeChild( oldSlide );
		newSlide.removeEventListener( 'transitionend', afterSlideIn );

		oldSlide = null;

	}

};

Page.prototype.addButton = function ( title, func ) {

	const button = document.createElement( 'button' );

	button.type = 'button';
	button.textContent = this.i18n( title );

	this.addListener( button, 'click', func );

	this.page.appendChild( button );

	return button;

};

Page.prototype.addTextBox = function ( labelText, placeholder, getResultGetter ) {

	const div = document.createElement( 'div' );
	const label = document.createElement( 'label' );

	label.textContent = this.i18n( labelText );

	const input = document.createElement( 'input' );

	var value;

	input.type = 'text';
	input.placeholder = placeholder;

	div.appendChild( label );
	div.appendChild( input );

	this.page.appendChild( div );

	this.addListener( input, 'change', function ( e ) { value = e.target.value; return true; } ) ;

	getResultGetter( _result );

	return div;

	function _result() {

		input.value = '';
		return value;

	}

};

Page.prototype.addDownloadButton = function ( title, urlProvider, fileName ) {

	const a = document.createElement( 'a' );

	if ( typeof a.download === 'undefined' ) return null;

	this.addListener( a, 'click', _setHref );

	a.textContent = this.i18n( title );
	a.type = 'download';
	a.download = fileName;
	a.href = 'javascript:void();';

	a.classList.add( 'download' );

	this.page.appendChild( a );

	return a;

	function _setHref() {

		a.href = urlProvider( a );

	}

};

Page.canDownload = function () {

	const a = document.createElement( 'a' );
	return ( typeof a.download !== 'undefined' );

};

Page.prototype.download = function ( data, fileName ) {

	const a = document.createElement( 'a' );

	if ( typeof a.download === 'undefined' ) return null;

	a.type = 'download';
	a.download = fileName;
	a.href = data;
	a.click();

};

Page.prototype.addColor = function ( title, name ) {

	const frame = this.frame;
	const label = document.createElement( 'label' );
	const cb    = document.createElement( 'input' );
	const div   = document.createElement( 'div' );
	const cfg = frame.ctx.cfg;

	const id = 'cv-' + frame.getSeq();

	div.classList.add( 'control' );

	cb.type = 'color';
	cb.value = cfg.themeColorHex( name ),

	cb.id = id;

	label.textContent = this.i18n( title );
	label.htmlFor = id;
	label.classList.add( 'color' );

	this.addListener( cb, 'change', _colorChanged );

	frame.controls[ name ] = cb;

	div.appendChild( cb );
	div.appendChild( label );

	this.page.appendChild( div );

	return div;

	function _colorChanged ( event ) {

		frame.inHandler = true;

		cfg.setThemeColorCSS( name, event.target.value );

		frame.inHandler = false;

	}

};

Page.prototype.addLogo = function () {

	const img = document.createElement( 'div' );

	img.classList.add( 'logo' );
	img.title = 'logo';

	this.appendChild( img );

};

Page.prototype.dispose = function () {
	if ( this._dispose ) this._dispose();
};

export { Page };<commit_msg>share common code<commit_after>
function Page ( id, x18nPrefix, onTop, onLeave ) {

	const tab  = document.createElement( 'div' );
	const page = document.createElement( 'div' );

	page.classList.add( 'page' );

	tab.classList.add( id );
	tab.classList.add( 'tab' );

	this.page = page;
	this.tab = tab;
	this.onTop = onTop;
	this.frame = null;
	this.onLeave = onLeave;
	this.slide = undefined;
	this.x18nPrefix = x18nPrefix + '.';
	this.onChange = null;
	this.id = id;

}

Page.prototype.constructor = Page;

Page.prototype.i18n = function ( text ) {

	const cfg = this.frame.ctx.cfg;
	const tr = cfg.i18n( this.x18nPrefix + text );

	return ( tr === undefined ) ? text : tr;

};

Page.prototype.addListener = function ( obj, name, handler ) {

	this.frame.addListener( obj, name, handler );
	// redirect to frame method - allows later rework to page specific destruction

};

Page.prototype.tabHandleClick = function ( event ) {

	event.preventDefault();
	event.stopPropagation();

	this.open();

};

Page.prototype.open = function () {

	const tab = this.tab;
	const pages = this.frame.pages;

	tab.classList.add( 'toptab' );

	this.frame.onScreen( this.i18n( 'title' ) );
	this.frame.openPageId = this.id;

	pages.forEach( function ( page ) {

		const otherPage = page.page;
		const otherTab = page.tab;
		const owner = page.owner;

		if ( otherTab === tab ) {

			otherPage.style.display = 'block';

		} else {

			otherPage.style.display = 'none';

			if ( otherTab.classList.contains( 'toptab' ) ) {

				otherTab.classList.remove( 'toptab' );

				if ( owner.onLeave !== undefined ) owner.onLeave();

			}

		}

	} );

};

Page.prototype.appendChild = function ( domElement ) {

	this.page.appendChild( domElement );

	return domElement;

};

Page.prototype.addHeader = function ( text ) {

	const div = document.createElement( 'div' );

	div.classList.add( 'header' );
	div.textContent = this.i18n( text );

	this.page.appendChild( div );

	return div;

};

Page.prototype.addCollapsingHeader = function ( text ) {

	const div = document.createElement( 'div' );

	div.classList.add( 'header' );
	div.textContent = this.i18n( text );
	div.classList.add( 'header_full' );

	this.page.appendChild( div );

	const container = document.createElement( 'div' );

	container.classList.add( 'container_full' );

	this.page.appendChild( container );

	div.addEventListener( 'click', function () {

		var redraw; // eslint-disable-line no-unused-vars

		if ( div.classList.contains( 'header_collapsed' ) ) {

			container.style.display = 'block';

			container.addEventListener( 'transitionend', _onReveal );

			redraw = container.clientHeight; // lgtm
			container.classList.remove( 'container_collapsed' );

		} else {

			container.addEventListener( 'transitionend', _onCollapse );

			container.classList.add( 'container_collapsed' );

		}

		function _onReveal () {

			container.removeEventListener( 'transitionend', _onReveal );

			div.classList.remove( 'header_collapsed' );

		}

		function _onCollapse () {

			container.removeEventListener( 'transitionend', _onCollapse );

			div.classList.add( 'header_collapsed' );
			container.style.display = 'none';

		}

	} );

	return container;

};

Page.prototype.addText = function ( text ) {

	const p = this.addLine( text );

	p.classList.add( 'spaced' );

	return p;

};

Page.prototype.addLine = function ( text ) {

	const p = document.createElement( 'p' );

	p.textContent = text;

	this.page.appendChild( p );

	return p;

};

Page.prototype.addLink = function ( url, text ) {

	const a = document.createElement( 'a' );

	a.href = url;
	a.textContent = text;
	a.target = '_blank';

	this.page.appendChild( a );

	return a;

};

Page.prototype.makeLabel = function ( title, labelClass, idFor = 'na' ) {

	const label = document.createElement( 'label' );

	label.textContent = this.i18n( title );
	label.htmlFor = idFor;
	label.classList.add( labelClass );

	return label;

};

Page.prototype.addSelect = function ( title, obj, trgObj, property, replace ) {

	const div    = document.createElement( 'div' );
	const select = document.createElement( 'select' );

	div.classList.add( 'control' );

	if ( obj instanceof Array ) {

		obj.forEach( function ( element ) {

			const opt = document.createElement( 'option' );

			opt.value = element;
			opt.text = element;

			if ( opt.text === trgObj[ property ] ) opt.selected = true;

			select.add( opt, null );

		} );

	} else {

		for ( var p in obj ) {

			const opt = document.createElement( 'option' );

			// translate each space delimited substring of ui text
			opt.text = p.split( ' ' ).reduce( ( res, val ) => { return res + ' ' + this.i18n( val ); }, '' ).trim();
			opt.value = obj[ p ];

			if ( opt.value == trgObj[ property ] ) opt.selected = true;

			select.add( opt, null );

		}

	}

	const frame = this.frame;

	this.addListener( select, 'change', function onChange ( event ) { frame.inHandler = true; trgObj[ property ] = event.target.value; frame.inHandler = false; } );

	frame.controls[ property ] = select;

	div.appendChild( this.makeLabel( title, 'cv-select' ) );
	div.appendChild( select );

	if ( replace === undefined ) {

		this.page.appendChild( div );

	} else {

		this.page.replaceChild( div, replace );

	}

	return div;

};

Page.prototype.addFileSelect = function ( title, obj, trgObj, property ) {

	const frame = this.frame;
	const div = this.addSelect( title, obj, trgObj, property );

	const label = div.firstChild;
	const id = 'cv-' + frame.getSeq();

	label.for = id;
	label.classList.add( 'cv-file-label' );

	const input = document.createElement( 'input' );

	input.id = id;
	input.classList.add( 'cv-file' );
	input.type = 'file';
	input.accept = '.svx,.lox,.plt';
	input.multiple = true;

	this.addListener( input, 'change', function _handleFileChange () {

		const count = input.files.length;
		const files = [];

		if ( count > 0 ) {

			for ( var i = 0; i < count; i++ ) files.push( input.files[ i ] );

			trgObj[ property ] = files;

		}

	} );

	label.appendChild( input );

	return div;

};

Page.prototype.addCheckbox = function ( title, obj, property ) {

	const frame = this.frame;
	const cb    = document.createElement( 'input' );
	const div   = document.createElement( 'div' );

	const id = 'cv-' + frame.getSeq();

	div.classList.add( 'control' );

	cb.type = 'checkbox';
	cb.checked = obj[ property ];
	cb.id = id;

	this.addListener( cb, 'change', _checkboxChanged );

	frame.controls[ property ] = cb;

	div.appendChild( cb );
	div.appendChild( this.makeLabel( title, 'check', id ) );

	this.page.appendChild( div );

	return div;

	function _checkboxChanged ( event ) {

		frame.inHandler = true;

		obj[ property ] = event.target.checked;

		frame.inHandler = false;

	}

};

Page.prototype.addRange = function ( title, obj, property ) {

	const frame = this.frame;
	const div = document.createElement( 'div' );
	const range = document.createElement( 'input' );

	div.classList.add( 'control' );

	range.type = 'range';

	range.min = 0;
	range.max = 1;

	range.step = 0.05;
	range.value = obj[ property ];

	this.addListener( range, 'input', _rangeChanged );
	this.addListener( range, 'change', _rangeChanged ); // for IE11 support

	frame.controls[ property ] = range;

	div.appendChild( this.makeLabel( title, 'cv-range' ) );
	div.appendChild( range );

	this.page.appendChild( div );

	return div;

	function _rangeChanged ( event ) {

		frame.inHandler = true;

		obj[ property ] = event.target.value;

		frame.inHandler = false;

	}

};

Page.prototype.addSlide = function ( domElement, depth ) {

	const slide = document.createElement( 'div' );

	slide.classList.add( 'slide' );
	slide.style.zIndex = 200 - depth;

	slide.appendChild( domElement );

	this.page.appendChild( slide );

	this.slide = slide;
	this.slideDepth = depth;

	return slide;

};

Page.prototype.replaceSlide = function ( domElement, depth ) {

	const newSlide = document.createElement( 'div' );
	const page = this.page;

	var oldSlide = this.slide;

	var redraw; // eslint-disable-line no-unused-vars

	newSlide.classList.add( 'slide' );
	newSlide.style.zIndex = 200 - depth;

	if ( depth < this.slideDepth ) {

		newSlide.classList.add( 'slide-out' );

	}

	newSlide.appendChild( domElement );

	page.appendChild( newSlide );

	if ( depth > this.slideDepth ) {

		oldSlide.addEventListener( 'transitionend', afterSlideOut );
		oldSlide.classList.add( 'slide-out' );

		redraw = oldSlide.clientHeight; // lgtm

	} else if ( depth < this.slideDepth ) {

		newSlide.addEventListener( 'transitionend', afterSlideIn );

		redraw = newSlide.clientHeight; // lgtm

		newSlide.classList.remove( 'slide-out' );

	} else {

		page.removeChild( oldSlide );

	}

	this.slide = newSlide;
	this.slideDepth = depth;

	return newSlide;

	function afterSlideOut () {

		oldSlide.removeEventListener( 'transitionend', afterSlideOut );
		page.removeChild( oldSlide );

		oldSlide = null;

	}

	function afterSlideIn () {

		page.removeChild( oldSlide );
		newSlide.removeEventListener( 'transitionend', afterSlideIn );

		oldSlide = null;

	}

};

Page.prototype.addButton = function ( title, func ) {

	const button = document.createElement( 'button' );

	button.type = 'button';
	button.textContent = this.i18n( title );

	this.addListener( button, 'click', func );

	this.page.appendChild( button );

	return button;

};

Page.prototype.addTextBox = function ( title, placeholder, getResultGetter ) {

	const div = document.createElement( 'div' );
	const input = document.createElement( 'input' );

	var value;

	input.type = 'text';
	input.placeholder = placeholder;

	div.appendChild( this.makeLabel( title, 'text' ) );
	div.appendChild( input );

	this.page.appendChild( div );

	this.addListener( input, 'change', function ( e ) { value = e.target.value; return true; } ) ;

	getResultGetter( _result );

	return div;

	function _result() {

		input.value = '';
		return value;

	}

};

Page.prototype.addDownloadButton = function ( title, urlProvider, fileName ) {

	const a = document.createElement( 'a' );

	if ( typeof a.download === 'undefined' ) return null;

	this.addListener( a, 'click', _setHref );

	a.textContent = this.i18n( title );
	a.type = 'download';
	a.download = fileName;
	a.href = 'javascript:void();';

	a.classList.add( 'download' );

	this.page.appendChild( a );

	return a;

	function _setHref() {

		a.href = urlProvider( a );

	}

};

Page.canDownload = function () {

	const a = document.createElement( 'a' );
	return ( typeof a.download !== 'undefined' );

};

Page.prototype.download = function ( data, fileName ) {

	const a = document.createElement( 'a' );

	if ( typeof a.download === 'undefined' ) return null;

	a.type = 'download';
	a.download = fileName;
	a.href = data;
	a.click();

};

Page.prototype.addColor = function ( title, name ) {

	const frame = this.frame;
	const cb    = document.createElement( 'input' );
	const div   = document.createElement( 'div' );
	const cfg = frame.ctx.cfg;

	const id = 'cv-' + frame.getSeq();

	div.classList.add( 'control' );

	cb.type = 'color';
	cb.value = cfg.themeColorHex( name ),

	cb.id = id;

	this.addListener( cb, 'change', _colorChanged );

	frame.controls[ name ] = cb;

	div.appendChild( cb );
	div.appendChild( this.makeLabel( title, 'color', id ) );

	this.page.appendChild( div );

	return div;

	function _colorChanged ( event ) {

		frame.inHandler = true;

		cfg.setThemeColorCSS( name, event.target.value );

		frame.inHandler = false;

	}

};

Page.prototype.addLogo = function () {

	const img = document.createElement( 'div' );

	img.classList.add( 'logo' );
	img.title = 'logo';

	this.appendChild( img );

};

Page.prototype.dispose = function () {
	if ( this._dispose ) this._dispose();
};

export { Page };<|endoftext|>


<commit_before>

function Page( id ) {

	var tab  = document.createElement( 'div' );
	var page = document.createElement( 'div' );

	var frame = Page.frame;

	page.classList.add( 'page' );

	tab.id = id;
	tab.classList.add( 'tab' );
	tab.addEventListener( 'click', this.tabHandleClick );
	tab.style.top = ( Page.position++ * 40 ) + 'px';

	if ( frame === null ) {

		// create UI side panel and reveal tabs
		frame = document.createElement( 'div' );

		frame.id = 'frame';
		frame.style.display = 'block';

		Page.frame = frame;

		var close = document.createElement( 'div' );

		close.id = 'close';

		close.addEventListener( 'click', _closeFrame );

		frame.appendChild( close );

	}

	frame.appendChild( tab );
	frame.appendChild( page );

	Page.pages.push( { tab: tab, page: page } );

	this.page = page;
	this.slide = undefined;

	function _closeFrame ( event ) {

		event.target.parentElement.classList.remove( 'onscreen' );

	}

}

Page.pages     = [];
Page.position  = 0;
Page.inHandler = false;
Page.controls  = [];
Page.frame = null;

Page.reset = function () {

	Page.pages     = [];
	Page.position  = 0;
	Page.inHandler = false;
	Page.controls  = [];
	Page.frame     = null;

};

Page.clear = function () {

	Page.frame.addEventListener( 'transitionend', _afterReset );
	Page.frame.classList.remove( 'onscreen' );

	function _afterReset ( event ) {

		var frame = event.target;

		frame.removeEventListener( 'transitionend', _afterReset );

		if ( frame !== null ) frame.parentElement.removeChild( frame );

	}

};

Page.handleChange = function ( event ) {

	var obj = event.target;
	var property = event.name;

	if ( !Page.inHandle ) {

		if ( Page.controls[ property ] ) {

			var ctrl = Page.controls[ property ];

			switch ( ctrl.type ) {

			case 'checkbox':

				ctrl.checked = obj[ property ];

				break;

			case 'select-one':
			case 'range':

				ctrl.value = obj[ property ];

				break;

			case 'download':

				ctrl.href = obj[ property ];

				break;

			}

		}

	}

};

Page.prototype.constructor = Page;

Page.prototype.tabHandleClick = function ( event ) {

	var tab = event.target;
	var pages = Page.pages;

	tab.classList.add( 'toptab' );
	tab.parentElement.classList.add( 'onscreen' );

	for ( var i = 0, l = pages.length; i < l; i++ ) {

		var otherTab  = pages[ i ].tab;
		var otherPage = pages[ i ].page;

		if ( otherTab === tab ) {

			otherPage.style.display = 'block';

		} else {

			otherTab.classList.remove( 'toptab' );
			otherPage.style.display = 'none';

		}

	}

};

Page.prototype.appendChild = function ( domElement ) {

	this.page.appendChild( domElement );

};

Page.prototype.addHeader = function ( text ) {

	var div = document.createElement( 'div' );

	div.classList.add( 'header' );
	div.textContent = text;
	this.page.appendChild( div );

	return div;

};

Page.prototype.addSelect = function ( title, obj, trgObj, property ) {

	var div    = document.createElement( 'div' );
	var label  = document.createElement( 'label' );
	var select = document.createElement( 'select' );
	var opt;

	div.classList.add( 'control' );

	if ( obj instanceof Array ) {

		for ( var i = 0, l = obj.length; i < l; i++ ) {

			opt = document.createElement( 'option' );

			opt.value = i;
			opt.text  = obj[ i ];

			if ( opt.text === trgObj[ property ] ) opt.selected = true;

			select.add( opt, null );

		}

		select.addEventListener( 'change', function ( event ) { Page.inHandler = true; trgObj[ property ] = obj[ event.target.value ]; Page.inHandler = false; } );

	} else {

		for ( var p in obj ) {

			opt = document.createElement( 'option' );

			opt.text  = p;
			opt.value = obj[ p ];

			if ( opt.value == trgObj[ property ] ) opt.selected = true;

			select.add( opt, null );

		}

		select.addEventListener( 'change', function ( event ) { Page.inHandler = true; trgObj[ property ] = event.target.value; Page.inHandler = false; } );

	}

	label.textContent = title;

	Page.controls[ property ] = select;

	div.appendChild( label );
	div.appendChild( select );

	this.page.appendChild( div );

	return div;

};

Page.prototype.addCheckbox = function ( title, obj, property ) {

	var label = document.createElement( 'label' );
	var cb    = document.createElement( 'input' );

	label.textContent = title;

	cb.type    = 'checkbox';
	cb.checked = obj[ property ];

	cb.addEventListener( 'change', _checkboxChanged );

	Page.controls[ property ] = cb;

	label.appendChild( cb );

	this.page.appendChild( label );

	return;

	function _checkboxChanged ( event ) {

		Page.inHandler = true;

		obj[ property ] = event.target.checked;

		Page.inHandler = false;

	}

};

Page.prototype.addRange = function ( title, obj, property ) {

	var div = document.createElement( 'div' );
	var label = document.createElement( 'label' );
	var range = document.createElement( 'input' );

	div.classList.add( 'control' );

	range.type = 'range';

	range.min  = 0;
	range.max  = 1;

	range.step = 0.05;
	range.value = obj[ property ];

	range.addEventListener( 'input', _rangeChanged );
	range.addEventListener( 'change', _rangeChanged ); // for IE11 support

	label.textContent = title;

	Page.controls[ property ] = range;

	div.appendChild( label );
	div.appendChild( range );

	this.page.appendChild( div );

	return div;

	function _rangeChanged ( event ) {

		Page.inHandler = true;

		obj[ property ] = event.target.value;

		Page.inHandler = false;

	}

};

Page.prototype.addSlide = function ( domElement, depth, handleClick ) {

	var slide = document.createElement( 'div' );

	slide.classList.add( 'slide' );
	slide.style.zIndex = 200 - depth;

	slide.addEventListener( 'click', handleClick );
	slide.appendChild( domElement );

	this.page.appendChild( slide );

	this.slide = slide;
	this.slideDepth = depth;

	return slide;

};

Page.prototype.replaceSlide = function ( domElement, depth, handleClick ) {

	var newSlide = document.createElement( 'div' );
	var oldSlide = this.slide;
	var page = this.page;
	var redraw; // eslint-disable-line no-unused-vars

	newSlide.classList.add( 'slide' );
	newSlide.style.zIndex = 200 - depth;
	newSlide.addEventListener( 'click', handleClick );

	if ( depth < this.slideDepth ) {

		newSlide.classList.add( 'slide-out' );

	}

	newSlide.appendChild( domElement );

	page.appendChild( newSlide );

	if ( depth > this.slideDepth ) {

		oldSlide.addEventListener( 'transitionend', afterSlideOut );
		oldSlide.classList.add( 'slide-out' );

		redraw = oldSlide.clientHeight;

	} else if ( depth < this.slideDepth ) {

		newSlide.addEventListener( 'transitionend', afterSlideIn );

		redraw = newSlide.clientHeight;

		newSlide.classList.remove( 'slide-out' );

	} else {

		page.removeChild( oldSlide );

	}

	this.slide = newSlide;
	this.slideDepth = depth;

	return;

	function afterSlideOut () {

		oldSlide.removeEventListener( 'transitionend', afterSlideOut );
		page.removeChild( oldSlide );

	}

	function afterSlideIn () {

		page.removeChild( oldSlide );
		newSlide.removeEventListener( 'transitionend', afterSlideIn );

	}

};

Page.prototype.addDownloadButton = function ( title, obj, property, fileName ) {

	var a = document.createElement( 'a' );

	if ( typeof a.download === 'undefined' ) return false;

	a.textContent = title;
	a.type = 'download';
	a.download = fileName;
	a.href = obj[ property ];

	Page.controls[ property ] = a;

	this.page.appendChild( a );

};

export { Page };

// EOF<commit_msg>add new Page method<commit_after>

function Page( id ) {

	var tab  = document.createElement( 'div' );
	var page = document.createElement( 'div' );

	var frame = Page.frame;

	page.classList.add( 'page' );

	tab.id = id;
	tab.classList.add( 'tab' );
	tab.addEventListener( 'click', this.tabHandleClick );
	tab.style.top = ( Page.position++ * 40 ) + 'px';

	if ( frame === null ) {

		// create UI side panel and reveal tabs
		frame = document.createElement( 'div' );

		frame.id = 'frame';
		frame.style.display = 'block';

		Page.frame = frame;

		var close = document.createElement( 'div' );

		close.id = 'close';

		close.addEventListener( 'click', _closeFrame );

		frame.appendChild( close );

	}

	frame.appendChild( tab );
	frame.appendChild( page );

	Page.pages.push( { tab: tab, page: page } );

	this.page = page;
	this.slide = undefined;

	function _closeFrame ( event ) {

		event.target.parentElement.classList.remove( 'onscreen' );

	}

}

Page.pages     = [];
Page.position  = 0;
Page.inHandler = false;
Page.controls  = [];
Page.frame = null;

Page.reset = function () {

	Page.pages     = [];
	Page.position  = 0;
	Page.inHandler = false;
	Page.controls  = [];
	Page.frame     = null;

};

Page.clear = function () {

	Page.frame.addEventListener( 'transitionend', _afterReset );
	Page.frame.classList.remove( 'onscreen' );

	function _afterReset ( event ) {

		var frame = event.target;

		frame.removeEventListener( 'transitionend', _afterReset );

		if ( frame !== null ) frame.parentElement.removeChild( frame );

	}

};

Page.handleChange = function ( event ) {

	var obj = event.target;
	var property = event.name;

	if ( !Page.inHandle ) {

		if ( Page.controls[ property ] ) {

			var ctrl = Page.controls[ property ];

			switch ( ctrl.type ) {

			case 'checkbox':

				ctrl.checked = obj[ property ];

				break;

			case 'select-one':
			case 'range':

				ctrl.value = obj[ property ];

				break;

			case 'download':

				ctrl.href = obj[ property ];

				break;

			}

		}

	}

};

Page.prototype.constructor = Page;

Page.prototype.tabHandleClick = function ( event ) {

	var tab = event.target;
	var pages = Page.pages;

	tab.classList.add( 'toptab' );
	tab.parentElement.classList.add( 'onscreen' );

	for ( var i = 0, l = pages.length; i < l; i++ ) {

		var otherTab  = pages[ i ].tab;
		var otherPage = pages[ i ].page;

		if ( otherTab === tab ) {

			otherPage.style.display = 'block';

		} else {

			otherTab.classList.remove( 'toptab' );
			otherPage.style.display = 'none';

		}

	}

};

Page.prototype.appendChild = function ( domElement ) {

	this.page.appendChild( domElement );

};

Page.prototype.addHeader = function ( text ) {

	var div = document.createElement( 'div' );

	div.classList.add( 'header' );
	div.textContent = text;
	this.page.appendChild( div );

	return div;

};

Page.prototype.addText = function ( text ) {

	var p = document.createElement( 'p' );

	p.textContent = text;
	this.page.appendChild( p );

	return p;

};

Page.prototype.addSelect = function ( title, obj, trgObj, property ) {

	var div    = document.createElement( 'div' );
	var label  = document.createElement( 'label' );
	var select = document.createElement( 'select' );
	var opt;

	div.classList.add( 'control' );

	if ( obj instanceof Array ) {

		for ( var i = 0, l = obj.length; i < l; i++ ) {

			opt = document.createElement( 'option' );

			opt.value = i;
			opt.text  = obj[ i ];

			if ( opt.text === trgObj[ property ] ) opt.selected = true;

			select.add( opt, null );

		}

		select.addEventListener( 'change', function ( event ) { Page.inHandler = true; trgObj[ property ] = obj[ event.target.value ]; Page.inHandler = false; } );

	} else {

		for ( var p in obj ) {

			opt = document.createElement( 'option' );

			opt.text  = p;
			opt.value = obj[ p ];

			if ( opt.value == trgObj[ property ] ) opt.selected = true;

			select.add( opt, null );

		}

		select.addEventListener( 'change', function ( event ) { Page.inHandler = true; trgObj[ property ] = event.target.value; Page.inHandler = false; } );

	}

	label.textContent = title;

	Page.controls[ property ] = select;

	div.appendChild( label );
	div.appendChild( select );

	this.page.appendChild( div );

	return div;

};

Page.prototype.addCheckbox = function ( title, obj, property ) {

	var label = document.createElement( 'label' );
	var cb    = document.createElement( 'input' );

	label.textContent = title;

	cb.type    = 'checkbox';
	cb.checked = obj[ property ];

	cb.addEventListener( 'change', _checkboxChanged );

	Page.controls[ property ] = cb;

	label.appendChild( cb );

	this.page.appendChild( label );

	return;

	function _checkboxChanged ( event ) {

		Page.inHandler = true;

		obj[ property ] = event.target.checked;

		Page.inHandler = false;

	}

};

Page.prototype.addRange = function ( title, obj, property ) {

	var div = document.createElement( 'div' );
	var label = document.createElement( 'label' );
	var range = document.createElement( 'input' );

	div.classList.add( 'control' );

	range.type = 'range';

	range.min  = 0;
	range.max  = 1;

	range.step = 0.05;
	range.value = obj[ property ];

	range.addEventListener( 'input', _rangeChanged );
	range.addEventListener( 'change', _rangeChanged ); // for IE11 support

	label.textContent = title;

	Page.controls[ property ] = range;

	div.appendChild( label );
	div.appendChild( range );

	this.page.appendChild( div );

	return div;

	function _rangeChanged ( event ) {

		Page.inHandler = true;

		obj[ property ] = event.target.value;

		Page.inHandler = false;

	}

};

Page.prototype.addSlide = function ( domElement, depth, handleClick ) {

	var slide = document.createElement( 'div' );

	slide.classList.add( 'slide' );
	slide.style.zIndex = 200 - depth;

	slide.addEventListener( 'click', handleClick );
	slide.appendChild( domElement );

	this.page.appendChild( slide );

	this.slide = slide;
	this.slideDepth = depth;

	return slide;

};

Page.prototype.replaceSlide = function ( domElement, depth, handleClick ) {

	var newSlide = document.createElement( 'div' );
	var oldSlide = this.slide;
	var page = this.page;
	var redraw; // eslint-disable-line no-unused-vars

	newSlide.classList.add( 'slide' );
	newSlide.style.zIndex = 200 - depth;
	newSlide.addEventListener( 'click', handleClick );

	if ( depth < this.slideDepth ) {

		newSlide.classList.add( 'slide-out' );

	}

	newSlide.appendChild( domElement );

	page.appendChild( newSlide );

	if ( depth > this.slideDepth ) {

		oldSlide.addEventListener( 'transitionend', afterSlideOut );
		oldSlide.classList.add( 'slide-out' );

		redraw = oldSlide.clientHeight;

	} else if ( depth < this.slideDepth ) {

		newSlide.addEventListener( 'transitionend', afterSlideIn );

		redraw = newSlide.clientHeight;

		newSlide.classList.remove( 'slide-out' );

	} else {

		page.removeChild( oldSlide );

	}

	this.slide = newSlide;
	this.slideDepth = depth;

	return;

	function afterSlideOut () {

		oldSlide.removeEventListener( 'transitionend', afterSlideOut );
		page.removeChild( oldSlide );

	}

	function afterSlideIn () {

		page.removeChild( oldSlide );
		newSlide.removeEventListener( 'transitionend', afterSlideIn );

	}

};

Page.prototype.addDownloadButton = function ( title, obj, property, fileName ) {

	var a = document.createElement( 'a' );

	if ( typeof a.download === 'undefined' ) return false;

	a.textContent = title;
	a.type = 'download';
	a.download = fileName;
	a.href = obj[ property ];

	Page.controls[ property ] = a;

	this.page.appendChild( a );

};

export { Page };

// EOF<|endoftext|>