<commit_before>define(function (require) {
    var jquery = require("jquery");
    var activity = require("sugar-web/activity/activity");
    var palette = require("sugar-web/graphics/palette");
    var icon = require("sugar-web/graphics/icon");
    var dictstore = require("sugar-web/dictstore")
    var l10n = require("webL10n");
    var spritely = require("spritely");
    var words = null;

    function count(array) {
        var counter = 0;
        for (var i = 0; i < array.length; i++) {
            if (array[i]) {
                counter++;
            }
        }
        return counter;
    }

    function getWords(level) {
        if (words == null) {
            words = require("words");
        }
        return words[level][Math.floor(Math.random() * (words[level].length))];
    }

    function Game() {
        this.level = null;
        this.mode = null;
        this.currentWord = [];
        this.answer = '';
        this.boxGame = null;
        this.sentence = null;
        this.answerBox = null;
        this.error_count = 0;
        this.point_count = 0;
        this.win_level =  0;
        this.character = 0;
        this.data_level = Array(12);

        function onStoreReady() {
            if (localStorage['level']) {
                this.data_level = JSON.parse(localStorage['level']);
                console.log(this.data_level);
                for (var i = 1; i <= this.data_level.length; i++) {
                    if (this.data_level[i - 1]) {
                        document.getElementById(String(i)).className = 'world world-'+ i +' done';
                    }
                }
            }
        }

        dictstore.init(onStoreReady);

        this.init = function(level, mode) {
            this.level = level;
            this.mode = mode;
            this.point_count = 0;

            if (this.mode == '1') {
                this.win_level = 70;
            }
            else if (this.mode == '2') {
                this.win_level = 40;
            }

            document.getElementById('point-bar').innerHTML = '';
            document.getElementById('world-menu').classList.toggle('hidden');
            document.getElementById('box-game').classList.toggle('hidden');
            document.getElementById('point-bar').classList.toggle('hidden');
            document.getElementById('land').classList.toggle('hidden');
            document.getElementById('stop-game').classList.toggle('hidden');
            /*
            I didn't expect to use JQuery at the beginning, but it's required
            by the animation library.
            I hope you love spaguetti code.
            */
            $('#land').css('background', 'url(../images/land-' + level + '.png) left top repeat-x');
            $('#land').pan({fps: 30, speed: 0.7, dir: 'left'});
            $('#land').spStart();
            console.log('Iniciar animacion');
            if (this.character == 1) {
                document.getElementById('walking-character').className = 'boy-' +  level;
            }
            else {
                document.getElementById('walking-character').className = 'girl-' + level;
            }

            this.interface();
        }

        this.start = function() {
            this.currentWord = getWords(this.level);
            this.answer = this.currentWord['answer'];
            sentence.innerHTML = this.currentWord['sentence'];

            if (sentence.className == 'main-sentence') {
                sentence.className = '';
            }

            if (this.mode == '1') {
                document.getElementById('op1').innerHTML = this.currentWord['op1'];
                document.getElementById('op2').innerHTML = this.currentWord['op2'];
            }
        }

        this.interface = function() {
            document.getElementById('top-box').innerHTML = '

';
            boxGame = document.getElementById('box-game');
            sentence = document.getElementById('sentence');
            answerBox = document.getElementById('answer-box');
            if (this.mode == '1') {
                answerBox.innerHTML =
                    '
Selecciona la palabra correcta
' +
                    '
' +
                    '  <button id="op1"></button>' +
                    '
' +
                    '
' +
                    '  <button id="op2"></button>' +
                    '
';
                var op1 = document.getElementById('op1');
                var op2 = document.getElementById('op2');
                op1.addEventListener('click', function() {
                    game.checkAnswer(this.innerHTML);
                });
                op2.addEventListener('click', function() {
                    game.checkAnswer(this.innerHTML);
                });
            }

            else if (this.mode == '2') {
                answerBox.innerHTML =
                    '
Escribe la letra que falta
' +
                    '<input type="text" id="answer">';
                var answerInput = document.getElementById('answer');
                answerInput.addEventListener('input', function() {
                    var self = this;
                    setTimeout(function() {
                        game.checkAnswer(self.value);
                        self.value = '';
                    }, 900);
                });
            }

            this.start();
        }

        this.showError = function() {
            var topBox = document.getElementById('top-box');
            var answerBox = document.getElementById('answer-box');

            topBox.innerHTML =
            '
¡Has fallado...!
'+
            'Vuelve a intentarlo»';

            document.getElementById('restart').addEventListener('click', this.interface.bind(this), false);

            if (this.mode == '1') {
                answerBox.innerHTML =
                    '
Aprende la diferencia
' +
                    '
' +
                    '
' + this.currentWord['op1'] + '
' +
                    '
' + this.currentWord['op1_concept'] + '
' +
                    '
' +
                    '
' +
                    '
' + this.currentWord['op2'] + '
' +
                    '
' + this.currentWord['op2_concept'] + '
' +
                    '
';
            }
            else if (this.mode == '2') {
                answerBox.innerHTML =
                '
Aprende la regla:
' +
                '
' + this.currentWord['concept'] + '
';

            }

        }

        this.setBar = function() {
            var bar = document.getElementById('point-bar');
            bar.innerHTML = '';
            for (var i = this.point_count; i > 0; i--) {
                bar.innerHTML += '';
            }
        }
        var self = this;

        this.checkAnswer = function(answer) {
            if (answer.toLowerCase() == this.answer.toLowerCase()) {
                this.error_count = 0;
                this.point_count += 1;
                // Siguiente pregunta
                $('#walking-character').sprite({
                    fps: 3,
                    no_of_frames: 3,
                    play_frames: 3
                });
                if (this.point_count < this.win_level) {
                    this.setBar();
                    this.start();
                }

                // Fin de nivel
                else {
                    // var approvedLevels = JSON.parse(localStorage['level']);
                    // approvedLevels[parseInt(this.level) - 1] = true;
                    // localStorage['level'] = JSON.stringify(approvedLevels);
                    // dictstore.save();

                    // Fin de juego
                    if (count(this.data_level) >= 12) {
                        document.getElementById('history-end').classList.toggle('hidden');
                        document.getElementById('box-game').classList.toggle('hidden');
                        document.getElementById('point-bar').classList.toggle('hidden');
                        document.getElementById('walking-character').className = 'hidden';

                        document.getElementById('end-next').addEventListener('click', function() {
                            document.getElementById('world-menu').classList.toggle('hidden');
                            document.getElementById('history-end').classList.toggle('hidden');
                            document.getElementById('land').classList.toggle('hidden');
                            document.getElementById('stop-game').classList.toggle('hidden');
                            $('#land').spStop(true);

                        });
                    }
                    else {
                        var topBox = document.getElementById('top-box');
                        var answerBox = document.getElementById('answer-box');
                        topBox.innerHTML =
                        '
¡Felicidades, has completado este mundo!
';
                        answerBox.innerHTML =
                        '
Has ganado una medalla
' +
                        '

' +
                        '
<button id="next">Continuar</button>
';

                        document.getElementById('next').addEventListener('click', function() {
                            document.getElementById('world-menu').classList.toggle('hidden');
                            document.getElementById('stop-game').classList.toggle('hidden');
                            document.getElementById('land').classList.toggle('hidden');
                            document.getElementById('box-game').classList.toggle('hidden');
                            document.getElementById('point-bar').classList.toggle('hidden');
                            document.getElementById('walking-character').className = 'hidden';
                            $('#land').spStop(true);
                        });
                    }

                }
            }
            else {
                this.error_count += 1;
                if (this.point_count > 0) {
                    this.point_count = this.point_count - 1;
                    this.setBar();

                }

                if (this.error_count >= 5) {
                    this.error_count = 0;
                    document.getElementById('world-menu').classList.toggle('hidden');
                    document.getElementById('stop-game').classList.toggle('hidden');
                    document.getElementById('land').classList.toggle('hidden');
                    document.getElementById('box-game').classList.toggle('hidden');
                    document.getElementById('point-bar').classList.toggle('hidden');
                    document.getElementById('walking-character').className = 'hidden';
                    $('#land').spStop(true);
                }
                else {
                    this.showError();
                }
            }
        }
    }

    require(['domReady!'], function (doc) {
        activity.setup();
        game = new Game();
        document.getElementById('stop-game').addEventListener('click', function() {
            location.reload();
        });
        document.getElementById('boy').addEventListener('click', function() {
            document.getElementById('character').classList.toggle('hidden');
            document.getElementById('history').classList.toggle('hidden');
            document.getElementById('history-gender').innerHTML =
            "Lalo debe encontrar a su hermana y tienes la misión de ayudarle.";
            document.getElementById('end-gender').innerHTML = "Lola";
            document.getElementById('world-character').className = 'boy-world';
            game.character = 1;
        });
        document.getElementById('girl').addEventListener('click', function() {
            document.getElementById('character').classList.toggle('hidden');
            document.getElementById('history').classList.toggle('hidden');
            document.getElementById('history-gender').innerHTML =
            "Lola debe encontrar a su hermano y tienes la misión de ayudarle.";
            document.getElementById('end-gender').innerHTML = "Lalo";
            document.getElementById('world-character').className = 'girl-world';
            game.character = 2;
        });

        document.getElementById('history-next').addEventListener('click', function() {
            document.getElementById('world-menu').classList.toggle('hidden');
            document.getElementById('history').classList.toggle('hidden');
        });

        document.getElementById('1').addEventListener('click', function() {
            game.init('1', '2');
        });
        document.getElementById('2').addEventListener('click', function() {
            game.init('2', '2');
        });
        document.getElementById('3').addEventListener('click', function() {
            game.init('3', '2');
        });
        document.getElementById('4').addEventListener('click', function() {
            game.init('4', '2');
        });
        document.getElementById('5').addEventListener('click', function() {
            game.init('5', '2');
        });
        document.getElementById('6').addEventListener('click', function() {
            game.init('6', '2');
        });
        document.getElementById('7').addEventListener('click', function() {
            game.init('7', '2');
        });
        document.getElementById('8').addEventListener('click', function() {
            game.init('8', '2');
        });
        document.getElementById('9').addEventListener('click', function() {
            game.init('9', '1');
        });
        document.getElementById('10').addEventListener('click', function() {
            game.init('10', '1');
        });
        document.getElementById('11').addEventListener('click', function() {
            game.init('11', '1');
        });
        document.getElementById('12').addEventListener('click', function() {
            game.init('12', '1');
        });
    });
});
<commit_msg>numero para ganar<commit_after>define(function (require) {
    var jquery = require("jquery");
    var activity = require("sugar-web/activity/activity");
    var palette = require("sugar-web/graphics/palette");
    var icon = require("sugar-web/graphics/icon");
    var dictstore = require("sugar-web/dictstore")
    var l10n = require("webL10n");
    var spritely = require("spritely");
    var words = null;

    function count(array) {
        var counter = 0;
        for (var i = 0; i < array.length; i++) {
            if (array[i]) {
                counter++;
            }
        }
        return counter;
    }

    function getWords(level) {
        if (words == null) {
            words = require("words");
        }
        return words[level][Math.floor(Math.random() * (words[level].length))];
    }

    function Game() {
        this.level = null;
        this.mode = null;
        this.currentWord = [];
        this.answer = '';
        this.boxGame = null;
        this.sentence = null;
        this.answerBox = null;
        this.error_count = 0;
        this.point_count = 0;
        this.win_level =  0;
        this.character = 0;
        this.data_level = Array(12);

        function onStoreReady() {
            if (localStorage['level']) {
                this.data_level = JSON.parse(localStorage['level']);
                console.log(this.data_level);
                for (var i = 1; i <= this.data_level.length; i++) {
                    if (this.data_level[i - 1]) {
                        document.getElementById(String(i)).className = 'world world-'+ i +' done';
                    }
                }
            }
        }

        dictstore.init(onStoreReady);

        this.init = function(level, mode) {
            this.level = level;
            this.mode = mode;
            this.point_count = 0;

            if (this.mode == '1') {
                this.win_level = 40;
            }
            else if (this.mode == '2') {
                this.win_level = 70;
            }

            document.getElementById('point-bar').innerHTML = '';
            document.getElementById('world-menu').classList.toggle('hidden');
            document.getElementById('box-game').classList.toggle('hidden');
            document.getElementById('point-bar').classList.toggle('hidden');
            document.getElementById('land').classList.toggle('hidden');
            document.getElementById('stop-game').classList.toggle('hidden');
            /*
            I didn't expect to use JQuery at the beginning, but it's required
            by the animation library.
            I hope you love spaguetti code.
            */
            $('#land').css('background', 'url(../images/land-' + level + '.png) left top repeat-x');
            $('#land').pan({fps: 30, speed: 0.7, dir: 'left'});
            $('#land').spStart();
            console.log('Iniciar animacion');
            if (this.character == 1) {
                document.getElementById('walking-character').className = 'boy-' +  level;
            }
            else {
                document.getElementById('walking-character').className = 'girl-' + level;
            }

            this.interface();
        }

        this.start = function() {
            this.currentWord = getWords(this.level);
            this.answer = this.currentWord['answer'];
            sentence.innerHTML = this.currentWord['sentence'];

            if (sentence.className == 'main-sentence') {
                sentence.className = '';
            }

            if (this.mode == '1') {
                document.getElementById('op1').innerHTML = this.currentWord['op1'];
                document.getElementById('op2').innerHTML = this.currentWord['op2'];
            }
        }

        this.interface = function() {
            document.getElementById('top-box').innerHTML = '

';
            boxGame = document.getElementById('box-game');
            sentence = document.getElementById('sentence');
            answerBox = document.getElementById('answer-box');
            if (this.mode == '1') {
                answerBox.innerHTML =
                    '
Selecciona la palabra correcta
' +
                    '
' +
                    '  <button id="op1"></button>' +
                    '
' +
                    '
' +
                    '  <button id="op2"></button>' +
                    '
';
                var op1 = document.getElementById('op1');
                var op2 = document.getElementById('op2');
                op1.addEventListener('click', function() {
                    game.checkAnswer(this.innerHTML);
                });
                op2.addEventListener('click', function() {
                    game.checkAnswer(this.innerHTML);
                });
            }

            else if (this.mode == '2') {
                answerBox.innerHTML =
                    '
Escribe la letra que falta
' +
                    '<input type="text" id="answer">';
                var answerInput = document.getElementById('answer');
                answerInput.addEventListener('input', function() {
                    var self = this;
                    setTimeout(function() {
                        game.checkAnswer(self.value);
                        self.value = '';
                    }, 900);
                });
            }

            this.start();
        }

        this.showError = function() {
            var topBox = document.getElementById('top-box');
            var answerBox = document.getElementById('answer-box');

            topBox.innerHTML =
            '
¡Has fallado...!
'+
            'Vuelve a intentarlo»';

            document.getElementById('restart').addEventListener('click', this.interface.bind(this), false);

            if (this.mode == '1') {
                answerBox.innerHTML =
                    '
Aprende la diferencia
' +
                    '
' +
                    '
' + this.currentWord['op1'] + '
' +
                    '
' + this.currentWord['op1_concept'] + '
' +
                    '
' +
                    '
' +
                    '
' + this.currentWord['op2'] + '
' +
                    '
' + this.currentWord['op2_concept'] + '
' +
                    '
';
            }
            else if (this.mode == '2') {
                answerBox.innerHTML =
                '
Aprende la regla:
' +
                '
' + this.currentWord['concept'] + '
';

            }

        }

        this.setBar = function() {
            var bar = document.getElementById('point-bar');
            bar.innerHTML = '';
            for (var i = this.point_count; i > 0; i--) {
                bar.innerHTML += '';
            }
        }
        var self = this;

        this.checkAnswer = function(answer) {
            if (answer.toLowerCase() == this.answer.toLowerCase()) {
                this.error_count = 0;
                this.point_count += 1;
                // Siguiente pregunta
                $('#walking-character').sprite({
                    fps: 3,
                    no_of_frames: 3,
                    play_frames: 3
                });
                if (this.point_count < this.win_level) {
                    this.setBar();
                    this.start();
                }

                // Fin de nivel
                else {
                    // var approvedLevels = JSON.parse(localStorage['level']);
                    // approvedLevels[parseInt(this.level) - 1] = true;
                    // localStorage['level'] = JSON.stringify(approvedLevels);
                    // dictstore.save();

                    // Fin de juego
                    if (count(this.data_level) >= 12) {
                        document.getElementById('history-end').classList.toggle('hidden');
                        document.getElementById('box-game').classList.toggle('hidden');
                        document.getElementById('point-bar').classList.toggle('hidden');
                        document.getElementById('walking-character').className = 'hidden';

                        document.getElementById('end-next').addEventListener('click', function() {
                            document.getElementById('world-menu').classList.toggle('hidden');
                            document.getElementById('history-end').classList.toggle('hidden');
                            document.getElementById('land').classList.toggle('hidden');
                            document.getElementById('stop-game').classList.toggle('hidden');
                            $('#land').spStop(true);

                        });
                    }
                    else {
                        var topBox = document.getElementById('top-box');
                        var answerBox = document.getElementById('answer-box');
                        topBox.innerHTML =
                        '
¡Felicidades, has completado este mundo!
';
                        answerBox.innerHTML =
                        '
Has ganado una medalla
' +
                        '

' +
                        '
<button id="next">Continuar</button>
';

                        document.getElementById('next').addEventListener('click', function() {
                            document.getElementById('world-menu').classList.toggle('hidden');
                            document.getElementById('stop-game').classList.toggle('hidden');
                            document.getElementById('land').classList.toggle('hidden');
                            document.getElementById('box-game').classList.toggle('hidden');
                            document.getElementById('point-bar').classList.toggle('hidden');
                            document.getElementById('walking-character').className = 'hidden';
                            $('#land').spStop(true);
                        });
                    }

                }
            }
            else {
                this.error_count += 1;
                if (this.point_count > 0) {
                    this.point_count = this.point_count - 1;
                    this.setBar();

                }

                if (this.error_count >= 5) {
                    this.error_count = 0;
                    document.getElementById('world-menu').classList.toggle('hidden');
                    document.getElementById('stop-game').classList.toggle('hidden');
                    document.getElementById('land').classList.toggle('hidden');
                    document.getElementById('box-game').classList.toggle('hidden');
                    document.getElementById('point-bar').classList.toggle('hidden');
                    document.getElementById('walking-character').className = 'hidden';
                    $('#land').spStop(true);
                }
                else {
                    this.showError();
                }
            }
        }
    }

    require(['domReady!'], function (doc) {
        activity.setup();
        game = new Game();
        document.getElementById('stop-game').addEventListener('click', function() {
            location.reload();
        });
        document.getElementById('boy').addEventListener('click', function() {
            document.getElementById('character').classList.toggle('hidden');
            document.getElementById('history').classList.toggle('hidden');
            document.getElementById('history-gender').innerHTML =
            "Lalo debe encontrar a su hermana y tienes la misión de ayudarle.";
            document.getElementById('end-gender').innerHTML = "Lola";
            document.getElementById('world-character').className = 'boy-world';
            game.character = 1;
        });
        document.getElementById('girl').addEventListener('click', function() {
            document.getElementById('character').classList.toggle('hidden');
            document.getElementById('history').classList.toggle('hidden');
            document.getElementById('history-gender').innerHTML =
            "Lola debe encontrar a su hermano y tienes la misión de ayudarle.";
            document.getElementById('end-gender').innerHTML = "Lalo";
            document.getElementById('world-character').className = 'girl-world';
            game.character = 2;
        });

        document.getElementById('history-next').addEventListener('click', function() {
            document.getElementById('world-menu').classList.toggle('hidden');
            document.getElementById('history').classList.toggle('hidden');
        });

        document.getElementById('1').addEventListener('click', function() {
            game.init('1', '2');
        });
        document.getElementById('2').addEventListener('click', function() {
            game.init('2', '2');
        });
        document.getElementById('3').addEventListener('click', function() {
            game.init('3', '2');
        });
        document.getElementById('4').addEventListener('click', function() {
            game.init('4', '2');
        });
        document.getElementById('5').addEventListener('click', function() {
            game.init('5', '2');
        });
        document.getElementById('6').addEventListener('click', function() {
            game.init('6', '2');
        });
        document.getElementById('7').addEventListener('click', function() {
            game.init('7', '2');
        });
        document.getElementById('8').addEventListener('click', function() {
            game.init('8', '2');
        });
        document.getElementById('9').addEventListener('click', function() {
            game.init('9', '1');
        });
        document.getElementById('10').addEventListener('click', function() {
            game.init('10', '1');
        });
        document.getElementById('11').addEventListener('click', function() {
            game.init('11', '1');
        });
        document.getElementById('12').addEventListener('click', function() {
            game.init('12', '1');
        });
    });
});
<|endoftext|>


<commit_before>define(function (require) {
    var activity = require("sugar-web/activity/activity");

    // Manipulate the DOM only when it is ready.
    require(['domReady!'], function (doc) {

        // Initialize the activity
        activity.setup();

		// Initialize cordova
		var useragent = navigator.userAgent.toLowerCase();
		var sensorButton = document.getElementById("sensor-button");
		var readyToWatch = false;
		var sensorMode = true;
		if (useragent.indexOf('android') != -1 || useragent.indexOf('iphone') != -1 || useragent.indexOf('ipad') != -1 || useragent.indexOf('ipod') != -1 || useragent.indexOf('mozilla/5.0 (mobile') != -1) {
			document.addEventListener('deviceready', function() {
				readyToWatch = true;
			}, false);
			sensorButton.disabled = false;
			sensorButton.classList.add('active');
		} else {
			sensorButton.disabled = true;
		}

		// Initialize the world
		var body = document.getElementById("body");
		var innerWidth = body.offsetWidth;
		var innerHeight = body.offsetHeight;
		var toolbarHeight = 55;
		var outerWidth = 0; // Use to determine if items could disappear, could be 300;
		var init = false;
		var gravityMode = 0;
		var currentType = 0;
		Physics({ timestep: 6 }, function (world) {

			// bounds of the window
			var viewWidth = innerWidth
				,viewportBounds = Physics.aabb(0-outerWidth, toolbarHeight, innerWidth+outerWidth, innerHeight)
				,edgeBounce
				,renderer
				;

			// let's use the pixi renderer
			require(['pixi'], function( PIXI ){
				window.PIXI = PIXI;
				// create a renderer
				renderer = Physics.renderer('pixi', {
					el: 'viewport'
				});

				// add the renderer
				world.add(renderer);
				// render on each step
				world.on('step', function () {
					world.render();
					if (!init) {
						init = true;
						zoom();
					}
					if (readyToWatch) {
						watchId = navigator.accelerometer.watchAcceleration(accelerationChanged, null, { frequency: 500 });
						readyToWatch = false;
					}
				});
				// add the interaction
				world.add(Physics.behavior('interactive', { el: renderer.container }));
			});

			// constrain objects to these bounds
			edgeBounce = Physics.behavior('edge-collision-detection', {
				aabb: viewportBounds
				,restitution: 0.2
				,cof: 0.8
			});

			// resize events
			window.addEventListener('resize', function () {
				// as of 0.7.0 the renderer will auto resize... so we just take the values from the renderer
				viewportBounds = Physics.aabb(0-outerWidth, toolbarHeight, renderer.width+outerWidth, renderer.height);
				// update the boundaries
				edgeBounce.setAABB(viewportBounds);
				innerWidth = body.offsetWidth;
				innerHeight = body.offsetHeight;
				zoom();

			}, true);

			// handle toolbar buttons
			document.getElementById("box-button").addEventListener('click', function (e) {
				currentType = 1;
				switchToType(currentType);
			}, true);
			document.getElementById("circle-button").addEventListener('click', function (e) {
				currentType = 0;
				switchToType(currentType);
			}, true);

			document.getElementById("triangle-button").addEventListener('click', function (e) {
				currentType = 2;
				switchToType(currentType);
			}, true);

			document.getElementById("gravity-button").addEventListener('click', function () {
				setGravity((gravityMode + 1)%8);
			}, true);

			sensorButton.addEventListener('click', function () {
				sensorMode = !sensorMode;
				if (sensorMode)
					sensorButton.classList.add('active');
				else
					sensorButton.classList.remove('active');
			}, true);

			function accelerationChanged(acceleration) {
				if (!sensorMode) return;
				if (acceleration.x < -4.5) {
					if (acceleration.y > 4.75)
						setGravity(3);
					else if (acceleration.y < -4.75)
						setGravity(5);
					else
						setGravity(4);
				} else if (acceleration.x <= 4.5 && acceleration.x >= -4.5) {
					if (acceleration.y > 4.75)
						setGravity(2);
					else if (acceleration.y < -4.75)
						setGravity(6);
				} else if (acceleration.x > 4.5) {
					if (acceleration.y > 4.75)
						setGravity(1);
					else if (acceleration.y < -4.75)
						setGravity(7);
					else
						setGravity(0);
				}
			}

			document.getElementById("clearall-button").addEventListener('click', function () {
				world.remove(world.getBodies());
			}, true);

			// Save/Load world
			loadWorld();
			var stopButton = document.getElementById("stop-button");
			stopButton.addEventListener('click', function (event) {
				console.log("writing...");
				saveWorld(function (error) {
					if (error === null) {
						console.log("write done.");
					}
					else {
						console.log("write failed.");
					}
				});
			});

			var colors = [
				['0x268bd2', '0x0d394f']
				,['0xc93b3b', '0x561414']
				,['0xe25e36', '0x79231b']
				,['0x6c71c4', '0x393f6a']
				,['0x58c73c', '0x30641c']
				,['0xcac34c', '0x736a2c']
			];

			function zoom() {
				if (window.devicePixelRatio == 1) {
					return;
				}
				var canvas = document.getElementById("viewport").children[0];
				var zoom = 1.0 / window.devicePixelRatio;
				canvas.style.zoom = zoom;
				var useragent = navigator.userAgent.toLowerCase();
				if (useragent.indexOf('chrome') == -1) {
					canvas.style.MozTransform = "scale("+zoom+")";
					canvas.style.MozTransformOrigin = "0 0";
				}
			}

			function random( min, max ){
				return (Math.random() * (max-min) + min)|0;
			}

			function switchToType(newtype) {
				document.getElementById("box-button").classList.remove('active');
				document.getElementById("circle-button").classList.remove('active');
				document.getElementById("triangle-button").classList.remove('active');
				if (newtype == 0) document.getElementById("circle-button").classList.add('active');
				else if (newtype == 1) document.getElementById("box-button").classList.add('active');
				else if (newtype == 2) document.getElementById("triangle-button").classList.add('active');
			}

			function dropInBody(type, pos){

				var body;
				var c;

				switch (type){

						// add a circle
					case 0:
						c = colors[random(0, colors.length-1)];
						body = Physics.body('circle', {
							x: pos.x
							,y: pos.y
							,vx: random(-5, 5)/100
							,radius: 40+random(0, 70)
							,restitution: 0.9
							,styles: {
								fillStyle: c[0]
								,strokeStyle: c[1]
								,lineWidth: 1
								,angleIndicator: c[1]
							}
						});
						break;

						// add a square
					case 1:
						c = colors[random(0, colors.length-1)];
						var l = random(0, 70);
						body = Physics.body('rectangle', {
							width: 50+l
							,height: 50+l
							,x: pos.x
							,y: pos.y
							,vx: random(-5, 5)/100
							,restitution: 0.9
							,styles: {
								fillStyle: c[0]
								,strokeStyle: c[1]
								,lineWidth: 1
								,angleIndicator: c[1]
							}
						});
						break;

						// add a polygon
					case 2:
					case 3:
						var s = (type == 2 ? 3 : random( 5, 10 ));
						c = colors[ random(0, colors.length-1) ];
						body = Physics.body('convex-polygon', {
							vertices: Physics.geometry.regularPolygonVertices( s, random(30, 100) )
							,x: pos.x
							,y: pos.y
							,vx: random(-5, 5)/100
							,angle: random( 0, 2 * Math.PI )
							,restitution: 0.9
							,styles: {
								fillStyle: c[0]
								,strokeStyle: c[1]
								,lineWidth: 1
								,angleIndicator: c[1]
							}
						});
						break;
				}

				world.add( body );
			}

			// Save world to datastore
			function saveWorld(callback) {
				// Build bodies list
				var bodies = world.getBodies();
				var objects = [];
				for(var i = 0 ; i < bodies.length ; i++) {
					var body = bodies[i];
					var object = {};
					object.type = body.geometry.name;
					if (object.type == "circle") {
						object.radius = body.radius;
					} else if (body.geometry.name == "rectangle") {
						object.width = body.view.width;
						object.height = body.view.height;
					} else if (body.geometry.name == "convex-polygon") {
						object.vertices = body.vertices;
					}
					object.restitution = body.restitution;
					object.styles = body.styles;
					object.x = body.view.x;
					object.y = body.view.y;
					objects.push(object);
				}

				// Save to datastore
				var datastoreObject = activity.getDatastoreObject();
				var jsonData = JSON.stringify({world: objects});
				datastoreObject.setDataAsText(jsonData);
				datastoreObject.save(callback);
			}

			// Load world from datastore
			function loadWorld(objects) {
				var datastoreObject = activity.getDatastoreObject();
				datastoreObject.loadAsText(function (error, metadata, data) {
					var data = JSON.parse(data);
					if (data == null)
						return;

					// Create bodies
					var objects = data.world;
					for(var i = 0 ; i < objects.length ; i++) {
						var savedObject = objects[i];
						var newOptions = {
							x: savedObject.x,
							y: savedObject.y,
							restitution: savedObject.restitution,
							styles: savedObject.styles
						};
						if (savedObject.type == "circle") {
							newOptions.radius = savedObject.radius;
						} else if (savedObject.type == "rectangle") {
							newOptions.width = savedObject.width;
							newOptions.height = savedObject.height;
						} else if (savedObject.type = "convex-polygon") {
							newOptions.vertices = savedObject.vertices;
						}
						var newBody = Physics.body(savedObject.type, newOptions);
						world.add(newBody);
					}
				});
			}

			// Change gravity value
			function setGravity(value) {
				if (gravityMode == value) return;
				document.getElementById("gravity-button").style.backgroundImage = "url(icons/gravity"+value+".svg)";
				var acc = {};
				switch(value) {
				case 0:
					acc = { x: 0, y: 0.0004 };
					break;
				case 1:
					acc = { x: 0.0004, y: 0.0004 };
					break;
				case 2:
					acc = { x: 0.0004, y: 0 };
					break;
				case 3:
					acc = { x: 0.0004, y: -0.0004 };
					break;
				case 4:
					acc = { x: 0, y: -0.0004 };
					break;
				case 5:
					acc = { x: -0.0004, y: -0.0004 };
					break;
				case 6:
					acc = { x: -0.0004, y: 0 };
					break;
				case 7:
					acc = { x: -0.0004, y: 0.0004 };
					break;
				}
				gravity.setAcceleration(acc);
				world.wakeUpAll();
				gravityMode = value;
			}

			// add some fun interaction
			var attractor = Physics.behavior('attractor', {
				order: 0,
				strength: 0.002
			});
			world.on({
				'interact:poke': function( pos ){
					if (pos.y > toolbarHeight)
						dropInBody(currentType, pos);
				}
				,'interact:move': function( pos ){
					attractor.position( pos );
				}
				,'interact:release': function(){
					world.wakeUpAll();
					world.remove( attractor );
				}
			});

			// add things to the world
			var gravity = Physics.behavior('constant-acceleration');
			world.add([
				gravity
				,Physics.behavior('body-impulse-response')
				,Physics.behavior('body-collision-detection')
				,Physics.behavior('sweep-prune')
				,edgeBounce
			]);

			// subscribe to ticker to advance the simulation
			Physics.util.ticker.on(function( time ) {
				// next step
				world.step( time );

				// remove bodies out of
				var bodies = world.getBodies();
				var limit = outerWidth / 2;
				if (limit > 0) {
					for(var i = 0 ; i < bodies.length ; i++) {
						var body = bodies[i];
						if (body.state.pos.x < 0-limit || body.state.pos.x > innerWidth+limit)
							world.remove(body);
					}
				}
			});
		});
    });

});
<commit_msg>Allow to resize created object<commit_after>define(function (require) {
    var activity = require("sugar-web/activity/activity");

    // Manipulate the DOM only when it is ready.
    require(['domReady!'], function (doc) {

        // Initialize the activity
        activity.setup();

		// Initialize cordova
		var useragent = navigator.userAgent.toLowerCase();
		var sensorButton = document.getElementById("sensor-button");
		var readyToWatch = false;
		var sensorMode = true;
		if (useragent.indexOf('android') != -1 || useragent.indexOf('iphone') != -1 || useragent.indexOf('ipad') != -1 || useragent.indexOf('ipod') != -1 || useragent.indexOf('mozilla/5.0 (mobile') != -1) {
			document.addEventListener('deviceready', function() {
				readyToWatch = true;
			}, false);
			sensorButton.disabled = false;
			sensorButton.classList.add('active');
		} else {
			sensorButton.disabled = true;
		}

		// Initialize the world
		var body = document.getElementById("body");
		var innerWidth = body.offsetWidth;
		var innerHeight = body.offsetHeight;
		var toolbarHeight = 55;
		var outerWidth = 0; // Use to determine if items could disappear, could be 300;
		var init = false;
		var gravityMode = 0;
		var currentType = 0;
		Physics({ timestep: 6 }, function (world) {

			// bounds of the window
			var viewWidth = innerWidth
				,viewportBounds = Physics.aabb(0-outerWidth, toolbarHeight, innerWidth+outerWidth, innerHeight)
				,edgeBounce
				,renderer
				;

			// let's use the pixi renderer
			require(['pixi'], function( PIXI ){
				window.PIXI = PIXI;
				// create a renderer
				renderer = Physics.renderer('pixi', {
					el: 'viewport'
				});

				// add the renderer
				world.add(renderer);
				// render on each step
				world.on('step', function () {
					world.render();
					if (!init) {
						init = true;
						zoom();
					}
					if (readyToWatch) {
						watchId = navigator.accelerometer.watchAcceleration(accelerationChanged, null, { frequency: 500 });
						readyToWatch = false;
					}
				});
				// add the interaction
				world.add(Physics.behavior('interactive', { el: renderer.container }));
			});

			// constrain objects to these bounds
			edgeBounce = Physics.behavior('edge-collision-detection', {
				aabb: viewportBounds
				,restitution: 0.2
				,cof: 0.8
			});

			// resize events
			window.addEventListener('resize', function () {
				// as of 0.7.0 the renderer will auto resize... so we just take the values from the renderer
				viewportBounds = Physics.aabb(0-outerWidth, toolbarHeight, renderer.width+outerWidth, renderer.height);
				// update the boundaries
				edgeBounce.setAABB(viewportBounds);
				innerWidth = body.offsetWidth;
				innerHeight = body.offsetHeight;
				zoom();

			}, true);

			// handle toolbar buttons
			document.getElementById("box-button").addEventListener('click', function (e) {
				currentType = 1;
				switchToType(currentType);
			}, true);
			document.getElementById("circle-button").addEventListener('click', function (e) {
				currentType = 0;
				switchToType(currentType);
			}, true);

			document.getElementById("triangle-button").addEventListener('click', function (e) {
				currentType = 2;
				switchToType(currentType);
			}, true);

			document.getElementById("gravity-button").addEventListener('click', function () {
				setGravity((gravityMode + 1)%8);
			}, true);

			sensorButton.addEventListener('click', function () {
				sensorMode = !sensorMode;
				if (sensorMode)
					sensorButton.classList.add('active');
				else
					sensorButton.classList.remove('active');
			}, true);

			function accelerationChanged(acceleration) {
				if (!sensorMode) return;
				if (acceleration.x < -4.5) {
					if (acceleration.y > 4.75)
						setGravity(3);
					else if (acceleration.y < -4.75)
						setGravity(5);
					else
						setGravity(4);
				} else if (acceleration.x <= 4.5 && acceleration.x >= -4.5) {
					if (acceleration.y > 4.75)
						setGravity(2);
					else if (acceleration.y < -4.75)
						setGravity(6);
				} else if (acceleration.x > 4.5) {
					if (acceleration.y > 4.75)
						setGravity(1);
					else if (acceleration.y < -4.75)
						setGravity(7);
					else
						setGravity(0);
				}
			}

			document.getElementById("clearall-button").addEventListener('click', function () {
				world.remove(world.getBodies());
			}, true);

			// Save/Load world
			loadWorld();
			var stopButton = document.getElementById("stop-button");
			stopButton.addEventListener('click', function (event) {
				console.log("writing...");
				saveWorld(function (error) {
					if (error === null) {
						console.log("write done.");
					}
					else {
						console.log("write failed.");
					}
				});
			});

			var colors = [
				['0x268bd2', '0x0d394f']
				,['0xc93b3b', '0x561414']
				,['0xe25e36', '0x79231b']
				,['0x6c71c4', '0x393f6a']
				,['0x58c73c', '0x30641c']
				,['0xcac34c', '0x736a2c']
			];

			function zoom() {
				if (window.devicePixelRatio == 1) {
					return;
				}
				var canvas = document.getElementById("viewport").children[0];
				var zoom = 1.0 / window.devicePixelRatio;
				canvas.style.zoom = zoom;
				var useragent = navigator.userAgent.toLowerCase();
				if (useragent.indexOf('chrome') == -1) {
					canvas.style.MozTransform = "scale("+zoom+")";
					canvas.style.MozTransformOrigin = "0 0";
				}
			}

			function random( min, max ){
				return (Math.random() * (max-min) + min)|0;
			}

			function switchToType(newtype) {
				document.getElementById("box-button").classList.remove('active');
				document.getElementById("circle-button").classList.remove('active');
				document.getElementById("triangle-button").classList.remove('active');
				if (newtype == 0) document.getElementById("circle-button").classList.add('active');
				else if (newtype == 1) document.getElementById("box-button").classList.add('active');
				else if (newtype == 2) document.getElementById("triangle-button").classList.add('active');
			}

			function dropInBody(type, pos){

				var body;
				var c;

				switch (type){

						// add a circle
					case 0:
						c = colors[random(0, colors.length-1)];
						body = Physics.body('circle', {
							x: pos.x
							,y: pos.y
							,vx: random(-5, 5)/100
							,radius: 40
							,restitution: 0.9
							,styles: {
								fillStyle: c[0]
								,strokeStyle: c[1]
								,lineWidth: 1
								,angleIndicator: c[1]
							}
						});
						break;

						// add a square
					case 1:
						c = colors[random(0, colors.length-1)];
						var l = random(0, 70);
						body = Physics.body('rectangle', {
							width: 50+l
							,height: 50+l
							,x: pos.x
							,y: pos.y
							,vx: random(-5, 5)/100
							,restitution: 0.9
							,styles: {
								fillStyle: c[0]
								,strokeStyle: c[1]
								,lineWidth: 1
								,angleIndicator: c[1]
							}
						});
						break;

						// add a polygon
					case 2:
					case 3:
						var s = (type == 2 ? 3 : random( 5, 10 ));
						c = colors[ random(0, colors.length-1) ];
						body = Physics.body('convex-polygon', {
							vertices: Physics.geometry.regularPolygonVertices( s, 30 )
							,x: pos.x
							,y: pos.y
							,vx: random(-5, 5)/100
							,angle: random( 0, 2 * Math.PI )
							,restitution: 0.9
							,styles: {
								fillStyle: c[0]
								,strokeStyle: c[1]
								,lineWidth: 1
								,angleIndicator: c[1]
							}
						});
						break;
				}

				body.treatment = "static";

				world.add( body );
				return body;
			}

			// Save world to datastore
			function saveWorld(callback) {
				// Build bodies list
				var bodies = world.getBodies();
				var objects = [];
				for(var i = 0 ; i < bodies.length ; i++) {
					var object = serializeObject(bodies[i]);
					objects.push(object);
				}

				// Save to datastore
				var datastoreObject = activity.getDatastoreObject();
				var jsonData = JSON.stringify({world: objects});
				datastoreObject.setDataAsText(jsonData);
				datastoreObject.save(callback);
			}

			function serializeObject(body) {
				var object = {};
				object.type = body.geometry.name;
				if (object.type == "circle") {
					object.radius = body.radius;
				} else if (body.geometry.name == "rectangle") {
					object.width = body.view.width;
					object.height = body.view.height;
				} else if (body.geometry.name == "convex-polygon") {
					object.vertices = body.vertices;
				}
				object.restitution = body.restitution;
				object.styles = body.styles;
				object.x = body.view.x;
				object.y = body.view.y;
				return object;
			}

			// Load world from datastore
			function loadWorld(objects) {
				var datastoreObject = activity.getDatastoreObject();
				datastoreObject.loadAsText(function (error, metadata, data) {
					var data = JSON.parse(data);
					if (data == null)
						return;

					// Create bodies
					var objects = data.world;
					for(var i = 0 ; i < objects.length ; i++) {
						var newBody = deserializeObject(objects[i]);
						world.add(newBody);
					}
				});
			}

			function deserializeObject(savedObject) {
				var newOptions = {
					x: savedObject.x,
					y: savedObject.y,
					restitution: savedObject.restitution,
					styles: savedObject.styles
				};
				if (savedObject.type == "circle") {
					newOptions.radius = savedObject.radius;
				} else if (savedObject.type == "rectangle") {
					newOptions.width = savedObject.width;
					newOptions.height = savedObject.height;
				} else if (savedObject.type = "convex-polygon") {
					newOptions.vertices = savedObject.vertices;
				}
				return Physics.body(savedObject.type, newOptions);
			}

			// Change gravity value
			function setGravity(value) {
				if (gravityMode == value) return;
				document.getElementById("gravity-button").style.backgroundImage = "url(icons/gravity"+value+".svg)";
				var acc = {};
				switch(value) {
				case 0:
					acc = { x: 0, y: 0.0004 };
					break;
				case 1:
					acc = { x: 0.0004, y: 0.0004 };
					break;
				case 2:
					acc = { x: 0.0004, y: 0 };
					break;
				case 3:
					acc = { x: 0.0004, y: -0.0004 };
					break;
				case 4:
					acc = { x: 0, y: -0.0004 };
					break;
				case 5:
					acc = { x: -0.0004, y: -0.0004 };
					break;
				case 6:
					acc = { x: -0.0004, y: 0 };
					break;
				case 7:
					acc = { x: -0.0004, y: 0.0004 };
					break;
				}
				gravity.setAcceleration(acc);
				world.wakeUpAll();
				gravityMode = value;
			}

			// add some fun interaction
			var createdBody = null;
			var createdStart = null;
			var attractor = Physics.behavior('attractor', {
				order: 0,
				strength: 0.002
			});
			world.on({
				'interact:poke': function( pos ){
					// create body at a static place
					if (pos.y > toolbarHeight) {
						createdBody = dropInBody(currentType, pos);
						createdStart = pos;
					}
				}
				,'interact:move': function( pos ){
					// update size of created body
					if (createdBody != null) {
						// compute new size
						var distx = createdStart.x - pos.x;
						var disty = createdStart.y - pos.y;
						var distance = Math.min(Math.sqrt(Math.abs(distx*distx-disty*disty)),createdStart.y-toolbarHeight);
						if (createdBody.view != null) {
							// Recreate the object with new size
							var object = serializeObject(createdBody);
							if (object.type == "circle") {
								object.radius = Math.max(40, distance);
							} else if (object.type == "rectangle") {
								object.width = object.height = Math.max(50, distance);
							} else if (object.type = "convex-polygon") {
								object.vertices = Physics.geometry.regularPolygonVertices( object.vertices.length, Math.max(30, distance));
							}
							world.removeBody(createdBody);
							createdBody = deserializeObject(object);
							createdBody.treatment = "static";
							world.add(createdBody);
						}
					}

					attractor.position( pos );
				}
				,'interact:release': function( pos ){
					if (createdBody != null) {
						createdBody.treatment = "dynamic";
						createdBody = null;
					}
					world.wakeUpAll();
					world.remove( attractor );
				}
			});

			// add things to the world
			var gravity = Physics.behavior('constant-acceleration');
			world.add([
				gravity
				,Physics.behavior('body-impulse-response')
				,Physics.behavior('body-collision-detection')
				,Physics.behavior('sweep-prune')
				,edgeBounce
			]);

			// subscribe to ticker to advance the simulation
			Physics.util.ticker.on(function( time ) {
				// next step
				world.step( time );

				// remove bodies out of
				var bodies = world.getBodies();
				var limit = outerWidth / 2;
				if (limit > 0) {
					for(var i = 0 ; i < bodies.length ; i++) {
						var body = bodies[i];
						if (body.state.pos.x < 0-limit || body.state.pos.x > innerWidth+limit)
							world.remove(body);
					}
				}
			});
		});
    });

});
<|endoftext|>


<commit_before>/**
 * Created with IntelliJ IDEA.
 * User: tparmer
 * Date: 11/27/13
 * Time: 12:21 PM
 * To change this template use File | Settings | File Templates.
 */

var serviceURL = "http://216.74.49.91:8080/tssvc/resourcesS/stories/";
//var serviceURL = "http://localhost:8080/tssvc/resourcesS/stories";
//var serviceURL = "http://localhost:8080/tssvc/getstorylist2.html";

//var employees;
//var stories;

$('#mediaPage').bind('pagebeforecreate', function(event) {
    //alert('bind: pagebeforecreate');
    //getEmployeeList();
});
$('#mediaPage').bind('pagecreate', function(event) {
   // alert('bind: pagecreate');
    //getEmployeeList();
});

$('#mediaPage').bind('pageinit', function(event) {
    //alert('bind: pageinit');
    //getEmployeeList();
});

$('#mediaPage').live('pageinit', function(event) {
    alert('live: pageinit');
    app.initialize();
    alert('live: after app.init');
    //getEmployeeList();
});
$('#mediaPage').bind('pagebeforeload', function(event) {
   // alert('bind: pagebeforeload');
    //getEmployeeList();
});

$('#mediaPage').bind('pageload', function(event) {
   // alert('bind: pageload');
    //getEmployeeList();
});

$('#mediaPage').bind('pagebeforeshow', function(event) {
   // alert('bind: pagebeforeshow');
    //getEmployeeList();
});

$('#mediaPage').bind('pageshow', function(event) {
    //alert('bind: pageshow');
    //getEmployeeList();
});
$('#mediaPage').bind('pagebeforechange', function(event) {
    //alert('bind: pagebeforeshow');
    //getEmployeeList();
});

$('#mediaPage').bind('pagechange', function(event) {
   // alert('bind: pageshow');
    //getEmployeeList();
});

var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // `load`, `deviceready`, `offline`, and `online`.
    bindEvents: function() {
        alert('before binding events');
// document.addEventListener('deviceready', this.onDeviceReady, false);
// document.getElementById('scan').addEventListener('click', this.scan, false);
// document.getElementById('encode').addEventListener('click', this.encode, false);
// document.getElementById('whitelist').addEventListener('click', this.whitelist, false);
        document.getElementById('camera').addEventListener('click', this.camera, false);
        document.getElementById('video').addEventListener('click', this.captureVideo, false);
        document.getElementById('audio').addEventListener('click', this.captureAudio, false);
        document.getElementById('getphoto').addEventListener('click', this.getphoto, false);
        alert('after binding events');
    },

// // deviceready Event Handler
// //
// // The scope of `this` is the event. In order to call the `receivedEvent`
// // function, we must explicity call `app.receivedEvent(...);`
// onDeviceReady: function() {
// app.receivedEvent('deviceready');
// console.log('CORDOVA VERSION: ' + window.device.cordova);
// window.addEventListener('batterystatus', app.onBatteryStatus, false);
// },
// // Update DOM on a Received Event
// receivedEvent: function(id) {
// var parentElement = document.getElementById(id);
// var listeningElement = parentElement.querySelector('.listening');
// var receivedElement = parentElement.querySelector('.received');
//
// listeningElement.setAttribute('style', 'display:none;');
// receivedElement.setAttribute('style', 'display:block;');
//
// console.log('Received Event: ' + id);
// },
// onBatteryStatus: function(info) {
// console.log("Level: " + info.level + " isPlugged: " + info.isPlugged);
// },
// scan: function() {
// console.log('scanning');
// var scanner = cordova.require("cordova/plugin/BarcodeScanner");
//
// scanner.scan( function (result) {
//
// alert("We got a barcode\n" +
// "Result: " + result.text + "\n" +
// "Format: " + result.format + "\n" +
// "Cancelled: " + result.cancelled);
//
// console.log("Scanner result: \n" +
// "text: " + result.text + "\n" +
// "format: " + result.format + "\n" +
// "cancelled: " + result.cancelled + "\n");
// document.getElementById("info").innerHTML = result.text;
// console.log(result);
// /*
// if (args.format == "QR_CODE") {
// window.plugins.childBrowser.showWebPage(args.text, { showLocationBar: false });
// }
// */
//
// }, function (error) {
// console.log("Scanning failed: ", error);
// } );
// },
//
// encode: function() {
// var scanner = cordova.require("cordova/plugin/BarcodeScanner");
//
// scanner.encode(scanner.Encode.TEXT_TYPE, "http://www.nhl.com", function(success) {
// alert("encode success: " + success);
// }, function(fail) {
// alert("encoding failed: " + fail);
// }
// );
//
// },
//
// whitelist: function() {
//
// app.xhr("https://tv.eurosport.com/", function(xhr) {
// console.log("eurosport is invalid " + xhr.status);
// console.log("eurosport: " + xhr.responseText.substring(0, 100));
// });
// /*
// app.xhr("http://ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js", function(xhr) {
// console.log("googleapis: should succeed: " + xhr.status);
// console.log("googleapis: " + xhr.responseText.substring(0, 100));
// });
//
// app.xhr("http://code.jquery.com/jquery-1.10.2.min.js", function(xhr) {
// console.log("jquery: should fail: " + xhr.status);
// console.log("jquery: " + xhr.responseText.substring(0, 100));
// });
//
// app.xhr("http://phonegap.com", function(xhr) {
// console.log("phonegap: should fail: " + xhr.status);
// console.log("phonegap: " + xhr.responseText.substring(0, 100));
// });
//
// app.xhr("http://googleapis.com", function(xhr) {
// console.log("googleapis.com: should succeed: " + xhr.status);
// console.log("googleapis.com: " + xhr.responseText.substring(0, 100));
// });
//
// app.xhr("http://jquery.com", function(xhr) {
// console.log("jquery.com: should succeed: " + xhr.status);
// console.log("jquery.com: " + xhr.responseText.substring(0, 100));
// });
// */
//
// },

    camera: function() {
        function onSuccessURI(imageURI) {

            var options = new FileUploadOptions();
            options.fileKey="file";
            options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
            options.mimeType="image/jpeg";

            var params = {};
            params.value1 = "test";
            params.value2 = "param";

            options.params = params;

            var ft = new FileTransfer();
            ft.upload(imageURI, encodeURI("http://216.74.49.91:8080/tssvc/resourcesS/upload"), fileok, filefail, options);

        }
        function onSuccess(imageData) {
            //console.log('success');

            // AT: the old code
            //
            document.getElementById('testMsg').value = "in onSuccess";

            //Anna
            //var image = document.getElementById('myImage');
            //image.src = "data:image/jpeg;base64," + imageData;

            var smallImage = document.getElementById('smallImage');

            // Unhide image elements
            //
            smallImage.style.display = 'block';

            // Show the captured photo
            // The inline CSS rules are used to resize the image
            //
            smallImage.src = "data:image/jpeg;base64," + imageData;

            // Get image handle
            //
            var largeImage = document.getElementById('largeImage');

            // Unhide image elements
            //
            largeImage.style.display = 'block';
            largeImage.src = "data:image/jpeg;base64," + imageData;

        }

        function onFail(message) {
            console.log('failed');
        }
        var cameraPopoverOptions = new CameraPopoverOptions(220, 600, 320, 480, Camera.PopoverArrowDirection.ARROW_DOWN) ;
        var cameraHandle = navigator.camera.getPicture(onSuccessURI, onFail, { quality: 50, saveToPhotoAlbum: true,
            destinationType: Camera.DestinationType.FILE_URI, popoverOptions:cameraPopoverOptions
        });
        //cameraHandle.setPosition(cameraPopoverOptions);
        function fileok(r) {
            document.getElementById('testMsg').value = "Success. Code = " + r.responseCode + " Resposne = " + r.response + " sent = " + r.byteSent;
            //console.log("Response = " + r.response);
            //console.log("Sent = " + r.bytesSent);
        }

        function filefail(error) {
            document.getElementById('testMsg').value = "Error. Code = " + error.code + " source = " + error.source + " target = " + error.target;
            //alert("An error has occurred: Code = " + error.code);
            //console.log("upload error source " + error.source);
            //console.log("upload error target " + error.target);
        }

    },

    getphoto: function() {

        function onSuccess(imageData) {
            //console.log('success');

            document.getElementById('testMsg').value = "in onSuccess";

            //Anna
            //var image = document.getElementById('myImage');
            //image.src = "data:image/jpeg;base64," + imageData;

            var smallImage = document.getElementById('smallImage');

            // Unhide image elements
            //
            smallImage.style.display = 'block';

            // Show the captured photo
            // The inline CSS rules are used to resize the image
            //
            smallImage.src = "data:image/jpeg;base64," + imageData;

            // Get image handle
            //
            var largeImage = document.getElementById('largeImage');

            // Unhide image elements
            //
            largeImage.style.display = 'block';
            largeImage.src = "data:image/jpeg;base64," + imageData;

        }

        function onFail(message) {
            console.log('failed');
        }

        navigator.camera.getPicture(onSuccess, onFail, { quality: 50, saveToPhotoAlbum: true,
            destinationType: Camera.DestinationType.DATA_URL,sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
            mediaType: Camera.MediaType.ALLMEDIA
        });

    },

    xhr: function(url, cb) {
        var xhr1 = new XMLHttpRequest();
        xhr1.onreadystatechange = function(args) {
            if(xhr1.readyState==4)
                cb(xhr1);
        };
        xhr1.open("GET", url, true);
        xhr1.send();
    },

    captureVideo: function() {
        navigator.device.capture.captureVideo(function(mediaFiles)
            {
                console.log('CALLBACK!');
                console.log(JSON.stringify(mediaFiles));
            }, function(error)
            {
                console.log('Video capture failed');
                alert ('video failed');
            },
            {
                limit: 1,
                duration: 12
            });

    },

 /*   // Record audio
//
     recordAudio: function() {
    var src = "myrecording.wav";
    var mediaRec = new Media(src,
        // success callback
        function() {
            console.log("recordAudio():Audio Success");
            alert('audio success');
        },

        // error callback
        function(err) {
            console.log("recordAudio():Audio Error: "+ err.code);
        }
    );

    // Record audio
    mediaRec.startRecord();

    // Stop recording after 10 seconds
    setTimeout(function() {
        mediaRec.stopRecord();
    }, 10000);
}*/

    captureAudio: function() {

        // Called when capture operation is finished
        //
        function captureSuccess(mediaFiles) {

            alert ('audio success');
            var i, len;
            for (i = 0, len = mediaFiles.length; i < len; i += 1) {
                uploadFile(mediaFiles[i]);
            }

        }

        // Called if something bad happens.
        //
        function captureError(error) {
            var msg = 'An error occurred during capture: ' + error.code;
            navigator.notification.alert(msg, null, 'Uh oh!');
        }

        navigator.device.capture.captureAudio(function(mediaFiles)
            {
                console.log('CALLBACK!');
                console.log(JSON.stringify(mediaFiles));
            }, function(error)
            {
                console.log('Audio capture failed');
            },
            {
                limit: 1,
                duration: 12
            });

        // Upload files to server
//        function uploadFile(mediaFile) {
//            var ft = new FileTransfer(),
//                path = mediaFile.fullPath,
//                name = mediaFile.name;
//
//            ft.upload(path,
//                "http://my.domain.com/upload.php",
//                function(result) {
//                    console.log('Upload success: ' + result.responseCode);
//                    console.log(result.bytesSent + ' bytes sent');
//                },
//                function(error) {
//                    console.log('Error uploading file ' + path + ': ' + error.code);
//                },
//                { fileName: name });
//        }

    }
};

<commit_msg> upload test and alert comments<commit_after>/**
 * Created with IntelliJ IDEA.
 * User: tparmer
 * Date: 11/27/13
 * Time: 12:21 PM
 * To change this template use File | Settings | File Templates.
 */

var serviceURL = "http://216.74.49.91:8080/tssvc/resourcesS/stories/";
//var serviceURL = "http://localhost:8080/tssvc/resourcesS/stories";
//var serviceURL = "http://localhost:8080/tssvc/getstorylist2.html";

//var employees;
//var stories;

$('#mediaPage').bind('pagebeforecreate', function(event) {
    //alert('bind: pagebeforecreate');
    //getEmployeeList();
});
$('#mediaPage').bind('pagecreate', function(event) {
   // alert('bind: pagecreate');
    //getEmployeeList();
});

$('#mediaPage').bind('pageinit', function(event) {
    //alert('bind: pageinit');
    //getEmployeeList();
});

$('#mediaPage').live('pageinit', function(event) {
    //alert('live: pageinit');
    app.initialize();
   // alert('live: after app.init');
    //getEmployeeList();
});
$('#mediaPage').bind('pagebeforeload', function(event) {
   // alert('bind: pagebeforeload');
    //getEmployeeList();
});

$('#mediaPage').bind('pageload', function(event) {
   // alert('bind: pageload');
    //getEmployeeList();
});

$('#mediaPage').bind('pagebeforeshow', function(event) {
   // alert('bind: pagebeforeshow');
    //getEmployeeList();
});

$('#mediaPage').bind('pageshow', function(event) {
    //alert('bind: pageshow');
    //getEmployeeList();
});
$('#mediaPage').bind('pagebeforechange', function(event) {
    //alert('bind: pagebeforeshow');
    //getEmployeeList();
});

$('#mediaPage').bind('pagechange', function(event) {
   // alert('bind: pageshow');
    //getEmployeeList();
});

var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // `load`, `deviceready`, `offline`, and `online`.
    bindEvents: function() {
       // alert('before binding events');
// document.addEventListener('deviceready', this.onDeviceReady, false);
// document.getElementById('scan').addEventListener('click', this.scan, false);
// document.getElementById('encode').addEventListener('click', this.encode, false);
// document.getElementById('whitelist').addEventListener('click', this.whitelist, false);
        document.getElementById('camera').addEventListener('click', this.camera, false);
        document.getElementById('video').addEventListener('click', this.captureVideo, false);
        document.getElementById('audio').addEventListener('click', this.captureAudio, false);
        document.getElementById('getphoto').addEventListener('click', this.getphoto, false);
       // alert('after binding events');
    },

// // deviceready Event Handler
// //
// // The scope of `this` is the event. In order to call the `receivedEvent`
// // function, we must explicity call `app.receivedEvent(...);`
// onDeviceReady: function() {
// app.receivedEvent('deviceready');
// console.log('CORDOVA VERSION: ' + window.device.cordova);
// window.addEventListener('batterystatus', app.onBatteryStatus, false);
// },
// // Update DOM on a Received Event
// receivedEvent: function(id) {
// var parentElement = document.getElementById(id);
// var listeningElement = parentElement.querySelector('.listening');
// var receivedElement = parentElement.querySelector('.received');
//
// listeningElement.setAttribute('style', 'display:none;');
// receivedElement.setAttribute('style', 'display:block;');
//
// console.log('Received Event: ' + id);
// },
// onBatteryStatus: function(info) {
// console.log("Level: " + info.level + " isPlugged: " + info.isPlugged);
// },
// scan: function() {
// console.log('scanning');
// var scanner = cordova.require("cordova/plugin/BarcodeScanner");
//
// scanner.scan( function (result) {
//
// alert("We got a barcode\n" +
// "Result: " + result.text + "\n" +
// "Format: " + result.format + "\n" +
// "Cancelled: " + result.cancelled);
//
// console.log("Scanner result: \n" +
// "text: " + result.text + "\n" +
// "format: " + result.format + "\n" +
// "cancelled: " + result.cancelled + "\n");
// document.getElementById("info").innerHTML = result.text;
// console.log(result);
// /*
// if (args.format == "QR_CODE") {
// window.plugins.childBrowser.showWebPage(args.text, { showLocationBar: false });
// }
// */
//
// }, function (error) {
// console.log("Scanning failed: ", error);
// } );
// },
//
// encode: function() {
// var scanner = cordova.require("cordova/plugin/BarcodeScanner");
//
// scanner.encode(scanner.Encode.TEXT_TYPE, "http://www.nhl.com", function(success) {
// alert("encode success: " + success);
// }, function(fail) {
// alert("encoding failed: " + fail);
// }
// );
//
// },
//
// whitelist: function() {
//
// app.xhr("https://tv.eurosport.com/", function(xhr) {
// console.log("eurosport is invalid " + xhr.status);
// console.log("eurosport: " + xhr.responseText.substring(0, 100));
// });
// /*
// app.xhr("http://ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js", function(xhr) {
// console.log("googleapis: should succeed: " + xhr.status);
// console.log("googleapis: " + xhr.responseText.substring(0, 100));
// });
//
// app.xhr("http://code.jquery.com/jquery-1.10.2.min.js", function(xhr) {
// console.log("jquery: should fail: " + xhr.status);
// console.log("jquery: " + xhr.responseText.substring(0, 100));
// });
//
// app.xhr("http://phonegap.com", function(xhr) {
// console.log("phonegap: should fail: " + xhr.status);
// console.log("phonegap: " + xhr.responseText.substring(0, 100));
// });
//
// app.xhr("http://googleapis.com", function(xhr) {
// console.log("googleapis.com: should succeed: " + xhr.status);
// console.log("googleapis.com: " + xhr.responseText.substring(0, 100));
// });
//
// app.xhr("http://jquery.com", function(xhr) {
// console.log("jquery.com: should succeed: " + xhr.status);
// console.log("jquery.com: " + xhr.responseText.substring(0, 100));
// });
// */
//
// },

    camera: function() {
        function onSuccessURI(imageURI) {

            var options = new FileUploadOptions();
            options.fileKey="file";
            options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
            options.mimeType="image/jpeg";

            var params = {};
            params.value1 = "test";
            params.value2 = "param";

            options.params = params;

            var ft = new FileTransfer();
            ft.upload(imageURI, encodeURI("http://216.74.49.91:8080/tssvc/resourcesS/upload"), fileok, filefail, options);

        }
        function onSuccess(imageData) {
            //console.log('success');

            // AT: the old code
            //
            document.getElementById('testMsg').value = "in onSuccess";

            //Anna
            //var image = document.getElementById('myImage');
            //image.src = "data:image/jpeg;base64," + imageData;

            var smallImage = document.getElementById('smallImage');

            // Unhide image elements
            //
            smallImage.style.display = 'block';

            // Show the captured photo
            // The inline CSS rules are used to resize the image
            //
            smallImage.src = "data:image/jpeg;base64," + imageData;

            // Get image handle
            //
            var largeImage = document.getElementById('largeImage');

            // Unhide image elements
            //
            largeImage.style.display = 'block';
            largeImage.src = "data:image/jpeg;base64," + imageData;

        }

        function onFail(message) {
            console.log('failed');
        }
        var cameraPopoverOptions = new CameraPopoverOptions(220, 600, 320, 480, Camera.PopoverArrowDirection.ARROW_DOWN) ;
        var cameraHandle = navigator.camera.getPicture(onSuccessURI, onFail, { quality: 10, saveToPhotoAlbum: true,
            destinationType: Camera.DestinationType.FILE_URI, popoverOptions:cameraPopoverOptions
        });
        //cameraHandle.setPosition(cameraPopoverOptions);
        function fileok(r) {
            document.getElementById('testMsg').value = "Success. Code = " + r.responseCode + " Resposne = " + r.response + " sent = " + r.byteSent;
            //console.log("Response = " + r.response);
            //console.log("Sent = " + r.bytesSent);
        }

        function filefail(error) {
            document.getElementById('testMsg').value = "Error. Code = " + error.code + " source = " + error.source + " target = " + error.target;
            //alert("An error has occurred: Code = " + error.code);
            //console.log("upload error source " + error.source);
            //console.log("upload error target " + error.target);
        }

    },

    getphoto: function() {

        function onSuccess(imageData) {
            //console.log('success');

            document.getElementById('testMsg').value = "in onSuccess";

            //Anna
            //var image = document.getElementById('myImage');
            //image.src = "data:image/jpeg;base64," + imageData;

            var smallImage = document.getElementById('smallImage');

            // Unhide image elements
            //
            smallImage.style.display = 'block';

            // Show the captured photo
            // The inline CSS rules are used to resize the image
            //
            smallImage.src = "data:image/jpeg;base64," + imageData;

            // Get image handle
            //
            var largeImage = document.getElementById('largeImage');

            // Unhide image elements
            //
            largeImage.style.display = 'block';
            largeImage.src = "data:image/jpeg;base64," + imageData;

        }

        function onFail(message) {
            console.log('failed');
        }

        navigator.camera.getPicture(onSuccess, onFail, { quality: 50, saveToPhotoAlbum: true,
            destinationType: Camera.DestinationType.DATA_URL,sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
            mediaType: Camera.MediaType.ALLMEDIA
        });

    },

    xhr: function(url, cb) {
        var xhr1 = new XMLHttpRequest();
        xhr1.onreadystatechange = function(args) {
            if(xhr1.readyState==4)
                cb(xhr1);
        };
        xhr1.open("GET", url, true);
        xhr1.send();
    },

    captureVideo: function() {
        navigator.device.capture.captureVideo(function(mediaFiles)
            {
                console.log('CALLBACK!');
                console.log(JSON.stringify(mediaFiles));
            }, function(error)
            {
                console.log('Video capture failed');
                alert ('video failed');
            },
            {
                limit: 1,
                duration: 12
            });

    },

 /*   // Record audio
//
     recordAudio: function() {
    var src = "myrecording.wav";
    var mediaRec = new Media(src,
        // success callback
        function() {
            console.log("recordAudio():Audio Success");
            alert('audio success');
        },

        // error callback
        function(err) {
            console.log("recordAudio():Audio Error: "+ err.code);
        }
    );

    // Record audio
    mediaRec.startRecord();

    // Stop recording after 10 seconds
    setTimeout(function() {
        mediaRec.stopRecord();
    }, 10000);
}*/

    captureAudio: function() {

        // Called when capture operation is finished
        //
        function captureSuccess(mediaFiles) {

            alert ('audio success');
            var i, len;
            for (i = 0, len = mediaFiles.length; i < len; i += 1) {
                uploadFile(mediaFiles[i]);
            }

        }

        // Called if something bad happens.
        //
        function captureError(error) {
            var msg = 'An error occurred during capture: ' + error.code;
            navigator.notification.alert(msg, null, 'Uh oh!');
        }

        navigator.device.capture.captureAudio(function(mediaFiles)
            {
                console.log('CALLBACK!');
                console.log(JSON.stringify(mediaFiles));
            }, function(error)
            {
                console.log('Audio capture failed');
            },
            {
                limit: 1,
                duration: 12
            });

        // Upload files to server
//        function uploadFile(mediaFile) {
//            var ft = new FileTransfer(),
//                path = mediaFile.fullPath,
//                name = mediaFile.name;
//
//            ft.upload(path,
//                "http://my.domain.com/upload.php",
//                function(result) {
//                    console.log('Upload success: ' + result.responseCode);
//                    console.log(result.bytesSent + ' bytes sent');
//                },
//                function(error) {
//                    console.log('Error uploading file ' + path + ': ' + error.code);
//                },
//                { fileName: name });
//        }

    }
};

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

define(function (require, exports, module) {
    "use strict";

    var Fluxxor = require("fluxxor"),
        events = require("../events"),
        Bounds = require("../models/bounds"),
        log = require("js/util/log");

    var BoundsStore = Fluxxor.createStore({
        initialize: function () {
            this._layerBounds = {};
            this._documentBounds = {};
            this.bindActions(
                events.documents.DOCUMENT_UPDATED, this._updateDocumentLayerBounds,
                events.documents.CURRENT_DOCUMENT_UPDATED, this._updateDocumentLayerBounds,
                events.documents.RESET_DOCUMENTS, this._resetAllDocumentLayerBounds,
                events.transform.TRANSLATE_LAYERS, this._handleLayerTranslate,
                events.transform.RESIZE_LAYERS, this._handleLayerResize,
                events.transform.RESIZE_DOCUMENT, this._handleDocumentResize
            );
        },

        getState: function () {
            return {};
        },

        /**
         * Gets the bounds of the document with the ID
         * @param {number} documentID
         * @return {Bounds}
         */
        getDocumentBounds: function (documentID) {
            return this._documentBounds[documentID];
        },

        /**
         * Gets the bounds of specified layer in the specified document
         * @param {number} documentID
         * @param {number} layerID
         * @return {Bounds}
         */
        getLayerBounds: function (documentID, layerID) {
            return this._layerBounds[documentID][layerID];
        },

        /**
         * Given a layer group, that has children bounds already calculated
         * Calculates the bounds of the group
         * Must be called in the right order during initialization, hence it is protected
         * @protected
         *
         * @param {number} documentID
         * @param {Layer} layer Layer Group bounds are calculated for
         * @return {Bounds}
         */
        calculateGroupBounds: function (documentID, layer) {
            var _unionBounds = function (group, child) {
                if (!group) {
                    return new Bounds(child);
                } else if (!child) {
                    // THIS SHOULD NEVER HAPPEN
                    log.warn("child without borders ")
                    return group;
                }

                // Since we're collecting on the group's bounds, we can edit those
                group._top = Math.min(group.top, child.top);
                group._left = Math.min(group.left, child.left);
                group._bottom = Math.max(group.bottom, child.bottom);
                group._right = Math.max(group.right, child.right);
                group._height = group.bottom - group.top;
                group._width = group.right - group.left;

                return group;
            };

            return layer.children.reduce(function (bounds, child) {
                // Skip the group ends
                if (child.kind === child.layerKinds.GROUPEND) {
                    return bounds;
                }

                return _unionBounds(bounds, child.bounds);
            }, null);
        },

        /**
         * Update the bounds bounds for all layers in the document
         *
         * @private
         * @param {{document: object, layers: Array.<object>}} payload
         */
        _updateDocumentLayerBounds: function (payload) {
            var rawDocument = payload.document,
                documentID = rawDocument.documentID,
                layerArray = payload.layers;

            this._documentBounds[documentID] = new Bounds(rawDocument);

            this._layerBounds[documentID] = layerArray.reduce(function (boundsMap, layerObj) {
                boundsMap[layerObj.layerID] = new Bounds(layerObj);
                return boundsMap;
            }, {});

            this.emit("change");
        },

        /**
         * Completely reset all the bounds for all layers in all documents
         *
         * @private
         * @param {Array.<{document: object, layers: Array.<object>}>} payload
         */
        _resetAllDocumentLayerBounds: function (payload) {
            payload.documents.forEach(function (docObj) {
                var rawDocument = docObj.document,
                    documentID = rawDocument.documentID,
                    layerArray = docObj.layers;

                this._documentBounds[documentID] = new Bounds(rawDocument);

                this._layerBounds[documentID] = layerArray.reduce(function (boundsMap, layerObj) {
                    boundsMap[layerObj.layerID] = new Bounds(layerObj);
                    return boundsMap;
                }, {});
            }, this);

            this.emit("change");
        },

        /**
         * Update the bounds of affected layers
         * @private
         * @param {{documentID: number, layerIDs: Array.<number>, position: {x: number, y: number}}} payload
         */
        _handleLayerTranslate: function (payload) {
            payload.layerIDs.forEach(function (layerID) {
                var layerBounds = this._layerBounds[payload.documentID][layerID];
                layerBounds._setPosition(payload.position.x, payload.position.y);
            }, this);

            this.emit("change");
        },

        /**
         * Update the bounds of affected layers
         * @private
         * @param {{documentID: number, layerIDs: Array.<number>, size: {w: number, h: number}}} payload
         */
        _handleLayerResize: function (payload) {
            payload.layerIDs.forEach(function (layerID) {
                var layerBounds = this._layerBounds[payload.documentID][layerID];
                layerBounds._setSize(payload.size.w, payload.size.h);
            }, this);

            this.emit("change");
        },

        /**
         * Update the bounds of the document
         * @private
         * @param {{documentID: number, layerIDs: Array.<number>, size: {w: number, h: number}}} payload
         */
        _handleDocumentResize: function (payload) {
            var documentBounds = this._documentBounds[payload.documentID];

            documentBounds._setSize(payload.size.w, payload.size.h);
            this.emit("change");
        }

    });
    module.exports = BoundsStore;
});
<commit_msg>Set group bounds correctly<commit_after>/*
 * Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

define(function (require, exports, module) {
    "use strict";

    var Fluxxor = require("fluxxor"),
        events = require("../events"),
        Bounds = require("../models/bounds"),
        log = require("js/util/log");

    var BoundsStore = Fluxxor.createStore({
        initialize: function () {
            this._layerBounds = {};
            this._documentBounds = {};
            this.bindActions(
                events.documents.DOCUMENT_UPDATED, this._updateDocumentLayerBounds,
                events.documents.CURRENT_DOCUMENT_UPDATED, this._updateDocumentLayerBounds,
                events.documents.RESET_DOCUMENTS, this._resetAllDocumentLayerBounds,
                events.transform.TRANSLATE_LAYERS, this._handleLayerTranslate,
                events.transform.RESIZE_LAYERS, this._handleLayerResize,
                events.transform.RESIZE_DOCUMENT, this._handleDocumentResize
            );
        },

        getState: function () {
            return {};
        },

        /**
         * Gets the bounds of the document with the ID
         * @param {number} documentID
         * @return {Bounds}
         */
        getDocumentBounds: function (documentID) {
            return this._documentBounds[documentID];
        },

        /**
         * Gets the bounds of specified layer in the specified document
         * @param {number} documentID
         * @param {number} layerID
         * @return {Bounds}
         */
        getLayerBounds: function (documentID, layerID) {
            return this._layerBounds[documentID][layerID];
        },

        /**
         * Given a layer group, that has children bounds already calculated
         * Calculates the bounds of the group
         * Must be called in the right order during initialization, hence it is protected
         * @protected
         *
         * @param {number} documentID
         * @param {Layer} layer Layer Group bounds are calculated for
         * @return {Bounds}
         */
        calculateGroupBounds: function (documentID, layer) {
            var _unionBounds = function (group, child) {
                if (!group) {
                    return new Bounds(child);
                } else if (!child) {
                    // THIS SHOULD NEVER HAPPEN
                    log.warn("child without borders ")
                    return group;
                }

                // Since we're collecting on the group's bounds, we can edit those
                group._top = Math.min(group.top, child.top);
                group._left = Math.min(group.left, child.left);
                group._bottom = Math.max(group.bottom, child.bottom);
                group._right = Math.max(group.right, child.right);
                group._height = group.bottom - group.top;
                group._width = group.right - group.left;

                return group;
            };

            var groupBounds = layer.children.reduce(function (bounds, child) {
                // Skip the group ends
                if (child.kind === child.layerKinds.GROUPEND) {
                    return bounds;
                }

                return _unionBounds(bounds, child.bounds);
            }, null);

            this._layerBounds[documentID][layer.id] = groupBounds;

            return groupBounds;
        },

        /**
         * Update the bounds bounds for all layers in the document
         *
         * @private
         * @param {{document: object, layers: Array.<object>}} payload
         */
        _updateDocumentLayerBounds: function (payload) {
            var rawDocument = payload.document,
                documentID = rawDocument.documentID,
                layerArray = payload.layers;

            this._documentBounds[documentID] = new Bounds(rawDocument);

            this._layerBounds[documentID] = layerArray.reduce(function (boundsMap, layerObj) {
                boundsMap[layerObj.layerID] = new Bounds(layerObj);
                return boundsMap;
            }, {});

            this.emit("change");
        },

        /**
         * Completely reset all the bounds for all layers in all documents
         *
         * @private
         * @param {Array.<{document: object, layers: Array.<object>}>} payload
         */
        _resetAllDocumentLayerBounds: function (payload) {
            payload.documents.forEach(function (docObj) {
                var rawDocument = docObj.document,
                    documentID = rawDocument.documentID,
                    layerArray = docObj.layers;

                this._documentBounds[documentID] = new Bounds(rawDocument);

                this._layerBounds[documentID] = layerArray.reduce(function (boundsMap, layerObj) {
                    boundsMap[layerObj.layerID] = new Bounds(layerObj);
                    return boundsMap;
                }, {});
            }, this);

            this.emit("change");
        },

        /**
         * Update the bounds of affected layers
         * @private
         * @param {{documentID: number, layerIDs: Array.<number>, position: {x: number, y: number}}} payload
         */
        _handleLayerTranslate: function (payload) {
            payload.layerIDs.forEach(function (layerID) {
                var layerBounds = this._layerBounds[payload.documentID][layerID];
                layerBounds._setPosition(payload.position.x, payload.position.y);
            }, this);

            this.emit("change");
        },

        /**
         * Update the bounds of affected layers
         * @private
         * @param {{documentID: number, layerIDs: Array.<number>, size: {w: number, h: number}}} payload
         */
        _handleLayerResize: function (payload) {
            payload.layerIDs.forEach(function (layerID) {
                var layerBounds = this._layerBounds[payload.documentID][layerID];
                layerBounds._setSize(payload.size.w, payload.size.h);
            }, this);

            this.emit("change");
        },

        /**
         * Update the bounds of the document
         * @private
         * @param {{documentID: number, layerIDs: Array.<number>, size: {w: number, h: number}}} payload
         */
        _handleDocumentResize: function (payload) {
            var documentBounds = this._documentBounds[payload.documentID];

            documentBounds._setSize(payload.size.w, payload.size.h);
            this.emit("change");
        }

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