<commit_before>/**
 * contextmenu.
 * User: raytin
 * Date: 13-7-25
 */
var require = global.require,
    window = global.window,
    console = window.console,
    process = global.process,
    fs = require('fs'),
    iconv = require('iconv-lite');

var aaa = {
    init: function() {
        var markdown = global.markdown;
        var cache = markdown.cache;
        var editor = cache.editor;
        var gui  = cache.gui;
        var clipboard = gui.Clipboard.get();

        var source = {};

        function showToolOrConsole(that, type){
            var footer = $('#J-footer'),
                toolbar = $('#J-toolbar'),
                main = $('#J-tab, #codeMirror, #showdown'),
                fireOnloadLocalData = cache.tempFlag === 'localData';

            // 这一次是 加载本地数据时进来的 取反
            if(fireOnloadLocalData){
                that.checked = !that.checked;
            }

            if(type === 'toolbar'){
                if(that.checked){
                    toolbar.removeClass('hide');
                    main.css('top', '+=30px');
                }else{
                    toolbar.addClass('hide');
                    main.css('top', '-=30px');
                }
            }
            else if(type === 'console'){
                if(that.checked){
                    footer.removeClass('hide');
                    main.css('bottom', '25px');
                }else{
                    footer.addClass('hide');
                    main.css('bottom', '0px');
                }
            }

            markdown.adjustWorkspace();

            // 保存用户选择的工具栏和状态栏显隐值
            markdown.userFootprint.saveToMemory(type, that.checked);

            if(fireOnloadLocalData){
                delete cache.tempFlag;
            }
        }

        var separatorFactory = function() {
            var menuItem = new gui.MenuItem({
                type: 'separator'
            });
            return menuItem;
        }

        var clearHistoryMenuFactory = function() {
            var menuItem = new gui.MenuItem({
                label: '清除所有历史记录',
                click: function(){
                    markdown.userFootprint.clearHistoryInMenu();
                    markdown.userFootprint.clearInMemory('historyList');
                }
            });
            return menuItem;
        }

        var toolbarMenuFactory = function() {
            var menuItem = new gui.MenuItem({
                label: '显示工具栏', //提示通过‘查看’可再次打开
                type: 'checkbox',
                checked: true,
                click: function(){
                    showToolOrConsole(this, 'toolbar');
                }
            });
            return menuItem;
        }

        var consoleMenuFactory = function() {
            var menuItem = new gui.MenuItem({
                label: '显示状态栏', //提示通过‘查看’可再次打开
                type: 'checkbox',
                checked: true,
                click: function(){
                    showToolOrConsole(this, 'console');
                }
            });
            return menuItem;
        }

        source.separatorFactory = separatorFactory;
        source.clearHistoryMenuFactory = clearHistoryMenuFactory;
        source.toolbarMenuFactory = toolbarMenuFactory;
        source.consoleMenuFactory = consoleMenuFactory;

        var menu = new gui.Menu({type: 'menubar'});

        menu.createMacBuiltin("Rock! Markdown Editor", {
            hideWindow: true
        });

        // 文件 menu
        var fileMenu = new gui.Menu();
        fileMenu.append(new gui.MenuItem({
            label: '新建文档 (Ctrl+N)',
            click: function(){
                $('#J-tool-new').trigger('click');
            }
        }));
        fileMenu.append(new gui.MenuItem({
            label: '保存文档 (Ctrl+S)',
            click: function(){
                $('#J-tool-save').trigger('click');
            }
        }));
        fileMenu.append(new gui.MenuItem({
            label: '打开文件... (Ctrl+O)',
            click: function(){
                $('#J-tool-select').trigger('click');
            }
        }));
        fileMenu.append(new gui.MenuItem({
            label: '另存为... (Ctrl+Shift+S)',
            click: function(){
                markdown.file.saveAs();
            }
        }));
        fileMenu.append(new gui.MenuItem({
            label: '查看文件目录',
            click: function(){
                markdown.file.viewPath();
            }
        }));
        fileMenu.append(new gui.MenuItem({
            label: '从磁盘删除',
            click: function(){
                markdown.file.delFileFromDisk();
            }
        }));
        fileMenu.append(new gui.MenuItem({
            type: 'separator'
        }));
        fileMenu.append(new gui.MenuItem({
            label: '关闭 (Alt+C)',
            click: function(){
                markdown.tab.close(markdown.tab.getCurrentTab().id);
            }
        }));
        fileMenu.append(new gui.MenuItem({
            label: '全部关闭',
            click: function(){
                markdown.tab.closeAll();
            }
        }));
        fileMenu.append(new gui.MenuItem({
            label: '关闭当前以外所有标签',
            click: function(){
                markdown.tab.closeOthers();
            }
        }));
        fileMenu.append(separatorFactory());
        fileMenu.append(new gui.MenuItem({
            label: '打印 (Ctrl+P)',
            enabled: false,
            click: function(){
                window.print();
            }
        }));
        fileMenu.append(separatorFactory());
        fileMenu.append(new gui.MenuItem({
            label: '退出 (Exit)',
            click: function(){
                cache.guiWin.close();
            }
        }));

        source.file = fileMenu;

        menu.append(new gui.MenuItem({
            label: '文件',
            submenu: fileMenu
        }));

        // 插入 menu
        var insertMenu = new gui.Menu();
        insertMenu.append(new gui.MenuItem({
            label: '标题 1 (Ctrl+1)',
            click: function(){
                markdown.toolbar.pre(1, 1, '# ');
            }
        }));
        insertMenu.append(new gui.MenuItem({
            label: '标题 2 (Ctrl+2)',
            click: function(){
                markdown.toolbar.pre(1, 1, '## ');
            }
        }));
        insertMenu.append(new gui.MenuItem({
            label: '标题 3 (Ctrl+3)',
            click: function(){
                markdown.toolbar.pre(1, 1, '### ');
            }
        }));
        insertMenu.append(new gui.MenuItem({
            label: '标题 4 (Ctrl+4)',
            click: function(){
                markdown.toolbar.pre(1, 1, '#### ');
            }
        }));
        insertMenu.append(new gui.MenuItem({
            label: '标题 5 (Ctrl+5)',
            click: function(){
                markdown.toolbar.pre(1, 1, '##### ');
            }
        }));
        insertMenu.append(new gui.MenuItem({
            label: '标题 6 (Ctrl+6)',
            click: function(){
                markdown.toolbar.pre(1, 1, '###### ');
            }
        }));
        insertMenu.append(separatorFactory());
        insertMenu.append(new gui.MenuItem({
            label: '粗体 (Ctrl+B)',
            click: function(){
                $('#J-tool-bold').trigger('click');
            }
        }));
        insertMenu.append(new gui.MenuItem({
            label: '斜体 (Ctrl+I)',
            click: function(){
                $('#J-tool-italic').trigger('click');
            }
        }));
        insertMenu.append(new gui.MenuItem({
            label: '代码 (Ctrl+K)',
            click: function(){
                $('#J-tool-code').trigger('click');
            }
        }));
        insertMenu.append(new gui.MenuItem({
            label: '引用 (Ctrl+Q)',
            click: function(){
                $('#J-tool-block').trigger('click');
            }
        }));
        insertMenu.append(separatorFactory());
        insertMenu.append(new gui.MenuItem({
            label: '图片 (Ctrl+G)',
            click: function(){
                $('#J-tool-image').trigger('click');
            }
        }))
        insertMenu.append(new gui.MenuItem({
            label: '链接 (Ctrl+L)',
            click: function(){
                $('#J-tool-link').trigger('click');
            }
        }));
        insertMenu.append(separatorFactory());
        insertMenu.append(new gui.MenuItem({
            label: '无序列表 (Ctrl+U)',
            click: function(){
                $('#J-tool-list').trigger('click');
            }
        }))
        insertMenu.append(new gui.MenuItem({
            label: '水平标尺 (Ctrl+R)',
            click: function(){
                $('#J-tool-hr').trigger('click');
            }
        }));
        insertMenu.append(separatorFactory());
        insertMenu.append(new gui.MenuItem({
            label: '时间戳 (Ctrl+T)',
            click: function(){
                $('#J-tool-timestamp').trigger('click');
            }
        }));

        menu.append(new gui.MenuItem({
            label: '插入',
            submenu: insertMenu
        }));

        // 查看 menu
        var viewMenu = new gui.Menu(),
            encodeSubMenu = new gui.Menu();

        encodeSubMenu.append(new gui.MenuItem({
            label: 'Unicode (UTF-8)',
            type: 'checkbox',
            checked: true,
            click: function(){
                if(!this.checked){
                    this.checked = true;
                }
                source['view-encode_gbk'].checked = false;
            }
        }));
        encodeSubMenu.append(new gui.MenuItem({
            label: '简体中文 (GBK)',
            type: 'checkbox',
            click: function(){
                if(!this.checked){
                    this.checked = true;
                }
                source['view-encode_utf'].checked = false;
            }
        }));
        viewMenu.append(new gui.MenuItem({
            label: '运行 (F5)',
            enabled: false,
            click: function(){
                $('#J-tool-run').trigger('click');
            }
        }));
        viewMenu.append(new gui.MenuItem({
            label: '启用实时预览',
            type: 'checkbox',
            checked: true,
            click: function(){
                $('#J-tool-realtime').trigger('click');
            }
        }));
        viewMenu.append(new gui.MenuItem({
            label: '最大化编辑器 (F11)',
            type: 'checkbox',
            checked: false,
            click: function(){
                $('#J-tool-maxsize').trigger('click');
            }
        }));
        viewMenu.append(separatorFactory());
        viewMenu.append(new gui.MenuItem({
            label: '文件编码',
            enabled: false,
            submenu: encodeSubMenu
        }));
        viewMenu.append(separatorFactory());
        viewMenu.append(toolbarMenuFactory());
        viewMenu.append(consoleMenuFactory());

        menu.append(new gui.MenuItem({
            label: '查看',
            submenu: viewMenu
        }));

        // 工具 menu
        var toolMenu = new gui.Menu();
        toolMenu.append(new gui.MenuItem({
            label: '在浏览器中预览 (Ctrl+F12)',
            click: function(){
                markdown.file.preview();
            }
        }));
        toolMenu.append(new gui.MenuItem({
            label: '导出为HTML文件',
            click: function(){
                cache.tabCache.saveType = 'exportHTML';
                $('#J-hi-savePath').trigger('click');
            }
        }));
        toolMenu.append(new gui.MenuItem({
            label: '发送邮件 (以当前HTML为内容)',
            click: function(){
                markdown.mail.showDialog();
            }
        }));
        toolMenu.append(separatorFactory());
        toolMenu.append(new gui.MenuItem({
            label: '设置',
            click: function(){
                $.artDialog({
                    title: '设 置',
                    lock: true,
                    resize: false,
                    button: [
                        {
                            value: '保 存',
                            callback: function () {
                                console.log('点击保存')
                                return markdown.rockSettings.saveAllSetting();
                            },
                            focus: true
                        },
                        {
                            value: '取 消',
                            callback: function () {
                                console.log('取消保存')
                            }
                        }
                    ],
                    initialize: function(){
                        markdown.dialog_commonInit();
                        var dialogParent = $('.d-outer').parent();

                        this.content($('#J-settings').html());
                        dialogParent.hide();
                        $('.dialogWrap').parent().css('padding', 0);

                        // 打开设置界面前先初始化用户选择
                        markdown.rockSettings.init();

                        dialogParent.fadeIn(300);

                        markdown.rockSettings.listen();
                    }
                });
            }
        }));

        menu.append(new gui.MenuItem({
            label: '工具',
            submenu: toolMenu
        }));

        // 帮助 menu
        var helpMenu = new gui.Menu(),
            docSubMenu = new gui.Menu();

        docSubMenu.append(new gui.MenuItem({
            label: 'markdown语法参考(GFM)',
            click: function(){
                markdown.tab.add('./docs/github.markdown', true);
            }
        }));
        helpMenu.append(new gui.MenuItem({
            label: '问题反馈',
            click: function(){
                gui.Shell.openExternal('https://github.com/superRaytin/Rock_Markdown/issues');
            }
        }));
        helpMenu.append(new gui.MenuItem({
            label: '帮助文档',
            submenu: docSubMenu
        }));
        helpMenu.append(new gui.MenuItem({
            label: 'Rock Markdown 网站',
            click: function(){
                gui.Shell.openExternal('https://github.com/superRaytin/Rock_Markdown');
            }
        }));
        helpMenu.append(separatorFactory());
        helpMenu.append(new gui.MenuItem({
            label: '检查新版本',
            click: function(){
                markdown.update.init();
            }
        }));
        helpMenu.append(new gui.MenuItem({
            label: '版本日志',
            click: function(){
                markdown.tab.add('./docs/CHANGELOG.md', true);
            }
        }));
        helpMenu.append(separatorFactory());
        helpMenu.append(new gui.MenuItem({
            label: '关于 Rock! MarkDown',
            click: function(){
                $.artDialog({
                    title: '关于 Rock! MarkDown',
                    lock: true,
                    resize: false,
                    initialize: function(){
                        markdown.dialog_commonInit();

                        var dialogParent = $('.d-outer').parent();

                        this.content($('#J-about-rock').html());
                        $('#J-about-version').text(markdown.settings.version);
                        dialogParent.hide();

                        dialogParent.fadeIn(300);

                        $('#J-about-update').click(function(){
                            markdown.update.init();
                        });
                    }
                });
            }
        }));
        helpMenu.append(new gui.MenuItem({
            label: '关于作者',
            click: function(){
                $.artDialog({
                    title: '关于作者',
                    lock: true,
                    resize: false,
                    initialize: function(){
                        markdown.dialog_commonInit();

                        var dialogParent = $('.d-outer').parent();

                        this.content($('#J-about-author').html());
                        dialogParent.hide();

                        dialogParent.fadeIn(300);
                    }
                });
            }
        }));

        menu.append(new gui.MenuItem({
            label: '帮助',
            submenu: helpMenu
        }));

        var manyMenus = {};
        manyMenus.toolbarMenu = toolbarMenuFactory();
        manyMenus.consoleMenu = consoleMenuFactory();
        manyMenus.file = fileMenu;
        manyMenus.insert = insertMenu;
        manyMenus.view = viewMenu;
        manyMenus.tool = toolMenu;
        //menu.history = historyMenu;
        manyMenus.help = helpMenu;

        this.contextMenuSource = source;

        gui.Window.get().menu = menu;

        return manyMenus;
    },

    contextMenuSource: {}
};

exports.init = aaa.init;
exports.contextMenuSource = aaa.contextMenuSource;<commit_msg>contextmenu for osx<commit_after>/**
 * contextmenu.
 * User: raytin
 * Date: 13-7-25
 */
var require = global.require,
    window = global.window,
    console = window.console,
    process = global.process,
    fs = require('fs');

var Contextmenu = {
    init: function() {
        var markdown = global.markdown;
        var cache = markdown.cache;
        // var editor = cache.editor;
        var gui  = cache.gui;
        // var clipboard = gui.Clipboard.get();

        var source = {};

        var separatorFactory = this.factory.separatorFactory;
        var clearHistoryMenuFactory = this.factory.clearHistoryMenuFactory;
        var toolbarMenuFactory = this.factory.toolbarMenuFactory;
        var consoleMenuFactory = this.factory.consoleMenuFactory;

        source.separatorFactory = separatorFactory;
        source.clearHistoryMenuFactory = clearHistoryMenuFactory;
        source.toolbarMenuFactory = toolbarMenuFactory;
        source.consoleMenuFactory = consoleMenuFactory;

        var menu = new gui.Menu({type: 'menubar'});

        menu.createMacBuiltin("Rock! Markdown Editor", {
            hideWindow: true
        });

        // 文件 menu
        var fileMenu = new gui.Menu();
        fileMenu.append(new gui.MenuItem({
            label: '新建文档 (Ctrl+N)',
            click: function() {
                $('#J-tool-new').trigger('click');
            }
        }));
        fileMenu.append(new gui.MenuItem({
            label: '保存文档 (Ctrl+S)',
            click: function() {
                $('#J-tool-save').trigger('click');
            }
        }));
        fileMenu.append(new gui.MenuItem({
            label: '打开文件... (Ctrl+O)',
            click: function() {
                $('#J-tool-select').trigger('click');
            }
        }));
        fileMenu.append(new gui.MenuItem({
            label: '另存为... (Ctrl+Shift+S)',
            click: function() {
                markdown.file.saveAs();
            }
        }));
        fileMenu.append(new gui.MenuItem({
            label: '查看文件目录',
            click: function() {
                markdown.file.viewPath();
            }
        }));
        fileMenu.append(new gui.MenuItem({
            label: '从磁盘删除',
            click: function() {
                markdown.file.delFileFromDisk();
            }
        }));
        fileMenu.append(new gui.MenuItem({
            type: 'separator'
        }));
        fileMenu.append(new gui.MenuItem({
            label: '关闭 (Alt+C)',
            click: function() {
                markdown.tab.close(markdown.tab.getCurrentTab().id);
            }
        }));
        fileMenu.append(new gui.MenuItem({
            label: '全部关闭',
            click: function() {
                markdown.tab.closeAll();
            }
        }));
        fileMenu.append(new gui.MenuItem({
            label: '关闭当前以外所有标签',
            click: function() {
                markdown.tab.closeOthers();
            }
        }));
        fileMenu.append(separatorFactory());
        fileMenu.append(new gui.MenuItem({
            label: '打印 (Ctrl+P)',
            enabled: false,
            click: function() {
                window.print();
            }
        }));
        fileMenu.append(separatorFactory());
        fileMenu.append(new gui.MenuItem({
            label: '退出 (Exit)',
            click: function() {
                cache.guiWin.close();
            }
        }));

        source.file = fileMenu;

        menu.append(new gui.MenuItem({
            label: '文件',
            submenu: fileMenu
        }));

        // 插入 menu
        var insertMenu = new gui.Menu();
        insertMenu.append(new gui.MenuItem({
            label: '标题 1 (Ctrl+1)',
            click: function() {
                markdown.toolbar.pre(1, 1, '# ');
            }
        }));
        insertMenu.append(new gui.MenuItem({
            label: '标题 2 (Ctrl+2)',
            click: function() {
                markdown.toolbar.pre(1, 1, '## ');
            }
        }));
        insertMenu.append(new gui.MenuItem({
            label: '标题 3 (Ctrl+3)',
            click: function() {
                markdown.toolbar.pre(1, 1, '### ');
            }
        }));
        insertMenu.append(new gui.MenuItem({
            label: '标题 4 (Ctrl+4)',
            click: function() {
                markdown.toolbar.pre(1, 1, '#### ');
            }
        }));
        insertMenu.append(new gui.MenuItem({
            label: '标题 5 (Ctrl+5)',
            click: function() {
                markdown.toolbar.pre(1, 1, '##### ');
            }
        }));
        insertMenu.append(new gui.MenuItem({
            label: '标题 6 (Ctrl+6)',
            click: function() {
                markdown.toolbar.pre(1, 1, '###### ');
            }
        }));
        insertMenu.append(separatorFactory());
        insertMenu.append(new gui.MenuItem({
            label: '粗体 (Ctrl+B)',
            click: function() {
                $('#J-tool-bold').trigger('click');
            }
        }));
        insertMenu.append(new gui.MenuItem({
            label: '斜体 (Ctrl+I)',
            click: function() {
                $('#J-tool-italic').trigger('click');
            }
        }));
        insertMenu.append(new gui.MenuItem({
            label: '代码 (Ctrl+K)',
            click: function() {
                $('#J-tool-code').trigger('click');
            }
        }));
        insertMenu.append(new gui.MenuItem({
            label: '引用 (Ctrl+Q)',
            click: function() {
                $('#J-tool-block').trigger('click');
            }
        }));
        insertMenu.append(separatorFactory());
        insertMenu.append(new gui.MenuItem({
            label: '图片 (Ctrl+G)',
            click: function() {
                $('#J-tool-image').trigger('click');
            }
        }))
        insertMenu.append(new gui.MenuItem({
            label: '链接 (Ctrl+L)',
            click: function() {
                $('#J-tool-link').trigger('click');
            }
        }));
        insertMenu.append(separatorFactory());
        insertMenu.append(new gui.MenuItem({
            label: '无序列表 (Ctrl+U)',
            click: function() {
                $('#J-tool-list').trigger('click');
            }
        }))
        insertMenu.append(new gui.MenuItem({
            label: '水平标尺 (Ctrl+R)',
            click: function() {
                $('#J-tool-hr').trigger('click');
            }
        }));
        insertMenu.append(separatorFactory());
        insertMenu.append(new gui.MenuItem({
            label: '时间戳 (Ctrl+T)',
            click: function() {
                $('#J-tool-timestamp').trigger('click');
            }
        }));

        menu.append(new gui.MenuItem({
            label: '插入',
            submenu: insertMenu
        }));

        // 查看 menu
        var viewMenu = new gui.Menu(),
            encodeSubMenu = new gui.Menu();

        encodeSubMenu.append(new gui.MenuItem({
            label: 'Unicode (UTF-8)',
            type: 'checkbox',
            checked: true,
            click: function() {
                if (!this.checked) {
                    this.checked = true;
                }
                source['view-encode_gbk'].checked = false;
            }
        }));
        encodeSubMenu.append(new gui.MenuItem({
            label: '简体中文 (GBK)',
            type: 'checkbox',
            click: function() {
                if (!this.checked) {
                    this.checked = true;
                }
                source['view-encode_utf'].checked = false;
            }
        }));

        var viewRunMenuItem = new gui.MenuItem({
            label: '运行 (F5)',
            enabled: false,
            click: function() {
                $('#J-tool-run').trigger('click');
            }
        });
        viewMenu.append(viewRunMenuItem);
        source['view-run'] = viewRunMenuItem;

        viewMenu.append(new gui.MenuItem({
            label: '启用实时预览',
            type: 'checkbox',
            checked: true,
            click: function() {
                $('#J-tool-realtime').trigger('click');
            }
        }));
        viewMenu.append(new gui.MenuItem({
            label: '最大化编辑器 (F11)',
            type: 'checkbox',
            checked: false,
            click: function() {
                $('#J-tool-maxsize').trigger('click');
            }
        }));
        viewMenu.append(separatorFactory());
        viewMenu.append(new gui.MenuItem({
            label: '文件编码',
            enabled: false,
            submenu: encodeSubMenu
        }));
        viewMenu.append(separatorFactory());
        viewMenu.append(toolbarMenuFactory());
        viewMenu.append(consoleMenuFactory());

        menu.append(new gui.MenuItem({
            label: '查看',
            submenu: viewMenu
        }));

        // 工具 menu
        var toolMenu = new gui.Menu();
        toolMenu.append(new gui.MenuItem({
            label: '在浏览器中预览 (Ctrl+F12)',
            click: function() {
                markdown.file.preview();
            }
        }));
        toolMenu.append(new gui.MenuItem({
            label: '导出为HTML文件',
            click: function() {
                cache.tabCache.saveType = 'exportHTML';
                $('#J-hi-savePath').trigger('click');
            }
        }));
        toolMenu.append(new gui.MenuItem({
            label: '发送邮件 (以当前HTML为内容)',
            click: function() {
                markdown.mail.showDialog();
            }
        }));
        toolMenu.append(separatorFactory());
        toolMenu.append(new gui.MenuItem({
            label: '设置',
            click: function() {
                $.artDialog({
                    title: '设 置',
                    lock: true,
                    resize: false,
                    button: [
                        {
                            value: '保 存',
                            callback: function () {
                                console.log('点击保存')
                                return markdown.rockSettings.saveAllSetting();
                            },
                            focus: true
                        },
                        {
                            value: '取 消',
                            callback: function () {
                                console.log('取消保存')
                            }
                        }
                    ],
                    initialize: function() {
                        markdown.dialog_commonInit();
                        var dialogParent = $('.d-outer').parent();

                        this.content($('#J-settings').html());
                        dialogParent.hide();
                        $('.dialogWrap').parent().css('padding', 0);

                        // 打开设置界面前先初始化用户选择
                        markdown.rockSettings.init();

                        dialogParent.fadeIn(300);

                        markdown.rockSettings.listen();
                    }
                });
            }
        }));

        menu.append(new gui.MenuItem({
            label: '工具',
            submenu: toolMenu
        }));

        // 帮助 menu
        var helpMenu = new gui.Menu(),
            docSubMenu = new gui.Menu();

        docSubMenu.append(new gui.MenuItem({
            label: 'markdown语法参考(GFM)',
            click: function() {
                markdown.tab.add('./docs/github.markdown', true);
            }
        }));
        helpMenu.append(new gui.MenuItem({
            label: '问题反馈',
            click: function() {
                gui.Shell.openExternal('https://github.com/superRaytin/rock-markdown-editor/issues');
            }
        }));
        helpMenu.append(new gui.MenuItem({
            label: '帮助文档',
            submenu: docSubMenu
        }));
        helpMenu.append(new gui.MenuItem({
            label: 'Rock Markdown 网站',
            click: function() {
                gui.Shell.openExternal('https://github.com/superRaytin/rock-markdown-editor');
            }
        }));
        helpMenu.append(separatorFactory());
        helpMenu.append(new gui.MenuItem({
            label: '检查新版本',
            click: function() {
                markdown.update.init();
            }
        }));
        helpMenu.append(new gui.MenuItem({
            label: '版本日志',
            click: function() {
                markdown.tab.add('./docs/CHANGELOG.md', true);
            }
        }));
        helpMenu.append(separatorFactory());
        helpMenu.append(new gui.MenuItem({
            label: '关于 Rock! MarkDown',
            click: function() {
                $.artDialog({
                    title: '关于 Rock! MarkDown',
                    lock: true,
                    resize: false,
                    initialize: function() {
                        markdown.dialog_commonInit();

                        var dialogParent = $('.d-outer').parent();

                        this.content($('#J-about-rock').html());
                        $('#J-about-version').text(markdown.settings.version);
                        dialogParent.hide();

                        dialogParent.fadeIn(300);

                        $('#J-about-update').click(function() {
                            markdown.update.init();
                        });
                    }
                });
            }
        }));
        helpMenu.append(new gui.MenuItem({
            label: '关于作者',
            click: function() {
                $.artDialog({
                    title: '关于作者',
                    lock: true,
                    resize: false,
                    initialize: function() {
                        markdown.dialog_commonInit();

                        var dialogParent = $('.d-outer').parent();

                        this.content($('#J-about-author').html());
                        dialogParent.hide();

                        dialogParent.fadeIn(300);
                    }
                });
            }
        }));

        menu.append(new gui.MenuItem({
            label: '帮助',
            submenu: helpMenu
        }));

        var manyMenus = {};
        manyMenus.toolbarMenu = toolbarMenuFactory();
        manyMenus.consoleMenu = consoleMenuFactory();
        manyMenus.file = fileMenu;
        manyMenus.insert = insertMenu;
        manyMenus.view = viewMenu;
        manyMenus.tool = toolMenu;
        //menu.history = historyMenu;
        manyMenus.help = helpMenu;

        this.contextMenuSource = source;

        gui.Window.get().menu = menu;

        return manyMenus;
    },

    contextMenuSource: {},

    showToolOrConsole: function(that, type) {
        var markdown = global.markdown;
        var cache = markdown.cache;

        var footer = $('#J-footer'),
            toolbar = $('#J-toolbar'),
            main = $('#J-tab, #codeMirror, #showdown'),
            fireOnloadLocalData = cache.tempFlag === 'localData';

        // 这一次是 加载本地数据时进来的 取反
        if (fireOnloadLocalData) {
            that.checked = !that.checked;
        }

        if (type === 'toolbar') {
            if (that.checked) {
                toolbar.removeClass('hide');
                main.css('top', '+=30px');
            } else {
                toolbar.addClass('hide');
                main.css('top', '-=30px');
            }
        }
        else if (type === 'console') {
            if (that.checked) {
                footer.removeClass('hide');
                main.css('bottom', '25px');
            } else {
                footer.addClass('hide');
                main.css('bottom', '0px');
            }
        }

        markdown.adjustWorkspace();

        // 保存用户选择的工具栏和状态栏显隐值
        markdown.userFootprint.saveToMemory(type, that.checked);

        if (fireOnloadLocalData) {
            delete cache.tempFlag;
        }
    },

    factory: {
        create: function(options) {
            var markdown = global.markdown;
            var cache = markdown.cache;
            var gui  = cache.gui;

            return new gui.MenuItem(options);
        },

        separatorFactory: function() {
            return Contextmenu.factory.create({
                type: 'separator'
            });
        },

        clearHistoryMenuFactory: function() {
            var markdown = global.markdown;

            return Contextmenu.factory.create({
                label: '清除所有历史记录',
                click: function() {
                    markdown.userFootprint.clearHistoryInMenu();
                    markdown.userFootprint.clearInMemory('historyList');
                }
            });
        },

        toolbarMenuFactory: function() {
            var self = Contextmenu.factory;

            return self.create({
                label: '显示工具栏', // 提示通过‘查看’可再次打开
                type: 'checkbox',
                checked: true,
                click: function() {
                    self.showToolOrConsole(this, 'toolbar');
                }
            });
        },

        consoleMenuFactory: function() {
            var self = Contextmenu.factory;

            return self.create({
                label: '显示状态栏', // 提示通过‘查看’可再次打开
                type: 'checkbox',
                checked: true,
                click: function() {
                    self.showToolOrConsole(this, 'console');
                }
            });
        },

        previewInBrowser: function() {
            var markdown = global.markdown;

            return Contextmenu.factory.create({
                label: '在浏览器中预览 (Ctrl+F12)',
                click: function() {
                    markdown.file.preview();
                }
            });
        },

        exportAsHtml: function() {
            var markdown = global.markdown;
            var cache = markdown.cache;

            return Contextmenu.factory.create({
                label: '导出为HTML文件',
                click: function() {
                    cache.tabCache.saveType = 'exportHTML';
                    $('#J-hi-savePath').trigger('click');
                }
            });
        },

        sendEmailAsHtml: function() {
            var markdown = global.markdown;

            return Contextmenu.factory.create({
                label: '发送邮件 (以当前HTML为内容)',
                click: function() {
                    markdown.mail.showDialog();
                }
            });
        }
    }
};

exports.init = Contextmenu.init;
exports.contextMenuSource = Contextmenu.contextMenuSource;
exports.factory = Contextmenu.factory;<|endoftext|>


<commit_before>/* jshint browser: true, devel: true, indent: 2, curly: true, eqeqeq: true, futurehostile: true, latedef: true, undef: true, unused: true */
/* global $, jQuery, document, Site, Modernizr */

Site = {
  mobileThreshold: 601,
  init: function() {
    var _this = this;

    $(window).resize($.debounce(250, function(){
      console.log('resize');
      _this.onResize();
    }));

    $(document).ready(function () {
      _this.Layout.init();
      _this.Menu.init();
    });

    if ($('body').hasClass('post-type-archive-programacion')) {
      _this.Programacion.Archive.init();
    }

    if ($('body').hasClass('single-programacion')) {
      _this.Programacion.Single.init();
    }

    if ($('body').hasClass('blog') || $('body').hasClass('single-post')) {
      _this.Noticias.init();
    }

    _this.Home.init();
  },

  onResize: function() {
    var _this = this;

    _this.Programacion.Single.sizeSlideImageHolder();
    _this.Menu.closeMenu();
  },

  fixWidows: function() {
    // utility class mainly for use on headines to avoid widows [single words on a new line]
    $('.js-fix-widows').each(function(){
      var string = $(this).html();
      string = string.replace(/ ([^ ]*)$/,' $1');
      $(this).html(string);
    });
  }
};

Site.Layout = {
  init: function() {
    var _this = this;

    if ($('.home-item').length) {
      _this.layoutMasonry();
    }
  },

  layoutMasonry: function() {
    var $masonry = $('#home-holder').masonry({
      itemSelector: '.home-item',
      transitionDuration: 0,
    });

    $masonry.imagesLoaded().progress( function() {
      $masonry.masonry('layout');
    });
  }
};

Site.Home = {
  init: function() {
    var _this = this;

    if ($('.home-item').length) {
      _this.bindItemHover();
    }
  },

  bindItemHover: function() {
    $('.home-item a').hover(
      function() {
        $('.home-item a').not(this).parent('.home-item').addClass('home-item-hidden');
        $(this).parent('.home-item').addClass('home-item-hover');
      },
      function() {
        $('.home-item').removeClass('home-item-hidden home-item-hover');
      }
    );
  }
};

Site.Menu = {
  init: function() {
    var _this = this;

    _this.bindToggle();
  },

  bindToggle: function() {
    $('.menu-toggle').on('click', function() {
      $('body').toggleClass('menu-active');
    });
  },

  closeMenu: function() {
    $('body').removeClass('menu-active');
  },
};

Site.Programacion = {

  Archive: {
    init: function() {
      var _this = this;

      if ($('[data-hover-color]').length) {
        _this.bindHoverColor();
      }
    },

    bindHoverColor: function() {
      $('[data-hover-color]').hover(
        function() {
          $(this).css('color', $(this).attr('data-hover-color'));
        },
        function() {
          $(this).css('color', 'inherit');
        }
      );
    }
  },

  Single: {
    init: function() {
      var _this = this;

      $(document).ready(function () {
        _this.initGallery();
        _this.bindToggle();
        _this.sizeSlideImageHolder();
      });
    },

    initGallery: function() {
      var _this = this;

      _this.swiper = new Swiper('.swiper-container', {
        loop: true,
        nextButton: '.swiper-next',
        prevButton: '.swiper-prev',
        pagination: '#single-programacion-gallery-pagination',
        paginationType: 'custom',
        paginationCustomRender: function (swiper, current, total) {
          return '' + current + ' / ' + total + '';
        },
        onClick: function(swiper) {
          swiper.slideNext();
        },
      });
    },

    sizeSlideImageHolder: function() {
      var _this = this,
        windowWidth = $(window).width(),
        headerHeight = $('#header').outerHeight(true);

      $('.programacion-content-holder').scrollTop(0);
      $('body').removeClass('drawer-open');

      var contentHeight = $('.programacion-header').outerHeight(true);

      if (windowWidth < 1024) {
        $('.slide-image-holder').css({
          'padding-top': 0,
          'padding-bottom': 0,
        });
      } else {
        $('.slide-image-holder').css({
          'padding-top': headerHeight,
          'padding-bottom': contentHeight,
        });
      }
    },

    bindToggle: function() {
      var _this = this;

      $('.programacion-drawer-toggle').on('click', function() {
        _this.toggleContent();
      });
    },

    toggleContent: function() {
      $('body').toggleClass('drawer-open');
      $('.programacion-content-holder').scrollTop(0);
    }
  }

};

Site.Noticias = {
  init: function() {
    this.Galleries.init();
  },

  Galleries: {
    init: function() {
      $('.swiper-container').each(function() {
        var swiper = new Swiper($(this), {
          loop: true,
          onClick: function(swiper) {
            swiper.slideNext();
          },
        });
      });
    },
  }
};

Site.init();
<commit_msg>move masonry layout into function. call in onResize<commit_after>/* jshint browser: true, devel: true, indent: 2, curly: true, eqeqeq: true, futurehostile: true, latedef: true, undef: true, unused: true */
/* global $, jQuery, document, Site, Modernizr */

Site = {
  mobileThreshold: 601,
  init: function() {
    var _this = this;

    $(window).resize($.debounce(250, function(){
      console.log('resize');
      _this.onResize();
    }));

    $(document).ready(function () {
      _this.Layout.init();
      _this.Menu.init();
    });

    if ($('body').hasClass('post-type-archive-programacion')) {
      _this.Programacion.Archive.init();
    }

    if ($('body').hasClass('single-programacion')) {
      _this.Programacion.Single.init();
    }

    if ($('body').hasClass('blog') || $('body').hasClass('single-post')) {
      _this.Noticias.init();
    }

    _this.Home.init();
  },

  onResize: function() {
    var _this = this;

    _this.Programacion.Single.sizeSlideImageHolder();
    _this.Menu.closeMenu();
    _this.Layout.layoutMasonry();
  },

  fixWidows: function() {
    // utility class mainly for use on headines to avoid widows [single words on a new line]
    $('.js-fix-widows').each(function(){
      var string = $(this).html();
      string = string.replace(/ ([^ ]*)$/,' $1');
      $(this).html(string);
    });
  }
};

Site.Layout = {
  $masonry: null,

  init: function() {
    var _this = this;

    if ($('.home-item').length) {
      _this.initMasonry();
    }
  },

  initMasonry: function() {
    var _this = this;

    _this.$masonry = $('#home-holder').masonry({
      itemSelector: '.home-item',
      transitionDuration: 0,
      resize: false
    });

    _this.$masonry.imagesLoaded().progress( function() {
      _this.layoutMasonry();
    });
  },

  layoutMasonry: function() {
    var _this = this;

    if ($('.home-item').length) {
      _this.$masonry.masonry('layout');
    }
  }
};

Site.Home = {
  init: function() {
    var _this = this;

    if ($('.home-item').length) {
      _this.bindItemHover();
    }
  },

  bindItemHover: function() {
    $('.home-item a').hover(
      function() {
        $('.home-item a').not(this).parent('.home-item').addClass('home-item-hidden');
        $(this).parent('.home-item').addClass('home-item-hover');
      },
      function() {
        $('.home-item').removeClass('home-item-hidden home-item-hover');
      }
    );
  }
};

Site.Menu = {
  init: function() {
    var _this = this;

    _this.bindToggle();
  },

  bindToggle: function() {
    $('.menu-toggle').on('click', function() {
      $('body').toggleClass('menu-active');
    });
  },

  closeMenu: function() {
    $('body').removeClass('menu-active');
  },
};

Site.Programacion = {

  Archive: {
    init: function() {
      var _this = this;

      if ($('[data-hover-color]').length) {
        _this.bindHoverColor();
      }
    },

    bindHoverColor: function() {
      $('[data-hover-color]').hover(
        function() {
          $(this).css('color', $(this).attr('data-hover-color'));
        },
        function() {
          $(this).css('color', 'inherit');
        }
      );
    }
  },

  Single: {
    init: function() {
      var _this = this;

      $(document).ready(function () {
        _this.initGallery();
        _this.bindToggle();
        _this.sizeSlideImageHolder();
      });
    },

    initGallery: function() {
      var _this = this;

      _this.swiper = new Swiper('.swiper-container', {
        loop: true,
        nextButton: '.swiper-next',
        prevButton: '.swiper-prev',
        pagination: '#single-programacion-gallery-pagination',
        paginationType: 'custom',
        paginationCustomRender: function (swiper, current, total) {
          return '' + current + ' / ' + total + '';
        },
        onClick: function(swiper) {
          swiper.slideNext();
        },
      });
    },

    sizeSlideImageHolder: function() {
      var _this = this,
        windowWidth = $(window).width(),
        headerHeight = $('#header').outerHeight(true);

      $('.programacion-content-holder').scrollTop(0);
      $('body').removeClass('drawer-open');

      var contentHeight = $('.programacion-header').outerHeight(true);

      if (windowWidth < 1024) {
        $('.slide-image-holder').css({
          'padding-top': 0,
          'padding-bottom': 0,
        });
      } else {
        $('.slide-image-holder').css({
          'padding-top': headerHeight,
          'padding-bottom': contentHeight,
        });
      }
    },

    bindToggle: function() {
      var _this = this;

      $('.programacion-drawer-toggle').on('click', function() {
        _this.toggleContent();
      });
    },

    toggleContent: function() {
      $('body').toggleClass('drawer-open');
      $('.programacion-content-holder').scrollTop(0);
    }
  }

};

Site.Noticias = {
  init: function() {
    this.Galleries.init();
  },

  Galleries: {
    init: function() {
      $('.swiper-container').each(function() {
        var swiper = new Swiper($(this), {
          loop: true,
          onClick: function(swiper) {
            swiper.slideNext();
          },
        });
      });
    },
  }
};

Site.init();
<|endoftext|>


<commit_before>/**
 * InvertedIndex Class
 * @class
 */
class Index {

  /**
   * class constructor
   * @constructor
   */
  constructor() {
    this.indexObject = {};
    this.fileArray = [];
  }

  /**
   * validJson
   *
   * Reads the JSON data using FileReader
   *
   * @param {object} file - Content of the file
   * @param {string} filename - Name of the file
   * @return {string}
   */
  validJson(filename, file) {
    if (!file.length) {
      return 'Empty file';
    }

    try {
      const jsonData = JSON.parse(file);
      if (this.checkTitleAndText(jsonData)) {
        return 'No title or text';
      }
      this.createIndex(filename, jsonData);
      this.jsonData = jsonData;
      return 'File Uploaded';
    } catch (error) {
      return 'Invalid Json file';
    }
  }

  /**
   * cleanData
   *
   * Tokenizes data
   *
   * @param {string}
   * @return {object}
   */
  cleanData(data) {
    const terms = (data)
      .toLowerCase()
      .replace(/[^a-z0-9 ]/gi, '')
      .split(' ');
    return terms;
  }

  /**
   * checkTitleAndText
   *
   * Checks that the array has a title and a text.
   *
   * @param {array}
   * @return {bool}
   */
  checkTitleAndText(myArray) {
    return myArray.some(value => !value.hasOwnProperty('title') || !value.hasOwnProperty('text'));
  }

  /**
   * getUniqueTerms
   *
   * Gets the unique terms.
   *
   * @param {array}
   * @return {object}
   */
  getUniqueTerms(terms) {
    return terms.filter((value, index, arr) => arr.indexOf(value) === index);
  }

  /**
   * getValues
   *
   * Gets the values for each of the terms.
   *
   * @param {object}
   * @param {string}
   * @return {array}
   */
  getValues(jsonData, indexTerm) {
    const objArray = [];
    let i = 0;
    for (const object of jsonData) {
      for (const key in object) {
        if (object.hasOwnProperty(key)) {
          const terms = this.cleanData(object[key]);
          if (terms.indexOf(indexTerm) > -1 && objArray.indexOf(i) < 0) {
            objArray.push(i);
          }
        }
      }
      i += 1;
    }
    return objArray;
  }

  /**
   * createIndex
   *
   * Ensures that a correct Index is created
   *
   * @param {object}
   * @param {string}
   */
  createIndex(filename, jsonData) {
    if (jsonData != null) {
      let indexTerms = [];
      const index = {};
      jsonData.forEach((obj, objIndex) => {
        Object.keys(obj).forEach((key) => {
          const terms = this.cleanData(obj[key]);
          indexTerms = indexTerms.concat(this.getUniqueTerms(terms));
        });
      });
      indexTerms.forEach((indexTerm) => {
        const objArray = this.getValues(jsonData, indexTerm);
        index[indexTerm] = objArray;
      });
      this.indexObject[filename] = index;
    }
  }

  /**
   * getIndex
   *
   * Gets the created Index from createIndex
   *
   * @param {object} file - Content of the file
   * @return {object}
   */
  getIndex(file) {
    return this.indexObject;
  }

  /**
   * getResult
   *
   * Searches the created index
   *
   * @param {string}
   * @param {string}
   * @preturn {object}
   */
  getResult(items, filename) {
    const fileResult = {};
    for (const item of items) {
      if (item !== '') {
        if (this.indexObject[filename][item.toLowerCase()] !== undefined) {
          fileResult[item] = this.indexObject[filename][item.toLowerCase()];
        } else {
          fileResult[item] = [];
        }
      }
    }
    return fileResult;
  }

  /**
   * searchIndex
   *
   * Searches the created Index
   *
   * @param {string}
   * @param {array}
   *
   * @return{object}
   */
  searchIndex(filename, ...valuesToSearch) {
    if (Object.keys(this.indexObject).length !== 0) {
      const results = {};
      let items = valuesToSearch.toString();
      items = this.cleanData(items);
      if (Object.keys(this.indexObject).indexOf(filename) !== -1) {
        results[filename] = this.getResult(items, filename);
      } else {
        if (filename === 'All') {
          for (const file of Object.keys(this.indexObject)) {
            results[file] = this.getResult(items, file);
          }
        }
      }
      return results;
    }
  }
}
<commit_msg>Implemented all the feedback as per the pull request comments<commit_after>/**
 * InvertedIndex Class
 * @class
 */
class Index {

  /**
   * class constructor
   * @constructor
   */
  constructor() {
    this.indexObject = {};
    this.fileArray = [];
  }

  /**
   * validJson
   *
   * Validates the file input
   *
   * @param {string} filename - Name of the file
   * @param {object} file - Content of the file
   * @return {string}
   */
  validJson(filename, file) {
    if (!file.length) {
      return 'Empty file';
    }
    try {
      const jsonData = JSON.parse(file);
      if (this.checkTitleAndText(jsonData)) {
        return 'No title or text';
      }
      this.jsonData = jsonData;
      return 'Correct file';
    } catch (error) {
      return 'Invalid JSON file';
    }
  }

  /**
   * cleanData
   *
   * Tokenizes data
   *
   * @param {string}
   * @return {object}
   */
  cleanData(data) {
    const terms = (data)
      .toLowerCase()
      .replace(/[^a-z0-9 ]/gi, '')
      .split(' ');
    return terms;
  }

  /**
   * checkTitleAndText
   *
   * Checks that the array has a title and a text.
   *
   * @param {array}
   * @return {bool}
   */
  checkTitleAndText(myArray) {
    return myArray.some(value => !value.hasOwnProperty('title') || !value.hasOwnProperty('text'));
  }

  /**
   * getUniqueTerms
   *
   * Gets the unique terms.
   *
   * @param {array}
   * @return {object}
   */
  getUniqueTerms(terms) {
    return terms.filter((value, index, arr) => arr.indexOf(value) === index);
  }

  /**
   * getValues
   *
   * Gets the values for each of the terms.
   *
   * @param {object}
   * @param {string}
   * @return {array}
   */
  getValues(jsonData, indexTerm) {
    const objArray = [];
    let i = 0;
    jsonData.forEach((object) => {
      Object.keys(object).forEach((key) => {
        const terms = this.cleanData(object[key]);
        if (terms.indexOf(indexTerm) > -1 && objArray.indexOf(i) < 0) {
          objArray.push(i);
        }
      });
      i += 1;
    });
    return objArray;
  }

  /**
   * createIndex
   *
   * Ensures that a correct Index is created
   *
   * @param {object}
   * @param {string}
   */
  createIndex(filename, content) {
    const valid = this.validJson(filename, content);
    if (valid === 'Correct file') {
      const jsonData = JSON.parse(content);
      if (jsonData != null) {
        let indexTerms = [];
        const index = {};
        jsonData.forEach((obj) => {
          Object.keys(obj).forEach((key) => {
            const terms = this.cleanData(obj[key]);
            indexTerms = indexTerms.concat(this.getUniqueTerms(terms));
          });
        });
        indexTerms.forEach((indexTerm) => {
          const objArray = this.getValues(jsonData, indexTerm);
          index[indexTerm] = objArray;
        });
        this.indexObject[filename] = index;
        return valid;
      }
    } else {
      return valid;
    }
  }

  /**
   * getIndex
   *
   * Gets the created Index from createIndex
   *
   * @param {object} file - Content of the file
   * @return {object}
   */
  getIndex(filename) {
    return this.indexObject[filename];
  }

  /**
   * getResult
   *
   * Searches the created index
   *
   * @param {string}
   * @param {string}
   * @preturn {object}
   */
  getResult(items, filename) {
    const fileResult = {};
    items.forEach((item) => {
      if (item !== '') {
        fileResult[item] = this.indexObject[filename][item.toLowerCase()];
      } else {
        fileResult[item] = [];
      }
    });
    return fileResult;
  }

  /**
   * searchIndex
   *
   * Searches the created Index
   *
   * @param {string}
   * @param {array}
   *
   * @return{object}
   */
  searchIndex(filename, ...valuesToSearch) {
    const results = {};
    let items = valuesToSearch.toString();
    items = this.cleanData(items);
    if (filename === 'All') {
      Object.keys(this.indexObject).forEach((file) => {
        results[file] = this.getResult(items, file);
      });
    } else {
      results[filename] = this.getResult(items, filename);
    }
    return results;
  }
}
<|endoftext|>


<commit_before>function get_orientation_mode(){
  var width = $(window).width();
  var height = $(window).height();

  if(height > width){
    return true;
  }else{
    return false;
  }
};

var right_pos = $("video").width() - $(window).width();

if (window.DeviceOrientationEvent) {

  window.addEventListener('deviceorientation', function(eventData) {
    var tiltLR = Math.floor(eventData.gamma);
    $("#LR").text(tiltLR);
    var tiltFB = Math.floor(eventData.beta);
    $("#FB").text(tiltFB);

    $("#log2").text(right_pos);

    if(tiltLR > 0){
      $(".video-wrapper").css("left", 0)
    }else if (parseInt($(".video-wrapper").css("right")) > right_pos) {

    }else{
      $(".video-wrapper").css("left", tiltLR*4 + "%")
    }

  }, false);
}

$.fn.zoom = function () {

  var w_height = $(window).height();
  console.log(w_height);
  $(this).css("height", w_height +"px");
};

$(document).ready(function(){
  $("video").zoom();
  var isPlaying = false;
  var portrait = get_orientation_mode();
  var videoPlayer = $("video")[0];
  $(window).on("orientationchange",function(){
    portrait = get_orientation_mode();
    if(portrait){
      $("video").zoom();
    }else{
      //$("video").css("zoom", "100%");
    }
  });

  $(".play-button").click( function(){
    console.log("click");
    $(this).find('i').toggleClass('fa-pause fa-play');
   togglePlay();
 })
 function togglePlay() {
   console.log(isPlaying);
  if (isPlaying) {
    videoPlayer.pause()
    console.log("if");
    isPlaying = false;

  } else {
    console.log("else");
    videoPlayer.play();
    $(this).find('i.fa').removeClass('fa-play');
    $(this).find("i.fa").addClass('fa-pause');
    isPlaying = true;

  }
 };

});
<commit_msg>commit in order to pull<commit_after>function get_orientation_mode(){
  var width = $(window).width();
  var height = $(window).height();

  if(height > width){
    return true;
  }else{
    return false;
  }
};

if (window.DeviceOrientationEvent) {

  window.addEventListener('deviceorientation', function(eventData) {
    var tiltLR = Math.floor(eventData.gamma);
    $("#LR").text(tiltLR);
    var tiltFB = Math.floor(eventData.beta);
    $("#FB").text(tiltFB);

    var right_pos = $("video").width() - $(window).width();

    $("#log2").text(right_pos);

    if(tiltLR > 0){
      $(".video-wrapper").css("left", 0)
    }else if (parseInt($(".video-wrapper").css("right")) > right_pos) {
        alert("hit the wall")
    }else{
      $(".video-wrapper").css("left", tiltLR*4 + "%")

    }

  }, false);
}

$.fn.zoom = function () {

  var w_height = $(window).height();
  console.log(w_height);
  $(this).css("height", w_height +"px");
};

$(document).ready(function(){
  $("video").zoom();
  var isPlaying = false;
  var portrait = get_orientation_mode();
  var videoPlayer = $("video")[0];
  $(window).on("orientationchange",function(){
    portrait = get_orientation_mode();
    if(portrait){
      $("video").zoom();
    }else{
      //$("video").css("zoom", "100%");
    }
  });

  $(".play-button").click( function(){
    console.log("click");
   /*playButton.find('span').toggleClass('glyphicon-pause glyphicon-play');*/
   togglePlay();
 })
 function togglePlay() {
   console.log(isPlaying);
  if (isPlaying) {
    videoPlayer.pause()
    $(".play-button").innerHTML="Play";
    console.log("if");
    isPlaying = false;
    //playButton.innerHTML='Pause';
    //playButton.style.backgroundColor = '#91D7F3 ';

  } else {
    console.log("else");
    videoPlayer.play();
    $(".play-button").innerHTML="Pause";
    isPlaying = true;
   // playButton.innerHTML='Play';
   // playButton.style.backgroundColor = '#C9EAF8 ';
  }
 };

});
<|endoftext|>


<commit_before>import Media from '../mixin/media';
import { getMaxPathLength } from '../core/svg';
import {
    css,
    Dimensions,
    each,
    findIndex,
    isNumber,
    isString,
    isUndefined,
    noop,
    toFloat,
    toPx,
    trigger,
    ucfirst,
} from 'uikit-util';

const props = {
    x: transformFn,
    y: transformFn,
    rotate: transformFn,
    scale: transformFn,
    color: colorFn,
    backgroundColor: colorFn,
    borderColor: colorFn,
    blur: filterFn,
    hue: filterFn,
    fopacity: filterFn,
    grayscale: filterFn,
    invert: filterFn,
    saturate: filterFn,
    sepia: filterFn,
    opacity: cssPropFn,
    stroke: strokeFn,
    bgx: backgroundFn,
    bgy: backgroundFn,
};

const { keys } = Object;

export default {
    mixins: [Media],

    props: fillObject(keys(props), 'list'),

    data: fillObject(keys(props), undefined),

    computed: {
        props(properties, $el) {
            return keys(props).reduce((result, prop) => {
                if (!isUndefined(properties[prop])) {
                    result[prop] = props[prop](prop, $el, properties[prop].slice());
                }
                return result;
            }, {});
        },
    },

    events: {
        bgimageload() {
            this.$emit();
        },
    },

    methods: {
        reset() {
            each(this.getCss(0), (_, prop) => css(this.$el, prop, ''));
        },

        getCss(percent) {
            return keys(this.props).reduce(
                (css, prop) => {
                    this.props[prop](css, percent);
                    return css;
                },
                { transform: '', filter: '' }
            );
        },
    },
};

function transformFn(prop, el, stops) {
    const unit = getUnit(stops) || { x: 'px', y: 'px', rotate: 'deg' }[prop] || '';
    let transformFn;

    if (prop === 'x' || prop === 'y') {
        prop = `translate${ucfirst(prop)}`;
        transformFn = (stop) => toFloat(toFloat(stop).toFixed(unit === 'px' ? 0 : 6));
    }

    if (stops.length === 1) {
        stops.unshift(prop === 'scale' ? 1 : 0);
    }

    stops = parseStops(stops, transformFn);

    return (css, percent) => {
        css.transform += ` ${prop}(${getValue(stops, percent)}${unit})`;
    };
}

function colorFn(prop, el, stops) {
    if (stops.length === 1) {
        stops.unshift(getCssValue(el, prop, ''));
    }

    stops = parseStops(stops, (stop) => parseColor(el, stop));

    return (css, percent) => {
        const [start, end, p] = getStop(stops, percent);
        const value = start
            .map((value, i) => {
                value += p * (end[i] - value);
                return i === 3 ? toFloat(value) : parseInt(value, 10);
            })
            .join(',');
        css[prop] = `rgba(${value})`;
    };
}

function parseColor(el, color) {
    return getCssValue(el, 'color', color)
        .split(/[(),]/g)
        .slice(1, -1)
        .concat(1)
        .slice(0, 4)
        .map(toFloat);
}

function filterFn(prop, el, stops) {
    if (stops.length === 1) {
        stops.unshift(0);
    }

    const unit = getUnit(stops) || { blur: 'px', hue: 'deg' }[prop] || '%';
    prop = { fopacity: 'opacity', hue: 'hue-rotate' }[prop] || prop;
    stops = parseStops(stops);

    return (css, percent) => {
        const value = getValue(stops, percent);
        css.filter += ` ${prop}(${value + unit})`;
    };
}

function cssPropFn(prop, el, stops) {
    if (stops.length === 1) {
        stops.unshift(getCssValue(el, prop, ''));
    }

    stops = parseStops(stops);

    return (css, percent) => {
        css[prop] = getValue(stops, percent);
    };
}

function strokeFn(prop, el, stops) {
    if (stops.length === 1) {
        stops.unshift(0);
    }

    const unit = getUnit(stops);
    const length = getMaxPathLength(el);
    stops = parseStops(stops.reverse(), (stop) => {
        stop = toFloat(stop);
        return unit === '%' ? (stop * length) / 100 : stop;
    });

    if (!stops.some(([value]) => value)) {
        return noop;
    }

    css(el, 'strokeDasharray', length);

    return (css, percent) => {
        css.strokeDashoffset = getValue(stops, percent);
    };
}

function backgroundFn(prop, el, stops) {
    if (stops.length === 1) {
        stops.unshift(0);
    }

    prop = prop.substr(-1);
    const attr = prop === 'y' ? 'height' : 'width';
    stops = parseStops(stops, (stop) => toPx(stop, attr, el));

    const bgPos = getCssValue(el, `background-position-${prop}`, '');

    return getCssValue(el, 'backgroundSize', '') === 'cover'
        ? backgroundCoverFn(prop, el, stops, bgPos, attr)
        : setBackgroundPosFn(prop, stops, bgPos);
}

function backgroundCoverFn(prop, el, stops, bgPos, attr) {
    const dimImage = getBackgroundImageDimensions(el);

    if (!dimImage.width) {
        return noop;
    }

    const values = stops.map(([value]) => value);
    const min = Math.min(...values);
    const max = Math.max(...values);
    const down = values.indexOf(min) < values.indexOf(max);

    const diff = max - min;
    let pos = (down ? -diff : 0) - (down ? min : max);

    const dimEl = {
        width: el.offsetWidth,
        height: el.offsetHeight,
    };

    const baseDim = Dimensions.cover(dimImage, dimEl);
    const span = baseDim[attr] - dimEl[attr];

    if (span < diff) {
        dimEl[attr] = baseDim[attr] + diff - span;
    } else if (span > diff) {
        const posPercentage = dimEl[attr] / toPx(bgPos, attr, el, true);

        if (posPercentage) {
            pos -= (span - diff) / posPercentage;
        }
    }

    const dim = Dimensions.cover(dimImage, dimEl);

    const fn = setBackgroundPosFn(prop, stops, `${pos}px`);
    return (css, percent) => {
        fn(css, percent);
        css.backgroundSize = `${dim.width}px ${dim.height}px`;
        css.backgroundRepeat = 'no-repeat';
    };
}

function setBackgroundPosFn(prop, stops, pos) {
    return function (css, percent) {
        css[`background-position-${prop}`] = `calc(${pos} + ${getValue(stops, percent)}px)`;
    };
}

const dimensions = {};
function getBackgroundImageDimensions(el) {
    const src = css(el, 'backgroundImage').replace(/^none|url\(["']?(.+?)["']?\)$/, '$1');

    if (dimensions[src]) {
        return dimensions[src];
    }

    const image = new Image();
    if (src) {
        image.src = src;

        if (!image.naturalWidth) {
            image.onload = () => {
                dimensions[src] = toDimensions(image);
                trigger(el, 'bgimageload');
            };
        }
    }

    return (dimensions[src] = toDimensions(image));
}

function toDimensions(image) {
    return {
        width: image.naturalWidth,
        height: image.naturalHeight,
    };
}

function parseStops(stops, fn = toFloat) {
    const result = [];
    const { length } = stops;
    let nullIndex = 0;
    for (let i = 0; i < length; i++) {
        let [value, percent] = isString(stops[i]) ? stops[i].trim().split(' ') : [stops[i]];
        value = fn(value);
        percent = percent ? toFloat(percent) / 100 : null;

        if (i === 0) {
            if (percent === null) {
                percent = 0;
            } else if (percent) {
                result.push([value, 0]);
            }
        } else if (i === length - 1) {
            if (percent === null) {
                percent = 1;
            } else if (percent !== 1) {
                result.push([value, percent]);
                percent = 1;
            }
        }

        result.push([value, percent]);

        if (percent === null) {
            nullIndex++;
        } else if (nullIndex) {
            const leftPercent = result[i - nullIndex - 1][1];
            const p = (percent - leftPercent) / (nullIndex + 1);
            for (let j = nullIndex; j > 0; j--) {
                result[i - j][1] = leftPercent + p * (nullIndex - j + 1);
            }

            nullIndex = 0;
        }
    }

    return result;
}

function getStop(stops, percent) {
    const index = findIndex(stops.slice(1), ([, targetPercent]) => percent <= targetPercent) + 1;
    return [
        stops[index - 1][0],
        stops[index][0],
        (percent - stops[index - 1][1]) / (stops[index][1] - stops[index - 1][1]),
    ];
}

function getValue(stops, percent) {
    const [start, end, p] = getStop(stops, percent);
    return isNumber(start) ? start + Math.abs(start - end) * p * (start < end ? 1 : -1) : +end;
}

const unitRe = /^[\d-]+([^\s]+)/;
function getUnit(stops, defaultUnit) {
    for (const stop of stops) {
        const match = stop.match?.(unitRe);
        if (match) {
            return match[1];
        }
    }
    return defaultUnit;
}

function getCssValue(el, prop, value) {
    const prev = el.style[prop];
    const val = css(css(el, prop, value), prop);
    el.style[prop] = prev;
    return val;
}

function fillObject(keys, value) {
    return keys.reduce((data, prop) => {
        data[prop] = value;
        return data;
    }, {});
}
<commit_msg>fix: unit regex<commit_after>import Media from '../mixin/media';
import { getMaxPathLength } from '../core/svg';
import {
    css,
    Dimensions,
    each,
    findIndex,
    isNumber,
    isString,
    isUndefined,
    noop,
    toFloat,
    toPx,
    trigger,
    ucfirst,
} from 'uikit-util';

const props = {
    x: transformFn,
    y: transformFn,
    rotate: transformFn,
    scale: transformFn,
    color: colorFn,
    backgroundColor: colorFn,
    borderColor: colorFn,
    blur: filterFn,
    hue: filterFn,
    fopacity: filterFn,
    grayscale: filterFn,
    invert: filterFn,
    saturate: filterFn,
    sepia: filterFn,
    opacity: cssPropFn,
    stroke: strokeFn,
    bgx: backgroundFn,
    bgy: backgroundFn,
};

const { keys } = Object;

export default {
    mixins: [Media],

    props: fillObject(keys(props), 'list'),

    data: fillObject(keys(props), undefined),

    computed: {
        props(properties, $el) {
            return keys(props).reduce((result, prop) => {
                if (!isUndefined(properties[prop])) {
                    result[prop] = props[prop](prop, $el, properties[prop].slice());
                }
                return result;
            }, {});
        },
    },

    events: {
        bgimageload() {
            this.$emit();
        },
    },

    methods: {
        reset() {
            each(this.getCss(0), (_, prop) => css(this.$el, prop, ''));
        },

        getCss(percent) {
            return keys(this.props).reduce(
                (css, prop) => {
                    this.props[prop](css, percent);
                    return css;
                },
                { transform: '', filter: '' }
            );
        },
    },
};

function transformFn(prop, el, stops) {
    const unit = getUnit(stops) || { x: 'px', y: 'px', rotate: 'deg' }[prop] || '';
    let transformFn;

    if (prop === 'x' || prop === 'y') {
        prop = `translate${ucfirst(prop)}`;
        transformFn = (stop) => toFloat(toFloat(stop).toFixed(unit === 'px' ? 0 : 6));
    }

    if (stops.length === 1) {
        stops.unshift(prop === 'scale' ? 1 : 0);
    }

    stops = parseStops(stops, transformFn);

    return (css, percent) => {
        css.transform += ` ${prop}(${getValue(stops, percent)}${unit})`;
    };
}

function colorFn(prop, el, stops) {
    if (stops.length === 1) {
        stops.unshift(getCssValue(el, prop, ''));
    }

    stops = parseStops(stops, (stop) => parseColor(el, stop));

    return (css, percent) => {
        const [start, end, p] = getStop(stops, percent);
        const value = start
            .map((value, i) => {
                value += p * (end[i] - value);
                return i === 3 ? toFloat(value) : parseInt(value, 10);
            })
            .join(',');
        css[prop] = `rgba(${value})`;
    };
}

function parseColor(el, color) {
    return getCssValue(el, 'color', color)
        .split(/[(),]/g)
        .slice(1, -1)
        .concat(1)
        .slice(0, 4)
        .map(toFloat);
}

function filterFn(prop, el, stops) {
    if (stops.length === 1) {
        stops.unshift(0);
    }

    const unit = getUnit(stops) || { blur: 'px', hue: 'deg' }[prop] || '%';
    prop = { fopacity: 'opacity', hue: 'hue-rotate' }[prop] || prop;
    stops = parseStops(stops);

    return (css, percent) => {
        const value = getValue(stops, percent);
        css.filter += ` ${prop}(${value + unit})`;
    };
}

function cssPropFn(prop, el, stops) {
    if (stops.length === 1) {
        stops.unshift(getCssValue(el, prop, ''));
    }

    stops = parseStops(stops);

    return (css, percent) => {
        css[prop] = getValue(stops, percent);
    };
}

function strokeFn(prop, el, stops) {
    if (stops.length === 1) {
        stops.unshift(0);
    }

    const unit = getUnit(stops);
    const length = getMaxPathLength(el);
    stops = parseStops(stops.reverse(), (stop) => {
        stop = toFloat(stop);
        return unit === '%' ? (stop * length) / 100 : stop;
    });

    if (!stops.some(([value]) => value)) {
        return noop;
    }

    css(el, 'strokeDasharray', length);

    return (css, percent) => {
        css.strokeDashoffset = getValue(stops, percent);
    };
}

function backgroundFn(prop, el, stops) {
    if (stops.length === 1) {
        stops.unshift(0);
    }

    prop = prop.substr(-1);
    const attr = prop === 'y' ? 'height' : 'width';
    stops = parseStops(stops, (stop) => toPx(stop, attr, el));

    const bgPos = getCssValue(el, `background-position-${prop}`, '');

    return getCssValue(el, 'backgroundSize', '') === 'cover'
        ? backgroundCoverFn(prop, el, stops, bgPos, attr)
        : setBackgroundPosFn(prop, stops, bgPos);
}

function backgroundCoverFn(prop, el, stops, bgPos, attr) {
    const dimImage = getBackgroundImageDimensions(el);

    if (!dimImage.width) {
        return noop;
    }

    const values = stops.map(([value]) => value);
    const min = Math.min(...values);
    const max = Math.max(...values);
    const down = values.indexOf(min) < values.indexOf(max);

    const diff = max - min;
    let pos = (down ? -diff : 0) - (down ? min : max);

    const dimEl = {
        width: el.offsetWidth,
        height: el.offsetHeight,
    };

    const baseDim = Dimensions.cover(dimImage, dimEl);
    const span = baseDim[attr] - dimEl[attr];

    if (span < diff) {
        dimEl[attr] = baseDim[attr] + diff - span;
    } else if (span > diff) {
        const posPercentage = dimEl[attr] / toPx(bgPos, attr, el, true);

        if (posPercentage) {
            pos -= (span - diff) / posPercentage;
        }
    }

    const dim = Dimensions.cover(dimImage, dimEl);

    const fn = setBackgroundPosFn(prop, stops, `${pos}px`);
    return (css, percent) => {
        fn(css, percent);
        css.backgroundSize = `${dim.width}px ${dim.height}px`;
        css.backgroundRepeat = 'no-repeat';
    };
}

function setBackgroundPosFn(prop, stops, pos) {
    return function (css, percent) {
        css[`background-position-${prop}`] = `calc(${pos} + ${getValue(stops, percent)}px)`;
    };
}

const dimensions = {};
function getBackgroundImageDimensions(el) {
    const src = css(el, 'backgroundImage').replace(/^none|url\(["']?(.+?)["']?\)$/, '$1');

    if (dimensions[src]) {
        return dimensions[src];
    }

    const image = new Image();
    if (src) {
        image.src = src;

        if (!image.naturalWidth) {
            image.onload = () => {
                dimensions[src] = toDimensions(image);
                trigger(el, 'bgimageload');
            };
        }
    }

    return (dimensions[src] = toDimensions(image));
}

function toDimensions(image) {
    return {
        width: image.naturalWidth,
        height: image.naturalHeight,
    };
}

function parseStops(stops, fn = toFloat) {
    const result = [];
    const { length } = stops;
    let nullIndex = 0;
    for (let i = 0; i < length; i++) {
        let [value, percent] = isString(stops[i]) ? stops[i].trim().split(' ') : [stops[i]];
        value = fn(value);
        percent = percent ? toFloat(percent) / 100 : null;

        if (i === 0) {
            if (percent === null) {
                percent = 0;
            } else if (percent) {
                result.push([value, 0]);
            }
        } else if (i === length - 1) {
            if (percent === null) {
                percent = 1;
            } else if (percent !== 1) {
                result.push([value, percent]);
                percent = 1;
            }
        }

        result.push([value, percent]);

        if (percent === null) {
            nullIndex++;
        } else if (nullIndex) {
            const leftPercent = result[i - nullIndex - 1][1];
            const p = (percent - leftPercent) / (nullIndex + 1);
            for (let j = nullIndex; j > 0; j--) {
                result[i - j][1] = leftPercent + p * (nullIndex - j + 1);
            }

            nullIndex = 0;
        }
    }

    return result;
}

function getStop(stops, percent) {
    const index = findIndex(stops.slice(1), ([, targetPercent]) => percent <= targetPercent) + 1;
    return [
        stops[index - 1][0],
        stops[index][0],
        (percent - stops[index - 1][1]) / (stops[index][1] - stops[index - 1][1]),
    ];
}

function getValue(stops, percent) {
    const [start, end, p] = getStop(stops, percent);
    return isNumber(start) ? start + Math.abs(start - end) * p * (start < end ? 1 : -1) : +end;
}

const unitRe = /^-?\d+([^\s\d]+)/;
function getUnit(stops, defaultUnit) {
    for (const stop of stops) {
        const match = stop.match?.(unitRe);
        if (match) {
            return match[1];
        }
    }
    return defaultUnit;
}

function getCssValue(el, prop, value) {
    const prev = el.style[prop];
    const val = css(css(el, prop, value), prop);
    el.style[prop] = prev;
    return val;
}

function fillObject(keys, value) {
    return keys.reduce((data, prop) => {
        data[prop] = value;
        return data;
    }, {});
}
<|endoftext|>


<commit_before>
    $(document).ready(function(){
        //$('#replaceable').fadeIn(300);
        if ('onhashchange' in window) {
            window.onhashchange = hashHasChanged;
        } else {
           alert('Browser doesnt support hashchanges, need to account for this - direct link alternative');
        }

        $('#mainNav').on("click","span",function(){
            $('#mainNav span').each(function() {
                 $(this).removeClass('active');
            })

            $(this).addClass('active');
        });

    });

    function hashHasChanged(event){
        var url = event.currentTarget.location.hash;
        $('#mainNav span').each(function() {
             $(this).removeClass('active');
        })
        $('#mainNav a[href=' + url + ']').parent().addClass('active');

        url = url.replace('#','');
        console.log(url);
        pageOut(url);
    };

    function pageOut(url){
        $('#replaceable').animate({
                opacity: 0,
                left: -100
            },
            1000,
            function() {
                loadPage(url);
        });
    }

    function loadPage(url)	//the function that loads pages via AJAX
    {
        //url=url.replace('#page','');	//strip the #page part of the hash and leave only the page number

        $('#loading').css('visibility','visible');	//show the rotating gif animation

        if (url == null || url == '') {
            url = 'indexFill';
        }

        $.ajax({	//create an ajax request to load_page.php
            type: "POST",
            url: "load_page.php",
            data: "page=" + url,
            dataType: "html",	//expect html to be returned
            success: function(msg){

                if(parseInt(msg)!=0)	//if no errors
                {

                    $('#replaceable').html(msg);	//load the returned html into pageContent
                    $('#replaceable').animate({
                        opacity: 1,
                        left: 0
                    },
                    1000,
                    function() {
                    });
                }
            }

        });
    };<commit_msg>nav update<commit_after>
    $(document).ready(function(){
        //$('#replaceable').fadeIn(300);
        if ('onhashchange' in window) {
            window.onhashchange = hashHasChanged;
        } else {
           alert('Browser doesnt support hashchanges, need to account for this - direct link alternative');
        }

        $('#mainNav a').on("click","span",function(){
            $('#mainNav span').each(function() {
                 $(this).removeClass('active');
            })

            $(this).addClass('active');
        });

    });

    function hashHasChanged(event){
        var url = event.currentTarget.location.hash;
        $('#mainNav span').each(function() {
             $(this).removeClass('active');
        })
        $('#mainNav a[href=' + url + ']').parent().addClass('active');

        url = url.replace('#','');
        console.log(url);
        pageOut(url);
    };

    function pageOut(url){
        $('#replaceable').animate({
                opacity: 0,
                left: -100
            },
            1000,
            function() {
                loadPage(url);
        });
    }

    function loadPage(url)	//the function that loads pages via AJAX
    {
        //url=url.replace('#page','');	//strip the #page part of the hash and leave only the page number

        $('#loading').css('visibility','visible');	//show the rotating gif animation

        if (url == null || url == '') {
            url = 'indexFill';
        }

        $.ajax({	//create an ajax request to load_page.php
            type: "POST",
            url: "load_page.php",
            data: "page=" + url,
            dataType: "html",	//expect html to be returned
            success: function(msg){

                if(parseInt(msg)!=0)	//if no errors
                {

                    $('#replaceable').html(msg);	//load the returned html into pageContent
                    $('#replaceable').animate({
                        opacity: 1,
                        left: 0
                    },
                    1000,
                    function() {
                    });
                }
            }

        });
    };<|endoftext|>


<commit_before>function placeBsBtn() {
	var importBtn = "<button id='import' class='bs-btn bs-btn-default'>Import</button>";
	$("#import-1_wrapper").append(importBtn);

	$("#import.bs-btn").click(function () {
		var pokes = document.getElementsByClassName("import-team-text")[0].value;
		addSets(pokes);
	});
}

function ExportPokemon(pokeInfo) {
	var pokemon = createPokemon(pokeInfo);
	var EV_counter = 0;
	var finalText = "";
	finalText = pokemon.name + (pokemon.item ? " @ " + pokemon.item : "") + "\n";
	finalText += pokemon.nature && gen > 2 ? pokemon.nature + " Nature" + "\n" : "";
	finalText += pokemon.ability ? "Ability: " + pokemon.ability + "\n" : "";
	if (gen > 2) {
		finalText += "EVs: ";
		var EVs_Array = [];
		for (var stat in pokemon.evs) {
			if (pokemon.evs[stat]) {
				EVs_Array.push(pokemon.evs[stat] + " " + calc.displayStat(stat));
				EV_counter += pokemon.evs[stat];
				if (EV_counter > 510) break;
			}
		}
		finalText += serialize(EVs_Array, " / ");
		finalText += "\n";
	}
	for (var i = 0; i < 4; i++) {
		var moveName = pokemon.moves[i].name;
		if (moveName !== "(No Move)") {
			finalText += "- " + moveName + "\n";
		}
	}
	finalText = finalText.trim();
	$("textarea.import-team-text").text(finalText);
}

$("#exportL").click(function () {
	ExportPokemon($("#p1"));
});

$("#exportR").click(function () {
	ExportPokemon($("#p2"));
});

function serialize(array, separator) {
	var text = "";
	for (var i = 0; i < array.length; i++) {
		if (i < array.length - 1) {
			text += array[i] + separator;
		} else {
			text += array[i];
		}
	}
	return text;
}

function getAbility(row) {
	var ability = row[1] ? row[1].trim() : '';
	if (calc.ABILITIES[8].indexOf(ability) !== -1) return ability;
}

function statToLegacyStat(stat) {
	switch (stat) {
	case 'hp':
		return "hp";
	case 'atk':
		return "at";
	case 'def':
		return "df";
	case 'spa':
		return "sa";
	case 'spd':
		return "sd";
	case 'spe':
		return "sp";
	}
}

function getStats(currentPoke, rows, offset) {
	currentPoke.nature = "Serious";
	var currentEV;
	var currentIV;
	var currentNature;
	currentPoke.level = 100;
	for (var x = offset; x < offset + 8; x++) {
		var currentRow = rows[x] ? rows[x].split(/[/:]/) : '';
		var evs = {};
		var ivs = {};
		var ev;
		var j;

		switch (currentRow[0]) {
		case 'Level':
			currentPoke.level = parseInt(currentRow[1].trim());
			break;
		case 'EVs':
			for (j = 1; j < currentRow.length; j++) {
				currentEV = currentRow[j].trim().split(" ");
				currentEV[1] = statToLegacyStat(currentEV[1].toLowerCase());
				evs[currentEV[1]] = parseInt(currentEV[0]);
			}
			currentPoke.evs = evs;
			break;
		case 'IVs':
			for (j = 1; j < currentRow.length; j++) {
				currentIV = currentRow[j].trim().split(" ");
				currentIV[1] = statToLegacyStat(currentIV[1].toLowerCase());
				ivs[currentIV[1]] = parseInt(currentIV[0]);
			}
			currentPoke.ivs = ivs;
			break;

		}
		currentNature = rows[x] ? rows[x].trim().split(" ") : '';
		if (currentNature[1] == "Nature") {
			currentPoke.nature = currentNature[0];
		}
	}
	return currentPoke;
}

function getItem(currentRow, j) {
	for (;j < currentRow.length; j++) {
		var item = currentRow[j].trim();
		if (calc.ITEMS[8].indexOf(item) != -1) {
			return item;
		}
	}
}

function getMoves(currentPoke, rows, offset) {
	var movesFound = false;
	var moves = [];
	for (var x = offset; x < offset + 12; x++) {
		if (rows[x]) {
			if (rows[x][0] == "-") {
				movesFound = true;
				var move = rows[x].substr(2, rows[x].length - 2).replace("[", "").replace("]", "").replace("  ", "");
				moves.push(move);
			} else {
				if (movesFound == true) {
					break;
				}
			}
		}
	}
	currentPoke.moves = moves;
	return currentPoke;
}

function addToDex(poke) {
	var dexObject = {};
	if (SETDEX_SS[poke.name] == undefined) SETDEX_SS[poke.name] = {};
	if (SETDEX_SM[poke.name] == undefined) SETDEX_SM[poke.name] = {};
	if (SETDEX_XY[poke.name] == undefined) SETDEX_XY[poke.name] = {};
	if (SETDEX_BW[poke.name] == undefined) SETDEX_BW[poke.name] = {};
	if (SETDEX_DPP[poke.name] == undefined) SETDEX_DPP[poke.name] = {};
	if (SETDEX_ADV[poke.name] == undefined) SETDEX_ADV[poke.name] = {};
	if (SETDEX_GSC[poke.name] == undefined) SETDEX_GSC[poke.name] = {};
	if (SETDEX_RBY[poke.name] == undefined) SETDEX_RBY[poke.name] = {};

	if (poke.ability !== undefined) {
		dexObject.ability = poke.ability;
	}
	dexObject.level = poke.level;
	dexObject.evs = poke.evs;
	dexObject.ivs = poke.ivs;
	dexObject.moves = poke.moves;
	dexObject.nature = poke.nature;
	dexObject.item = poke.item;
	dexObject.isCustomSet = poke.isCustomSet;
	var customsets;
	if (localStorage.customsets) {
		customsets = JSON.parse(localStorage.customsets);
	} else {
		customsets = {};
	}
	if (!customsets[poke.name]) {
		customsets[poke.name] = {};
	}
	customsets[poke.name][poke.nameProp] = dexObject;
	if (poke.name === "Aegislash-Blade") {
		if (!customsets["Aegislash-Shield"]) {
			customsets["Aegislash-Shield"] = {};
		}
		customsets["Aegislash-Shield"][poke.nameProp] = dexObject;
	}
	updateDex(customsets);
}

function updateDex(customsets) {
	for (var pokemon in customsets) {
		for (var moveset in customsets[pokemon]) {
			if (!SETDEX_SS[pokemon]) SETDEX_SS[pokemon] = {};
			SETDEX_SS[pokemon][moveset] = customsets[pokemon][moveset];
			if (!SETDEX_SM[pokemon]) SETDEX_SM[pokemon] = {};
			SETDEX_SM[pokemon][moveset] = customsets[pokemon][moveset];
			if (!SETDEX_XY[pokemon]) SETDEX_XY[pokemon] = {};
			SETDEX_XY[pokemon][moveset] = customsets[pokemon][moveset];
			if (!SETDEX_BW[pokemon]) SETDEX_BW[pokemon] = {};
			SETDEX_BW[pokemon][moveset] = customsets[pokemon][moveset];
			if (!SETDEX_DPP[pokemon]) SETDEX_DPP[pokemon] = {};
			SETDEX_DPP[pokemon][moveset] = customsets[pokemon][moveset];
			if (!SETDEX_ADV[pokemon]) SETDEX_ADV[pokemon] = {};
			SETDEX_ADV[pokemon][moveset] = customsets[pokemon][moveset];
			if (!SETDEX_GSC[pokemon]) SETDEX_GSC[pokemon] = {};
			SETDEX_GSC[pokemon][moveset] = customsets[pokemon][moveset];
			if (!SETDEX_RBY[pokemon]) SETDEX_RBY[pokemon] = {};
			SETDEX_RBY[pokemon][moveset] = customsets[pokemon][moveset];
		}
	}
	localStorage.customsets = JSON.stringify(customsets);
}

function addSets(pokes) {
	var rows = pokes.split("\n");
	var currentRow;
	var currentPoke;
	var addedpokes = 0;
	for (var i = 0; i < rows.length; i++) {
		currentRow = rows[i].split(/[()@]/);
		for (var j = 0; j < currentRow.length; j++) {
			currentRow[j] = checkExeptions(currentRow[j].trim());
			if (calc.SPECIES[8][currentRow[j].trim()] !== undefined) {
				currentPoke = calc.SPECIES[8][currentRow[j].trim()];
				currentPoke.name = currentRow[j].trim();
				currentPoke.item = getItem(currentRow, j + 1);
				if (j === 1 && currentRow[0].trim()) {
					currentPoke.nameProp = currentRow[0].trim();
				} else {
					currentPoke.nameProp = "Custom Set";
				}
				currentPoke.isCustomSet = true;
				currentPoke.ability = getAbility(rows[i + 1].split(":"));
				currentPoke = getStats(currentPoke, rows, i + 1);
				currentPoke = getMoves(currentPoke, rows, i);
				addToDex(currentPoke);
				addedpokes++;
			}
		}
	}
	if (addedpokes > 0) {
		alert("Successfully imported " + addedpokes + " set(s)");
		$(allPokemon("#importedSetsOptions")).css("display", "inline");
	} else {
		alert("No sets imported, please check your syntax and try again");
	}
}

function checkExeptions(poke) {
	switch (poke) {
	case 'Aegislash':
		poke = "Aegislash-Blade";
		break;
	case 'Basculin-Blue-Striped':
		poke = "Basculin";
		break;
	case 'Keldeo-Resolute':
		poke = "Keldeo";
		break;
	case 'Mimikyu-Busted-Totem':
		poke = "Mimikyu-Totem";
		break;
	case 'Mimikyu-Busted':
		poke = "Mimikyu";
		break;
	case 'Pikachu-Alola':
	case 'Pikachu-Belle':
	case 'Pikachu-Cosplay':
	case 'Pikachu-Hoenn':
	case 'Pikachu-Kalos':
	case 'Pikachu-Libre':
	case 'Pikachu-Original':
	case 'Pikachu-Partner':
	case 'Pikachu-PhD':
	case 'Pikachu-Pop-Star':
	case 'Pikachu-Rock-Star':
	case 'Pikachu-Sinnoh':
	case 'Pikachu-Unova':
		poke = "Pikachu";
		break;
	case 'Vivillon-Fancy':
	case 'Vivillon-Pokeball':
		poke = "Vivillon";
		break;
	case 'Florges-White':
	case 'Florges-Blue':
	case 'Florges-Orange':
	case 'Florges-Yellow':
		poke = "Florges";
		break;
	}
	return poke;

}

$(allPokemon("#clearSets")).click(function () {
	if (confirm("Are you sure you want to delete your custom sets? This action cannot be undone.")) {
		localStorage.removeItem("customsets");
		alert("Custom Sets successfully cleared. Please refresh the page.");
		$(allPokemon("#importedSetsOptions")).hide();
		loadDefaultLists();
	}
});

$(allPokemon("#importedSets")).click(function () {
	var pokeID = $(this).parent().parent().prop("id");
	var showCustomSets = $(this).prop("checked");
	if (showCustomSets) {
		loadCustomList(pokeID);
	} else {
		loadDefaultLists();
	}
});

$(document).ready(function () {
	var customSets;
	placeBsBtn();
	if (localStorage.customsets) {
		customSets = JSON.parse(localStorage.customsets);
		updateDex(customSets);
		$(allPokemon("#importedSetsOptions")).css("display", "inline");
	} else {
		loadDefaultLists();
	}
});
<commit_msg>Add a Gastrodon-East condition to checkExpetions#<commit_after>function placeBsBtn() {
	var importBtn = "<button id='import' class='bs-btn bs-btn-default'>Import</button>";
	$("#import-1_wrapper").append(importBtn);

	$("#import.bs-btn").click(function () {
		var pokes = document.getElementsByClassName("import-team-text")[0].value;
		addSets(pokes);
	});
}

function ExportPokemon(pokeInfo) {
	var pokemon = createPokemon(pokeInfo);
	var EV_counter = 0;
	var finalText = "";
	finalText = pokemon.name + (pokemon.item ? " @ " + pokemon.item : "") + "\n";
	finalText += pokemon.nature && gen > 2 ? pokemon.nature + " Nature" + "\n" : "";
	finalText += pokemon.ability ? "Ability: " + pokemon.ability + "\n" : "";
	if (gen > 2) {
		finalText += "EVs: ";
		var EVs_Array = [];
		for (var stat in pokemon.evs) {
			if (pokemon.evs[stat]) {
				EVs_Array.push(pokemon.evs[stat] + " " + calc.displayStat(stat));
				EV_counter += pokemon.evs[stat];
				if (EV_counter > 510) break;
			}
		}
		finalText += serialize(EVs_Array, " / ");
		finalText += "\n";
	}
	for (var i = 0; i < 4; i++) {
		var moveName = pokemon.moves[i].name;
		if (moveName !== "(No Move)") {
			finalText += "- " + moveName + "\n";
		}
	}
	finalText = finalText.trim();
	$("textarea.import-team-text").text(finalText);
}

$("#exportL").click(function () {
	ExportPokemon($("#p1"));
});

$("#exportR").click(function () {
	ExportPokemon($("#p2"));
});

function serialize(array, separator) {
	var text = "";
	for (var i = 0; i < array.length; i++) {
		if (i < array.length - 1) {
			text += array[i] + separator;
		} else {
			text += array[i];
		}
	}
	return text;
}

function getAbility(row) {
	var ability = row[1] ? row[1].trim() : '';
	if (calc.ABILITIES[8].indexOf(ability) !== -1) return ability;
}

function statToLegacyStat(stat) {
	switch (stat) {
	case 'hp':
		return "hp";
	case 'atk':
		return "at";
	case 'def':
		return "df";
	case 'spa':
		return "sa";
	case 'spd':
		return "sd";
	case 'spe':
		return "sp";
	}
}

function getStats(currentPoke, rows, offset) {
	currentPoke.nature = "Serious";
	var currentEV;
	var currentIV;
	var currentNature;
	currentPoke.level = 100;
	for (var x = offset; x < offset + 8; x++) {
		var currentRow = rows[x] ? rows[x].split(/[/:]/) : '';
		var evs = {};
		var ivs = {};
		var ev;
		var j;

		switch (currentRow[0]) {
		case 'Level':
			currentPoke.level = parseInt(currentRow[1].trim());
			break;
		case 'EVs':
			for (j = 1; j < currentRow.length; j++) {
				currentEV = currentRow[j].trim().split(" ");
				currentEV[1] = statToLegacyStat(currentEV[1].toLowerCase());
				evs[currentEV[1]] = parseInt(currentEV[0]);
			}
			currentPoke.evs = evs;
			break;
		case 'IVs':
			for (j = 1; j < currentRow.length; j++) {
				currentIV = currentRow[j].trim().split(" ");
				currentIV[1] = statToLegacyStat(currentIV[1].toLowerCase());
				ivs[currentIV[1]] = parseInt(currentIV[0]);
			}
			currentPoke.ivs = ivs;
			break;

		}
		currentNature = rows[x] ? rows[x].trim().split(" ") : '';
		if (currentNature[1] == "Nature") {
			currentPoke.nature = currentNature[0];
		}
	}
	return currentPoke;
}

function getItem(currentRow, j) {
	for (;j < currentRow.length; j++) {
		var item = currentRow[j].trim();
		if (calc.ITEMS[8].indexOf(item) != -1) {
			return item;
		}
	}
}

function getMoves(currentPoke, rows, offset) {
	var movesFound = false;
	var moves = [];
	for (var x = offset; x < offset + 12; x++) {
		if (rows[x]) {
			if (rows[x][0] == "-") {
				movesFound = true;
				var move = rows[x].substr(2, rows[x].length - 2).replace("[", "").replace("]", "").replace("  ", "");
				moves.push(move);
			} else {
				if (movesFound == true) {
					break;
				}
			}
		}
	}
	currentPoke.moves = moves;
	return currentPoke;
}

function addToDex(poke) {
	var dexObject = {};
	if (SETDEX_SS[poke.name] == undefined) SETDEX_SS[poke.name] = {};
	if (SETDEX_SM[poke.name] == undefined) SETDEX_SM[poke.name] = {};
	if (SETDEX_XY[poke.name] == undefined) SETDEX_XY[poke.name] = {};
	if (SETDEX_BW[poke.name] == undefined) SETDEX_BW[poke.name] = {};
	if (SETDEX_DPP[poke.name] == undefined) SETDEX_DPP[poke.name] = {};
	if (SETDEX_ADV[poke.name] == undefined) SETDEX_ADV[poke.name] = {};
	if (SETDEX_GSC[poke.name] == undefined) SETDEX_GSC[poke.name] = {};
	if (SETDEX_RBY[poke.name] == undefined) SETDEX_RBY[poke.name] = {};

	if (poke.ability !== undefined) {
		dexObject.ability = poke.ability;
	}
	dexObject.level = poke.level;
	dexObject.evs = poke.evs;
	dexObject.ivs = poke.ivs;
	dexObject.moves = poke.moves;
	dexObject.nature = poke.nature;
	dexObject.item = poke.item;
	dexObject.isCustomSet = poke.isCustomSet;
	var customsets;
	if (localStorage.customsets) {
		customsets = JSON.parse(localStorage.customsets);
	} else {
		customsets = {};
	}
	if (!customsets[poke.name]) {
		customsets[poke.name] = {};
	}
	customsets[poke.name][poke.nameProp] = dexObject;
	if (poke.name === "Aegislash-Blade") {
		if (!customsets["Aegislash-Shield"]) {
			customsets["Aegislash-Shield"] = {};
		}
		customsets["Aegislash-Shield"][poke.nameProp] = dexObject;
	}
	updateDex(customsets);
}

function updateDex(customsets) {
	for (var pokemon in customsets) {
		for (var moveset in customsets[pokemon]) {
			if (!SETDEX_SS[pokemon]) SETDEX_SS[pokemon] = {};
			SETDEX_SS[pokemon][moveset] = customsets[pokemon][moveset];
			if (!SETDEX_SM[pokemon]) SETDEX_SM[pokemon] = {};
			SETDEX_SM[pokemon][moveset] = customsets[pokemon][moveset];
			if (!SETDEX_XY[pokemon]) SETDEX_XY[pokemon] = {};
			SETDEX_XY[pokemon][moveset] = customsets[pokemon][moveset];
			if (!SETDEX_BW[pokemon]) SETDEX_BW[pokemon] = {};
			SETDEX_BW[pokemon][moveset] = customsets[pokemon][moveset];
			if (!SETDEX_DPP[pokemon]) SETDEX_DPP[pokemon] = {};
			SETDEX_DPP[pokemon][moveset] = customsets[pokemon][moveset];
			if (!SETDEX_ADV[pokemon]) SETDEX_ADV[pokemon] = {};
			SETDEX_ADV[pokemon][moveset] = customsets[pokemon][moveset];
			if (!SETDEX_GSC[pokemon]) SETDEX_GSC[pokemon] = {};
			SETDEX_GSC[pokemon][moveset] = customsets[pokemon][moveset];
			if (!SETDEX_RBY[pokemon]) SETDEX_RBY[pokemon] = {};
			SETDEX_RBY[pokemon][moveset] = customsets[pokemon][moveset];
		}
	}
	localStorage.customsets = JSON.stringify(customsets);
}

function addSets(pokes) {
	var rows = pokes.split("\n");
	var currentRow;
	var currentPoke;
	var addedpokes = 0;
	for (var i = 0; i < rows.length; i++) {
		currentRow = rows[i].split(/[()@]/);
		for (var j = 0; j < currentRow.length; j++) {
			currentRow[j] = checkExeptions(currentRow[j].trim());
			if (calc.SPECIES[8][currentRow[j].trim()] !== undefined) {
				currentPoke = calc.SPECIES[8][currentRow[j].trim()];
				currentPoke.name = currentRow[j].trim();
				currentPoke.item = getItem(currentRow, j + 1);
				if (j === 1 && currentRow[0].trim()) {
					currentPoke.nameProp = currentRow[0].trim();
				} else {
					currentPoke.nameProp = "Custom Set";
				}
				currentPoke.isCustomSet = true;
				currentPoke.ability = getAbility(rows[i + 1].split(":"));
				currentPoke = getStats(currentPoke, rows, i + 1);
				currentPoke = getMoves(currentPoke, rows, i);
				addToDex(currentPoke);
				addedpokes++;
			}
		}
	}
	if (addedpokes > 0) {
		alert("Successfully imported " + addedpokes + " set(s)");
		$(allPokemon("#importedSetsOptions")).css("display", "inline");
	} else {
		alert("No sets imported, please check your syntax and try again");
	}
}

function checkExeptions(poke) {
	switch (poke) {
	case 'Aegislash':
		poke = "Aegislash-Blade";
		break;
	case 'Basculin-Blue-Striped':
		poke = "Basculin";
		break;
	case 'Gastrodon-East':
		poke = "Gastrodon";
		break;
	case 'Keldeo-Resolute':
		poke = "Keldeo";
		break;
	case 'Mimikyu-Busted-Totem':
		poke = "Mimikyu-Totem";
		break;
	case 'Mimikyu-Busted':
		poke = "Mimikyu";
		break;
	case 'Pikachu-Alola':
	case 'Pikachu-Belle':
	case 'Pikachu-Cosplay':
	case 'Pikachu-Hoenn':
	case 'Pikachu-Kalos':
	case 'Pikachu-Libre':
	case 'Pikachu-Original':
	case 'Pikachu-Partner':
	case 'Pikachu-PhD':
	case 'Pikachu-Pop-Star':
	case 'Pikachu-Rock-Star':
	case 'Pikachu-Sinnoh':
	case 'Pikachu-Unova':
		poke = "Pikachu";
		break;
	case 'Vivillon-Fancy':
	case 'Vivillon-Pokeball':
		poke = "Vivillon";
		break;
	case 'Florges-White':
	case 'Florges-Blue':
	case 'Florges-Orange':
	case 'Florges-Yellow':
		poke = "Florges";
		break;
	}
	return poke;

}

$(allPokemon("#clearSets")).click(function () {
	if (confirm("Are you sure you want to delete your custom sets? This action cannot be undone.")) {
		localStorage.removeItem("customsets");
		alert("Custom Sets successfully cleared. Please refresh the page.");
		$(allPokemon("#importedSetsOptions")).hide();
		loadDefaultLists();
	}
});

$(allPokemon("#importedSets")).click(function () {
	var pokeID = $(this).parent().parent().prop("id");
	var showCustomSets = $(this).prop("checked");
	if (showCustomSets) {
		loadCustomList(pokeID);
	} else {
		loadDefaultLists();
	}
});

$(document).ready(function () {
	var customSets;
	placeBsBtn();
	if (localStorage.customsets) {
		customSets = JSON.parse(localStorage.customsets);
		updateDex(customSets);
		$(allPokemon("#importedSetsOptions")).css("display", "inline");
	} else {
		loadDefaultLists();
	}
});
<|endoftext|>