<commit_before>/*
	The MIT License (MIT)

	Copyright (c) 2014 Julian Xhokaxhiu

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in all
	copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
	SOFTWARE.
*/
module.exports = function(grunt) {

	// Load Tasks
    require('load-grunt-tasks')(grunt);

    // Configure the tasks
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        app: grunt.file.readJSON('app.json'),
        cssMin: 'css/<%= pkg.name %>.min.<%= getCurrentDate() %>.css',
        cssPrintMin: 'css/<%= pkg.name %>.min.<%= getCurrentDate() %>.print.css',
        jsMin: 'js/<%= pkg.name %>.min.<%= getCurrentDate() %>.js',
        getCurrentDate: function() {
            var date = new Date();
            return date.getDate() + '-' + ( date.getMonth() + 1 ) + '-' + date.getFullYear();
        },
        clean: {
            options: {
                force: true
            },
            output: [
                '<%= app.config.output.path %>/*',
                'tpl/scss/_<%= pkg.name %>-icons.scss'
            ],
            cssFiles: [
                'tpl/css/99_<%= pkg.name %>.css',
                'tpl/css-print/99_<%= pkg.name %>.css'
            ],
            mapFiles: [
            	'tpl/css/*.map',
                'tpl/css/*.map',
            ],
            webfonts: [
            	'webfonts/'
            ],
            webicons: [
            	'webicons/'
            ]
        },
        tasty_swig: {
        	build: {
        		options: {
            		context: {
            			app: {
			                name: '<%= pkg.name %>',
			                liveReloadHost: '<%= app.config.livereload.host %>:<%= app.config.livereload.port %>',
			                cssFiles: {
			                    'screen': grunt.file.expand({
			                        filter: 'isFile',
			                        cwd: 'tpl/'
			                    }, 'css/**/*.css'),
			                    'print': grunt.file.expand({
			                        filter: 'isFile',
			                        cwd: 'tpl/'
			                    }, 'css-print/**/*.css')
			                },
			                jsFiles: [ '<%= jsMin %>' ],
			                data: '<%= app.data %>'
			            }
            		}
            	},
				src: [ 'tpl/*.swig' ],
				dest: '<%= app.config.output.path %>/'
			},
			deploy: {
				options: {
            		context: {
            			app: {
			                name: '<%= pkg.name %>',
			                liveReloadHost: false,
			                cssFiles: {
			                    'screen': [ '<%= cssMin %>' ],
								'print': [ '<%= cssPrintMin %>' ]
			                },
			                jsFiles: [ '<%= jsMin %>' ],
			                data: '<%= app.data %>'
			            }
            		}
            	},
				src: [ 'tpl/*.swig' ],
				dest: '<%= app.config.output.path %>/'
			}
        },
		sass: {
            options: {
                style: 'compressed'
            },
			build: {
				files: {
					'tpl/css/99_<%= pkg.name %>.css' : [ 'tpl/scss/screen.scss' ],
					'tpl/css-print/99_<%= pkg.name %>.css' : [ 'tpl/scss/print.scss' ]
				}
			}
		},
		fontgen: {
			build: {
				options: {
					path_prefix: '../fonts/'
				},
				files: {
					'webfonts/' : [
		            	'fonts/*.otf',
						'fonts/*.ttf'
		            ]
				}
			}
		},
		webfont: {
			icons: {
				src: 'icons/*.svg',
				dest: 'webicons/',
                destCss: 'tpl/scss/',
				options: {
					template: 'tpl/icons.css',
                    relativeFontPath: '../fonts/',
					font: '<%= pkg.name %>-icons',
                    stylesheet: 'scss',
                    htmlDemo: false,
                    templateOptions: {
                        baseClass: '<%= pkg.name %>-icon',
                        classPrefix: '<%= pkg.name %>-icon-',
                        mixinPrefix: '<%= pkg.name %>-icon-'
                    }
				}
			}
		},
        concat: {
        	webfonts: {
        		files: {
        			'tpl/css/98_webfonts.css' : [ 'webfonts/*.css' ],
        			'tpl/css-print/98_webfonts.css' : [ 'webfonts/*.css' ]
        		}
        	},
            css: {
                filter: 'isFile',
                src: 'tpl/css/**/*.css',
                dest: '<%= app.config.output.path %>/<%= cssMin %>'
            },
            cssPrint: {
                filter: 'isFile',
                src: 'tpl/css-print/**/*.css',
                dest: '<%= app.config.output.path %>/<%= cssPrintMin %>'
            },
            js: {
            	files: {
            		'<%= app.config.output.path %>/<%= jsMin %>' : '<%= app.assets.js %>'
            	}
            }
        },
        autoprefixer: {
            options: {
                browsers: ['last 3 versions', 'bb 10', 'android 3']
            },
            build: {
            	options: {
            		map: true
            	},
                src: '<%= app.config.output.path %>/css/*.css'
            },
            deploy: {
            	options: {
            		map: false
            	},
            	src: '<%= app.config.output.path %>/css/*.css'
            }
        },
        cssmin: {
            build: {
                files: {
                	'<%= app.config.output.path %>/css/<%= pkg.name %>.min.<%= getCurrentDate() %>.css' : [ 'tpl/css/**/*.css' ],
                	'<%= app.config.output.path %>/css-print/<%= pkg.name %>.min.<%= getCurrentDate() %>.css' : [ 'tpl/css-print/**/*.css' ]
                }
            }
        },
        closurecompiler: {
            build: {
            	files: {
            		'<%= app.config.output.path %>/<%= jsMin %>': '<%= app.assets.js %>'
            	},
            	options: {
	                // Any options supported by Closure Compiler, for example:
	                "compilation_level": "SIMPLE_OPTIMIZATIONS",

	                // Plus a simultaneous processes limit
	                "max_processes": 5,
	            }
            }
        },
        copy: {
            build: {
                files: [
                    // The project CSS and JS files
                    {
                        expand: true,
                        cwd: 'tpl/',
                        src: [
                            'css/**/*.css',
                            'css-print/**/*.css',
                            'css/**/*.map',
                            'css-print/**/*.map',
                            'js/**/*.js'
                        ],
                        dest: '<%= app.config.output.path %>/'
                    }
                ]
            },
            deploy: {
                files: [
                	// External Packages Fonts
                	{
                		expand: true,
                		flatten: true,
                		src: '<%= app.assets.fonts %>',
                		dest: '<%= app.config.output.path %>/fonts/'
                	},
                	// The project Webfonts
                	{
                		expand: true,
                		flatten: true,
                		cwd: 'webfonts/',
                		src: ['**/*.{ttf,woff,eot,svg,otf}'],
                		dest: '<%= app.config.output.path %>/fonts/'
                	},
                	// The project Webicons
                	{
                		expand: true,
                		flatten: true,
                		cwd: 'webicons/',
                		src: ['**/*.{ttf,woff,eot,svg,otf}'],
                		dest: '<%= app.config.output.path %>/fonts/'
                	},
                	// Webicons sass generated file
                	{
                        expand: true,
                        cwd: 'webicons/',
                        src: [
                            '*.scss'
                        ],
                        dest: 'tpl/scss/'
                    },
                	// The project resource files
                    {
                        expand: true,
                        cwd: 'rsc/',
                        src: ['**'],
                        dest: '<%= app.config.output.path %>/'
                    }
                ]
            },
            typo3: {
            	files: [
            		// Icons
            		{
            			expand: true,
                		flatten: true,
                		cwd: 'icons/',
                		src: [ '*.svg' ],
                		dest: '<%= app.config.typo3.path %>/<%= pkg.name %><%= app.config.typo3.suffix %>/Resources/Private/Icons/'
            		},
                	// Fonts
                	{
                		expand: true,
                		flatten: true,
                		cwd: 'fonts/',
                		src: [ '*' ],
                		dest: '<%= app.config.typo3.path %>/<%= pkg.name %><%= app.config.typo3.suffix %>/Resources/Private/Fonts/'
                	},
                	// Images
                	{
                        expand: true,
                        cwd: 'rsc/img',
                        src: [ '*' ],
                        dest: '<%= app.config.typo3.path %>/<%= pkg.name %><%= app.config.typo3.suffix %>/Resources/Private/Images/'
                    },
                	// HTML
                    {
                        expand: true,
                        flatten: true,
                        cwd: '<%= app.config.output.path %>/',
                        src: ['*.html'],
                        dest: '<%= app.config.typo3.path %>/<%= pkg.name %><%= app.config.typo3.suffix %>/Resources/Private/Templates/Html/'
                    },
                    // SCSS
                    {
                        expand: true,
                        flatten: true,
                        cwd: 'tpl/scss/',
                        src: ['*.scss'],
                        dest: '<%= app.config.typo3.path %>/<%= pkg.name %><%= app.config.typo3.suffix %>/Resources/Private/Scss/'
                    },
                    // Javascript
                    {
                    	expand: true,
                        flatten: true,
                        cwd: 'tpl/js/',
                        src: ['*.js'],
                        dest: '<%= app.config.typo3.path %>/<%= pkg.name %><%= app.config.typo3.suffix %>/Resources/Private/JavaScript/'
                    },
                    // Bower + App configuration
                    {
                        expand: true,
                        flatten: true,
                    	src: [ 'app.json', 'bower.json' ],
                    	dest: '<%= app.config.typo3.path %>/<%= pkg.name %><%= app.config.typo3.suffix %>/'
                    },
                    /// Typo3 related stuff
                    {
                        expand: true,
                        flatten: true,
                        dot: true,
                        cwd: '_typo3/',
                        src: [ '*' ],
                        dest: '<%= app.config.typo3.path %>/<%= pkg.name %><%= app.config.typo3.suffix %>/'
                    }
                ]
            }
        },
        watch: {
        	options: {
        		livereload: '<%= app.config.livereload.port %>'
        	},
            html: {
                files: [
                    'tpl/**/*.swig',
                    'app.json'
                ],
                tasks: [
                	'rebuild:html'
                ]
            },
            css: {
                files: [
                    'tpl/**/*.scss',
                ],
                tasks: [
                    'rebuild:css'
                ]
            },
            js: {
                files: [
                    'tpl/**/*.js'
                ],
                tasks: [
                    'rebuild:js'
                ]
            }
        },
        rsync: {
            options: {
                recursive: true,
                deleteAll: true
            },
            deploy: {
                options: {
                    src: '<%= app.config.output.path %>/',
                    dest: '<%= app.config.deploy.path %>',
                    host: '<%= app.config.deploy.host %>'
                }
            }
        },
        connect: {
			build: {
				options: {
					port: '<%= app.server.port %>',
					hostname: '*',
					base: '<%= app.config.output.path %>/'
				}
			}
		}
    });

    grunt.registerTask('default', 'Gruntfile for Mockups', function() {
        grunt.warn('No task name specified.\n\nAvailable tasks: build, deploy, server, typo3"\n\n');
    });

    grunt.registerTask('server', 'Serve an already built mockup', [
    	'connect:build:keepalive'
    ]);

    grunt.registerTask('build', 'Build a mockup and watch for file modifications', [
		'rebuild',
		'watch'
    ]);

    grunt.registerTask('rebuild', 'Build a mockup without watching for file modifications', function ( watchTask ) {
        var tasks = [];

        if ( watchTask === undefined ) watchTask = 'all';

        if ( watchTask == 'all' ) {
            tasks = tasks.concat([
                'clean',
                'fontgen',
                'webfont',
                'concat:webfonts',
                'sass',
                'concat:js',
                'tasty_swig:build',
                'copy:deploy',
                'copy:build',
                'autoprefixer:build',
                'clean:mapFiles',
                'clean:webfonts',
                'clean:webicons'
            ]);
            if ( grunt.config.get('app').config.server.port > -1 )
                tasks = tasks.concat([
                	'connect:build'
                ]);
        } else if ( watchTask == 'html' ) {
            tasks = tasks.concat([
                'tasty_swig:build',
                'copy:deploy',
                'copy:build'
            ]);
        } else if ( watchTask == 'css' ) {
            tasks = tasks.concat([
                'clean:cssFiles',
                'sass',
                'copy:deploy',
                'copy:build',
                'autoprefixer:build'
            ]);
        } else if ( watchTask == 'js' ) {
            tasks = tasks.concat([
                'concat:js',
                'copy:deploy',
                'copy:build'
            ]);
        }
        grunt.task.run(tasks);
    });

    grunt.registerTask('build_deploy', 'Build a mockup ready for deployment sync', [
    	'clean',
        'fontgen',
        'webfont',
        'concat:webfonts',
        'sass',
        'concat:css',
        'concat:cssPrint',
        'cssmin',
        'closurecompiler',
        'tasty_swig:deploy',
        'copy:deploy',
        'autoprefixer:deploy',
        'clean:mapFiles',
        'clean:webfonts',
        'clean:webicons'
    ]);

    grunt.registerTask('deploy', 'Deploy a mockup to the Mockups Server', [
		'build_deploy',
		'rsync:deploy'
    ]);

    grunt.registerTask('typo3', 'Create a TYPO3 extension based on the current output of the mockup', [
    	'build_deploy',
    	'copy:typo3'
    ])
};
<commit_msg>Deeply copy image resources.<commit_after>/*
	The MIT License (MIT)

	Copyright (c) 2014 Julian Xhokaxhiu

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in all
	copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
	SOFTWARE.
*/
module.exports = function(grunt) {

	// Load Tasks
    require('load-grunt-tasks')(grunt);

    // Configure the tasks
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        app: grunt.file.readJSON('app.json'),
        cssMin: 'css/<%= pkg.name %>.min.<%= getCurrentDate() %>.css',
        cssPrintMin: 'css/<%= pkg.name %>.min.<%= getCurrentDate() %>.print.css',
        jsMin: 'js/<%= pkg.name %>.min.<%= getCurrentDate() %>.js',
        getCurrentDate: function() {
            var date = new Date();
            return date.getDate() + '-' + ( date.getMonth() + 1 ) + '-' + date.getFullYear();
        },
        clean: {
            options: {
                force: true
            },
            output: [
                '<%= app.config.output.path %>/*',
                'tpl/scss/_<%= pkg.name %>-icons.scss'
            ],
            cssFiles: [
                'tpl/css/99_<%= pkg.name %>.css',
                'tpl/css-print/99_<%= pkg.name %>.css'
            ],
            mapFiles: [
            	'tpl/css/*.map',
                'tpl/css/*.map',
            ],
            webfonts: [
            	'webfonts/'
            ],
            webicons: [
            	'webicons/'
            ]
        },
        tasty_swig: {
        	build: {
        		options: {
            		context: {
            			app: {
			                name: '<%= pkg.name %>',
			                liveReloadHost: '<%= app.config.livereload.host %>:<%= app.config.livereload.port %>',
			                cssFiles: {
			                    'screen': grunt.file.expand({
			                        filter: 'isFile',
			                        cwd: 'tpl/'
			                    }, 'css/**/*.css'),
			                    'print': grunt.file.expand({
			                        filter: 'isFile',
			                        cwd: 'tpl/'
			                    }, 'css-print/**/*.css')
			                },
			                jsFiles: [ '<%= jsMin %>' ],
			                data: '<%= app.data %>'
			            }
            		}
            	},
				src: [ 'tpl/*.swig' ],
				dest: '<%= app.config.output.path %>/'
			},
			deploy: {
				options: {
            		context: {
            			app: {
			                name: '<%= pkg.name %>',
			                liveReloadHost: false,
			                cssFiles: {
			                    'screen': [ '<%= cssMin %>' ],
								'print': [ '<%= cssPrintMin %>' ]
			                },
			                jsFiles: [ '<%= jsMin %>' ],
			                data: '<%= app.data %>'
			            }
            		}
            	},
				src: [ 'tpl/*.swig' ],
				dest: '<%= app.config.output.path %>/'
			}
        },
		sass: {
            options: {
                style: 'compressed'
            },
			build: {
				files: {
					'tpl/css/99_<%= pkg.name %>.css' : [ 'tpl/scss/screen.scss' ],
					'tpl/css-print/99_<%= pkg.name %>.css' : [ 'tpl/scss/print.scss' ]
				}
			}
		},
		fontgen: {
			build: {
				options: {
					path_prefix: '../fonts/'
				},
				files: {
					'webfonts/' : [
		            	'fonts/*.otf',
						'fonts/*.ttf'
		            ]
				}
			}
		},
		webfont: {
			icons: {
				src: 'icons/*.svg',
				dest: 'webicons/',
                destCss: 'tpl/scss/',
				options: {
					template: 'tpl/icons.css',
                    relativeFontPath: '../fonts/',
					font: '<%= pkg.name %>-icons',
                    stylesheet: 'scss',
                    htmlDemo: false,
                    templateOptions: {
                        baseClass: '<%= pkg.name %>-icon',
                        classPrefix: '<%= pkg.name %>-icon-',
                        mixinPrefix: '<%= pkg.name %>-icon-'
                    }
				}
			}
		},
        concat: {
        	webfonts: {
        		files: {
        			'tpl/css/98_webfonts.css' : [ 'webfonts/*.css' ],
        			'tpl/css-print/98_webfonts.css' : [ 'webfonts/*.css' ]
        		}
        	},
            css: {
                filter: 'isFile',
                src: 'tpl/css/**/*.css',
                dest: '<%= app.config.output.path %>/<%= cssMin %>'
            },
            cssPrint: {
                filter: 'isFile',
                src: 'tpl/css-print/**/*.css',
                dest: '<%= app.config.output.path %>/<%= cssPrintMin %>'
            },
            js: {
            	files: {
            		'<%= app.config.output.path %>/<%= jsMin %>' : '<%= app.assets.js %>'
            	}
            }
        },
        autoprefixer: {
            options: {
                browsers: ['last 3 versions', 'bb 10', 'android 3']
            },
            build: {
            	options: {
            		map: true
            	},
                src: '<%= app.config.output.path %>/css/*.css'
            },
            deploy: {
            	options: {
            		map: false
            	},
            	src: '<%= app.config.output.path %>/css/*.css'
            }
        },
        cssmin: {
            build: {
                files: {
                	'<%= app.config.output.path %>/css/<%= pkg.name %>.min.<%= getCurrentDate() %>.css' : [ 'tpl/css/**/*.css' ],
                	'<%= app.config.output.path %>/css-print/<%= pkg.name %>.min.<%= getCurrentDate() %>.css' : [ 'tpl/css-print/**/*.css' ]
                }
            }
        },
        closurecompiler: {
            build: {
            	files: {
            		'<%= app.config.output.path %>/<%= jsMin %>': '<%= app.assets.js %>'
            	},
            	options: {
	                // Any options supported by Closure Compiler, for example:
	                "compilation_level": "SIMPLE_OPTIMIZATIONS",

	                // Plus a simultaneous processes limit
	                "max_processes": 5,
	            }
            }
        },
        copy: {
            build: {
                files: [
                    // The project CSS and JS files
                    {
                        expand: true,
                        cwd: 'tpl/',
                        src: [
                            'css/**/*.css',
                            'css-print/**/*.css',
                            'css/**/*.map',
                            'css-print/**/*.map',
                            'js/**/*.js'
                        ],
                        dest: '<%= app.config.output.path %>/'
                    }
                ]
            },
            deploy: {
                files: [
                	// External Packages Fonts
                	{
                		expand: true,
                		flatten: true,
                		src: '<%= app.assets.fonts %>',
                		dest: '<%= app.config.output.path %>/fonts/'
                	},
                	// The project Webfonts
                	{
                		expand: true,
                		flatten: true,
                		cwd: 'webfonts/',
                		src: ['**/*.{ttf,woff,eot,svg,otf}'],
                		dest: '<%= app.config.output.path %>/fonts/'
                	},
                	// The project Webicons
                	{
                		expand: true,
                		flatten: true,
                		cwd: 'webicons/',
                		src: ['**/*.{ttf,woff,eot,svg,otf}'],
                		dest: '<%= app.config.output.path %>/fonts/'
                	},
                	// Webicons sass generated file
                	{
                        expand: true,
                        cwd: 'webicons/',
                        src: [
                            '*.scss'
                        ],
                        dest: 'tpl/scss/'
                    },
                	// The project resource files
                    {
                        expand: true,
                        cwd: 'rsc/',
                        src: ['**'],
                        dest: '<%= app.config.output.path %>/'
                    }
                ]
            },
            typo3: {
            	files: [
            		// Icons
            		{
            			expand: true,
                		flatten: true,
                		cwd: 'icons/',
                		src: [ '*.svg' ],
                		dest: '<%= app.config.typo3.path %>/<%= pkg.name %><%= app.config.typo3.suffix %>/Resources/Private/Icons/'
            		},
                	// Fonts
                	{
                		expand: true,
                		flatten: true,
                		cwd: 'fonts/',
                		src: [ '*' ],
                		dest: '<%= app.config.typo3.path %>/<%= pkg.name %><%= app.config.typo3.suffix %>/Resources/Private/Fonts/'
                	},
                	// Images
                	{
                        expand: true,
                        cwd: 'rsc/img',
                        src: [ '**/*' ],
                        dest: '<%= app.config.typo3.path %>/<%= pkg.name %><%= app.config.typo3.suffix %>/Resources/Private/Images/'
                    },
                	// HTML
                    {
                        expand: true,
                        flatten: true,
                        cwd: '<%= app.config.output.path %>/',
                        src: ['*.html'],
                        dest: '<%= app.config.typo3.path %>/<%= pkg.name %><%= app.config.typo3.suffix %>/Resources/Private/Templates/Html/'
                    },
                    // SCSS
                    {
                        expand: true,
                        flatten: true,
                        cwd: 'tpl/scss/',
                        src: ['*.scss'],
                        dest: '<%= app.config.typo3.path %>/<%= pkg.name %><%= app.config.typo3.suffix %>/Resources/Private/Scss/'
                    },
                    // Javascript
                    {
                    	expand: true,
                        flatten: true,
                        cwd: 'tpl/js/',
                        src: ['*.js'],
                        dest: '<%= app.config.typo3.path %>/<%= pkg.name %><%= app.config.typo3.suffix %>/Resources/Private/JavaScript/'
                    },
                    // Bower + App configuration
                    {
                        expand: true,
                        flatten: true,
                    	src: [ 'app.json', 'bower.json' ],
                    	dest: '<%= app.config.typo3.path %>/<%= pkg.name %><%= app.config.typo3.suffix %>/'
                    },
                    /// Typo3 related stuff
                    {
                        expand: true,
                        flatten: true,
                        dot: true,
                        cwd: '_typo3/',
                        src: [ '*' ],
                        dest: '<%= app.config.typo3.path %>/<%= pkg.name %><%= app.config.typo3.suffix %>/'
                    }
                ]
            }
        },
        watch: {
        	options: {
        		livereload: '<%= app.config.livereload.port %>'
        	},
            html: {
                files: [
                    'tpl/**/*.swig',
                    'app.json'
                ],
                tasks: [
                	'rebuild:html'
                ]
            },
            css: {
                files: [
                    'tpl/**/*.scss',
                ],
                tasks: [
                    'rebuild:css'
                ]
            },
            js: {
                files: [
                    'tpl/**/*.js'
                ],
                tasks: [
                    'rebuild:js'
                ]
            }
        },
        rsync: {
            options: {
                recursive: true,
                deleteAll: true
            },
            deploy: {
                options: {
                    src: '<%= app.config.output.path %>/',
                    dest: '<%= app.config.deploy.path %>',
                    host: '<%= app.config.deploy.host %>'
                }
            }
        },
        connect: {
			build: {
				options: {
					port: '<%= app.server.port %>',
					hostname: '*',
					base: '<%= app.config.output.path %>/'
				}
			}
		}
    });

    grunt.registerTask('default', 'Gruntfile for Mockups', function() {
        grunt.warn('No task name specified.\n\nAvailable tasks: build, deploy, server, typo3"\n\n');
    });

    grunt.registerTask('server', 'Serve an already built mockup', [
    	'connect:build:keepalive'
    ]);

    grunt.registerTask('build', 'Build a mockup and watch for file modifications', [
		'rebuild',
		'watch'
    ]);

    grunt.registerTask('rebuild', 'Build a mockup without watching for file modifications', function ( watchTask ) {
        var tasks = [];

        if ( watchTask === undefined ) watchTask = 'all';

        if ( watchTask == 'all' ) {
            tasks = tasks.concat([
                'clean',
                'fontgen',
                'webfont',
                'concat:webfonts',
                'sass',
                'concat:js',
                'tasty_swig:build',
                'copy:deploy',
                'copy:build',
                'autoprefixer:build',
                'clean:mapFiles',
                'clean:webfonts',
                'clean:webicons'
            ]);
            if ( grunt.config.get('app').config.server.port > -1 )
                tasks = tasks.concat([
                	'connect:build'
                ]);
        } else if ( watchTask == 'html' ) {
            tasks = tasks.concat([
                'tasty_swig:build',
                'copy:deploy',
                'copy:build'
            ]);
        } else if ( watchTask == 'css' ) {
            tasks = tasks.concat([
                'clean:cssFiles',
                'sass',
                'copy:deploy',
                'copy:build',
                'autoprefixer:build'
            ]);
        } else if ( watchTask == 'js' ) {
            tasks = tasks.concat([
                'concat:js',
                'copy:deploy',
                'copy:build'
            ]);
        }
        grunt.task.run(tasks);
    });

    grunt.registerTask('build_deploy', 'Build a mockup ready for deployment sync', [
    	'clean',
        'fontgen',
        'webfont',
        'concat:webfonts',
        'sass',
        'concat:css',
        'concat:cssPrint',
        'cssmin',
        'closurecompiler',
        'tasty_swig:deploy',
        'copy:deploy',
        'autoprefixer:deploy',
        'clean:mapFiles',
        'clean:webfonts',
        'clean:webicons'
    ]);

    grunt.registerTask('deploy', 'Deploy a mockup to the Mockups Server', [
		'build_deploy',
		'rsync:deploy'
    ]);

    grunt.registerTask('typo3', 'Create a TYPO3 extension based on the current output of the mockup', [
    	'build_deploy',
    	'copy:typo3'
    ])
};
<|endoftext|>


<commit_before>'use strict';
var Engine = Engine || {};
var gl;
var g = {}; // global variables

Engine.toRad=function(d){return d*0.0174533;}
Engine.getExtension=function(f){return f.substr((~-f.lastIndexOf(".")>>>0)+2);}

Engine.framerate = function(){ return 1.00000000 / Engine.dt; }
Engine.fps = Engine.framerate;

if(!Array.prototype.indexOf){
Array.prototype.indexOf=function(e){var l=this.length>>>0;var f=Number(arguments[1]) || 0;
f=(f<0)?Math.ceil(f):Math.floor(f);if(f<0)f+=l;for(;f<l;f++){if(f in this && this[f]===e)return f;}return -1;};}

Engine.run = function(){
    var now = Date.now();
    Engine.dt = (now - Engine.currentTime)/1000.00000000;
    Engine.currentTime = now;

    Engine.update(Engine.dt);
    Engine.render();

    Engine.requestId = window.requestAnimFrame(Engine.run, Engine.canvas);
}
Engine.handleContextLost = function(e) {
    e.preventDefault();
    if (Engine.requestId !== undefined) {
        window.cancelAnimFrame(Engine.requestId);
        Engine.requestId = undefined;
    }
}
Engine.handleContextRestored = function() {
    Engine.run();
}
Engine.init = function(w,h){
	Engine.windowWidth = w;
    Engine.currentTime = 0.0000000;
    Engine.dt = 0.0000000;
    //first build the canvas and it's necessary html elements.
    var body = document.getElementsByTagName('body')[0];

    var canvas_event_element = document.createElement('div');
    canvas_event_element.setAttribute('tabindex', '0');
    canvas_event_element.setAttribute('id', 'canvasEventCatcher');
    canvas_event_element.setAttribute('style', 'position:absolute;top:0;left:0;z-index:5;outline:none;');

    var canvas_debug_element = document.createElement('div');
    canvas_debug_element.setAttribute('tabindex', '-1');
    canvas_debug_element.setAttribute('id', 'canvasDebug');
    canvas_debug_element.setAttribute('style', 'margin:0;outline:0;border:0;padding:0;top:0;left:0;position:absolute;color:yellow;font-size:200%;z-index:4');

    var canvas_element = document.createElement('canvas');
    canvas_element.setAttribute('tabindex', '-1');
    canvas_element.setAttribute('id', 'canvas');
    canvas_element.setAttribute('style', 'position:relative;top:0;left:0;');

    body.appendChild(canvas_event_element);
    body.appendChild(canvas_debug_element);
    body.appendChild(canvas_element);
    //
    Engine.requestId = undefined;
    Engine.canvas = document.getElementById('canvas');
    Engine.canvasEventCatcher = document.getElementById("canvasEventCatcher");

    Engine.canvas.width = w;
    Engine.canvas.height = h;
    Engine.canvasEventCatcher.style.width = w + "px";
    Engine.canvasEventCatcher.style.height = h + "px";

    gl = Engine.RenderManager.init(Engine.canvas);

    Engine.canvas.addEventListener('webglcontextlost', Engine.handleContextLost, false);
    Engine.canvas.addEventListener('webglcontextrestored', Engine.handleContextRestored, false);

	Engine.Math.init();
	Engine.PhysicsManager.init();
	Engine.SoundManager.init();
    Engine.ResourceManager.initPreGameResources();
    Engine.Game.initResources();
    Engine.ResourceManager.initDefaultResources();

    //this is the above area referenced below
}
Engine.onResourcesLoaded = function(){
    Engine.EventManager.init();

    var now = Date.now();
    Engine.dt = 0.0000000;
    Engine.currentTime = now;

    //move this to above area if needed
    Engine.ResourceManager.initPreGameLogic();
    Engine.Game.initLogic();
    Engine.ResourceManager.initDefaultLogic();
    Engine.resize(Engine.canvas.width,Engine.canvas.height);
    Engine.run();
}
Engine.disableOrientationChange = function(orientationType){
	Engine.EventManager.orientationChange.enabled = false;
	var s = orientationType.toLowerCase();
	var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0.0);
	var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0.0);
	if(s == "horizontal" || s == "landscape" || s == "h" || s == "l"){
		Engine.EventManager.orientationChange.mode = "horizontal";
	}
	else if(s == "vertical" || s == "portrait" || s == "v" || s == "p"){
		Engine.EventManager.orientationChange.mode = "vertical";
	}
	if(w > h){ Engine.EventManager.orientationChange.currOrientation = "horizontal"; }
	else{      Engine.EventManager.orientationChange.currOrientation = "vertical"; }
	Engine.EventManager.doWindowRotation();
}
Engine.requestPointerLock = function(){
    Engine.EventManager.pointerLock.desired = true;
}
Engine.resize = function(width,height){
    Engine.canvas.width = width;
    Engine.canvas.height = height;
    Engine.canvasEventCatcher.style.width = width + "px";
    Engine.canvasEventCatcher.style.height = height + "px";
    gl.viewport(0, 0, width, height);
    for (var key in Engine.ResourceManager.scenes) {
        var scene = Engine.ResourceManager.scenes[key];
        for (var key1 in scene.cameras) {
            scene.cameras[key1].resize(width,height);
        }
    }
}
Engine.update = function(dt){
    Engine.Game.update(dt);

	//cleanup memory
	for(var key in Engine.scene.objects){
		if(Engine.scene.objects[key].hasOwnProperty('_isToBeDestroyed')){
			Engine.scene.objects[key]._free();
			delete Engine.scene.objects[key];
		}
	}

    for (var key in Engine.scene.lights) {
        Engine.scene.lights[key].update(dt);
    }
    for (var key in Engine.scene.objects) {
        Engine.scene.objects[key].update(dt);
    }
    for (var key in Engine.scene.cameras) {
        Engine.scene.cameras[key].update(dt);
    }
    for (var key in Engine.ResourceManager.sounds) {
        Engine.ResourceManager.sounds[key].update(dt);
    }
    Engine.EventManager.update(dt);
	Engine.PhysicsManager.update(dt);

}

Engine.render = function(){
    Engine.RenderManager.render();
}

Engine.isKeyDown = function(key){ return Engine.EventManager.isKeyDown(key); }
Engine.isKeyUp = function(key){ return Engine.EventManager.isKeyUp(key); }<commit_msg>Update Engine_Core.js<commit_after>'use strict';
var Engine = Engine || {};
var gl;
var g = {}; // global variables

Engine.toRad=function(d){return d*0.0174533;}
Engine.getExtension=function(f){return f.substr((~-f.lastIndexOf(".")>>>0)+2);}

Engine.framerate = function(){ return 1.00000000 / Engine.dt; }
Engine.fps = Engine.framerate;

if(!Array.prototype.indexOf){
Array.prototype.indexOf=function(e){var l=this.length>>>0;var f=Number(arguments[1]) || 0;
f=(f<0)?Math.ceil(f):Math.floor(f);if(f<0)f+=l;for(;f<l;f++){if(f in this && this[f]===e)return f;}return -1;};}

Engine.run = function(){
    var now = Date.now();
    Engine.dt = (now - Engine.currentTime)/1000.00000000;
    Engine.currentTime = now;

    Engine.update(Engine.dt);
    Engine.render();

    Engine.requestId = window.requestAnimFrame(Engine.run, Engine.canvas);
}
Engine.handleContextLost = function(e) {
    e.preventDefault();
    if (Engine.requestId !== undefined) {
        window.cancelAnimFrame(Engine.requestId);
        Engine.requestId = undefined;
    }
}
Engine.handleContextRestored = function() {
    Engine.run();
}
Engine.init = function(w,h){
    Engine.windowWidth = w;
    Engine.currentTime = 0.0000000;
    Engine.dt = 0.0000000;
    //first build the canvas and it's necessary html elements.
    var body = document.getElementsByTagName('body')[0];

    var canvas_event_element = document.createElement('div');
    canvas_event_element.setAttribute('tabindex', '0');
    canvas_event_element.setAttribute('id', 'canvasEventCatcher');
    canvas_event_element.setAttribute('style', 'position:absolute;top:0;left:0;z-index:5;outline:none;');

    var canvas_debug_element = document.createElement('div');
    canvas_debug_element.setAttribute('tabindex', '-1');
    canvas_debug_element.setAttribute('id', 'canvasDebug');
    canvas_debug_element.setAttribute('style', 'margin:0;outline:0;border:0;padding:0;top:0;left:0;position:absolute;color:yellow;font-size:200%;z-index:4');

    var canvas_element = document.createElement('canvas');
    canvas_element.setAttribute('tabindex', '-1');
    canvas_element.setAttribute('id', 'canvas');
    canvas_element.setAttribute('style', 'position:relative;top:0;left:0;');

    body.appendChild(canvas_event_element);
    body.appendChild(canvas_debug_element);
    body.appendChild(canvas_element);
    //
    Engine.requestId = undefined;
    Engine.canvas = document.getElementById('canvas');
    Engine.canvasEventCatcher = document.getElementById("canvasEventCatcher");

    Engine.canvas.width = w;
    Engine.canvas.height = h;
    Engine.canvasEventCatcher.style.width = w + "px";
    Engine.canvasEventCatcher.style.height = h + "px";

    gl = Engine.RenderManager.init(Engine.canvas);

    Engine.canvas.addEventListener('webglcontextlost', Engine.handleContextLost, false);
    Engine.canvas.addEventListener('webglcontextrestored', Engine.handleContextRestored, false);

    Engine.Math.init();
    Engine.PhysicsManager.init();
    Engine.SoundManager.init();
    Engine.ResourceManager.initPreGameResources();
    Engine.Game.initResources();
    Engine.ResourceManager.initDefaultResources();

    //this is the above area referenced below
}
Engine.onResourcesLoaded = function(){
    Engine.EventManager.init();

    var now = Date.now();
    Engine.dt = 0.0000000;
    Engine.currentTime = now;

    //move this to above area if needed
    Engine.ResourceManager.initPreGameLogic();
    Engine.Game.initLogic();
    Engine.ResourceManager.initDefaultLogic();
    Engine.resize(Engine.canvas.width,Engine.canvas.height);
    Engine.run();
}
Engine.disableOrientationChange = function(orientationType){
    Engine.EventManager.orientationChange.enabled = false;
    var s = orientationType.toLowerCase();
    var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0.0);
    var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0.0);
    if(s == "horizontal" || s == "landscape" || s == "h" || s == "l"){
        Engine.EventManager.orientationChange.mode = "horizontal";
    }
    else if(s == "vertical" || s == "portrait" || s == "v" || s == "p"){
        Engine.EventManager.orientationChange.mode = "vertical";
    }
    if(w > h){ Engine.EventManager.orientationChange.currOrientation = "horizontal"; }
    else{      Engine.EventManager.orientationChange.currOrientation = "vertical"; }
    Engine.EventManager.doWindowRotation();
}
Engine.requestPointerLock = function(){
    Engine.EventManager.pointerLock.desired = true;
}
Engine.resize = function(width,height){
    Engine.canvas.width = width;
    Engine.canvas.height = height;
    Engine.canvasEventCatcher.style.width = width + "px";
    Engine.canvasEventCatcher.style.height = height + "px";
    gl.viewport(0, 0, width, height);
    for (var key in Engine.ResourceManager.scenes) {
        var scene = Engine.ResourceManager.scenes[key];
        for (var key1 in scene.cameras) {
            scene.cameras[key1].resize(width,height);
        }
    }
}
Engine.update = function(dt){
    Engine.Game.update(dt);

    //cleanup memory
    for(var key in Engine.scene.objects){
        if(Engine.scene.objects[key].hasOwnProperty('_isToBeDestroyed')){
            Engine.scene.objects[key]._free();
            delete Engine.scene.objects[key];
        }
    }

    for (var key in Engine.scene.lights) {
        Engine.scene.lights[key].update(dt);
    }
    for (var key in Engine.scene.objects) {
        Engine.scene.objects[key].update(dt);
    }
    for (var key in Engine.scene.cameras) {
        Engine.scene.cameras[key].update(dt);
    }
    for (var key in Engine.ResourceManager.sounds) {
        Engine.ResourceManager.sounds[key].update(dt);
    }
    Engine.EventManager.update(dt);
    Engine.PhysicsManager.update(dt);
}
Engine.render = function(){
    Engine.RenderManager.render();
}

Engine.isKeyDown = function(key){ return Engine.EventManager.isKeyDown(key); }
Engine.isKeyUp = function(key){ return Engine.EventManager.isKeyUp(key); }
<|endoftext|>


<commit_before>// Reusable treemap visualization
// Ishan Saksena

var treemap = function () {
    // Setting defaults
    var margin = {
        top: 40,
        right: 10,
        bottom: 10,
        left: 10
    },
        width = 960,
        height = 500,
        drawWidth = width - margin.left - margin.right,
        drawHeight = height - margin.top - margin.bottom,
        measure = 'fertility_rate'; // variable to visualize

    // Function returned by treemap
    var chart = function (nestedData) {

        // Append a wrapper div for the chart
        var div = d3.select('#treemap')
            .append("div")
            .attr('height', height)
            .attr('width', width)
            .style("left", margin.left + "px")
            .style("top", margin.top + "px");

        /* ********************************** Create hierarchical data structure & treemap function  ********************************** */

        // Define a hierarchy for your data
        var root = d3.hierarchy({
            values: nestedData
        }, function (d) {
            return d.values;
        });

        // Create a *treemap function* that will compute your layout given your data structure
        var treemap = d3.treemap() // function that returns a function!
            .size([width, height]) // set size: scaling will be done internally
            .round(true)
            .tile(d3.treemapResquarify)
            .padding(0);

        /* ********************************** Create an ordinal color scale  ********************************** */

        // Get list of regions for colors
        var regions = nestedData.map(function (d) {
            return d.key;
        });

        // Set an ordinal scale for colors
        var colorScale = d3.scaleOrdinal().domain(regions).range(d3.schemeCategory10);

        // Redefine which value you want to visualize in your data by using the `.sum()` method
        root.sum(function (d) {
            return +d[measure];
        });

        // (Re)build your treemap data structure by passing your `root` to your `treemap` function
        treemap(root);

        // Bind your data to a selection of elements with class node
        // The data that you want to join is array of elements returned by `root.leaves()`
        var nodes = div.selectAll(".node").data(root.leaves());

        // Enter and append elements, then position them using the appropriate *styles*
        nodes.enter()
            .append("div")
            .text(function (d) {
                return d.data.country_code;
            })
            .merge(nodes)
            .attr('class', 'node')
            .transition().duration(1500)
            .style("left", function (d, i) {
                return d.x0 + "px";
            })
            .style("top", function (d) {
                return d.y0 + "px";
            })
            .style('width', function (d) {
                return d.x1 - d.x0 + 'px';
            })
            .style("height", function (d) {
                return d.y1 - d.y0 + "px";
            })
            .style("background", function (d, i) {
                return colorScale(d.data.region);
            });
    };

    // Getter/setter methods
    chart.height = function (value) {
        if (!arguments.length) return height;
        height = value;
        drawHeight = height - margin.top - margin.bottom;
        return chart;
    };

    chart.width = function (value) {
        if (!arguments.length) return width;
        width = value;
        drawWidth = width - margin.left - margin.right;
        return chart;
    };

    chart.measure = function (value) {
        if (!arguments.length) return measure;
        measure = value;
        return chart;
    };

    return chart;
};

// Render treemap
$(function () {
    // Prep data
    d3.csv('data/treedata.csv', function (error, data) {
        var tree = treemap().width(960).height(500);
        // Nest your data *by region* using d3.nest()
        var nestedData = d3.nest()
            .key(function (d) {
                return d.region;
            })
            .entries(data);

        tree(nestedData);
    });
});
<commit_msg>Using yearbook data for treemap<commit_after>// Reusable treemap visualization
// Ishan Saksena

var treemap = function () {
    // Setting defaults
    var margin = {
        top: 40,
        right: 10,
        bottom: 10,
        left: 10
    },
        width = 960,
        height = 500,
        drawWidth = width - margin.left - margin.right,
        drawHeight = height - margin.top - margin.bottom,
        measure = 'Total'; // variable to visualize

    // Function returned by treemap
    var chart = function (nestedData) {

        // Append a wrapper div for the chart
        var div = d3.select('#treemap')
            .append("div")
            .attr('height', height)
            .attr('width', width)
            .style("left", margin.left + "px")
            .style("top", margin.top + "px");

        /* ********************************** Create hierarchical data structure & treemap function  ********************************** */

        // Define a hierarchy for your data
        var root = d3.hierarchy({
            values: nestedData
        }, function (d) {
            return d.values;
        });

        // Create a *treemap function* that will compute your layout given your data structure
        var treemap = d3.treemap() // function that returns a function!
            .size([width, height]) // set size: scaling will be done internally
            .round(true)
            .tile(d3.treemapResquarify)
            .padding(0);

        /* ********************************** Create an ordinal color scale  ********************************** */

        // Get list of regions for colors
        var regions = nestedData.map(function (d) {
            return d.key;
        });

        // Set an ordinal scale for colors
        var colorScale = d3.scaleOrdinal().domain(regions).range(d3.schemeCategory10);

        // Redefine which value you want to visualize in your data by using the `.sum()` method
        root.sum(function (d) {
            return +d[measure];
        });

        // (Re)build your treemap data structure by passing your `root` to your `treemap` function
        treemap(root);

        // Bind your data to a selection of elements with class node
        // The data that you want to join is array of elements returned by `root.leaves()`
        var nodes = div.selectAll(".node").data(root.leaves());

        // Enter and append elements, then position them using the appropriate *styles*
        nodes.enter()
            .append("div")
            .text(function (d) {
                return d.data.ISO3;
            })
            .merge(nodes)
            .attr('class', 'node')
            .transition().duration(1500)
            .style("left", function (d, i) {
                return d.x0 + "px";
            })
            .style("top", function (d) {
                return d.y0 + "px";
            })
            .style('width', function (d) {
                return d.x1 - d.x0 + 'px';
            })
            .style("height", function (d) {
                return d.y1 - d.y0 + "px";
            })
            .style("background", function (d, i) {
                return colorScale(d.data.Continent);
            });
    };

    // Getter/setter methods
    chart.height = function (value) {
        if (!arguments.length) return height;
        height = value;
        drawHeight = height - margin.top - margin.bottom;
        return chart;
    };

    chart.width = function (value) {
        if (!arguments.length) return width;
        width = value;
        drawWidth = width - margin.left - margin.right;
        return chart;
    };

    chart.measure = function (value) {
        if (!arguments.length) return measure;
        measure = value;
        return chart;
    };

    return chart;
};

// Render treemap
$(function () {
    // Prep data
    //d3.csv('data/treedata.csv', function (error, data) {
    d3.csv('data/prep/table_11region.csv', function (error, data) {
        var tree = treemap().width(960).height(500);
        // Nest your data *by region* using d3.nest()
        var nestedData = d3.nest()
            .key(function (d) {
                return d.Continent;
            })
            .entries(data);

        tree(nestedData);
    });
});
<|endoftext|>


<commit_before>/*!
* Turkuaz Framework v1.0
* www.turkuazcss.com
*/

/*!
*    Turkuaz Framework - JavaScript Kod Duzeni
*
*   1. Form
*   2. Menu
*   3. Notlar
*
*/

/* ============= 1. Form */

// Radio ve checkbox haric diger inputlari ve textarea'yi degiskene atar.
$formEtiketleri = "input[type=text],input[type=password],input[type=email],input[type=url],input[type=date],input[type=tel],input[type=number],input[type=search],textarea";

// Inputlarin Labellerinin Ilk Hareketleri
$($formEtiketleri).focus(function(){
    //inputlara ve textarea'ya imlec geldiginde bu tag'lara 'aktif dolu' sinifini ekler ve labeller uste gecer.
    $(this).addClass("aktif dolu");
});

// Input Labellerinin Sonraki Hareketleri
$($formEtiketleri).focusout(function(){
    //inputtan veya textarea'dan ayrilindiginda icerisinde yazi yoksa 'dolu' sinifini kaldirir ve label alta gecer, yazi varsa kaldirmaz.
    if($(this).val() == ""){
        $(this).removeClass("dolu");
    }
    //inputtan veya textarea'dan ayrilindiginda aktif class'ini kaldirir.
    $(this).removeClass("aktif");
});

/* ============= 2. Menu */

// Menuyu Acar
$("nav.menu>img.logo").click(function(){
    //mobil menuyu acmak icin butona basilinca butonu gizler.
    $(this).hide();
    //menuyu 0 left'e getirir (eskisi left:-240px) yani mobil menu gorunur.
    $(this).parent().animate({left:"0"});
    //body'e karart divini ekler ve menu harici her yeri karartir.
    $("body").append("

");
});

// Menuyu Gizler
$("body").on('click', '.karart', function(){
    //menuyu 240px sola tasir yani gizler.
    $("nav.menu").animate({left:"-240px"});
    //karart divini kaldirir.
    $(".karart").remove();
    //400 milisaniye sonra logoyu gosterir.
    $("nav.menu>img.logo").delay(400).fadeIn();
});

// Acilir Menulerin Oklari
//menudeki li'lerin icerisinde alt menu var ise o li'ye 'acilir' class'ini ekler ve sagina minik bir ok gelir.
$("nav.menu ul li").find("ul li a").parent().parent().parent().addClass("acilir");

// Akordiyon Menu
$("body").on('click', 'nav.menu.mobil ul li.acilir', function(){
    //alt menudeki link sayisina gore ul'nin yuksekligini hesaplar.
    var yukseklik = $(this).find("li").length * 50;
    //alt menuye yukseklik degerini verir.
    $(this).find("ul").css({
        "height": yukseklik + "px"
        //500ms hizinda acilir menuyu gorunur yapar, diger acilir menuleri gizler.
    }).slideToggle("500").parent().siblings(".acilir").find("ul:visible").slideToggle("500");
});

// Mobil Menu
function mobil(){
    if ($(window).width() <= 1000) {
        //cozunurluk 1000px'in altina indiginde menuye mobil sinifini ekler.
        $("nav.menu").addClass("mobil");
    }
    else {
        //cozunurluk 1000px'in ustunde mobil sinifini kaldirir.
        $("nav.menu").removeClass("mobil");
    }
    $("nav.menu ul li.acilir ul").each(function(){
        //cozunurluk degistiginde acilir menuler gizlenir.
        $(this).hide("600");
    });
}

//cozunurluk her degistiginde mobil fonksiyonunu calistir.
mobil(); $(window).resize(function() { mobil(); });

/* ============= 3. Notlar */

// Notlara Kapatma Butonu Getirir
//not class'ina ait tag'lari kapatmak icin sag ustune 'x' butonunu ekler.
$("div.not").append("×");

// Notlarin Kaldirilmasi
//'x' butonuna basinca o notu kaldirir.
$("div.not span.kaldir").click(function(){
    $(this).parent().remove();
});
<commit_msg>Tab Menu Js<commit_after>/*!
* Turkuaz Framework v1.0
* www.turkuazcss.com
*/

/*!
*    Turkuaz Framework - JavaScript Kod Duzeni
*
*   1. Form
*   2. Menu
*   3. Notlar
*
*/

/* ============= 1. Form */

// Radio ve checkbox haric diger inputlari ve textarea'yi degiskene atar.
$formEtiketleri = "input[type=text],input[type=password],input[type=email],input[type=url],input[type=date],input[type=tel],input[type=number],input[type=search],textarea";

// Inputlarin Labellerinin Ilk Hareketleri
$($formEtiketleri).focus(function(){
    //inputlara ve textarea'ya imlec geldiginde bu tag'lara 'aktif dolu' sinifini ekler ve labeller uste gecer.
    $(this).addClass("aktif dolu");
});

// Input Labellerinin Sonraki Hareketleri
$($formEtiketleri).focusout(function(){
    //inputtan veya textarea'dan ayrilindiginda icerisinde yazi yoksa 'dolu' sinifini kaldirir ve label alta gecer, yazi varsa kaldirmaz.
    if($(this).val() == ""){
        $(this).removeClass("dolu");
    }
    //inputtan veya textarea'dan ayrilindiginda aktif class'ini kaldirir.
    $(this).removeClass("aktif");
});

/* ============= 2. Menu */

// Menuyu Acar
$("nav.menu>img.logo").click(function(){
    //mobil menuyu acmak icin butona basilinca butonu gizler.
    $(this).hide();
    //menuyu 0 left'e getirir (eskisi left:-240px) yani mobil menu gorunur.
    $(this).parent().animate({left:"0"});
    //body'e karart divini ekler ve menu harici her yeri karartir.
    $("body").append("

");
});

// Menuyu Gizler
$("body").on('click', '.karart', function(){
    //menuyu 240px sola tasir yani gizler.
    $("nav.menu").animate({left:"-240px"});
    //karart divini kaldirir.
    $(".karart").remove();
    //400 milisaniye sonra logoyu gosterir.
    $("nav.menu>img.logo").delay(400).fadeIn();
});

// Acilir Menulerin Oklari
//menudeki li'lerin icerisinde alt menu var ise o li'ye 'acilir' class'ini ekler ve sagina minik bir ok gelir.
$("nav.menu ul li").find("ul li a").parent().parent().parent().addClass("acilir");

// Akordiyon Menu
$("body").on('click', 'nav.menu.mobil ul li.acilir', function(){
    //alt menudeki link sayisina gore ul'nin yuksekligini hesaplar.
    var yukseklik = $(this).find("li").length * 50;
    //alt menuye yukseklik degerini verir.
    $(this).find("ul").css({
        "height": yukseklik + "px"
        //500ms hizinda acilir menuyu gorunur yapar, diger acilir menuleri gizler.
    }).slideToggle("500").parent().siblings(".acilir").find("ul:visible").slideToggle("500");
});

// Mobil Menu
function mobil(){
    if ($(window).width() <= 1000) {
        //cozunurluk 1000px'in altina indiginde menuye mobil sinifini ekler.
        $("nav.menu").addClass("mobil");
    }
    else {
        //cozunurluk 1000px'in ustunde mobil sinifini kaldirir.
        $("nav.menu").removeClass("mobil");
    }
    $("nav.menu ul li.acilir ul").each(function(){
        //cozunurluk degistiginde acilir menuler gizlenir.
        $(this).hide("600");
    });
}

//cozunurluk her degistiginde mobil fonksiyonunu calistir.
mobil(); $(window).resize(function() { mobil(); });

/* ============= 3. Notlar */

// Notlara Kapatma Butonu Getirir
//not class'ina ait tag'lari kapatmak icin sag ustune 'x' butonunu ekler.
$("div.not").append("×");

// Notlarin Kaldirilmasi
//'x' butonuna basinca o notu kaldirir.
$("div.not span.kaldir").click(function(){
    $(this).parent().remove();
});

$(".tab-icerik").hide();
            $(".tab-icerik:first").show();

            $(".tab-no").click(function(){

                var sira = $(this).index();

                $(".tab-no").removeClass("aktif");

                $(this).addClass("aktif");

                $(".tab-icerik").hide();
                $(".tab-icerik:eq("+ sira +")").show();

                return false;
            });

        });
<|endoftext|>


<commit_before>/* global SolidAuthClient, SolidUtils, $rdf */

TweeFiUtils = {

    TweetUri: class {
        constructor(value) {
            // Regex-pattern to check URLs against:
            // https://twitter.com/<twitteruser>/status/<long number>
            var urlRegex = /^https:\/\/twitter.com\/([a-zA-Z _.,!"'/$]+)\/status\/([0-9]*$)/;
            this.match = urlRegex.exec(value);
            this.value = value;
        }

        isValid() {
            return this.match !== null;
        }

        getUser() {
            return this.match[1];
        }

        getStatus() {
            return this.match[2];
        }

        toString() {
            return this.value;
        }
    },
    updateLoginInfo() {
        SolidAuthClient.currentSession().then(function (session) {
            if (session) {
                var user = $rdf.sym(session.webId);
                SolidUtils.rdfFetch(session.webId).then(function (response) {
                    var name = response.graph.any(user, SolidUtils.vocab.foaf('name'));
                    $("#loginInfo").html("Logged in as:");
                    $("#loginName").show();
                    $("#loginName").html("" + name + "");
                    $("#logoutButton").show();
                    $("#loginButton").hide();
                });
            } else {
                $("#loginInfo").html("Not logged in");
                $("#loginName").hide();
                $("#logoutButton").hide();
                $("#loginButton").show();
            }
        });
    },

};

SolidUtils.postLoginAction = TweeFiUtils.updateLoginInfo;

$(function () {
    TweeFiUtils.updateLoginInfo();

    $('#logoutButton').on('click', function () {
        localStorage.clear();
        TweeFiUtils.updateLoginInfo();
    });

    $('#loginButton').on('click', function () {
        SolidUtils.login().catch(function (error) {
            console.log("Couldn't log in: " + error);
        });
    });
});
<commit_msg>Spaces are not okay in twitter-usernames, but digits are<commit_after>/* global SolidAuthClient, SolidUtils, $rdf */

TweeFiUtils = {

    TweetUri: class {
        constructor(value) {
            // Regex-pattern to check URLs against:
            // https://twitter.com/<twitteruser>/status/<long number>
            var urlRegex = /^https:\/\/twitter.com\/([a-zA-Z0-9_.,!"'/$]+)\/status\/([0-9]*$)/;
            this.match = urlRegex.exec(value);
            this.value = value;
        }

        isValid() {
            return this.match !== null;
        }

        getUser() {
            return this.match[1];
        }

        getStatus() {
            return this.match[2];
        }

        toString() {
            return this.value;
        }
    },
    updateLoginInfo() {
        SolidAuthClient.currentSession().then(function (session) {
            if (session) {
                var user = $rdf.sym(session.webId);
                SolidUtils.rdfFetch(session.webId).then(function (response) {
                    var name = response.graph.any(user, SolidUtils.vocab.foaf('name'));
                    $("#loginInfo").html("Logged in as:");
                    $("#loginName").show();
                    $("#loginName").html("" + name + "");
                    $("#logoutButton").show();
                    $("#loginButton").hide();
                });
            } else {
                $("#loginInfo").html("Not logged in");
                $("#loginName").hide();
                $("#logoutButton").hide();
                $("#loginButton").show();
            }
        });
    },

};

SolidUtils.postLoginAction = TweeFiUtils.updateLoginInfo;

$(function () {
    TweeFiUtils.updateLoginInfo();

    $('#logoutButton').on('click', function () {
        localStorage.clear();
        TweeFiUtils.updateLoginInfo();
    });

    $('#loginButton').on('click', function () {
        SolidUtils.login().catch(function (error) {
            console.log("Couldn't log in: " + error);
        });
    });
});
<|endoftext|>


<commit_before>/**
JavaScript Game framework for beginner.

oosamanet@gmail.com

*/
var unitaro={};

unitaro.scaler=function(id){
  var scale = function () {
    var container = document.querySelector('#'+id+'-canvas');
    var containerWidth = container.offsetWidth;
    var containerHeight = container.offsetHeight;

    var viewportWidth = document.documentElement.clientWidth;
    var viewportHeight = document.documentElement.clientHeight;

    var scaleWidth = viewportWidth / containerWidth;
    var scaleHeight = viewportHeight / containerHeight;
    var scaleBoth = (scaleHeight < scaleWidth) ? scaleHeight : scaleWidth;

    var newContainerWidth = containerWidth * scaleBoth;
    var newContainerHeight = containerHeight * scaleBoth;

    var left = (viewportWidth - newContainerWidth) / 2;
    left = parseInt(left * (1 / scaleBoth), 10);

    var top = (viewportHeight - newContainerHeight) / 2;
    top = parseInt(top * (1 / scaleBoth), 10);

    // scale the whole container
    var transform = 'scale(' + scaleBoth + ',' + scaleBoth + ') translate(' + left + 'px, ' + top + 'px)';
    container.style['-webkit-transform-origin'] = 'top left 0';
    container.style['-webkit-transform'] = transform;
    container.style['transform-origin'] = 'top left 0';
    container.style['transform'] = transform;
    unitaro.scale=scaleBoth;
    unitaro.offset=[left*scaleBoth,top*scaleBoth];
  };

  window.onresize = scale;
  scale();
};

unitaro.dib={
  init: function(w,h,target){
    this.target=target;
    if (!this.target){
      this.target='unitaro-world';
    }
    var world = document.getElementById(this.target);
    if (!world) {
      world = document.createElement('div');
      world.id = this.target;
      document.body.appendChild(world);
    }
    this.canvas = document.createElement('canvas');
    this.canvas.id=this.target+"-canvas";
    this.canvas.width = w;
    this.canvas.height = h;
    world.appendChild(this.canvas);
    this.ctx = this.canvas.getContext('2d');
    this.ctx.textAlign = "center";
    this.ctx.font = "12px";
  },
  clear: function(x1,y1,w,h){
    this.ctx.clearRect(x1,y1,w,h);
  },
  box: function(x1,y1,w,h,color){
    if (color!=undefined){
      this.ctx.fillStyle = color;
    }
    this.ctx.fillRect(x1,y1,w,h);
  },
  textout: function(x1,y1,text,color,w){
    if (color!=undefined){
      this.ctx.fillStyle = color;
    }
    this.ctx.fillText(text,x1,y1,w);
  },
  sprites: {},
};

unitaro.TaskManager={
  task_list: [],
  type_list: {},
  add_task: function(task){
    this.task_list.push(task);
  },
  add_type: function(type,task){
    if (!this.type_list[type]){
      this.type_list[type]=[];
    }
    this.type_list[type].push(task);
  },
  del_type: function(type,task){
    if (!this.type_list[type]){
      this.type_list[type]=[];
    }
    this.delete_if(task,this.type_list[type]);
  },
  clear: function(){
    this.task_list=[];
    this.type_list={};
  },
  hitcheck_all: function(t1,t2){
    if (! this.type_list[t1] || ! this.type_list[t2]){
       return;
    }
    for (var i in this.type_list[t1]){
      var task1 = this.type_list[t1][i];
      var x1_1=task1.x-task1.w/2;
      var x1_2=x1_1+task1.w;
      var y1_1=task1.y-task1.h/2;
      var y1_2=y1_1+task1.h;
      var flag=false;
      for (var j in this.type_list[t2]){
        var task2 = this.type_list[t2][j];
        var x2_1=task2.x-task2.w/2;
        var x2_2=x2_1+task2.w;
        var y2_1=task2.y-task2.h/2;
        var y2_2=y2_1+task2.h;
        if (x2_2 <= x1_1 || x1_2 <= x2_1 ||
            y2_2 <= y1_1 || y1_2 <= y2_1){
           continue;
        }
        if (typeof task2.onhit == "function"){
          task2.onhit();
        }
        flag=true;
      }
      if (!flag){
        continue;
      }
      if (typeof task1.onhit == "function"){
        task1.onhit();
      }
    }
  },
  delete_if:function(target,array1){
    array1.some(function(v, i){
      if (v==target){
        array1.splice(i,1);
      }
    });
  },
  update_all: function(){
    var delete_list=[];
    for (var i in this.task_list){
      var t=this.task_list[i];
      if (t===undefined){
        continue;
      }
      t.age++;
      var age=t.age;
      t.update(age);
      if (!t.live){
        delete_list.push(t);
      }
    }
    for (var i in delete_list){
      this.delete_if(delete_list[i],this.task_list);
      for (var j in this.type_list){
        this.delete_if(delete_list[i],this.type_list[j]);
      }
    }
  },
  is_inside: function(src,x,y,w,h){
    if (w===undefined){
      w=1;
      h=1;
    }
    return (src.x===undefined) || (
      src.x-src.w/2 < x+w/2 &&
      src.x+src.w/2 > x-w/2 &&
      src.y-src.h/2 < y+h/2 &&
      src.y+src.h/2 > y-h/2
    );
  },
  call_all: function(mes){
    for (var i in this.task_list){
      var t=this.task_list[i];
      if ("function" == typeof(t[mes])){
        t[mes].apply(t,Array.prototype.slice.call(arguments,1));
      }
    }

  },
  call_all_with_hitcheck: function(mes,x,y){
    for (var i in this.task_list){
      var t=this.task_list[i];
      if (!this.is_inside(t,x,y)){
        continue;
      }
      if ("function" == typeof(t[mes])){
        t[mes].apply(t,Array.prototype.slice.call(arguments,1));
      }
    }

  },
  draw_all: function(){
    this.call_all('draw');
  },
};

unitaro.Task=function(task){
  this.timer=0;
  this.type='';
  this.age=0;
  this.live=true;
  this.init=function(){};
  this.update=function(){};
  this.draw=function(){
    if (this.w > 0){
      unitaro.dib.box(this.x-this.w/2,this.y-this.h/2,this.w,this.h,this.color);
    }
  };
  for (i in task){
    this[i]=task[i];
  }

  unitaro.TaskManager.add_task(this);
  this.init.apply(this,Array.prototype.slice.call(arguments,1));
};
unitaro.Task.prototype={
  stop: function(){
    this.live=false;
    unitaro.TaskManager.del_type(this.type,this);
  },
  set_type: function(type){
    this.type=type;
    unitaro.TaskManager.add_type(type,this);
  },
  clear: function(){
    unitaro.TaskManager.clear();
  },
  onhit: function(){
    console.dir("BOMB "+this.type+" "+this.x+","+this.y);
    this.stop();
  }
};

unitaro.App=function(app){
  var self=this;
  self.init = function(){};
  self.update = function(){};
  self.draw = function(){};
  for (i in app){
    self[i]=app[i];
  }
  self.fps = self.fps || 20;

  unitaro.dib.init(self.WIDTH,self.HEIGHT,self.target);

  var _click = (window.ontouchstart === undefined)? 'click' : 'touchstart';
  window.addEventListener(_click,function(e){
    var x=e.pageX || e.touches[0].pageX;
    var y=e.pageY || e.touches[0].pageY;
    if (unitaro.scaler && unitaro.offset){
      x=x-unitaro.offset[0];
      y=y-unitaro.offset[1];
      x/=unitaro.scale;
      y/=unitaro.scale;
    }
    unitaro.TaskManager.call_all_with_hitcheck("onclick",x,y);
    if (self.onclick){
      self.onclick(x,y);
    }
  });

  var age=0;
  var loop = function(){
    setTimeout(function(){
      if (age==0){
        self.init();
      }
      self.update(age);

      unitaro.TaskManager.update_all();
      unitaro.TaskManager.draw_all();

      loop();
      age++;
    },1000/self.fps);
  };
  loop();
  if (!self.target){
    unitaro.scaler(unitaro.dib.target);
  }
};
<commit_msg>add clearTimeout function<commit_after>/**
JavaScript Game framework for beginner.

oosamanet@gmail.com

*/
var unitaro={};

unitaro.scaler=function(id){
  var scale = function () {
    var container = document.querySelector('#'+id+'-canvas');
    var containerWidth = container.offsetWidth;
    var containerHeight = container.offsetHeight;

    var viewportWidth = document.documentElement.clientWidth;
    var viewportHeight = document.documentElement.clientHeight;

    var scaleWidth = viewportWidth / containerWidth;
    var scaleHeight = viewportHeight / containerHeight;
    var scaleBoth = (scaleHeight < scaleWidth) ? scaleHeight : scaleWidth;

    var newContainerWidth = containerWidth * scaleBoth;
    var newContainerHeight = containerHeight * scaleBoth;

    var left = (viewportWidth - newContainerWidth) / 2;
    left = parseInt(left * (1 / scaleBoth), 10);

    var top = (viewportHeight - newContainerHeight) / 2;
    top = parseInt(top * (1 / scaleBoth), 10);

    // scale the whole container
    var transform = 'scale(' + scaleBoth + ',' + scaleBoth + ') translate(' + left + 'px, ' + top + 'px)';
    container.style['-webkit-transform-origin'] = 'top left 0';
    container.style['-webkit-transform'] = transform;
    container.style['transform-origin'] = 'top left 0';
    container.style['transform'] = transform;
    unitaro.scale=scaleBoth;
    unitaro.offset=[left*scaleBoth,top*scaleBoth];
  };

  window.onresize = scale;
  scale();
};

unitaro.dib={
  init: function(w,h,target){
    this.target=target;
    if (!this.target){
      this.target='unitaro-world';
    }
    var world = document.getElementById(this.target);
    if (!world) {
      world = document.createElement('div');
      world.id = this.target;
      document.body.appendChild(world);
    }
    this.canvas = document.createElement('canvas');
    this.canvas.id=this.target+"-canvas";
    this.canvas.width = w;
    this.canvas.height = h;
    world.appendChild(this.canvas);
    this.ctx = this.canvas.getContext('2d');
    this.ctx.textAlign = "center";
    this.ctx.font = "12px";
  },
  clear: function(x1,y1,w,h){
    this.ctx.clearRect(x1,y1,w,h);
  },
  box: function(x1,y1,w,h,color){
    if (color!=undefined){
      this.ctx.fillStyle = color;
    }
    this.ctx.fillRect(x1,y1,w,h);
  },
  textout: function(x1,y1,text,color,w){
    if (color!=undefined){
      this.ctx.fillStyle = color;
    }
    this.ctx.fillText(text,x1,y1,w);
  },
  sprites: {},
};

unitaro.TaskManager={
  task_list: [],
  type_list: {},
  add_task: function(task){
    this.task_list.push(task);
  },
  add_type: function(type,task){
    if (!this.type_list[type]){
      this.type_list[type]=[];
    }
    this.type_list[type].push(task);
  },
  del_type: function(type,task){
    if (!this.type_list[type]){
      this.type_list[type]=[];
    }
    this.delete_if(task,this.type_list[type]);
  },
  clear: function(){
    this.task_list=[];
    this.type_list={};
  },
  hitcheck_all: function(t1,t2){
    if (! this.type_list[t1] || ! this.type_list[t2]){
       return;
    }
    for (var i in this.type_list[t1]){
      var task1 = this.type_list[t1][i];
      var x1_1=task1.x-task1.w/2;
      var x1_2=x1_1+task1.w;
      var y1_1=task1.y-task1.h/2;
      var y1_2=y1_1+task1.h;
      var flag=false;
      for (var j in this.type_list[t2]){
        var task2 = this.type_list[t2][j];
        var x2_1=task2.x-task2.w/2;
        var x2_2=x2_1+task2.w;
        var y2_1=task2.y-task2.h/2;
        var y2_2=y2_1+task2.h;
        if (x2_2 <= x1_1 || x1_2 <= x2_1 ||
            y2_2 <= y1_1 || y1_2 <= y2_1){
           continue;
        }
        if (typeof task2.onhit == "function"){
          task2.onhit();
        }
        flag=true;
      }
      if (!flag){
        continue;
      }
      if (typeof task1.onhit == "function"){
        task1.onhit();
      }
    }
  },
  delete_if:function(target,array1){
    array1.some(function(v, i){
      if (v==target){
        array1.splice(i,1);
      }
    });
  },
  update_all: function(){
    var delete_list=[];
    for (var i in this.task_list){
      var t=this.task_list[i];
      if (t===undefined){
        continue;
      }
      t.age++;
      var age=t.age;
      t.update(age);
      if (!t.live){
        delete_list.push(t);
      }
    }
    for (var i in delete_list){
      this.delete_if(delete_list[i],this.task_list);
      for (var j in this.type_list){
        this.delete_if(delete_list[i],this.type_list[j]);
      }
    }
  },
  is_inside: function(src,x,y,w,h){
    if (w===undefined){
      w=1;
      h=1;
    }
    return (src.x===undefined) || (
      src.x-src.w/2 < x+w/2 &&
      src.x+src.w/2 > x-w/2 &&
      src.y-src.h/2 < y+h/2 &&
      src.y+src.h/2 > y-h/2
    );
  },
  call_all: function(mes){
    for (var i in this.task_list){
      var t=this.task_list[i];
      if ("function" == typeof(t[mes])){
        t[mes].apply(t,Array.prototype.slice.call(arguments,1));
      }
    }

  },
  call_all_with_hitcheck: function(mes,x,y){
    for (var i in this.task_list){
      var t=this.task_list[i];
      if (!this.is_inside(t,x,y)){
        continue;
      }
      if ("function" == typeof(t[mes])){
        t[mes].apply(t,Array.prototype.slice.call(arguments,1));
      }
    }

  },
  draw_all: function(){
    this.call_all('draw');
  },
};

unitaro.Task=function(task){
  this.timer=0;
  this.type='';
  this.age=0;
  this.live=true;
  this.init=function(){};
  this.update=function(){};
  this.draw=function(){
    if (this.w > 0){
      unitaro.dib.box(this.x-this.w/2,this.y-this.h/2,this.w,this.h,this.color);
    }
  };
  for (i in task){
    this[i]=task[i];
  }

  unitaro.TaskManager.add_task(this);
  this.init.apply(this,Array.prototype.slice.call(arguments,1));
};
unitaro.Task.prototype={
  stop: function(){
    this.live=false;
    unitaro.TaskManager.del_type(this.type,this);
  },
  set_type: function(type){
    this.type=type;
    unitaro.TaskManager.add_type(type,this);
  },
  clear: function(){
    unitaro.TaskManager.clear();
  },
  onhit: function(){
    console.dir("BOMB "+this.type+" "+this.x+","+this.y);
    this.stop();
  }
};

unitaro.App=function(app){
  var self=this;
  self.init = function(){};
  self.update = function(){};
  self.draw = function(){};
  for (i in app){
    self[i]=app[i];
  }
  self.fps = self.fps || 20;

  unitaro.dib.init(self.WIDTH,self.HEIGHT,self.target);

  var _click = (window.ontouchstart === undefined)? 'click' : 'touchstart';
  window.addEventListener(_click,function(e){
    var x=e.pageX || e.touches[0].pageX;
    var y=e.pageY || e.touches[0].pageY;
    if (unitaro.scaler && unitaro.offset){
      x=x-unitaro.offset[0];
      y=y-unitaro.offset[1];
      x/=unitaro.scale;
      y/=unitaro.scale;
    }
    unitaro.TaskManager.call_all_with_hitcheck("onclick",x,y);
    if (self.onclick){
      self.onclick(x,y);
    }
  });

  var age=0;
  var loop = function(){
    clearTimeout(self.timer);
    self.timer=setTimeout(function(){
      if (age==0){
        self.init();
      }
      self.update(age);

      unitaro.TaskManager.update_all();
      unitaro.TaskManager.draw_all();

      loop();
      age++;
    },1000/self.fps);
  };
  loop();
  if (!self.target){
    unitaro.scaler(unitaro.dib.target);
  }
};
<|endoftext|>


<commit_before>var margin = {top: 50, right: 62, bottom: 100, left: 50},
    dim = Math.min(parseInt(d3.select("#chart").style("width")), parseInt(d3.select("#chart").style("height"))),
    width = dim - margin.left - margin.right,
    height = dim - margin.top - margin.bottom;
//width = 700 - margin.left - margin.right,
//height = 700 - margin.top - margin.bottom;

var parseDate = d3.time.format("%Y").parse;

// escalas
var x = d3.time.scale().range([0, width]);
//var y = d3.scale.log().range([height, 0]); Logaritmica, se necessário
var y = d3.scale.linear().range([height, 40]);

// eixos
var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom")
    .ticks(7)
    .innerTickSize(-height)
    .outerTickSize(0)
    .tickPadding(10);

var yAxis = d3.svg.axis().scale(y)
    .orient("left")
    .ticks(6, "%")
    .tickSize(3, 0)
    .innerTickSize(-width)
    .outerTickSize(0)
    .tickPadding(15);

// linhas do gráfico
var valueline = d3.svg.line()
    .x(function (d) {
        return x(d.date);
    })
    // se usar escala log, cria o valor referência
    .y(function (d) {
        return y(d.value + 1);
    });

var nota = d3.select(".nota")
    .attr("class", "nota")
    .style("opacity", "0");

// acrescenta a canvas de svg
var svg = d3.select("#chart")
    .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform",
        "translate(" + margin.left + "," + margin.top + ")");

// puxa os dados da tabela
d3.tsv("dados/reject.tsv", function (error, data) {
    data.forEach(function (d) {
        d.date = parseDate(d.date);
        d.value = +d.value;
    });

    // o range dos dados
    x.domain(d3.extent(data, function (d) {
        return d.date;
    }));
    y.domain([1, d3.max(data, function (d) {
        return d.value;
    })]);

    // colocar os paises em nest
    var dataNest = d3.nest()
        .key(function (d) {
            return d.key;
        })
        .entries(data);

    var piaui = ["#7bad65", "#777", "#5ea4ab", "#eabf54", "#d94f30"]

    var color = d3.scale.ordinal()
        .range(piaui)

    legendSpace = width / dataNest.length; // espaçamento da legenda

    // utiliza as categorias
    dataNest.forEach(function (d, i) {

        svg.append("path")
            .attr("class", "line")
            .style("stroke", function () {
                return d.color = color(d.key);
            })
            //acrescenta linha dashed pra média
            .style('stroke-dasharray', function () {
                return d.key === 'Média' ? '4 4' : '';
            })
            .style('opacity', function () {
                if (d.key === 'Rússia') return '.1';
                if (d.key === 'China') return '.1'
                if (d.key === 'Índia') return '.1'
                if (d.key === 'Média') return '.1'
            })
            .attr("id", 'tag' + d.key.replace(/\s+/g, '')) // aplicar classe das linhas
            .attr("d", valueline(d.values))
            .append("title");

        // legenda retangular
        //svg.append("rect")
            //.attr("x", (legendSpace / 8) + i * legendSpace) // space legend
            //.attr("class", "legend")
            //.style("text-anchor", "end")
            //.attr("y", -38)
            //.attr("width", 8)
            //.attr("height", 8)
            //.style("fill", function() { return d.color = color(d.key); });

        //linhas para anos
        //svg.selectAll("line").data(data).enter().append("line")
        //.attr('x1',function(d) { return x(d.date); })
        //.attr('y1',function(d) { return y(0); })
        //.attr('x2',function(d) { return x(d.date); })
        //.attr('y2',function(d) { return y(d.value); })
        //.style("stroke-width", 2)
        //.style("stroke", "gray")
        //.style("stroke-dasharray", ("2, 2"))
        //.style("opacity",0);

        // Define a div para tooltip
        var button = d3.select("#chart").append("button")
            .data(data)
            .attr("class", "tooltip")
            .style("opacity", 0);

        // Formata data para tooltip
        var FormatDate = d3.time.format("%Y");

        //rect botões
        //svg.append("rect")
            //.attr("x", (legendSpace / 5) + i * legendSpace) // space legend
            //.attr("y", -38)
            //.attr("rx", 4)
            //.attr("class", "botoes")
            //.style("fill", function () {
                //return d.color = color(d.key);
            //})
           // .on("mouseover", function () {
                //nota.transition()
                    //.style("display", "block")
                   // .style("opacity", "1");
           // })
           // .on("mouseout", function (d) {
               // nota.transition()
                 //   .style("opacity", .5);
            //})
           // .on("click", function () {
                // Determine if current line is visible
               // var active = d.active ? false : true,
                    //newOpacity = active ? 1 : 0.2;
                // Hide or show the elements based on the ID
               // d3.select("#tag" + d.key.replace(/\s+/g, ''))
                    //.transition().duration(300)
                    //.ease("linear")
                   // .style("opacity", newOpacity);
               // d.active = active;
            //})
           // .text(d.key);

        // texto legenda
        svg.append("text")
            .attr("x", (legendSpace / 2) + i * legendSpace) // space legend
            //.attr("y", height + (margin.bottom/1.5)+ 5)
            .attr("y", -30)
            .attr("class", "legend")
            .style("stroke", "none")
            .style("fill", function () {return d.color = color(d.key);})
            //.style("fill", "#fff")
            .on("mouseover", function () {
                dot.transition()
                    .style("display", "block")
                    .style("opacity", "1");
            })
            .on("mouseout", function (d) {
                dot.transition()
                    .style("opacity", .2);
            })
            .on("click", function () {
                // Determine if current line is visible
                var active = d.active ? false : true,
                    newOpacity = active ? 1 : 0.2;
                // Hide or show the elements based on the ID
                d3.select("#tag" + d.key.replace(/\s+/g, ''))
                    .transition().duration(300)
                    .ease("linear")
                    .style("opacity", newOpacity);
                d.active = active;
            })
            .text(d.key);

         // Acrescenta os pontos pra tooltip
        svg.selectAll("dot")
            .data(data)
            .enter().append("circle")
            .attr("r", 4)
            .attr("cx", function (d) {
                return x(d.date);
            })
            .attr("cy", function (d) {
                return y(d.value + 1);
            })
            .style("fill", function (d) {
                return d.color = color(d.key);
            })
            .style("opacity", ".1")
            .classed("hidden", true)
            .style("display", "block")
            .style("cursor", "pointer")
            .attr("id", 'key' + d.key.replace(/\s+/g, ''))
            .on("mouseenter", function (d) {
                button.transition()
                    .duration(200)
                    .style("cursor", "pointer")
                    .style("opacity", 1);
                button.html("
Ano: " + d.key + "

" + "
Ano:
" + FormatDate(d.date) + "
" + "
Taxa de rejeição:
 " + d.value + "%
" + "
" + "
Total de vistos concedidos:
" + d.vistos + "
" + "
Turismo/Negócios:
" + d.v_pct + "
" + "
Trabalho/Estudos:
" + d.t_pct + "
" + "
Outros tipos:
" + d.o_pct)
                    .style("left", d3.select(this).attr("cx") + "px")
                    .style("top", d3.select(this).attr("cy") + "px");
            })
            .on("mouseleave", function (d) {
                button.transition()
                    .delay(0)
                    .duration(200)
                    .style("opacity", "0")
                    .style("pointer-events", "none")
                    ;
            })
            .on("click", function (d) {
                button.transition()
                    .delay(0)
                    .duration(200)
                    .style("opacity", "0")
                    .style("pointer-events", "none")
                    ;
            });
    });

    // eixo x
    svg.append("g")
        .attr("class", "x_axis")
        .attr("transform", "translate(0," + height + ")")
        .style("stroke", "none")
        .call(xAxis);

    // eixo y
    svg.append("g")
        .attr("class", "y_axis")
        .style("stroke", "none")
        .call(yAxis);

    // Fonte
    svg.append("text")
        //.attr("y", 0 - margin.left)
        //.attr("x",0 - (height / 2))
        .attr("transform", "rotate(0)")
        .attr("class", "fonte")
        .attr("y", height + 70)
        .attr("x", 73)
        .attr("dy", "1em")
        .style("text-anchor", "middle")
        .style("fill", "#bbb")
        .text("Fonte: Depto. de Estado dos EUA");

    svg.append("rect")
        //.attr("x",0 - (height / 2))
        //.attr("y", 0 - margin.left)
        .attr("y", height + 60)
        .attr("x", -38)
        .attr("width", width - 50)
        .attr("height", "2px")
        .style("fill", "#bbbbbb");

    svg.append("svg:image")
        .attr("xlink:href", "piauicinza.png")
        .attr("y", height + 20)
        .attr("x", width - 60)
        .attr("width", 60)
        .attr("height", 80);

});

function resize() {

  var dim = Math.min(parseInt(d3.select("#chart").style("width")), parseInt(d3.select("#chart").style("height"))),
  width = dim - margin.left - margin.right,
  height = dim - margin.top - margin.bottom;

  console.log(dim);

  // Update the range of the scale with new width/height
  x.range([0, width]);
  y.range([height, 0]);

}

d3.select(window).on('resize', resize);

resize();<commit_msg>new test<commit_after>var margin = {top: 50, right: 62, bottom: 100, left: 50},
    dim = Math.min(parseInt(d3.select("#chart").style("width")), parseInt(d3.select("#chart").style("height"))),
    width = dim - margin.left - margin.right,
    height = dim - margin.top - margin.bottom;
//width = 700 - margin.left - margin.right,
//height = 700 - margin.top - margin.bottom;

var parseDate = d3.time.format("%Y").parse;

// escalas
var x = d3.time.scale().range([0, width]);
//var y = d3.scale.log().range([height, 0]); Logaritmica, se necessário
var y = d3.scale.linear().range([height, 40]);

// eixos
var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom")
    .ticks(7)
    .innerTickSize(-height)
    .outerTickSize(0)
    .tickPadding(10);

var yAxis = d3.svg.axis().scale(y)
    .orient("left")
    .ticks(6, "%")
    .tickSize(3, 0)
    .innerTickSize(-width)
    .outerTickSize(0)
    .tickPadding(15);

// linhas do gráfico
var valueline = d3.svg.line()
    .x(function (d) {
        return x(d.date);
    })
    // se usar escala log, cria o valor referência
    .y(function (d) {
        return y(d.value + 1);
    });

var nota = d3.select(".nota")
    .attr("class", "nota")
    .style("opacity", "0");

// acrescenta a canvas de svg
var svg = d3.select("#chart")
    .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform",
        "translate(" + margin.left + "," + margin.top + ")");

// puxa os dados da tabela
d3.tsv("dados/reject.tsv", function (error, data) {
    data.forEach(function (d) {
        d.date = parseDate(d.date);
        d.value = +d.value;
    });

    // o range dos dados
    x.domain(d3.extent(data, function (d) {
        return d.date;
    }));
    y.domain([1, d3.max(data, function (d) {
        return d.value;
    })]);

    // colocar os paises em nest
    var dataNest = d3.nest()
        .key(function (d) {
            return d.key;
        })
        .entries(data);

    var piaui = ["#7bad65", "#777", "#5ea4ab", "#eabf54", "#d94f30"]

    var color = d3.scale.ordinal()
        .range(piaui)

    legendSpace = width / dataNest.length; // espaçamento da legenda

    // utiliza as categorias
    dataNest.forEach(function (d, i) {

        svg.append("path")
            .attr("class", "line")
            .style("stroke", function () {
                return d.color = color(d.key);
            })
            //acrescenta linha dashed pra média
            .style('stroke-dasharray', function () {
                return d.key === 'Média' ? '4 4' : '';
            })
            .style('opacity', function () {
                if (d.key === 'Rússia') return '.1';
                if (d.key === 'China') return '.1'
                if (d.key === 'Índia') return '.1'
                if (d.key === 'Média') return '.1'
            })
            .attr("id", 'tag' + d.key.replace(/\s+/g, '')) // aplicar classe das linhas
            .attr("d", valueline(d.values))
            .append("title");

        // legenda retangular
        //svg.append("rect")
            //.attr("x", (legendSpace / 8) + i * legendSpace) // space legend
            //.attr("class", "legend")
            //.style("text-anchor", "end")
            //.attr("y", -38)
            //.attr("width", 8)
            //.attr("height", 8)
            //.style("fill", function() { return d.color = color(d.key); });

        //linhas para anos
        //svg.selectAll("line").data(data).enter().append("line")
        //.attr('x1',function(d) { return x(d.date); })
        //.attr('y1',function(d) { return y(0); })
        //.attr('x2',function(d) { return x(d.date); })
        //.attr('y2',function(d) { return y(d.value); })
        //.style("stroke-width", 2)
        //.style("stroke", "gray")
        //.style("stroke-dasharray", ("2, 2"))
        //.style("opacity",0);

        // Define a div para tooltip
        var button = d3.select("#chart").append("button")
            .data(data)
            .attr("class", "tooltip")
            .style("opacity", 0);

        // Formata data para tooltip
        var FormatDate = d3.time.format("%Y");

        //rect botões
        //svg.append("rect")
            //.attr("x", (legendSpace / 5) + i * legendSpace) // space legend
            //.attr("y", -38)
            //.attr("rx", 4)
            //.attr("class", "botoes")
            //.style("fill", function () {
                //return d.color = color(d.key);
            //})
           // .on("mouseover", function () {
                //nota.transition()
                    //.style("display", "block")
                   // .style("opacity", "1");
           // })
           // .on("mouseout", function (d) {
               // nota.transition()
                 //   .style("opacity", .5);
            //})
           // .on("click", function () {
                // Determine if current line is visible
               // var active = d.active ? false : true,
                    //newOpacity = active ? 1 : 0.2;
                // Hide or show the elements based on the ID
               // d3.select("#tag" + d.key.replace(/\s+/g, ''))
                    //.transition().duration(300)
                    //.ease("linear")
                   // .style("opacity", newOpacity);
               // d.active = active;
            //})
           // .text(d.key);

        // texto legenda
        svg.append("text")
            .attr("x", (legendSpace / 2) + i * legendSpace) // space legend
            //.attr("y", height + (margin.bottom/1.5)+ 5)
            .attr("y", -30)
            .attr("class", "legend")
            .style("stroke", "none")
            .style("fill", function () {return d.color = color(d.key);})
            //.style("fill", "#fff")
            .on("mouseover", function () {
                dot.transition()
                    .style("display", "block")
                    .style("opacity", "1");
            })
            .on("mouseout", function (d) {
                dot.transition()
                    .style("opacity", .2);
            })
            .on("click", function () {
                // Determine if current line is visible
                var active = d.active ? false : true,
                    newOpacity = active ? 1 : 0.2;
                // Hide or show the elements based on the ID
                d3.select("#tag" + d.key.replace(/\s+/g, ''))
                    .transition().duration(300)
                    .ease("linear")
                    .style("opacity", newOpacity);
                d.active = active;
            })
            .text(d.key);

         // Acrescenta os pontos pra tooltip
        svg.selectAll("dot")
            .data(data)
            .enter().append("circle")
            .attr("r", 5)
            .attr("cx", function (d) {
                return x(d.date);
            })
            .attr("cy", function (d) {
                return y(d.value + 1);
            })
            .style("fill", function (d) {
                return d.color = color(d.key);
            })
            .style("opacity", ".1")
            .classed("hidden", true)
            .style("display", "block")
            .style("cursor", "pointer")
            .attr("id", 'key' + d.key.replace(/\s+/g, ''))
            .on("mouseenter", function (d) {
                button.transition()
                    .duration(200)
                    .style("cursor", "pointer")
                    .style("opacity", 1);
                button.html("
Ano: " + d.key + "

" + "
Ano:
" + FormatDate(d.date) + "
" + "
Taxa de rejeição:
 " + d.value + "%
" + "
" + "
Total de vistos concedidos:
" + d.vistos + "
" + "
Turismo/Negócios:
" + d.v_pct + "
" + "
Trabalho/Estudos:
" + d.t_pct + "
" + "
Outros tipos:
" + d.o_pct)
                    .style("left", d3.select(this).attr("cx") + "px")
                    .style("top", d3.select(this).attr("cy") + "px");
            })
            .on("mouseleave", function (d) {
                button.transition()
                    .delay(0)
                    .duration(200)
                    .style("opacity", "0")
                    .style("pointer-events", "none")
                    ; tip.hide;
            })
            .on("click", function (d) {
                button.transition()
                    .delay(0)
                    .duration(200)
                    .style("opacity", "0")
                    .style("pointer-events", "none")
                    ;
            });
    });

    // eixo x
    svg.append("g")
        .attr("class", "x_axis")
        .attr("transform", "translate(0," + height + ")")
        .style("stroke", "none")
        .call(xAxis);

    // eixo y
    svg.append("g")
        .attr("class", "y_axis")
        .style("stroke", "none")
        .call(yAxis);

    // Fonte
    svg.append("text")
        //.attr("y", 0 - margin.left)
        //.attr("x",0 - (height / 2))
        .attr("transform", "rotate(0)")
        .attr("class", "fonte")
        .attr("y", height + 70)
        .attr("x", 73)
        .attr("dy", "1em")
        .style("text-anchor", "middle")
        .style("fill", "#bbb")
        .text("Fonte: Depto. de Estado dos EUA");

    svg.append("rect")
        //.attr("x",0 - (height / 2))
        //.attr("y", 0 - margin.left)
        .attr("y", height + 60)
        .attr("x", -38)
        .attr("width", width - 50)
        .attr("height", "2px")
        .style("fill", "#bbbbbb");

    svg.append("svg:image")
        .attr("xlink:href", "piauicinza.png")
        .attr("y", height + 20)
        .attr("x", width - 60)
        .attr("width", 60)
        .attr("height", 80);

});

function resize() {

  var dim = Math.min(parseInt(d3.select("#chart").style("width")), parseInt(d3.select("#chart").style("height"))),
  width = dim - margin.left - margin.right,
  height = dim - margin.top - margin.bottom;

  console.log(dim);

  // Update the range of the scale with new width/height
  x.range([0, width]);
  y.range([height, 0]);

}

d3.select(window).on('resize', resize);

resize();<|endoftext|>