<commit_before>// "Glorious Leader" game, created by Jack Dalton.
// No JQuery.
// No third-party libraries.
// Two assets (un.png; obama.png)
function init() { // called on page load
    c = document.getElementById("canvas"); // get canvas
    ctx = c.getContext("2d"); // get context
    // c.addEventListener("mousedown", getPosition, false);
    startMenu();
}
function startGame() { // game starting function
    document.getElementById("playbutton").style.opacity = 0;
    document.getElementById("playbutton").style.left = -999 + "px";
    document.getElementById("playbutton").style.top = -999 + "px";
    scoreLoop();
    gameloop();
    detectHits();
}
var c, ctx, unX = [], unY = [],
    then = Date.now(),
    lost = false,
    score = 0,
    playing = false; // misc vars
var obama = { // main obama var
    x:240,
    y:460,
    render:function() {
        ctx.drawImage(obamaImage, this.x, this.y, 25, 33); // draws image of obama
    }
};
var un = { // main un var
    render:function() {
        for (var i = 0; i < unX.length; i++) {
            ctx.drawImage(unImage, unX[i], unY[i], 25, 29.619565217); // draws image of un
        }
    },
    generate:function() { // generates new instances of un
        unX.push(rand(40, 460));
        unY.push(rand(0, -10));
    },
    drop:function() { // makes un instances fall
        for (var i = 0; i < unY.length; i++) {
            unY[i] += 2;
        }
    }
};
function detectHits() { // detects collisions between obama and un
    for (var i = 0; i < unX.length; i++) {
        if (
            obama.x <= (unX[i] + 25) &&
            unX[i] <= (obama.x + 25) &&
            obama.y <= (unY[i] + 29.619565217) &&
            unY[i] <= (obama.y + 33)
        ) {
            lost = true; // if player touches an instance of un, player loses
        }
    }
    window.requestAnimationFrame(detectHits); // does it all again
}
function scoreLoop() { // main score loop
    if (!lost) { // if player hasn't lost yet, their score increases
        score++;
        setTimeout(scoreLoop, 100); // does it all again every 10th of a second
    }
}
function gameloop() { // main game loop
    c.width = c.width; // clears canvas
    if (!lost) { // if player hasn't lost
        un.render(); // renders un
        obama.render(); // renders obama
        if (chance5()) { // 5% chance of un instance being generated
            un.generate();
        }
        un.drop(); // makes the fat man fall :)
        var now = Date.now(); // time delta stuff *
        var delta = now - then; //*
        move(delta / 1000); // *
        then = now; // *
        ctx.fillStyle = "red"; // sets text color
        ctx.fillText("Score:" + score, 10, 10); // displays score
    }
    else {
        lose();
        startResetButton();
    }
    window.requestAnimationFrame(gameloop); // does it all again
}
function lose() { // displays loss message
    document.getElementById("lostmessage").style.opacity = 1;
    document.getElementById("lostmessagetext").innerHTML = "Game Over!
Score:" + score + ".";
}
function rand(min, max) { //  random number generator
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
function removeItem(array, item) { // removes item from given array
    var e = array.indexOf(item);
    if (e > -1) {
        array.splice(e, 1);
    }
}
var move = function(m) { // movement function
    if (37 in keysDown && obama.x > 10) { // if left arrow key pressed, move left
        obama.x -= 180 * m; // obama movement
    }
    if (39 in keysDown && obama.x < 485) { // if right arrow key pressed, move right
        obama.x += 180 * m; // obama movement
    }
};
function chance50() { // 50 percent chance
    if (rand(1,2) == 1) {
        return true;
    }
    else {
        return false;
    }
}
function chance5() { // 5 percent chance
    if (rand(1,20) == 1) {
        return true;
    }
    else {
        return false;
    }
}
var keysDown = {}; // keys pressed
addEventListener("keydown", function(e) { // checks for keys down
    keysDown[e.keyCode] = true;
}, false);

addEventListener("keyup", function(e) { // checks for keys released
    delete keysDown[e.keyCode];
}, false);
/*function getPosition(event) {
    var x = event.x;
    var y = event.y;
    x -= c.offsetLeft;
    y -= c.offsetTop;
    buttonCheck(x,y);
}
function buttonCheck(x,y) {
    if (
        x >= 300 &&
        y >= 125 &&
        y <= 335 &&
        x <= 475
    ) {
        startGame();
    }
}*/
function startMenu() { // starts game menu
    c.width = c.width; // clears canvas
    ctx.font = "normal 36px Verdana"; // sets up menu *
    ctx.strokeRect(100, 30, 300, 100); // *
    ctx.strokeStyle = "red"; // *
    ctx.strokeText("Glorious Leader", 130, 90); // *
    ctx.strokeStyle = "black"; // *
    ctx.strokeRect(125, 300, 250, 75); // *
    ctx.strokeText("Play", 210, 350); // **
    if (!playing) { // if play button has not been pressed, rerender menu
        window.requestAnimationFrame(startMenu);
    }
}
function startResetButton() { // sets up reset button
    ctx.strokeRect(125, 300, 250, 75);
    ctx.font = "normal 36px Verdana";
    ctx.strokeText("Reset", 210, 350);
    document.getElementById("resetbutton").style.left = 196 + "px";
    document.getElementById("resetbutton").style.top = 308 + "px";
}
<commit_msg>Update un.js<commit_after>// "Glorious Leader" game, created by Jack Dalton.
// No JQuery.
// No third-party libraries.
// Two assets (un.png; obama.png)
function init() { // called on page load
    c = document.getElementById("canvas"); // get canvas
    ctx = c.getContext("2d"); // get context
    // c.addEventListener("mousedown", getPosition, false);
    startMenu();
}
function startGame() { // game starting function
    playing = true;
    scoreLoop();
    gameloop();
    detectHits();
}
var c, ctx, unX = [], unY = [],
    then = Date.now(),
    lost = false,
    score = 0,
    playing = false; // misc vars
var obama = { // main obama var
    x:240,
    y:460,
    render:function() {
        ctx.drawImage(obamaImage, this.x, this.y, 25, 33); // draws image of obama
    }
};
var un = { // main un var
    render:function() {
        for (var i = 0; i < unX.length; i++) {
            ctx.drawImage(unImage, unX[i], unY[i], 25, 29.619565217); // draws image of un
        }
    },
    generate:function() { // generates new instances of un
        unX.push(rand(40, 460));
        unY.push(rand(0, -10));
    },
    drop:function() { // makes un instances fall
        for (var i = 0; i < unY.length; i++) {
            unY[i] += 2;
        }
    }
};
function detectHits() { // detects collisions between obama and un
    for (var i = 0; i < unX.length; i++) {
        if (
            obama.x <= (unX[i] + 25) &&
            unX[i] <= (obama.x + 25) &&
            obama.y <= (unY[i] + 29.619565217) &&
            unY[i] <= (obama.y + 33)
        ) {
            lost = true; // if player touches an instance of un, player loses
        }
    }
    window.requestAnimationFrame(detectHits); // does it all again
}
function scoreLoop() { // main score loop
    if (!lost) { // if player hasn't lost yet, their score increases
        score++;
        setTimeout(scoreLoop, 100); // does it all again every 10th of a second
    }
}
function gameloop() { // main game loop
    c.width = c.width; // clears canvas
    if (!lost) { // if player hasn't lost
        un.render(); // renders un
        obama.render(); // renders obama
        if (chance5()) { // 5% chance of un instance being generated
            un.generate();
        }
        un.drop(); // makes the fat man fall :)
        var now = Date.now(); // time delta stuff *
        var delta = now - then; //*
        move(delta / 1000); // *
        then = now; // *
        ctx.fillStyle = "red"; // sets text color
        ctx.fillText("Score:" + score, 10, 10); // displays score
    }
    else {
        lose();
        startResetButton();
    }
    window.requestAnimationFrame(gameloop); // does it all again
}
function lose() { // displays loss message
    document.getElementById("lostmessage").style.opacity = 1;
    document.getElementById("lostmessagetext").innerHTML = "Game Over!
Score:" + score + ".";
}
function rand(min, max) { //  random number generator
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
function removeItem(array, item) { // removes item from given array
    var e = array.indexOf(item);
    if (e > -1) {
        array.splice(e, 1);
    }
}
var move = function(m) { // movement function
    if (37 in keysDown && obama.x > 10) { // if left arrow key pressed, move left
        obama.x -= 180 * m; // obama movement
    }
    if (39 in keysDown && obama.x < 485) { // if right arrow key pressed, move right
        obama.x += 180 * m; // obama movement
    }
};
function chance50() { // 50 percent chance
    if (rand(1,2) == 1) {
        return true;
    }
    else {
        return false;
    }
}
function chance5() { // 5 percent chance
    if (rand(1,20) == 1) {
        return true;
    }
    else {
        return false;
    }
}
var keysDown = {}; // keys pressed
addEventListener("keydown", function(e) { // checks for keys down
    keysDown[e.keyCode] = true;
}, false);

addEventListener("keyup", function(e) { // checks for keys released
    delete keysDown[e.keyCode];
}, false);
/*function getPosition(event) {
    var x = event.x;
    var y = event.y;
    x -= c.offsetLeft;
    y -= c.offsetTop;
    buttonCheck(x,y);
}
function buttonCheck(x,y) {
    if (
        x >= 300 &&
        y >= 125 &&
        y <= 335 &&
        x <= 475
    ) {
        startGame();
    }
}*/
window.onkeypress = checkKey;
function checkKey(e) {
    if (e.keyCode == 32 && playing === false) {
        startGame();
    }
    if (e.keyCode == 32 && lost === true) {
        window.location.assign(window.location);
    }
}
function startMenu() { // starts game menu
    c.width = c.width; // clears canvas
    ctx.font = "normal 32px Verdana"; // sets up menu *
    ctx.strokeRect(100, 30, 300, 100); // *
    ctx.strokeStyle = "red"; // *
    ctx.strokeText("Glorious Leader", 130, 90); // *
    ctx.strokeStyle = "black"; // *
    ctx.strokeRect(125, 300, 250, 75); // *
    ctx.strokeText("Space to play.", 165, 350); // **
    if (!playing) { // if play button has not been pressed, rerender menu
        window.requestAnimationFrame(startMenu);
    }
}
function startResetButton() { // sets up reset button
    ctx.strokeRect(125, 300, 250, 75);
    ctx.font = "normal 32px Verdana";
    ctx.strokeText("Space to reset.", 165, 350);
}
<|endoftext|>


<commit_before>var br = true;
var running = false;
(function () {
    var mute = false, muteSt;
    var m = 0;
    var s = 15;
    var r = 1;
    var ds = "00";
    var c = 0;
    var txt = "First grace period";
    var start = 1;
    (function () {
        if (Notification.permission !== "granted")
            Notification.requestPermission();
        muteSt = document.getElementById('muteSt');
        document.getElementById('mute').addEventListener('click', function () { mute = !mute; (mute) ? (muteSt.innerHTML = 'Muted', muteSt.style.marginBottom = ".65em") : (muteSt.innerHTML = '', muteSt.style.marginBottom = "1.75em") });
        document.getElementById('toggle').addEventListener('click', function () { var btn = document.getElementById('toggle'); if (!running) { interval = setInterval(function () { tick() }, 1000); btn.style.content = "url(/tomodoro/Content/pause.png)"; } else { clearInterval(interval); btn.style.content = "url(./Content/play.png)"; } running = !running; btn.classList.toggle('pause'); btn.classList.toggle('play') });
    }());
    function tick() {
        s--;
        update();
    }
    function update() {
        if (m === 0 && s <= 0) {
            if (r === 0) {
                alarm(txt);
                txt = "Grace period";
                m = 0;
                s = 15;
                r = 1;
            }
            if (start == 1) {
                alarm(txt);
                start = 0;
            }
            if (r == 1 && s !== 15) {
                if (!br) {
                    if (c < 3) {
                        txt = "Short break";
                        m = 5;
                    }
                    else {
                        txt = 'Long break';
                        c = 0;
                        m = 10;
                    }
                    s = 60;
                    c++;
                    br = true;
                }
                if (br && m === 0) {
                    br = false;
                    txt = 'Work time';
                    m = 25;
                    s = 60;
                }
                r = 0;
            }
            document.getElementById('txt').innerText = txt;
        }
        format();
        document.getElementById('disp').innerText = m + ':' + ds;
    }
    function format() {
        switch (true) {
            case (s <= 0 && m !== 0):
                s = 60;
                break;
            case (s <= 9):
                ds = String("0" + s);
                break;
            case (s >= 60):
                ds = String("00");
                break;
            case (s == 59 && m !== 0):
                m--;
                ds = '59';
                break;
            default:
                ds = String(s);
                break;
        }
    }
    function alarm(a) {
        var stop = function () {
            document.getElementById('break').pause();
            document.getElementById('work').pause();
            document.getElementById('break').currentTime = 0;
            document.getElementById('work').currentTime = 0;
        };
        var ntxt = a + " is over";
        if (Notification.permission === "granted") {
            var note = new Notification((!br) ? "Time to take a break" : "Time to get back to work", { icon: '/tomodoro/Content/clock.png', body: ntxt });
            note.addEventListener('show', function () { setTimeout(note.close.bind(note), 2000) });
            note.addEventListener('click', stop);
            note.addEventListener('close', stop);
        }
        if (!mute) {
            if (!br)
                document.getElementById('break').play();
            else
                document.getElementById('work').play();
            setTimeout(stop, 2000);
        }
    }
}());
<commit_msg>Fix refs<commit_after>var br = true;
var running = false;
(function () {
    var mute = false, muteSt;
    var m = 0;
    var s = 15;
    var r = 1;
    var ds = "00";
    var c = 0;
    var txt = "First grace period";
    var start = 1;
    (function () {
        if (Notification.permission !== "granted")
            Notification.requestPermission();
        muteSt = document.getElementById('muteSt');
        document.getElementById('mute').addEventListener('click', function () { mute = !mute; (mute) ? (muteSt.innerHTML = 'Muted', muteSt.style.marginBottom = ".65em") : (muteSt.innerHTML = '', muteSt.style.marginBottom = "1.75em") });
        document.getElementById('toggle').addEventListener('click', function () { var btn = document.getElementById('toggle'); if (!running) { interval = setInterval(function () { tick() }, 1000); btn.style.content = "url(/tomodoro/Content/pause.png)"; } else { clearInterval(interval); btn.style.content = "url(/tomodoro/Content/play.png)"; } running = !running; btn.classList.toggle('pause'); btn.classList.toggle('play') });
    }());
    function tick() {
        s--;
        update();
    }
    function update() {
        if (m === 0 && s <= 0) {
            if (r === 0) {
                alarm(txt);
                txt = "Grace period";
                m = 0;
                s = 15;
                r = 1;
            }
            if (start == 1) {
                alarm(txt);
                start = 0;
            }
            if (r == 1 && s !== 15) {
                if (!br) {
                    if (c < 3) {
                        txt = "Short break";
                        m = 5;
                    }
                    else {
                        txt = 'Long break';
                        c = 0;
                        m = 10;
                    }
                    s = 60;
                    c++;
                    br = true;
                }
                if (br && m === 0) {
                    br = false;
                    txt = 'Work time';
                    m = 25;
                    s = 60;
                }
                r = 0;
            }
            document.getElementById('txt').innerText = txt;
        }
        format();
        document.getElementById('disp').innerText = m + ':' + ds;
    }
    function format() {
        switch (true) {
            case (s <= 0 && m !== 0):
                s = 60;
                break;
            case (s <= 9):
                ds = String("0" + s);
                break;
            case (s >= 60):
                ds = String("00");
                break;
            case (s == 59 && m !== 0):
                m--;
                ds = '59';
                break;
            default:
                ds = String(s);
                break;
        }
    }
    function alarm(a) {
        var stop = function () {
            document.getElementById('break').pause();
            document.getElementById('work').pause();
            document.getElementById('break').currentTime = 0;
            document.getElementById('work').currentTime = 0;
        };
        var ntxt = a + " is over";
        if (Notification.permission === "granted") {
            var note = new Notification((!br) ? "Time to take a break" : "Time to get back to work", { icon: '/tomodoro/Content/clock.png', body: ntxt });
            note.addEventListener('show', function () { setTimeout(note.close.bind(note), 2000) });
            note.addEventListener('click', stop);
            note.addEventListener('close', stop);
        }
        if (!mute) {
            if (!br)
                document.getElementById('break').play();
            else
                document.getElementById('work').play();
            setTimeout(stop, 2000);
        }
    }
}());
<|endoftext|>


<commit_before>/**
Message for highlighting the failure, possible failure, or success of
an action. Particularly useful for forms.
*/
Ext.define('devilry_extjsextras.AlertMessage', {
    extend: 'Ext.Component',
    alias: 'widget.alertmessage',

    tpl: [
        '
',
            '<tpl if="title">',
                '
{title}
',
            '</tpl>',
            '{message}',
        '
'
    ],

    /**
     * @cfg
     * Type of message. Valid values: 'error', 'warning', 'info' or 'success'.
     * Defaults to 'warning'.
     */
    type: 'warning',

    /**
     * @cfg
     * The one line of message to display. This is not required, as it may be
     * useful to initialize an hidden alert message and use update() to change
     * the message when there is a message to show.
     */
    message: '',

    /**
     * @cfg
     * An optional title for the message.
     */
    title: null,

    initComponent: function() {
        var cls = 'bootstrap devilry_extjsextras_alertmessage';
        if(this.cls) {
            cls += Ext.String.format('{0} {1}', cls, this.cls);
        }
        this.cls = cls;
        this.callParent(arguments);
        this.update(this.message, this.type);
    },

    /**
     * Update the message and optionally the type. If the type is not
     * specified, the type will not be changed.
     * */
    update: function(message, type) {
        if(type) {
            this.type = type;
        }
        this.message = message;
        this.callParent([{
            type: this.type,
            message: this.message,
            title: this.title
        }]);
    }
});
<commit_msg>devilry_extjsextras...AlertMessage: Closable.<commit_after>/**
Message for highlighting the failure, possible failure, or success of
an action. Particularly useful for forms.
*/
Ext.define('devilry_extjsextras.AlertMessage', {
    extend: 'Ext.Component',
    alias: 'widget.alertmessage',

    tpl: [
        '
',
            '<tpl if="closable">',
                '<button type="button" class="close" data-dismiss="alert">×</button>',
            '</tpl>',
            '<tpl if="title">',
                '{title}',
            '</tpl>',
            '{message}',
        '
'
    ],

    /**
     * @cfg
     * Type of message. Valid values: 'error', 'warning', 'info' or 'success'.
     * Defaults to 'warning'.
     */
    type: 'warning',

    /**
     * @cfg
     * The one line of message to display. This is not required, as it may be
     * useful to initialize an hidden alert message and use update() to change
     * the message when there is a message to show.
     */
    message: '',

    /**
     * @cfg {bool} [closable=false]
     * Show close button. The ``closed`` event is fired when the button is
     * clicked.
     */
    closable: false,

    /**
     * @cfg
     * An optional title for the message.
     */
    title: null,

    initComponent: function() {
        var cls = 'bootstrap devilry_extjsextras_alertmessage';
        if(this.cls) {
            cls += Ext.String.format('{0} {1}', cls, this.cls);
        }
        this.cls = cls;
        this.callParent(arguments);
        this.update(this.message, this.type);

        this.addListener({
            scope: this,
            element: 'el',
            delegate: '.close',
            click: function(e) {
                e.preventDefault();
                this.fireEvent('closed', this, e);
            }
        });
    },

    /**
     * Update the message and optionally the type. If the type is not
     * specified, the type will not be changed.
     * */
    update: function(message, type) {
        if(type) {
            this.type = type;
        }
        this.message = message;
        this.callParent([{
            type: this.type,
            message: this.message,
            title: this.title,
            closable: this.closable
        }]);
    }
});
<|endoftext|>


<commit_before>/*global module:false*/
module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    // Metadata.
    meta: {
      version: '0.1.0'
    },
    banner: '/*! PROJECT_NAME - v<%= meta.version %> - ' +
      '<%= grunt.template.today("yyyy-mm-dd") %>\n' +
      '* http://PROJECT_WEBSITE/\n' +
      '* Copyright (c) <%= grunt.template.today("yyyy") %> ' +
      'YOUR_NAME; Licensed MIT */\n',
    // Task configuration.
    concat: {
      options: {
        banner: '<%= banner %>',
        stripBanners: true
      },
      dist: {
        src: ['lib/FILE_NAME.js'],
        dest: 'dist/FILE_NAME.js'
      }
    },
    bower: {
      target: {
        rjsConfig: 'init.js'
      }
    },
    uglify: {
      options: {
        banner: '<%= banner %>'
      },
      dist: {
        src: '<%= concat.dist.dest %>',
        dest: 'dist/FILE_NAME.min.js'
      }
    },
    jshint: {
      options: {
        curly: true,
        eqeqeq: true,
        immed: true,
        latedef: true,
        newcap: true,
        noarg: true,
        sub: true,
        undef: true,
        unused: true,
        boss: true,
        eqnull: true,
        browser: true,
        globals: {
          jQuery: true
        }
      },
      gruntfile: {
        src: 'Gruntfile.js'
      },
      lib_test: {
        src: ['lib/**/*.js', 'test/**/*.js']
      }
    },
    less: {
      development: {
        options: {
          paths: ["css"]
        },
        files: {
          "css/main.css": "less/main.less"
        }
      },
      production: {
        options: {
          paths: ["css"],
          cleancss: true,
          modifyVars: {
            //imgPath: '"http://mycdn.com/path/to/images"',
          }
        },
        files: {
          "css/main.css": "less/main.less"
        }
      }
    },
    qunit: {
      files: ['test/**/*.html']
    },
    watch: {
      gruntfile: {
        files: '<%= jshint.gruntfile.src %>',
        tasks: ['jshint:gruntfile']
      },
      lib_test: {
        files: '<%= jshint.lib_test.src %>',
        tasks: ['jshint:lib_test', 'qunit']
      }
    }
  });

  // These plugins provide necessary tasks.
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-qunit');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-less');
  grunt.loadNpmTasks('grunt-bower-requirejs');

  // Default task.
  grunt.registerTask('default', ['jshint', 'qunit', 'concat', 'uglify', 'less']);
  grunt.registerTask('bower', ['bower']);

};
<commit_msg>update Grunt banner info<commit_after>/*global module:false*/
module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    // Metadata.
    meta: {
      version: '0.1.0'
    },
    banner: '/*! dropwizard-backbone-app - v<%= meta.version %> - ' +
      '<%= grunt.template.today("yyyy-mm-dd") %>\n' +
      '* https://github.com/yokuze/dropwizard-backbone-app/\n' +
      '* Copyright (c) <%= grunt.template.today("yyyy") %> ' +
      'Matt Luedke; Licensed MIT */\n',
    // Task configuration.
    concat: {
      options: {
        banner: '<%= banner %>',
        stripBanners: true
      },
      dist: {
        src: ['lib/FILE_NAME.js'],
        dest: 'dist/FILE_NAME.js'
      }
    },
    bower: {
      target: {
        rjsConfig: 'init.js'
      }
    },
    uglify: {
      options: {
        banner: '<%= banner %>'
      },
      dist: {
        src: '<%= concat.dist.dest %>',
        dest: 'dist/FILE_NAME.min.js'
      }
    },
    jshint: {
      options: {
        curly: true,
        eqeqeq: true,
        immed: true,
        latedef: true,
        newcap: true,
        noarg: true,
        sub: true,
        undef: true,
        unused: true,
        boss: true,
        eqnull: true,
        browser: true,
        globals: {
          jQuery: true
        }
      },
      gruntfile: {
        src: 'Gruntfile.js'
      },
      lib_test: {
        src: ['lib/**/*.js', 'test/**/*.js']
      }
    },
    less: {
      development: {
        options: {
          paths: ["css"]
        },
        files: {
          "css/main.css": "less/main.less"
        }
      },
      production: {
        options: {
          paths: ["css"],
          cleancss: true,
          modifyVars: {
            //imgPath: '"http://mycdn.com/path/to/images"',
          }
        },
        files: {
          "css/main.css": "less/main.less"
        }
      }
    },
    qunit: {
      files: ['test/**/*.html']
    },
    watch: {
      gruntfile: {
        files: '<%= jshint.gruntfile.src %>',
        tasks: ['jshint:gruntfile']
      },
      lib_test: {
        files: '<%= jshint.lib_test.src %>',
        tasks: ['jshint:lib_test', 'qunit']
      }
    }
  });

  // These plugins provide necessary tasks.
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-qunit');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-less');
  grunt.loadNpmTasks('grunt-bower-requirejs');

  // Default task.
  grunt.registerTask('default', ['jshint', 'qunit', 'concat', 'uglify', 'less']);
  grunt.registerTask('bower', ['bower']);

};
<|endoftext|>


<commit_before>dojo.provide("dijit.form._FormWidget");

dojo.require("dijit._Widget");
dojo.require("dijit._Templated");

dojo.declare("dijit.form._FormWidget", [dijit._Widget, dijit._Templated],
{
	/*
	Summary:
		FormElement widgets correspond to native HTML elements such as <input> or <button> or <select>.
		Each FormElement represents a single input value, and has a (possibly hidden) <input> element,
		to which it serializes its input value, so that form submission (either normal submission or via FormBind?)
		works as expected.

		All these widgets should have these attributes just like native HTML input elements.
		You can set them during widget construction, but after that they are read only.

		They also share some common methods.
	*/

	// baseClass: String
	//		Used to add CSS classes like FormElementDisabled
	// TODO: remove this in favor of this.domNode.baseClass?
	baseClass: "",

	// value: String
	//		Corresponds to the native HTML <input> element's attribute.
	value: "",

	// name: String
	//		Name used when submitting form; same as "name" attribute or plain HTML elements
	name: "",

	// id: String
	//		Corresponds to the native HTML <input> element's attribute.
	//		Also becomes the id for the widget.
	id: "",

	// alt: String
	//		Corresponds to the native HTML <input> element's attribute.
	alt: "",

	// type: String
	//		Corresponds to the native HTML <input> element's attribute.
	type: "text",

	// tabIndex: Integer
	//		Order fields are traversed when user hits the tab key
	tabIndex: "0",

	// disabled: Boolean
	//		Should this widget respond to user input?
	//		In markup, this is specified as "disabled='disabled'", or just "disabled".
	disabled: false,

	// intermediateChanges: Boolean
	//              Fires onChange for each value change or only on demand
	intermediateChanges: false,

	setDisabled: function(/*Boolean*/ disabled){
		// summary:
		//		Set disabled state of widget.

		this.domNode.disabled = this.disabled = disabled;
		if(this.focusNode){
			this.focusNode.disabled = disabled;
		}
		dijit.wai.setAttr(this.focusNode || this.domNode, "waiState", "disabled", disabled);
		this._setStateClass();
	},

	_onMouse : function(/*Event*/ event){
		// summary:
		//	Sets _hovering, _active, and baseClass attributes depending on mouse state,
		//	then calls setStateClass() to set appropriate CSS class for this.domNode.
		//
		//	To get a different CSS class for hover, send onmouseover and onmouseout events to this method.
		//	To get a different CSS class while mouse button is depressed, send onmousedown to this method.

		var mouseNode = event.target;

		if(!this.disabled){
			switch(event.type){
				case "mouseover" :
					this._hovering = true;
					var baseClass, node=mouseNode;
					while( !(baseClass=node.getAttribute("baseClass")) && node != this.domNode ){
						node=node.parentNode;
					}
					this.baseClass= baseClass || "dijit"+this.declaredClass.replace(/.*\./g,"");
					break;

				case "mouseout" :
					this._hovering = false;
					this.baseClass=null;
					break;

				case "mousedown" :
					this._active = true;
					// set a global event to handle mouseup, so it fires properly
					//	even if the cursor leaves the button
					var self = this;
					// #2685: use this.connect and disconnect so destroy works properly
					var mouseUpConnector = this.connect(dojo.body(), "onmouseup", function(){
						self._active = false;
						self._setStateClass();
						self.disconnect(mouseUpConnector);
					});
					break;
			}
			this._setStateClass();
		}
	},

	focus: function(){
		dijit.focus(this.focusNode);
	},

	_setStateClass: function(/*String*/ base){
		// summary:
		//	Update the visual state of the widget by changing the css class on the domnode
		//	according to widget state.
		//
		//	State will be one of:
		//		<baseClass>
		//		<baseClass> + "Disabled"	- if the widget is disabled
		//		<baseClass> + "Active"		- if the mouse (or space/enter key?) is being pressed down
		//		<baseClass> + "Hover"		- if the mouse is over the widget
		//		<baseClass> + "Focused"		- if the widget has focus
		//
		//	Note: if you don't want to change the way the widget looks on hover, then don't call
		//	this routine on hover.  Similarly for mousedown --> active
		//
		//	For widgets which can be in a checked state (like checkbox or radio),
		//	in addition to the above classes...
		//		<baseClass> + "Checked"
		//		<baseClass> + "CheckedDisabled"	- if the widget is disabled
		//		<baseClass> + "CheckedActive"		- if the mouse is being pressed down
		//		<baseClass> + "CheckedHover"		- if the mouse is over the widget
		//		<baseClass> + "CheckedFocused"		- if the widget has focus

		// get original class (non state related) specified in template
		var origClass = this._origClass || (this._origClass = this.domNode.className);

		// compute list of classname representing the states of the widget
		var base = this.baseClass || this.domNode.getAttribute("baseClass");
		var classes = [ base ];

		function multiply(modifier){
			classes=classes.concat(dojo.map(classes, function(c){ return c+modifier; }));
		}

		if(this.checked){
			multiply("Checked");
		}
		if(this.selected){
			multiply("Selected");
		}

		// Only one of these three can be applied.
		// Active trumps Focused, Focused trumps Hover, and Disabled trumps all.
		if(this.disabled){
			multiply("Disabled");
		}else if(this._active){
			multiply("Active");
		}else if(this._focused){
			multiply("Focused");
		}else if(this._hovering){
			multiply("Hover");
		}

		this.domNode.className = origClass + " " + classes.join(" ");
	},

	onChange: function(newValue){
		// summary: callback when value is changed
	},

	postCreate: function(){
		this.setDisabled(this.disabled);
		this._setStateClass();
		this.setValue(this.value, true);
	},

	setValue: function(/*anything*/ newValue, /*Boolean, optional*/ priorityChange){
		// summary: set the value of the widget.
		this._lastValue = newValue;
		dijit.wai.setAttr(this.focusNode || this.domNode, "waiState", "valuenow", this.forWaiValuenow());
		if((this.intermediateChanges || priorityChange) && newValue != this._lastValueReported){
			this._lastValueReported = newValue;
			this.onChange(newValue);
		}
	},

	getValue: function(){
		// summary: get the value of the widget.
		return this._lastValue;
	},

	undo: function(){
		// summary: restore the value to the last value passed to onChange
		this.setValue(this._lastValueReported, false);
	},

	_onKeyPress: function(e){
		if(e.keyCode == dojo.keys.ESCAPE && !e.shiftKey && !e.ctrlKey && !e.altKey){
			var v = this.getValue();
			var lv = this._lastValueReported;
			// Equality comparison of objects such as dates are done by reference so
			// two distinct objects are != even if they have the same data. So use
			// toStrings in case the values are objects.
			if(lv != undefined && v.toString() != lv.toString()){
				this.undo();
				dojo.stopEvent(e);
				return false;
			}
		}
		return true;
	},

	forWaiValuenow: function(){
		// summary: returns a value, reflecting the current state of the widget,
		//		to be used for the ARIA valuenow.
		// 		This method may be overridden by subclasses that want
		// 		to use something other than this.getValue() for valuenow
		return this.getValue();
	},

	resize:function(/*Object*/ contentBox){
		// summary:
		//		Explicitly set this widget's size (in pixels).
		//		Unlike layout containers, this sets the content box size.
		//		Subwidgets may override this function
		//
		// contentBox: Object
		//		{w: int, h: int}
		dojo.contentBox(this.domNode, contentBox);
	}
});
<commit_msg>Fixes #3853.  Proxy commit for haysmark. Added styleNode to list of special dojoAtachPoints. Changed TextArea template to allow FF to resize.<commit_after>dojo.provide("dijit.form._FormWidget");

dojo.require("dijit._Widget");
dojo.require("dijit._Templated");

dojo.declare("dijit.form._FormWidget", [dijit._Widget, dijit._Templated],
{
	/*
	Summary:
		FormElement widgets correspond to native HTML elements such as <input> or <button> or <select>.
		Each FormElement represents a single input value, and has a (possibly hidden) <input> element,
		to which it serializes its input value, so that form submission (either normal submission or via FormBind?)
		works as expected.

		All these widgets should have these attributes just like native HTML input elements.
		You can set them during widget construction, but after that they are read only.

		They also share some common methods.
	*/

	// baseClass: String
	//		Used to add CSS classes like FormElementDisabled
	// TODO: remove this in favor of this.domNode.baseClass?
	baseClass: "",

	// value: String
	//		Corresponds to the native HTML <input> element's attribute.
	value: "",

	// name: String
	//		Name used when submitting form; same as "name" attribute or plain HTML elements
	name: "",

	// id: String
	//		Corresponds to the native HTML <input> element's attribute.
	//		Also becomes the id for the widget.
	id: "",

	// alt: String
	//		Corresponds to the native HTML <input> element's attribute.
	alt: "",

	// type: String
	//		Corresponds to the native HTML <input> element's attribute.
	type: "text",

	// tabIndex: Integer
	//		Order fields are traversed when user hits the tab key
	tabIndex: "0",

	// disabled: Boolean
	//		Should this widget respond to user input?
	//		In markup, this is specified as "disabled='disabled'", or just "disabled".
	disabled: false,

	// intermediateChanges: Boolean
	//              Fires onChange for each value change or only on demand
	intermediateChanges: false,

	setDisabled: function(/*Boolean*/ disabled){
		// summary:
		//		Set disabled state of widget.

		this.domNode.disabled = this.disabled = disabled;
		if(this.focusNode){
			this.focusNode.disabled = disabled;
		}
		dijit.wai.setAttr(this.focusNode || this.domNode, "waiState", "disabled", disabled);
		this._setStateClass();
	},

	_onMouse : function(/*Event*/ event){
		// summary:
		//	Sets _hovering, _active, and baseClass attributes depending on mouse state,
		//	then calls setStateClass() to set appropriate CSS class for this.domNode.
		//
		//	To get a different CSS class for hover, send onmouseover and onmouseout events to this method.
		//	To get a different CSS class while mouse button is depressed, send onmousedown to this method.

		var mouseNode = event.target;

		if(!this.disabled){
			switch(event.type){
				case "mouseover" :
					this._hovering = true;
					var baseClass, node=mouseNode;
					while( !(baseClass=node.getAttribute("baseClass")) && node != this.domNode ){
						node=node.parentNode;
					}
					this.baseClass= baseClass || "dijit"+this.declaredClass.replace(/.*\./g,"");
					break;

				case "mouseout" :
					this._hovering = false;
					this.baseClass=null;
					break;

				case "mousedown" :
					this._active = true;
					// set a global event to handle mouseup, so it fires properly
					//	even if the cursor leaves the button
					var self = this;
					// #2685: use this.connect and disconnect so destroy works properly
					var mouseUpConnector = this.connect(dojo.body(), "onmouseup", function(){
						self._active = false;
						self._setStateClass();
						self.disconnect(mouseUpConnector);
					});
					break;
			}
			this._setStateClass();
		}
	},

	focus: function(){
		dijit.focus(this.focusNode);
	},

	_setStateClass: function(/*String*/ base){
		// summary:
		//	Update the visual state of the widget by changing the css class on the domnode
		//	according to widget state.
		//
		//	State will be one of:
		//		<baseClass>
		//		<baseClass> + "Disabled"	- if the widget is disabled
		//		<baseClass> + "Active"		- if the mouse (or space/enter key?) is being pressed down
		//		<baseClass> + "Hover"		- if the mouse is over the widget
		//		<baseClass> + "Focused"		- if the widget has focus
		//
		//	Note: if you don't want to change the way the widget looks on hover, then don't call
		//	this routine on hover.  Similarly for mousedown --> active
		//
		//	For widgets which can be in a checked state (like checkbox or radio),
		//	in addition to the above classes...
		//		<baseClass> + "Checked"
		//		<baseClass> + "CheckedDisabled"	- if the widget is disabled
		//		<baseClass> + "CheckedActive"		- if the mouse is being pressed down
		//		<baseClass> + "CheckedHover"		- if the mouse is over the widget
		//		<baseClass> + "CheckedFocused"		- if the widget has focus

		// get original class (non state related) specified in template
		var origClass = this._origClass || (this._origClass = (this.styleNode||this.domNode).className);

		// compute list of classname representing the states of the widget
		var base = this.baseClass || this.domNode.getAttribute("baseClass");
		var classes = [ base ];

		function multiply(modifier){
			classes=classes.concat(dojo.map(classes, function(c){ return c+modifier; }));
		}

		if(this.checked){
			multiply("Checked");
		}
		if(this.selected){
			multiply("Selected");
		}

		// Only one of these three can be applied.
		// Active trumps Focused, Focused trumps Hover, and Disabled trumps all.
		if(this.disabled){
			multiply("Disabled");
		}else if(this._active){
			multiply("Active");
		}else if(this._focused){
			multiply("Focused");
		}else if(this._hovering){
			multiply("Hover");
		}

		(this.styleNode || this.domNode).className = origClass + " " + classes.join(" ");
	},

	onChange: function(newValue){
		// summary: callback when value is changed
	},

	postCreate: function(){
		this.setDisabled(this.disabled);
		this._setStateClass();
		this.setValue(this.value, true);
	},

	setValue: function(/*anything*/ newValue, /*Boolean, optional*/ priorityChange){
		// summary: set the value of the widget.
		this._lastValue = newValue;
		dijit.wai.setAttr(this.focusNode || this.domNode, "waiState", "valuenow", this.forWaiValuenow());
		if((this.intermediateChanges || priorityChange) && newValue != this._lastValueReported){
			this._lastValueReported = newValue;
			this.onChange(newValue);
		}
	},

	getValue: function(){
		// summary: get the value of the widget.
		return this._lastValue;
	},

	undo: function(){
		// summary: restore the value to the last value passed to onChange
		this.setValue(this._lastValueReported, false);
	},

	_onKeyPress: function(e){
		if(e.keyCode == dojo.keys.ESCAPE && !e.shiftKey && !e.ctrlKey && !e.altKey){
			var v = this.getValue();
			var lv = this._lastValueReported;
			// Equality comparison of objects such as dates are done by reference so
			// two distinct objects are != even if they have the same data. So use
			// toStrings in case the values are objects.
			if(lv != undefined && v.toString() != lv.toString()){
				this.undo();
				dojo.stopEvent(e);
				return false;
			}
		}
		return true;
	},

	forWaiValuenow: function(){
		// summary: returns a value, reflecting the current state of the widget,
		//		to be used for the ARIA valuenow.
		// 		This method may be overridden by subclasses that want
		// 		to use something other than this.getValue() for valuenow
		return this.getValue();
	},

	resize:function(/*Object*/ contentBox){
		// summary:
		//		Explicitly set this widget's size (in pixels).
		//		Unlike layout containers, this sets the content box size.
		//		Subwidgets may override this function
		//
		// contentBox: Object
		//		{w: int, h: int}
		dojo.contentBox(this.domNode, contentBox);
	}
});
<|endoftext|>


<commit_before>dojo.provide("dijit.form._FormWidget");

dojo.require("dijit._Widget");
dojo.require("dijit._Templated");
dojo.require("dijit.util.sniff");
dojo.require("dijit.util.wai");

dojo.declare("dijit.form._FormWidget", [dijit._Widget, dijit._Templated],
{
	/*
	Summary:
		FormElement widgets correspond to native HTML elements such as <input> or <button> or <select>.
		Each FormElement represents a single input value, and has a (possibly hidden) <input> element,
		to which it serializes its input value, so that form submission (either normal submission or via FormBind?)
		works as expected.

		All these widgets should have these attributes just like native HTML input elements.
		You can set them during widget construction, but after that they are read only.

		They also share some common methods.
	*/

	// baseClass: String
	//		Used to add CSS classes like FormElementDisabled
	// TODO: remove this in favor of this.domNode.baseClass?
	baseClass: "",

	// value: String
	//		Corresponds to the native HTML <input> element's attribute.
	value: "",

	// name: String
	//		Name used when submitting form; same as "name" attribute or plain HTML elements
	name: "",

	// id: String
	//		Corresponds to the native HTML <input> element's attribute.
	//		Also becomes the id for the widget.
	id: "",

	// alt: String
	//		Corresponds to the native HTML <input> element's attribute.
	alt: "",

	// type: String
	//		Corresponds to the native HTML <input> element's attribute.
	type: "text",

	// tabIndex: Integer
	//		Order fields are traversed when user hits the tab key
	tabIndex: "0",

	// disabled: Boolean
	//		Should this widget respond to user input?
	//		In markup, this is specified as "disabled='disabled'", or just "disabled".
	disabled: false,

	// intermediateChanges: Boolean
	//              Fires onChange for each value change or only on demand
	intermediateChanges: false,

	setDisabled: function(/*Boolean*/ disabled){
		// summary:
		//		Set disabled state of widget.

		this.domNode.disabled = this.disabled = disabled;
		if(this.focusNode){
			this.focusNode.disabled = disabled;
		}
		dijit.util.wai.setAttr(this.focusNode || this.domNode, "waiState", "disabled", disabled);
		this._setStateClass();
	},

	_onMouse : function(/*Event*/ event){
		// summary:
		//	Sets _hovering, _active, and baseClass attributes depending on mouse state,
		//	then calls setStateClass() to set appropriate CSS class for this.domNode.
		//
		//	To get a different CSS class for hover, send onmouseover and onmouseout events to this method.
		//	To get a different CSS class while mouse button is depressed, send onmousedown to this method.

		var mouseNode = event.target;

		if(!this.disabled){
			switch(event.type){
				case "mouseover" :
					this._hovering = true;
					var baseClass, node=mouseNode;
					while( !(baseClass=node.getAttribute("baseClass")) && node != this.domNode ){
						node=node.parentNode;
					}
					this.baseClass= baseClass || "dijit"+this.declaredClass.replace(/.*\./g,"");
					break;

				case "mouseout" :
					this._hovering = false;
					this.baseClass=null;
					break;

				case "mousedown" :
					this._active = true;
					// set a global event to handle mouseup, so it fires properly
					//	even if the cursor leaves the button
					this._active = true;
					var self = this;
					// #2685: use this.connect and disconnect so destroy works properly
					var mouseUpConnector = this.connect(dojo.body(), "onmouseup", function(){
						self._active = false;
						self._setStateClass();
						self.disconnect(mouseUpConnector);
					});
					break;
			}
			this._setStateClass();
		}
	},

	focus: function(){
		if(this.focusNode && this.focusNode.focus){	// mozilla 1.7 doesn't have focus() func
			this.focusNode.focus();
		}
	},

	_setStateClass: function(/*String*/ base){
		// summary:
		//	Update the visual state of the widget by changing the css class on the domnode
		//	according to widget state.
		//
		//	State will be one of:
		//		<baseClass>
		//		<baseClass> + "Disabled"	- if the widget is disabled
		//		<baseClass> + "Active"		- if the mouse is being pressed down
		//		<baseClass> + "Hover"		- if the mouse is over the widget
		//
		//	For widgets which can be in a selected state (like checkbox or radio),
		//	in addition to the above classes...
		//		<baseClass> + "Selected"
		//		<baseClass> + "SelectedDisabled"	- if the widget is disabled
		//		<baseClass> + "SelectedActive"		- if the mouse is being pressed down
		//		<baseClass> + "SelectedHover"		- if the mouse is over the widget

		// get original class specified in template
		var origClass = this._origClass || (this._origClass = this.domNode.className);

		// compute the single classname representing the state of the widget
		var state = this.baseClass || this.domNode.getAttribute("baseClass");
		if(this.selected){
			state += "Selected"
		}
		if(this.disabled){
			state += "Disabled";
		}else if(this._active){
			state += "Active";
		}else if(this._hovering){
			state += "Hover";
		}
		this.domNode.className = origClass + " " + " " + state;
		//console.log(this.id + ": disabled=" + this.disabled + ", active=" + this._active + ", hover=" + this._hovering + "; state=" + state + "--> className is " + this.domNode.className);
	},

	onChange: function(newValue){
		// summary: callback when value is changed
	},

	postCreate: function(){
		this.setDisabled(this.disabled);
		this._setStateClass();
	},

	_lastValueReported: null,
	_lastValue: null,
	setValue: function(/*anything*/ newValue, /*Boolean, optional*/ priorityChange){
		// summary: set the value of the widget.
		this._lastValue = newValue;
		dijit.util.wai.setAttr(this.focusNode || this.domNode, "waiState", "valuenow", this.forWaiValuenow());
		if((this.intermediateChanges || priorityChange) && newValue != this._lastValueReported){
			this._lastValueReported = newValue;
			this.onChange(newValue);
		}
	},

	getValue: function(){
		// summary: get the value of the widget.
		return this._lastValue;
	},

	forWaiValuenow: function(){
		// summary: returns a value, reflecting the current state of the widget,
		//		to be used for the ARIA valuenow.
		// 		This method may be overridden by subclasses that want
		// 		to use something other than this.getValue() for valuenow
		return this.getValue();
	}
});
<commit_msg>Fixes #3610.  Textarea widget can now be autosaved in InlineEditBox.  Also, ESC acts like an undo key for form widgets.<commit_after>dojo.provide("dijit.form._FormWidget");

dojo.require("dijit._Widget");
dojo.require("dijit._Templated");
dojo.require("dijit.util.sniff");
dojo.require("dijit.util.wai");

dojo.declare("dijit.form._FormWidget", [dijit._Widget, dijit._Templated],
{
	/*
	Summary:
		FormElement widgets correspond to native HTML elements such as <input> or <button> or <select>.
		Each FormElement represents a single input value, and has a (possibly hidden) <input> element,
		to which it serializes its input value, so that form submission (either normal submission or via FormBind?)
		works as expected.

		All these widgets should have these attributes just like native HTML input elements.
		You can set them during widget construction, but after that they are read only.

		They also share some common methods.
	*/

	// baseClass: String
	//		Used to add CSS classes like FormElementDisabled
	// TODO: remove this in favor of this.domNode.baseClass?
	baseClass: "",

	// value: String
	//		Corresponds to the native HTML <input> element's attribute.
	value: "",

	// name: String
	//		Name used when submitting form; same as "name" attribute or plain HTML elements
	name: "",

	// id: String
	//		Corresponds to the native HTML <input> element's attribute.
	//		Also becomes the id for the widget.
	id: "",

	// alt: String
	//		Corresponds to the native HTML <input> element's attribute.
	alt: "",

	// type: String
	//		Corresponds to the native HTML <input> element's attribute.
	type: "text",

	// tabIndex: Integer
	//		Order fields are traversed when user hits the tab key
	tabIndex: "0",

	// disabled: Boolean
	//		Should this widget respond to user input?
	//		In markup, this is specified as "disabled='disabled'", or just "disabled".
	disabled: false,

	// intermediateChanges: Boolean
	//              Fires onChange for each value change or only on demand
	intermediateChanges: false,

	setDisabled: function(/*Boolean*/ disabled){
		// summary:
		//		Set disabled state of widget.

		this.domNode.disabled = this.disabled = disabled;
		if(this.focusNode){
			this.focusNode.disabled = disabled;
		}
		dijit.util.wai.setAttr(this.focusNode || this.domNode, "waiState", "disabled", disabled);
		this._setStateClass();
	},

	_onMouse : function(/*Event*/ event){
		// summary:
		//	Sets _hovering, _active, and baseClass attributes depending on mouse state,
		//	then calls setStateClass() to set appropriate CSS class for this.domNode.
		//
		//	To get a different CSS class for hover, send onmouseover and onmouseout events to this method.
		//	To get a different CSS class while mouse button is depressed, send onmousedown to this method.

		var mouseNode = event.target;

		if(!this.disabled){
			switch(event.type){
				case "mouseover" :
					this._hovering = true;
					var baseClass, node=mouseNode;
					while( !(baseClass=node.getAttribute("baseClass")) && node != this.domNode ){
						node=node.parentNode;
					}
					this.baseClass= baseClass || "dijit"+this.declaredClass.replace(/.*\./g,"");
					break;

				case "mouseout" :
					this._hovering = false;
					this.baseClass=null;
					break;

				case "mousedown" :
					this._active = true;
					// set a global event to handle mouseup, so it fires properly
					//	even if the cursor leaves the button
					this._active = true;
					var self = this;
					// #2685: use this.connect and disconnect so destroy works properly
					var mouseUpConnector = this.connect(dojo.body(), "onmouseup", function(){
						self._active = false;
						self._setStateClass();
						self.disconnect(mouseUpConnector);
					});
					break;
			}
			this._setStateClass();
		}
	},

	focus: function(){
		if(this.focusNode && this.focusNode.focus){	// mozilla 1.7 doesn't have focus() func
			this.focusNode.focus();
		}
	},

	_setStateClass: function(/*String*/ base){
		// summary:
		//	Update the visual state of the widget by changing the css class on the domnode
		//	according to widget state.
		//
		//	State will be one of:
		//		<baseClass>
		//		<baseClass> + "Disabled"	- if the widget is disabled
		//		<baseClass> + "Active"		- if the mouse is being pressed down
		//		<baseClass> + "Hover"		- if the mouse is over the widget
		//
		//	For widgets which can be in a selected state (like checkbox or radio),
		//	in addition to the above classes...
		//		<baseClass> + "Selected"
		//		<baseClass> + "SelectedDisabled"	- if the widget is disabled
		//		<baseClass> + "SelectedActive"		- if the mouse is being pressed down
		//		<baseClass> + "SelectedHover"		- if the mouse is over the widget

		// get original class specified in template
		var origClass = this._origClass || (this._origClass = this.domNode.className);

		// compute the single classname representing the state of the widget
		var state = this.baseClass || this.domNode.getAttribute("baseClass");
		if(this.selected){
			state += "Selected"
		}
		if(this.disabled){
			state += "Disabled";
		}else if(this._active){
			state += "Active";
		}else if(this._hovering){
			state += "Hover";
		}
		this.domNode.className = origClass + " " + " " + state;
	},

	onChange: function(newValue){
		// summary: callback when value is changed
	},

	postCreate: function(){
		this.setDisabled(this.disabled);
		this._setStateClass();
		this.setValue(this.value, true);
	},

	setValue: function(/*anything*/ newValue, /*Boolean, optional*/ priorityChange){
		// summary: set the value of the widget.
		this._lastValue = newValue;
		dijit.util.wai.setAttr(this.focusNode || this.domNode, "waiState", "valuenow", this.forWaiValuenow());
		if((this.intermediateChanges || priorityChange) && newValue != this._lastValueReported){
			this._lastValueReported = newValue;
			this.onChange(newValue);
		}
	},

	getValue: function(){
		// summary: get the value of the widget.
		return this._lastValue;
	},

	undo: function(){
		// summary: restore the value to the last value passed to onChange
		this.setValue(this._lastValueReported, false);
	},

	_onKeyPress: function(e){
		if(e.keyCode == 27 && !e.shiftKey && !e.ctrlKey && !e.altKey){
			var v = this.getValue();
			if(v != this._lastValueReported && this._lastValueReported != undefined){
				this.undo();
				dojo.stopEvent(e);
			}else if(dojo.isMozilla){ // needed by FF2 to keep it from putting the value back
				this.setValue(v, false);
			}
		}
	},

	forWaiValuenow: function(){
		// summary: returns a value, reflecting the current state of the widget,
		//		to be used for the ARIA valuenow.
		// 		This method may be overridden by subclasses that want
		// 		to use something other than this.getValue() for valuenow
		return this.getValue();
	}
});
<|endoftext|>


<commit_before>dojo.provide("dijit.form._FormWidget");

dojo.require("dijit._Widget");
dojo.require("dijit._Templated");

dojo.declare("dijit.form._FormWidget", [dijit._Widget, dijit._Templated],
{
	/*
	Summary:
		FormElement widgets correspond to native HTML elements such as <input> or <button> or <select>.
		Each FormElement represents a single input value, and has a (possibly hidden) <input> element,
		to which it serializes its input value, so that form submission (either normal submission or via FormBind?)
		works as expected.

		All these widgets should have these attributes just like native HTML input elements.
		You can set them during widget construction, but after that they are read only.

		They also share some common methods.
	*/

	// baseClass: String
	//		Used to add CSS classes like FormElementDisabled
	// TODO: remove this in favor of this.domNode.baseClass?
	baseClass: "",

	// value: String
	//		Corresponds to the native HTML <input> element's attribute.
	value: "",

	// name: String
	//		Name used when submitting form; same as "name" attribute or plain HTML elements
	name: "",

	// id: String
	//		Corresponds to the native HTML <input> element's attribute.
	//		Also becomes the id for the widget.
	id: "",

	// alt: String
	//		Corresponds to the native HTML <input> element's attribute.
	alt: "",

	// type: String
	//		Corresponds to the native HTML <input> element's attribute.
	type: "text",

	// tabIndex: Integer
	//		Order fields are traversed when user hits the tab key
	tabIndex: "0",

	// disabled: Boolean
	//		Should this widget respond to user input?
	//		In markup, this is specified as "disabled='disabled'", or just "disabled".
	disabled: false,

	// intermediateChanges: Boolean
	//              Fires onChange for each value change or only on demand
	intermediateChanges: false,

	setDisabled: function(/*Boolean*/ disabled){
		// summary:
		//		Set disabled state of widget.

		this.domNode.disabled = this.disabled = disabled;
		if(this.focusNode){
			this.focusNode.disabled = disabled;
		}
		dijit.wai.setAttr(this.focusNode || this.domNode, "waiState", "disabled", disabled);
		this._setStateClass();
	},

	_onMouse : function(/*Event*/ event){
		// summary:
		//	Sets _hovering, _active, and baseClass attributes depending on mouse state,
		//	then calls setStateClass() to set appropriate CSS class for this.domNode.
		//
		//	To get a different CSS class for hover, send onmouseover and onmouseout events to this method.
		//	To get a different CSS class while mouse button is depressed, send onmousedown to this method.

		var mouseNode = event.target;

		if(!this.disabled){
			switch(event.type){
				case "mouseover" :
					this._hovering = true;
					var baseClass, node=mouseNode;
					while( node.nodeType===1 && !(baseClass=node.getAttribute("baseClass")) && node != this.domNode ){
						node=node.parentNode;
					}
					this.baseClass= baseClass || "dijit"+this.declaredClass.replace(/.*\./g,"");
					break;

				case "mouseout" :
					this._hovering = false;
					this.baseClass=null;
					break;

				case "mousedown" :
					this._active = true;
					// set a global event to handle mouseup, so it fires properly
					//	even if the cursor leaves the button
					var self = this;
					// #2685: use this.connect and disconnect so destroy works properly
					var mouseUpConnector = this.connect(dojo.body(), "onmouseup", function(){
						self._active = false;
						self._setStateClass();
						self.disconnect(mouseUpConnector);
					});
					break;
			}
			this._setStateClass();
		}
	},

	focus: function(){
		dijit.focus(this.focusNode);
	},

	_setStateClass: function(/*String*/ base){
		// summary:
		//	Update the visual state of the widget by changing the css class on the domnode
		//	according to widget state.
		//
		//	State will be one of:
		//		<baseClass>
		//		<baseClass> + "Disabled"	- if the widget is disabled
		//		<baseClass> + "Active"		- if the mouse (or space/enter key?) is being pressed down
		//		<baseClass> + "Hover"		- if the mouse is over the widget
		//		<baseClass> + "Focused"		- if the widget has focus
		//
		//	Note: if you don't want to change the way the widget looks on hover, then don't call
		//	this routine on hover.  Similarly for mousedown --> active
		//
		//	For widgets which can be in a checked state (like checkbox or radio),
		//	in addition to the above classes...
		//		<baseClass> + "Checked"
		//		<baseClass> + "CheckedDisabled"	- if the widget is disabled
		//		<baseClass> + "CheckedActive"		- if the mouse is being pressed down
		//		<baseClass> + "CheckedHover"		- if the mouse is over the widget
		//		<baseClass> + "CheckedFocused"		- if the widget has focus

		// get original class (non state related) specified in template
		var origClass = (this.styleNode||this.domNode).className;

		// compute list of classname representing the states of the widget
		var base = this.baseClass || this.domNode.getAttribute("baseClass") || "dijitFormWidget";
		origClass = origClass.replace(new RegExp("\\b"+base+"(Checked)?(Selected)?(Disabled|Active|Focused|Hover)?\\b\\s*", "g"), "");
		var classes = [ base ];

		function multiply(modifier){
			classes=classes.concat(dojo.map(classes, function(c){ return c+modifier; }));
		}

		if(this.checked){
			multiply("Checked");
		}
		if(this.selected){
			multiply("Selected");
		}

		// Only one of these three can be applied.
		// Active trumps Focused, Focused trumps Hover, and Disabled trumps all.
		if(this.disabled){
			multiply("Disabled");
		}else if(this._active){
			multiply("Active");
		}else if(this._focused){
			multiply("Focused");
		}else if(this._hovering){
			multiply("Hover");
		}

		(this.styleNode || this.domNode).className = origClass + " " + classes.join(" ");
	},

	onChange: function(newValue){
		// summary: callback when value is changed
	},

	postCreate: function(){
		this.setValue(this.value, true);
		this.setDisabled(this.disabled);
		this._setStateClass();
	},

	setValue: function(/*anything*/ newValue, /*Boolean, optional*/ priorityChange){
		// summary: set the value of the widget.
		this._lastValue = newValue;
		dijit.wai.setAttr(this.focusNode || this.domNode, "waiState", "valuenow", this.forWaiValuenow());
		if((this.intermediateChanges || priorityChange) && newValue != this._lastValueReported){
			this._lastValueReported = newValue;
			this.onChange(newValue);
		}
	},

	getValue: function(){
		// summary: get the value of the widget.
		return this._lastValue;
	},

	undo: function(){
		// summary: restore the value to the last value passed to onChange
		this.setValue(this._lastValueReported, false);
	},

	_onKeyPress: function(e){
		if(e.keyCode == dojo.keys.ESCAPE && !e.shiftKey && !e.ctrlKey && !e.altKey){
			var v = this.getValue();
			var lv = this._lastValueReported;
			// Equality comparison of objects such as dates are done by reference so
			// two distinct objects are != even if they have the same data. So use
			// toStrings in case the values are objects.
			if(lv != undefined && v.toString() != lv.toString()){
				this.undo();
				dojo.stopEvent(e);
				return false;
			}
		}
		return true;
	},

	forWaiValuenow: function(){
		// summary: returns a value, reflecting the current state of the widget,
		//		to be used for the ARIA valuenow.
		// 		This method may be overridden by subclasses that want
		// 		to use something other than this.getValue() for valuenow
		return this.getValue();
	}
});
<commit_msg>fixes #4200: disabled form widget may have wrong hover status<commit_after>dojo.provide("dijit.form._FormWidget");

dojo.require("dijit._Widget");
dojo.require("dijit._Templated");

dojo.declare("dijit.form._FormWidget", [dijit._Widget, dijit._Templated],
{
	/*
	Summary:
		FormElement widgets correspond to native HTML elements such as <input> or <button> or <select>.
		Each FormElement represents a single input value, and has a (possibly hidden) <input> element,
		to which it serializes its input value, so that form submission (either normal submission or via FormBind?)
		works as expected.

		All these widgets should have these attributes just like native HTML input elements.
		You can set them during widget construction, but after that they are read only.

		They also share some common methods.
	*/

	// baseClass: String
	//		Used to add CSS classes like FormElementDisabled
	// TODO: remove this in favor of this.domNode.baseClass?
	baseClass: "",

	// value: String
	//		Corresponds to the native HTML <input> element's attribute.
	value: "",

	// name: String
	//		Name used when submitting form; same as "name" attribute or plain HTML elements
	name: "",

	// id: String
	//		Corresponds to the native HTML <input> element's attribute.
	//		Also becomes the id for the widget.
	id: "",

	// alt: String
	//		Corresponds to the native HTML <input> element's attribute.
	alt: "",

	// type: String
	//		Corresponds to the native HTML <input> element's attribute.
	type: "text",

	// tabIndex: Integer
	//		Order fields are traversed when user hits the tab key
	tabIndex: "0",

	// disabled: Boolean
	//		Should this widget respond to user input?
	//		In markup, this is specified as "disabled='disabled'", or just "disabled".
	disabled: false,

	// intermediateChanges: Boolean
	//              Fires onChange for each value change or only on demand
	intermediateChanges: false,

	setDisabled: function(/*Boolean*/ disabled){
		// summary:
		//		Set disabled state of widget.

		this.domNode.disabled = this.disabled = disabled;
		if(this.focusNode){
			this.focusNode.disabled = disabled;
		}
		if(disabled){
			//reset those, because after the domNode is disabled, we can no longer receive
			//mouse related events, see #4200
			this._hovering = false;
			this._active = false;
		}
		dijit.wai.setAttr(this.focusNode || this.domNode, "waiState", "disabled", disabled);
		this._setStateClass();
	},

	_onMouse : function(/*Event*/ event){
		// summary:
		//	Sets _hovering, _active, and baseClass attributes depending on mouse state,
		//	then calls setStateClass() to set appropriate CSS class for this.domNode.
		//
		//	To get a different CSS class for hover, send onmouseover and onmouseout events to this method.
		//	To get a different CSS class while mouse button is depressed, send onmousedown to this method.

		var mouseNode = event.target;

		if(!this.disabled){
			switch(event.type){
				case "mouseover" :
					this._hovering = true;
					var baseClass, node=mouseNode;
					while( node.nodeType===1 && !(baseClass=node.getAttribute("baseClass")) && node != this.domNode ){
						node=node.parentNode;
					}
					this.baseClass= baseClass || "dijit"+this.declaredClass.replace(/.*\./g,"");
					break;

				case "mouseout" :
					this._hovering = false;
					this.baseClass=null;
					break;

				case "mousedown" :
					this._active = true;
					// set a global event to handle mouseup, so it fires properly
					//	even if the cursor leaves the button
					var self = this;
					// #2685: use this.connect and disconnect so destroy works properly
					var mouseUpConnector = this.connect(dojo.body(), "onmouseup", function(){
						self._active = false;
						self._setStateClass();
						self.disconnect(mouseUpConnector);
					});
					break;
			}
			this._setStateClass();
		}
	},

	focus: function(){
		dijit.focus(this.focusNode);
	},

	_setStateClass: function(/*String*/ base){
		// summary:
		//	Update the visual state of the widget by changing the css class on the domnode
		//	according to widget state.
		//
		//	State will be one of:
		//		<baseClass>
		//		<baseClass> + "Disabled"	- if the widget is disabled
		//		<baseClass> + "Active"		- if the mouse (or space/enter key?) is being pressed down
		//		<baseClass> + "Hover"		- if the mouse is over the widget
		//		<baseClass> + "Focused"		- if the widget has focus
		//
		//	Note: if you don't want to change the way the widget looks on hover, then don't call
		//	this routine on hover.  Similarly for mousedown --> active
		//
		//	For widgets which can be in a checked state (like checkbox or radio),
		//	in addition to the above classes...
		//		<baseClass> + "Checked"
		//		<baseClass> + "CheckedDisabled"	- if the widget is disabled
		//		<baseClass> + "CheckedActive"		- if the mouse is being pressed down
		//		<baseClass> + "CheckedHover"		- if the mouse is over the widget
		//		<baseClass> + "CheckedFocused"		- if the widget has focus

		// get original class (non state related) specified in template
		var origClass = (this.styleNode||this.domNode).className;

		// compute list of classname representing the states of the widget
		var base = this.baseClass || this.domNode.getAttribute("baseClass") || "dijitFormWidget";
		origClass = origClass.replace(new RegExp("\\b"+base+"(Checked)?(Selected)?(Disabled|Active|Focused|Hover)?\\b\\s*", "g"), "");
		var classes = [ base ];

		function multiply(modifier){
			classes=classes.concat(dojo.map(classes, function(c){ return c+modifier; }));
		}

		if(this.checked){
			multiply("Checked");
		}
		if(this.selected){
			multiply("Selected");
		}

		// Only one of these four can be applied.
		// Active trumps Focused, Focused trumps Hover, and Disabled trumps all.
		if(this.disabled){
			multiply("Disabled");
		}else if(this._active){
			multiply("Active");
		}else if(this._focused){
			multiply("Focused");
		}else if(this._hovering){
			multiply("Hover");
		}

		(this.styleNode || this.domNode).className = origClass + " " + classes.join(" ");
	},

	onChange: function(newValue){
		// summary: callback when value is changed
	},

	postCreate: function(){
		this.setValue(this.value, true);
		this.setDisabled(this.disabled);
		this._setStateClass();
	},

	setValue: function(/*anything*/ newValue, /*Boolean, optional*/ priorityChange){
		// summary: set the value of the widget.
		this._lastValue = newValue;
		dijit.wai.setAttr(this.focusNode || this.domNode, "waiState", "valuenow", this.forWaiValuenow());
		if((this.intermediateChanges || priorityChange) && newValue != this._lastValueReported){
			this._lastValueReported = newValue;
			this.onChange(newValue);
		}
	},

	getValue: function(){
		// summary: get the value of the widget.
		return this._lastValue;
	},

	undo: function(){
		// summary: restore the value to the last value passed to onChange
		this.setValue(this._lastValueReported, false);
	},

	_onKeyPress: function(e){
		if(e.keyCode == dojo.keys.ESCAPE && !e.shiftKey && !e.ctrlKey && !e.altKey){
			var v = this.getValue();
			var lv = this._lastValueReported;
			// Equality comparison of objects such as dates are done by reference so
			// two distinct objects are != even if they have the same data. So use
			// toStrings in case the values are objects.
			if(lv != undefined && v.toString() != lv.toString()){
				this.undo();
				dojo.stopEvent(e);
				return false;
			}
		}
		return true;
	},

	forWaiValuenow: function(){
		// summary: returns a value, reflecting the current state of the widget,
		//		to be used for the ARIA valuenow.
		// 		This method may be overridden by subclasses that want
		// 		to use something other than this.getValue() for valuenow
		return this.getValue();
	}
});
<|endoftext|>


<commit_before>angular.module('app').controller('form_new_round_p', function ($scope, apiphp, $http) {
  $scope.teams = ['atletico-go',
                  'atletico-mg',
                  'atletico-pr',
                  'avai',
                  'bahia',
                  'botafogo',
                  'chapecoense',
                  'corinthians ',
                  'coritiba',
                  'cruzeiro',
                  'flamengo',
                  'fluminense ',
                  'gremio',
                  'palmeiras',
                  'ponte-preta',
                  'santos',
                  'sao-paulo',
                  'sport',
                  'vasco',
                  'vitoria'];

  $scope.home = [];
  $scope.away = [];
  $scope.matches = [];
  for(var i=0; i < $scope.teams.length / 2;i++) {
    $scope.matches.push(i);
    //$scope.home.push($scope.teams[0]);
    //$scope.away.push($scope.teams[0]);
  }
  $scope.submitForm = function(){
    console.log("submitForm");
    console.log($scope.home);
    data = [];

    for(var i=0;i<$scope.matches.length;i++) {
      data.push({"name": $scope.home[i] + ' x ' + $scope.away[i]});
    }
    console.log(data);
    apiphp.post({table: 'br_g'}, data, function(result) {
      console.log(result);
      alert("form data saved");
    });
  };
});

// add this partial and controller to the menu service
angular.module('app').config(function($menuProvider) {
  $menuProvider.add({name: 'Inserir nova rodada', href: 'form_new_round_p'});
});
<commit_msg>Delete form_new_round_p.js<commit_after><|endoftext|>


<commit_before>//readingCenterMyBookshelfCtrl.js

ctrls.controller("readingCenterMyBookshelfController", ['$rootScope', '$scope','BookshelfView',
    'Bookshelf','BookInShelf','DropBookFromShelf', 'NoteTake', 'BookDetail', 'Dropzone', 'config', function($rootScope, $scope,BookshelfView,Bookshelf,BookInShelf,DropBookFromShelf,NoteTake, BookDetail, Dropzone, config) {
	$scope.name='阅读中心->我的书架';

    var size = 9;
    var stateTexts = { more : "加载更多",loading: "更多加载中...",nomore: "没有了"};
    $scope.unreadLoading = stateTexts.loading;
    $scope.readLoading = stateTexts.loading;
    // Get the user id form rootScope
    $scope.arguments = {id: $rootScope.id};

    // $scope.BookshelfView = new BookshelfView();
    // $scope.BookshelfView.ShowMoreBooksInShelf($scope.arguments);

    $scope.statuses = [{
        id: 0,
        name:"全部",
        callback: function(){$scope.selectBookAttributes()}
    }, {
        id: 1,
        name: "必读",
        callback: function(){$scope.selectBookAttributes()}
    }, {
        id: 2,
        name: "选读",
        callback: function(){$scope.selectBookAttributes()}
    }];
    $scope.selected_status = 0;

    // //Get books with number of size.
    // var bookInShelf = BookInShelf.get({id:$rootScope.id,page:0,size:size},function(){
    //     console.log(bookInShelf);
    //     //init $scope.readBooks  & $scope.unreadBooks
    //     spileBooksByReadState(bookInShelf.content,$scope.readBooks,$scope.unreadBooks);
    //
    // });
    var unreadBooksALL;
    var readBooksALL;

    $scope.radio = 0;

    $scope.selectBookAttributes = function(){
          unreadBooksALL = new Array();
          readBooksALL = new Array();
        // console.log($scope.selected_status);
        // $scope.bookInShelf = BookInShelf.get({id:$rootScope.id,page:0,size:size},function(){
        var bookshelf = Bookshelf.get({id:$rootScope.id},function(){
          // console.log(bookshelf.booksInShelf);
          $scope.shelf = bookshelf;
          var content = bookshelf.booksInShelf;
          for(var i = 0; i < content.length; i++){
              //console.log(content[i]);
              if(content[i].readState){
                  // if($scope.selected_status=== 1&& !content[i].bookAttribute)
                  //     continue;
                  // if($scope.selected_status=== 2&& content[i].bookAttribute)
                  //     continue;
                  if($scope.radio=== 1&& !content[i].bookAttribute)
                      continue;
                  if($scope.radio=== 2&& content[i].bookAttribute)
                      continue;
                   readBooksALL.push(content[i]);
              }
              else{
                  // if($scope.selected_status=== 1&& !content[i].bookAttribute)
                  //     continue;
                  // if($scope.selected_status=== 2&& content[i].bookAttribute)
                  //     continue;
                  if($scope.button.radio=== 1&& !content[i].bookAttribute)
                      continue;
                  if($scope.button.radio=== 2&& content[i].bookAttribute)
                      continue;
                   unreadBooksALL.push(content[i]);
              }
          }
          $scope.unreadLoading = setLoadingState(unreadBooksALL,size);
          $scope.readLoading = setLoadingState(readBooksALL,size);

          $scope.unreadBooks = new Array();
          $scope.readBooks = new Array();

          initBooks($scope.unreadBooks,unreadBooksALL,size);
          initBooks($scope.readBooks,readBooksALL,size);
        });
    };

    $scope.unreadBooksLoadingMore = function(){
      if($scope.unreadLoading === stateTexts.nomore)
        return;
      if(loadingMore($scope.unreadBooks,unreadBooksALL,size))
        $scope.unreadLoading = stateTexts.more;
      else{
        $scope.unreadLoading = stateTexts.nomore;
      }
    }

    $scope.readBooksLoadingMore = function(){
      if($scope.readLoading === stateTexts.nomore)
        return;
      if(loadingMore($scope.readBooks,readBooksALL,size))
        $scope.readLoading = stateTexts.more;
      else{
        $scope.readLoading = stateTexts.nomore;
      }
    }

    var initBooks = function(books,booksALL,size){
      if(typeof(booksALL)=== 'undefined')
        return 0;
      for(var i=0; i<booksALL.length&&i<size;i++)
        books.push(booksALL[i]);
      // console.log(books);
      return books.length;
   };

    var setLoadingState = function(books,size){
      if(books.length<=size)
        return stateTexts.nomore;
      else if(books.length>size)
        return stateTexts.more;
    };

/*
  For loding more
  return false means nomore, then set loadingState to nomore.
  return true means more. And you can click again,
  ONE click loads nine books at most
*/
    var loadingMore = function(bookArray,bookALL,pageSize){
      var allNum = bookALL.length;
        for(var i=0;i<pageSize;i++){
          if(bookArray.length<allNum)
            bookArray.push(bookALL[bookArray.length]);
          else
            return false;
          }
      return true;
  };
//End loadingMore

//DELETE A BOOK IN SHELF
    $scope.dropBookFromShelf = function(book){
        // console.log(book.id);
        $scope.dropBook = DropBookFromShelf.remove({id:book.id},function(){
          if(typeof($scope.dropBook) === "undefined"){
              alert("删除失败");
          }
          else{
              alert("移除成功");
              $scope.selectBookAttributes();
          }
        });

    };

    $rootScope.exam = {};
    $scope.CertificationTest = function(data){
        $rootScope.exam.id = 0;
        $rootScope.exam.returnURL = "/student/protype/index.html#/readingCenter/myBookshelf";
        $rootScope.exam.bookId = data.bookId;
        $rootScope.exam.bookName = data.bookName;
        $rootScope.exam.typeName = "我的书架 > 认证训练";
    }
    $scope.SubjectiveTest = function(data){
        $rootScope.exam.id = 2;
        $rootScope.exam.returnURL = "/student/protype/index.html#/readingCenter/myBookshelf";
        $rootScope.exam.bookId = data.bookId;
        $rootScope.exam.bookName = data.bookName;
        $rootScope.exam.typeName = "我的书架 > 思维训练";
    }
    $scope.WordTest = function(data){
        $rootScope.exam.id = 1;
        $rootScope.exam.returnURL = "/student/protype/index.html#/readingCenter/myBookshelf";
        $rootScope.exam.bookId = data.bookId;
        $rootScope.exam.bookName = data.bookName;
        $rootScope.exam.typeName = "我的书架 > 词汇训练";
    }

    // Image uploader
    $scope.dropzone = Dropzone(config.NOTEPIC, function(url){
        $scope.noteTake.image = url;
    });

    $scope.takeNoteByBookinshelf = function(bookinshelf){
        var bookDetail = BookDetail.get({ id: bookinshelf.bookId }, function(){
            // console.log(bookDetail);

            // Initlizate the note entity
            $scope.noteTake = new NoteTake(bookDetail);

            // Get the image server
            $scope.imageServer = config.IMAGESERVER;
        });
    }
    $scope.imageServer = config.IMAGESERVER;
}]);

var spileBooksByReadState = function(content,readBooks,unreadBooks){
  if(typeof(content)=== 'undefined')
    return;
  for(var i = 0; i < content.length; i++){
      //console.log(content[i]);
      if(content[i].readState)
          readBooks.push(content[i]);
      else
          unreadBooks.push(content[i]);
  }
}

//Must or select of books
var findBooksByBookAttibutes = function(content,books){
  if(typeof(content)=== 'undefined')
    return false;
  if(content.length==0)
      return false;
  for(var i = 0; i <  content.length; i++){
    if($scope.selected_status=== 1&& !content[i].bookAttribute)
        continue;
    if($scope.selected_status=== 2&& content[i].bookAttribute)
        continue;
      books.push(content[i]);
  }
  return true;
};

var spileBooks = function(content){
  $scope.readBooks = new Array();
  $scope.unreadBooks = new Array();
  for(var i = 0; i < content.length; i++){
      //console.log(content[i]);
      if(content[i].readState){
          if($scope.selected_status=== 1&& !content[i].bookAttribute)
              continue;
          if($scope.selected_status=== 2&& content[i].bookAttribute)
              continue;
          $scope.readBooks.push(content[i]);
      }
      else{
          if($scope.selected_status=== 1&& !content[i].bookAttribute)
              continue;
          if($scope.selected_status=== 2&& content[i].bookAttribute)
              continue;
          $scope.unreadBooks.push(content[i]);
      }
  }
};
var findUnreadBooks = function(content,unreadBooks){
  for(var i = 0; i < content.length; i++){
    if(!content[i].readState){
        if($scope.selected_status=== 1&& !content[i].bookAttribute)
            continue;
        if($scope.selected_status=== 2&& content[i].bookAttribute)
            continue;
        unreadBooks.push(content[i]);
    }
  }
};

ctrls.filter('formatBookAttribute', function(){
  return function(input){
    // console.log(input);
    if (input)
      return "必读";
    else
      return "选读";
  }
});
//var booksCtrl = angular.module('nourControllers',['nourConfig', 'ngResource','bookInShelfService']);
<commit_msg>radio<commit_after>//readingCenterMyBookshelfCtrl.js

ctrls.controller("readingCenterMyBookshelfController", ['$rootScope', '$scope','BookshelfView',
    'Bookshelf','BookInShelf','DropBookFromShelf', 'NoteTake', 'BookDetail', 'Dropzone', 'config', function($rootScope, $scope,BookshelfView,Bookshelf,BookInShelf,DropBookFromShelf,NoteTake, BookDetail, Dropzone, config) {
	$scope.name='阅读中心->我的书架';

    var size = 9;
    var stateTexts = { more : "加载更多",loading: "更多加载中...",nomore: "没有了"};
    $scope.unreadLoading = stateTexts.loading;
    $scope.readLoading = stateTexts.loading;
    // Get the user id form rootScope
    $scope.arguments = {id: $rootScope.id};

    // $scope.BookshelfView = new BookshelfView();
    // $scope.BookshelfView.ShowMoreBooksInShelf($scope.arguments);

    $scope.statuses = [{
        id: 0,
        name:"全部",
        callback: function(){$scope.selectBookAttributes()}
    }, {
        id: 1,
        name: "必读",
        callback: function(){$scope.selectBookAttributes()}
    }, {
        id: 2,
        name: "选读",
        callback: function(){$scope.selectBookAttributes()}
    }];
    $scope.selected_status = 0;

    // //Get books with number of size.
    // var bookInShelf = BookInShelf.get({id:$rootScope.id,page:0,size:size},function(){
    //     console.log(bookInShelf);
    //     //init $scope.readBooks  & $scope.unreadBooks
    //     spileBooksByReadState(bookInShelf.content,$scope.readBooks,$scope.unreadBooks);
    //
    // });
    var unreadBooksALL;
    var readBooksALL;

    $scope.radio = 0;

    $scope.selectBookAttributes = function(){
          unreadBooksALL = new Array();
          readBooksALL = new Array();
        // console.log($scope.selected_status);
        // $scope.bookInShelf = BookInShelf.get({id:$rootScope.id,page:0,size:size},function(){
        var bookshelf = Bookshelf.get({id:$rootScope.id},function(){
          // console.log(bookshelf.booksInShelf);
          $scope.shelf = bookshelf;
          var content = bookshelf.booksInShelf;
          for(var i = 0; i < content.length; i++){
              //console.log(content[i]);
              if(content[i].readState){
                  // if($scope.selected_status=== 1&& !content[i].bookAttribute)
                  //     continue;
                  // if($scope.selected_status=== 2&& content[i].bookAttribute)
                  //     continue;
                  if($scope.radio=== 1&& !content[i].bookAttribute)
                      continue;
                  if($scope.radio=== 2&& content[i].bookAttribute)
                      continue;
                   readBooksALL.push(content[i]);
              }
              else{
                  // if($scope.selected_status=== 1&& !content[i].bookAttribute)
                  //     continue;
                  // if($scope.selected_status=== 2&& content[i].bookAttribute)
                  //     continue;
                  if($scope.radio=== 1&& !content[i].bookAttribute)
                      continue;
                  if($scope.radio=== 2&& content[i].bookAttribute)
                      continue;
                   unreadBooksALL.push(content[i]);
              }
          }
          $scope.unreadLoading = setLoadingState(unreadBooksALL,size);
          $scope.readLoading = setLoadingState(readBooksALL,size);

          $scope.unreadBooks = new Array();
          $scope.readBooks = new Array();

          initBooks($scope.unreadBooks,unreadBooksALL,size);
          initBooks($scope.readBooks,readBooksALL,size);
        });
    };

    $scope.unreadBooksLoadingMore = function(){
      if($scope.unreadLoading === stateTexts.nomore)
        return;
      if(loadingMore($scope.unreadBooks,unreadBooksALL,size))
        $scope.unreadLoading = stateTexts.more;
      else{
        $scope.unreadLoading = stateTexts.nomore;
      }
    }

    $scope.readBooksLoadingMore = function(){
      if($scope.readLoading === stateTexts.nomore)
        return;
      if(loadingMore($scope.readBooks,readBooksALL,size))
        $scope.readLoading = stateTexts.more;
      else{
        $scope.readLoading = stateTexts.nomore;
      }
    }

    var initBooks = function(books,booksALL,size){
      if(typeof(booksALL)=== 'undefined')
        return 0;
      for(var i=0; i<booksALL.length&&i<size;i++)
        books.push(booksALL[i]);
      // console.log(books);
      return books.length;
   };

    var setLoadingState = function(books,size){
      if(books.length<=size)
        return stateTexts.nomore;
      else if(books.length>size)
        return stateTexts.more;
    };

/*
  For loding more
  return false means nomore, then set loadingState to nomore.
  return true means more. And you can click again,
  ONE click loads nine books at most
*/
    var loadingMore = function(bookArray,bookALL,pageSize){
      var allNum = bookALL.length;
        for(var i=0;i<pageSize;i++){
          if(bookArray.length<allNum)
            bookArray.push(bookALL[bookArray.length]);
          else
            return false;
          }
      return true;
  };
//End loadingMore

//DELETE A BOOK IN SHELF
    $scope.dropBookFromShelf = function(book){
        // console.log(book.id);
        $scope.dropBook = DropBookFromShelf.remove({id:book.id},function(){
          if(typeof($scope.dropBook) === "undefined"){
              alert("删除失败");
          }
          else{
              alert("移除成功");
              $scope.selectBookAttributes();
          }
        });

    };

    $rootScope.exam = {};
    $scope.CertificationTest = function(data){
        $rootScope.exam.id = 0;
        $rootScope.exam.returnURL = "/student/protype/index.html#/readingCenter/myBookshelf";
        $rootScope.exam.bookId = data.bookId;
        $rootScope.exam.bookName = data.bookName;
        $rootScope.exam.typeName = "我的书架 > 认证训练";
    }
    $scope.SubjectiveTest = function(data){
        $rootScope.exam.id = 2;
        $rootScope.exam.returnURL = "/student/protype/index.html#/readingCenter/myBookshelf";
        $rootScope.exam.bookId = data.bookId;
        $rootScope.exam.bookName = data.bookName;
        $rootScope.exam.typeName = "我的书架 > 思维训练";
    }
    $scope.WordTest = function(data){
        $rootScope.exam.id = 1;
        $rootScope.exam.returnURL = "/student/protype/index.html#/readingCenter/myBookshelf";
        $rootScope.exam.bookId = data.bookId;
        $rootScope.exam.bookName = data.bookName;
        $rootScope.exam.typeName = "我的书架 > 词汇训练";
    }

    // Image uploader
    $scope.dropzone = Dropzone(config.NOTEPIC, function(url){
        $scope.noteTake.image = url;
    });

    $scope.takeNoteByBookinshelf = function(bookinshelf){
        var bookDetail = BookDetail.get({ id: bookinshelf.bookId }, function(){
            // console.log(bookDetail);

            // Initlizate the note entity
            $scope.noteTake = new NoteTake(bookDetail);

            // Get the image server
            $scope.imageServer = config.IMAGESERVER;
        });
    }
    $scope.imageServer = config.IMAGESERVER;
}]);

var spileBooksByReadState = function(content,readBooks,unreadBooks){
  if(typeof(content)=== 'undefined')
    return;
  for(var i = 0; i < content.length; i++){
      //console.log(content[i]);
      if(content[i].readState)
          readBooks.push(content[i]);
      else
          unreadBooks.push(content[i]);
  }
}

//Must or select of books
var findBooksByBookAttibutes = function(content,books){
  if(typeof(content)=== 'undefined')
    return false;
  if(content.length==0)
      return false;
  for(var i = 0; i <  content.length; i++){
    if($scope.selected_status=== 1&& !content[i].bookAttribute)
        continue;
    if($scope.selected_status=== 2&& content[i].bookAttribute)
        continue;
      books.push(content[i]);
  }
  return true;
};

var spileBooks = function(content){
  $scope.readBooks = new Array();
  $scope.unreadBooks = new Array();
  for(var i = 0; i < content.length; i++){
      //console.log(content[i]);
      if(content[i].readState){
          if($scope.selected_status=== 1&& !content[i].bookAttribute)
              continue;
          if($scope.selected_status=== 2&& content[i].bookAttribute)
              continue;
          $scope.readBooks.push(content[i]);
      }
      else{
          if($scope.selected_status=== 1&& !content[i].bookAttribute)
              continue;
          if($scope.selected_status=== 2&& content[i].bookAttribute)
              continue;
          $scope.unreadBooks.push(content[i]);
      }
  }
};
var findUnreadBooks = function(content,unreadBooks){
  for(var i = 0; i < content.length; i++){
    if(!content[i].readState){
        if($scope.selected_status=== 1&& !content[i].bookAttribute)
            continue;
        if($scope.selected_status=== 2&& content[i].bookAttribute)
            continue;
        unreadBooks.push(content[i]);
    }
  }
};

ctrls.filter('formatBookAttribute', function(){
  return function(input){
    // console.log(input);
    if (input)
      return "必读";
    else
      return "选读";
  }
});
//var booksCtrl = angular.module('nourControllers',['nourConfig', 'ngResource','bookInShelfService']);
<|endoftext|>


<commit_before>import Ember from 'ember';
import Resolver from 'ember/resolver';
import loadInitializers from 'ember/load-initializers';
import config from './config/environment';

Ember.MODEL_FACTORY_INJECTIONS = false;

var App = Ember.Application.extend({
  modulePrefix: config.modulePrefix,
  podModulePrefix: config.podModulePrefix,
  Resolver: Resolver
});

loadInitializers(App, config.modulePrefix);

export default App;
<commit_msg>Add comment for polymorphic fix<commit_after>import Ember from 'ember';
import Resolver from 'ember/resolver';
import loadInitializers from 'ember/load-initializers';
import config from './config/environment';

// Set to false to fix polymorphic relationships
Ember.MODEL_FACTORY_INJECTIONS = false;

var App = Ember.Application.extend({
  modulePrefix: config.modulePrefix,
  podModulePrefix: config.podModulePrefix,
  Resolver: Resolver
});

loadInitializers(App, config.modulePrefix);

export default App;
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import GoogleMap from 'google-map-react'
import { observable } from 'mobx';
import { observer } from 'mobx-react'
import './App.css'
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap/dist/css/bootstrap-theme.css'
import 'font-awesome/css/font-awesome.min.css'
import Container from './Container'
import Controller from './Controller'
import Center from './Center'
import ContainerDetail from './ContainerDetail'
import { Modal } from 'react-bootstrap';

export default observer(class App extends Component {

  static defaultProps = {
    defaultCenter: {lat: 50.1197589, lng: 14.4673313},
    defaultZoom: 13,
    apiKey: process.env.REACT_APP_GOOGLE_MAPS_API_KEY
  }

  model = observable({
    containers: [],
    center: null,
    selectedContainer: null
  });

  handleSearch = (data) => {
    this.model.containers = data
  }

  handleLocate = (lat, lng) => {
    this.model.center = {lat, lng}
  }

  handleContainerClick = (id, name) => {
    this.model.selectedContainer = {id, name}
  }

  handleCloseDetail = () => {
    this.model.selectedContainer = null;
  }

  renderDetail(id, name) {
    return (<Modal show={true} onHide={this.handleCloseDetail}>
        <Modal.Header closeButton>
          <Modal.Title>{name}</Modal.Title>
        </Modal.Header>

        <Modal.Body>
          <ContainerDetail id={id} name={name} />
        </Modal.Body>
    </Modal>);
  }

  render() {
    const { defaultCenter, defaultZoom, apiKey } = this.props;
    const { center, containers, selectedContainer } = this.model;
    const bootstrapURLKeys = {
      key: apiKey,
    };

    return (

        <Controller onSearch={this.handleSearch} onLocate={this.handleLocate} />

            <GoogleMap
              bootstrapURLKeys={bootstrapURLKeys}
              defaultCenter={defaultCenter}
              defaultZoom={defaultZoom}
              hoverDistance={24}
              center={center}>

              {center ?  : null}
              {containers.map((container) => {
                return (<Container
                  {...container}
                  {...container.coordinates}
                  key={container.id}
                  onClick={this.handleContainerClick} />)
              })}
              {selectedContainer ? this.renderDetail(selectedContainer.id, selectedContainer.name) : null}
            </GoogleMap>

    );
  }
})
<commit_msg>close button in containers modal window<commit_after>import React, { Component } from 'react'
import GoogleMap from 'google-map-react'
import { observable } from 'mobx';
import { observer } from 'mobx-react'
import './App.css'
import 'bootstrap/dist/css/bootstrap.min.css'
import 'font-awesome/css/font-awesome.min.css'
import Container from './Container'
import Controller from './Controller'
import Center from './Center'
import ContainerDetail from './ContainerDetail'
import { Modal, Button } from 'react-bootstrap';

export default observer(class App extends Component {

  static defaultProps = {
    defaultCenter: {lat: 50.1197589, lng: 14.4673313},
    defaultZoom: 13,
    apiKey: process.env.REACT_APP_GOOGLE_MAPS_API_KEY
  }

  model = observable({
    containers: [],
    center: null,
    selectedContainer: null
  });

  handleSearch = (data) => {
    this.model.containers = data
  }

  handleLocate = (lat, lng) => {
    this.model.center = {lat, lng}
  }

  handleContainerClick = (id, name) => {
    this.model.selectedContainer = {id, name}
  }

  handleCloseDetail = () => {
    this.model.selectedContainer = null;
  }

  renderDetail(id, name) {
    return (<Modal show={true} onHide={this.handleCloseDetail}>
        <Modal.Header closeButton>
          <Modal.Title>{name}</Modal.Title>
        </Modal.Header>

        <Modal.Body>
          <ContainerDetail id={id} name={name} />
        </Modal.Body>
        <Modal.Footer>
          <Button className="btn btn-default" onClick={this.handleCloseDetail}>Zavřít</Button>
        </Modal.Footer>
    </Modal>);
  }

  render() {
    const { defaultCenter, defaultZoom, apiKey } = this.props;
    const { center, containers, selectedContainer } = this.model;
    const bootstrapURLKeys = {
      key: apiKey,
    };

    return (

        <Controller onSearch={this.handleSearch} onLocate={this.handleLocate} />

            <GoogleMap
              bootstrapURLKeys={bootstrapURLKeys}
              defaultCenter={defaultCenter}
              defaultZoom={defaultZoom}
              hoverDistance={24}
              center={center}>

              {center && }
              {containers.map((container) => {
                return (<Container
                  {...container}
                  {...container.coordinates}
                  key={container.id}
                  onClick={this.handleContainerClick} />)
              })}
              {selectedContainer && this.renderDetail(selectedContainer.id, selectedContainer.name)}
            </GoogleMap>

    );
  }
})
<|endoftext|>