<commit_before>module.exports = function(grunt) {
    grunt.loadNpmTasks('grunt-contrib-symlink');
    grunt.loadNpmTasks('grunt-contrib-less');
    grunt.loadNpmTasks('grunt-contrib-cssmin');
    grunt.loadNpmTasks('grunt-contrib-coffee');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-contrib-commands');

    var filesLess = {},
        filesCoffee = {};

    // Configuration
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        symlink: {
            // BOWER COMPONENT
            fontawesome_font_otf: {
                src: 'bower_components/font-awesome/fonts/FontAwesome.otf',
                dest: 'web/fonts/FontAwesome.otf'
            },
            fontawesome_font_eot: {
                src: 'bower_components/font-awesome/fonts/fontawesome-webfont.eot',
                dest: 'web/fonts/fontawesome-webfont.eot'
            },
            fontawesome_font_svg: {
                src: 'bower_components/font-awesome/fonts/fontawesome-webfont.svg',
                dest: 'web/fonts/fontawesome-webfont.svg'
            },
            fontawesome_font_ttf: {
                src: 'bower_components/font-awesome/fonts/fontawesome-webfont.ttf',
                dest: 'web/fonts/fontawesome-webfont.ttf'
            },
            fontawesome_font_woff: {
                src: 'bower_components/font-awesome/fonts/fontawesome-webfont.woff',
                dest: 'web/fonts/fontawesome-webfont.woff'
            },
            bootstrap_font_eot: {
                src: 'bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.eot',
                dest: 'web/fonts/glyphicons-halflings-regular.eot'
            },
            bootstrap_font_svg: {
                src: 'bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.svg',
                dest: 'web/fonts/glyphicons-halflings-regular.svg'
            },
            bootstrap_font_ttf: {
                src: 'bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.ttf',
                dest: 'web/fonts/glyphicons-halflings-regular.ttf'
            },
            bootstrap_font_woff: {
                src: 'bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.woff',
                dest: 'web/fonts/glyphicons-halflings-regular.woff'
            },
            datatable_img_sort_asc: {
                src: 'bower_components/datatables/media/images/sort_asc.png',
                dest: 'web/images/sort_asc.png'
            },
            datatable_img_sort_both: {
                src: 'bower_components/datatables/media/images/sort_both.png',
                dest: 'web/images/sort_both.png'
            },
            datatable_img_sort_desc: {
                src: 'bower_components/datatables/media/images/sort_desc.png',
                dest: 'web/images/sort_desc.png'
            },
            pace_js: {
                src: 'bower_components/pace/pace.min.js',
                dest: 'web/js/pace.min.js'
            },
            jcrop_gif: {
                src: 'bower_components/jcrop/css/Jcrop.gif',
                dest: 'web/img/jcrop/Jcrop.gif'
            },
            // SMARTADMIN ASSETS
            smartadmin_bg: {
                src: 'web/bundles/phporchestrabackoffice/smartadmin/img/mybg.png',
                dest: 'web/img/mybg.png'
            },
            smartadmin_flags: {
                src: 'web/bundles/phporchestrabackoffice/smartadmin/img/flags/flags.png',
                dest: 'web/img/flags/flags.png'
            },
            select2_gif: {
                src: 'web/bundles/phporchestrabackoffice/smartadmin/img/select2-spinner.gif',
                dest: 'web/img/select2-spinner.gif'
            },

            // ORCHESTRA ASSET
            no_image: {
                src: 'web/bundles/phporchestrabackoffice/images/no_image_available.jpg',
                dest: 'web/img/no_image_available.jpg'
            }

        },

        clean: {
            built: ["web/built"]
        },

        less: {
            bundles: {
                files: filesLess
            }
        },

        cssmin: {
            minify: {
                expand: true,
                src: ['web/css/all.css'],
                ext: '.min.css'
            }
        },

        coffee: {
            compileBare: {
                options: {
                    bare: true
                },
                files: filesCoffee
            }
        },

        uglify: {
            dist: {
                files: {
                    'web/js/all.min.js': ['web/js/all.js']
                }
            }
        },

        concat: {
            smartadminjs: {
                src: [
                    'bower_components/jquery/dist/jquery.js',
                    'bower_components/jquery-ui/jquery-ui.js',
                    'web/bundles/phporchestrabackoffice/smartadmin/js/app.config.js',
                    'bower_components/bootstrap/dist/js/bootstrap.js',
                    'bower_components/jcrop/js/jquery.Jcrop.js',
                    'bower_components/select2/select2.js',
                    'web/bundles/phporchestrabackoffice/smartadmin/js/notification/SmartNotification.min.js',
                    'web/bundles/phporchestrabackoffice/smartadmin/js/smartwidgets/jarvis.widget.min.js',
                    'web/bundles/phporchestrabackoffice/smartadmin/js/app.min.js'
                ],
                dest: 'web/built/smartadmin.js'
            },

            libjs: {
                src: [
                    'bower_components/underscore/underscore.js',
                    'bower_components/backbone/backbone.js',
                    'bower_components/angular/angular.js',
                    'bower_components/datatables/media/js/jquery.dataTables.js',
                    'bower_components/jquery-form/jquery.form.js',
                    'web/bundles/phporchestrabackoffice/js/latinise.js',
                    'web/bundles/phporchestrabackoffice/js/jQuery.DOMNodeAppear.js',
                    'web/bundles/phporchestrabackoffice/js/underscoreTemplateLoader.js'
                ],
                dest: 'web/built/lib.js'
            },

            orchestrajs: {
                src: [
                     'web/built/phporchestrabackoffice/js/orchestraLib.js',
                     'web/built/phporchestrabackoffice/js/orchestraListeners.js',

                     // MISC
                     'web/built/phporchestrabackoffice/js/OrchestraView.js',
                     'web/built/phporchestrabackoffice/js/addPrototype.js',
                     'web/built/phporchestrabackoffice/js/modelBackbone.js',
                     'web/built/phporchestrabackoffice/js/adminFormView.js',
                     'web/built/phporchestrabackoffice/js/generateAlias.js',
                     'web/built/phporchestrabackoffice/js/generateContentTypeId.js',
                     'web/built/phporchestrabackoffice/js/page/makeSortable.js',
                     'web/built/phporchestrabackoffice/js/page/areaView.js',
                     'web/built/phporchestrabackoffice/js/page/blockView.js',
                     'web/built/phporchestrabackoffice/js/page/nodeView.js',
                     'web/built/phporchestrabackoffice/js/page/NodeVersionView.js',
                     'web/built/phporchestrabackoffice/js/page/NodeLanguageView.js',
                     'web/built/phporchestrabackoffice/js/page/previewLinkView.js',
                     'web/built/phporchestrabackoffice/js/table/TableviewView.js',
                     'web/built/phporchestrabackoffice/js/table/TableviewCollectionView.js',
                     'web/built/phporchestrabackoffice/js/FullPageFormView.js',
                     'web/built/phporchestrabackoffice/js/ContentTypeChangeTypeListener.js',
                     'web/built/phporchestrabackoffice/js/page/templateView.js',
                     'web/built/phporchestrabackoffice/js/page/showNode.js',
                     'web/built/phporchestrabackoffice/js/page/showTemplate.js',
                     'web/built/phporchestrabackoffice/js/table/tableviewLoader.js',
                     'web/built/phporchestrabackoffice/js/page/nodeConstructor.js',
                     'web/built/phporchestrabackoffice/js/treeAjaxDelete.js',
                     'web/built/phporchestrabackoffice/js/configurableContentFormListener.js',
                     'web/built/phporchestrabackoffice/js/page/blocksPanel.js',
                     'web/built/phporchestrabackoffice/js/security.js',

                     // MEDIATHEQUE
                     'web/built/phporchestrabackoffice/js/mediatheque/*.js',

                     // INDEXATION
                     'web/bundles/phporchestraindexation/js/*.js',

                     // LEXIKTRANSLATION
                     'web/bundles/lexiktranslation/ng-table/ng-table.min.js',
                     'web/built/phporchestratranslation/js/translationView.js',

                     // BACKBONE ROUTER
                     'web/bundles/phporchestrabackoffice/js/backboneRouter.js'
                ],
                dest: 'web/built/orchestra.js'
            },

            js: {
                src: [
                    'web/built/smartadmin.js',
                    'web/built/lib.js',
                    'web/built/orchestra.js'
                ],
                dest: 'web/js/all.js'
            },

            smartadmincss: {
                src: [
                    // SMARTADMIN PACKAGE
//                    'bower_components/bootstrap/dist/css/bootstrap.min.css',
                    'web/bundles/phporchestrabackoffice/smartadmin/css/bootstrap.min.css',
                    'bower_components/font-awesome/css/font-awesome.min.css',
                    'web/bundles/phporchestrabackoffice/smartadmin/css/smartadmin-production-plugins.min.css',
                    'web/bundles/phporchestrabackoffice/smartadmin/css/smartadmin-production.min.css',
                    'web/bundles/phporchestrabackoffice/smartadmin/css/smartadmin-skins.min.css',
                    'web/bundles/phporchestrabackoffice/smartadmin/css/smartadmin-rtl.min.css',

                    // ORCHESTRA SMARTADMIN PATCHES
                    'web/built/phporchestrabackoffice/css/smartadminPatches/flags.css',
                    'web/built/phporchestrabackoffice/css/smartadminPatches/title.css',
                    'web/built/phporchestrabackoffice/css/smartadminPatches/modal.css',
                    'web/built/phporchestrabackoffice/css/smartadminPatches/widget.css',
                    'web/built/phporchestrabackoffice/css/smartadminPatches/checkbox.css',
                    'web/built/phporchestrabackoffice/css/smartadminPatches/tab.css',
                    'web/built/phporchestrabackoffice/css/smartadminPatches/form.css',

                    // TINYMCE PATCHES
                    'web/built/phporchestrabackoffice/css/tinyMCEPatches/floatPanel.css'

                ],
                dest: 'web/built/smartadmin.css'
            },

            libcss: {
                src: [
                      'bower_components/jquery-ui/themes/base/all.css',
                      'bower_components/datatables/media/css/jquery.dataTables.css'
                ],
                dest: 'web/built/lib.css'
            },

            orchestracss: {
                src: [
                      'web/built/phporchestrabackoffice/css/phporchestra.css',
                      'web/built/phporchestrabackoffice/css/mediatheque.css',
                      'web/built/phporchestrabackoffice/css/template.css',
                      'web/built/phporchestrabackoffice/css/blocksPanel.css',
                      'web/built/phporchestrabackoffice/css/blocksIcon.css',
                      'web/built/phporchestrabackoffice/css/mediaModal.css',
                      'web/bundles/lexiktranslation/ng-table/ng-table.min.css',
                      'web/built/phporchestrabackoffice/css/loginPage.css',
                      'web/built/phporchestrabackoffice/css/editTable.css',
                      'web/built/phporchestrabackoffice/css/node.css'
                ],
                dest: 'web/built/orchestra.css'
            },

            css: {
                src: [
                      'web/built/smartadmin.css',
                      'web/built/lib.css',
                      'web/built/orchestra.css'
                ],
                dest: 'web/css/all.css'
            }
        },

        watch: {
            css: {
                files: ['web/bundles/*/less/*.less'],
                tasks: ['css', 'command:assetic_dump']
            },
            javascript: {
                files: ['web/bundles/*/coffee/*.coffee'],
                tasks: ['javascript', 'command:assetic_dump']
            }
        },

        command : {
            assets_install: {
                cmd  : 'php app/console assets:install --symlink'
            },
            assetic_dump: {
                cmd  : 'php app/console assetic:dump'
            }
        }
    });

    // Default task(s).
    grunt.registerTask('default', ['clean', 'command:assets_install', 'symlink', 'css', 'javascript', 'javascriptProd', 'command:assetic_dump']);
    grunt.registerTask('css', ['less:discovering', 'less', 'concat:smartadmincss', 'concat:libcss', 'concat:orchestracss', 'concat:css', 'cssmin']);
    grunt.registerTask('javascript', ['coffee:discovering', 'coffee', 'concat:smartadminjs', 'concat:libjs', 'concat:orchestrajs', 'concat:js']);
    grunt.registerTask('javascriptProd', ['uglify']);
    grunt.registerTask('less:discovering', 'This is a function', function() {
        // LESS Files management
        // Source LESS files are located inside : bundles/[bundle]/less/
        // Destination CSS files are located inside : built/[bundle]/css/
        var mappingFileLess = grunt.file.expandMapping(
            ['*/less/*.less', '*/less/*/*.less'],
            'web/built/', {
                cwd: 'web/bundles/',
                rename: function(dest, matchedSrcPath, options) {
                    return dest + matchedSrcPath.replace(/less/g, 'css');
                }
            });

        grunt.util._.each(mappingFileLess, function(value) {
            // Why value.src is an array ??
            filesLess[value.dest] = value.src[0];
        });
    });
    grunt.registerTask('coffee:discovering', 'This is a function', function() {
        // COFFEE Files management
        // Source COFFEE files are located inside : bundles/[bundle]/coffee/
        // Destination JS files are located inside : built/[bundle]/js/
        var mappingFileCoffee = grunt.file.expandMapping(
            ['*/coffee/*.coffee', '*/coffee/*/*.coffee'],
            'web/built/', {
                cwd: 'web/bundles/',
                rename: function(dest, matchedSrcPath, options) {
                    return dest + matchedSrcPath.replace(/coffee/g, 'js');
                }
            });

        grunt.util._.each(mappingFileCoffee, function(value) {
            // Why value.src is an array ??
            filesCoffee[value.dest] = value.src[0];
        });
    });
};
<commit_msg>extract multilinguisme from node contexte<commit_after>module.exports = function(grunt) {
    grunt.loadNpmTasks('grunt-contrib-symlink');
    grunt.loadNpmTasks('grunt-contrib-less');
    grunt.loadNpmTasks('grunt-contrib-cssmin');
    grunt.loadNpmTasks('grunt-contrib-coffee');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-contrib-commands');

    var filesLess = {},
        filesCoffee = {};

    // Configuration
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        symlink: {
            // BOWER COMPONENT
            fontawesome_font_otf: {
                src: 'bower_components/font-awesome/fonts/FontAwesome.otf',
                dest: 'web/fonts/FontAwesome.otf'
            },
            fontawesome_font_eot: {
                src: 'bower_components/font-awesome/fonts/fontawesome-webfont.eot',
                dest: 'web/fonts/fontawesome-webfont.eot'
            },
            fontawesome_font_svg: {
                src: 'bower_components/font-awesome/fonts/fontawesome-webfont.svg',
                dest: 'web/fonts/fontawesome-webfont.svg'
            },
            fontawesome_font_ttf: {
                src: 'bower_components/font-awesome/fonts/fontawesome-webfont.ttf',
                dest: 'web/fonts/fontawesome-webfont.ttf'
            },
            fontawesome_font_woff: {
                src: 'bower_components/font-awesome/fonts/fontawesome-webfont.woff',
                dest: 'web/fonts/fontawesome-webfont.woff'
            },
            bootstrap_font_eot: {
                src: 'bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.eot',
                dest: 'web/fonts/glyphicons-halflings-regular.eot'
            },
            bootstrap_font_svg: {
                src: 'bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.svg',
                dest: 'web/fonts/glyphicons-halflings-regular.svg'
            },
            bootstrap_font_ttf: {
                src: 'bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.ttf',
                dest: 'web/fonts/glyphicons-halflings-regular.ttf'
            },
            bootstrap_font_woff: {
                src: 'bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.woff',
                dest: 'web/fonts/glyphicons-halflings-regular.woff'
            },
            datatable_img_sort_asc: {
                src: 'bower_components/datatables/media/images/sort_asc.png',
                dest: 'web/images/sort_asc.png'
            },
            datatable_img_sort_both: {
                src: 'bower_components/datatables/media/images/sort_both.png',
                dest: 'web/images/sort_both.png'
            },
            datatable_img_sort_desc: {
                src: 'bower_components/datatables/media/images/sort_desc.png',
                dest: 'web/images/sort_desc.png'
            },
            pace_js: {
                src: 'bower_components/pace/pace.min.js',
                dest: 'web/js/pace.min.js'
            },
            jcrop_gif: {
                src: 'bower_components/jcrop/css/Jcrop.gif',
                dest: 'web/img/jcrop/Jcrop.gif'
            },
            // SMARTADMIN ASSETS
            smartadmin_bg: {
                src: 'web/bundles/phporchestrabackoffice/smartadmin/img/mybg.png',
                dest: 'web/img/mybg.png'
            },
            smartadmin_flags: {
                src: 'web/bundles/phporchestrabackoffice/smartadmin/img/flags/flags.png',
                dest: 'web/img/flags/flags.png'
            },
            select2_gif: {
                src: 'web/bundles/phporchestrabackoffice/smartadmin/img/select2-spinner.gif',
                dest: 'web/img/select2-spinner.gif'
            },

            // ORCHESTRA ASSET
            no_image: {
                src: 'web/bundles/phporchestrabackoffice/images/no_image_available.jpg',
                dest: 'web/img/no_image_available.jpg'
            }

        },

        clean: {
            built: ["web/built"]
        },

        less: {
            bundles: {
                files: filesLess
            }
        },

        cssmin: {
            minify: {
                expand: true,
                src: ['web/css/all.css'],
                ext: '.min.css'
            }
        },

        coffee: {
            compileBare: {
                options: {
                    bare: true
                },
                files: filesCoffee
            }
        },

        uglify: {
            dist: {
                files: {
                    'web/js/all.min.js': ['web/js/all.js']
                }
            }
        },

        concat: {
            smartadminjs: {
                src: [
                    'bower_components/jquery/dist/jquery.js',
                    'bower_components/jquery-ui/jquery-ui.js',
                    'web/bundles/phporchestrabackoffice/smartadmin/js/app.config.js',
                    'bower_components/bootstrap/dist/js/bootstrap.js',
                    'bower_components/jcrop/js/jquery.Jcrop.js',
                    'bower_components/select2/select2.js',
                    'web/bundles/phporchestrabackoffice/smartadmin/js/notification/SmartNotification.min.js',
                    'web/bundles/phporchestrabackoffice/smartadmin/js/smartwidgets/jarvis.widget.min.js',
                    'web/bundles/phporchestrabackoffice/smartadmin/js/app.min.js'
                ],
                dest: 'web/built/smartadmin.js'
            },

            libjs: {
                src: [
                    'bower_components/underscore/underscore.js',
                    'bower_components/backbone/backbone.js',
                    'bower_components/angular/angular.js',
                    'bower_components/datatables/media/js/jquery.dataTables.js',
                    'bower_components/jquery-form/jquery.form.js',
                    'web/bundles/phporchestrabackoffice/js/latinise.js',
                    'web/bundles/phporchestrabackoffice/js/jQuery.DOMNodeAppear.js',
                    'web/bundles/phporchestrabackoffice/js/underscoreTemplateLoader.js'
                ],
                dest: 'web/built/lib.js'
            },

            orchestrajs: {
                src: [
                     'web/built/phporchestrabackoffice/js/orchestraLib.js',
                     'web/built/phporchestrabackoffice/js/orchestraListeners.js',

                     // MISC
                     'web/built/phporchestrabackoffice/js/OrchestraView.js',
                     'web/built/phporchestrabackoffice/js/addPrototype.js',
                     'web/built/phporchestrabackoffice/js/modelBackbone.js',
                     'web/built/phporchestrabackoffice/js/adminFormView.js',
                     'web/built/phporchestrabackoffice/js/generateAlias.js',
                     'web/built/phporchestrabackoffice/js/generateContentTypeId.js',
                     'web/built/phporchestrabackoffice/js/page/makeSortable.js',
                     'web/built/phporchestrabackoffice/js/page/areaView.js',
                     'web/built/phporchestrabackoffice/js/page/blockView.js',
                     'web/built/phporchestrabackoffice/js/page/nodeView.js',
                     'web/built/phporchestrabackoffice/js/page/NodeVersionView.js',
                     'web/built/phporchestrabackoffice/js/LanguageView.js',
                     'web/built/phporchestrabackoffice/js/page/previewLinkView.js',
                     'web/built/phporchestrabackoffice/js/table/TableviewView.js',
                     'web/built/phporchestrabackoffice/js/table/TableviewCollectionView.js',
                     'web/built/phporchestrabackoffice/js/FullPageFormView.js',
                     'web/built/phporchestrabackoffice/js/ContentTypeChangeTypeListener.js',
                     'web/built/phporchestrabackoffice/js/page/templateView.js',
                     'web/built/phporchestrabackoffice/js/page/showNode.js',
                     'web/built/phporchestrabackoffice/js/page/showTemplate.js',
                     'web/built/phporchestrabackoffice/js/table/tableviewLoader.js',
                     'web/built/phporchestrabackoffice/js/page/nodeConstructor.js',
                     'web/built/phporchestrabackoffice/js/treeAjaxDelete.js',
                     'web/built/phporchestrabackoffice/js/configurableContentFormListener.js',
                     'web/built/phporchestrabackoffice/js/page/blocksPanel.js',
                     'web/built/phporchestrabackoffice/js/security.js',

                     // MEDIATHEQUE
                     'web/built/phporchestrabackoffice/js/mediatheque/*.js',

                     // INDEXATION
                     'web/bundles/phporchestraindexation/js/*.js',

                     // LEXIKTRANSLATION
                     'web/bundles/lexiktranslation/ng-table/ng-table.min.js',
                     'web/built/phporchestratranslation/js/translationView.js',

                     // BACKBONE ROUTER
                     'web/bundles/phporchestrabackoffice/js/backboneRouter.js'
                ],
                dest: 'web/built/orchestra.js'
            },

            js: {
                src: [
                    'web/built/smartadmin.js',
                    'web/built/lib.js',
                    'web/built/orchestra.js'
                ],
                dest: 'web/js/all.js'
            },

            smartadmincss: {
                src: [
                    // SMARTADMIN PACKAGE
//                    'bower_components/bootstrap/dist/css/bootstrap.min.css',
                    'web/bundles/phporchestrabackoffice/smartadmin/css/bootstrap.min.css',
                    'bower_components/font-awesome/css/font-awesome.min.css',
                    'web/bundles/phporchestrabackoffice/smartadmin/css/smartadmin-production-plugins.min.css',
                    'web/bundles/phporchestrabackoffice/smartadmin/css/smartadmin-production.min.css',
                    'web/bundles/phporchestrabackoffice/smartadmin/css/smartadmin-skins.min.css',
                    'web/bundles/phporchestrabackoffice/smartadmin/css/smartadmin-rtl.min.css',

                    // ORCHESTRA SMARTADMIN PATCHES
                    'web/built/phporchestrabackoffice/css/smartadminPatches/flags.css',
                    'web/built/phporchestrabackoffice/css/smartadminPatches/title.css',
                    'web/built/phporchestrabackoffice/css/smartadminPatches/modal.css',
                    'web/built/phporchestrabackoffice/css/smartadminPatches/widget.css',
                    'web/built/phporchestrabackoffice/css/smartadminPatches/checkbox.css',
                    'web/built/phporchestrabackoffice/css/smartadminPatches/tab.css',
                    'web/built/phporchestrabackoffice/css/smartadminPatches/form.css',

                    // TINYMCE PATCHES
                    'web/built/phporchestrabackoffice/css/tinyMCEPatches/floatPanel.css'

                ],
                dest: 'web/built/smartadmin.css'
            },

            libcss: {
                src: [
                      'bower_components/jquery-ui/themes/base/all.css',
                      'bower_components/datatables/media/css/jquery.dataTables.css'
                ],
                dest: 'web/built/lib.css'
            },

            orchestracss: {
                src: [
                      'web/built/phporchestrabackoffice/css/phporchestra.css',
                      'web/built/phporchestrabackoffice/css/mediatheque.css',
                      'web/built/phporchestrabackoffice/css/template.css',
                      'web/built/phporchestrabackoffice/css/blocksPanel.css',
                      'web/built/phporchestrabackoffice/css/blocksIcon.css',
                      'web/built/phporchestrabackoffice/css/mediaModal.css',
                      'web/bundles/lexiktranslation/ng-table/ng-table.min.css',
                      'web/built/phporchestrabackoffice/css/loginPage.css',
                      'web/built/phporchestrabackoffice/css/editTable.css',
                      'web/built/phporchestrabackoffice/css/node.css'
                ],
                dest: 'web/built/orchestra.css'
            },

            css: {
                src: [
                      'web/built/smartadmin.css',
                      'web/built/lib.css',
                      'web/built/orchestra.css'
                ],
                dest: 'web/css/all.css'
            }
        },

        watch: {
            css: {
                files: ['web/bundles/*/less/*.less'],
                tasks: ['css', 'command:assetic_dump']
            },
            javascript: {
                files: ['web/bundles/*/coffee/*.coffee'],
                tasks: ['javascript', 'command:assetic_dump']
            }
        },

        command : {
            assets_install: {
                cmd  : 'php app/console assets:install --symlink'
            },
            assetic_dump: {
                cmd  : 'php app/console assetic:dump'
            }
        }
    });

    // Default task(s).
    grunt.registerTask('default', ['clean', 'command:assets_install', 'symlink', 'css', 'javascript', 'javascriptProd', 'command:assetic_dump']);
    grunt.registerTask('css', ['less:discovering', 'less', 'concat:smartadmincss', 'concat:libcss', 'concat:orchestracss', 'concat:css', 'cssmin']);
    grunt.registerTask('javascript', ['coffee:discovering', 'coffee', 'concat:smartadminjs', 'concat:libjs', 'concat:orchestrajs', 'concat:js']);
    grunt.registerTask('javascriptProd', ['uglify']);
    grunt.registerTask('less:discovering', 'This is a function', function() {
        // LESS Files management
        // Source LESS files are located inside : bundles/[bundle]/less/
        // Destination CSS files are located inside : built/[bundle]/css/
        var mappingFileLess = grunt.file.expandMapping(
            ['*/less/*.less', '*/less/*/*.less'],
            'web/built/', {
                cwd: 'web/bundles/',
                rename: function(dest, matchedSrcPath, options) {
                    return dest + matchedSrcPath.replace(/less/g, 'css');
                }
            });

        grunt.util._.each(mappingFileLess, function(value) {
            // Why value.src is an array ??
            filesLess[value.dest] = value.src[0];
        });
    });
    grunt.registerTask('coffee:discovering', 'This is a function', function() {
        // COFFEE Files management
        // Source COFFEE files are located inside : bundles/[bundle]/coffee/
        // Destination JS files are located inside : built/[bundle]/js/
        var mappingFileCoffee = grunt.file.expandMapping(
            ['*/coffee/*.coffee', '*/coffee/*/*.coffee'],
            'web/built/', {
                cwd: 'web/bundles/',
                rename: function(dest, matchedSrcPath, options) {
                    return dest + matchedSrcPath.replace(/coffee/g, 'js');
                }
            });

        grunt.util._.each(mappingFileCoffee, function(value) {
            // Why value.src is an array ??
            filesCoffee[value.dest] = value.src[0];
        });
    });
};
<|endoftext|>


<commit_before>// code modified from flot AJAX example
// http://www.flotcharts.org/flot/examples/ajax/index.html

	$(function() {

		// flot plot options!
		var options = {
			lines: {
				show: true
			},
			points: {
				show: false
			},
			legend: {
				show: true
			},
			grid: {
        		hoverable: true
      		}
	};

		// GLOBAL VARIABLES AND FUNCTIONS

		console.log('Initializing variables.');
		// initialize the arrays hold the data for plotting
		var data = [];
		var dataTarget = [];

		// IP address to access our UI
		// (empty for relative URLs)
		var publicIP = '';

		// building blocks of metadata table
		var tableTop = "
";
		var tableBottom = "
";
		var tableHeader = "
ID	Mean	StDev	Level	Blarg
";
		var metadataTable = tableTop + tableHeader;

		// helps with managing the uploaded time series
		var files;

		// initialize the timeseries plot (will be empty)
		console.log('Initializing flot plot (empty plot).');
		$.plot("#placeholder", data, options);

		// ACTIONS TO COMPLETE WHEN THE `SUBMIT` BUTTON IS CLICKED
		$("button#tsQuery").click(function () {

			console.log('Submit button has been clicked.');

			// show the progress bar so the user knows that stuff
			// is going on behind the scenes

			console.log('Adding in ticking progress bar.');
			$( "#progressbar" ).progressbar({
  				value: false
			});

			// reset everything in preparation for new data
			console.log('Resetting helper variables in preparation for new data.');
			document.getElementById('timeseriesMetadata').innerHTML = '';
			data = [];
			var simIDs = [];
			var idNum = {};
			var counter = 0;
			metadataTable = tableTop + tableHeader;

			$.plot("#placeholder", data, options);

			// retrieve the time series specified by the user, and the number of
			//   most similar time series
			var timeSeriesID = document.getElementById("tsID").value;
			var numSim = document.getElementById("n_closest").value;
			console.log('Retrieved timeseries ID #' + timeSeriesID + 'and will retrieve the ' + numSim + 'most similar timeseries.');

			// CONSTRUCT OUR QUERY
			// if the user has specified an ID, use that;
			//   otherwise assume there's an uploaded file.
			if (timeSeriesID != '') {

				// DECIDE WHETHER WE NEED A SIMQUERY
				// if the user hasn't provided a number of similar TS, or the
				//   number is zero, we won't bother sending off a simquery
				if (numSim == '' | numSim == 0) {

					// add on the ID number of the target TS
					simIDs.push(timeSeriesID);

					// now we loop over all the IDs and collect their data
					console.log("Collecting data of specified time series.");

					var dataurl = publicIP + "/timeseries/" + timeSeriesID;

					console.log('Retrieving data associated with TS ID#'+ timeSeriesID + '.');

					$.ajax({
						url: dataurl,
						type: "GET",
						dataType: "json",
						success: onDataReceived
					});

				} else {

					var simurl = publicIP + "/simquery?id=" + timeSeriesID + "&topn=" + numSim;
					console.log('Constructed simquery:', simurl);

					// get the IDs of the similar time series
					console.log('Retrieving the ID numbers of the similar TS (ID number supplied).');
					$.ajax({
						url: simurl,
						type: "GET",
						dataType: "json",
						success: function(data) {

									// parse the ID numbers returned from the server
									getSimIDs(data);

									// add on the ID number of the target TS
									simIDs.push(timeSeriesID);

									// now we loop over all the IDs and collect their data
									console.log("Looping over the retrieved ID numbers and collecting their data.");

									for(var i=0; i < simIDs.length; i++) {

										idNum   = simIDs[i];

										var dataurl = publicIP + "/timeseries/" + idNum;

										console.log('Retrieving data associated with TS ID#'+ idNum + '.');
										// solution from http://stackoverflow.com/questions/4201934/
										//               jquery-ajax-pass-additional-argument-to-success-callback
										$.ajax({
											url: dataurl,
											type: "GET",
											dataType: "json",
											success: onDataReceived
										});

									}
						 }
					});
				}

			} else if ( document.getElementById("fileSelect").files.length > 0  ) {

				// DECIDE WHETHER WE NEED A SIMQUERY
				// if the user hasn't provided a number of similar TS, or the
				//   number is zero, we won't bother sending off a simquery
				if (numSim == '' | numSim == 0) {

					console.log("Locally received data uploaded by user.");
					console.log( document.getElementById("fileSelect").files[0] );

					// parse the uploaded file
					// https://www.html5rocks.com/en/tutorials/file/dndfiles/
					read = new FileReader();
					read.readAsText(document.getElementById("fileSelect").files[0]);

					read.onloadend = function(){
						//console.log(read.result);
						//console.log(JSON.parse(read.result))
						//console.log(JSON.parse(read.result).ts)
						var dataTemp = JSON.parse(read.result).ts;
						dataTarget = dataTemp[0].map(function (e, i) {
												return [e, dataTemp[1][i]];});

						tsData = {label: "uploaded timeseries", data: dataTarget, lines: {lineWidth:6}};

						console.log('Appending uploaded time series to Flot data.');

						data.push(tsData);

						console.log(tsData);

						console.log('Plotting the data of the uploaded TS.');

						$.plot("#placeholder", data, options);

						console.log("Destroy the progress bar -- we don't need it anymore.");
						$("#progressbar").progressbar( "destroy" );

					}

				} else {

					console.log("Locally received data uploaded by user.");
					console.log( document.getElementById("fileSelect").files[0] );

					var simurl = publicIP + "/simquery?" + "topn=" + numSim;

					console.log("Sending user-loaded data off to be processed:" + simurl);
					$.ajax({
						url: simurl,
						type: 'POST',
						data: document.getElementById("fileSelect").files[0],
						cache: false,
						contentType: 'application/json; charset=utf-8',
						dataType: 'json',
						processData: false, // Don't process the files
						contentType: false, // Set content type to false as jQuery will tell the server its a query string request
						error: function(jqXHR, textStatus, errorThrown) {
					 			// Handle errors here
									console.log('ERRORS: ' + textStatus);
						}
					})
						.done(function (result) {

							simIDs = result.id;

							$.ajax({
								url: simurl,
								type: "GET",
								dataType: "json",
								success: function(data) {

										// loop over all the IDs and collect their data
										console.log("Looping over the retrieved ID numbers and collecting their data.");

										for(var i=0; i < simIDs.length; i++) {

											idNum   = simIDs[i];

											var dataurl = publicIP + "/timeseries/" + idNum;

											console.log('Retrieving data associated with TS ID#' + idNum + '.');
											// solution from http://stackoverflow.com/questions/4201934/
											//               jquery-ajax-pass-additional-argument-to-success-callback
											$.ajax({
												url: dataurl,
												type: "GET",
												dataType: "json",
												success: onDataReceived
											});

										}
							 }
						});

					// parse the uploaded file
					// https://www.html5rocks.com/en/tutorials/file/dndfiles/
					read = new FileReader();
					read.readAsText(document.getElementById("fileSelect").files[0]);

					read.onloadend = function(){
						//console.log(read.result);
						//console.log(JSON.parse(read.result))
						//console.log(JSON.parse(read.result).ts)
						var dataTemp = JSON.parse(read.result).ts;
						dataTarget = dataTemp[0].map(function (e, i) {
												return [e, dataTemp[1][i]];});

						tsData = {label: "uploaded timeseries", data: dataTarget, lines: {lineWidth:6}};

						console.log('Appending uploaded time series to Flot data.');

						data.push(tsData);

						console.log(tsData);

						console.log('Plotting the data of the uploaded TS.');

						$.plot("#placeholder", data, options);

					}
			});
				}

			} else {
				// user hasn't specified anything!
				alert("You gotta give us something valid to work with...");

				$("#progressbar").progressbar( "destroy" );
			}

			function onDataReceived(series) {

				// pull the similar TS
				//

				// * solution from Stack Overflow:
				//   http://stackoverflow.com/questions/22015684/
				//             how-do-i-zip-two-arrays-in-javascript
				console.log('Zipping TS ID#' + simIDs[counter] + ' into appropriate form for Flot to plot.');
				var dataTarget = series.ts[0].map(function (e, i) {
					return [e, series.ts[1][i]];
				});

				tsData = {label: "timeseries " + simIDs[counter], data: dataTarget};

				console.log('Appending TS ID#' + simIDs[counter] +' to Flot data.');
				data.push(tsData);

				$.plot("#placeholder", data, options);

				// if (1) we've reached the target TS ID, in the case of a specified TS ID
				//    (2) we've reached the end of the similar IDs, in the case of
				//        an uploaded TS,
				// we're done putting together the metadata table.
				// highlight the row of the targt TS ID and show the table to the world
				if( series.metadata[0].id == timeSeriesID ) {

					var tableRow = "
" + series.metadata[0].id + "	";
					tableRow    += "" +series.metadata[0].mean  + "	";
					tableRow    += "" +series.metadata[0].std   + "	";
					tableRow    += "" +series.metadata[0].level + "	";
					tableRow    += "" +series.metadata[0].blarg + "
";

					console.log("Adding ID #" + series.metadata[0].id + " to metadata table.")
					metadataTable += tableRow;

					console.log("Put together + display the metadata table.");
					metadataTable += tableBottom;
					document.getElementById('timeseriesMetadata').innerHTML = metadataTable;
					console.log("Destroy the progress bar -- we don't need it anymore.");
					$("#progressbar").progressbar( "destroy" );

				} else if ( counter == simIDs.length - 1 ) {

					var tableRow = "
" + series.metadata[0].id + "	";
					tableRow    += "" +series.metadata[0].mean  + "	";
					tableRow    += "" +series.metadata[0].std   + "	";
					tableRow    += "" +series.metadata[0].level + "	";
					tableRow    += "" +series.metadata[0].blarg + "
";

					console.log("Adding ID #" + series.metadata[0].id + " to metadata table.")
					metadataTable += tableRow;

					console.log("Put together + display the metadata table.");
					metadataTable += tableBottom;
					document.getElementById('timeseriesMetadata').innerHTML = metadataTable;
					console.log("Destroy the progress bar -- we don't need it anymore.");
					$("#progressbar").progressbar( "destroy" );

				} else {

					// put together the metadata
					var tableRow = "
" + series.metadata[0].id + "	";
					tableRow    += "" +series.metadata[0].mean  + "	";
					tableRow    += "" +series.metadata[0].std   + "	";
					tableRow    += "" +series.metadata[0].level + "	";
					tableRow    += "" +series.metadata[0].blarg + "
";

					console.log("Adding ID #" + series.metadata[0].id + " to metadata table.")
					metadataTable += tableRow;

				}

				// keeps track of where we are in the array of TS IDs to plot
				counter++;

			}

			function getSimIDs(series) {
				for(var i=0; i < series.id.length; i++) {
					simIDs.push(series.id[i]);
				}
			}

		});

		// Add the Flot version string to the footer
		$("#footer").prepend("Flot " + $.plot.version + " + ");
	});<commit_msg>Minor edit to simquery URL<commit_after>// code modified from flot AJAX example
// http://www.flotcharts.org/flot/examples/ajax/index.html

	$(function() {

		// flot plot options!
		var options = {
			lines: {
				show: true
			},
			points: {
				show: false
			},
			legend: {
				show: true
			},
			grid: {
        		hoverable: true
      		}
	};

		// GLOBAL VARIABLES AND FUNCTIONS

		console.log('Initializing variables.');
		// initialize the arrays hold the data for plotting
		var data = [];
		var dataTarget = [];

		// IP address to access our UI
		// (empty for relative URLs)
		var publicIP = '';

		// building blocks of metadata table
		var tableTop = "
";
		var tableBottom = "
";
		var tableHeader = "
ID	Mean	StDev	Level	Blarg
";
		var metadataTable = tableTop + tableHeader;

		// helps with managing the uploaded time series
		var files;

		// initialize the timeseries plot (will be empty)
		console.log('Initializing flot plot (empty plot).');
		$.plot("#placeholder", data, options);

		// ACTIONS TO COMPLETE WHEN THE `SUBMIT` BUTTON IS CLICKED
		$("button#tsQuery").click(function () {

			console.log('Submit button has been clicked.');

			// show the progress bar so the user knows that stuff
			// is going on behind the scenes

			console.log('Adding in ticking progress bar.');
			$( "#progressbar" ).progressbar({
  				value: false
			});

			// reset everything in preparation for new data
			console.log('Resetting helper variables in preparation for new data.');
			document.getElementById('timeseriesMetadata').innerHTML = '';
			data = [];
			var simIDs = [];
			var idNum = {};
			var counter = 0;
			metadataTable = tableTop + tableHeader;

			$.plot("#placeholder", data, options);

			// retrieve the time series specified by the user, and the number of
			//   most similar time series
			var timeSeriesID = document.getElementById("tsID").value;
			var numSim = document.getElementById("n_closest").value;
			console.log('Retrieved timeseries ID #' + timeSeriesID + 'and will retrieve the ' + numSim + 'most similar timeseries.');

			// CONSTRUCT OUR QUERY
			// if the user has specified an ID, use that;
			//   otherwise assume there's an uploaded file.
			if (timeSeriesID != '') {

				// DECIDE WHETHER WE NEED A SIMQUERY
				// if the user hasn't provided a number of similar TS, or the
				//   number is zero, we won't bother sending off a simquery
				if (numSim == '' | numSim == 0) {

					// add on the ID number of the target TS
					simIDs.push(timeSeriesID);

					// now we loop over all the IDs and collect their data
					console.log("Collecting data of specified time series.");

					var dataurl = publicIP + "/timeseries/" + timeSeriesID;

					console.log('Retrieving data associated with TS ID#'+ timeSeriesID + '.');

					$.ajax({
						url: dataurl,
						type: "GET",
						dataType: "json",
						success: onDataReceived
					});

				} else {

					var simurl = publicIP + "/simquery?id=" + timeSeriesID + "&topn=" + numSim;
					console.log('Constructed simquery:', simurl);

					// get the IDs of the similar time series
					console.log('Retrieving the ID numbers of the similar TS (ID number supplied).');
					$.ajax({
						url: simurl,
						type: "GET",
						dataType: "json",
						success: function(data) {

									// parse the ID numbers returned from the server
									getSimIDs(data);

									// add on the ID number of the target TS
									simIDs.push(timeSeriesID);

									// now we loop over all the IDs and collect their data
									console.log("Looping over the retrieved ID numbers and collecting their data.");

									for(var i=0; i < simIDs.length; i++) {

										idNum   = simIDs[i];

										var dataurl = publicIP + "/timeseries/" + idNum;

										console.log('Retrieving data associated with TS ID#'+ idNum + '.');
										// solution from http://stackoverflow.com/questions/4201934/
										//               jquery-ajax-pass-additional-argument-to-success-callback
										$.ajax({
											url: dataurl,
											type: "GET",
											dataType: "json",
											success: onDataReceived
										});

									}
						 }
					});
				}

			} else if ( document.getElementById("fileSelect").files.length > 0  ) {

				// DECIDE WHETHER WE NEED A SIMQUERY
				// if the user hasn't provided a number of similar TS, or the
				//   number is zero, we won't bother sending off a simquery
				if (numSim == '' | numSim == 0) {

					console.log("Locally received data uploaded by user.");
					console.log( document.getElementById("fileSelect").files[0] );

					// parse the uploaded file
					// https://www.html5rocks.com/en/tutorials/file/dndfiles/
					read = new FileReader();
					read.readAsText(document.getElementById("fileSelect").files[0]);

					read.onloadend = function(){
						//console.log(read.result);
						//console.log(JSON.parse(read.result))
						//console.log(JSON.parse(read.result).ts)
						var dataTemp = JSON.parse(read.result).ts;
						dataTarget = dataTemp[0].map(function (e, i) {
												return [e, dataTemp[1][i]];});

						tsData = {label: "uploaded timeseries", data: dataTarget, lines: {lineWidth:6}};

						console.log('Appending uploaded time series to Flot data.');

						data.push(tsData);

						console.log(tsData);

						console.log('Plotting the data of the uploaded TS.');

						$.plot("#placeholder", data, options);

						console.log("Destroy the progress bar -- we don't need it anymore.");
						$("#progressbar").progressbar( "destroy" );

					}

				} else {

					console.log("Locally received data uploaded by user.");
					console.log( document.getElementById("fileSelect").files[0] );

					var simurl = publicIP + "/simquery" //+ "topn=" + numSim;

					console.log("Sending user-loaded data off to be processed:" + simurl);
					$.ajax({
						url: simurl,
						type: 'POST',
						data: document.getElementById("fileSelect").files[0],
						cache: false,
						contentType: 'application/json; charset=utf-8',
						dataType: 'json',
						processData: false, // Don't process the files
						contentType: false, // Set content type to false as jQuery will tell the server its a query string request
						error: function(jqXHR, textStatus, errorThrown) {
					 			// Handle errors here
									console.log('ERRORS: ' + textStatus);
						}
					})
						.done(function (result) {

							simIDs = result.id;

							$.ajax({
								url: simurl,
								type: "GET",
								dataType: "json",
								success: function(data) {

										// loop over all the IDs and collect their data
										console.log("Looping over the retrieved ID numbers and collecting their data.");

										for(var i=0; i < simIDs.length; i++) {

											idNum   = simIDs[i];

											var dataurl = publicIP + "/timeseries/" + idNum;

											console.log('Retrieving data associated with TS ID#' + idNum + '.');
											// solution from http://stackoverflow.com/questions/4201934/
											//               jquery-ajax-pass-additional-argument-to-success-callback
											$.ajax({
												url: dataurl,
												type: "GET",
												dataType: "json",
												success: onDataReceived
											});

										}
							 }
						});

					// parse the uploaded file
					// https://www.html5rocks.com/en/tutorials/file/dndfiles/
					read = new FileReader();
					read.readAsText(document.getElementById("fileSelect").files[0]);

					read.onloadend = function(){
						//console.log(read.result);
						//console.log(JSON.parse(read.result))
						//console.log(JSON.parse(read.result).ts)
						var dataTemp = JSON.parse(read.result).ts;
						dataTarget = dataTemp[0].map(function (e, i) {
												return [e, dataTemp[1][i]];});

						tsData = {label: "uploaded timeseries", data: dataTarget, lines: {lineWidth:6}};

						console.log('Appending uploaded time series to Flot data.');

						data.push(tsData);

						console.log(tsData);

						console.log('Plotting the data of the uploaded TS.');

						$.plot("#placeholder", data, options);

					}
			});
				}

			} else {
				// user hasn't specified anything!
				alert("You gotta give us something valid to work with...");

				$("#progressbar").progressbar( "destroy" );
			}

			function onDataReceived(series) {

				// pull the similar TS
				//

				// * solution from Stack Overflow:
				//   http://stackoverflow.com/questions/22015684/
				//             how-do-i-zip-two-arrays-in-javascript
				console.log('Zipping TS ID#' + simIDs[counter] + ' into appropriate form for Flot to plot.');
				var dataTarget = series.ts[0].map(function (e, i) {
					return [e, series.ts[1][i]];
				});

				tsData = {label: "timeseries " + simIDs[counter], data: dataTarget};

				console.log('Appending TS ID#' + simIDs[counter] +' to Flot data.');
				data.push(tsData);

				$.plot("#placeholder", data, options);

				// if (1) we've reached the target TS ID, in the case of a specified TS ID
				//    (2) we've reached the end of the similar IDs, in the case of
				//        an uploaded TS,
				// we're done putting together the metadata table.
				// highlight the row of the targt TS ID and show the table to the world
				if( series.metadata[0].id == timeSeriesID ) {

					var tableRow = "
" + series.metadata[0].id + "	";
					tableRow    += "" +series.metadata[0].mean  + "	";
					tableRow    += "" +series.metadata[0].std   + "	";
					tableRow    += "" +series.metadata[0].level + "	";
					tableRow    += "" +series.metadata[0].blarg + "
";

					console.log("Adding ID #" + series.metadata[0].id + " to metadata table.")
					metadataTable += tableRow;

					console.log("Put together + display the metadata table.");
					metadataTable += tableBottom;
					document.getElementById('timeseriesMetadata').innerHTML = metadataTable;
					console.log("Destroy the progress bar -- we don't need it anymore.");
					$("#progressbar").progressbar( "destroy" );

				} else if ( counter == simIDs.length - 1 ) {

					var tableRow = "
" + series.metadata[0].id + "	";
					tableRow    += "" +series.metadata[0].mean  + "	";
					tableRow    += "" +series.metadata[0].std   + "	";
					tableRow    += "" +series.metadata[0].level + "	";
					tableRow    += "" +series.metadata[0].blarg + "
";

					console.log("Adding ID #" + series.metadata[0].id + " to metadata table.")
					metadataTable += tableRow;

					console.log("Put together + display the metadata table.");
					metadataTable += tableBottom;
					document.getElementById('timeseriesMetadata').innerHTML = metadataTable;
					console.log("Destroy the progress bar -- we don't need it anymore.");
					$("#progressbar").progressbar( "destroy" );

				} else {

					// put together the metadata
					var tableRow = "
" + series.metadata[0].id + "	";
					tableRow    += "" +series.metadata[0].mean  + "	";
					tableRow    += "" +series.metadata[0].std   + "	";
					tableRow    += "" +series.metadata[0].level + "	";
					tableRow    += "" +series.metadata[0].blarg + "
";

					console.log("Adding ID #" + series.metadata[0].id + " to metadata table.")
					metadataTable += tableRow;

				}

				// keeps track of where we are in the array of TS IDs to plot
				counter++;

			}

			function getSimIDs(series) {
				for(var i=0; i < series.id.length; i++) {
					simIDs.push(series.id[i]);
				}
			}

		});

		// Add the Flot version string to the footer
		$("#footer").prepend("Flot " + $.plot.version + " + ");
	});<|endoftext|>


<commit_before>#ifndef __lang_Enumerable__
#define __lang_Enumerable__

#comment Use macros to produce different version of the code bellow,
#comment depending on wether SET_ITERATOR is set or not.
#ifdef SET_ITERATOR
#comment The field 'name' on the 'bind' object is set to the iterator before
#comment iteration. We can call it directly instead using #call.
#comment This leads to better performance (2x on Firefox), and even more  on
#comment legacy browsers where we can avoid the emulated Function.call.
#define ITERATOR(ITER, BIND, VALUE, KEY, SELF, NAME) BIND.NAME(VALUE, KEY, SELF)
#define ITERATE(ITER, NAME) Base.iterate(ITER, NAME)
#else // !SET_ITERATOR
#comment Call the iterator funciton on the bind object through Function.call.
#comment This is cleanear but slower than the SET_ITERATOR hack.
#define ITERATOR(ITER, BIND, VALUE, KEY, SELF, NAME) ITER.call(BIND, VALUE, KEY, SELF)
#define ITERATE(ITER, NAME) Base.iterate(ITER)
#endif // !SET_ITERATOR

////////////////////////////////////////////////////////////////////////////////
// Enumerable

/**
 * The Enumerable interface. To add enumerable functionality to any prototype,
 * just use Constructor.inject(Enumerable);
 * This adds the function .each() that can handle both arrays (detected through
 * .length) and dictionaries (if it's not an array, enumerating with for-in).
 */
Enumerable = new function() {
	/**
	 * Converts the passed function to an iterate-function.
	 * This is part of an optimization that is based on the observation that
	 * calling the iterator through bind.__iterate is faster than using iter.apply()
	 * each time.
	 * So iterate wraps the passed function in a closure that sets the __iterate
	 * function (defined by name) on the bind object and then calls the original
	 * function, restoring the original state after it returns.
	 * This is used in many places in Enumerable, each place defining its own
	 * name for the iterate function, so there are no clashes if calls are nested.
	 */
#ifdef SET_ITERATOR
	Base.iterate = function(fn, name) {
#else
	Base.iterate = function(fn) {
#endif
#if defined(SET_ITERATOR) && defined(DONT_ENUM)
		// dontEnum all set iterators once and for all on browsers:
		Base.prototype.dontEnum(true, name);
#endif // APPLY_ITERATOR && DONT_ENUM
		return function(iter, bind) {
			// Convert the argument to an iterator function. If none is specified,
			// the identity function is returned.
			// This supports regular expressions, normal functions, which are
			// returned unmodified, and values to compare to.
			// Wherever this private function is used in the Enumerable functions
			// bellow, a RegExp object, a Function or null may be passed.
			if (!iter) iter = function(val) { return val };
			else if (typeof iter != 'function') iter = function(val) { return val == iter };
			/*
			// For RegExp support, used this:
			else switch (Base.type(iter)) {
				case 'function': break;
				case 'regexp': iter = function(val) { return iter.test(val) }; break;
				default: iter = function(val) { return val == iter };
			}
			*/
			if (!bind) bind = this;
#ifdef SET_ITERATOR
			// Backup previous value of the field, and set iterator.
			var prev = bind[name];
			bind[name] = iter;
#ifdef HELMA
			// On Helma, we can only dontEnum once the property is defined.
			bind.dontEnum(name);
#endif // HELMA
#endif// !SET_ITERATOR
			// Interesting benchmark observation: The loops seem execute
			// faster when called on the object (this), so outsource to
			// the above functions each_Array / each_Object here.
			// pass this twice, so it can be recieved as 'that' in the iterating
			// functions, to be passed to the iterator (and being able to use
			// 'this' in .each differently)
#ifdef SET_ITERATOR
			// Allways restore previous value in the end.
			try { return fn.call(this, iter, bind, this); }
			finally { prev ? bind[name] = prev : delete bind[name] }
#else // !SET_ITERATOR
			return fn.call(this, iter, bind, this);
#endif// !SET_ITERATOR
		};
	};

	/**
	 * A special constant, to be thrown by closures passed to each()
	 *
	 * $continue / Base.next is not implemented, as the same functionality can achieved
	 * by using return in the closure. In prototype, the implementation of $continue
	 * also leads to a huge speed decrease, as the closure is wrapped in another
	 * closure that does nothing else than handling $continue.
	 */
	Base.stop = {};

	var each_Array = Array.prototype.forEach || function(iter, bind) {
		for (var i = 0, l = this.length; i < l; ++i)
			ITERATOR(iter, bind, this[i], i, this, __each);
	};

	var each_Object = function(iter, bind) {
#ifdef DONT_ENUM
		// We use for-in here, but need to filter out what should not be iterated.
		// Object#dontEnum defines a method to flag such a fields, and Object#has
		// a way to find out for any given key if it is enumerable or not.
		// The loop here uses an inline version of Object#has (See Core.js).
		var entries = this._dontEnum || {};
		for (var i in this) {
			var val = this[i], entry = entries[i];
			// Skip dontEnum fields.
			// This line here is similar to Base.prototype.has
			if (!entry || entry.allow && entry.object[i] !== this[i])
				ITERATOR(iter, bind, val, i, this, __each);
		}
#elif !defined(HELMA)
		// We use for-in here, but need to filter out what should not be iterated.
		// The loop here uses an inline version of Object#has (See Core.js).
#ifdef EXTEND_OBJECT
		for (var i in this) {
			var val = this[i];
			if (NAME_IS_VISIBLE(i, val !== this.__proto__[i]))
				ITERATOR(iter, bind, val, i, this, __each);
		}
#else // !EXTEND_OBJECT
		// Object.prototype is untouched, so we cannot assume __proto__ to always
		// be defined on legacy browsers. Use two versions of the loops for
		// better performance here:
		if (!this.__proto__) {
			for (var i in this)
				IF_NAME_IS_VISIBLE(i, ITERATOR(iter, bind, this[i], i, this, __each);)
		} else {
			for (var i in this) {
				var val = this[i];
				if (NAME_IS_VISIBLE(i, val !== this.__proto__[i]))
					ITERATOR(iter, bind, val, i, this, __each);
			}
		}
#endif // !EXTEND_OBJECT
#else // HELMA
		// No need to check when not extending Object and when on Helma as
		// dontEnum is always used to hide fields there.
		for (var i in this)
			ITERATOR(iter, bind, this[i], i, this, __each);
#endif
	};

	return {
		HIDE
		_generics: true,

		/**
		 * The core of all Enumerable functions. TODO: document
		 */
		each: ITERATE(function(iter, bind) {
			try { (this.length != null ? each_Array : each_Object).call(this, iter, bind); }
			catch (e) { if (e !== Base.stop) throw e; }
			return bind;
		}, '__each'),

		/**
		 * Searches the list for the first element where the passed iterator
		 * does not return null and returns an object containing key, value and
		 * iterator result for the given entry. This is used in find and remove.
		 */
		findEntry: ITERATE(function(iter, bind, that) {
			return this.each(function(val, key) {
				this.result = ITERATOR(iter, bind, val, key, that, __findEntry);
				if (this.result) {
					this.key = key;
					this.value = val;
					throw Base.stop;
				}
			}, {});
		}, '__findEntry'),

		/**
		 * Calls the passed iterator for each element and returns the first
		 * result of the iterator calls that is not null.
		 */
		find: function(iter, bind) {
			return this.findEntry(iter, bind).result;
		},

		remove: function(iter, bind) {
			var entry = this.findEntry(iter, bind);
			delete this[entry.key];
			return entry.value;
		},

		/**
		 * Returns true if the condition defined by the passed iterator is true
		 * for one or more of the elements, false otherwise.
		 * If no iterator is passed, the value is used directly.
		 * This is compatible with JS 1.5's .some, but adds more flexibility
		 * regarding iterators (as defined in iterate())
		 */
		some: function(iter, bind) {
			return this.find(iter, bind) != null;
		},

		/**
		 * Returns true if the condition defined by the passed iterator is true
		 * for	all elements, false otherwise.
		 * If no iterator is passed, the value is used directly.
		 * This is compatible with JS 1.5's .every, but adds more flexibility
		 * regarding iterators (as defined in iterate())
		 */
		every: ITERATE(function(iter, bind, that) {
			return this.find(function(val, i) {
				// as "this" is not used for anything else, use it for bind,
				// so that lookups on the object are faster (according to
				// benchmarking)
				return !ITERATOR(iter, this, val, i, that, __every);
			}, bind) == null;
		}, '__every'),

		/**
		 * Collects the result of the given iterator applied to each of the
		 * elements in an array and returns it.
		 * If no iterator is passed, the value is used directly.
		 * This is compatible with JS 1.5's .map, but adds more flexibility
		 * regarding iterators (as defined in iterate())
		 */
		map: ITERATE(function(iter, bind, that) {
			return this.each(function(val, i) {
				this[this.length] = ITERATOR(iter, bind, val, i, that, __map);
			}, []);
		}, '__map'),

		/**
		 * Collects all elements for which the condition of the passed iterator
		 * or regular expression is true.
		 * This is compatible with JS 1.5's .filter, but adds more flexibility
		 * regarding iterators (as defined in iterate())
		 * TODO: consider collect: similar to filter, but collects the returned
		 * elements if they are != null.
		 * TOOD: See if collect and filter could be joined somehow
		 */
		filter: ITERATE(function(iter, bind, that) {
			return this.each(function(val, i) {
				if (ITERATOR(iter, bind, val, i, that, __filter))
					this[this.length] = val;
			}, []);
		}, '__filter'),

		/**
		 * Returns the maximum value of the result of the passed iterator
		 * applied to each element.
		 * If no iterator is passed, the value is used directly.
		 */
		max: ITERATE(function(iter, bind, that) {
			return this.each(function(val, i) {
				val = ITERATOR(iter, bind, val, i, that, __max);
				if (val >= (this.max || val)) this.max = val;
			}, {}).max;
		}, '__max'),

		/**
		 * Returns the minimum value of the result of the passed iterator
		 * applied to each element.
		 * If no iterator is passed, the value is used directly.
		 */
		min: ITERATE(function(iter, bind, that) {
			return this.each(function(val, i) {
				val = ITERATOR(iter, bind, val, i, that, __min);
				if (val <= (this.min || val)) this.min = val;
			}, {}).min;
		}, '__min'),

		/**
		 * Collects the values of the given property of each of the elements
		 * in an array and returns it.
		 */
		pluck: function(prop) {
			return this.map(function(val) {
				return val[prop];
			});
		},

		/**
		 * Sorts the elements depending on the outcome of the passed iterator
		 * and returns the sorted list in an array.
		 * Inspired by Prototype.js
		 */
		sortBy: ITERATE(function(iter, bind, that) {
			return this.map(function(val, i) {
				return { value: val, compare: ITERATOR(iter, bind, val, i, that, __sortBy) };
			}, bind).sort(function(left, right) {
				var a = left.compare, b = right.compare;
				return a < b ? -1 : a > b ? 1 : 0;
			}).pluck('value');
		}, '__sortBy'),

		/**
		 * Converts the Enumerable to a normal array.
		 */
		toArray: function() {
			return this.map();
		}
	};
}

#endif // __lang_Enumerable__<commit_msg>Check type of length to determine wether to use Array_each or Object_each.<commit_after>#ifndef __lang_Enumerable__
#define __lang_Enumerable__

#comment Use macros to produce different version of the code bellow,
#comment depending on wether SET_ITERATOR is set or not.
#ifdef SET_ITERATOR
#comment The field 'name' on the 'bind' object is set to the iterator before
#comment iteration. We can call it directly instead using #call.
#comment This leads to better performance (2x on Firefox), and even more  on
#comment legacy browsers where we can avoid the emulated Function.call.
#define ITERATOR(ITER, BIND, VALUE, KEY, SELF, NAME) BIND.NAME(VALUE, KEY, SELF)
#define ITERATE(ITER, NAME) Base.iterate(ITER, NAME)
#else // !SET_ITERATOR
#comment Call the iterator funciton on the bind object through Function.call.
#comment This is cleanear but slower than the SET_ITERATOR hack.
#define ITERATOR(ITER, BIND, VALUE, KEY, SELF, NAME) ITER.call(BIND, VALUE, KEY, SELF)
#define ITERATE(ITER, NAME) Base.iterate(ITER)
#endif // !SET_ITERATOR

////////////////////////////////////////////////////////////////////////////////
// Enumerable

/**
 * The Enumerable interface. To add enumerable functionality to any prototype,
 * just use Constructor.inject(Enumerable);
 * This adds the function .each() that can handle both arrays (detected through
 * .length) and dictionaries (if it's not an array, enumerating with for-in).
 */
Enumerable = new function() {
	/**
	 * Converts the passed function to an iterate-function.
	 * This is part of an optimization that is based on the observation that
	 * calling the iterator through bind.__iterate is faster than using iter.apply()
	 * each time.
	 * So iterate wraps the passed function in a closure that sets the __iterate
	 * function (defined by name) on the bind object and then calls the original
	 * function, restoring the original state after it returns.
	 * This is used in many places in Enumerable, each place defining its own
	 * name for the iterate function, so there are no clashes if calls are nested.
	 */
#ifdef SET_ITERATOR
	Base.iterate = function(fn, name) {
#else
	Base.iterate = function(fn) {
#endif
#if defined(SET_ITERATOR) && defined(DONT_ENUM)
		// dontEnum all set iterators once and for all on browsers:
		Base.prototype.dontEnum(true, name);
#endif // APPLY_ITERATOR && DONT_ENUM
		return function(iter, bind) {
			// Convert the argument to an iterator function. If none is specified,
			// the identity function is returned.
			// This supports regular expressions, normal functions, which are
			// returned unmodified, and values to compare to.
			// Wherever this private function is used in the Enumerable functions
			// bellow, a RegExp object, a Function or null may be passed.
			if (!iter) iter = function(val) { return val };
			else if (typeof iter != 'function') iter = function(val) { return val == iter };
			/*
			// For RegExp support, used this:
			else switch (Base.type(iter)) {
				case 'function': break;
				case 'regexp': iter = function(val) { return iter.test(val) }; break;
				default: iter = function(val) { return val == iter };
			}
			*/
			if (!bind) bind = this;
#ifdef SET_ITERATOR
			// Backup previous value of the field, and set iterator.
			var prev = bind[name];
			bind[name] = iter;
#ifdef HELMA
			// On Helma, we can only dontEnum once the property is defined.
			bind.dontEnum(name);
#endif // HELMA
#endif// !SET_ITERATOR
			// Interesting benchmark observation: The loops seem execute
			// faster when called on the object (this), so outsource to
			// the above functions each_Array / each_Object here.
			// pass this twice, so it can be recieved as 'that' in the iterating
			// functions, to be passed to the iterator (and being able to use
			// 'this' in .each differently)
#ifdef SET_ITERATOR
			// Allways restore previous value in the end.
			try { return fn.call(this, iter, bind, this); }
			finally { prev ? bind[name] = prev : delete bind[name] }
#else // !SET_ITERATOR
			return fn.call(this, iter, bind, this);
#endif// !SET_ITERATOR
		};
	};

	/**
	 * A special constant, to be thrown by closures passed to each()
	 *
	 * $continue / Base.next is not implemented, as the same functionality can achieved
	 * by using return in the closure. In prototype, the implementation of $continue
	 * also leads to a huge speed decrease, as the closure is wrapped in another
	 * closure that does nothing else than handling $continue.
	 */
	Base.stop = {};

	var each_Array = Array.prototype.forEach || function(iter, bind) {
		for (var i = 0, l = this.length; i < l; ++i)
			ITERATOR(iter, bind, this[i], i, this, __each);
	};

	var each_Object = function(iter, bind) {
#ifdef DONT_ENUM
		// We use for-in here, but need to filter out what should not be iterated.
		// Object#dontEnum defines a method to flag such a fields, and Object#has
		// a way to find out for any given key if it is enumerable or not.
		// The loop here uses an inline version of Object#has (See Core.js).
		var entries = this._dontEnum || {};
		for (var i in this) {
			var val = this[i], entry = entries[i];
			// Skip dontEnum fields.
			// This line here is similar to Base.prototype.has
			if (!entry || entry.allow && entry.object[i] !== this[i])
				ITERATOR(iter, bind, val, i, this, __each);
		}
#elif !defined(HELMA)
		// We use for-in here, but need to filter out what should not be iterated.
		// The loop here uses an inline version of Object#has (See Core.js).
#ifdef EXTEND_OBJECT
		for (var i in this) {
			var val = this[i];
			if (NAME_IS_VISIBLE(i, val !== this.__proto__[i]))
				ITERATOR(iter, bind, val, i, this, __each);
		}
#else // !EXTEND_OBJECT
		// Object.prototype is untouched, so we cannot assume __proto__ to always
		// be defined on legacy browsers. Use two versions of the loops for
		// better performance here:
		if (!this.__proto__) {
			for (var i in this)
				IF_NAME_IS_VISIBLE(i, ITERATOR(iter, bind, this[i], i, this, __each);)
		} else {
			for (var i in this) {
				var val = this[i];
				if (NAME_IS_VISIBLE(i, val !== this.__proto__[i]))
					ITERATOR(iter, bind, val, i, this, __each);
			}
		}
#endif // !EXTEND_OBJECT
#else // HELMA
		// No need to check when not extending Object and when on Helma as
		// dontEnum is always used to hide fields there.
		for (var i in this)
			ITERATOR(iter, bind, this[i], i, this, __each);
#endif
	};

	return {
		HIDE
		_generics: true,

		/**
		 * The core of all Enumerable functions. TODO: document
		 */
		each: ITERATE(function(iter, bind) {
			try { (typeof this.length == 'number' ? each_Array : each_Object).call(this, iter, bind); }
			catch (e) { if (e !== Base.stop) throw e; }
			return bind;
		}, '__each'),

		/**
		 * Searches the list for the first element where the passed iterator
		 * does not return null and returns an object containing key, value and
		 * iterator result for the given entry. This is used in find and remove.
		 */
		findEntry: ITERATE(function(iter, bind, that) {
			return this.each(function(val, key) {
				this.result = ITERATOR(iter, bind, val, key, that, __findEntry);
				if (this.result) {
					this.key = key;
					this.value = val;
					throw Base.stop;
				}
			}, {});
		}, '__findEntry'),

		/**
		 * Calls the passed iterator for each element and returns the first
		 * result of the iterator calls that is not null.
		 */
		find: function(iter, bind) {
			return this.findEntry(iter, bind).result;
		},

		remove: function(iter, bind) {
			var entry = this.findEntry(iter, bind);
			delete this[entry.key];
			return entry.value;
		},

		/**
		 * Returns true if the condition defined by the passed iterator is true
		 * for one or more of the elements, false otherwise.
		 * If no iterator is passed, the value is used directly.
		 * This is compatible with JS 1.5's .some, but adds more flexibility
		 * regarding iterators (as defined in iterate())
		 */
		some: function(iter, bind) {
			return this.find(iter, bind) != null;
		},

		/**
		 * Returns true if the condition defined by the passed iterator is true
		 * for	all elements, false otherwise.
		 * If no iterator is passed, the value is used directly.
		 * This is compatible with JS 1.5's .every, but adds more flexibility
		 * regarding iterators (as defined in iterate())
		 */
		every: ITERATE(function(iter, bind, that) {
			return this.find(function(val, i) {
				// as "this" is not used for anything else, use it for bind,
				// so that lookups on the object are faster (according to
				// benchmarking)
				return !ITERATOR(iter, this, val, i, that, __every);
			}, bind) == null;
		}, '__every'),

		/**
		 * Collects the result of the given iterator applied to each of the
		 * elements in an array and returns it.
		 * If no iterator is passed, the value is used directly.
		 * This is compatible with JS 1.5's .map, but adds more flexibility
		 * regarding iterators (as defined in iterate())
		 */
		map: ITERATE(function(iter, bind, that) {
			return this.each(function(val, i) {
				this[this.length] = ITERATOR(iter, bind, val, i, that, __map);
			}, []);
		}, '__map'),

		/**
		 * Collects all elements for which the condition of the passed iterator
		 * or regular expression is true.
		 * This is compatible with JS 1.5's .filter, but adds more flexibility
		 * regarding iterators (as defined in iterate())
		 * TODO: consider collect: similar to filter, but collects the returned
		 * elements if they are != null.
		 * TOOD: See if collect and filter could be joined somehow
		 */
		filter: ITERATE(function(iter, bind, that) {
			return this.each(function(val, i) {
				if (ITERATOR(iter, bind, val, i, that, __filter))
					this[this.length] = val;
			}, []);
		}, '__filter'),

		/**
		 * Returns the maximum value of the result of the passed iterator
		 * applied to each element.
		 * If no iterator is passed, the value is used directly.
		 */
		max: ITERATE(function(iter, bind, that) {
			return this.each(function(val, i) {
				val = ITERATOR(iter, bind, val, i, that, __max);
				if (val >= (this.max || val)) this.max = val;
			}, {}).max;
		}, '__max'),

		/**
		 * Returns the minimum value of the result of the passed iterator
		 * applied to each element.
		 * If no iterator is passed, the value is used directly.
		 */
		min: ITERATE(function(iter, bind, that) {
			return this.each(function(val, i) {
				val = ITERATOR(iter, bind, val, i, that, __min);
				if (val <= (this.min || val)) this.min = val;
			}, {}).min;
		}, '__min'),

		/**
		 * Collects the values of the given property of each of the elements
		 * in an array and returns it.
		 */
		pluck: function(prop) {
			return this.map(function(val) {
				return val[prop];
			});
		},

		/**
		 * Sorts the elements depending on the outcome of the passed iterator
		 * and returns the sorted list in an array.
		 * Inspired by Prototype.js
		 */
		sortBy: ITERATE(function(iter, bind, that) {
			return this.map(function(val, i) {
				return { value: val, compare: ITERATOR(iter, bind, val, i, that, __sortBy) };
			}, bind).sort(function(left, right) {
				var a = left.compare, b = right.compare;
				return a < b ? -1 : a > b ? 1 : 0;
			}).pluck('value');
		}, '__sortBy'),

		/**
		 * Converts the Enumerable to a normal array.
		 */
		toArray: function() {
			return this.map();
		}
	};
}

#endif // __lang_Enumerable__<|endoftext|>


<commit_before>/*
 * Notes :
 * need to figure out if there is a way to continously check if
 * the alarms sets off.
 */

/**
 * Welcome to Pebble.js!
 * Test
 * This is where you write your app.
 */

// Calls in required stuff
var UI = require('ui');
var Vibe = require('ui/vibe');
var Settings = require('settings');
var date = new Date();

//var Vector2 = require('vector2');

// A for loop to make array of hours
var hours = [];
for (var i = 0; i < 24; i++) {
    hours.push(i + 1);
}

var createAlarmItems = function(alarms) {
    var items = [];
    items.push({
        title: "Add New Alarm"
    });
    console.log("added new alarm");
    for (var i = 0; i < hours.length; i++) {
        items.push({
            title: alarms[i].time,
            subtitle: alarms[i].enabled
        });
    }
    console.log("Created item list");
    return items;
};

// Sets up the alarms
var alarms = Settings.data('alarms') || [];
var alarmItems = createAlarmItems(alarms);

/*
// Creates a loop to make an array of hours
var createHourItems = function() {
  var items = [];
  for (var i = 0; i < hours.length; i++) {
    items.push({
      title: hours[i]
    });
  }
  return items;
};
*/

/*
var main = new UI.Menu({
   sections:[{
     items: createItems()
  }]
});

main.show();
*/

// The Spashscreen
var spashScreen = new UI.Card({
    title: 'Alarm',
    icon: 'images/menu_icon.png',
    subtitle: 'Welcome to Our App',
    body: 'This is the splash page'
    //banner (future plans)
});

// Makes a menu with New Alarms
var main = new UI.Menu({
    sections: [{
        items: alarmItems
        /*
            [{
            title: 'Add New Alarm',
            subtitle: 'New Alarm'
        }, {
            // Dr. Seuss
            title: 'One Alarm'
        }, {
            title: 'Two Alarm'
        }, {
            title: 'Red Alarm'
        }, {
            title: 'Blue Alarm'
        }]
        */
        //, createAlarmItems(alarms)
    }]
});

// Shows the spashscreen and goes to the menu after 400 ms
spashScreen.show();
setTimeout(function() {
    spashScreen.hide();
    main.show();
}, 400);

main.on('select', function(e) {
    // If it is on the "New Alarm Option"
    if (e.itemIndex === 0) {
        // Has a random card as a placeholder
        var card = new UI.Card();
        card.title('A Card');
        card.subtitle('Is a Window');
        card.body('The simplest window type in Pebble.js.');
        card.show();

        // When click the middle button it makes an alarm
        card.on('click', 'select', function() {
            Vibe.vibrate('long');
            alarms.push({
                hour: date.getHours() + 1,
                minute: date.getMinutes() + 2,
                enabled: true
            });
            createAlarmItems(alarms);
            card.hide();
        });
    } else {
        // Otherwise the user selects an alarm
        // Creates the Menu for Alarm Options
        var alarmOptions = new UI.Menu({
            sections : [{
                items: [{
                    title: 'Disable'
                }, {
                    title: 'Edit'
                }, {
                    title: 'Delete'
                }]
            }]
        });
        alarmOptions.show();
    }
    // Choose an option to chnage alarm
    alarmOptions.on('select', function(e) {
        switch(e.itemIndex) {
            case 0:
                // Disable or Enable the Alarm
                if (e.item.enabled) {
                    e.item.enabled = false;
                } else {
                    e.item.enabled = true;
                }
                break;
            case 1:
                // Edit the time of the alarm
                break;
            case 2:
                // Deletes the alarm
                alarms.splice(e.itemIndex, 1);
                break;
            default:
                console.log("error");
                break;
        }
        // Update the alarms and gets rid of the option menu
        //createAlarmItems();
        alarmOptions.hide();
    });
});

// Code from before, I don't currently remove it for reference
/*
// Try but doesn't work
main.on('click', 'select', function(e) {
    var item = this.items(0);
    if (item.title == "Add New Alarm") {
        Vibe.vibrate('long');
        var card = new UI.Card();
        card.title('A Card');
        card.subtitle('Is a Window');
        card.body('The simplest window type in Pebble.js.');
        card.show();
    }
});
*/

/*
main.on('click', 'up', function(e) {
    var menu = new UI.Menu({
        sections: [{
            items: [{
                title: 'Pebble.js',
                icon: 'images/menu_icon.png',
                subtitle: 'Can do Menus'
            }, {
                title: 'Second Item',
                subtitle: 'Subtitle Text'
            }]
        }]
    });
    menu.on('select', function(e) {
        console.log('Selected item #' + e.itemIndex + ' of section #' + e.sectionIndex);
        console.log('The item is titled "' + e.item.title + '"');
    });
    menu.show();
});
*/

// When click middle button
/*
main.on('click', 'up', function(e) {
    //test vibrqtion and date fubction
    console.log("foo");
    if (new Date() == new Date()) {
        Vibe.vibrate('long');
    }
    var wind = new UI.Window();
    //var time = new UI.TimeText();
    // Time in Text form
    var textfield = new UI.TimeText({
        position: new Vector2(0, 50),
        size: new Vector2(144, 30),
        font: 'gothic-24-bold',
        text: '%M:%S, %a',
        textAlign: 'center'
    });
    wind.add(textfield);
    wind.show();
});
*/

/*
main.on('click', 'down', function(e) {
    var card = new UI.Card();
    card.title('A Card');
    card.subtitle('Is a Window');
    card.body('The simplest window type in Pebble.js.');
    card.show();
});
*/
<commit_msg>moved line around<commit_after>/*
 * Notes :
 * need to figure out if there is a way to continously check if
 * the alarms sets off.
 */

/**
 * Welcome to Pebble.js!
 * Test
 * This is where you write your app.
 */

// Calls in required stuff
var UI = require('ui');
var Vibe = require('ui/vibe');
var Settings = require('settings');
var date = new Date();

//var Vector2 = require('vector2');

// A for loop to make array of hours
var hours = [];
for (var i = 0; i < 24; i++) {
    hours.push(i + 1);
}

var alarms = Settings.data('alarms') || [];
var createAlarmItems = function(alarms) {
    var items = [];
    items.push({
        title: "Add New Alarm"
    });
    console.log("added new alarm");
    for (var i = 0; i < hours.length; i++) {
        items.push({
            title: alarms[i].time,
            subtitle: alarms[i].enabled
        });
    }
    console.log("Created item list");
    return items;
};

// Sets up the alarms
var alarmItems = createAlarmItems(alarms);

/*
// Creates a loop to make an array of hours
var createHourItems = function() {
  var items = [];
  for (var i = 0; i < hours.length; i++) {
    items.push({
      title: hours[i]
    });
  }
  return items;
};
*/

/*
var main = new UI.Menu({
   sections:[{
     items: createItems()
  }]
});

main.show();
*/

// The Spashscreen
var spashScreen = new UI.Card({
    title: 'Alarm',
    icon: 'images/menu_icon.png',
    subtitle: 'Welcome to Our App',
    body: 'This is the splash page'
    //banner (future plans)
});

// Makes a menu with New Alarms
var main = new UI.Menu({
    sections: [{
        items: alarmItems
        /*
            [{
            title: 'Add New Alarm',
            subtitle: 'New Alarm'
        }, {
            // Dr. Seuss
            title: 'One Alarm'
        }, {
            title: 'Two Alarm'
        }, {
            title: 'Red Alarm'
        }, {
            title: 'Blue Alarm'
        }]
        */
        //, createAlarmItems(alarms)
    }]
});

// Shows the spashscreen and goes to the menu after 400 ms
spashScreen.show();
setTimeout(function() {
    spashScreen.hide();
    main.show();
}, 400);

main.on('select', function(e) {
    // If it is on the "New Alarm Option"
    if (e.itemIndex === 0) {
        // Has a random card as a placeholder
        var card = new UI.Card();
        card.title('A Card');
        card.subtitle('Is a Window');
        card.body('The simplest window type in Pebble.js.');
        card.show();

        // When click the middle button it makes an alarm
        card.on('click', 'select', function() {
            Vibe.vibrate('long');
            alarms.push({
                hour: date.getHours() + 1,
                minute: date.getMinutes() + 2,
                enabled: true
            });
            createAlarmItems(alarms);
            card.hide();
        });
    } else {
        // Otherwise the user selects an alarm
        // Creates the Menu for Alarm Options
        var alarmOptions = new UI.Menu({
            sections : [{
                items: [{
                    title: 'Disable'
                }, {
                    title: 'Edit'
                }, {
                    title: 'Delete'
                }]
            }]
        });
        alarmOptions.show();
    }
    // Choose an option to chnage alarm
    alarmOptions.on('select', function(e) {
        switch(e.itemIndex) {
            case 0:
                // Disable or Enable the Alarm
                if (e.item.enabled) {
                    e.item.enabled = false;
                } else {
                    e.item.enabled = true;
                }
                break;
            case 1:
                // Edit the time of the alarm
                break;
            case 2:
                // Deletes the alarm
                alarms.splice(e.itemIndex, 1);
                break;
            default:
                console.log("error");
                break;
        }
        // Update the alarms and gets rid of the option menu
        //createAlarmItems();
        alarmOptions.hide();
    });
});

// Code from before, I don't currently remove it for reference
/*
// Try but doesn't work
main.on('click', 'select', function(e) {
    var item = this.items(0);
    if (item.title == "Add New Alarm") {
        Vibe.vibrate('long');
        var card = new UI.Card();
        card.title('A Card');
        card.subtitle('Is a Window');
        card.body('The simplest window type in Pebble.js.');
        card.show();
    }
});
*/

/*
main.on('click', 'up', function(e) {
    var menu = new UI.Menu({
        sections: [{
            items: [{
                title: 'Pebble.js',
                icon: 'images/menu_icon.png',
                subtitle: 'Can do Menus'
            }, {
                title: 'Second Item',
                subtitle: 'Subtitle Text'
            }]
        }]
    });
    menu.on('select', function(e) {
        console.log('Selected item #' + e.itemIndex + ' of section #' + e.sectionIndex);
        console.log('The item is titled "' + e.item.title + '"');
    });
    menu.show();
});
*/

// When click middle button
/*
main.on('click', 'up', function(e) {
    //test vibrqtion and date fubction
    console.log("foo");
    if (new Date() == new Date()) {
        Vibe.vibrate('long');
    }
    var wind = new UI.Window();
    //var time = new UI.TimeText();
    // Time in Text form
    var textfield = new UI.TimeText({
        position: new Vector2(0, 50),
        size: new Vector2(144, 30),
        font: 'gothic-24-bold',
        text: '%M:%S, %a',
        textAlign: 'center'
    });
    wind.add(textfield);
    wind.show();
});
*/

/*
main.on('click', 'down', function(e) {
    var card = new UI.Card();
    card.title('A Card');
    card.subtitle('Is a Window');
    card.body('The simplest window type in Pebble.js.');
    card.show();
});
*/
<|endoftext|>